context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml.Linq;
using Castle.MicroKernel.Proxy;
using log4net;
using Rhino.ServiceBus.Internal;
namespace Rhino.ServiceBus.Impl
{
public class DefaultReflection : IReflection
{
private readonly ILog logger = LogManager.GetLogger(typeof (DefaultReflection));
private readonly IDictionary<Type, string> typeToWellKnownTypeName;
private readonly IDictionary<string, Type> wellKnownTypeNameToType;
private readonly MethodInfo internalPreserveStackTraceMethod;
public DefaultReflection()
{
internalPreserveStackTraceMethod = typeof(Exception).GetMethod("InternalPreserveStackTrace",
BindingFlags.Instance | BindingFlags.NonPublic);
wellKnownTypeNameToType = new Dictionary<string, Type>();
typeToWellKnownTypeName = new Dictionary<Type, string>
{
{typeof (string), typeof (string).FullName},
{typeof (int), typeof (int).FullName},
{typeof (byte), typeof (byte).FullName},
{typeof (bool), typeof (bool).FullName},
{typeof (DateTime), typeof (DateTime).FullName},
{typeof (TimeSpan), typeof (TimeSpan).FullName},
{typeof (decimal), typeof (decimal).FullName},
{typeof (float), typeof (float).FullName},
{typeof (double), typeof (double).FullName},
{typeof (char), typeof (char).FullName},
{typeof (Guid), typeof (Guid).FullName},
{typeof (Uri), typeof (Uri).FullName},
{typeof (short), typeof (short).FullName},
{typeof (long), typeof (long).FullName},
{typeof(byte[]), "binary"}
};
foreach (var pair in typeToWellKnownTypeName)
{
wellKnownTypeNameToType.Add(pair.Value, pair.Key);
}
}
#region IReflection Members
public object CreateInstance(Type type, params object[] args)
{
try
{
return Activator.CreateInstance(type, args);
}
catch (Exception e)
{
throw new MissingMethodException("No parameterless constructor defined for this object: " + type, e);
}
}
public Type GetType(string type)
{
Type value;
if (wellKnownTypeNameToType.TryGetValue(type, out value))
return value;
if(type.StartsWith("array_of_"))
{
return GetType(type.Substring("array_of_".Length));
}
return Type.GetType(type);
}
public void InvokeAdd(object instance, object item)
{
try
{
Type type = instance.GetType();
MethodInfo method = type.GetMethod("Add", new[] {item.GetType()});
method.Invoke(instance, new[] {item});
}
catch (TargetInvocationException e)
{
throw InnerExceptionWhilePreservingStackTrace(e);
}
}
public XElement InvokeToElement(object instance, object item, Func<Type, XNamespace> getNamespace)
{
try
{
Type type = instance.GetType();
MethodInfo method = type.GetMethod("ToElement", new[] { item.GetType(), typeof(Func<Type, XNamespace>) });
return (XElement)method.Invoke(instance, new [] { item, getNamespace });
}
catch (TargetInvocationException e)
{
throw InnerExceptionWhilePreservingStackTrace(e);
}
}
public object InvokeFromElement(object instance, XElement value)
{
try
{
Type type = instance.GetType();
MethodInfo method = type.GetMethod("FromElement", new[] { typeof(XElement) });
return method.Invoke(instance, new [] { value });
}
catch (TargetInvocationException e)
{
throw InnerExceptionWhilePreservingStackTrace(e);
}
}
public void Set(object instance, string name, Func<Type, object> generateValue)
{
try
{
Type type = instance.GetType();
PropertyInfo property = type.GetProperty(name);
if (property == null || property.CanWrite == false)
{
logger.DebugFormat("Could not find settable property {0} to set on {1}", name, type);
return;
}
object value = generateValue(property.PropertyType);
property.SetValue(instance, value, null);
}
catch (TargetInvocationException e)
{
throw InnerExceptionWhilePreservingStackTrace(e);
}
}
private Exception InnerExceptionWhilePreservingStackTrace(TargetInvocationException e)
{
internalPreserveStackTraceMethod.Invoke(e.InnerException, new object[0]);
return e.InnerException;
}
public object Get(object instance, string name)
{
try
{
Type type = instance.GetType();
PropertyInfo property = type.GetProperty(name);
if (property == null)
{
logger.InfoFormat("Could not find property {0} to get on {1}", name, type);
return null;
}
return property.GetValue(instance, null);
}
catch (TargetInvocationException e)
{
throw InnerExceptionWhilePreservingStackTrace(e);
}
}
public Type GetGenericTypeOf(Type type, object msg)
{
return GetGenericTypeOf(type, ProxyUtil.GetUnproxiedType(msg));
}
public Type GetGenericTypeOf(Type type, Type paramType)
{
return type.MakeGenericType(paramType);
}
public Type GetGenericTypeOf(Type type, params Type[] paramTypes)
{
return type.MakeGenericType(paramTypes);
}
public ICollection<Type> GetGenericTypesOfWithBaseTypes(Type type, object msg)
{
return GetGenericTypesOfWithBaseTypes(type, ProxyUtil.GetUnproxiedType(msg));
}
public ICollection<Type> GetGenericTypesOfWithBaseTypes(Type type, Type paramType)
{
var constructedTypes = new List<Type>();
//loop through all interfaces of the paramType, constructing a generic type for each.
foreach (var interfaceType in paramType.GetInterfaces())
{
var constructedTypeWithInterfaceArg = GetGenericTypeOf(type, interfaceType);
constructedTypes.Add(constructedTypeWithInterfaceArg);
}
//travel up the chain of base types, constructing a generic type for each.
Type currentParamType = paramType;
while (currentParamType != null)
{
var constructedType = GetGenericTypeOf(type, currentParamType);
constructedTypes.Add(constructedType);
currentParamType = currentParamType.BaseType;
}
return constructedTypes;
}
public void InvokeConsume(object consumer, object msg)
{
try
{
Type type = consumer.GetType();
MethodInfo consume = type.GetMethod("Consume", new[] { msg.GetType() });
consume.Invoke(consumer, new[] { msg });
}
catch (TargetInvocationException e)
{
throw InnerExceptionWhilePreservingStackTrace(e);
}
}
public object InvokeSagaPersisterGet(object persister, Guid correlationId)
{
try
{
Type type = persister.GetType();
MethodInfo method = type.GetMethod("Get");
return method.Invoke(persister, new object[] {correlationId});
}
catch (TargetInvocationException e)
{
throw InnerExceptionWhilePreservingStackTrace(e);
}
}
public void InvokeSagaPersisterSave(object persister, object entity)
{
try
{
Type type = persister.GetType();
MethodInfo method = type.GetMethod("Save");
method.Invoke(persister, new object[] {entity});
}
catch (TargetInvocationException e)
{
throw InnerExceptionWhilePreservingStackTrace(e);
}
}
public void InvokeSagaPersisterComplete(object persister, object entity)
{
try
{
Type type = persister.GetType();
MethodInfo method = type.GetMethod("Complete");
method.Invoke(persister, new object[] {entity});
}
catch (TargetInvocationException e)
{
throw InnerExceptionWhilePreservingStackTrace(e);
}
}
public object InvokeSagaFinderFindBy(object sagaFinder, object msg)
{
try
{
Type type = sagaFinder.GetType();
MethodInfo method = type.GetMethod("FindBy");
return method.Invoke(sagaFinder, new object[] { msg });
}
catch (TargetInvocationException e)
{
throw InnerExceptionWhilePreservingStackTrace(e);
}
}
public string GetNameForXml(Type type)
{
var typeName = type.Name;
typeName = typeName.Replace('[', '_').Replace(']', '_');
var indexOf = typeName.IndexOf('`');
if (indexOf == -1)
return typeName;
typeName = typeName.Substring(0, indexOf) + "_of_";
foreach (var argument in type.GetGenericArguments())
{
typeName += GetNamespaceForXml(argument) + "_";
}
return typeName.Substring(0, typeName.Length - 1);
}
public string GetNamespaceForXml(Type type)
{
string value;
if(typeToWellKnownTypeName.TryGetValue(type, out value))
return value;
if (type.IsArray)
return "array_of_" + GetNamespaceForXml(type.GetElementType());
if (type.Namespace == null && type.Name.StartsWith("<>"))
throw new InvalidOperationException("Anonymous types are not supported");
if (type.Namespace == null) //global types?
{
return type.Name
.ToLowerInvariant();
}
var typeName = type.Namespace.Split('.')
.Last().ToLowerInvariant() + "." + type.Name.ToLowerInvariant();
var indexOf = typeName.IndexOf('`');
if (indexOf == -1)
return typeName;
typeName = typeName.Substring(0, indexOf)+ "_of_";
foreach (var argument in type.GetGenericArguments())
{
typeName += GetNamespaceForXml(argument) + "_";
}
return typeName.Substring(0,typeName.Length-1);
}
public string GetAssemblyQualifiedNameWithoutVersion(Type type)
{
string value;
if (typeToWellKnownTypeName.TryGetValue(type, out value))
return value;
Assembly assembly = type.Assembly;
string fullName = assembly.FullName ?? assembly.GetName().Name;
if (type.IsGenericType)
{
var builder = new StringBuilder();
int startOfGenericName = type.FullName.IndexOf('[');
builder.Append(type.FullName.Substring(0, startOfGenericName))
.Append("[")
.Append(String.Join(",",
type.GetGenericArguments()
.Select(t => "[" + GetAssemblyQualifiedNameWithoutVersion(t) + "]")
.ToArray()))
.Append("], ");
if (assembly.GlobalAssemblyCache)
{
builder.Append(fullName);
}
else
{
builder.Append(fullName.Split(',')[0]);
}
return builder.ToString();
}
if (assembly.GlobalAssemblyCache == false)
{
return type.FullName + ", " + fullName.Split(',')[0];
}
return type.AssemblyQualifiedName;
}
public IEnumerable<string> GetProperties(object value)
{
return value.GetType().GetProperties()
.Select(x => x.Name);
}
public Type[] GetMessagesConsumed(IMessageConsumer consumer)
{
Type consumerType = consumer.GetType();
return GetMessagesConsumed(consumerType, type => false);
}
public Type[] GetMessagesConsumed(Type consumerType, Predicate<Type> filter)
{
var list = new HashSet<Type>();
var toRemove = new HashSet<Type>();
Type[] interfaces = consumerType.GetInterfaces();
foreach (Type type in interfaces)
{
if (type.IsGenericType == false)
continue;
if(type.GetGenericArguments()[0].IsGenericParameter)
continue;
Type definition = type.GetGenericTypeDefinition();
if (filter(definition))
{
toRemove.Add(type.GetGenericArguments()[0]);
continue;
}
if (definition != typeof (ConsumerOf<>))
continue;
list.Add(type.GetGenericArguments()[0]);
}
list.ExceptWith(toRemove);
return list.ToArray();
}
#endregion
}
}
| |
// <copyright company="Simply Code Ltd.">
// Copyright (c) Simply Code Ltd. All rights reserved.
// Licensed under the MIT License.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace PackItUI.Areas.Materials.Models
{
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using PackIt.Helpers.Enums;
using PackIt.Material;
using PackItUI.Helpers;
/// <summary> Material edit view model. </summary>
public class MaterialEditViewModel
{
/// <summary> The data. </summary>
private Material data;
/// <summary>
/// Initialises a new instance of the <see cref="MaterialEditViewModel"/> class.
/// </summary>
public MaterialEditViewModel()
{
this.Data = new();
this.SetSectionTypes();
}
/// <summary> Gets and sets the section types used in select box. </summary>
public IList<ListForFlag<SectionTypes>> SectionTypes { get; private set; }
/// <summary> Gets or sets the material data. </summary>
///
/// <value> The material data. </value>
public Material Data
{
get => this.data;
set
{
this.data = value;
this.SetSectionTypes();
}
}
/// <summary> Sets the section types. </summary>
private void SetSectionTypes()
{
this.SectionTypes = new List<ListForFlag<SectionTypes>>();
foreach (var section in this.Data.Sections)
{
this.SectionTypes.Add(new(section.SectionType));
}
}
/// <summary> Data for material view model. </summary>
public class Material
{
/// <summary>
/// Initialises a new instance of the <see cref="Material" /> class.
/// </summary>
public Material()
{
this.Type = MaterialType.Bottle;
this.Form = FormType.Bottle;
this.Costings = new List<Costing>();
this.Sections = new List<Section>();
}
/// <summary> Gets or sets the Material identifier. </summary>
///
/// <value> The Material identifier. </value>
[Required]
[Display(Name = "ID", Prompt = "Enter Material Id")]
public string MaterialId { get; set; }
/// <summary> Gets or sets the type of the Material. </summary>
///
/// <value> The type of the Material. </value>
[Display(Prompt = "Enter Material Type")]
public MaterialType Type { get; set; }
/// <summary> Gets or sets the name. </summary>
///
/// <value> The name. </value>
[Display(Prompt = "Enter Material Name")]
public string Name { get; set; }
/// <summary> Gets or sets the form. </summary>
///
/// <value> The form. </value>
public FormType Form { get; set; }
/// <summary> Gets or sets the type of the closure. </summary>
///
/// <value> The type of the closure. </value>
public long ClosureType { get; set; }
/// <summary> Gets or sets the closure weight. </summary>
///
/// <value> The closure weight. </value>
[Display(Name = "Closure Weight", Prompt = "Enter Closure Weight")]
public double ClosureWeight { get; set; }
/// <summary> Gets or sets the stack step. </summary>
///
/// <value> The stack step. </value>
[Display(Name = "Stack Step", Prompt = "Enter Stack Step")]
public double StackStep { get; set; }
/// <summary> Gets or sets the flap. </summary>
///
/// <value> The flap. </value>
[Display(Prompt = "Enter Flap Size")]
public double Flap { get; set; }
/// <summary> Gets or sets the length of the internal. </summary>
///
/// <value> The length of the internal. </value>
[Display(Name = "Internal Length", Prompt = "Enter Internal Length")]
public double InternalLength { get; set; }
/// <summary> Gets or sets the internal breadth. </summary>
///
/// <value> The internal breadth. </value>
[Display(Name = "Internal Breadth", Prompt = "Enter Internal Breadth")]
public double InternalBreadth { get; set; }
/// <summary> Gets or sets the height of the internal. </summary>
///
/// <value> The height of the internal. </value>
[Display(Name = "Internal Height", Prompt = "Enter Internal Height")]
public double InternalHeight { get; set; }
/// <summary> Gets or sets the internal volume. </summary>
///
/// <value> The internal volume. </value>
[Display(Name = "Internal Volume", Prompt = "Enter Internal Volume")]
public double InternalVolume { get; set; }
/// <summary> Gets or sets the nett weight. </summary>
///
/// <value> The nett weight. </value>
[Display(Name = "Nett Weight", Prompt = "Enter Nett Weight")]
public double NettWeight { get; set; }
/// <summary> Gets or sets the length of the external. </summary>
///
/// <value> The length of the external. </value>
[Display(Name = "External Length", Prompt = "Enter External Length")]
public double ExternalLength { get; set; }
/// <summary> Gets or sets the external breadth. </summary>
///
/// <value> The external breadth. </value>
[Display(Name = "External Breadth", Prompt = "Enter External Breadth")]
public double ExternalBreadth { get; set; }
/// <summary> Gets or sets the height of the external. </summary>
///
/// <value> The height of the external. </value>
[Display(Name = "External Height", Prompt = "Enter External Height")]
public double ExternalHeight { get; set; }
/// <summary> Gets or sets the external volume. </summary>
///
/// <value> The external volume. </value>
[Display(Name = "External Volume", Prompt = "Enter External Volume")]
public double ExternalVolume { get; set; }
/// <summary> Gets or sets the gross weight. </summary>
///
/// <value> The gross weight. </value>
[Display(Name = "Gross Weight", Prompt = "Enter Gross Weight")]
public double GrossWeight { get; set; }
/// <summary> Gets or sets the load capacity. </summary>
///
/// <value> The load capacity. </value>
[Display(Name = "Load Capacity", Prompt = "Enter Load Capacity")]
public double LoadCapacity { get; set; }
/// <summary> Gets or sets the centre of gravity x coordinate. </summary>
///
/// <value> The centre of gravity x coordinate. </value>
[Display(Name = "Length Center Of Gravity", Prompt = "Enter Center Of Gravity On The Length")]
public double CentreOfGravityX { get; set; }
/// <summary> Gets or sets the centre of gravity y coordinate. </summary>
///
/// <value> The centre of gravity y coordinate. </value>
[Display(Name = "Breadth Center Of Gravity", Prompt = "Enter Center Of Gravity On The Breadth")]
public double CentreOfGravityY { get; set; }
/// <summary> Gets or sets the centre of gravity z coordinate. </summary>
///
/// <value> The centre of gravity z coordinate. </value>
[Display(Name = "Height Center Of Gravity", Prompt = "Enter Center Of Gravity On The Height")]
public double CentreOfGravityZ { get; set; }
/// <summary> Gets or sets the caliper. </summary>
///
/// <value> The caliper. </value>
[Display(Prompt = "Enter Material Caliper")]
public double Caliper { get; set; }
/// <summary> Gets or sets the length of the cell. </summary>
///
/// <value> The length of the cell. </value>
[Display(Name = "Cell Length", Prompt = "Enter Cell Length")]
public double CellLength { get; set; }
/// <summary> Gets or sets the cell breadth. </summary>
///
/// <value> The cell breadth. </value>
[Display(Name = "Cell Breadth", Prompt = "Enter Cell Breadth")]
public double CellBreadth { get; set; }
/// <summary> Gets or sets the height of the cell. </summary>
///
/// <value> The height of the cell. </value>
[Display(Name = "Cell Height", Prompt = "Enter Cell Height")]
public double CellHeight { get; set; }
/// <summary> Gets or sets the blank area. </summary>
///
/// <value> The blank area. </value>
[Display(Name = "Blank Area", Prompt = "Enter Blank Area")]
public double BlankArea { get; set; }
/// <summary> Gets or sets the density. </summary>
///
/// <value> The density. </value>
[Display(Prompt = "Enter Material Density")]
public double Density { get; set; }
/// <summary> Gets or sets the board strength. </summary>
///
/// <value> The board strength. </value>
[Display(Name = "Board Strength", Prompt = "Enter Board Strength")]
public double BoardStrength { get; set; }
/// <summary> Gets or sets target compression. </summary>
///
/// <value> The target compression. </value>
[Display(Name = "Target Compression", Prompt = "Enter Target Compression")]
public double TargetCompression { get; set; }
/// <summary> Gets or sets the collection of costings. </summary>
///
/// <value> Collection of costings. </value>
public IList<Costing> Costings { get; set; }
/// <summary> Gets or sets the collection of sections. </summary>
///
/// <value> Collection of sections. </value>
public IList<Section> Sections { get; set; }
}
}
}
| |
// 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 gcoc = Google.Cloud.OsLogin.Common;
using sys = System;
namespace Google.Cloud.OsLogin.Common
{
/// <summary>Resource name for the <c>PosixAccount</c> resource.</summary>
public sealed partial class PosixAccountName : gax::IResourceName, sys::IEquatable<PosixAccountName>
{
/// <summary>The possible contents of <see cref="PosixAccountName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>users/{user}/projects/{project}</c>.</summary>
UserProject = 1,
}
private static gax::PathTemplate s_userProject = new gax::PathTemplate("users/{user}/projects/{project}");
/// <summary>Creates a <see cref="PosixAccountName"/> 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="PosixAccountName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static PosixAccountName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new PosixAccountName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="PosixAccountName"/> with the pattern <c>users/{user}/projects/{project}</c>.
/// </summary>
/// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="PosixAccountName"/> constructed from the provided ids.</returns>
public static PosixAccountName FromUserProject(string userId, string projectId) =>
new PosixAccountName(ResourceNameType.UserProject, userId: gax::GaxPreconditions.CheckNotNullOrEmpty(userId, nameof(userId)), projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="PosixAccountName"/> with pattern
/// <c>users/{user}/projects/{project}</c>.
/// </summary>
/// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="PosixAccountName"/> with pattern
/// <c>users/{user}/projects/{project}</c>.
/// </returns>
public static string Format(string userId, string projectId) => FormatUserProject(userId, projectId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="PosixAccountName"/> with pattern
/// <c>users/{user}/projects/{project}</c>.
/// </summary>
/// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="PosixAccountName"/> with pattern
/// <c>users/{user}/projects/{project}</c>.
/// </returns>
public static string FormatUserProject(string userId, string projectId) =>
s_userProject.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(userId, nameof(userId)), gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)));
/// <summary>Parses the given resource name string into a new <see cref="PosixAccountName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>users/{user}/projects/{project}</c></description></item></list>
/// </remarks>
/// <param name="posixAccountName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="PosixAccountName"/> if successful.</returns>
public static PosixAccountName Parse(string posixAccountName) => Parse(posixAccountName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="PosixAccountName"/> 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>users/{user}/projects/{project}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="posixAccountName">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="PosixAccountName"/> if successful.</returns>
public static PosixAccountName Parse(string posixAccountName, bool allowUnparsed) =>
TryParse(posixAccountName, allowUnparsed, out PosixAccountName 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="PosixAccountName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>users/{user}/projects/{project}</c></description></item></list>
/// </remarks>
/// <param name="posixAccountName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="PosixAccountName"/>, 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 posixAccountName, out PosixAccountName result) =>
TryParse(posixAccountName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="PosixAccountName"/> 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>users/{user}/projects/{project}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="posixAccountName">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="PosixAccountName"/>, 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 posixAccountName, bool allowUnparsed, out PosixAccountName result)
{
gax::GaxPreconditions.CheckNotNull(posixAccountName, nameof(posixAccountName));
gax::TemplatedResourceName resourceName;
if (s_userProject.TryParseName(posixAccountName, out resourceName))
{
result = FromUserProject(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(posixAccountName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private PosixAccountName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string projectId = null, string userId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
ProjectId = projectId;
UserId = userId;
}
/// <summary>
/// Constructs a new instance of a <see cref="PosixAccountName"/> class from the component parts of pattern
/// <c>users/{user}/projects/{project}</c>
/// </summary>
/// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
public PosixAccountName(string userId, string projectId) : this(ResourceNameType.UserProject, userId: gax::GaxPreconditions.CheckNotNullOrEmpty(userId, nameof(userId)), projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)))
{
}
/// <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>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>User</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string UserId { 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.UserProject: return s_userProject.Expand(UserId, ProjectId);
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 PosixAccountName);
/// <inheritdoc/>
public bool Equals(PosixAccountName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(PosixAccountName a, PosixAccountName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(PosixAccountName a, PosixAccountName b) => !(a == b);
}
/// <summary>Resource name for the <c>SshPublicKey</c> resource.</summary>
public sealed partial class SshPublicKeyName : gax::IResourceName, sys::IEquatable<SshPublicKeyName>
{
/// <summary>The possible contents of <see cref="SshPublicKeyName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>users/{user}/sshPublicKeys/{fingerprint}</c>.</summary>
UserFingerprint = 1,
}
private static gax::PathTemplate s_userFingerprint = new gax::PathTemplate("users/{user}/sshPublicKeys/{fingerprint}");
/// <summary>Creates a <see cref="SshPublicKeyName"/> 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="SshPublicKeyName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static SshPublicKeyName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new SshPublicKeyName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="SshPublicKeyName"/> with the pattern <c>users/{user}/sshPublicKeys/{fingerprint}</c>.
/// </summary>
/// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="fingerprintId">The <c>Fingerprint</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="SshPublicKeyName"/> constructed from the provided ids.</returns>
public static SshPublicKeyName FromUserFingerprint(string userId, string fingerprintId) =>
new SshPublicKeyName(ResourceNameType.UserFingerprint, userId: gax::GaxPreconditions.CheckNotNullOrEmpty(userId, nameof(userId)), fingerprintId: gax::GaxPreconditions.CheckNotNullOrEmpty(fingerprintId, nameof(fingerprintId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SshPublicKeyName"/> with pattern
/// <c>users/{user}/sshPublicKeys/{fingerprint}</c>.
/// </summary>
/// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="fingerprintId">The <c>Fingerprint</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SshPublicKeyName"/> with pattern
/// <c>users/{user}/sshPublicKeys/{fingerprint}</c>.
/// </returns>
public static string Format(string userId, string fingerprintId) => FormatUserFingerprint(userId, fingerprintId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SshPublicKeyName"/> with pattern
/// <c>users/{user}/sshPublicKeys/{fingerprint}</c>.
/// </summary>
/// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="fingerprintId">The <c>Fingerprint</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SshPublicKeyName"/> with pattern
/// <c>users/{user}/sshPublicKeys/{fingerprint}</c>.
/// </returns>
public static string FormatUserFingerprint(string userId, string fingerprintId) =>
s_userFingerprint.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(userId, nameof(userId)), gax::GaxPreconditions.CheckNotNullOrEmpty(fingerprintId, nameof(fingerprintId)));
/// <summary>Parses the given resource name string into a new <see cref="SshPublicKeyName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>users/{user}/sshPublicKeys/{fingerprint}</c></description></item>
/// </list>
/// </remarks>
/// <param name="sshPublicKeyName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="SshPublicKeyName"/> if successful.</returns>
public static SshPublicKeyName Parse(string sshPublicKeyName) => Parse(sshPublicKeyName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="SshPublicKeyName"/> 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>users/{user}/sshPublicKeys/{fingerprint}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="sshPublicKeyName">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="SshPublicKeyName"/> if successful.</returns>
public static SshPublicKeyName Parse(string sshPublicKeyName, bool allowUnparsed) =>
TryParse(sshPublicKeyName, allowUnparsed, out SshPublicKeyName 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="SshPublicKeyName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>users/{user}/sshPublicKeys/{fingerprint}</c></description></item>
/// </list>
/// </remarks>
/// <param name="sshPublicKeyName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="SshPublicKeyName"/>, 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 sshPublicKeyName, out SshPublicKeyName result) =>
TryParse(sshPublicKeyName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="SshPublicKeyName"/> 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>users/{user}/sshPublicKeys/{fingerprint}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="sshPublicKeyName">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="SshPublicKeyName"/>, 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 sshPublicKeyName, bool allowUnparsed, out SshPublicKeyName result)
{
gax::GaxPreconditions.CheckNotNull(sshPublicKeyName, nameof(sshPublicKeyName));
gax::TemplatedResourceName resourceName;
if (s_userFingerprint.TryParseName(sshPublicKeyName, out resourceName))
{
result = FromUserFingerprint(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(sshPublicKeyName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private SshPublicKeyName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string fingerprintId = null, string userId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
FingerprintId = fingerprintId;
UserId = userId;
}
/// <summary>
/// Constructs a new instance of a <see cref="SshPublicKeyName"/> class from the component parts of pattern
/// <c>users/{user}/sshPublicKeys/{fingerprint}</c>
/// </summary>
/// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="fingerprintId">The <c>Fingerprint</c> ID. Must not be <c>null</c> or empty.</param>
public SshPublicKeyName(string userId, string fingerprintId) : this(ResourceNameType.UserFingerprint, userId: gax::GaxPreconditions.CheckNotNullOrEmpty(userId, nameof(userId)), fingerprintId: gax::GaxPreconditions.CheckNotNullOrEmpty(fingerprintId, nameof(fingerprintId)))
{
}
/// <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>Fingerprint</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string FingerprintId { get; }
/// <summary>
/// The <c>User</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string UserId { 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.UserFingerprint: return s_userFingerprint.Expand(UserId, FingerprintId);
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 SshPublicKeyName);
/// <inheritdoc/>
public bool Equals(SshPublicKeyName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(SshPublicKeyName a, SshPublicKeyName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(SshPublicKeyName a, SshPublicKeyName b) => !(a == b);
}
/// <summary>Resource name for the <c>User</c> resource.</summary>
public sealed partial class UserName : gax::IResourceName, sys::IEquatable<UserName>
{
/// <summary>The possible contents of <see cref="UserName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>users/{user}</c>.</summary>
User = 1,
}
private static gax::PathTemplate s_user = new gax::PathTemplate("users/{user}");
/// <summary>Creates a <see cref="UserName"/> 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="UserName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static UserName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new UserName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>Creates a <see cref="UserName"/> with the pattern <c>users/{user}</c>.</summary>
/// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="UserName"/> constructed from the provided ids.</returns>
public static UserName FromUser(string userId) =>
new UserName(ResourceNameType.User, userId: gax::GaxPreconditions.CheckNotNullOrEmpty(userId, nameof(userId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="UserName"/> with pattern <c>users/{user}</c>
/// .
/// </summary>
/// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="UserName"/> with pattern <c>users/{user}</c>.
/// </returns>
public static string Format(string userId) => FormatUser(userId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="UserName"/> with pattern <c>users/{user}</c>
/// .
/// </summary>
/// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="UserName"/> with pattern <c>users/{user}</c>.
/// </returns>
public static string FormatUser(string userId) =>
s_user.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(userId, nameof(userId)));
/// <summary>Parses the given resource name string into a new <see cref="UserName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>users/{user}</c></description></item></list>
/// </remarks>
/// <param name="userName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="UserName"/> if successful.</returns>
public static UserName Parse(string userName) => Parse(userName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="UserName"/> 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>users/{user}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="userName">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="UserName"/> if successful.</returns>
public static UserName Parse(string userName, bool allowUnparsed) =>
TryParse(userName, allowUnparsed, out UserName 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="UserName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>users/{user}</c></description></item></list>
/// </remarks>
/// <param name="userName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="UserName"/>, 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 userName, out UserName result) => TryParse(userName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="UserName"/> 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>users/{user}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="userName">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="UserName"/>, 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 userName, bool allowUnparsed, out UserName result)
{
gax::GaxPreconditions.CheckNotNull(userName, nameof(userName));
gax::TemplatedResourceName resourceName;
if (s_user.TryParseName(userName, out resourceName))
{
result = FromUser(resourceName[0]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(userName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private UserName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string userId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
UserId = userId;
}
/// <summary>
/// Constructs a new instance of a <see cref="UserName"/> class from the component parts of pattern
/// <c>users/{user}</c>
/// </summary>
/// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param>
public UserName(string userId) : this(ResourceNameType.User, userId: gax::GaxPreconditions.CheckNotNullOrEmpty(userId, nameof(userId)))
{
}
/// <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>User</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string UserId { 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.User: return s_user.Expand(UserId);
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 UserName);
/// <inheritdoc/>
public bool Equals(UserName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(UserName a, UserName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(UserName a, UserName b) => !(a == b);
}
public partial class PosixAccount
{
/// <summary>
/// <see cref="gcoc::PosixAccountName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcoc::PosixAccountName PosixAccountName
{
get => string.IsNullOrEmpty(Name) ? null : gcoc::PosixAccountName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class SshPublicKey
{
/// <summary>
/// <see cref="gcoc::SshPublicKeyName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcoc::SshPublicKeyName SshPublicKeyName
{
get => string.IsNullOrEmpty(Name) ? null : gcoc::SshPublicKeyName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Collections;
using System.Text;
using gov.va.medora.utils;
using gov.va.medora.mdo.src.mdo;
using gov.va.medora.mdo.exceptions;
namespace gov.va.medora.mdo.dao.vista
{
/// <summary>
///
/// </summary>
/// <remarks>
/// for more information on underlying calls, see http://www.hardhats.org/fileman/pm/dba_frm.htm
/// </remarks>
public class VistaToolsDao : IToolsDao
{
AbstractConnection cxn = null;
public VistaToolsDao(AbstractConnection cxn)
{
this.cxn = cxn;
}
public string[] ddrLister(
string file,
string iens,
string flds,
string flags,
string maxRex,
string from,
string part,
string xref,
string screen,
string identifier
)
{
DdrLister query = new DdrLister(cxn);
query.File = file;
query.Iens = iens;
query.Fields = flds;
query.Flags = flags;
query.Max = maxRex;
query.From = from;
query.Part = part;
query.Xref = xref;
query.Screen = screen;
query.Id = identifier;
String[] rtn = query.execute();
return rtn;
}
public string getFieldAttribute(string file, string fld, string attribute)
{
string arg = "$P($$GET1^DID(\"" + file + "\",\"" + fld + "\",\"\",\"" + attribute + "\"),U,1)";
string rtn = VistaUtils.getVariableValue(cxn,arg);
return rtn;
}
public string ddiol(string file, string fld, string attribute)
{
string arg = "$P(D EN^DDIOL($$GET1^DID(\"9000010.23\",\".02\",\"\",\"LABEL\")),U,1)";
string rtn = VistaUtils.getVariableValue(cxn,arg);
return rtn;
}
public string[] ddrGetsEntry(
string file,
string iens,
string flds,
string flags)
{
DdrGetsEntry query = new DdrGetsEntry(cxn);
query.File = file;
query.Iens = iens;
query.Fields = flds;
query.Flags = flags;
string[] result = query.execute();
return result;
}
public string getVariableValue(string arg)
{
return VistaUtils.getVariableValue(cxn,arg);
}
public KeyValuePair<string,string>[] getRpcList(string target)
{
MdoQuery request = buildGetRpcListRequest(target);
string response = (string)cxn.query(request);
return toRpcArray(response);
}
internal MdoQuery buildGetRpcListRequest(string target)
{
VistaQuery vq = new VistaQuery("XWB RPC LIST");
vq.addParameter(vq.LITERAL, target);
return vq;
}
internal KeyValuePair<string,string>[] toRpcArray(string response)
{
if (response == "")
{
return null;
}
string[] lines = StringUtils.split(response, StringUtils.CRLF);
lines = StringUtils.trimArray(lines);
KeyValuePair<string, string>[] result = new KeyValuePair<string,string>[lines.Length];
for (int i = 0; i < lines.Length; i++)
{
int p = lines[i].IndexOf(' ');
string IEN = lines[i].Substring(0, p);
string name = getRpcName(IEN);
result[i] = new KeyValuePair<string, string>(IEN, name);
}
return result;
}
public string getRpcName(string rpcIEN)
{
string arg = "$P($G(^XWB(8994," + rpcIEN + ",0)),U,1)";
string response = VistaUtils.getVariableValue(cxn,arg);
return response;
}
public bool isRpcAvailableAtSite(string target, string localRemote, string version)
{
MdoQuery request = buildIsRpcAvailableAtSiteRequest(target, localRemote, version);
string response = (string)cxn.query(request);
return response == "1";
}
internal MdoQuery buildIsRpcAvailableAtSiteRequest(string target, string localRemote, string version)
{
localRemote = localRemote.ToUpper();
if (localRemote != "R" && localRemote != "L" && localRemote != "")
{
throw new Exception("Invalid localRemote param, must be empty, R or L");
}
VistaQuery vq = new VistaQuery("XWB IS RPC AVAILABLE");
vq.addParameter(vq.LITERAL, target);
vq.addParameter(vq.LITERAL, localRemote);
vq.addParameter(vq.LITERAL, (version == "" ? "0" : version));
return vq;
}
public string isRpcAvailable(string target, string context)
{
return isRpcAvailable(target, context, "L", "");
}
public string isRpcAvailable(string target, string context, string localRemote, string version)
{
if (!isRpcAvailableAtSite(target, localRemote, version))
{
return "Not installed at site";
}
KeyValuePair<string,string>[] rpcList = getRpcList(target);
string rpcIEN = rpcList[0].Key;
VistaUserDao userDao = new VistaUserDao(cxn);
string optIEN = userDao.getOptionIen(context);
if (!StringUtils.isNumeric(optIEN))
{
return "Error getting context IEN: " + optIEN;
}
DdrLister query = buildGetOptionRpcsQuery(optIEN);
string[] optRpcs = query.execute();
if (!isRpcIenPresent(optRpcs, rpcIEN))
{
return "RPC not in context";
}
return "YES";
}
internal DdrLister buildGetOptionRpcsQuery(string optIEN)
{
DdrLister query = new DdrLister(cxn);
query.File = "19.05";
query.Iens = "," + optIEN + ",";
query.Fields = ".01";
query.Flags = "IP";
return query;
}
internal bool isRpcIenPresent(string[] optRpcs, string rpcIEN)
{
if (optRpcs == null)
{
return false;
}
for (int i = 0; i < optRpcs.Length; i++)
{
string[] flds = StringUtils.split(optRpcs[i], StringUtils.CARET);
if (flds[1] == rpcIEN)
{
return true;
}
}
return false;
}
public string xusHash(string s)
{
DdrLister query = buildXusHashQuery(s);
string[] response = query.execute();
return StringUtils.piece(response[0],StringUtils.CARET,2);
}
internal DdrLister buildXusHashQuery(string s)
{
DdrLister query = new DdrLister(cxn);
query.File = "200";
query.Flags = "IP";
query.Fields = "";
query.Max = "1";
query.Id = "S X=$$EN^XUSHSH(\"" + s + "\") D EN^DDIOL(X)";
return query;
}
public FileHeader getFileHeader(string globalName)
{
string arg = "$G(" + globalName + "0))";
string response = VistaUtils.getVariableValue(cxn, arg);
return toFileHeader(response);
}
internal FileHeader toFileHeader(string response)
{
if (response == "")
{
return null;
}
FileHeader result = new FileHeader();
string[] flds = StringUtils.split(response, StringUtils.CARET);
result.Name = flds[0];
result.AlternateName = "";
int i = 0;
while (StringUtils.isNumericChar(flds[1][i]))
{
result.AlternateName += flds[1][i];
i++;
}
if (i < flds[1].Length)
{
result.Characteristics = new ArrayList();
do
{
result.Characteristics.Add(flds[1][i]);
i++;
} while (i < flds[1].Length);
}
result.LatestId = flds[2];
result.NumberOfRecords = Convert.ToInt64(flds[3]);
return result;
}
public string getTimestamp()
{
MdoQuery request = buildGetTimestampRequest();
string response = (string)cxn.query(request);
return VistaTimestamp.toUtcString(response);
}
internal MdoQuery buildGetTimestampRequest()
{
VistaQuery vq = new VistaQuery("ORWU DT");
vq.addParameter(vq.LITERAL, "NOW");
return vq;
}
public string runRpc(string rpcName, string[] paramValues, int[] paramTypes, bool[] paramEncrypted)
{
MdoQuery request = buildRpcRequest(rpcName, paramValues, paramTypes, paramEncrypted);
string response = (string)cxn.query(request);
return response;
}
public MdoQuery buildRpcRequest(string rpcName, string[] paramValues, int[] paramTypes, bool[] paramEncrypted)
{
if (String.IsNullOrEmpty(rpcName))
{
throw new MdoException(MdoExceptionCode.ARGUMENT_INVALID, "rpcName must be specified");
}
if (paramValues.Length != paramTypes.Length || paramValues.Length != paramEncrypted.Length)
{
throw new MdoException(MdoExceptionCode.ARGUMENT_INVALID, "paramValues, paramTypes and paramEncrpted must be the same size");
}
VistaQuery vq = new VistaQuery(rpcName);
for (int n = 0; n < paramValues.Length; n++)
{
if (paramEncrypted[n])
{
vq.addEncryptedParameter(paramTypes[n], paramValues[n]);
}
else
{
vq.addParameter(paramTypes[n], paramValues[n]);
}
}
return vq;
}
public byte runQueryThread()
{
// this function serves to do nothing more than serve as a tool to initialize a query thread.
// Afaik, a byte is the smallest object available in the .NET runtime
return new byte();
}
/// <summary>
/// Get a VistA file - details include file name and globoal as well as all VistA fields (each field has detailed info such as name, number, transforms and type).
///
/// This call can be long running depending on the size of the file (the PATIENT file contains over 500 fields which currently means over 500 RPCs
/// will be executed to retrieve all the information - this file can take nearly a minute at an average site)
/// </summary>
/// <param name="fileNumber">The Vista file number (e.g. "2")</param>
/// <returns>VistaFile</returns>
public VistaFile getFile(string vistaNumber)
{
return getFile(vistaNumber, false); // don't get XRefs by default as it can be unintentionally long running
}
/// <summary>
/// Get a VistA file - details include file name and globoal as well as all VistA fields (each field has detailed info such as name, number, transforms and type).
///
/// This call can be long running depending on the size of the file (the PATIENT file contains over 500 fields which currently means over 500 RPCs
/// will be executed to retrieve all the information - this file can take nearly a minute at an average site)
/// </summary>
/// <param name="fileNumber">The Vista file number (e.g. "2")</param>
/// <param name="includeXRefs">If true, fetches cross refs for files</param>
/// <returns>VistaFile</returns>
public VistaFile getFile(string fileNumber, bool includeXRefs)
{
VistaFile result = new VistaFile() { FileNumber = fileNumber };
string fileNameQuery = String.Format("$P($G(^DIC({0},0)),U,1)", fileNumber);
string fileGlobalQuery = String.Format("$G(^DIC({0},0,\"GL\"))", fileNumber);
string combinedQueries = new StringBuilder().Append(fileNameQuery).Append("_\"|^|\"_").Append(fileGlobalQuery).ToString();
string combinedResult = getVariableValue(combinedQueries);
string[] pieces = StringUtils.split(combinedResult, "|^|");
result.FileName = pieces[0];
result.Global = pieces[1];
result.FieldsDict = getFields(result);
if (includeXRefs)
{
Dictionary<string, CrossRef> xrefs = getXRefs(result);
result.XRefs = new List<CrossRef>();
foreach (CrossRef xref in xrefs.Values)
{
result.XRefs.Add(xref);
}
}
return result;
}
public Dictionary<string, VistaField> getFields(VistaFile file)
{
Dictionary<string, VistaField> result = new Dictionary<string, VistaField>();
string currentFieldName = getVariableValue(String.Format("$O(^DD({0},\"B\",\"{1}\"))", file.FileNumber, ""));
while (!String.IsNullOrEmpty(currentFieldName))
{
VistaField currentField = getField(file, currentFieldName, ref currentFieldName); // passed by reference because RPC below fetches next field name for loop
if (!result.ContainsKey(currentField.VistaNumber))
{
result.Add(currentField.VistaNumber, currentField);
}
//currentFieldName = getVariableValue(String.Format("$O(^DD({0},\"B\",\"{1}\"))", file.FileNumber, currentFieldName));
}
return result;
}
internal VistaField getField(VistaFile file, string fieldName, ref string nextField)
{
VistaField result = new VistaField();
result.VistaName = fieldName;
// get next field, get field number and get field props with one combined query delimited with the |^| string
string combinedQuery = String.Format("$O(^DD({0},\"B\",\"{1}\"))_\"|^|\"_$O(^DD({0},\"B\",\"{1}\",0))_\"|^|\"_$G(^DD({0},$O(^DD({0},\"B\",\"{1}\",0)),0))", file.FileNumber, fieldName);
string combinedResults = getVariableValue(combinedQuery);
string[] pieces = StringUtils.split(combinedResults, "|^|");
nextField = pieces[0];
result.VistaNumber = pieces[1];
string fieldProps = pieces[2];
//result.VistaNumber = getVariableValue(String.Format("$O(^DD({0},\"B\",\"{1}\",0))", file.FileNumber, fieldName));
//string fieldProps = getVariableValue(String.Format("$G(^DD({0},{1},0))", file.FileNumber, result.VistaNumber));
string[] propPieces = StringUtils.split(fieldProps, StringUtils.CARET);
if (propPieces.Length < 4)
{
return result;
}
result.Type = propPieces[1];
result.VistaNode = String.Concat("(", propPieces[3], ")");
if (propPieces.Length > 2 && !String.IsNullOrEmpty(propPieces[1]))
{
if (propPieces[1].Contains("P") && !String.IsNullOrEmpty(propPieces[2]))
{
result.IsPointer = true;
string pointedToFileHeader = getVariableValue(String.Format("$G(^{0}0))", propPieces[2])); // need to put carat back in because string split removes it
string[] pointedToFileHeaderPieces = StringUtils.split(pointedToFileHeader, StringUtils.CARET);
result.PointsTo = new VistaFile()
{
Global = "^" + propPieces[2], // need to put carat back in because string split removes it
FileName = pointedToFileHeaderPieces[0],
FileNumber = pointedToFileHeaderPieces[1]
};
}
else if (String.Equals(propPieces[1], "S", StringComparison.CurrentCultureIgnoreCase))
{
if (!String.IsNullOrEmpty(propPieces[2]))
{
result.Externals = new Dictionary<string, string>();
String[] externalsKeysAndVals = propPieces[2].Split(new String[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
foreach (String individual in externalsKeysAndVals)
{
String[] keyAndVal = individual.Split(new String[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
if (!result.Externals.ContainsKey(keyAndVal[0]))
{
result.Externals.Add(keyAndVal[0], keyAndVal[1]);
}
else
{
System.Console.WriteLine("Found dupe: " + keyAndVal[0] + " - " + keyAndVal[1] + " which was a duplicate of: " + keyAndVal[0] + ":" + result.Externals[keyAndVal[0]]);
}
}
}
}
}
if (propPieces.Length == 4) // multiple or WP - Need to do some work figuring out what all these characters mean - here??? -> http://www.hardhats.org/fileman/u2/fa_cond.htm
{
decimal trash = 0;
if (Decimal.TryParse(propPieces[1], out trash))
{
result.IsMultiple = true;
result.Multiple = new VistaFile() { FileNumber = propPieces[1] };
//result.Multiple.FieldsDict = getFields(result.Multiple);
}
else
{
result.IsWordProc = true;
}
}
// re-assemble transform
if (propPieces.Length > 4)
{
StringBuilder sb = new StringBuilder();
for (int i = 4; i < propPieces.Length; i++)
{
sb.Append(propPieces[i]);
sb.Append("^");
}
sb = sb.Remove(sb.Length - 1, 1);
result.Transform = sb.ToString();
}
return result;
}
private VistaField setPropsForCodes(VistaField result, string p)
{
throw new NotImplementedException();
}
public Dictionary<string, CrossRef> getXRefs(VistaFile file)
{
Dictionary<string, CrossRef> result = new Dictionary<string, CrossRef>();
string currentXRefName = getVariableValue(String.Format("$O(^DD({0},0,\"IX\",\"\"))", file.FileNumber));
while (!String.IsNullOrEmpty(currentXRefName))
{
if (!result.ContainsKey(currentXRefName))
{
result.Add(currentXRefName, new CrossRef() { Name = currentXRefName });
}
// cut number of queries by 3 for each pass - 1/4 as many RPC calls to Vista
string combinedQuery = String.Format("$O(^DD({0},0,\"IX\",\"{1}\"))_\"|^|\"_" + // get next xref name
"$O(^DD({0},0,\"IX\",\"{1}\",\"\"))_\"|^|\"_" + // get DD
"$O(^DD({0},0,\"IX\",\"{1}\",$O(^DD({0},0,\"IX\",\"{1}\",\"\")),\"\"))_\"|^|\"_" + // get field number
"$P($G(^DD($O(^DD({0},0,\"IX\",\"{1}\",\"\")),$O(^DD({0},0,\"IX\",\"{1}\",$O(^DD({0},0,\"IX\",\"{1}\",\"\")),\"\")),0)),U,1)", file.FileNumber, currentXRefName); // get fieldName
//string dd = getVariableValue(String.Format("$O(^DD({0},0,\"IX\",\"{1}\",\"\"))", file.FileNumber, currentXRefName));
//string fieldNumber = getVariableValue(String.Format("$O(^DD({0},0,\"IX\",\"{1}\",\"{2}\",\"\"))", file.FileNumber, currentXRefName, dd));
//string fieldName = getVariableValue(String.Format("$P($G(^DD(\"{0}\",\"{1}\",0)),U,1)", dd, fieldNumber));
string combinedResults = getVariableValue(combinedQuery);
string[] pieces = StringUtils.split(combinedResults, "|^|");
string dd = pieces[1];
string fieldNumber = pieces[2];
string fieldName = pieces[3];
result[currentXRefName].FieldNumber = fieldNumber;
result[currentXRefName].FieldName = fieldName;
result[currentXRefName].DD = dd;
currentXRefName = pieces[0];
//currentXRefName = getVariableValue(String.Format("$O(^DD({0},0,\"IX\",\"{1}\"))", file.FileNumber, currentXRefName));
}
return result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading;
using Xunit;
using Xunit.NetCore.Extensions;
namespace System.Diagnostics.Tests
{
public partial class ProcessTests : ProcessTestBase
{
private class FinalizingProcess : Process
{
public static volatile bool WasFinalized;
public static void CreateAndRelease()
{
new FinalizingProcess();
}
protected override void Dispose(bool disposing)
{
if (!disposing)
{
WasFinalized = true;
}
base.Dispose(disposing);
}
}
private void SetAndCheckBasePriority(ProcessPriorityClass exPriorityClass, int priority)
{
_process.PriorityClass = exPriorityClass;
_process.Refresh();
Assert.Equal(priority, _process.BasePriority);
}
private void AssertNonZeroWindowsZeroUnix(long value)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.NotEqual(0, value);
}
else
{
Assert.Equal(0, value);
}
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
[PlatformSpecific(TestPlatforms.Windows)] // Expected behavior varies on Windows and Unix
public void TestBasePriorityOnWindows()
{
ProcessPriorityClass originalPriority = _process.PriorityClass;
Assert.Equal(ProcessPriorityClass.Normal, originalPriority);
try
{
// We are not checking for RealTime case here, as RealTime priority process can
// preempt the threads of all other processes, including operating system processes
// performing important tasks, which may cause the machine to be unresponsive.
//SetAndCheckBasePriority(ProcessPriorityClass.RealTime, 24);
SetAndCheckBasePriority(ProcessPriorityClass.High, 13);
SetAndCheckBasePriority(ProcessPriorityClass.Idle, 4);
SetAndCheckBasePriority(ProcessPriorityClass.Normal, 8);
}
finally
{
_process.PriorityClass = originalPriority;
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior varies on Windows and Unix
[OuterLoop]
[Trait(XunitConstants.Category, XunitConstants.RequiresElevation)]
public void TestBasePriorityOnUnix()
{
ProcessPriorityClass originalPriority = _process.PriorityClass;
Assert.Equal(ProcessPriorityClass.Normal, originalPriority);
try
{
SetAndCheckBasePriority(ProcessPriorityClass.High, -11);
SetAndCheckBasePriority(ProcessPriorityClass.Idle, 19);
SetAndCheckBasePriority(ProcessPriorityClass.Normal, 0);
}
finally
{
_process.PriorityClass = originalPriority;
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
[InlineData(null)]
public void TestEnableRaiseEvents(bool? enable)
{
bool exitedInvoked = false;
Process p = CreateProcessLong();
if (enable.HasValue)
{
p.EnableRaisingEvents = enable.Value;
}
p.Exited += delegate { exitedInvoked = true; };
StartSleepKillWait(p);
if (enable.GetValueOrDefault())
{
// There's no guarantee that the Exited callback will be invoked by
// the time Process.WaitForExit completes, though it's extremely likely.
// There could be a race condition where WaitForExit is returning from
// its wait and sees that the callback is already running asynchronously,
// at which point it returns to the caller even if the callback hasn't
// entirely completed. As such, we spin until the value is set.
Assert.True(SpinWait.SpinUntil(() => exitedInvoked, WaitInMS));
}
else
{
Assert.False(exitedInvoked);
}
}
[Fact]
public void TestExitCode()
{
{
Process p = CreateProcess();
p.Start();
Assert.True(p.WaitForExit(WaitInMS));
Assert.Equal(SuccessExitCode, p.ExitCode);
}
{
Process p = CreateProcessLong();
StartSleepKillWait(p);
Assert.NotEqual(0, p.ExitCode);
}
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests UseShellExecute with ProcessStartInfo
[Fact]
public void TestUseShellExecute_Unix_Succeeds()
{
using (var p = Process.Start(new ProcessStartInfo { UseShellExecute = true, FileName = "exit", Arguments = "42" }))
{
Assert.True(p.WaitForExit(WaitInMS));
Assert.Equal(42, p.ExitCode);
}
}
[Fact]
public void TestExitTime()
{
// ExitTime resolution on some platforms is less accurate than our DateTime.UtcNow resolution, so
// we subtract ms from the begin time to account for it.
DateTime timeBeforeProcessStart = DateTime.UtcNow.AddMilliseconds(-25);
Process p = CreateProcessLong();
p.Start();
Assert.Throws<InvalidOperationException>(() => p.ExitTime);
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
Assert.True(p.ExitTime.ToUniversalTime() >= timeBeforeProcessStart,
$@"TestExitTime is incorrect. " +
$@"TimeBeforeStart {timeBeforeProcessStart} Ticks={timeBeforeProcessStart.Ticks}, " +
$@"ExitTime={p.ExitTime}, Ticks={p.ExitTime.Ticks}, " +
$@"ExitTimeUniversal {p.ExitTime.ToUniversalTime()} Ticks={p.ExitTime.ToUniversalTime().Ticks}, " +
$@"NowUniversal {DateTime.Now.ToUniversalTime()} Ticks={DateTime.Now.Ticks}");
}
[Fact]
public void StartTime_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.StartTime);
}
[Fact]
public void TestId()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.Equal(_process.Id, Interop.GetProcessId(_process.SafeHandle));
}
else
{
IEnumerable<int> testProcessIds = Process.GetProcessesByName(HostRunnerName).Select(p => p.Id);
Assert.Contains(_process.Id, testProcessIds);
}
}
[Fact]
public void TestHasExited()
{
{
Process p = CreateProcess();
p.Start();
Assert.True(p.WaitForExit(WaitInMS));
Assert.True(p.HasExited, "TestHasExited001 failed");
}
{
Process p = CreateProcessLong();
p.Start();
try
{
Assert.False(p.HasExited, "TestHasExited002 failed");
}
finally
{
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
}
Assert.True(p.HasExited, "TestHasExited003 failed");
}
}
[Fact]
public void HasExited_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.HasExited);
}
[Fact]
public void Kill_NotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.Kill());
}
[Fact]
public void TestMachineName()
{
// Checking that the MachineName returns some value.
Assert.NotNull(_process.MachineName);
}
[Fact]
public void MachineName_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.MachineName);
}
[Fact]
public void TestMainModuleOnNonOSX()
{
string fileName = "dotnet";
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
fileName = "dotnet.exe";
Process p = Process.GetCurrentProcess();
Assert.True(p.Modules.Count > 0);
Assert.Equal(fileName, p.MainModule.ModuleName);
Assert.EndsWith(fileName, p.MainModule.FileName);
Assert.Equal(string.Format("System.Diagnostics.ProcessModule ({0})", fileName), p.MainModule.ToString());
}
[Fact]
public void TestMaxWorkingSet()
{
using (Process p = Process.GetCurrentProcess())
{
Assert.True((long)p.MaxWorkingSet > 0);
Assert.True((long)p.MinWorkingSet >= 0);
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
return; // doesn't support getting/setting working set for other processes
long curValue = (long)_process.MaxWorkingSet;
Assert.True(curValue >= 0);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
try
{
_process.MaxWorkingSet = (IntPtr)((int)curValue + 1024);
IntPtr min, max;
uint flags;
Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags);
curValue = (int)max;
_process.Refresh();
Assert.Equal(curValue, (int)_process.MaxWorkingSet);
}
finally
{
_process.MaxWorkingSet = (IntPtr)curValue;
}
}
}
[Fact]
[PlatformSpecific(~TestPlatforms.OSX)] // Getting MaxWorkingSet is not supported on OSX.
public void MaxWorkingSet_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.MaxWorkingSet);
}
[Fact]
[PlatformSpecific(TestPlatforms.OSX)]
public void MaxValueWorkingSet_GetSetMacos_ThrowsPlatformSupportedException()
{
var process = new Process();
Assert.Throws<PlatformNotSupportedException>(() => process.MaxWorkingSet);
Assert.Throws<PlatformNotSupportedException>(() => process.MaxWorkingSet = (IntPtr)1);
}
[Fact]
public void TestMinWorkingSet()
{
using (Process p = Process.GetCurrentProcess())
{
Assert.True((long)p.MaxWorkingSet > 0);
Assert.True((long)p.MinWorkingSet >= 0);
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
return; // doesn't support getting/setting working set for other processes
long curValue = (long)_process.MinWorkingSet;
Assert.True(curValue >= 0);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
try
{
_process.MinWorkingSet = (IntPtr)((int)curValue - 1024);
IntPtr min, max;
uint flags;
Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags);
curValue = (int)min;
_process.Refresh();
Assert.Equal(curValue, (int)_process.MinWorkingSet);
}
finally
{
_process.MinWorkingSet = (IntPtr)curValue;
}
}
}
[Fact]
[PlatformSpecific(~TestPlatforms.OSX)] // Getting MinWorkingSet is not supported on OSX.
public void MinWorkingSet_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.MinWorkingSet);
}
[Fact]
[PlatformSpecific(TestPlatforms.OSX)]
public void MinWorkingSet_GetMacos_ThrowsPlatformSupportedException()
{
var process = new Process();
Assert.Throws<PlatformNotSupportedException>(() => process.MinWorkingSet);
}
[Fact]
public void TestModules()
{
ProcessModuleCollection moduleCollection = Process.GetCurrentProcess().Modules;
foreach (ProcessModule pModule in moduleCollection)
{
// Validated that we can get a value for each of the following.
Assert.NotNull(pModule);
Assert.NotNull(pModule.FileName);
Assert.NotNull(pModule.ModuleName);
// Just make sure these don't throw
IntPtr baseAddr = pModule.BaseAddress;
IntPtr entryAddr = pModule.EntryPointAddress;
int memSize = pModule.ModuleMemorySize;
}
}
[Fact]
public void TestNonpagedSystemMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.NonpagedSystemMemorySize64);
}
[Fact]
public void NonpagedSystemMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.NonpagedSystemMemorySize64);
}
[Fact]
public void TestPagedMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PagedMemorySize64);
}
[Fact]
public void PagedMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PagedMemorySize64);
}
[Fact]
public void TestPagedSystemMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PagedSystemMemorySize64);
}
[Fact]
public void PagedSystemMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PagedSystemMemorySize64);
}
[Fact]
public void TestPeakPagedMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PeakPagedMemorySize64);
}
[Fact]
public void PeakPagedMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PeakPagedMemorySize64);
}
[Fact]
public void TestPeakVirtualMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PeakVirtualMemorySize64);
}
[Fact]
public void PeakVirtualMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PeakVirtualMemorySize64);
}
[Fact]
public void TestPeakWorkingSet64()
{
AssertNonZeroWindowsZeroUnix(_process.PeakWorkingSet64);
}
[Fact]
public void PeakWorkingSet64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PeakWorkingSet64);
}
[Fact]
public void TestPrivateMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PrivateMemorySize64);
}
[Fact]
public void PrivateMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PrivateMemorySize64);
}
[Fact]
public void TestVirtualMemorySize64()
{
Assert.True(_process.VirtualMemorySize64 > 0);
}
[Fact]
public void VirtualMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.VirtualMemorySize64);
}
[Fact]
public void TestWorkingSet64()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
// resident memory can be 0 on OSX.
Assert.True(_process.WorkingSet64 >= 0);
return;
}
Assert.True(_process.WorkingSet64 > 0);
}
[Fact]
public void WorkingSet64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.WorkingSet64);
}
[Fact]
public void TestProcessorTime()
{
Assert.True(_process.UserProcessorTime.TotalSeconds >= 0);
Assert.True(_process.PrivilegedProcessorTime.TotalSeconds >= 0);
double processorTimeBeforeSpin = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds;
double processorTimeAtHalfSpin = 0;
// Perform loop to occupy cpu, takes less than a second.
int i = int.MaxValue / 16;
while (i > 0)
{
i--;
if (i == int.MaxValue / 32)
processorTimeAtHalfSpin = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds;
}
Assert.InRange(processorTimeAtHalfSpin, processorTimeBeforeSpin, Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds);
}
[Fact]
public void UserProcessorTime_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.UserProcessorTime);
}
[Fact]
public void PriviledgedProcessorTime_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PrivilegedProcessorTime);
}
[Fact]
public void TotalProcessorTime_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.TotalProcessorTime);
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/974
public void TestProcessStartTime()
{
TimeSpan allowedWindow = TimeSpan.FromSeconds(3);
DateTime testStartTime = DateTime.UtcNow;
using (var remote = RemoteInvoke(() => { Console.Write(Process.GetCurrentProcess().StartTime.ToUniversalTime()); return SuccessExitCode; },
new RemoteInvokeOptions { StartInfo = new ProcessStartInfo { RedirectStandardOutput = true } }))
{
Assert.Equal(remote.Process.StartTime, remote.Process.StartTime);
DateTime remoteStartTime = DateTime.Parse(remote.Process.StandardOutput.ReadToEnd());
DateTime curTime = DateTime.UtcNow;
Assert.InRange(remoteStartTime, testStartTime - allowedWindow, curTime + allowedWindow);
}
}
[Fact]
public void ExitTime_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.ExitTime);
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/968
[PlatformSpecific(~TestPlatforms.OSX)] // getting/setting affinity not supported on OSX
public void TestProcessorAffinity()
{
IntPtr curProcessorAffinity = _process.ProcessorAffinity;
try
{
_process.ProcessorAffinity = new IntPtr(0x1);
Assert.Equal(new IntPtr(0x1), _process.ProcessorAffinity);
}
finally
{
_process.ProcessorAffinity = curProcessorAffinity;
Assert.Equal(curProcessorAffinity, _process.ProcessorAffinity);
}
}
[Fact]
public void TestPriorityBoostEnabled()
{
bool isPriorityBoostEnabled = _process.PriorityBoostEnabled;
try
{
_process.PriorityBoostEnabled = true;
Assert.True(_process.PriorityBoostEnabled, "TestPriorityBoostEnabled001 failed");
_process.PriorityBoostEnabled = false;
Assert.False(_process.PriorityBoostEnabled, "TestPriorityBoostEnabled002 failed");
}
finally
{
_process.PriorityBoostEnabled = isPriorityBoostEnabled;
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // PriorityBoostEnabled is a no-op on Unix.
public void PriorityBoostEnabled_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PriorityBoostEnabled);
Assert.Throws<InvalidOperationException>(() => process.PriorityBoostEnabled = true);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior varies on Windows and Unix
[OuterLoop]
[Trait(XunitConstants.Category, XunitConstants.RequiresElevation)]
public void TestPriorityClassUnix()
{
ProcessPriorityClass priorityClass = _process.PriorityClass;
try
{
_process.PriorityClass = ProcessPriorityClass.High;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.High);
_process.PriorityClass = ProcessPriorityClass.Normal;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Normal);
}
finally
{
_process.PriorityClass = priorityClass;
}
}
[Fact, PlatformSpecific(TestPlatforms.Windows)] // Expected behavior varies on Windows and Unix
public void TestPriorityClassWindows()
{
ProcessPriorityClass priorityClass = _process.PriorityClass;
try
{
_process.PriorityClass = ProcessPriorityClass.High;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.High);
_process.PriorityClass = ProcessPriorityClass.Normal;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Normal);
}
finally
{
_process.PriorityClass = priorityClass;
}
}
[Fact]
public void TestInvalidPriorityClass()
{
Process p = new Process();
Assert.Throws<ArgumentException>(() => { p.PriorityClass = ProcessPriorityClass.Normal | ProcessPriorityClass.Idle; });
}
[Fact]
public void PriorityClass_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PriorityClass);
}
[Fact]
public void TestProcessName()
{
Assert.Equal(Path.GetFileNameWithoutExtension(_process.ProcessName), Path.GetFileNameWithoutExtension(HostRunner), StringComparer.OrdinalIgnoreCase);
}
[Fact]
public void ProcessName_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.ProcessName);
}
[Fact]
public void TestSafeHandle()
{
Assert.False(_process.SafeHandle.IsInvalid);
}
[Fact]
public void SafeHandle_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.SafeHandle);
}
[Fact]
public void TestSessionId()
{
uint sessionId;
#if TargetsWindows
Interop.ProcessIdToSessionId((uint)_process.Id, out sessionId);
#else
sessionId = (uint)Interop.getsid(_process.Id);
#endif
Assert.Equal(sessionId, (uint)_process.SessionId);
}
[Fact]
public void SessionId_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.SessionId);
}
[Fact]
public void TestGetCurrentProcess()
{
Process current = Process.GetCurrentProcess();
Assert.NotNull(current);
int currentProcessId =
#if TargetsWindows
Interop.GetCurrentProcessId();
#else
Interop.getpid();
#endif
Assert.Equal(currentProcessId, current.Id);
}
[Fact]
public void TestGetProcessById()
{
Process p = Process.GetProcessById(_process.Id);
Assert.Equal(_process.Id, p.Id);
Assert.Equal(_process.ProcessName, p.ProcessName);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Uses P/Invokes to get process Id
public void TestRootGetProcessById()
{
Process p = Process.GetProcessById(1);
Assert.Equal(1, p.Id);
}
[Fact]
public void TestGetProcesses()
{
Process currentProcess = Process.GetCurrentProcess();
// Get all the processes running on the machine, and check if the current process is one of them.
var foundCurrentProcess = (from p in Process.GetProcesses()
where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName))
select p).Any();
Assert.True(foundCurrentProcess, "TestGetProcesses001 failed");
foundCurrentProcess = (from p in Process.GetProcesses(currentProcess.MachineName)
where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName))
select p).Any();
Assert.True(foundCurrentProcess, "TestGetProcesses002 failed");
}
[Fact]
public void GetProcesseses_NullMachineName_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("machineName", () => Process.GetProcesses(null));
}
[Fact]
public void GetProcesses_EmptyMachineName_ThrowsArgumentException()
{
Assert.Throws<ArgumentException>(null, () => Process.GetProcesses(""));
}
[Fact]
public void GetProcessesByName_ProcessName_ReturnsExpected()
{
// Get the current process using its name
Process currentProcess = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName);
Assert.NotEmpty(processes);
Assert.All(processes, process => Assert.Equal(".", process.MachineName));
}
public static IEnumerable<object[]> MachineName_TestData()
{
string currentProcessName = Process.GetCurrentProcess().MachineName;
yield return new object[] { currentProcessName };
yield return new object[] { "." };
yield return new object[] { Dns.GetHostName() };
}
public static IEnumerable<object[]> MachineName_Remote_TestData()
{
yield return new object[] { Guid.NewGuid().ToString("N") };
yield return new object[] { "\\" + Guid.NewGuid().ToString("N") };
}
[Theory]
[MemberData(nameof(MachineName_TestData))]
public void GetProcessesByName_ProcessNameMachineName_ReturnsExpected(string machineName)
{
Process currentProcess = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName, machineName);
Assert.NotEmpty(processes);
Assert.All(processes, process => Assert.Equal(machineName, process.MachineName));
}
[ConditionalTheory(nameof(ProcessPerformanceCounterEnabled))]
[MemberData(nameof(MachineName_Remote_TestData))]
[PlatformSpecific(TestPlatforms.Windows)] // Accessing processes on remote machines is only supported on Windows.
public void GetProcessesByName_RemoteMachineNameWindows_ReturnsExpected(string machineName)
{
GetProcessesByName_ProcessNameMachineName_ReturnsExpected(machineName);
}
[Theory]
[MemberData(nameof(MachineName_Remote_TestData))]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Accessing processes on remote machines is not supported on Unix.
public void GetProcessesByName_RemoteMachineNameUnix_ThrowsPlatformNotSupportedException(string machineName)
{
Process currentProcess = Process.GetCurrentProcess();
Assert.Throws<PlatformNotSupportedException>(() => Process.GetProcessesByName(currentProcess.ProcessName, machineName));
}
[Fact]
public void GetProcessesByName_NoSuchProcess_ReturnsEmpty()
{
string processName = Guid.NewGuid().ToString("N");
Assert.Empty(Process.GetProcessesByName(processName));
}
[Fact]
public void GetProcessesByName_NullMachineName_ThrowsArgumentNullException()
{
Process currentProcess = Process.GetCurrentProcess();
AssertExtensions.Throws<ArgumentNullException>("machineName", () => Process.GetProcessesByName(currentProcess.ProcessName, null));
}
[Fact]
public void GetProcessesByName_EmptyMachineName_ThrowsArgumentException()
{
Process currentProcess = Process.GetCurrentProcess();
Assert.Throws<ArgumentException>(null, () => Process.GetProcessesByName(currentProcess.ProcessName, ""));
}
public static IEnumerable<object[]> GetTestProcess()
{
Process currentProcess = Process.GetCurrentProcess();
yield return new object[] { currentProcess, Process.GetProcessById(currentProcess.Id, "127.0.0.1") };
yield return new object[] { currentProcess, Process.GetProcessesByName(currentProcess.ProcessName, "127.0.0.1").Where(p => p.Id == currentProcess.Id).Single() };
}
private static bool ProcessPerformanceCounterEnabled()
{
try
{
using (Microsoft.Win32.RegistryKey perfKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\PerfProc\Performance"))
{
if (perfKey == null)
return false;
int? value = (int?)perfKey.GetValue("Disable Performance Counters", null);
return !value.HasValue || value.Value == 0;
}
}
catch (Exception)
{
// Ignore exceptions, and just assume the counter is disabled.
return false;
}
}
[PlatformSpecific(TestPlatforms.Windows)] // Behavior differs on Windows and Unix
[ConditionalTheory(nameof(ProcessPerformanceCounterEnabled))]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "https://github.com/dotnet/corefx/issues/18212")]
[MemberData(nameof(GetTestProcess))]
public void TestProcessOnRemoteMachineWindows(Process currentProcess, Process remoteProcess)
{
Assert.Equal(currentProcess.Id, remoteProcess.Id);
Assert.Equal(currentProcess.BasePriority, remoteProcess.BasePriority);
Assert.Equal(currentProcess.EnableRaisingEvents, remoteProcess.EnableRaisingEvents);
Assert.Equal("127.0.0.1", remoteProcess.MachineName);
// This property throws exception only on remote processes.
Assert.Throws<NotSupportedException>(() => remoteProcess.MainModule);
}
[Fact, PlatformSpecific(TestPlatforms.AnyUnix)] // Behavior differs on Windows and Unix
public void TestProcessOnRemoteMachineUnix()
{
Process currentProcess = Process.GetCurrentProcess();
Assert.Throws<PlatformNotSupportedException>(() => Process.GetProcessesByName(currentProcess.ProcessName, "127.0.0.1"));
Assert.Throws<PlatformNotSupportedException>(() => Process.GetProcessById(currentProcess.Id, "127.0.0.1"));
}
[Fact]
public void TestStartInfo()
{
{
Process process = CreateProcessLong();
process.Start();
Assert.Equal(HostRunner, process.StartInfo.FileName);
process.Kill();
Assert.True(process.WaitForExit(WaitInMS));
}
{
Process process = CreateProcessLong();
process.Start();
Assert.Throws<System.InvalidOperationException>(() => (process.StartInfo = new ProcessStartInfo()));
process.Kill();
Assert.True(process.WaitForExit(WaitInMS));
}
{
Process process = new Process();
process.StartInfo = new ProcessStartInfo(TestConsoleApp);
Assert.Equal(TestConsoleApp, process.StartInfo.FileName);
}
{
Process process = new Process();
Assert.Throws<ArgumentNullException>(() => process.StartInfo = null);
}
{
Process process = Process.GetCurrentProcess();
Assert.Throws<System.InvalidOperationException>(() => process.StartInfo);
}
}
[Theory]
[InlineData(@"""abc"" d e", @"abc,d,e")]
[InlineData(@"""abc"" d e", @"abc,d,e")]
[InlineData("\"abc\"\t\td\te", @"abc,d,e")]
[InlineData(@"a\\b d""e f""g h", @"a\\b,de fg,h")]
[InlineData(@"\ \\ \\\", @"\,\\,\\\")]
[InlineData(@"a\\\""b c d", @"a\""b,c,d")]
[InlineData(@"a\\\\""b c"" d e", @"a\\b c,d,e")]
[InlineData(@"a""b c""d e""f g""h i""j k""l", @"ab cd,ef gh,ij kl")]
[InlineData(@"a b c""def", @"a,b,cdef")]
[InlineData(@"""\a\"" \\""\\\ b c", @"\a"" \\\\,b,c")]
public void TestArgumentParsing(string inputArguments, string expectedArgv)
{
using (var handle = RemoteInvokeRaw((Func<string, string, string, int>)ConcatThreeArguments,
inputArguments,
new RemoteInvokeOptions { Start = true, StartInfo = new ProcessStartInfo { RedirectStandardOutput = true } }))
{
Assert.Equal(expectedArgv, handle.Process.StandardOutput.ReadToEnd());
}
}
[Fact]
public void StandardInput_GetNotRedirected_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.StandardInput);
}
private static int ConcatThreeArguments(string one, string two, string three)
{
Console.Write(string.Join(",", one, two, three));
return SuccessExitCode;
}
// [Fact] // uncomment for diagnostic purposes to list processes to console
public void TestDiagnosticsWithConsoleWriteLine()
{
foreach (var p in Process.GetProcesses().OrderBy(p => p.Id))
{
Console.WriteLine("{0} : \"{1}\" (Threads: {2})", p.Id, p.ProcessName, p.Threads.Count);
p.Dispose();
}
}
[Fact]
public void CanBeFinalized()
{
FinalizingProcess.CreateAndRelease();
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.True(FinalizingProcess.WasFinalized);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestStartWithMissingFile(bool fullPath)
{
string path = Guid.NewGuid().ToString("N");
if (fullPath)
{
path = Path.GetFullPath(path);
Assert.True(Path.IsPathRooted(path));
}
else
{
Assert.False(Path.IsPathRooted(path));
}
Assert.False(File.Exists(path));
Win32Exception e = Assert.Throws<Win32Exception>(() => Process.Start(path));
Assert.NotEqual(0, e.NativeErrorCode);
}
[PlatformSpecific(TestPlatforms.Windows)] // Needs permissions on Unix
// NativeErrorCode not 193 on Windows Nano for ERROR_BAD_EXE_FORMAT, issue #10290
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
public void TestStartOnWindowsWithBadFileFormat()
{
string path = GetTestFilePath();
File.Create(path).Dispose();
Win32Exception e = Assert.Throws<Win32Exception>(() => Process.Start(path));
Assert.NotEqual(0, e.NativeErrorCode);
}
[Fact]
public void Start_NullStartInfo_ThrowsArgumentNullExceptionException()
{
AssertExtensions.Throws<ArgumentNullException>("startInfo", () => Process.Start((ProcessStartInfo)null));
}
[Fact]
public void Start_EmptyFileName_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.Start());
}
[Fact]
public void Start_HasStandardOutputEncodingNonRedirected_ThrowsInvalidOperationException()
{
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "FileName",
RedirectStandardOutput = false,
StandardOutputEncoding = Encoding.UTF8
}
};
Assert.Throws<InvalidOperationException>(() => process.Start());
}
[Fact]
public void Start_HasStandardErrorEncodingNonRedirected_ThrowsInvalidOperationException()
{
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "FileName",
RedirectStandardError = false,
StandardErrorEncoding = Encoding.UTF8
}
};
Assert.Throws<InvalidOperationException>(() => process.Start());
}
[Fact]
public void Start_Disposed_ThrowsObjectDisposedException()
{
var process = new Process();
process.StartInfo.FileName = "Nothing";
process.Dispose();
Assert.Throws<ObjectDisposedException>(() => process.Start());
}
[Fact]
[PlatformSpecific(TestPlatforms.Linux | TestPlatforms.Windows)] // Expected process HandleCounts differs on OSX
public void TestHandleCount()
{
using (Process p = Process.GetCurrentProcess())
{
Assert.True(p.HandleCount > 0);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.OSX)] // Expected process HandleCounts differs on OSX
public void TestHandleCount_OSX()
{
using (Process p = Process.GetCurrentProcess())
{
Assert.Equal(0, p.HandleCount);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Linux | TestPlatforms.Windows)] // Expected process HandleCounts differs on OSX
public void HandleCountChanges()
{
RemoteInvoke(() =>
{
Process p = Process.GetCurrentProcess();
int handleCount = p.HandleCount;
using (var fs1 = File.Open(GetTestFilePath(), FileMode.OpenOrCreate))
using (var fs2 = File.Open(GetTestFilePath(), FileMode.OpenOrCreate))
using (var fs3 = File.Open(GetTestFilePath(), FileMode.OpenOrCreate))
{
p.Refresh();
int secondHandleCount = p.HandleCount;
Assert.True(handleCount < secondHandleCount);
handleCount = secondHandleCount;
}
p.Refresh();
int thirdHandleCount = p.HandleCount;
Assert.True(thirdHandleCount < handleCount);
return SuccessExitCode;
}).Dispose();
}
[Fact]
public void HandleCount_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.HandleCount);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // MainWindowHandle is not supported on Unix.
public void MainWindowHandle_NoWindow_ReturnsEmptyHandle()
{
Assert.Equal(IntPtr.Zero, _process.MainWindowHandle);
Assert.Equal(_process.MainWindowHandle, _process.MainWindowHandle);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // MainWindowHandle is not supported on Unix.
public void MainWindowHandle_GetUnix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => _process.MainWindowHandle);
}
[Fact]
public void MainWindowHandle_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.MainWindowHandle);
}
[Fact]
public void MainWindowTitle_NoWindow_ReturnsEmpty()
{
Assert.Empty(_process.MainWindowTitle);
Assert.Same(_process.MainWindowTitle, _process.MainWindowTitle);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // MainWindowTitle is a no-op and always returns string.Empty on Unix.
public void MainWindowTitle_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.MainWindowTitle);
}
[Fact]
public void CloseMainWindow_NoWindow_ReturnsFalse()
{
Assert.False(_process.CloseMainWindow());
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // CloseMainWindow is a no-op and always returns false on Unix.
public void CloseMainWindow_NotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.CloseMainWindow());
}
[PlatformSpecific(TestPlatforms.Windows)] // Needs to get the process Id from OS
[Fact]
public void TestRespondingWindows()
{
using (Process p = Process.GetCurrentProcess())
{
Assert.True(p.Responding);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Responding always returns true on Unix.
public void Responding_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.Responding);
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // Needs to get the process Id from OS
[Fact]
private void TestWindowApisUnix()
{
// This tests the hardcoded implementations of these APIs on Unix.
using (Process p = Process.GetCurrentProcess())
{
Assert.True(p.Responding);
Assert.Equal(string.Empty, p.MainWindowTitle);
Assert.False(p.CloseMainWindow());
Assert.Throws<InvalidOperationException>(()=>p.WaitForInputIdle());
}
}
[Fact]
public void TestNonpagedSystemMemorySize()
{
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.NonpagedSystemMemorySize);
#pragma warning restore 0618
}
[Fact]
public void NonpagedSystemMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.NonpagedSystemMemorySize);
#pragma warning restore 0618
}
[Fact]
public void TestPagedMemorySize()
{
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PagedMemorySize);
#pragma warning restore 0618
}
[Fact]
public void PagedMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PagedMemorySize);
#pragma warning restore 0618
}
[Fact]
public void TestPagedSystemMemorySize()
{
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PagedSystemMemorySize);
#pragma warning restore 0618
}
[Fact]
public void PagedSystemMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PagedSystemMemorySize);
#pragma warning restore 0618
}
[Fact]
public void TestPeakPagedMemorySize()
{
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PeakPagedMemorySize);
#pragma warning restore 0618
}
[Fact]
public void PeakPagedMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PeakPagedMemorySize);
#pragma warning restore 0618
}
[Fact]
public void TestPeakVirtualMemorySize()
{
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PeakVirtualMemorySize);
#pragma warning restore 0618
}
[Fact]
public void PeakVirtualMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PeakVirtualMemorySize);
#pragma warning restore 0618
}
[Fact]
public void TestPeakWorkingSet()
{
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PeakWorkingSet);
#pragma warning restore 0618
}
[Fact]
public void PeakWorkingSet_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PeakWorkingSet);
#pragma warning restore 0618
}
[Fact]
public void TestPrivateMemorySize()
{
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PrivateMemorySize);
#pragma warning restore 0618
}
[Fact]
public void PrivateMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PrivateMemorySize);
#pragma warning restore 0618
}
[Fact]
public void TestVirtualMemorySize()
{
#pragma warning disable 0618
Assert.Equal(unchecked((int)_process.VirtualMemorySize64), _process.VirtualMemorySize);
#pragma warning restore 0618
}
[Fact]
public void VirtualMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.VirtualMemorySize);
#pragma warning restore 0618
}
[Fact]
public void TestWorkingSet()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
// resident memory can be 0 on OSX.
#pragma warning disable 0618
Assert.True(_process.WorkingSet >= 0);
#pragma warning restore 0618
return;
}
#pragma warning disable 0618
Assert.True(_process.WorkingSet > 0);
#pragma warning restore 0618
}
[Fact]
public void WorkingSet_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.WorkingSet);
#pragma warning restore 0618
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix
public void Process_StartInvalidNamesTest()
{
Assert.Throws<InvalidOperationException>(() => Process.Start(null, "userName", new SecureString(), "thisDomain"));
Assert.Throws<InvalidOperationException>(() => Process.Start(string.Empty, "userName", new SecureString(), "thisDomain"));
Assert.Throws<Win32Exception>(() => Process.Start("exe", string.Empty, new SecureString(), "thisDomain"));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix
public void Process_StartWithInvalidUserNamePassword()
{
SecureString password = AsSecureString("Value");
Assert.Throws<Win32Exception>(() => Process.Start(GetCurrentProcessName(), "userName", password, "thisDomain"));
Assert.Throws<Win32Exception>(() => Process.Start(GetCurrentProcessName(), Environment.UserName, password, Environment.UserDomainName));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix
public void Process_StartTest()
{
string currentProcessName = GetCurrentProcessName();
string userName = string.Empty;
string domain = "thisDomain";
SecureString password = AsSecureString("Value");
Process p = Process.Start(currentProcessName, userName, password, domain);
Assert.NotNull(p);
Assert.Equal(currentProcessName, p.StartInfo.FileName);
Assert.Equal(userName, p.StartInfo.UserName);
Assert.Same(password, p.StartInfo.Password);
Assert.Equal(domain, p.StartInfo.Domain);
p.Kill();
password.Dispose();
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix
public void Process_StartWithArgumentsTest()
{
string currentProcessName = GetCurrentProcessName();
string userName = string.Empty;
string domain = Environment.UserDomainName;
string arguments = "-xml testResults.xml";
SecureString password = AsSecureString("Value");
Process p = Process.Start(currentProcessName, arguments, userName, password, domain);
Assert.NotNull(p);
Assert.Equal(currentProcessName, p.StartInfo.FileName);
Assert.Equal(arguments, p.StartInfo.Arguments);
Assert.Equal(userName, p.StartInfo.UserName);
Assert.Same(password, p.StartInfo.Password);
Assert.Equal(domain, p.StartInfo.Domain);
p.Kill();
password.Dispose();
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix
public void Process_StartWithDuplicatePassword()
{
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "exe";
psi.UserName = "dummyUser";
psi.PasswordInClearText = "Value";
psi.Password = AsSecureString("Value");
Process p = new Process();
p.StartInfo = psi;
Assert.Throws<ArgumentException>(() => p.Start());
}
private string GetCurrentProcessName()
{
return $"{Process.GetCurrentProcess().ProcessName}.exe";
}
private SecureString AsSecureString(string str)
{
SecureString secureString = new SecureString();
foreach (var ch in str)
{
secureString.AppendChar(ch);
}
return secureString;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Factotum
{
public partial class MeterModelView : Form
{
// ----------------------------------------------------------------------
// Initialization
// ----------------------------------------------------------------------
// Form constructor
public MeterModelView()
{
InitializeComponent();
// Take care of settings that are not easily managed in the designer.
InitializeControls();
}
// Take care of settings that are not easily managed in the designer.
private void InitializeControls()
{
}
// Set the status filter to show active tools by default
// and update the tool selector combo box
private void MeterModelView_Load(object sender, EventArgs e)
{
// Set the status combo first. The selector DataGridView depends on it.
cboStatusFilter.SelectedIndex = (int)FilterActiveStatus.ShowActive;
// Apply the current filters and set the selector row.
// Passing a null selects the first row if there are any rows.
UpdateSelector(null);
// Now that we have some rows and columns, we can do some customization.
CustomizeGrid();
// Need to do this because the customization clears the row selection.
SelectGridRow(null);
// Wire up the handler for the Entity changed event
EMeterModel.Changed += new EventHandler<EntityChangedEventArgs>(EMeterModel_Changed);
}
private void MeterModelView_FormClosed(object sender, FormClosedEventArgs e)
{
EMeterModel.Changed -= new EventHandler<EntityChangedEventArgs>(EMeterModel_Changed);
}
// ----------------------------------------------------------------------
// Event Handlers
// ----------------------------------------------------------------------
// If any of this type of entity object was saved or deleted, we want to update the selector
// The event args contain the ID of the entity that was added, mofified or deleted.
void EMeterModel_Changed(object sender, EntityChangedEventArgs e)
{
UpdateSelector(e.ID);
}
// Handle the user's decision to edit the current tool
private void EditCurrentSelection()
{
// Make sure there's a row selected
if (dgvMeterModels.SelectedRows.Count != 1) return;
Guid? currentEditItem = (Guid?)(dgvMeterModels.SelectedRows[0].Cells["ID"].Value);
// First check to see if an instance of the form set to the selected ID already exists
if (!Globals.CanActivateForm(this, "MeterModelEdit", currentEditItem))
{
// Open the edit form with the currently selected ID.
MeterModelEdit frm = new MeterModelEdit(currentEditItem);
frm.MdiParent = this.MdiParent;
frm.Show();
}
}
// This handles the datagridview double-click as well as button click
void btnEdit_Click(object sender, System.EventArgs e)
{
EditCurrentSelection();
}
private void dgvMeterModels_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
EditCurrentSelection();
}
// Handle the user's decision to add a new tool
private void btnAdd_Click(object sender, EventArgs e)
{
MeterModelEdit frm = new MeterModelEdit();
frm.MdiParent = this.MdiParent;
frm.Show();
}
// Handle the user's decision to delete the selected tool
private void btnDelete_Click(object sender, EventArgs e)
{
if (dgvMeterModels.SelectedRows.Count != 1)
{
MessageBox.Show("Please select a Calibration Block to delete first.", "Factotum");
return;
}
Guid? currentEditItem = (Guid?)(dgvMeterModels.SelectedRows[0].Cells["ID"].Value);
if (Globals.IsFormOpen(this, "MeterModelEdit", currentEditItem))
{
MessageBox.Show("Can't delete because that item is currently being edited.", "Factotum");
return;
}
EMeterModel MeterModel = new EMeterModel(currentEditItem);
MeterModel.Delete(true);
if (MeterModel.MeterModelErrMsg != null)
{
MessageBox.Show(MeterModel.MeterModelErrMsg, "Factotum");
MeterModel.MeterModelErrMsg = null;
}
}
// The user changed the status filter setting, so update the selector combo.
private void cboStatus_SelectedIndexChanged(object sender, EventArgs e)
{
ApplyFilters();
}
private void btnClose_Click(object sender, EventArgs e)
{
Close();
}
// ----------------------------------------------------------------------
// Private utilities
// ----------------------------------------------------------------------
// Update the tool selector combo box by filling its items based on current data and filters.
// Then set the currently displayed item to that of the supplied ID.
// If the supplied ID isn't on the list because of the current filter state, just show the
// first item if there is one.
private void UpdateSelector(Guid? id)
{
// Save the sort specs if there are any, so we can re-apply them
SortOrder sortOrder = dgvMeterModels.SortOrder;
int sortCol = -1;
if (sortOrder != SortOrder.None)
sortCol = dgvMeterModels.SortedColumn.Index;
// Update the grid view selector
DataView dv = EMeterModel.GetDefaultDataView();
dgvMeterModels.DataSource = dv;
ApplyFilters();
// Re-apply the sort specs
if (sortOrder == SortOrder.Ascending)
dgvMeterModels.Sort(dgvMeterModels.Columns[sortCol], ListSortDirection.Ascending);
else if (sortOrder == SortOrder.Descending)
dgvMeterModels.Sort(dgvMeterModels.Columns[sortCol], ListSortDirection.Descending);
// Select the current row
SelectGridRow(id);
}
private void CustomizeGrid()
{
// Apply a default sort
dgvMeterModels.Sort(dgvMeterModels.Columns["MeterModelName"], ListSortDirection.Ascending);
// Fix up the column headings
dgvMeterModels.Columns["MeterModelName"].HeaderText = "Model Name";
dgvMeterModels.Columns["MeterModelManfName"].HeaderText = "Manufacturer";
dgvMeterModels.Columns["MeterModelIsActive"].HeaderText = "Active";
// Hide some columns
dgvMeterModels.Columns["ID"].Visible = false;
dgvMeterModels.Columns["MeterModelIsActive"].Visible = false;
dgvMeterModels.Columns["MeterModelUsedInOUtage"].Visible = false;
dgvMeterModels.Columns["MeterModelIsLclChg"].Visible = false;
dgvMeterModels.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells);
}
// Apply the current filters to the DataView. The DataGridView will auto-refresh.
private void ApplyFilters()
{
if (dgvMeterModels.DataSource == null) return;
StringBuilder sb = new StringBuilder("MeterModelIsActive = ", 255);
sb.Append(cboStatusFilter.SelectedIndex == (int)FilterActiveStatus.ShowActive ? "'Yes'" : "'No'");
DataView dv = (DataView)dgvMeterModels.DataSource;
dv.RowFilter = sb.ToString();
}
// Select the row with the specified ID if it is currently displayed and scroll to it.
// If the ID is not in the list,
private void SelectGridRow(Guid? id)
{
bool found = false;
int rows = dgvMeterModels.Rows.Count;
if (rows == 0) return;
int r = 0;
DataGridViewCell firstCell = dgvMeterModels.FirstDisplayedCell;
if (id != null)
{
// Find the row with the specified key id and select it.
for (r = 0; r < rows; r++)
{
if ((Guid?)dgvMeterModels.Rows[r].Cells["ID"].Value == id)
{
dgvMeterModels.CurrentCell = dgvMeterModels[firstCell.ColumnIndex, r];
dgvMeterModels.Rows[r].Selected = true;
found = true;
break;
}
}
}
if (found)
{
if (!dgvMeterModels.Rows[r].Displayed)
{
// Scroll to the selected row if the ID was in the list.
dgvMeterModels.FirstDisplayedScrollingRowIndex = r;
}
}
else
{
// Select the first item
dgvMeterModels.CurrentCell = firstCell;
dgvMeterModels.Rows[0].Selected = true;
}
}
}
}
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Frapid.ApplicationState.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Frapid.Account.DataAccess;
using Frapid.Account.Api.Fakes;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Xunit;
namespace Frapid.Account.Api.Tests
{
public class GoogleAccessTokenTests
{
public static GoogleAccessTokenController Fixture()
{
GoogleAccessTokenController controller = new GoogleAccessTokenController(new GoogleAccessTokenRepository(), "", new LoginView());
return controller;
}
[Fact]
[Conditional("Debug")]
public void CountEntityColumns()
{
EntityView entityView = Fixture().GetEntityView();
Assert.Null(entityView.Columns);
}
[Fact]
[Conditional("Debug")]
public void Count()
{
long count = Fixture().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetAll()
{
int count = Fixture().GetAll().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void Export()
{
int count = Fixture().Export().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void Get()
{
Frapid.Account.Entities.GoogleAccessToken googleAccessToken = Fixture().Get(0);
Assert.NotNull(googleAccessToken);
}
[Fact]
[Conditional("Debug")]
public void First()
{
Frapid.Account.Entities.GoogleAccessToken googleAccessToken = Fixture().GetFirst();
Assert.NotNull(googleAccessToken);
}
[Fact]
[Conditional("Debug")]
public void Previous()
{
Frapid.Account.Entities.GoogleAccessToken googleAccessToken = Fixture().GetPrevious(0);
Assert.NotNull(googleAccessToken);
}
[Fact]
[Conditional("Debug")]
public void Next()
{
Frapid.Account.Entities.GoogleAccessToken googleAccessToken = Fixture().GetNext(0);
Assert.NotNull(googleAccessToken);
}
[Fact]
[Conditional("Debug")]
public void Last()
{
Frapid.Account.Entities.GoogleAccessToken googleAccessToken = Fixture().GetLast();
Assert.NotNull(googleAccessToken);
}
[Fact]
[Conditional("Debug")]
public void GetMultiple()
{
IEnumerable<Frapid.Account.Entities.GoogleAccessToken> googleAccessTokens = Fixture().Get(new int[] { });
Assert.NotNull(googleAccessTokens);
}
[Fact]
[Conditional("Debug")]
public void GetPaginatedResult()
{
int count = Fixture().GetPaginatedResult().Count();
Assert.Equal(1, count);
count = Fixture().GetPaginatedResult(1).Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void CountWhere()
{
long count = Fixture().CountWhere(new JArray());
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetWhere()
{
int count = Fixture().GetWhere(1, new JArray()).Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void CountFiltered()
{
long count = Fixture().CountFiltered("");
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetFiltered()
{
int count = Fixture().GetFiltered(1, "").Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetDisplayFields()
{
int count = Fixture().GetDisplayFields().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetCustomFields()
{
int count = Fixture().GetCustomFields().Count();
Assert.Equal(1, count);
count = Fixture().GetCustomFields("").Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void AddOrEdit()
{
try
{
var form = new JArray { null, null };
Fixture().AddOrEdit(form);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void Add()
{
try
{
Fixture().Add(null);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void Edit()
{
try
{
Fixture().Edit(0, null);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void BulkImport()
{
var collection = new JArray { null, null, null, null };
var actual = Fixture().BulkImport(collection);
Assert.NotNull(actual);
}
[Fact]
[Conditional("Debug")]
public void Delete()
{
try
{
Fixture().Delete(0);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.InternalServerError, ex.Response.StatusCode);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace Microsoft.Win32.SafeHandles
{
public sealed partial class SafeProcessHandle : System.Runtime.InteropServices.SafeHandle
{
public SafeProcessHandle(System.IntPtr existingHandle, bool ownsHandle) : base(default(System.IntPtr), default(bool)) { }
protected override bool ReleaseHandle() { return default(bool); }
}
}
namespace System.Diagnostics
{
public partial class DataReceivedEventArgs : System.EventArgs
{
internal DataReceivedEventArgs() { }
public string Data { get { return default(string); } }
}
public delegate void DataReceivedEventHandler(object sender, System.Diagnostics.DataReceivedEventArgs e);
public partial class Process
{
public Process() { }
public int BasePriority { get { return default(int); } }
[System.ComponentModel.DefaultValueAttribute(false)]
public bool EnableRaisingEvents { get { return default(bool); } set { } }
public int ExitCode { get { return default(int); } }
public System.DateTime ExitTime { get { return default(System.DateTime); } }
public bool HasExited { get { return default(bool); } }
public int Id { get { return default(int); } }
public string MachineName { get { return default(string); } }
public System.Diagnostics.ProcessModule MainModule { get { return default(System.Diagnostics.ProcessModule); } }
public System.IntPtr MaxWorkingSet { get { return default(System.IntPtr); } set { } }
public System.IntPtr MinWorkingSet { get { return default(System.IntPtr); } set { } }
public System.Diagnostics.ProcessModuleCollection Modules { get { return default(System.Diagnostics.ProcessModuleCollection); } }
public long NonpagedSystemMemorySize64 { get { return default(long); } }
public long PagedMemorySize64 { get { return default(long); } }
public long PagedSystemMemorySize64 { get { return default(long); } }
public long PeakPagedMemorySize64 { get { return default(long); } }
public long PeakVirtualMemorySize64 { get { return default(long); } }
public long PeakWorkingSet64 { get { return default(long); } }
public bool PriorityBoostEnabled { get { return default(bool); } set { } }
public System.Diagnostics.ProcessPriorityClass PriorityClass { get { return default(System.Diagnostics.ProcessPriorityClass); } set { } }
public long PrivateMemorySize64 { get { return default(long); } }
public System.TimeSpan PrivilegedProcessorTime { get { return default(System.TimeSpan); } }
public string ProcessName { get { return default(string); } }
public System.IntPtr ProcessorAffinity { get { return default(System.IntPtr); } set { } }
public Microsoft.Win32.SafeHandles.SafeProcessHandle SafeHandle { get { return default(Microsoft.Win32.SafeHandles.SafeProcessHandle); } }
public int SessionId { get { return default(int); } }
public System.IO.StreamReader StandardError { get { return default(System.IO.StreamReader); } }
public System.IO.StreamWriter StandardInput { get { return default(System.IO.StreamWriter); } }
public System.IO.StreamReader StandardOutput { get { return default(System.IO.StreamReader); } }
public System.Diagnostics.ProcessStartInfo StartInfo { get { return default(System.Diagnostics.ProcessStartInfo); } set { } }
public System.DateTime StartTime { get { return default(System.DateTime); } }
public System.Diagnostics.ProcessThreadCollection Threads { get { return default(System.Diagnostics.ProcessThreadCollection); } }
public System.TimeSpan TotalProcessorTime { get { return default(System.TimeSpan); } }
public System.TimeSpan UserProcessorTime { get { return default(System.TimeSpan); } }
public long VirtualMemorySize64 { get { return default(long); } }
public long WorkingSet64 { get { return default(long); } }
public event System.Diagnostics.DataReceivedEventHandler ErrorDataReceived { add { } remove { } }
public event System.EventHandler Exited { add { } remove { } }
public event System.Diagnostics.DataReceivedEventHandler OutputDataReceived { add { } remove { } }
public void BeginErrorReadLine() { }
public void BeginOutputReadLine() { }
public void CancelErrorRead() { }
public void CancelOutputRead() { }
public static void EnterDebugMode() { }
public static System.Diagnostics.Process GetCurrentProcess() { return default(System.Diagnostics.Process); }
public static System.Diagnostics.Process GetProcessById(int processId) { return default(System.Diagnostics.Process); }
public static System.Diagnostics.Process GetProcessById(int processId, string machineName) { return default(System.Diagnostics.Process); }
public static System.Diagnostics.Process[] GetProcesses() { return default(System.Diagnostics.Process[]); }
public static System.Diagnostics.Process[] GetProcesses(string machineName) { return default(System.Diagnostics.Process[]); }
public static System.Diagnostics.Process[] GetProcessesByName(string processName) { return default(System.Diagnostics.Process[]); }
public static System.Diagnostics.Process[] GetProcessesByName(string processName, string machineName) { return default(System.Diagnostics.Process[]); }
public void Kill() { }
public static void LeaveDebugMode() { }
protected void OnExited() { }
public void Refresh() { }
public bool Start() { return default(bool); }
public static System.Diagnostics.Process Start(System.Diagnostics.ProcessStartInfo startInfo) { return default(System.Diagnostics.Process); }
public static System.Diagnostics.Process Start(string fileName) { return default(System.Diagnostics.Process); }
public static System.Diagnostics.Process Start(string fileName, string arguments) { return default(System.Diagnostics.Process); }
public void WaitForExit() { }
public bool WaitForExit(int milliseconds) { return default(bool); }
}
public partial class ProcessModule
{
internal ProcessModule() { }
public System.IntPtr BaseAddress { get { return default(System.IntPtr); } }
public System.IntPtr EntryPointAddress { get { return default(System.IntPtr); } }
public string FileName { get { return default(string); } }
public int ModuleMemorySize { get { return default(int); } }
public string ModuleName { get { return default(string); } }
public override string ToString() { return default(string); }
}
public partial class ProcessModuleCollection
{
protected ProcessModuleCollection() { }
public ProcessModuleCollection(System.Diagnostics.ProcessModule[] processModules) { }
public System.Diagnostics.ProcessModule this[int index] { get { return default(System.Diagnostics.ProcessModule); } }
public bool Contains(System.Diagnostics.ProcessModule module) { return default(bool); }
public void CopyTo(System.Diagnostics.ProcessModule[] array, int index) { }
public int IndexOf(System.Diagnostics.ProcessModule module) { return default(int); }
}
public enum ProcessPriorityClass
{
AboveNormal = 32768,
BelowNormal = 16384,
High = 128,
Idle = 64,
Normal = 32,
RealTime = 256,
}
public sealed partial class ProcessStartInfo
{
public ProcessStartInfo() { }
public ProcessStartInfo(string fileName) { }
public ProcessStartInfo(string fileName, string arguments) { }
public string Arguments { get { return default(string); } set { } }
public bool CreateNoWindow { get { return default(bool); } set { } }
[System.ComponentModel.DefaultValueAttribute(null)]
public System.Collections.Generic.IDictionary<string, string> Environment { get { return default(System.Collections.Generic.IDictionary<string, string>); } }
public string FileName { get { return default(string); } set { } }
public bool RedirectStandardError { get { return default(bool); } set { } }
public bool RedirectStandardInput { get { return default(bool); } set { } }
public bool RedirectStandardOutput { get { return default(bool); } set { } }
public System.Text.Encoding StandardErrorEncoding { get { return default(System.Text.Encoding); } set { } }
public System.Text.Encoding StandardOutputEncoding { get { return default(System.Text.Encoding); } set { } }
public bool UseShellExecute { get { return default(bool); } set { } }
public string WorkingDirectory { get { return default(string); } set { } }
}
public partial class ProcessThread
{
internal ProcessThread() { }
public int BasePriority { get { return default(int); } }
public int CurrentPriority { get { return default(int); } }
public int Id { get { return default(int); } }
public int IdealProcessor { set { } }
public bool PriorityBoostEnabled { get { return default(bool); } set { } }
public System.Diagnostics.ThreadPriorityLevel PriorityLevel { get { return default(System.Diagnostics.ThreadPriorityLevel); } set { } }
public System.TimeSpan PrivilegedProcessorTime { get { return default(System.TimeSpan); } }
public System.IntPtr ProcessorAffinity { set { } }
public System.IntPtr StartAddress { get { return default(System.IntPtr); } }
public System.DateTime StartTime { get { return default(System.DateTime); } }
public System.Diagnostics.ThreadState ThreadState { get { return default(System.Diagnostics.ThreadState); } }
public System.TimeSpan TotalProcessorTime { get { return default(System.TimeSpan); } }
public System.TimeSpan UserProcessorTime { get { return default(System.TimeSpan); } }
public System.Diagnostics.ThreadWaitReason WaitReason { get { return default(System.Diagnostics.ThreadWaitReason); } }
public void ResetIdealProcessor() { }
}
public partial class ProcessThreadCollection
{
protected ProcessThreadCollection() { }
public ProcessThreadCollection(System.Diagnostics.ProcessThread[] processThreads) { }
public System.Diagnostics.ProcessThread this[int index] { get { return default(System.Diagnostics.ProcessThread); } }
public int Add(System.Diagnostics.ProcessThread thread) { return default(int); }
public bool Contains(System.Diagnostics.ProcessThread thread) { return default(bool); }
public void CopyTo(System.Diagnostics.ProcessThread[] array, int index) { }
public int IndexOf(System.Diagnostics.ProcessThread thread) { return default(int); }
public void Insert(int index, System.Diagnostics.ProcessThread thread) { }
public void Remove(System.Diagnostics.ProcessThread thread) { }
}
public enum ThreadPriorityLevel
{
AboveNormal = 1,
BelowNormal = -1,
Highest = 2,
Idle = -15,
Lowest = -2,
Normal = 0,
TimeCritical = 15,
}
public enum ThreadState
{
Initialized = 0,
Ready = 1,
Running = 2,
Standby = 3,
Terminated = 4,
Transition = 6,
Unknown = 7,
Wait = 5,
}
public enum ThreadWaitReason
{
EventPairHigh = 7,
EventPairLow = 8,
ExecutionDelay = 4,
Executive = 0,
FreePage = 1,
LpcReceive = 9,
LpcReply = 10,
PageIn = 2,
PageOut = 12,
Suspended = 5,
SystemAllocation = 3,
Unknown = 13,
UserRequest = 6,
VirtualMemory = 11,
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
namespace HttpServer
{
/// <summary>
/// represents a HTTP input item. Each item can have multiple sub items, a sub item
/// is made in a HTML form by using square brackets
/// </summary>
/// <example>
/// // <input type="text" name="user[FirstName]" value="jonas" /> becomes:
/// Console.WriteLine("Value: {0}", form["user"]["FirstName"].Value);
/// </example>
/// <remarks>
/// All names in a form SHOULD be in lowercase.
/// </remarks>
public class HttpInputItem : IHttpInput
{
/// <summary> Representation of a non-initialized <see cref="HttpInputItem"/>.</summary>
public static readonly HttpInputItem Empty = new HttpInputItem(string.Empty, true);
private readonly IDictionary<string, HttpInputItem> _items = new Dictionary<string, HttpInputItem>();
private readonly List<string> _values = new List<string>();
private string _name;
private readonly bool _ignoreChanges;
/// <summary>
/// Initializes an input item setting its name/identifier and value
/// </summary>
/// <param name="name">Parameter name/id</param>
/// <param name="value">Parameter value</param>
public HttpInputItem(string name, string value)
{
Name = name;
Add(value);
}
private HttpInputItem(string name, bool ignore)
{
Name = name;
_ignoreChanges = ignore;
}
/// <summary>Creates a deep copy of the item specified</summary>
/// <param name="item">The item to copy</param>
/// <remarks>The function makes a deep copy of quite a lot which can be slow</remarks>
public HttpInputItem(HttpInputItem item)
{
foreach (KeyValuePair<string, HttpInputItem> pair in item._items)
_items.Add(pair.Key, pair.Value);
foreach (string value in item._values)
_values.Add(value);
_ignoreChanges = item._ignoreChanges;
_name = item.Name;
}
/// <summary>
/// Number of values
/// </summary>
public int Count
{
get { return _values.Count; }
}
/// <summary>
/// Get a sub item
/// </summary>
/// <param name="name">name in lower case.</param>
/// <returns><see cref="HttpInputItem.Empty"/> if no item was found.</returns>
public HttpInputItem this[string name]
{
get {
return _items.ContainsKey(name) ? _items[name] : Empty;
}
}
/// <summary>
/// Name of item (in lower case).
/// </summary>
public string Name
{
get { return _name; }
set { _name = value; }
}
/// <summary>
/// Returns the first value, or null if no value exist.
/// </summary>
public string Value
{
get {
return _values.Count == 0 ? null : _values[0];
}
set
{
if (_values.Count == 0)
_values.Add(value);
else
_values[0] = value;
}
}
/// <summary>
/// Returns the last value, or null if no value exist.
/// </summary>
public string LastValue
{
get
{
return _values.Count == 0 ? null : _values[_values.Count - 1];
}
}
/// <summary>
/// Returns the list with values.
/// </summary>
public IList<string> Values
{
get { return _values.AsReadOnly(); }
}
/// <summary>
/// Add another value to this item
/// </summary>
/// <param name="value">Value to add.</param>
/// <exception cref="InvalidOperationException">Cannot add stuff to <see cref="HttpInput.Empty"/>.</exception>
public void Add(string value)
{
if (value == null)
return;
if (_ignoreChanges)
throw new InvalidOperationException("Cannot add stuff to HttpInput.Empty.");
_values.Add(value);
}
/// <summary>
/// checks if a sub-item exists (and has a value).
/// </summary>
/// <param name="name">name in lower case</param>
/// <returns>true if the sub-item exists and has a value; otherwise false.</returns>
public bool Contains(string name)
{
return _items.ContainsKey(name) && _items[name].Value != null;
}
/// <summary> Returns a formatted representation of the instance with the values of all contained parameters </summary>
public override string ToString()
{
return ToString(string.Empty);
}
/// <summary>
/// Outputs the string in a formatted manner
/// </summary>
/// <param name="prefix">A prefix to append, used internally</param>
/// <param name="asQuerySting">produce a query string</param>
public string ToString(string prefix, bool asQuerySting)
{
string name;
if (string.IsNullOrEmpty(prefix))
name = Name;
else
name = prefix + "[" + Name + "]";
if (asQuerySting)
{
string temp;
if (_values.Count == 0 && _items.Count > 0)
temp = string.Empty;
else
temp = name;
if (_values.Count > 0)
{
temp += '=';
foreach (string value in _values)
temp += value + ',';
temp = temp.Remove(temp.Length - 1, 1);
}
foreach (KeyValuePair<string, HttpInputItem> item in _items)
temp += item.Value.ToString(name, true) + '&';
return _items.Count > 0 ? temp.Substring(0, temp.Length - 1) : temp;
}
else
{
string temp = name;
if (_values.Count > 0)
{
temp += " = ";
foreach (string value in _values)
temp += value + ", ";
temp = temp.Remove(temp.Length - 2, 2);
}
temp += Environment.NewLine;
foreach (KeyValuePair<string, HttpInputItem> item in _items)
temp += item.Value.ToString(name, false);
return temp;
}
}
#region IHttpInput Members
/// <summary>
///
/// </summary>
/// <param name="name">name in lower case</param>
/// <returns></returns>
HttpInputItem IHttpInput.this[string name]
{
get
{
return _items.ContainsKey(name) ? _items[name] : Empty;
}
}
/// <summary>
/// Add a sub item.
/// </summary>
/// <param name="name">Can contain array formatting, the item is then parsed and added in multiple levels</param>
/// <param name="value">Value to add.</param>
/// <exception cref="ArgumentNullException">Argument is null.</exception>
/// <exception cref="InvalidOperationException">Cannot add stuff to <see cref="HttpInput.Empty"/>.</exception>
public void Add(string name, string value)
{
if (name == null && value != null)
throw new ArgumentNullException("name");
if (name == null)
return;
if (_ignoreChanges)
throw new InvalidOperationException("Cannot add stuff to HttpInput.Empty.");
int pos = name.IndexOf('[');
if (pos != -1)
{
string name1 = name.Substring(0, pos);
string name2 = HttpInput.ExtractOne(name);
if (!_items.ContainsKey(name1))
_items.Add(name1, new HttpInputItem(name1, null));
_items[name1].Add(name2, value);
/*
HttpInputItem item = HttpInput.ParseItem(name, value);
// Add the value to an existing sub item
if (_items.ContainsKey(item.Name))
_items[item.Name].Add(item.Value);
else
_items.Add(item.Name, item);
*/
}
else
{
if (_items.ContainsKey(name))
_items[name].Add(value);
else
_items.Add(name, new HttpInputItem(name, value));
}
}
#endregion
///<summary>
///Returns an enumerator that iterates through the collection.
///</summary>
///
///<returns>
///A <see cref="T:System.Collections.Generic.IEnumerator`1"></see> that can be used to iterate through the collection.
///</returns>
///<filterpriority>1</filterpriority>
IEnumerator<HttpInputItem> IEnumerable<HttpInputItem>.GetEnumerator()
{
return _items.Values.GetEnumerator();
}
#region IEnumerable Members
///<summary>
///Returns an enumerator that iterates through a collection.
///</summary>
///
///<returns>
///An <see cref="T:System.Collections.IEnumerator"></see> object that can be used to iterate through the collection.
///</returns>
///<filterpriority>2</filterpriority>
public IEnumerator GetEnumerator()
{
return _items.Values.GetEnumerator();
}
#endregion
/// <summary>
/// Outputs the string in a formatted manner
/// </summary>
/// <param name="prefix">A prefix to append, used internally</param>
/// <returns></returns>
public string ToString(string prefix)
{
return ToString(prefix, false);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Commons.Music.Midi
{
public partial class MidiAccessManager
{
static MidiAccessManager ()
{
Default = Empty = new EmptyMidiAccess ();
new MidiAccessManager ().InitializeDefault ();
}
private MidiAccessManager ()
{
// We need this only for that we want to use partial method!
}
public static IMidiAccess Default { get; private set; }
public static IMidiAccess Empty { get; internal set; }
partial void InitializeDefault ();
}
[Obsolete ("There will be breaking change in this interface in the next API-breaking release. If you want to avoid API breakage, use IMidiAccess2 now. It will become identical to IMidiAccess2 and IMidiAccess2 will remain for a while.")]
public interface IMidiAccess
{
IEnumerable<IMidiPortDetails> Inputs { get; }
IEnumerable<IMidiPortDetails> Outputs { get; }
Task<IMidiInput> OpenInputAsync (string portId);
Task<IMidiOutput> OpenOutputAsync (string portId);
[Obsolete ("This will be removed in the next API-breaking change. It is not functional at this state anyways.")]
event EventHandler<MidiConnectionEventArgs> StateChanged;
}
#region draft API
// In the future we could use default interface members, but we should target earlier frameworks in the meantime.
public interface IMidiAccess2 : IMidiAccess
{
MidiAccessExtensionManager ExtensionManager { get; }
}
public class MidiAccessExtensionManager
{
public virtual bool Supports<T> () where T : class => GetInstance<T> () != default (T);
public virtual T GetInstance<T> () where T : class => null;
}
public class MidiConnectionStateDetectorExtension
{
public event EventHandler<MidiConnectionEventArgs> StateChanged;
}
public abstract class MidiPortCreatorExtension
{
public abstract IMidiOutput CreateVirtualInputSender (PortCreatorContext context);
public abstract IMidiInput CreateVirtualOutputReceiver (PortCreatorContext context);
public delegate void SendDelegate (byte [] buffer, int index, int length, long timestamp);
public class PortCreatorContext
{
public string ApplicationName { get; set; }
public string PortName { get; set; }
public string Manufacturer { get; set; }
public string Version { get; set; }
}
}
public abstract class SimpleVirtualMidiPort : IMidiPort
{
IMidiPortDetails details;
Action on_dispose;
MidiPortConnectionState connection;
protected SimpleVirtualMidiPort (IMidiPortDetails details, Action onDispose)
{
this.details = details;
on_dispose = onDispose;
connection = MidiPortConnectionState.Open;
}
public IMidiPortDetails Details => details;
public MidiPortConnectionState Connection => connection;
public Task CloseAsync ()
{
return Task.Run (() => {
if (on_dispose != null)
on_dispose ();
connection = MidiPortConnectionState.Closed;
});
}
public void Dispose ()
{
CloseAsync ().Wait ();
}
}
public class SimpleVirtualMidiInput : SimpleVirtualMidiPort, IMidiInput
{
public SimpleVirtualMidiInput (IMidiPortDetails details, Action onDispose)
: base (details, onDispose)
{
}
public event EventHandler<MidiReceivedEventArgs> MessageReceived;
}
public class SimpleVirtualMidiOutput : SimpleVirtualMidiPort, IMidiOutput
{
public SimpleVirtualMidiOutput (IMidiPortDetails details, Action onDispose)
: base (details, onDispose)
{
}
public MidiPortCreatorExtension.SendDelegate OnSend { get; set; }
public void Send (byte [] mevent, int offset, int length, long timestamp)
{
if (OnSend != null)
OnSend (mevent, offset, length, timestamp);
}
}
#endregion
public class MidiConnectionEventArgs : EventArgs
{
public IMidiPortDetails Port { get; private set; }
}
public interface IMidiPortDetails
{
string Id { get; }
string Manufacturer { get; }
string Name { get; }
string Version { get; }
}
public enum MidiPortConnectionState
{
Open,
Closed,
Pending
}
public interface IMidiPort
{
IMidiPortDetails Details { get; }
MidiPortConnectionState Connection { get; }
Task CloseAsync ();
}
public interface IMidiInput : IMidiPort, IDisposable
{
event EventHandler<MidiReceivedEventArgs> MessageReceived;
}
public interface IMidiOutput : IMidiPort, IDisposable
{
void Send (byte [] mevent, int offset, int length, long timestamp);
}
public class MidiReceivedEventArgs : EventArgs
{
public long Timestamp { get; set; }
public byte [] Data { get; set; }
public int Start { get; set; }
public int Length { get; set; }
}
class EmptyMidiAccess : IMidiAccess
{
public IEnumerable<IMidiPortDetails> Inputs
{
get { yield return EmptyMidiInput.Instance.Details; }
}
public IEnumerable<IMidiPortDetails> Outputs
{
get { yield return EmptyMidiOutput.Instance.Details; }
}
public Task<IMidiInput> OpenInputAsync (string portId)
{
if (portId != EmptyMidiInput.Instance.Details.Id)
throw new ArgumentException (string.Format ("Port ID {0} does not exist.", portId));
return Task.FromResult<IMidiInput> (EmptyMidiInput.Instance);
}
public Task<IMidiOutput> OpenOutputAsync (string portId)
{
if (portId != EmptyMidiOutput.Instance.Details.Id)
throw new ArgumentException (string.Format ("Port ID {0} does not exist.", portId));
return Task.FromResult<IMidiOutput> (EmptyMidiOutput.Instance);
}
#pragma warning disable 0067
// it will never be fired.
public event EventHandler<MidiConnectionEventArgs> StateChanged;
#pragma warning restore 0067
}
abstract class EmptyMidiPort : IMidiPort
{
Task completed_task = Task.FromResult (false);
public IMidiPortDetails Details
{
get { return CreateDetails (); }
}
internal abstract IMidiPortDetails CreateDetails ();
public MidiPortConnectionState Connection { get; private set; }
public Task CloseAsync ()
{
// do nothing.
return completed_task;
}
public void Dispose ()
{
}
}
class EmptyMidiPortDetails : IMidiPortDetails
{
public EmptyMidiPortDetails (string id, string name)
{
Id = id;
Manufacturer = "dummy project";
Name = name;
Version = "0.0";
}
public string Id { get; set; }
public string Manufacturer { get; set; }
public string Name { get; set; }
public string Version { get; set; }
}
class EmptyMidiInput : EmptyMidiPort, IMidiInput
{
static EmptyMidiInput ()
{
Instance = new EmptyMidiInput ();
}
public static EmptyMidiInput Instance { get; private set; }
#pragma warning disable 0067
// will never be fired.
public event EventHandler<MidiReceivedEventArgs> MessageReceived;
#pragma warning restore 0067
internal override IMidiPortDetails CreateDetails ()
{
return new EmptyMidiPortDetails ("dummy_in", "Dummy MIDI Input");
}
}
class EmptyMidiOutput : EmptyMidiPort, IMidiOutput
{
Task completed_task = Task.FromResult (false);
static EmptyMidiOutput ()
{
Instance = new EmptyMidiOutput ();
}
public static EmptyMidiOutput Instance { get; private set; }
public void Send (byte [] mevent, int offset, int length, long timestamp)
{
// do nothing.
}
internal override IMidiPortDetails CreateDetails ()
{
return new EmptyMidiPortDetails ("dummy_out", "Dummy MIDI Output");
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
using NPOI.HSSF.UserModel;
using System.Collections.Generic;
using System;
using NPOI.Util;
using NPOI.SS.UserModel;
using System.Text;
using System.IO;
namespace TestCases.SS.Util
{
/**
* Creates a spreadsheet that demonstrates Excel's rendering of various IEEE double values.
*
* @author Josh Micich
*/
public class NumberRenderingSpreadsheetGenerator
{
private class SheetWriter
{
private ISheet _sheet;
private int _rowIndex;
private List<long> _ReplacementNaNs;
public SheetWriter(HSSFWorkbook wb)
{
ISheet sheet = wb.CreateSheet("Sheet1");
WriteHeaderRow(wb, sheet);
_sheet = sheet;
_rowIndex = 1;
_ReplacementNaNs = new List<long>();
}
public void AddTestRow(long rawBits, String expectedExcelRendering)
{
WriteDataRow(_sheet, _rowIndex++, rawBits, expectedExcelRendering);
if (Double.IsNaN(BitConverter.Int64BitsToDouble(rawBits)))
{
_ReplacementNaNs.Add(rawBits);
}
}
public long[] GetReplacementNaNs()
{
int nRepls = _ReplacementNaNs.Count;
long[] result = new long[nRepls];
for (int i = 0; i < nRepls; i++)
{
result[i] = _ReplacementNaNs[i];
}
return result;
}
}
/** 0x7ff8000000000000 encoded in little endian order */
private static byte[] JAVA_NAN_BYTES = HexRead.ReadFromString("00 00 00 00 00 00 F8 7F");
private static void WriteHeaderCell(IRow row, int i, String text, ICellStyle style)
{
ICell cell = row.CreateCell(i);
cell.SetCellValue(new HSSFRichTextString(text));
cell.CellStyle = (style);
}
static void WriteHeaderRow(IWorkbook wb, ISheet sheet)
{
sheet.SetColumnWidth(0, 3000);
sheet.SetColumnWidth(1, 6000);
sheet.SetColumnWidth(2, 6000);
sheet.SetColumnWidth(3, 6000);
sheet.SetColumnWidth(4, 6000);
sheet.SetColumnWidth(5, 1600);
sheet.SetColumnWidth(6, 20000);
IRow row = sheet.CreateRow(0);
ICellStyle style = wb.CreateCellStyle();
IFont font = wb.CreateFont();
WriteHeaderCell(row, 0, "Value", style);
font.Boldweight = (short)FontBoldWeight.Bold;
style.SetFont(font);
WriteHeaderCell(row, 1, "Raw Long Bits", style);
WriteHeaderCell(row, 2, "JDK Double Rendering", style);
WriteHeaderCell(row, 3, "Actual Rendering", style);
WriteHeaderCell(row, 4, "Expected Rendering", style);
WriteHeaderCell(row, 5, "Match", style);
WriteHeaderCell(row, 6, "Java Metadata", style);
}
static void WriteDataRow(ISheet sheet, int rowIx, long rawLongBits, String expectedExcelRendering)
{
double d = BitConverter.Int64BitsToDouble(rawLongBits);
IRow row = sheet.CreateRow(rowIx);
int rowNum = rowIx + 1;
String cel0ref = "A" + rowNum;
String rawBitsText = FormatLongAsHex(rawLongBits);
String jmExpr = "'ec(" + rawBitsText + ", ''\" & C" + rowNum + " & \"'', ''\" & D" + rowNum + " & \"''),'";
// The 'Match' column will contain 'OK' if the metadata (from NumberToTextConversionExamples)
// matches Excel's rendering.
String matchExpr = "if(D" + rowNum + "=E" + rowNum + ", \"OK\", \"ERROR\")";
row.CreateCell(0).SetCellValue(d);
row.CreateCell(1).SetCellValue(new HSSFRichTextString(rawBitsText));
row.CreateCell(2).SetCellValue(new HSSFRichTextString(d.ToString()));
row.CreateCell(3).CellFormula = ("\"\" & " + cel0ref);
row.CreateCell(4).SetCellValue(new HSSFRichTextString(expectedExcelRendering));
row.CreateCell(5).CellFormula = (matchExpr);
row.CreateCell(6).CellFormula = (jmExpr.Replace("'", "\""));
//if (false)
//{
// // for observing arithmetic near numeric range boundaries
// row.CreateCell(7).CellFormula=(cel0ref + " * 1.0001");
// row.CreateCell(8).CellFormula=(cel0ref + " / 1.0001");
//}
}
private static String FormatLongAsHex(long l)
{
StringBuilder sb = new StringBuilder(20);
sb.Append(HexDump.LongToHex(l)).Append('L');
return sb.ToString();
}
//public static void Main(String[] args)
//{
// WriteJavaDoc();
// HSSFWorkbook wb = new HSSFWorkbook();
// SheetWriter sw = new SheetWriter(wb);
// NumberToTextConversionExamples.ExampleConversion[] exampleValues = NumberToTextConversionExamples.GetExampleConversions();
// for (int i = 0; i < exampleValues.Length; i++)
// {
// TestCases.SS.Util.NumberToTextConversionExamples.ExampleConversion example = exampleValues[i];
// sw.AddTestRow(example.RawDoubleBits, example.ExcelRendering);
// }
// MemoryStream baos = new MemoryStream();
// wb.Write(baos);
// byte[] fileContent = baos.ToArray();
// ReplaceNaNs(fileContent, sw.GetReplacementNaNs());
// FileInfo outputFile = new FileInfo("ExcelNumberRendering.xls");
// FileStream os = File.OpenWrite(outputFile.FullName);
// os.Write(fileContent, 0, fileContent.Length);
// os.Close();
// Console.WriteLine("Finished writing '" + outputFile.FullName + "'");
//}
public static void WriteJavaDoc()
{
NumberToTextConversionExamples.ExampleConversion[] exampleConversions = NumberToTextConversionExamples.GetExampleConversions();
for (int i = 0; i < exampleConversions.Length; i++)
{
NumberToTextConversionExamples.ExampleConversion ec = exampleConversions[i];
String line = " * <tr><td>"
+ FormatLongAsHex(ec.RawDoubleBits)
+ "</td><td>" + ec.DoubleValue.ToString()
+ "</td><td>" + ec.ExcelRendering + "</td></tr>";
Console.WriteLine(line);
}
}
private static void ReplaceNaNs(byte[] fileContent, long[] ReplacementNaNs)
{
int countFound = 0;
for (int i = 0; i < fileContent.Length; i++)
{
if (IsNaNBytes(fileContent, i))
{
WriteLong(fileContent, i, ReplacementNaNs[countFound]);
countFound++;
}
}
if (countFound < ReplacementNaNs.Length)
{
throw new Exception("wrong repl count");
}
}
private static void WriteLong(byte[] bb, int i, long val)
{
String oldVal = InterpretLong(bb, i);
bb[i + 7] = (byte)(val >> 56);
bb[i + 6] = (byte)(val >> 48);
bb[i + 5] = (byte)(val >> 40);
bb[i + 4] = (byte)(val >> 32);
bb[i + 3] = (byte)(val >> 24);
bb[i + 2] = (byte)(val >> 16);
bb[i + 1] = (byte)(val >> 8);
bb[i + 0] = (byte)(val >> 0);
//if (false)
//{
// String newVal = interpretLong(bb, i);
// Console.WriteLine("Changed offset " + i + " from " + oldVal + " to " + newVal);
//}
}
private static String InterpretLong(byte[] fileContent, int offset)
{
Stream is1 = new MemoryStream(fileContent, offset, 8);
long l;
l = LittleEndian.ReadLong(is1);
return "0x" + StringUtil.ToHexString(l).ToUpper();
}
private static bool IsNaNBytes(byte[] fileContent, int offset)
{
if (offset + JAVA_NAN_BYTES.Length > fileContent.Length)
{
return false;
}
// excel NaN bits: 0xFFFF0420003C0000L
// java NaN bits :0x7ff8000000000000L
return AreArraySectionsEqual(fileContent, offset, JAVA_NAN_BYTES);
}
private static bool AreArraySectionsEqual(byte[] bb, int off, byte[] section)
{
for (int i = section.Length - 1; i >= 0; i--)
{
if (bb[off + i] != section[i])
{
return false;
}
}
return true;
}
}
}
| |
using Bridge.Html5;
using System;
namespace Bridge.Bootstrap3
{
/// <summary>
/// Tooltip/popover delay
/// </summary>
[Ignore]
[ObjectLiteral]
public class PopupDelay
{
/// <summary>
/// A delay for hiding of a tooltip/popover
/// </summary>
public virtual int Hide
{
get;
set;
}
/// <summary>
/// A delay for showing of a tooltip/popover
/// </summary>
public virtual int Show
{
get;
set;
}
}
/// <summary>
/// Tooltip/popover placement
/// </summary>
[Ignore]
[Enum(Emit.StringNameLowerCase)]
[Name("String")]
public enum PopupPlacement
{
Auto,
AutoBottom,
AutoLeft,
AutoRight,
AutoTop,
Bottom,
Left,
Right,
Top
}
/// <summary>
/// Tooltip/popover trigger
/// </summary>
[Ignore]
[Enum(Emit.StringNameLowerCase)]
[Name("String")]
public enum PopupTrigger
{
[Name("click focus hover manual")]
All,
Click,
[Name("click focus")]
ClickFocus,
[Name("click focus manual")]
ClickFocusManual,
[Name("click focus hover")]
ClickFocusHover,
[Name("click hover")]
ClickHover,
[Name("click hover manual")]
ClickHoverManual,
Focus,
[Name("focus hover")]
FocusHover,
[Name("focus manual")]
FocusManual,
Hover,
[Name("hover manual")]
HoverManual,
Manual
}
/// <summary>
/// Tooltip/popover viewport
/// </summary>
[Ignore]
[ObjectLiteral]
public class PopupViewport
{
/// <summary>
/// Selector
/// </summary>
public virtual string Selector
{
get;
set;
}
/// <summary>
/// Padding
/// </summary>
public virtual int Padding
{
get;
set;
}
}
/// <summary>
/// A base class for a tooltip and a popover options
/// </summary>
[Ignore]
[ObjectLiteral]
public class PopupOptions
{
/// <summary>
/// Apply a CSS fade transition to the tooltip/popover.
/// Defaults to true.
/// </summary>
public virtual bool Animation
{
get;
set;
}
/// <summary>
/// Appends the tooltip/popover to a specific element.
/// Example: container: 'body'. This option is particularly useful in that it allows you to position the tooltip/popover in the flow of the document near the triggering element - which will prevent the tooltip/popover from floating away from the triggering element during a window resize.
/// Defaults to false.
/// </summary>
public virtual string Container
{
get;
set;
}
/// <summary>
/// Delay showing and hiding the tooltip/popover (ms) - does not apply to manual trigger type.
/// If a number is supplied, delay is applied to both hide/show
/// Object structure is: delay: { show: 500, hide: 100 }
/// Defaults to 0.
/// </summary>
public virtual Any<int, PopupDelay> Delay
{
get;
set;
}
/// <summary>
/// Insert HTML into the tooltip/popover. If false, jQuery's text method will be used to insert content into the DOM. Use text if you're worried about XSS attacks.
/// Defaults to false.
/// </summary>
public virtual bool Html
{
get;
set;
}
/// <summary>
/// How to position the tooltip/popover - top | bottom | left | right | auto.
/// When "auto" is specified, it will dynamically reorient the tooltip/popover. For example, if placement is "auto left", the tooltip/popover will display to the left when possible, otherwise it will display right.
/// You can define a function which returns a placement string. The two arguments are passed to a function - a tooltip/popover and a target DOM elements.
/// Defaults to 'top'.
/// </summary>
public virtual Any<string, PopupPlacement, Delegate, Func<Element, Element, string>> Placement
{
get;
set;
}
/// <summary>
/// If a selector is provided, tooltip/popover objects will be delegated to the specified targets. In practice, this is used to enable dynamic HTML content to have tooltips/popovers added.
/// See this Issue: https://github.com/twbs/bootstrap/issues/4215
/// and an informative example: http://jsfiddle.net/fScua/
/// Defaults to no selector.
/// </summary>
public virtual string Selector
{
get;
set;
}
/// <summary>
/// Default title value if title attribute isn't present.
/// If a function is given, you can access the element that the popover is attached to via the "this" reference (Script.This<Element>()).
/// Defaults to "".
/// </summary>
public virtual Any<string, Delegate, Func<string>> Title
{
get;
set;
}
/// <summary>
/// How tooltip/popover is triggered - click | hover | focus | manual. You may pass multiple triggers; separate them with a space.
/// Defaults to "hover focus" for a tooltip and "click" for a popover.
/// </summary>
public virtual Any<string, PopupTrigger> Trigger
{
get;
set;
}
/// <summary>
/// Keeps the tooltip within the bounds of this element. Example: viewport: '#viewport' or { selector: '#viewport', padding: 0 }
/// Defaults to { selector: 'body', padding: 0 }.
/// </summary>
public virtual Any<string, PopupViewport> Viewport
{
get;
set;
}
}
[Ignore]
[ObjectLiteral]
public class TooltipOptions : PopupOptions
{
/// <summary>
/// Base HTML to use when creating the tooltip.
/// The tooltip's title will be injected into the .tooltip-inner.
/// .tooltip-arrow will become the tooltip's arrow.
/// The outermost wrapper element should have the .tooltip class.
/// Defaults to
/// <div class="tooltip" role="tooltip">
/// <div class="tooltip-arrow">
/// </div>
///
/// <div class="tooltip-inner">
/// </div>
/// </div>
/// </summary>
public virtual string Template
{
get;
set;
}
}
/// <summary>
/// Popover options
/// </summary>
[Ignore]
[ObjectLiteral]
public class PopoverOptions : PopupOptions
{
/// <summary>
/// Default content value if data-content attribute isn't present.
/// If a function is given, you can access the element that the popover is attached to via the "this" reference (Script.This<Element>()).
/// Defaults to ''.
/// </summary>
public virtual Any<string, Delegate, Func<string>> Content
{
get;
set;
}
/// <summary>
/// Base HTML to use when creating the popover.
/// The popover's title will be injected into the .popover-title.
/// The popover's content will be injected into the .popover-content.
/// .arrow will become the popover's arrow.
/// The outermost wrapper element should have the .popover class.
/// Defaults to
/// <div class="popover" role="tooltip">
/// <div class="arrow">
/// </div>
/// <h3 class="popover-title">
/// </h3>
/// <div class="popover-content">
/// </div>
/// </div>
/// </summary>
public virtual string Template
{
get;
set;
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2008 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
#if !(NETCOREAPP1_1 || NETCOREAPP2_0)
using System;
using System.Reflection;
namespace NUnit.Framework.Internal
{
[TestFixture]
public class RuntimeFrameworkTests
{
static readonly RuntimeType currentRuntime =
Type.GetType("Mono.Runtime", false) != null
? RuntimeType.Mono
: RuntimeType.Net;
[Test]
public void CanGetCurrentFramework()
{
RuntimeFramework framework = RuntimeFramework.CurrentFramework;
Assert.That(framework.Runtime, Is.EqualTo(currentRuntime), "#1");
Assert.That(framework.ClrVersion, Is.EqualTo(Environment.Version), "#2");
}
#if NET45
[Test]
public void TargetFrameworkIsSetCorrectly()
{
// We use reflection so it will compile and pass on Mono,
// including older versions that do not have the property.
var prop = typeof(AppDomainSetup).GetProperty("FrameworkName");
Assume.That(prop, Is.Not.Null);
Assert.That(
prop.GetValue(AppDomain.CurrentDomain.SetupInformation),
Is.EqualTo(".NETFramework,Version=v4.5"));
}
[Test]
public void DoesNotRunIn40CompatibilityModeWhenCompiled45()
{
var uri = new Uri( "http://host.com/path./" );
var uriStr = uri.ToString();
Assert.AreEqual( "http://host.com/path./", uriStr );
}
#elif NET40
[Test]
[Platform(Exclude = "Mono", Reason = "Mono does not run assemblies targeting 4.0 in compatibility mode")]
public void RunsIn40CompatibilityModeWhenCompiled40()
{
var uri = new Uri("http://host.com/path./");
var uriStr = uri.ToString();
Assert.AreEqual("http://host.com/path/", uriStr);
}
#endif
[Test]
public void CurrentFrameworkHasBuildSpecified()
{
Assert.That(RuntimeFramework.CurrentFramework.ClrVersion.Build, Is.GreaterThan(0));
}
[TestCaseSource(nameof(frameworkData))]
public void CanCreateUsingFrameworkVersion(FrameworkData data)
{
RuntimeFramework framework = new RuntimeFramework(data.runtime, data.frameworkVersion);
Assert.AreEqual(data.runtime, framework.Runtime, "#1");
Assert.AreEqual(data.frameworkVersion, framework.FrameworkVersion, "#2");
Assert.AreEqual(data.clrVersion, framework.ClrVersion, "#3");
}
[TestCaseSource(nameof(frameworkData))]
public void CanCreateUsingClrVersion(FrameworkData data)
{
Assume.That(data.frameworkVersion.Major != 3, "#0");
RuntimeFramework framework = new RuntimeFramework(data.runtime, data.clrVersion);
Assert.AreEqual(data.runtime, framework.Runtime, "#1");
Assert.AreEqual(data.frameworkVersion, framework.FrameworkVersion, "#2");
Assert.AreEqual(data.clrVersion, framework.ClrVersion, "#3");
}
[TestCaseSource(nameof(frameworkData))]
public void CanParseRuntimeFramework(FrameworkData data)
{
RuntimeFramework framework = RuntimeFramework.Parse(data.representation);
Assert.AreEqual(data.runtime, framework.Runtime, "#1");
Assert.AreEqual(data.clrVersion, framework.ClrVersion, "#2");
}
[TestCaseSource(nameof(frameworkData))]
public void CanDisplayFrameworkAsString(FrameworkData data)
{
RuntimeFramework framework = new RuntimeFramework(data.runtime, data.frameworkVersion);
Assert.AreEqual(data.representation, framework.ToString(), "#1");
Assert.AreEqual(data.displayName, framework.DisplayName, "#2");
}
[TestCaseSource(nameof(matchData))]
public bool CanMatchRuntimes(RuntimeFramework f1, RuntimeFramework f2)
{
return f1.Supports(f2);
}
internal static TestCaseData[] matchData = new TestCaseData[] {
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, new Version(3,5)),
new RuntimeFramework(RuntimeType.Net, new Version(2,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, new Version(2,0)),
new RuntimeFramework(RuntimeType.Net, new Version(3,5)))
.Returns(false),
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, new Version(3,5)),
new RuntimeFramework(RuntimeType.Net, new Version(3,5)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, new Version(2,0)),
new RuntimeFramework(RuntimeType.Net, new Version(2,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, new Version(2,0)),
new RuntimeFramework(RuntimeType.Net, new Version(2,0,50727)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, new Version(2,0,50727)),
new RuntimeFramework(RuntimeType.Net, new Version(2,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, new Version(2,0,50727)),
new RuntimeFramework(RuntimeType.Net, new Version(2,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, new Version(2,0)),
new RuntimeFramework(RuntimeType.Mono, new Version(2,0)))
.Returns(false),
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, new Version(2,0)),
new RuntimeFramework(RuntimeType.Net, new Version(1,1)))
.Returns(false),
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, new Version(2,0,50727)),
new RuntimeFramework(RuntimeType.Net, new Version(2,0,40607)))
.Returns(false),
new TestCaseData(
new RuntimeFramework(RuntimeType.Mono, new Version(1,1)), // non-existent version but it works
new RuntimeFramework(RuntimeType.Mono, new Version(1,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.Mono, new Version(2,0)),
new RuntimeFramework(RuntimeType.Any, new Version(2,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.Any, new Version(2,0)),
new RuntimeFramework(RuntimeType.Mono, new Version(2,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.Any, new Version(2,0)),
new RuntimeFramework(RuntimeType.Any, new Version(2,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.Any, new Version(2,0)),
new RuntimeFramework(RuntimeType.Any, new Version(4,0)))
.Returns(false),
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, RuntimeFramework.DefaultVersion),
new RuntimeFramework(RuntimeType.Net, new Version(2,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, new Version(2,0)),
new RuntimeFramework(RuntimeType.Net, RuntimeFramework.DefaultVersion))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.Any, RuntimeFramework.DefaultVersion),
new RuntimeFramework(RuntimeType.Net, new Version(2,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, new Version(2,0)),
new RuntimeFramework(RuntimeType.Any, RuntimeFramework.DefaultVersion))
.Returns(true)
};
public struct FrameworkData
{
public RuntimeType runtime;
public Version frameworkVersion;
public Version clrVersion;
public string representation;
public string displayName;
public FrameworkData(RuntimeType runtime, Version frameworkVersion, Version clrVersion,
string representation, string displayName)
{
this.runtime = runtime;
this.frameworkVersion = frameworkVersion;
this.clrVersion = clrVersion;
this.representation = representation;
this.displayName = displayName;
}
public override string ToString()
{
return string.Format("<{0},{1},{2}>", this.runtime, this.frameworkVersion, this.clrVersion);
}
}
internal static FrameworkData[] frameworkData = new FrameworkData[] {
new FrameworkData(RuntimeType.Net, new Version(1,0), new Version(1,0,3705), "net-1.0", "Net 1.0"),
// new FrameworkData(RuntimeType.Net, new Version(1,0,3705), new Version(1,0,3705), "net-1.0.3705", "Net 1.0.3705"),
// new FrameworkData(RuntimeType.Net, new Version(1,0), new Version(1,0,3705), "net-1.0.3705", "Net 1.0.3705"),
new FrameworkData(RuntimeType.Net, new Version(1,1), new Version(1,1,4322), "net-1.1", "Net 1.1"),
// new FrameworkData(RuntimeType.Net, new Version(1,1,4322), new Version(1,1,4322), "net-1.1.4322", "Net 1.1.4322"),
new FrameworkData(RuntimeType.Net, new Version(2,0), new Version(2,0,50727), "net-2.0", "Net 2.0"),
// new FrameworkData(RuntimeType.Net, new Version(2,0,40607), new Version(2,0,40607), "net-2.0.40607", "Net 2.0.40607"),
// new FrameworkData(RuntimeType.Net, new Version(2,0,50727), new Version(2,0,50727), "net-2.0.50727", "Net 2.0.50727"),
new FrameworkData(RuntimeType.Net, new Version(3,0), new Version(2,0,50727), "net-3.0", "Net 3.0"),
new FrameworkData(RuntimeType.Net, new Version(3,5), new Version(2,0,50727), "net-3.5", "Net 3.5"),
new FrameworkData(RuntimeType.Net, new Version(4,0), new Version(4,0,30319), "net-4.0", "Net 4.0"),
new FrameworkData(RuntimeType.Net, RuntimeFramework.DefaultVersion, RuntimeFramework.DefaultVersion, "net", "Net"),
new FrameworkData(RuntimeType.Mono, new Version(1,0), new Version(1,1,4322), "mono-1.0", "Mono 1.0"),
new FrameworkData(RuntimeType.Mono, new Version(2,0), new Version(2,0,50727), "mono-2.0", "Mono 2.0"),
// new FrameworkData(RuntimeType.Mono, new Version(2,0,50727), new Version(2,0,50727), "mono-2.0.50727", "Mono 2.0.50727"),
new FrameworkData(RuntimeType.Mono, new Version(3,5), new Version(2,0,50727), "mono-3.5", "Mono 3.5"),
new FrameworkData(RuntimeType.Mono, new Version(4,0), new Version(4,0,30319), "mono-4.0", "Mono 4.0"),
new FrameworkData(RuntimeType.Mono, RuntimeFramework.DefaultVersion, RuntimeFramework.DefaultVersion, "mono", "Mono"),
new FrameworkData(RuntimeType.Any, new Version(1,1), new Version(1,1,4322), "v1.1", "v1.1"),
new FrameworkData(RuntimeType.Any, new Version(2,0), new Version(2,0,50727), "v2.0", "v2.0"),
// new FrameworkData(RuntimeType.Any, new Version(2,0,50727), new Version(2,0,50727), "v2.0.50727", "v2.0.50727"),
new FrameworkData(RuntimeType.Any, new Version(3,5), new Version(2,0,50727), "v3.5", "v3.5"),
new FrameworkData(RuntimeType.Any, new Version(4,0), new Version(4,0,30319), "v4.0", "v4.0"),
new FrameworkData(RuntimeType.Any, RuntimeFramework.DefaultVersion, RuntimeFramework.DefaultVersion, "any", "Any")
};
}
}
#endif
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// Idea
///<para>SObject Name: Idea</para>
///<para>Custom Object: False</para>
///</summary>
public class SfIdea : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "Idea"; }
}
///<summary>
/// Idea ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Deleted
/// <para>Name: IsDeleted</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isDeleted")]
[Updateable(false), Createable(false)]
public bool? IsDeleted { get; set; }
///<summary>
/// Title
/// <para>Name: Title</para>
/// <para>SF Type: string</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "title")]
public string Title { get; set; }
///<summary>
/// Record Type ID
/// <para>Name: RecordTypeId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "recordTypeId")]
[Updateable(false), Createable(false)]
public string RecordTypeId { get; set; }
///<summary>
/// ReferenceTo: RecordType
/// <para>RelationshipName: RecordType</para>
///</summary>
[JsonProperty(PropertyName = "recordType")]
[Updateable(false), Createable(false)]
public SfRecordType RecordType { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
///<summary>
/// Created By ID
/// <para>Name: CreatedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdById")]
[Updateable(false), Createable(false)]
public string CreatedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: CreatedBy</para>
///</summary>
[JsonProperty(PropertyName = "createdBy")]
[Updateable(false), Createable(false)]
public SfUser CreatedBy { get; set; }
///<summary>
/// Last Modified Date
/// <para>Name: LastModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastModifiedDate { get; set; }
///<summary>
/// Last Modified By ID
/// <para>Name: LastModifiedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedById")]
[Updateable(false), Createable(false)]
public string LastModifiedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: LastModifiedBy</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedBy")]
[Updateable(false), Createable(false)]
public SfUser LastModifiedBy { get; set; }
///<summary>
/// System Modstamp
/// <para>Name: SystemModstamp</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "systemModstamp")]
[Updateable(false), Createable(false)]
public DateTimeOffset? SystemModstamp { get; set; }
///<summary>
/// Last Viewed Date
/// <para>Name: LastViewedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "lastViewedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastViewedDate { get; set; }
///<summary>
/// Last Referenced Date
/// <para>Name: LastReferencedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "lastReferencedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastReferencedDate { get; set; }
///<summary>
/// Zone ID
/// <para>Name: CommunityId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "communityId")]
[Updateable(false), Createable(true)]
public string CommunityId { get; set; }
///<summary>
/// ReferenceTo: Community
/// <para>RelationshipName: Community</para>
///</summary>
[JsonProperty(PropertyName = "community")]
[Updateable(false), Createable(false)]
public SfCommunity Community { get; set; }
///<summary>
/// Idea Body
/// <para>Name: Body</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "body")]
public string Body { get; set; }
///<summary>
/// Number of Comments
/// <para>Name: NumComments</para>
/// <para>SF Type: int</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "numComments")]
[Updateable(false), Createable(false)]
public int? NumComments { get; set; }
///<summary>
/// Vote Score
/// <para>Name: VoteScore</para>
/// <para>SF Type: double</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "voteScore")]
[Updateable(false), Createable(false)]
public double? VoteScore { get; set; }
///<summary>
/// Vote Total
/// <para>Name: VoteTotal</para>
/// <para>SF Type: double</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "voteTotal")]
[Updateable(false), Createable(false)]
public double? VoteTotal { get; set; }
///<summary>
/// Categories
/// <para>Name: Categories</para>
/// <para>SF Type: multipicklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "categories")]
public string Categories { get; set; }
///<summary>
/// Status
/// <para>Name: Status</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "status")]
public string Status { get; set; }
///<summary>
/// Last Idea Comment Date
/// <para>Name: LastCommentDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "lastCommentDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastCommentDate { get; set; }
///<summary>
/// Idea Comment ID
/// <para>Name: LastCommentId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "lastCommentId")]
[Updateable(false), Createable(false)]
public string LastCommentId { get; set; }
///<summary>
/// ReferenceTo: IdeaComment
/// <para>RelationshipName: LastComment</para>
///</summary>
[JsonProperty(PropertyName = "lastComment")]
[Updateable(false), Createable(false)]
public SfIdeaComment LastComment { get; set; }
///<summary>
/// Idea ID
/// <para>Name: ParentIdeaId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "parentIdeaId")]
[Updateable(false), Createable(false)]
public string ParentIdeaId { get; set; }
///<summary>
/// ReferenceTo: Idea
/// <para>RelationshipName: ParentIdea</para>
///</summary>
[JsonProperty(PropertyName = "parentIdea")]
[Updateable(false), Createable(false)]
public SfIdea ParentIdea { get; set; }
///<summary>
/// IsHtml
/// <para>Name: IsHtml</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isHtml")]
[Updateable(false), Createable(false)]
public bool? IsHtml { get; set; }
///<summary>
/// Is Merged
/// <para>Name: IsMerged</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isMerged")]
[Updateable(false), Createable(false)]
public bool? IsMerged { get; set; }
///<summary>
/// Url of Creator's Profile Photo
/// <para>Name: CreatorFullPhotoUrl</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "creatorFullPhotoUrl")]
[Updateable(false), Createable(false)]
public string CreatorFullPhotoUrl { get; set; }
///<summary>
/// Url of Creator's Thumbnail Photo
/// <para>Name: CreatorSmallPhotoUrl</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "creatorSmallPhotoUrl")]
[Updateable(false), Createable(false)]
public string CreatorSmallPhotoUrl { get; set; }
///<summary>
/// Name of Creator
/// <para>Name: CreatorName</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "creatorName")]
[Updateable(false), Createable(false)]
public string CreatorName { get; set; }
}
}
| |
namespace Petstore
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// UsageOperations operations.
/// </summary>
internal partial class UsageOperations : Microsoft.Rest.IServiceOperations<StorageManagementClient>, IUsageOperations
{
/// <summary>
/// Initializes a new instance of the UsageOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal UsageOperations(StorageManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the StorageManagementClient
/// </summary>
public StorageManagementClient Client { get; private set; }
/// <summary>
/// Gets the current usage count and the limit for the resources under the
/// subscription.
/// </summary>
/// <param name='customHeaders'>
/// 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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IEnumerable<Usage>>> ListWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Storage/usages").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IEnumerable<Usage>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Usage>>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using Newtonsoft.Json.Linq;
using NuGet.Client.Diagnostics;
using NuGet.Data;
using NuGet.Versioning;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JsonLD.Core;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using NuGet.Client.Resolution;
using System.Net.Http;
using System.Globalization;
using NuGet.Client.Installation;
using System.Threading;
namespace NuGet.Client
{
public class V3SourceRepository : SourceRepository, IDisposable
{
private DataClient _client;
private PackageSource _source;
private Uri _root;
private string _userAgent;
private System.Net.Http.HttpClient _http;
public async override Task<IEnumerable<JObject>> Search(string searchTerm, SearchFilter filters, int skip, int take, CancellationToken cancellationToken)
{
// Get the search service URL from the service
cancellationToken.ThrowIfCancellationRequested();
var searchService = await GetServiceUri(ServiceUris.SearchQueryService);
if (String.IsNullOrEmpty(searchService))
{
throw new NuGetProtocolException(Strings.Protocol_MissingSearchService);
}
cancellationToken.ThrowIfCancellationRequested();
// Construct the query
var queryUrl = new UriBuilder(searchService);
string queryString =
"q=" + searchTerm +
"&skip=" + skip.ToString() +
"&take=" + take.ToString() +
"&includePrerelease=" + filters.IncludePrerelease.ToString().ToLowerInvariant();
string frameworks =
String.Join("&",
filters.SupportedFrameworks.Select(
fx => "supportedFramework=" + VersionUtility.GetShortFrameworkName(fx)));
if (!String.IsNullOrEmpty(frameworks))
{
queryString += "&" + frameworks;
}
queryUrl.Query = queryString;
// Execute the query! Bypass the cache for now
NuGetTraceSources.V3SourceRepository.Info(
"searching",
"Executing Query: {0}",
queryUrl.ToString());
var results = await _client.GetFile(queryUrl.Uri);
cancellationToken.ThrowIfCancellationRequested();
if (results == null)
{
NuGetTraceSources.V3SourceRepository.Warning(
"results_invalid",
"Recieved unexpected results from {0}!",
queryUrl.ToString());
return Enumerable.Empty<JObject>();
}
var data = results.Value<JArray>("data");
if (data == null)
{
NuGetTraceSources.V3SourceRepository.Warning(
"results_invalid",
"Recieved invalid results from {0}!",
queryUrl.ToString());
return Enumerable.Empty<JObject>();
}
NuGetTraceSources.V3SourceRepository.Verbose(
"results_received",
"Received {1} hits from {0}",
queryUrl.ToString(),
data.Count);
// Resolve all the objects
List<JObject> outputs = new List<JObject>(take);
foreach (var result in data.Take(take).Cast<JObject>())
{
var output = await ProcessSearchResult(cancellationToken, result);
if (output != null)
{
outputs.Add(output);
}
}
var metricsUrl = await GetServiceUri(ServiceUris.MetricsService);
if (metricsUrl == null)
{
// Nothing to do!
return;
}
return outputs;
}
private static readonly Uri[] ResultItemRequiredProperties = new Uri[] {
new Uri("http://schema.nuget.org/schema#registration")
};
private static readonly Uri[] PackageRequiredProperties = new Uri[] {
new Uri("http://schema.nuget.org/schema#catalogEntry")
};
private static readonly Uri[] CatalogRequiredProperties = new Uri[] {
new Uri("http://schema.nuget.org/schema#items")
};
private static readonly Uri[] PackageDetailsRequiredProperties = new Uri[] {
new Uri("http://schema.nuget.org/schema#authors"),
new Uri("http://schema.nuget.org/schema#description"),
new Uri("http://schema.nuget.org/schema#iconUrl"),
new Uri("http://schema.nuget.org/schema#id"),
new Uri("http://schema.nuget.org/schema#language"),
new Uri("http://schema.nuget.org/schema#licenseUrl"),
new Uri("http://schema.nuget.org/schema#minClientVersion"),
new Uri("http://schema.nuget.org/schema#projectUrl"),
new Uri("http://schema.nuget.org/schema#published"),
new Uri("http://schema.nuget.org/schema#requireLicenseAcceptance"),
new Uri("http://schema.nuget.org/schema#summary"),
new Uri("http://schema.nuget.org/schema#tags"),
new Uri("http://schema.nuget.org/schema#title"),
new Uri("http://schema.nuget.org/schema#version"),
};
public override PackageSource Source
{
get { return _source; }
}
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "The HttpClient can be left open until VS shuts down.")]
public V3SourceRepository(PackageSource source, string host)
{
_source = source;
_root = new Uri(source.Url);
// TODO: Get context from current UI activity (PowerShell, Dialog, etc.)
_userAgent = UserAgentUtil.GetUserAgent("NuGet.Client", host);
_http = new System.Net.Http.HttpClient(
new TracingHttpHandler(
NuGetTraceSources.V3SourceRepository,
new SetUserAgentHandler(
_userAgent,
new HttpClientHandler())));
// Check if we should disable the browser file cache
FileCacheBase cache = new BrowserFileCache();
if (String.Equals(Environment.GetEnvironmentVariable("NUGET_DISABLE_IE_CACHE"), "true", StringComparison.OrdinalIgnoreCase))
{
cache = new NullFileCache();
}
cache = new NullFileCache(); // +++ Disable caching for testing
_client = new DataClient(
_http,
cache);
}
public DataClient DataClient
{
get
{
return _client;
}
}
// Async void because we don't want metric recording to block anything at all
public override async void RecordMetric(PackageActionType actionType, PackageIdentity packageIdentity, PackageIdentity dependentPackage, bool isUpdate, InstallationTarget target)
{
var metricsUrl = await GetServiceUri(ServiceUris.MetricsService, CancellationToken.None);
if (metricsUrl == null)
{
// Nothing to do!
return;
}
// Create the JSON payload
var payload = new JObject();
payload.Add("id", packageIdentity.Id);
payload.Add("version", packageIdentity.Version.ToNormalizedString());
payload.Add("operation", isUpdate ? "Update" : "Install");
payload.Add("userAgent", _userAgent);
payload.Add("targetFrameworks", new JArray(target.GetSupportedFrameworks().Select(fx => VersionUtility.GetShortFrameworkName(fx))));
if (dependentPackage != null)
{
payload.Add("dependentPackage", dependentPackage.Id);
payload.Add("dependentPackageVersion", dependentPackage.Version.ToNormalizedString());
}
target.AddMetricsMetadata(payload);
// Post the message
await _http.PostAsync(metricsUrl, new StringContent(payload.ToString()));
}
// +++ this would not be needed once the result matches searchResult.
private async Task<JObject> ProcessSearchResult(CancellationToken cancellationToken, JObject result)
{
NuGetTraceSources.V3SourceRepository.Verbose(
"resolving_package",
"Resolving Package: {0}",
result[Properties.SubjectId]);
cancellationToken.ThrowIfCancellationRequested();
// Get the registration
result = (JObject)(await _client.Ensure(result, ResultItemRequiredProperties));
var searchResult = new JObject();
searchResult["id"] = result["id"];
searchResult[Properties.LatestVersion] = result[Properties.Version];
searchResult[Properties.Versions] = result[Properties.Versions];
searchResult[Properties.Summary] = result[Properties.Summary];
searchResult[Properties.Description] = result[Properties.Description];
searchResult[Properties.IconUrl] = result[Properties.IconUrl];
return searchResult;
}
public override async Task<JObject> GetPackageMetadata(string id, NuGetVersion version)
{
var data = await GetPackageMetadataById(id);
return data.FirstOrDefault(p => StringComparer.OrdinalIgnoreCase.Equals(
p["version"].ToString(),
version.ToNormalizedString()));
}
public override async Task<IEnumerable<JObject>> GetPackageMetadataById(string packageId)
{
// Get the base URL
var baseUrl = await GetServiceUri(ServiceUris.RegistrationsBaseUrl, CancellationToken.None);
if (String.IsNullOrEmpty(baseUrl))
{
throw new NuGetProtocolException(Strings.Protocol_MissingRegistrationBase);
}
// Construct the URL
var packageUrl = baseUrl.TrimEnd('/') + "/" + packageId.ToLowerInvariant() + "/index.json";
// Resolve the catalog root
var catalogPackage = await _client.Ensure(
new Uri(packageUrl),
CatalogRequiredProperties);
if (catalogPackage["HttpStatusCode"] != null)
{
// Got an error response from the data client, so just return an empty array
return Enumerable.Empty<JObject>();
}
// Descend through the items to find all the versions
var versions = await Descend((JArray)catalogPackage["items"]);
// Return the catalogEntry values
return versions.Select(o =>
{
var result = (JObject)o["catalogEntry"];
result[Properties.PackageContent] = o[Properties.PackageContent];
return result;
});
}
private async Task<IEnumerable<JObject>> Descend(JArray json)
{
List<IEnumerable<JObject>> lists = new List<IEnumerable<JObject>>();
List<JObject> items = new List<JObject>();
lists.Add(items);
foreach (var item in json)
{
string type = item["@type"].ToString();
if (Equals(type, "catalog:CatalogPage"))
{
var resolved = await _client.Ensure(
item,
new[] { new Uri("http://schema.nuget.org/schema#items") });
Debug.Assert(resolved != null, "DataClient returned null from Ensure :(");
lists.Add(await Descend((JArray)resolved["items"]));
}
else if (Equals(type, "Package"))
{
// Yield this item with catalogEntry and it's subfields ensured
var resolved = await _client.Ensure(item, PackageRequiredProperties);
resolved["catalogEntry"] = await _client.Ensure(resolved["catalogEntry"], PackageDetailsRequiredProperties);
items.Add((JObject)resolved);
}
}
// Flatten the list and return it
return lists.SelectMany(j => j);
}
private async Task<string> GetServiceUri(Uri type, CancellationToken cancellationToken)
{
// Read the root document (usually out of the cache :))
JObject doc;
var sourceUrl = new Uri(_source.Url);
if (sourceUrl.IsFile)
{
using (var reader = new System.IO.StreamReader(
sourceUrl.LocalPath))
{
string json = await reader.ReadToEndAsync();
doc = JObject.Parse(json);
}
}
else
{
doc = await _client.GetFile(sourceUrl);
}
var obj = JsonLdProcessor.Expand(doc).FirstOrDefault();
if (obj == null)
{
throw new NuGetProtocolException(Strings.Protocol_IndexMissingResourcesNode);
}
var resources = obj[ServiceUris.Resources.ToString()] as JArray;
if (resources == null)
{
throw new NuGetProtocolException(Strings.Protocol_IndexMissingResourcesNode);
}
// Query it for the requested service
var candidates = (from resource in resources.OfType<JObject>()
let resourceType = resource["@type"].Select(t => t.ToString()).FirstOrDefault()
where resourceType != null && Equals(resourceType, type.ToString())
select resource)
.ToList();
NuGetTraceSources.V3SourceRepository.Verbose(
"service_candidates",
"Found {0} candidates for {1} service: [{2}]",
candidates.Count,
type,
String.Join(", ", candidates.Select(c => c.Value<string>("@id"))));
var selected = candidates.FirstOrDefault();
if (selected != null)
{
NuGetTraceSources.V3SourceRepository.Info(
"getserviceuri",
"Found {0} service at {1}",
selected["@type"][0],
selected["@id"]);
return selected.Value<string>("@id");
}
else
{
NuGetTraceSources.V3SourceRepository.Error(
"getserviceuri_failed",
"Unable to find compatible {0} service on {1}",
type,
_root);
return null;
}
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
_http.Dispose();
_client.Dispose();
}
disposedValue = true;
}
}
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="altserialization.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
* AltSerialization.cs
*
* Copyright (c) 1998-2000, Microsoft Corporation
*
*/
namespace System.Web.Util {
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
using System.Web.SessionState;
internal static class AltSerialization {
enum TypeID : byte {
String = 1,
Int32,
Boolean,
DateTime,
Decimal,
Byte,
Char,
Single,
Double,
SByte,
Int16,
Int64,
UInt16,
UInt32,
UInt64,
TimeSpan,
Guid,
IntPtr,
UIntPtr,
Object,
Null,
}
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This method is safe critical (we're allowed to call the SerializationSurrogateSelector property getter).")]
internal static void WriteValueToStream(Object value, BinaryWriter writer) {
if (value == null) {
writer.Write((byte)TypeID.Null);
}
else if (value is String) {
writer.Write((byte)TypeID.String);
writer.Write((String) value);
}
else if (value is Int32) {
writer.Write((byte)TypeID.Int32);
writer.Write((Int32) value);
}
else if (value is Boolean) {
writer.Write((byte)TypeID.Boolean);
writer.Write((Boolean) value);
}
else if (value is DateTime) {
writer.Write((byte)TypeID.DateTime);
writer.Write(((DateTime) value).Ticks);
}
else if (value is Decimal) {
writer.Write((byte)TypeID.Decimal);
int[] bits = Decimal.GetBits((Decimal)value);
for (int i = 0; i < 4; i++) {
writer.Write((int)bits[i]);
}
}
else if (value is Byte) {
writer.Write((byte)TypeID.Byte);
writer.Write((byte) value);
}
else if (value is Char) {
writer.Write((byte)TypeID.Char);
writer.Write((char) value);
}
else if (value is Single) {
writer.Write((byte)TypeID.Single);
writer.Write((float) value);
}
else if (value is Double) {
writer.Write((byte)TypeID.Double);
writer.Write((double) value);
}
else if (value is SByte) {
writer.Write((byte)TypeID.SByte);
writer.Write((SByte) value);
}
else if (value is Int16) {
writer.Write((byte)TypeID.Int16);
writer.Write((short) value);
}
else if (value is Int64) {
writer.Write((byte)TypeID.Int64);
writer.Write((long) value);
}
else if (value is UInt16) {
writer.Write((byte)TypeID.UInt16);
writer.Write((UInt16) value);
}
else if (value is UInt32) {
writer.Write((byte)TypeID.UInt32);
writer.Write((UInt32) value);
}
else if (value is UInt64) {
writer.Write((byte)TypeID.UInt64);
writer.Write((UInt64) value);
}
else if (value is TimeSpan) {
writer.Write((byte)TypeID.TimeSpan);
writer.Write(((TimeSpan) value).Ticks);
}
else if (value is Guid) {
writer.Write((byte)TypeID.Guid);
Guid guid = (Guid) value;
byte[] bits = guid.ToByteArray();
writer.Write(bits);
}
else if (value is IntPtr) {
writer.Write((byte)TypeID.IntPtr);
IntPtr v = (IntPtr) value;
if (IntPtr.Size == 4) {
writer.Write((Int32)v.ToInt32());
}
else {
Debug.Assert(IntPtr.Size == 8);
writer.Write((Int64)v.ToInt64());
}
}
else if (value is UIntPtr) {
writer.Write((byte)TypeID.UIntPtr);
UIntPtr v = (UIntPtr) value;
if (UIntPtr.Size == 4) {
writer.Write((UInt32)v.ToUInt32());
}
else {
Debug.Assert(UIntPtr.Size == 8);
writer.Write((UInt64)v.ToUInt64());
}
}
else {
writer.Write((byte)TypeID.Object);
BinaryFormatter formatter = new BinaryFormatter();
if (SessionStateUtility.SerializationSurrogateSelector != null) {
formatter.SurrogateSelector = SessionStateUtility.SerializationSurrogateSelector;
}
try {
formatter.Serialize(writer.BaseStream, value);
} catch (Exception innerException) {
HttpException outerException = new HttpException(SR.GetString(SR.Cant_serialize_session_state), innerException);
outerException.SetFormatter(new UseLastUnhandledErrorFormatter(outerException));
throw outerException;
}
}
}
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This method is safe critical (we're allowed to call the SerializationSurrogateSelector property getter).")]
internal static Object ReadValueFromStream(BinaryReader reader) {
TypeID id;
Object value = null;
id = (TypeID) reader.ReadByte();
switch (id) {
case TypeID.String:
value = reader.ReadString();
break;
case TypeID.Int32:
value = reader.ReadInt32();
break;
case TypeID.Boolean:
value = reader.ReadBoolean();
break;
case TypeID.DateTime:
value = new DateTime(reader.ReadInt64());
break;
case TypeID.Decimal:
{
int[] bits = new int[4];
for (int i = 0; i < 4; i++) {
bits[i] = reader.ReadInt32();
}
value = new Decimal(bits);
}
break;
case TypeID.Byte:
value = reader.ReadByte();
break;
case TypeID.Char:
value = reader.ReadChar();
break;
case TypeID.Single:
value = reader.ReadSingle();
break;
case TypeID.Double:
value = reader.ReadDouble();
break;
case TypeID.SByte:
value = reader.ReadSByte();
break;
case TypeID.Int16:
value = reader.ReadInt16();
break;
case TypeID.Int64:
value = reader.ReadInt64();
break;
case TypeID.UInt16:
value = reader.ReadUInt16();
break;
case TypeID.UInt32:
value = reader.ReadUInt32();
break;
case TypeID.UInt64:
value = reader.ReadUInt64();
break;
case TypeID.TimeSpan:
value = new TimeSpan(reader.ReadInt64());
break;
case TypeID.Guid:
{
byte[] bits = reader.ReadBytes(16);
value = new Guid(bits);
}
break;
case TypeID.IntPtr:
if (IntPtr.Size == 4) {
value = new IntPtr(reader.ReadInt32());
}
else {
Debug.Assert(IntPtr.Size == 8);
value = new IntPtr(reader.ReadInt64());
}
break;
case TypeID.UIntPtr:
if (UIntPtr.Size == 4) {
value = new UIntPtr(reader.ReadUInt32());
}
else {
Debug.Assert(UIntPtr.Size == 8);
value = new UIntPtr(reader.ReadUInt64());
}
break;
case TypeID.Object:
BinaryFormatter formatter = new BinaryFormatter();
if (SessionStateUtility.SerializationSurrogateSelector != null) {
formatter.SurrogateSelector = SessionStateUtility.SerializationSurrogateSelector;
}
value = formatter.Deserialize(reader.BaseStream);
break;
case TypeID.Null:
value = null;
break;
}
return value;
}
}
}
| |
using System;
using System.Xml;
using System.Text;
using System.IO;
namespace Hydra.Framework.XmlSerialization.Exslt
{
//
//**********************************************************************
/// <summary>
/// XSLT output method enumeration, see W3C XSLT 1.0 Recommendation at
/// <a href="http://www.w3.org/TR/xslt.html#output">http://www.w3.org/TR/xslt.html#output</a>.
/// </summary>
/// <remarks>Only <c>xml</c> and <c>text</c> methods are supported by this version of
/// the <c>MultiXmlTextWriter</c>.</remarks>
//**********************************************************************
//
internal enum OutputMethod
{
Xml,
Text
};
//
//**********************************************************************
/// <summary>
/// This class represents redirected output state and properties.
/// </summary>
//**********************************************************************
//
internal class OutputState
{
private XmlTextWriter xmlWriter;
private StreamWriter textWriter;
private int depth;
private string href;
private Encoding encoding;
private bool indent;
private string publicDoctype;
private string systemDoctype;
private bool standalone;
private string storedDir;
private OutputMethod method;
private bool omitXmlDecl;
//
//**********************************************************************
/// <summary>
/// Creates new <c>OutputState</c> with default properties values:
/// UTF8 encoding, no indentation, nonstandalone document, XML output
/// method.
/// </summary>
//**********************************************************************
//
public OutputState()
{
encoding = System.Text.Encoding.UTF8;
indent = false;
standalone = false;
omitXmlDecl = false;
method = OutputMethod.Xml;
}
//
//**********************************************************************
/// <summary>
/// Initializes the writer to write redirected output.
/// </summary>
/// <remarks>Depending on the <c>method</c> attribute value,
/// <c>XmlTextWriter</c> or <c>StreamWriter</c> is created.
/// <c>XmlTextWriter</c> is used for outputting XML and
/// <c>StreamWriter</c> - for plain text.
/// </remarks>
//**********************************************************************
//
public void InitWriter()
{
//
// Save current directory
//
storedDir = Directory.GetCurrentDirectory();
DirectoryInfo dir = Directory.GetParent(href);
if (!dir.Exists)
dir.Create();
//
// Create writer
//
if (method == OutputMethod.Xml)
{
xmlWriter = new XmlTextWriter(href, encoding);
if (indent)
xmlWriter.Formatting = Formatting.Indented;
if (!omitXmlDecl)
{
if (standalone)
xmlWriter.WriteStartDocument(true);
else
xmlWriter.WriteStartDocument();
}
}
else
textWriter = new StreamWriter(href, false, encoding);
//
// Set new current directory
//
Directory.SetCurrentDirectory(dir.ToString());
}
//
//**********************************************************************
/// <summary>
/// Closes the writer that was used to write redirected output.
/// </summary>
//**********************************************************************
//
public void CloseWriter()
{
if (method == OutputMethod.Xml)
{
if (!omitXmlDecl)
{
xmlWriter.WriteEndDocument();
}
xmlWriter.Close();
}
else
textWriter.Close();
//
// Restore previous current directory
//
Directory.SetCurrentDirectory(storedDir);
}
//
//**********************************************************************
/// <summary>
/// Specifies whether the result document should be written with
/// a standalone XML document declaration.
/// </summary>
/// <value>Standalone XML declaration as per W3C XSLT 1.0 Recommendation (see
/// <a href="http://www.w3.org/TR/xslt.html#output">http://www.w3.org/TR/xslt.html#output</a>
/// for more info).</value>
/// <remarks>The property does not affect output while output method is <c>text</c>.</remarks>
//**********************************************************************
//
public bool Standalone
{
get { return standalone; }
set { standalone = value; }
}
//
//**********************************************************************
/// <summary>
/// Specifies output method.
/// </summary>
/// <value>Output Method as per W3C XSLT 1.0 Recommendation (see
/// <a href="http://www.w3.org/TR/xslt.html#output">http://www.w3.org/TR/xslt.html#output</a>
/// for more info).</value>
//**********************************************************************
//
public OutputMethod Method
{
get { return method; }
set { method = value; }
}
//
//**********************************************************************
/// <summary>
/// Specifies the URI where the result document should be written to.
/// </summary>
/// <value>Absolute or relative URI of the output document.</value>
//**********************************************************************
//
public string Href
{
get { return href; }
set { href = value; }
}
//
//**********************************************************************
/// <summary>
/// Specifies the preferred character encoding of the result document.
/// </summary>
/// <value>Output encoding as per W3C XSLT 1.0 Recommendation (see
/// <a href="http://www.w3.org/TR/xslt.html#output">http://www.w3.org/TR/xslt.html#output</a>
/// for more info).</value>
//**********************************************************************
//
public Encoding Encoding
{
get { return encoding; }
set { encoding = value; }
}
//
//**********************************************************************
/// <summary>
/// Specifies whether the result document should be written in the
/// indented form.
/// </summary>
/// <value>Output document formatting as per W3C XSLT 1.0 Recommendation (see
/// <a href="http://www.w3.org/TR/xslt.html#output">http://www.w3.org/TR/xslt.html#output</a>
/// for more info).</value>
/// <remarks>The property does not affect output while output method is <c>text</c>.</remarks>
//**********************************************************************
//
public bool Indent
{
get { return indent; }
set { indent = value; }
}
//
//**********************************************************************
/// <summary>
/// Specifies the public identifier to be used in the document
/// type declaration.
/// </summary>
/// <value>Public part of the output document type definition as per W3C XSLT 1.0 Recommendation (see
/// <a href="http://www.w3.org/TR/xslt.html#output">http://www.w3.org/TR/xslt.html#output</a>
/// for more info).</value>
/// <remarks>The property does not affect output while output method is <c>text</c>.</remarks>
//**********************************************************************
//
public string PublicDoctype
{
get { return publicDoctype; }
set { publicDoctype = value; }
}
//
//**********************************************************************
/// <summary>
/// Specifies the system identifier to be used in the document
/// type declaration.
/// </summary>
/// <value>System part of the output document type definition as per W3C XSLT 1.0 Recommendation (see
/// <a href="http://www.w3.org/TR/xslt.html#output">http://www.w3.org/TR/xslt.html#output</a>
/// for more info).</value>
/// <remarks>The property does not affect output while output method is <c>text</c>.</remarks>
//**********************************************************************
//
public string SystemDoctype
{
get { return systemDoctype; }
set { systemDoctype = value; }
}
//
//**********************************************************************
/// <summary>
/// Actual <c>XmlTextWriter</c> used to write the redirected
/// result document.
/// </summary>
/// <value><c>XmlWriter</c>, which is used to write the output document in XML method.</value>
//**********************************************************************
//
public XmlTextWriter XmlWriter
{
get { return xmlWriter; }
}
//
//**********************************************************************
/// <summary>
/// Actual <c>TextWriter</c> used to write the redirected
/// result document in text output method.
/// </summary>
/// <value><c>StreamWriter</c>, which is used to write the output document in text method.</value>
//**********************************************************************
//
public StreamWriter TextWriter
{
get { return textWriter; }
}
//
//**********************************************************************
/// <summary>
/// Tree depth (used to detect end tag of the <c>exsl:document</c>).
/// </summary>
/// <value>Current output tree depth.</value>
//**********************************************************************
//
public int Depth
{
get { return depth; }
set { depth = value; }
}
//
//**********************************************************************
/// <summary>
/// Specifies whether the XSLT processor should output an XML declaration.
/// </summary>
//**********************************************************************
//
public bool OmitXmlDeclaration
{
get { return omitXmlDecl; }
set { omitXmlDecl = value; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
namespace System.Drawing
{
public static partial class SystemFonts
{
private static unsafe bool GetNonClientMetrics(out NativeMethods.NONCLIENTMETRICS metrics)
{
metrics = new NativeMethods.NONCLIENTMETRICS { cbSize = (uint)sizeof(NativeMethods.NONCLIENTMETRICS) };
fixed (void* m = &metrics)
{
return UnsafeNativeMethods.SystemParametersInfo(NativeMethods.SPI_GETNONCLIENTMETRICS, metrics.cbSize, m, 0);
}
}
public static Font CaptionFont
{
get
{
Font captionFont = null;
if (GetNonClientMetrics(out NativeMethods.NONCLIENTMETRICS metrics))
{
captionFont = GetFontFromData(metrics.lfCaptionFont);
captionFont.SetSystemFontName(nameof(CaptionFont));
}
return captionFont;
}
}
public static Font SmallCaptionFont
{
get
{
Font smcaptionFont = null;
if (GetNonClientMetrics(out NativeMethods.NONCLIENTMETRICS metrics))
{
smcaptionFont = GetFontFromData(metrics.lfSmCaptionFont);
smcaptionFont.SetSystemFontName(nameof(SmallCaptionFont));
}
return smcaptionFont;
}
}
public static Font MenuFont
{
get
{
Font menuFont = null;
if (GetNonClientMetrics(out NativeMethods.NONCLIENTMETRICS metrics))
{
menuFont = GetFontFromData(metrics.lfMenuFont);
menuFont.SetSystemFontName(nameof(MenuFont));
}
return menuFont;
}
}
public static Font StatusFont
{
get
{
Font statusFont = null;
if (GetNonClientMetrics(out NativeMethods.NONCLIENTMETRICS metrics))
{
statusFont = GetFontFromData(metrics.lfStatusFont);
statusFont.SetSystemFontName(nameof(StatusFont));
}
return statusFont;
}
}
public static Font MessageBoxFont
{
get
{
Font messageBoxFont = null;
if (GetNonClientMetrics(out NativeMethods.NONCLIENTMETRICS metrics))
{
messageBoxFont = GetFontFromData(metrics.lfMessageFont);
messageBoxFont.SetSystemFontName(nameof(MessageBoxFont));
}
return messageBoxFont;
}
}
private static bool IsCriticalFontException(Exception ex)
{
return !(
// In any of these cases we'll handle the exception.
ex is ExternalException ||
ex is ArgumentException ||
ex is OutOfMemoryException || // GDI+ throws this one for many reasons other than actual OOM.
ex is InvalidOperationException ||
ex is NotImplementedException ||
ex is FileNotFoundException);
}
public static unsafe Font IconTitleFont
{
get
{
Font iconTitleFont = null;
var itfont = new SafeNativeMethods.LOGFONT();
if (UnsafeNativeMethods.SystemParametersInfo(NativeMethods.SPI_GETICONTITLELOGFONT, (uint)sizeof(SafeNativeMethods.LOGFONT), &itfont, 0))
{
iconTitleFont = GetFontFromData(itfont);
iconTitleFont.SetSystemFontName(nameof(IconTitleFont));
}
return iconTitleFont;
}
}
public static Font DefaultFont
{
get
{
Font defaultFont = null;
// For Arabic systems, always return Tahoma 8.
if ((ushort)UnsafeNativeMethods.GetSystemDefaultLCID() == 0x0001)
{
try
{
defaultFont = new Font("Tahoma", 8);
}
catch (Exception ex) when (!IsCriticalFontException(ex)) { }
}
// First try DEFAULT_GUI.
if (defaultFont == null)
{
IntPtr handle = UnsafeNativeMethods.GetStockObject(NativeMethods.DEFAULT_GUI_FONT);
try
{
using (Font fontInWorldUnits = Font.FromHfont(handle))
{
defaultFont = FontInPoints(fontInWorldUnits);
}
}
catch (ArgumentException)
{
// This can happen in theory if we end up pulling a non-TrueType font
}
}
// If DEFAULT_GUI didn't work, try Tahoma.
if (defaultFont == null)
{
try
{
defaultFont = new Font("Tahoma", 8);
}
catch (ArgumentException)
{
}
}
// Use GenericSansSerif as a last resort - this will always work.
if (defaultFont == null)
{
defaultFont = new Font(FontFamily.GenericSansSerif, 8);
}
if (defaultFont.Unit != GraphicsUnit.Point)
{
defaultFont = FontInPoints(defaultFont);
}
Debug.Assert(defaultFont != null, "defaultFont wasn't set.");
defaultFont.SetSystemFontName(nameof(DefaultFont));
return defaultFont;
}
}
public static Font DialogFont
{
get
{
Font dialogFont = null;
if ((ushort)UnsafeNativeMethods.GetSystemDefaultLCID() == 0x0011)
{
// Always return DefaultFont for Japanese cultures.
dialogFont = DefaultFont;
}
else
{
try
{
// Use MS Shell Dlg 2, 8pt for anything other than Japanese.
dialogFont = new Font("MS Shell Dlg 2", 8);
}
catch (ArgumentException)
{
// This can happen in theory if we end up pulling a non-TrueType font
}
}
if (dialogFont == null)
{
dialogFont = DefaultFont;
}
else if (dialogFont.Unit != GraphicsUnit.Point)
{
dialogFont = FontInPoints(dialogFont);
}
// For Japanese cultures, SystemFonts.DefaultFont returns a new Font object every time it is invoked.
// So for Japanese we return the DefaultFont with its SystemFontName set to DialogFont.
dialogFont.SetSystemFontName(nameof(DialogFont));
return dialogFont;
}
}
private static Font FontInPoints(Font font)
{
return new Font(font.FontFamily, font.SizeInPoints, font.Style, GraphicsUnit.Point, font.GdiCharSet, font.GdiVerticalFont);
}
private static Font GetFontFromData(SafeNativeMethods.LOGFONT logFont)
{
Font font = null;
try
{
font = Font.FromLogFont(ref logFont);
}
catch (Exception ex) when (!IsCriticalFontException(ex)) { }
return
font == null ? DefaultFont :
font.Unit != GraphicsUnit.Point ? FontInPoints(font) :
font;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using BTCPayServer.Client.Models;
using BTCPayServer.Events;
using BTCPayServer.Logging;
using BTCPayServer.Services.Invoices;
using BTCPayServer.Services.Notifications;
using BTCPayServer.Services.Notifications.Blobs;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NBitcoin;
using NBXplorer;
namespace BTCPayServer.HostedServices
{
public class InvoiceWatcher : IHostedService
{
class UpdateInvoiceContext
{
public UpdateInvoiceContext(InvoiceEntity invoice)
{
Invoice = invoice;
}
public InvoiceEntity Invoice { get; set; }
public List<object> Events { get; set; } = new List<object>();
bool _Dirty = false;
private bool _Unaffect;
public void MarkDirty()
{
_Dirty = true;
}
public void UnaffectAddresses()
{
_Unaffect = true;
}
public bool Dirty => _Dirty;
public bool Unaffect => _Unaffect;
bool _IsBlobUpdated;
public bool IsBlobUpdated => _IsBlobUpdated;
public void BlobUpdated()
{
_IsBlobUpdated = true;
}
}
readonly InvoiceRepository _invoiceRepository;
readonly EventAggregator _eventAggregator;
readonly ExplorerClientProvider _explorerClientProvider;
private readonly NotificationSender _notificationSender;
private readonly PaymentService _paymentService;
public Logs Logs { get; }
public InvoiceWatcher(
InvoiceRepository invoiceRepository,
EventAggregator eventAggregator,
ExplorerClientProvider explorerClientProvider,
NotificationSender notificationSender,
PaymentService paymentService,
Logs logs)
{
_invoiceRepository = invoiceRepository ?? throw new ArgumentNullException(nameof(invoiceRepository));
_eventAggregator = eventAggregator ?? throw new ArgumentNullException(nameof(eventAggregator));
_explorerClientProvider = explorerClientProvider;
_notificationSender = notificationSender;
_paymentService = paymentService;
this.Logs = logs;
}
readonly CompositeDisposable leases = new CompositeDisposable();
private void UpdateInvoice(UpdateInvoiceContext context)
{
var invoice = context.Invoice;
if (invoice.Status == InvoiceStatusLegacy.New && invoice.ExpirationTime <= DateTimeOffset.UtcNow)
{
context.MarkDirty();
context.UnaffectAddresses();
invoice.Status = InvoiceStatusLegacy.Expired;
var paidPartial = invoice.ExceptionStatus == InvoiceExceptionStatus.PaidPartial;
context.Events.Add(new InvoiceEvent(invoice, InvoiceEvent.Expired) { PaidPartial = paidPartial });
if (invoice.ExceptionStatus == InvoiceExceptionStatus.PaidPartial)
context.Events.Add(new InvoiceEvent(invoice, InvoiceEvent.ExpiredPaidPartial) { PaidPartial = paidPartial });
}
var allPaymentMethods = invoice.GetPaymentMethods();
var paymentMethod = GetNearestClearedPayment(allPaymentMethods, out var accounting);
if (allPaymentMethods.Any() && paymentMethod == null)
return;
if (accounting is null && invoice.Price is 0m)
{
accounting = new PaymentMethodAccounting()
{
Due = Money.Zero,
Paid = Money.Zero,
CryptoPaid = Money.Zero,
DueUncapped = Money.Zero,
NetworkFee = Money.Zero,
TotalDue = Money.Zero,
TxCount = 0,
TxRequired = 0,
MinimumTotalDue = Money.Zero,
NetworkFeeAlreadyPaid = Money.Zero
};
}
if (invoice.Status == InvoiceStatusLegacy.New || invoice.Status == InvoiceStatusLegacy.Expired)
{
var isPaid = invoice.IsUnsetTopUp() ?
accounting.Paid > Money.Zero :
accounting.Paid >= accounting.MinimumTotalDue;
if (isPaid)
{
if (invoice.Status == InvoiceStatusLegacy.New)
{
context.Events.Add(new InvoiceEvent(invoice, InvoiceEvent.PaidInFull));
invoice.Status = InvoiceStatusLegacy.Paid;
if (invoice.IsUnsetTopUp())
{
invoice.ExceptionStatus = InvoiceExceptionStatus.None;
invoice.Price = (accounting.Paid - accounting.NetworkFeeAlreadyPaid).ToDecimal(MoneyUnit.BTC) * paymentMethod.Rate;
accounting = paymentMethod.Calculate();
context.BlobUpdated();
}
else
{
invoice.ExceptionStatus = accounting.Paid > accounting.TotalDue ? InvoiceExceptionStatus.PaidOver : InvoiceExceptionStatus.None;
}
context.UnaffectAddresses();
context.MarkDirty();
}
else if (invoice.Status == InvoiceStatusLegacy.Expired && invoice.ExceptionStatus != InvoiceExceptionStatus.PaidLate)
{
invoice.ExceptionStatus = InvoiceExceptionStatus.PaidLate;
context.Events.Add(new InvoiceEvent(invoice, InvoiceEvent.PaidAfterExpiration));
context.MarkDirty();
}
}
if (accounting.Paid < accounting.MinimumTotalDue && invoice.GetPayments(true).Count != 0 && invoice.ExceptionStatus != InvoiceExceptionStatus.PaidPartial)
{
invoice.ExceptionStatus = InvoiceExceptionStatus.PaidPartial;
context.MarkDirty();
}
}
// Just make sure RBF did not cancelled a payment
if (invoice.Status == InvoiceStatusLegacy.Paid)
{
if (accounting.MinimumTotalDue <= accounting.Paid && accounting.Paid <= accounting.TotalDue && invoice.ExceptionStatus == InvoiceExceptionStatus.PaidOver)
{
invoice.ExceptionStatus = InvoiceExceptionStatus.None;
context.MarkDirty();
}
if (accounting.Paid > accounting.TotalDue && invoice.ExceptionStatus != InvoiceExceptionStatus.PaidOver)
{
invoice.ExceptionStatus = InvoiceExceptionStatus.PaidOver;
context.MarkDirty();
}
if (accounting.Paid < accounting.MinimumTotalDue)
{
invoice.Status = InvoiceStatusLegacy.New;
invoice.ExceptionStatus = accounting.Paid == Money.Zero ? InvoiceExceptionStatus.None : InvoiceExceptionStatus.PaidPartial;
context.MarkDirty();
}
}
if (invoice.Status == InvoiceStatusLegacy.Paid)
{
var confirmedAccounting =
paymentMethod?.Calculate(p => p.GetCryptoPaymentData().PaymentConfirmed(p, invoice.SpeedPolicy)) ??
accounting;
if (// Is after the monitoring deadline
(invoice.MonitoringExpiration < DateTimeOffset.UtcNow)
&&
// And not enough amount confirmed
(confirmedAccounting.Paid < accounting.MinimumTotalDue))
{
context.UnaffectAddresses();
context.Events.Add(new InvoiceEvent(invoice, InvoiceEvent.FailedToConfirm));
invoice.Status = InvoiceStatusLegacy.Invalid;
context.MarkDirty();
}
else if (confirmedAccounting.Paid >= accounting.MinimumTotalDue)
{
context.UnaffectAddresses();
invoice.Status = InvoiceStatusLegacy.Confirmed;
context.Events.Add(new InvoiceEvent(invoice, InvoiceEvent.Confirmed));
context.MarkDirty();
}
}
if (invoice.Status == InvoiceStatusLegacy.Confirmed)
{
var completedAccounting = paymentMethod?.Calculate(p => p.GetCryptoPaymentData().PaymentCompleted(p)) ??
accounting;
if (completedAccounting.Paid >= accounting.MinimumTotalDue)
{
context.Events.Add(new InvoiceEvent(invoice, InvoiceEvent.Completed));
invoice.Status = InvoiceStatusLegacy.Complete;
context.MarkDirty();
}
}
}
public static PaymentMethod GetNearestClearedPayment(PaymentMethodDictionary allPaymentMethods, out PaymentMethodAccounting accounting)
{
PaymentMethod result = null;
accounting = null;
decimal nearestToZero = 0.0m;
foreach (var paymentMethod in allPaymentMethods)
{
var currentAccounting = paymentMethod.Calculate();
var distanceFromZero = Math.Abs(currentAccounting.DueUncapped.ToDecimal(MoneyUnit.BTC));
if (result == null || distanceFromZero < nearestToZero)
{
result = paymentMethod;
nearestToZero = distanceFromZero;
accounting = currentAccounting;
}
}
return result;
}
private void Watch(string invoiceId)
{
ArgumentNullException.ThrowIfNull(invoiceId);
if (!_WatchRequests.Writer.TryWrite(invoiceId))
{
Logs.PayServer.LogWarning($"Failed to write invoice {invoiceId} into WatchRequests channel");
}
}
private async Task Wait(string invoiceId)
{
var invoice = await _invoiceRepository.GetInvoice(invoiceId);
try
{
// add 1 second to ensure watch won't trigger moments before invoice expires
var delay = invoice.ExpirationTime.AddSeconds(1) - DateTimeOffset.UtcNow;
if (delay > TimeSpan.Zero)
{
await Task.Delay(delay, _Cts.Token);
}
Watch(invoiceId);
// add 1 second to ensure watch won't trigger moments before monitoring expires
delay = invoice.MonitoringExpiration.AddSeconds(1) - DateTimeOffset.UtcNow;
if (delay > TimeSpan.Zero)
{
await Task.Delay(delay, _Cts.Token);
}
Watch(invoiceId);
}
catch when (_Cts.IsCancellationRequested)
{ }
}
readonly Channel<string> _WatchRequests = Channel.CreateUnbounded<string>();
Task _Loop;
CancellationTokenSource _Cts;
public Task StartAsync(CancellationToken cancellationToken)
{
_Cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
_Loop = StartLoop(_Cts.Token);
_ = WaitPendingInvoices();
leases.Add(_eventAggregator.Subscribe<Events.InvoiceNeedUpdateEvent>(b =>
{
Watch(b.InvoiceId);
}));
leases.Add(_eventAggregator.SubscribeAsync<Events.InvoiceEvent>(async b =>
{
if (InvoiceEventNotification.HandlesEvent(b.Name))
{
await _notificationSender.SendNotification(new StoreScope(b.Invoice.StoreId),
new InvoiceEventNotification(b.Invoice.Id, b.Name));
}
if (b.Name == InvoiceEvent.Created)
{
Watch(b.Invoice.Id);
_ = Wait(b.Invoice.Id);
}
if (b.Name == InvoiceEvent.ReceivedPayment)
{
Watch(b.Invoice.Id);
}
}));
return Task.CompletedTask;
}
private async Task WaitPendingInvoices()
{
await Task.WhenAll((await _invoiceRepository.GetPendingInvoices())
.Select(id => Wait(id)).ToArray());
}
async Task StartLoop(CancellationToken cancellation)
{
Logs.PayServer.LogInformation("Start watching invoices");
while (await _WatchRequests.Reader.WaitToReadAsync(cancellation) && _WatchRequests.Reader.TryRead(out var invoiceId))
{
int maxLoop = 5;
int loopCount = -1;
while (loopCount < maxLoop)
{
loopCount++;
try
{
cancellation.ThrowIfCancellationRequested();
var invoice = await _invoiceRepository.GetInvoice(invoiceId, true);
if (invoice == null)
break;
var updateContext = new UpdateInvoiceContext(invoice);
UpdateInvoice(updateContext);
if (updateContext.Unaffect)
{
await _invoiceRepository.UnaffectAddress(invoice.Id);
}
if (updateContext.Dirty)
{
await _invoiceRepository.UpdateInvoiceStatus(invoice.Id, invoice.GetInvoiceState());
updateContext.Events.Insert(0, new InvoiceDataChangedEvent(invoice));
}
if (updateContext.IsBlobUpdated)
{
await _invoiceRepository.UpdateInvoicePrice(invoice.Id, invoice);
}
foreach (var evt in updateContext.Events)
{
_eventAggregator.Publish(evt, evt.GetType());
}
if (invoice.Status == InvoiceStatusLegacy.Complete ||
((invoice.Status == InvoiceStatusLegacy.Invalid || invoice.Status == InvoiceStatusLegacy.Expired) && invoice.MonitoringExpiration < DateTimeOffset.UtcNow))
{
var extendInvoiceMonitoring = await UpdateConfirmationCount(invoice);
// we extend monitor time if we haven't reached max confirmation count
// say user used low fee and we only got 3 confirmations right before it's time to remove
if (extendInvoiceMonitoring)
{
await _invoiceRepository.ExtendInvoiceMonitor(invoice.Id);
}
else if (await _invoiceRepository.RemovePendingInvoice(invoice.Id))
{
_eventAggregator.Publish(new InvoiceStopWatchedEvent(invoice.Id));
}
break;
}
if (updateContext.Events.Count == 0)
break;
}
catch (Exception ex) when (!cancellation.IsCancellationRequested)
{
Logs.PayServer.LogError(ex, "Unhandled error on watching invoice " + invoiceId);
_ = Task.Delay(10000, cancellation)
.ContinueWith(t => Watch(invoiceId), TaskScheduler.Default);
break;
}
}
}
}
private async Task<bool> UpdateConfirmationCount(InvoiceEntity invoice)
{
bool extendInvoiceMonitoring = false;
var updateConfirmationCountIfNeeded = invoice
.GetPayments(false)
.Select<PaymentEntity, Task<PaymentEntity>>(async payment =>
{
var paymentData = payment.GetCryptoPaymentData();
if (paymentData is Payments.Bitcoin.BitcoinLikePaymentData onChainPaymentData)
{
var network = payment.Network as BTCPayNetwork;
// Do update if confirmation count in the paymentData is not up to date
if ((onChainPaymentData.ConfirmationCount < network.MaxTrackedConfirmation && payment.Accounted)
&& (onChainPaymentData.Legacy || invoice.MonitoringExpiration < DateTimeOffset.UtcNow))
{
var transactionResult = await _explorerClientProvider.GetExplorerClient(payment.GetCryptoCode())?.GetTransactionAsync(onChainPaymentData.Outpoint.Hash);
var confirmationCount = transactionResult?.Confirmations ?? 0;
onChainPaymentData.ConfirmationCount = confirmationCount;
payment.SetCryptoPaymentData(onChainPaymentData);
// we want to extend invoice monitoring until we reach max confirmations on all onchain payment methods
if (confirmationCount < network.MaxTrackedConfirmation)
extendInvoiceMonitoring = true;
return payment;
}
}
return null;
})
.ToArray();
await Task.WhenAll(updateConfirmationCountIfNeeded);
var updatedPaymentData = updateConfirmationCountIfNeeded.Where(a => a.Result != null).Select(a => a.Result).ToList();
if (updatedPaymentData.Count > 0)
{
await _paymentService.UpdatePayments(updatedPaymentData);
}
return extendInvoiceMonitoring;
}
public async Task StopAsync(CancellationToken cancellationToken)
{
if (_Cts == null)
return;
leases.Dispose();
_Cts.Cancel();
try
{
await _Loop;
}
catch { }
finally
{
Logs.PayServer.LogInformation("Stop watching invoices");
}
}
}
}
| |
// Copyright 2015 Stig Schmidt Nielsson. All rights reserved.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
namespace Ssn.Utils.PasswordHashing {
/// <summary>
/// BCrypt implements OpenBSD-style Blowfish password hashing
/// using the scheme described in "A Future-Adaptable Password Scheme"
/// by Niels Provos and David Mazieres.
/// </summary>
/// <remarks>
/// <para>
/// This password hashing system tries to thwart offline
/// password cracking using a computationally-intensive hashing
/// algorithm, based on Bruce Schneier's Blowfish cipher. The work
/// factor of the algorithm is parameterized, so it can be increased as
/// computers get faster.
/// </para>
/// <para>
/// To hash a password for the first time, call the
/// <c>HashPassword</c> method with a random salt, like this:
/// </para>
/// <code>
/// string hashed = BCrypt.HashPassword(plainPassword, BCrypt.GenerateSalt());
/// </code>
/// <para>
/// To check whether a plaintext password matches one that has
/// been hashed previously, use the <c>CheckPassword</c> method:
/// </para>
/// <code>
/// if (BCrypt.CheckPassword(candidatePassword, storedHash)) {
/// Console.WriteLine("It matches");
/// } else {
/// Console.WriteLine("It does not match");
/// }
/// </code>
/// <para>
/// The <c>GenerateSalt</c> method takes an optional parameter
/// (logRounds) that determines the computational complexity of the
/// hashing:
/// </para>
/// <code>
/// string strongSalt = BCrypt.GenerateSalt(10);
/// string strongerSalt = BCrypt.GenerateSalt(12);
/// </code>
/// <para>
/// The amount of work increases exponentially (2**log_rounds), so
/// each increment is twice as much work. The default log_rounds is
/// 10, and the valid range is 4 to 31.
/// </para>
/// </remarks>
public class BCrypt {
private const int GENSALT_DEFAULT_LOG2_ROUNDS = 10;
private const int BCRYPT_SALT_LEN = 16;
// Blowfish parameters.
private const int BLOWFISH_NUM_ROUNDS = 16;
// Initial contents of key schedule.
private static readonly uint[] p_orig = {
0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,
0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
0x9216d5d9, 0x8979fb1b
};
private static readonly uint[] s_orig = {
0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,
0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,
0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,
0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce,
0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,
0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88,
0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,
0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88,
0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,
0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba,
0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,
0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,
0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,
0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0,
0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,
0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7,
0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,
0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477,
0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,
0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41,
0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,
0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,
0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6,
0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e,
0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,
0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701,
0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf,
0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e,
0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,
0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b,
0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f,
0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4,
0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,
0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510,
0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,
0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8,
0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128,
0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0,
0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,
0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00,
0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735,
0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9,
0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934,
0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45,
0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,
0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42,
0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2,
0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,
0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,
0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b,
0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922,
0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,
0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804,
0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,
0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,
0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,
0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f,
0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,
0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,
0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52,
0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5,
0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,
0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4,
0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b,
0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8,
0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,
0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9,
0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,
0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b,
0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,
0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,
0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,
0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae,
0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,
0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,
0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,
0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38,
0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,
0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964,
0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,
0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,
0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,
0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0,
0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,
0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
};
// bcrypt IV: "OrpheanBeholderScryDoubt".
private static readonly uint[] bf_crypt_ciphertext = {
0x4f727068, 0x65616e42, 0x65686f6c,
0x64657253, 0x63727944, 0x6f756274
};
// Table for Base64 encoding.
private static readonly char[] base64_code = {
'.', '/', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9'
};
// Table for Base64 decoding.
private static readonly int[] index_64 = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, 0, 1, 54, 55,
56, 57, 58, 59, 60, 61, 62, 63, -1, -1,
-1, -1, -1, -1, -1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
-1, -1, -1, -1, -1, -1, 28, 29, 30,
31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
51, 52, 53, -1, -1, -1, -1, -1
};
// Expanded Blowfish key.
private uint[] p;
private uint[] s;
/// <summary>
/// Encode a byte array using bcrypt's slightly-modified
/// Base64 encoding scheme. Note that this is _not_ compatible
/// with the standard MIME-Base64 encoding.
/// </summary>
/// <param name="d">The byte array to encode</param>
/// <param name="length">The number of bytes to encode</param>
/// <returns>A Base64-encoded string</returns>
private static string EncodeBase64(byte[] d, int length) {
if (length <= 0 || length > d.Length) throw new ArgumentOutOfRangeException("length", length, null);
var rs = new StringBuilder(length*2);
for (int offset = 0, c1, c2; offset < length;) {
c1 = d[offset++] & 0xff;
rs.Append(base64_code[(c1 >> 2) & 0x3f]);
c1 = (c1 & 0x03) << 4;
if (offset >= length) {
rs.Append(base64_code[c1 & 0x3f]);
break;
}
c2 = d[offset++] & 0xff;
c1 |= (c2 >> 4) & 0x0f;
rs.Append(base64_code[c1 & 0x3f]);
c1 = (c2 & 0x0f) << 2;
if (offset >= length) {
rs.Append(base64_code[c1 & 0x3f]);
break;
}
c2 = d[offset++] & 0xff;
c1 |= (c2 >> 6) & 0x03;
rs.Append(base64_code[c1 & 0x3f]);
rs.Append(base64_code[c2 & 0x3f]);
}
return rs.ToString();
}
/// <summary>
/// Look up the 3 bits base64-encoded by the specified
/// character, range-checking against the conversion
/// table.
/// </summary>
/// <param name="c">The Base64-encoded value</param>
/// <returns>
/// The decoded value of <c>x</c>
/// </returns>
private static int Char64(char c) {
int i = c;
return (i < 0 || i > index_64.Length) ? -1 : index_64[i];
}
/// <summary>
/// Decode a string encoded using BCrypt's Base64 scheme to a
/// byte array. Note that this is _not_ compatible with the standard
/// MIME-Base64 encoding.
/// </summary>
/// <param name="s">The string to decode</param>
/// <param name="maximumLength">The maximum number of bytes to decode</param>
/// <returns>An array containing the decoded bytes</returns>
private static byte[] DecodeBase64(string s, int maximumLength) {
var bytes = new List<byte>(Math.Min(maximumLength, s.Length));
if (maximumLength <= 0) throw new ArgumentOutOfRangeException("maximumLength", maximumLength, null);
for (int offset = 0, slen = s.Length, length = 0; offset < slen - 1 && length < maximumLength;) {
int c1 = Char64(s[offset++]);
int c2 = Char64(s[offset++]);
if (c1 == -1 || c2 == -1) break;
bytes.Add((byte) ((c1 << 2) | ((c2 & 0x30) >> 4)));
if (++length >= maximumLength || offset >= s.Length) break;
int c3 = Char64(s[offset++]);
if (c3 == -1) break;
bytes.Add((byte) (((c2 & 0x0f) << 4) | ((c3 & 0x3c) >> 2)));
if (++length >= maximumLength || offset >= s.Length) break;
int c4 = Char64(s[offset++]);
bytes.Add((byte) (((c3 & 0x03) << 6) | c4));
++length;
}
return bytes.ToArray();
}
/// <summary>
/// Blowfish encipher a single 64-bit block encoded as two 32-bit
/// halves.
/// </summary>
/// <param name="block">
/// An array containing the two 32-bit half
/// blocks.
/// </param>
/// <param name="offset">
/// The position in the array of the
/// blocks.
/// </param>
private void Encipher(uint[] block, int offset) {
uint i, n, l = block[offset], r = block[offset + 1];
l ^= p[0];
for (i = 0; i <= BLOWFISH_NUM_ROUNDS - 2;) {
// Feistel substitution on left word
n = s[(l >> 24) & 0xff];
n += s[0x100 | ((l >> 16) & 0xff)];
n ^= s[0x200 | ((l >> 8) & 0xff)];
n += s[0x300 | (l & 0xff)];
r ^= n ^ p[++i];
// Feistel substitution on right word
n = s[(r >> 24) & 0xff];
n += s[0x100 | ((r >> 16) & 0xff)];
n ^= s[0x200 | ((r >> 8) & 0xff)];
n += s[0x300 | (r & 0xff)];
l ^= n ^ p[++i];
}
block[offset] = r ^ p[BLOWFISH_NUM_ROUNDS + 1];
block[offset + 1] = l;
}
/// <summary>
/// Cycically extract a word of key material.
/// </summary>
/// <param name="data">
/// The string to extract the data
/// from.
/// </param>
/// <param name="offset">The current offset into data.</param>
/// <returns>The next work of material from data.</returns>
private static uint StreamToWord(byte[] data, ref int offset) {
uint word = 0;
for (int i = 0; i < 4; i++) {
word = (word << 8) | data[offset];
offset = (offset + 1)%data.Length;
}
return word;
}
/// <summary>
/// Initialize the Blowfish key schedule.
/// </summary>
private void InitKey() {
p = new uint[p_orig.Length];
p_orig.CopyTo(p, 0);
s = new uint[s_orig.Length];
s_orig.CopyTo(s, 0);
}
/// <summary>
/// Key the Blowfish cipher.
/// </summary>
/// <param name="key">An array containing the key.</param>
private void Key(byte[] key) {
uint[] lr = {0, 0};
int plen = p.Length, slen = s.Length;
int offset = 0;
for (int i = 0; i < plen; i++) {
p[i] = p[i] ^ StreamToWord(key, ref offset);
}
for (int i = 0; i < plen; i += 2) {
Encipher(lr, 0);
p[i] = lr[0];
p[i + 1] = lr[1];
}
for (int i = 0; i < slen; i += 2) {
Encipher(lr, 0);
s[i] = lr[0];
s[i + 1] = lr[1];
}
}
/// <summary>
/// Perform the "enhanced key schedule" step described by Provos
/// and Mazieres in "A Future-Adaptable Password Scheme"
/// (http://www.openbsd.org/papers/bcrypt-paper.ps).
/// </summary>
/// <param name="data">Salt information.</param>
/// <param name="key">Password information.</param>
private void EksKey(byte[] data, byte[] key) {
uint[] lr = {0, 0};
int plen = p.Length, slen = s.Length;
int keyOffset = 0;
for (int i = 0; i < plen; i++) {
p[i] = p[i] ^ StreamToWord(key, ref keyOffset);
}
int dataOffset = 0;
for (int i = 0; i < plen; i += 2) {
lr[0] ^= StreamToWord(data, ref dataOffset);
lr[1] ^= StreamToWord(data, ref dataOffset);
Encipher(lr, 0);
p[i] = lr[0];
p[i + 1] = lr[1];
}
for (int i = 0; i < slen; i += 2) {
lr[0] ^= StreamToWord(data, ref dataOffset);
lr[1] ^= StreamToWord(data, ref dataOffset);
Encipher(lr, 0);
s[i] = lr[0];
s[i + 1] = lr[1];
}
}
/// <summary>
/// Perform the central password hashing step in the bcrypt
/// scheme.
/// </summary>
/// <param name="password">The password to hash.</param>
/// <param name="salt">
/// The binary salt to hash with the
/// password.
/// </param>
/// <param name="logRounds">
/// The binary logarithm of the number of
/// rounds of hashing to apply.
/// </param>
/// <returns>An array containing the binary hashed password.</returns>
private byte[] CryptRaw(byte[] password, byte[] salt, int logRounds) {
var cdata = new uint[bf_crypt_ciphertext.Length];
bf_crypt_ciphertext.CopyTo(cdata, 0);
int clen = cdata.Length;
byte[] ret;
if (logRounds < 4 || logRounds > 31) throw new ArgumentOutOfRangeException("logRounds", logRounds, null);
int rounds = 1 << logRounds;
if (salt.Length != BCRYPT_SALT_LEN) throw new ArgumentException("Invalid salt length.", "salt");
InitKey();
EksKey(salt, password);
for (int i = 0; i < rounds; i++) {
Key(password);
Key(salt);
}
for (int i = 0; i < 64; i++) {
for (int j = 0; j < (clen >> 1); j++) {
Encipher(cdata, j << 1);
}
}
ret = new byte[clen*4];
for (int i = 0, j = 0; i < clen; i++) {
ret[j++] = (byte) ((cdata[i] >> 24) & 0xff);
ret[j++] = (byte) ((cdata[i] >> 16) & 0xff);
ret[j++] = (byte) ((cdata[i] >> 8) & 0xff);
ret[j++] = (byte) (cdata[i] & 0xff);
}
return ret;
}
/// <summary>
/// Hash a password using the OpenBSD bcrypt scheme.
/// </summary>
/// <param name="password">The password to hash.</param>
/// <param name="salt">
/// The salt to hash with (perhaps generated
/// using <c>BCrypt.GenerateSalt</c>).
/// </param>
/// <returns>The hashed password.</returns>
public static string HashPassword(string password, string salt) {
if (password == null) throw new ArgumentNullException("password");
if (salt == null) throw new ArgumentNullException("salt");
var minor = (char) 0;
if (salt[0] != '$' || salt[1] != '2') throw new ArgumentException("Invalid salt version");
int offset;
if (salt[2] == '$') offset = 3;
else {
minor = salt[2];
if (minor != 'a' || salt[3] != '$') throw new ArgumentException("Invalid salt revision");
offset = 4;
}
// Extract number of rounds
if (salt[offset + 2] > '$') throw new ArgumentException("Missing salt rounds");
int rounds = Int32.Parse(salt.Substring(offset, 2), NumberFormatInfo.InvariantInfo);
byte[] passwordBytes = Encoding.UTF8.GetBytes(password + (minor >= 'a' ? "\0" : String.Empty));
byte[] saltBytes = DecodeBase64(salt.Substring(offset + 3, 22),
BCRYPT_SALT_LEN);
var bcrypt = new BCrypt();
byte[] hashed = bcrypt.CryptRaw(passwordBytes, saltBytes, rounds);
var rs = new StringBuilder();
rs.Append("$2");
if (minor >= 'a') rs.Append(minor);
rs.Append('$');
if (rounds < 10) rs.Append('0');
rs.Append(rounds);
rs.Append('$');
rs.Append(EncodeBase64(saltBytes, saltBytes.Length));
rs.Append(EncodeBase64(hashed,
(bf_crypt_ciphertext.Length*4) - 1));
return rs.ToString();
}
/// <summary>
/// Generate a salt for use with the BCrypt.HashPassword() method.
/// </summary>
/// <param name="logRounds">
/// The log2 of the number of rounds of
/// hashing to apply. The work factor therefore increases as (2 **
/// logRounds).
/// </param>
/// <param name="random">An instance of RandomNumberGenerator to use.</param>
/// <returns>An encoded salt value.</returns>
public static string GenerateSalt(int logRounds, RandomNumberGenerator random) {
var randomBytes = new byte[BCRYPT_SALT_LEN];
random.GetBytes(randomBytes);
var rs = new StringBuilder((randomBytes.Length*2) + 8);
rs.Append("$2a$");
if (logRounds < 10) rs.Append('0');
rs.Append(logRounds);
rs.Append('$');
rs.Append(EncodeBase64(randomBytes, randomBytes.Length));
return rs.ToString();
}
/// <summary>
/// Generate a salt for use with the <c>BCrypt.HashPassword()</c> method.
/// </summary>
/// <param name="logRounds">
/// The log2 of the number of rounds of
/// hashing to apply. The work factor therefore increases as (2 **
/// logRounds).
/// </param>
/// <returns>An encoded salt value.</returns>
public static string GenerateSalt(int logRounds) {
return GenerateSalt(logRounds, RandomNumberGenerator.Create());
}
/// <summary>
/// Generate a salt for use with the <c>BCrypt.HashPassword()</c>
/// method, selecting a reasonable default for the number of hashing
/// rounds to apply.
/// </summary>
/// <returns>An encoded salt value.</returns>
public static string GenerateSalt() {
return GenerateSalt(GENSALT_DEFAULT_LOG2_ROUNDS);
}
/// <summary>
/// Check that a plaintext password matches a previously hashed
/// one.
/// </summary>
/// <param name="plaintext">The plaintext password to verify.</param>
/// <param name="hashed">The previously hashed password.</param>
/// <returns>
/// <c>true</c> if the passwords, <c>false</c>
/// otherwise.
/// </returns>
public static bool CheckPassword(string plaintext, string hashed) {
return StringComparer.Ordinal.Compare(hashed, HashPassword(plaintext, hashed)) == 0;
}
}
}
| |
/*
Copyright (c) 2009, hkrn 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 hkrn 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 REGENTS 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.
*/
//
// $Id: FlMMLStyleParser.cs 116 2009-05-23 14:39:36Z hikarin $
//
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace SlMML.Parsers
{
class FlMMLStyleParser : Parser, IParsable
{
struct MacroArgument
{
public string Name;
public int Index;
}
struct MacroValue
{
public StringBuilder Code;
public List<MacroArgument> Arguments;
}
#region nonpublic class methods
private static void GetArgumentFromKey(string key, out List<MacroArgument> arguments)
{
arguments = new List<MacroArgument>();
int start = key.IndexOf('{');
int end = key.IndexOf('}') - start - 1;
if (start >= 0 && end > 0)
{
string[] args = key.Substring(start + 1, end).Split(',');
int i = 0;
foreach (string arg in args)
{
string name = arg;
if (ValidateMacroName(ref name))
{
arguments.Add(new MacroArgument { Name = name, Index = i });
i++;
}
}
arguments.Sort((x, y) =>
{
int xl = x.Name.Length, yl = y.Name.Length;
if (xl > yl)
return -1;
else if (xl == yl)
return 0;
else
return 1;
});
}
}
private static void SortMacros(ref Dictionary<string, MacroValue> macros)
{
List<KeyValuePair<string, MacroValue>> pairs = new List<KeyValuePair<string, MacroValue>>(macros);
pairs.Sort((x, y) =>
{
int xl = x.Key.Length, yl = y.Key.Length;
if (xl > yl)
return -1;
else if (xl == yl)
return 0;
else
return 1;
});
macros.Clear();
foreach (KeyValuePair<string, MacroValue> pair in pairs)
macros[pair.Key] = pair.Value;
}
private static bool ValidateMacroName(ref string name)
{
char f = name[0];
StringBuilder s = new StringBuilder();
if (!char.IsLetter(f) && f != '_' && f != '#' && f != '+' && f != '(' && f != ')')
return false;
foreach (char c in name)
{
if (char.IsLetterOrDigit(c) || c == '_' || c == '#' || c == '+' || c == '(' || c == ')')
s.Append(c);
else
break;
}
name = s.ToString();
return true;
}
#endregion
#region public methods
public Sequencer Parse(string stringToParse)
{
ParseBefore(stringToParse);
ParseComment();
ParseMacro();
RemoveSpaces(ref m_text);
ToLower(ref m_text);
ParseRepeat();
m_index = 0;
int length = m_text.Length;
while (m_index < length)
FirstLetterToken();
return ParseAfter();
}
#endregion
#region nonpublic methods
private void ParseComment()
{
int start = -1, textLength = m_text.Length;
m_index = 0;
while (m_index < textLength)
{
char c = CharacterTokenAndNext();
switch (c)
{
case '/':
if (CharacterToken() == '*')
{
if (start < 0)
start = m_index - 1;
NextToken();
}
break;
case '*':
if (CharacterToken() == '/')
{
if (start >= 0)
{
m_text.Remove(start, m_index + 1 - start);
m_index = start;
textLength = m_text.Length;
start = -1;
}
else
m_warnings.Add(CompilerWarning.UnOpenedComment);
}
break;
default:
break;
}
}
if (start >= 0)
m_warnings.Add(CompilerWarning.UnClosedComment);
}
private bool ReplaceMacro(Dictionary<string, MacroValue> macros)
{
foreach (KeyValuePair<string, MacroValue> macro in macros)
{
string key = macro.Key;
int keyLength = key.Length;
if (m_text.ToString().Substring(m_index, keyLength).Equals(key))
{
int start = m_index, last = start + keyLength;
string code = macro.Value.Code.ToString();
m_index += keyLength;
char c = CharacterToken();
while (char.IsWhiteSpace(c))
c = CharacterTokenAndNext();
string[] args = new string[0];
if (c == '{')
{
c = CharacterTokenAndNext();
while (c != '}' && c != char.MinValue)
{
if (c == '$')
ReplaceMacro(macros);
c = CharacterTokenAndNext();
}
last = m_index;
int from = start + keyLength + 1, length = last - 1 - from;
args = m_text.ToString().Substring(from, length).Split(',');
}
List<MacroArgument> arguments = macro.Value.Arguments;
int codeLength = code.Length, argsLength = args.Length;
int macroArgumentCount = arguments.Count;
for (int i = 0; i < codeLength; i++)
{
for (int j = 0; j < argsLength; j++)
{
if (j >= macroArgumentCount)
break;
string argumentKey = arguments[j].Name, subs = "%" + argumentKey;
int subsLength = subs.Length, index = arguments[j].Index;
if (codeLength >= i + subsLength && code.Substring(i, subsLength).Equals(subs))
{
code = code.Substring(0, i) + code.Substring(i).Replace(subs, args[index]);
codeLength = code.Length;
i += args[arguments[j].Index].Length - 1;
break;
}
}
}
string chunk = m_text.ToString();
m_text = new StringBuilder(chunk.Substring(0, start - 1) + code + chunk.Substring(last));
m_index = start - 1;
return true;
}
}
return false;
}
private void ParseMacro()
{
StringBuilder s = new StringBuilder();
using (StringReader reader = new StringReader(m_text.ToString()))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (line.StartsWith("#OCTAVE"))
{
if (line.Substring(7).TrimStart().StartsWith("REVERSE"))
m_relativeDir = false;
}
else if (line.StartsWith("#WAV9"))
{
string[] wave = line.Substring(5).TrimStart().Split(",".ToCharArray());
if (wave.Length == 4)
{
int waveIndex = 0, intVol = 0, loopFlag = 0;
int.TryParse(wave[0], out waveIndex);
int.TryParse(wave[1], out intVol);
int.TryParse(wave[2], out loopFlag);
Modulators.FCDPCM.SetWave(waveIndex, intVol, loopFlag, wave[3]);
}
}
else if (line.StartsWith("#WAV10"))
{
int waveNo = 0;
string[] wave = line.Substring(6).TrimStart().Split(",".ToCharArray());
if (wave.Length == 2 && int.TryParse(wave[0], out waveNo))
{
string waveString = wave[1] + "00000000000000000000000000000000";
Modulators.GBWave.SetWaveString(waveString, waveNo);
}
}
else
{
s.Append(line);
s.Append("\n");
}
}
}
m_text = s;
m_index = 0;
bool top = true;
int last = 0, textLength = m_text.Length;
Dictionary<string, MacroValue> macros = new Dictionary<string, MacroValue>();
while (m_index < textLength)
{
char c = CharacterTokenAndNext();
switch (c)
{
case '$':
if (top)
{
string chunk = m_text.ToString();
last = chunk.IndexOf(';', m_index, m_text.Length - m_index);
if (last >= 0 && last > m_index)
{
string macro = chunk.Substring(m_index, last - m_index);
string[] kv = macro.Split('=');
if (kv.Length == 2 && kv[0].Length > 0)
{
int macroStartAt = m_index;
int keyEndAt = m_text.ToString().IndexOf('=');
string key = kv[0], name = key;
if (ValidateMacroName(ref name))
{
int keyLength = key.Length;
List<MacroArgument> arguments;
GetArgumentFromKey(key, out arguments);
m_index = keyEndAt + 1;
c = CharacterTokenAndNext();
while (m_index < last)
{
if (c == '$')
{
if (!ReplaceMacro(macros))
{
if (m_text.ToString().Substring(m_index, keyLength).Equals(key))
{
m_index--;
m_text.Remove(m_index, key.Length);
m_warnings.Add(CompilerWarning.RecursiveMacro);
}
}
last = m_text.ToString().IndexOf(';', m_index);
}
c = CharacterTokenAndNext();
}
int codeLength = last - keyEndAt - 1;
MacroValue value = new MacroValue()
{
Code = new StringBuilder(m_text.ToString().Substring(keyEndAt + 1, codeLength)),
Arguments = arguments
};
macros[name] = value;
SortMacros(ref macros);
int from = macroStartAt - 1, to = last - from;
m_text.Remove(from, to);
m_index = macroStartAt - 1;
textLength = m_text.Length;
}
}
else
{
ReplaceMacro(macros);
textLength = m_text.Length;
top = false;
}
}
else
{
ReplaceMacro(macros);
textLength = m_text.Length;
top = false;
}
}
else
{
ReplaceMacro(macros);
textLength = m_text.Length;
top = false;
}
break;
case ';':
top = true;
break;
default:
if (!char.IsWhiteSpace(c))
top = false;
break;
}
}
}
private void ParseRepeat()
{
List<int> repeats = new List<int>();
List<int> origins = new List<int>();
List<int> starts = new List<int>();
List<int> lasts = new List<int>();
int nest = -1, textLength = m_text.Length;
m_index = 0;
while (m_index < textLength)
{
char c = CharacterTokenAndNext();
switch (c)
{
case '/':
if (CharacterToken() == ':')
{
NextToken();
++nest;
origins.Add(m_index - 2);
repeats.Add((int)UIntToken(2));
starts.Add(m_index);
lasts.Add(-1);
}
else if (nest >= 0)
{
lasts[nest] = m_index - 1;
m_text.Remove(m_index - 1, 1);
textLength = m_text.Length;
--m_index;
}
break;
case ':':
if (CharacterToken() == '/' && nest >= 0)
{
NextToken();
int start = starts[nest];
int last = lasts[nest];
int repeat = repeats[nest];
string chunk = m_text.ToString();
string contents = chunk.Substring(start, m_index - 2 - start);
StringBuilder newString = new StringBuilder(chunk.Substring(0, origins[nest]));
for (int i = 0; i < repeat; i++)
if (i < repeat - 1 || last < 0)
newString.Append(contents);
else
newString.Append(m_text.ToString().Substring(start, last - start));
int newStringLength = newString.Length;
newString.Append(m_text.ToString().Substring(m_index));
m_text = newString;
m_index = newStringLength;
textLength = newString.Length;
origins.RemoveAt(nest);
repeats.RemoveAt(nest);
starts.RemoveAt(nest);
lasts.RemoveAt(nest);
--nest;
}
break;
default:
break;
}
}
if (nest >= 0)
m_warnings.Add(CompilerWarning.UnClosedRepeat);
}
#endregion
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management;
using Microsoft.WindowsAzure.Management.Models;
namespace Microsoft.WindowsAzure.Management
{
/// <summary>
/// You can use management certificates, which are also known as
/// subscription certificates, to authenticate clients attempting to
/// connect to resources associated with your Azure subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj154124.aspx for
/// more information)
/// </summary>
internal partial class ManagementCertificateOperations : IServiceOperations<ManagementClient>, IManagementCertificateOperations
{
/// <summary>
/// Initializes a new instance of the ManagementCertificateOperations
/// class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ManagementCertificateOperations(ManagementClient client)
{
this._client = client;
}
private ManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.ManagementClient.
/// </summary>
public ManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// The Create Management Certificate operation adds a certificate to
/// the list of management certificates. Management certificates,
/// which are also known as subscription certificates, authenticate
/// clients attempting to connect to resources associated with your
/// Azure subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj154123.aspx
/// for more information)
/// </summary>
/// <param name='parameters'>
/// Required. Parameters supplied to the Create Management Certificate
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> CreateAsync(ManagementCertificateCreateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/certificates";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement subscriptionCertificateElement = new XElement(XName.Get("SubscriptionCertificate", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(subscriptionCertificateElement);
if (parameters.PublicKey != null)
{
XElement subscriptionCertificatePublicKeyElement = new XElement(XName.Get("SubscriptionCertificatePublicKey", "http://schemas.microsoft.com/windowsazure"));
subscriptionCertificatePublicKeyElement.Value = Convert.ToBase64String(parameters.PublicKey);
subscriptionCertificateElement.Add(subscriptionCertificatePublicKeyElement);
}
if (parameters.Thumbprint != null)
{
XElement subscriptionCertificateThumbprintElement = new XElement(XName.Get("SubscriptionCertificateThumbprint", "http://schemas.microsoft.com/windowsazure"));
subscriptionCertificateThumbprintElement.Value = parameters.Thumbprint;
subscriptionCertificateElement.Add(subscriptionCertificateThumbprintElement);
}
if (parameters.Data != null)
{
XElement subscriptionCertificateDataElement = new XElement(XName.Get("SubscriptionCertificateData", "http://schemas.microsoft.com/windowsazure"));
subscriptionCertificateDataElement.Value = Convert.ToBase64String(parameters.Data);
subscriptionCertificateElement.Add(subscriptionCertificateDataElement);
}
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Delete Management Certificate operation deletes a certificate
/// from the list of management certificates. Management certificates,
/// which are also known as subscription certificates, authenticate
/// clients attempting to connect to resources associated with your
/// Azure subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj154127.aspx
/// for more information)
/// </summary>
/// <param name='thumbprint'>
/// Required. The thumbprint value of the certificate to delete.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string thumbprint, CancellationToken cancellationToken)
{
// Validate
if (thumbprint == null)
{
throw new ArgumentNullException("thumbprint");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("thumbprint", thumbprint);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/certificates/";
url = url + Uri.EscapeDataString(thumbprint);
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NotFound)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Get Management Certificate operation retrieves information
/// about the management certificate with the specified thumbprint.
/// Management certificates, which are also known as subscription
/// certificates, authenticate clients attempting to connect to
/// resources associated with your Azure subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj154131.aspx
/// for more information)
/// </summary>
/// <param name='thumbprint'>
/// Required. The thumbprint value of the certificate to retrieve
/// information about.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Get Management Certificate operation response.
/// </returns>
public async Task<ManagementCertificateGetResponse> GetAsync(string thumbprint, CancellationToken cancellationToken)
{
// Validate
if (thumbprint == null)
{
throw new ArgumentNullException("thumbprint");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("thumbprint", thumbprint);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/certificates/";
url = url + Uri.EscapeDataString(thumbprint);
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ManagementCertificateGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ManagementCertificateGetResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement subscriptionCertificateElement = responseDoc.Element(XName.Get("SubscriptionCertificate", "http://schemas.microsoft.com/windowsazure"));
if (subscriptionCertificateElement != null)
{
XElement subscriptionCertificatePublicKeyElement = subscriptionCertificateElement.Element(XName.Get("SubscriptionCertificatePublicKey", "http://schemas.microsoft.com/windowsazure"));
if (subscriptionCertificatePublicKeyElement != null)
{
byte[] subscriptionCertificatePublicKeyInstance = Convert.FromBase64String(subscriptionCertificatePublicKeyElement.Value);
result.PublicKey = subscriptionCertificatePublicKeyInstance;
}
XElement subscriptionCertificateThumbprintElement = subscriptionCertificateElement.Element(XName.Get("SubscriptionCertificateThumbprint", "http://schemas.microsoft.com/windowsazure"));
if (subscriptionCertificateThumbprintElement != null)
{
string subscriptionCertificateThumbprintInstance = subscriptionCertificateThumbprintElement.Value;
result.Thumbprint = subscriptionCertificateThumbprintInstance;
}
XElement subscriptionCertificateDataElement = subscriptionCertificateElement.Element(XName.Get("SubscriptionCertificateData", "http://schemas.microsoft.com/windowsazure"));
if (subscriptionCertificateDataElement != null)
{
byte[] subscriptionCertificateDataInstance = Convert.FromBase64String(subscriptionCertificateDataElement.Value);
result.Data = subscriptionCertificateDataInstance;
}
XElement createdElement = subscriptionCertificateElement.Element(XName.Get("Created", "http://schemas.microsoft.com/windowsazure"));
if (createdElement != null)
{
DateTime createdInstance = DateTime.Parse(createdElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
result.Created = createdInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The List Management Certificates operation lists and returns basic
/// information about all of the management certificates associated
/// with the specified subscription. Management certificates, which
/// are also known as subscription certificates, authenticate clients
/// attempting to connect to resources associated with your Azure
/// subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj154105.aspx
/// for more information)
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Management Certificates operation response.
/// </returns>
public async Task<ManagementCertificateListResponse> ListAsync(CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/certificates";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ManagementCertificateListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ManagementCertificateListResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement subscriptionCertificatesSequenceElement = responseDoc.Element(XName.Get("SubscriptionCertificates", "http://schemas.microsoft.com/windowsazure"));
if (subscriptionCertificatesSequenceElement != null)
{
foreach (XElement subscriptionCertificatesElement in subscriptionCertificatesSequenceElement.Elements(XName.Get("SubscriptionCertificate", "http://schemas.microsoft.com/windowsazure")))
{
ManagementCertificateListResponse.SubscriptionCertificate subscriptionCertificateInstance = new ManagementCertificateListResponse.SubscriptionCertificate();
result.SubscriptionCertificates.Add(subscriptionCertificateInstance);
XElement subscriptionCertificatePublicKeyElement = subscriptionCertificatesElement.Element(XName.Get("SubscriptionCertificatePublicKey", "http://schemas.microsoft.com/windowsazure"));
if (subscriptionCertificatePublicKeyElement != null)
{
byte[] subscriptionCertificatePublicKeyInstance = Convert.FromBase64String(subscriptionCertificatePublicKeyElement.Value);
subscriptionCertificateInstance.PublicKey = subscriptionCertificatePublicKeyInstance;
}
XElement subscriptionCertificateThumbprintElement = subscriptionCertificatesElement.Element(XName.Get("SubscriptionCertificateThumbprint", "http://schemas.microsoft.com/windowsazure"));
if (subscriptionCertificateThumbprintElement != null)
{
string subscriptionCertificateThumbprintInstance = subscriptionCertificateThumbprintElement.Value;
subscriptionCertificateInstance.Thumbprint = subscriptionCertificateThumbprintInstance;
}
XElement subscriptionCertificateDataElement = subscriptionCertificatesElement.Element(XName.Get("SubscriptionCertificateData", "http://schemas.microsoft.com/windowsazure"));
if (subscriptionCertificateDataElement != null)
{
byte[] subscriptionCertificateDataInstance = Convert.FromBase64String(subscriptionCertificateDataElement.Value);
subscriptionCertificateInstance.Data = subscriptionCertificateDataInstance;
}
XElement createdElement = subscriptionCertificatesElement.Element(XName.Get("Created", "http://schemas.microsoft.com/windowsazure"));
if (createdElement != null)
{
DateTime createdInstance = DateTime.Parse(createdElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
subscriptionCertificateInstance.Created = createdInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
//
// Mono.Cxxi.CppInstancePtr.cs: Represents a pointer to a native C++ instance
//
// Author:
// Alexander Corrado (alexander.corrado@gmail.com)
// Andreia Gaita (shana@spoiledcat.net)
//
// Copyright (C) 2010-2011 Alexander Corrado
//
// 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.Reflection.Emit;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Diagnostics;
using Mono.Cxxi.Abi;
namespace Mono.Cxxi {
public struct CppInstancePtr : ICppObject {
private IntPtr ptr, native_vtptr;
private bool manage_memory;
private static Dictionary<IntPtr,int> managed_vtptr_to_gchandle_offset = null;
// Alloc a new C++ instance
internal CppInstancePtr (CppTypeInfo typeInfo, object managedWrapper)
{
// Under the hood, we're secretly subclassing this C++ class to store a
// handle to the managed wrapper.
int allocSize = typeInfo.GCHandleOffset + IntPtr.Size;
ptr = Marshal.AllocHGlobal (allocSize);
// NOTE: native_vtptr will be set later after native ctor is called
native_vtptr = IntPtr.Zero;
// zero memory for sanity
// FIXME: This should be an initblk
byte[] zeroArray = new byte [allocSize];
Marshal.Copy (zeroArray, 0, ptr, allocSize);
IntPtr handlePtr = MakeGCHandle (managedWrapper);
Marshal.WriteIntPtr (ptr, typeInfo.GCHandleOffset, handlePtr);
manage_memory = true;
}
// Alloc a new C++ instance when there is no managed wrapper.
internal CppInstancePtr (int nativeSize)
{
ptr = Marshal.AllocHGlobal (nativeSize);
native_vtptr = IntPtr.Zero;
manage_memory = true;
}
// Gets a casted CppInstancePtr
internal CppInstancePtr (CppInstancePtr instance, int offset)
{
// FIXME: On NET_4_0 use IntPtr.Add
ptr = new IntPtr (instance.Native.ToInt64 () + offset);
native_vtptr = IntPtr.Zero;
manage_memory = false;
}
// Get a CppInstancePtr for an existing C++ instance from an IntPtr
public CppInstancePtr (IntPtr native)
{
if (native == IntPtr.Zero)
throw new ArgumentOutOfRangeException ("native cannot be null pointer");
ptr = native;
native_vtptr = IntPtr.Zero;
manage_memory = false;
}
// Fulfills ICppObject requirement
public CppInstancePtr (CppInstancePtr copy)
{
this.ptr = copy.ptr;
this.native_vtptr = copy.native_vtptr;
this.manage_memory = copy.manage_memory;
}
// Provide casts to/from IntPtr:
public static implicit operator CppInstancePtr (IntPtr native)
{
return new CppInstancePtr (native);
}
// cast from CppInstancePtr -> IntPtr is explicit because we lose information
public static explicit operator IntPtr (CppInstancePtr ip)
{
return ip.Native;
}
public IntPtr Native {
get {
if (ptr == IntPtr.Zero)
throw new ObjectDisposedException ("CppInstancePtr");
return ptr;
}
}
// Internal for now to prevent attempts to read vtptr from non-virtual class
internal IntPtr NativeVTable {
get {
if (native_vtptr == IntPtr.Zero) {
// For pointers from native code...
// Kludge! CppInstancePtr doesn't know whether this class is virtual or not, but we'll just assume that either
// way it's at least sizeof(void*) and read what would be the vtptr anyway. Supposedly, if it's not virtual,
// the wrappers won't use this field anyway...
native_vtptr = Marshal.ReadIntPtr (ptr);
}
return native_vtptr;
}
set {
native_vtptr = value;
}
}
CppInstancePtr ICppObject.Native {
get { return this; }
}
public bool IsManagedAlloc {
get { return manage_memory; }
}
internal static void RegisterManagedVTable (VTable vtable)
{
if (managed_vtptr_to_gchandle_offset == null)
managed_vtptr_to_gchandle_offset = new Dictionary<IntPtr, int> ();
managed_vtptr_to_gchandle_offset [vtable.Pointer] = vtable.TypeInfo.GCHandleOffset;
}
internal static IntPtr MakeGCHandle (object managedWrapper)
{
// TODO: Dispose() should probably be called at some point on this GCHandle.
GCHandle handle = GCHandle.Alloc (managedWrapper, GCHandleType.Normal);
return GCHandle.ToIntPtr (handle);
}
// This might be made public, but in this form it only works for classes with vtables.
// Returns null if the native ptr passed in does not appear to be a managed instance.
// (i.e. its vtable ptr is not in managed_vtptr_to_gchandle_offset)
internal static T ToManaged<T> (IntPtr native) where T : class
{
if (managed_vtptr_to_gchandle_offset == null)
return null;
int gchOffset;
if (!managed_vtptr_to_gchandle_offset.TryGetValue (Marshal.ReadIntPtr (native), out gchOffset))
return null;
return ToManaged<T> (native, gchOffset);
}
// WARNING! This method is not safe. DO NOT call
// if we do not KNOW that this instance is managed.
internal static T ToManaged<T> (IntPtr native, int nativeSize) where T : class
{
IntPtr handlePtr = Marshal.ReadIntPtr (native, nativeSize);
GCHandle handle = GCHandle.FromIntPtr (handlePtr);
return handle.Target as T;
}
// TODO: Free GCHandle?
public void Dispose ()
{
if (manage_memory && ptr != IntPtr.Zero)
Marshal.FreeHGlobal (ptr);
ptr = IntPtr.Zero;
manage_memory = false;
}
}
}
| |
using Discord.Commands.Builders;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Threading.Tasks;
namespace Discord.Commands
{
/// <summary>
/// Provides the information of a command.
/// </summary>
/// <remarks>
/// This object contains the information of a command. This can include the module of the command, various
/// descriptions regarding the command, and its <see cref="RunMode"/>.
/// </remarks>
[DebuggerDisplay("{Name,nq}")]
public class CommandInfo
{
private static readonly System.Reflection.MethodInfo _convertParamsMethod = typeof(CommandInfo).GetTypeInfo().GetDeclaredMethod(nameof(ConvertParamsList));
private static readonly ConcurrentDictionary<Type, Func<IEnumerable<object>, object>> _arrayConverters = new ConcurrentDictionary<Type, Func<IEnumerable<object>, object>>();
private readonly CommandService _commandService;
private readonly Func<ICommandContext, object[], IServiceProvider, CommandInfo, Task> _action;
/// <summary>
/// Gets the module that the command belongs in.
/// </summary>
public ModuleInfo Module { get; }
/// <summary>
/// Gets the name of the command. If none is set, the first alias is used.
/// </summary>
public string Name { get; }
/// <summary>
/// Gets the summary of the command.
/// </summary>
/// <remarks>
/// This field returns the summary of the command. <see cref="Summary"/> and <see cref="Remarks"/> can be
/// useful in help commands and various implementation that fetches details of the command for the user.
/// </remarks>
public string Summary { get; }
/// <summary>
/// Gets the remarks of the command.
/// </summary>
/// <remarks>
/// This field returns the summary of the command. <see cref="Summary"/> and <see cref="Remarks"/> can be
/// useful in help commands and various implementation that fetches details of the command for the user.
/// </remarks>
public string Remarks { get; }
/// <summary>
/// Gets the priority of the command. This is used when there are multiple overloads of the command.
/// </summary>
public int Priority { get; }
/// <summary>
/// Indicates whether the command accepts a <see langword="params"/> <see cref="Type"/>[] for its
/// parameter.
/// </summary>
public bool HasVarArgs { get; }
/// <summary>
/// Indicates whether extra arguments should be ignored for this command.
/// </summary>
public bool IgnoreExtraArgs { get; }
/// <summary>
/// Gets the <see cref="RunMode" /> that is being used for the command.
/// </summary>
public RunMode RunMode { get; }
/// <summary>
/// Gets a list of aliases defined by the <see cref="AliasAttribute" /> of the command.
/// </summary>
public IReadOnlyList<string> Aliases { get; }
/// <summary>
/// Gets a list of information about the parameters of the command.
/// </summary>
public IReadOnlyList<ParameterInfo> Parameters { get; }
/// <summary>
/// Gets a list of preconditions defined by the <see cref="PreconditionAttribute" /> of the command.
/// </summary>
public IReadOnlyList<PreconditionAttribute> Preconditions { get; }
/// <summary>
/// Gets a list of attributes of the command.
/// </summary>
public IReadOnlyList<Attribute> Attributes { get; }
internal CommandInfo(CommandBuilder builder, ModuleInfo module, CommandService service)
{
Module = module;
Name = builder.Name;
Summary = builder.Summary;
Remarks = builder.Remarks;
RunMode = (builder.RunMode == RunMode.Default ? service._defaultRunMode : builder.RunMode);
Priority = builder.Priority;
Aliases = module.Aliases
.Permutate(builder.Aliases, (first, second) =>
{
if (first == "")
return second;
else if (second == "")
return first;
else
return first + service._separatorChar + second;
})
.Select(x => service._caseSensitive ? x : x.ToLowerInvariant())
.ToImmutableArray();
Preconditions = builder.Preconditions.ToImmutableArray();
Attributes = builder.Attributes.ToImmutableArray();
Parameters = builder.Parameters.Select(x => x.Build(this)).ToImmutableArray();
HasVarArgs = builder.Parameters.Count > 0 && builder.Parameters[builder.Parameters.Count - 1].IsMultiple;
IgnoreExtraArgs = builder.IgnoreExtraArgs;
_action = builder.Callback;
_commandService = service;
}
public async Task<PreconditionResult> CheckPreconditionsAsync(ICommandContext context, IServiceProvider services = null)
{
services = services ?? EmptyServiceProvider.Instance;
async Task<PreconditionResult> CheckGroups(IEnumerable<PreconditionAttribute> preconditions, string type)
{
foreach (IGrouping<string, PreconditionAttribute> preconditionGroup in preconditions.GroupBy(p => p.Group, StringComparer.Ordinal))
{
if (preconditionGroup.Key == null)
{
foreach (PreconditionAttribute precondition in preconditionGroup)
{
var result = await precondition.CheckPermissionsAsync(context, this, services).ConfigureAwait(false);
if (!result.IsSuccess)
return result;
}
}
else
{
var results = new List<PreconditionResult>();
foreach (PreconditionAttribute precondition in preconditionGroup)
results.Add(await precondition.CheckPermissionsAsync(context, this, services).ConfigureAwait(false));
if (!results.Any(p => p.IsSuccess))
return PreconditionGroupResult.FromError($"{type} precondition group {preconditionGroup.Key} failed.", results);
}
}
return PreconditionGroupResult.FromSuccess();
}
var moduleResult = await CheckGroups(Module.Preconditions, "Module").ConfigureAwait(false);
if (!moduleResult.IsSuccess)
return moduleResult;
var commandResult = await CheckGroups(Preconditions, "Command").ConfigureAwait(false);
if (!commandResult.IsSuccess)
return commandResult;
return PreconditionResult.FromSuccess();
}
public async Task<ParseResult> ParseAsync(ICommandContext context, int startIndex, SearchResult searchResult, PreconditionResult preconditionResult = null, IServiceProvider services = null)
{
services = services ?? EmptyServiceProvider.Instance;
if (!searchResult.IsSuccess)
return ParseResult.FromError(searchResult);
if (preconditionResult != null && !preconditionResult.IsSuccess)
return ParseResult.FromError(preconditionResult);
string input = searchResult.Text.Substring(startIndex);
return await CommandParser.ParseArgsAsync(this, context, _commandService._ignoreExtraArgs, services, input, 0, _commandService._quotationMarkAliasMap).ConfigureAwait(false);
}
public Task<IResult> ExecuteAsync(ICommandContext context, ParseResult parseResult, IServiceProvider services)
{
if (!parseResult.IsSuccess)
return Task.FromResult((IResult)ExecuteResult.FromError(parseResult));
var argList = new object[parseResult.ArgValues.Count];
for (int i = 0; i < parseResult.ArgValues.Count; i++)
{
if (!parseResult.ArgValues[i].IsSuccess)
return Task.FromResult((IResult)ExecuteResult.FromError(parseResult.ArgValues[i]));
argList[i] = parseResult.ArgValues[i].Values.First().Value;
}
var paramList = new object[parseResult.ParamValues.Count];
for (int i = 0; i < parseResult.ParamValues.Count; i++)
{
if (!parseResult.ParamValues[i].IsSuccess)
return Task.FromResult((IResult)ExecuteResult.FromError(parseResult.ParamValues[i]));
paramList[i] = parseResult.ParamValues[i].Values.First().Value;
}
return ExecuteAsync(context, argList, paramList, services);
}
public async Task<IResult> ExecuteAsync(ICommandContext context, IEnumerable<object> argList, IEnumerable<object> paramList, IServiceProvider services)
{
services = services ?? EmptyServiceProvider.Instance;
try
{
object[] args = GenerateArgs(argList, paramList);
for (int position = 0; position < Parameters.Count; position++)
{
var parameter = Parameters[position];
object argument = args[position];
var result = await parameter.CheckPreconditionsAsync(context, argument, services).ConfigureAwait(false);
if (!result.IsSuccess)
{
await Module.Service._commandExecutedEvent.InvokeAsync(this, context, result).ConfigureAwait(false);
return ExecuteResult.FromError(result);
}
}
switch (RunMode)
{
case RunMode.Sync: //Always sync
return await ExecuteInternalAsync(context, args, services).ConfigureAwait(false);
case RunMode.Async: //Always async
var t2 = Task.Run(async () =>
{
await ExecuteInternalAsync(context, args, services).ConfigureAwait(false);
});
break;
}
return ExecuteResult.FromSuccess();
}
catch (Exception ex)
{
return ExecuteResult.FromError(ex);
}
}
private async Task<IResult> ExecuteInternalAsync(ICommandContext context, object[] args, IServiceProvider services)
{
await Module.Service._cmdLogger.DebugAsync($"Executing {GetLogText(context)}").ConfigureAwait(false);
try
{
var task = _action(context, args, services, this);
if (task is Task<IResult> resultTask)
{
var result = await resultTask.ConfigureAwait(false);
await Module.Service._commandExecutedEvent.InvokeAsync(this, context, result).ConfigureAwait(false);
if (result is RuntimeResult execResult)
return execResult;
}
else if (task is Task<ExecuteResult> execTask)
{
var result = await execTask.ConfigureAwait(false);
await Module.Service._commandExecutedEvent.InvokeAsync(this, context, result).ConfigureAwait(false);
return result;
}
else
{
await task.ConfigureAwait(false);
var result = ExecuteResult.FromSuccess();
await Module.Service._commandExecutedEvent.InvokeAsync(this, context, result).ConfigureAwait(false);
}
var executeResult = ExecuteResult.FromSuccess();
return executeResult;
}
catch (Exception ex)
{
var originalEx = ex;
while (ex is TargetInvocationException) //Happens with void-returning commands
ex = ex.InnerException;
var wrappedEx = new CommandException(this, context, ex);
await Module.Service._cmdLogger.ErrorAsync(wrappedEx).ConfigureAwait(false);
var result = ExecuteResult.FromError(ex);
await Module.Service._commandExecutedEvent.InvokeAsync(this, context, result).ConfigureAwait(false);
if (Module.Service._throwOnError)
{
if (ex == originalEx)
throw;
else
ExceptionDispatchInfo.Capture(ex).Throw();
}
return result;
}
finally
{
await Module.Service._cmdLogger.VerboseAsync($"Executed {GetLogText(context)}").ConfigureAwait(false);
}
}
private object[] GenerateArgs(IEnumerable<object> argList, IEnumerable<object> paramsList)
{
int argCount = Parameters.Count;
var array = new object[Parameters.Count];
if (HasVarArgs)
argCount--;
int i = 0;
foreach (object arg in argList)
{
if (i == argCount)
throw new InvalidOperationException("Command was invoked with too many parameters.");
array[i++] = arg;
}
if (i < argCount)
throw new InvalidOperationException("Command was invoked with too few parameters.");
if (HasVarArgs)
{
var func = _arrayConverters.GetOrAdd(Parameters[Parameters.Count - 1].Type, t =>
{
var method = _convertParamsMethod.MakeGenericMethod(t);
return (Func<IEnumerable<object>, object>)method.CreateDelegate(typeof(Func<IEnumerable<object>, object>));
});
array[i] = func(paramsList);
}
return array;
}
private static T[] ConvertParamsList<T>(IEnumerable<object> paramsList)
=> paramsList.Cast<T>().ToArray();
internal string GetLogText(ICommandContext context)
{
if (context.Guild != null)
return $"\"{Name}\" for {context.User} in {context.Guild}/{context.Channel}";
else
return $"\"{Name}\" for {context.User} in {context.Channel}";
}
}
}
| |
namespace XenAdmin.Dialogs
{
partial class NewDiskDialog
{
/// <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 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(NewDiskDialog));
this.DiskSizeNumericUpDown = new System.Windows.Forms.NumericUpDown();
this.SrListBox = new XenAdmin.Controls.SrPicker();
this.GbLabel = new System.Windows.Forms.Label();
this.CloseButton = new System.Windows.Forms.Button();
this.OkButton = new System.Windows.Forms.Button();
this.NameTextBox = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.DescriptionTextBox = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.panel1 = new System.Windows.Forms.FlowLayoutPanel();
this.label4 = new System.Windows.Forms.Label();
this.panel2 = new System.Windows.Forms.Panel();
this.comboBoxUnits = new System.Windows.Forms.ComboBox();
this.labelError = new System.Windows.Forms.Label();
this.pictureBoxError = new System.Windows.Forms.PictureBox();
this.label6 = new System.Windows.Forms.Label();
this.labelAllocationQuantum = new System.Windows.Forms.Label();
this.labelInitialAllocation = new System.Windows.Forms.Label();
this.initialAllocationNumericUpDown = new System.Windows.Forms.NumericUpDown();
this.allocationQuantumNumericUpDown = new System.Windows.Forms.NumericUpDown();
this.init_alloc_units = new System.Windows.Forms.ComboBox();
this.incr_alloc_units = new System.Windows.Forms.ComboBox();
this.queuedBackgroundWorker1 = new XenCenterLib.QueuedBackgroundWorker();
((System.ComponentModel.ISupportInitialize)(this.DiskSizeNumericUpDown)).BeginInit();
this.tableLayoutPanel1.SuspendLayout();
this.panel1.SuspendLayout();
this.panel2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxError)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.initialAllocationNumericUpDown)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.allocationQuantumNumericUpDown)).BeginInit();
this.SuspendLayout();
//
// DiskSizeNumericUpDown
//
resources.ApplyResources(this.DiskSizeNumericUpDown, "DiskSizeNumericUpDown");
this.DiskSizeNumericUpDown.Maximum = new decimal(new int[] {
1000000000,
0,
0,
0});
this.DiskSizeNumericUpDown.Name = "DiskSizeNumericUpDown";
this.DiskSizeNumericUpDown.Value = new decimal(new int[] {
1,
0,
0,
0});
this.DiskSizeNumericUpDown.ValueChanged += new System.EventHandler(this.DiskSizeNumericUpDown_ValueChanged);
this.DiskSizeNumericUpDown.KeyUp += new System.Windows.Forms.KeyEventHandler(this.DiskSizeNumericUpDown_KeyUp);
//
// SrListBox
//
resources.ApplyResources(this.SrListBox, "SrListBox");
this.tableLayoutPanel1.SetColumnSpan(this.SrListBox, 3);
this.SrListBox.Connection = null;
this.SrListBox.Name = "SrListBox";
//
// GbLabel
//
resources.ApplyResources(this.GbLabel, "GbLabel");
this.GbLabel.Name = "GbLabel";
//
// CloseButton
//
resources.ApplyResources(this.CloseButton, "CloseButton");
this.CloseButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.CloseButton.Name = "CloseButton";
this.CloseButton.UseVisualStyleBackColor = true;
this.CloseButton.Click += new System.EventHandler(this.CloseButton_Click);
//
// OkButton
//
resources.ApplyResources(this.OkButton, "OkButton");
this.OkButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.OkButton.Name = "OkButton";
this.OkButton.UseVisualStyleBackColor = true;
this.OkButton.Click += new System.EventHandler(this.OkButton_Click);
//
// NameTextBox
//
this.tableLayoutPanel1.SetColumnSpan(this.NameTextBox, 3);
resources.ApplyResources(this.NameTextBox, "NameTextBox");
this.NameTextBox.Name = "NameTextBox";
this.NameTextBox.TextChanged += new System.EventHandler(this.NameTextBox_TextChanged);
//
// label2
//
resources.ApplyResources(this.label2, "label2");
this.label2.Name = "label2";
//
// DescriptionTextBox
//
this.tableLayoutPanel1.SetColumnSpan(this.DescriptionTextBox, 3);
resources.ApplyResources(this.DescriptionTextBox, "DescriptionTextBox");
this.DescriptionTextBox.Name = "DescriptionTextBox";
this.DescriptionTextBox.TextChanged += new System.EventHandler(this.NameTextBox_TextChanged);
//
// label3
//
resources.ApplyResources(this.label3, "label3");
this.label3.Name = "label3";
//
// label1
//
resources.ApplyResources(this.label1, "label1");
this.label1.Name = "label1";
//
// tableLayoutPanel1
//
resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1");
this.tableLayoutPanel1.Controls.Add(this.label2, 0, 2);
this.tableLayoutPanel1.Controls.Add(this.label1, 0, 4);
this.tableLayoutPanel1.Controls.Add(this.NameTextBox, 1, 2);
this.tableLayoutPanel1.Controls.Add(this.DescriptionTextBox, 1, 3);
this.tableLayoutPanel1.Controls.Add(this.SrListBox, 1, 5);
this.tableLayoutPanel1.Controls.Add(this.label3, 0, 3);
this.tableLayoutPanel1.Controls.Add(this.DiskSizeNumericUpDown, 1, 4);
this.tableLayoutPanel1.Controls.Add(this.panel1, 1, 9);
this.tableLayoutPanel1.Controls.Add(this.label4, 0, 5);
this.tableLayoutPanel1.Controls.Add(this.panel2, 2, 4);
this.tableLayoutPanel1.Controls.Add(this.label6, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.labelAllocationQuantum, 0, 7);
this.tableLayoutPanel1.Controls.Add(this.labelInitialAllocation, 0, 6);
this.tableLayoutPanel1.Controls.Add(this.initialAllocationNumericUpDown, 1, 6);
this.tableLayoutPanel1.Controls.Add(this.allocationQuantumNumericUpDown, 1, 7);
this.tableLayoutPanel1.Controls.Add(this.init_alloc_units, 2, 6);
this.tableLayoutPanel1.Controls.Add(this.incr_alloc_units, 2, 7);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
//
// panel1
//
resources.ApplyResources(this.panel1, "panel1");
this.tableLayoutPanel1.SetColumnSpan(this.panel1, 3);
this.panel1.Controls.Add(this.CloseButton);
this.panel1.Controls.Add(this.OkButton);
this.panel1.Name = "panel1";
//
// label4
//
resources.ApplyResources(this.label4, "label4");
this.label4.Name = "label4";
//
// panel2
//
resources.ApplyResources(this.panel2, "panel2");
this.tableLayoutPanel1.SetColumnSpan(this.panel2, 2);
this.panel2.Controls.Add(this.comboBoxUnits);
this.panel2.Controls.Add(this.labelError);
this.panel2.Controls.Add(this.pictureBoxError);
this.panel2.Name = "panel2";
//
// comboBoxUnits
//
this.comboBoxUnits.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.comboBoxUnits, "comboBoxUnits");
this.comboBoxUnits.FormattingEnabled = true;
this.comboBoxUnits.Items.AddRange(new object[] {
resources.GetString("comboBoxUnits.Items"),
resources.GetString("comboBoxUnits.Items1")});
this.comboBoxUnits.Name = "comboBoxUnits";
//
// labelError
//
resources.ApplyResources(this.labelError, "labelError");
this.labelError.ForeColor = System.Drawing.Color.Red;
this.labelError.Name = "labelError";
//
// pictureBoxError
//
resources.ApplyResources(this.pictureBoxError, "pictureBoxError");
this.pictureBoxError.Name = "pictureBoxError";
this.pictureBoxError.TabStop = false;
//
// label6
//
resources.ApplyResources(this.label6, "label6");
this.tableLayoutPanel1.SetColumnSpan(this.label6, 4);
this.label6.Name = "label6";
//
// labelAllocationQuantum
//
resources.ApplyResources(this.labelAllocationQuantum, "labelAllocationQuantum");
this.labelAllocationQuantum.Name = "labelAllocationQuantum";
//
// labelInitialAllocation
//
resources.ApplyResources(this.labelInitialAllocation, "labelInitialAllocation");
this.labelInitialAllocation.Name = "labelInitialAllocation";
//
// initialAllocationNumericUpDown
//
resources.ApplyResources(this.initialAllocationNumericUpDown, "initialAllocationNumericUpDown");
this.initialAllocationNumericUpDown.DecimalPlaces = 1;
this.initialAllocationNumericUpDown.Name = "initialAllocationNumericUpDown";
this.initialAllocationNumericUpDown.Value = new decimal(new int[] {
10,
0,
0,
0});
this.initialAllocationNumericUpDown.ValueChanged += new System.EventHandler(this.initialAllocationNumericUpDown_ValueChanged);
this.initialAllocationNumericUpDown.Enter += new System.EventHandler(this.initialAllocationNumericUpDown_Enter);
this.initialAllocationNumericUpDown.Leave += new System.EventHandler(this.initialAllocationNumericUpDown_Leave);
//
// allocationQuantumNumericUpDown
//
resources.ApplyResources(this.allocationQuantumNumericUpDown, "allocationQuantumNumericUpDown");
this.allocationQuantumNumericUpDown.DecimalPlaces = 1;
this.allocationQuantumNumericUpDown.Name = "allocationQuantumNumericUpDown";
this.allocationQuantumNumericUpDown.Value = new decimal(new int[] {
10,
0,
0,
0});
//
// init_alloc_units
//
this.init_alloc_units.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.init_alloc_units, "init_alloc_units");
this.init_alloc_units.FormattingEnabled = true;
this.init_alloc_units.Items.AddRange(new object[] {
resources.GetString("init_alloc_units.Items"),
resources.GetString("init_alloc_units.Items1")});
this.init_alloc_units.Name = "init_alloc_units";
this.init_alloc_units.SelectedIndexChanged += new System.EventHandler(this.init_alloc_units_SelectedIndexChanged);
//
// incr_alloc_units
//
this.incr_alloc_units.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.incr_alloc_units, "incr_alloc_units");
this.incr_alloc_units.FormattingEnabled = true;
this.incr_alloc_units.Items.AddRange(new object[] {
resources.GetString("incr_alloc_units.Items"),
resources.GetString("incr_alloc_units.Items1")});
this.incr_alloc_units.Name = "incr_alloc_units";
this.incr_alloc_units.SelectedIndexChanged += new System.EventHandler(this.incr_alloc_units_SelectedIndexChanged);
//
// NewDiskDialog
//
this.AcceptButton = this.OkButton;
resources.ApplyResources(this, "$this");
this.CancelButton = this.CloseButton;
this.Controls.Add(this.tableLayoutPanel1);
this.Controls.Add(this.GbLabel);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
this.Name = "NewDiskDialog";
((System.ComponentModel.ISupportInitialize)(this.DiskSizeNumericUpDown)).EndInit();
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.panel1.ResumeLayout(false);
this.panel2.ResumeLayout(false);
this.panel2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxError)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.initialAllocationNumericUpDown)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.allocationQuantumNumericUpDown)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label GbLabel;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label1;
public System.Windows.Forms.NumericUpDown DiskSizeNumericUpDown;
public XenAdmin.Controls.SrPicker SrListBox;
public System.Windows.Forms.Button CloseButton;
public System.Windows.Forms.Button OkButton;
public System.Windows.Forms.TextBox NameTextBox;
public System.Windows.Forms.TextBox DescriptionTextBox;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.FlowLayoutPanel panel1;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label labelError;
private System.Windows.Forms.PictureBox pictureBoxError;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.ComboBox comboBoxUnits;
private XenCenterLib.QueuedBackgroundWorker queuedBackgroundWorker1;
private System.Windows.Forms.Label labelAllocationQuantum;
private System.Windows.Forms.Label labelInitialAllocation;
private System.Windows.Forms.NumericUpDown initialAllocationNumericUpDown;
private System.Windows.Forms.NumericUpDown allocationQuantumNumericUpDown;
private System.Windows.Forms.ComboBox init_alloc_units;
private System.Windows.Forms.ComboBox incr_alloc_units;
}
}
| |
#region Using Statements
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using CSJ2K;
using CSJ2K.Color;
using CSJ2K.Icc;
using CSJ2K.j2k;
using CSJ2K.j2k.codestream;
using CSJ2K.j2k.codestream.reader;
using CSJ2K.j2k.decoder;
using CSJ2K.j2k.entropy.decoder;
using CSJ2K.j2k.fileformat.reader;
using CSJ2K.j2k.image;
using CSJ2K.j2k.image.invcomptransf;
using CSJ2K.j2k.io;
using CSJ2K.j2k.quantization.dequantizer;
using CSJ2K.j2k.roi;
using CSJ2K.j2k.util;
using CSJ2K.j2k.wavelet.synthesis;
#endregion
namespace CSJ2K
{
public class J2kImage
{
#region Static Decoder Methods
public static Image FromFile(string filename)
{
Stream stream = new FileStream(filename, FileMode.Open, FileAccess.Read);
Image img = FromStream(stream);
stream.Close();
return (img);
}
public static Image FromBytes(byte[] j2kdata)
{
return FromStream(new MemoryStream(j2kdata));
}
public static Image FromStream(Stream stream)
{
RandomAccessIO in_stream = new ISRandomAccessIO(stream);
// Initialize default parameters
ParameterList defpl = GetDefaultParameterList(decoder_pinfo);
// Create parameter list using defaults
ParameterList pl = new ParameterList(defpl);
// **** File Format ****
// If the codestream is wrapped in the jp2 fileformat, Read the
// file format wrapper
FileFormatReader ff = new FileFormatReader(in_stream);
ff.readFileFormat();
if (ff.JP2FFUsed)
{
in_stream.seek(ff.FirstCodeStreamPos);
}
// +----------------------------+
// | Instantiate decoding chain |
// +----------------------------+
// **** Header decoder ****
// Instantiate header decoder and read main header
HeaderInfo hi = new HeaderInfo();
HeaderDecoder hd;
try
{
hd = new HeaderDecoder(in_stream, pl, hi);
}
catch (EndOfStreamException e)
{
throw new ApplicationException("Codestream too short or bad header, unable to decode.", e);
}
int nCompCod = hd.NumComps;
int nTiles = hi.sizValue.NumTiles;
DecoderSpecs decSpec = hd.DecoderSpecs;
// Get demixed bitdepths
int[] depth = new int[nCompCod];
for (int i = 0; i < nCompCod; i++)
{
depth[i] = hd.getOriginalBitDepth(i);
}
// **** Bit stream reader ****
BitstreamReaderAgent breader;
try
{
breader = BitstreamReaderAgent.
createInstance(in_stream, hd, pl, decSpec,
false, hi);
}
catch (IOException e)
{
throw new ApplicationException("Error while reading bit stream header or parsing packets.", e);
}
catch (ArgumentException e)
{
throw new ApplicationException("Cannot instantiate bit stream reader.", e);
}
// **** Entropy decoder ****
EntropyDecoder entdec;
try
{
entdec = hd.createEntropyDecoder(breader, pl);
}
catch (ArgumentException e)
{
throw new ApplicationException("Cannot instantiate entropy decoder.", e);
}
// **** ROI de-scaler ****
ROIDeScaler roids;
try
{
roids = hd.createROIDeScaler(entdec, pl, decSpec);
}
catch (ArgumentException e)
{
throw new ApplicationException("Cannot instantiate roi de-scaler.", e);
}
// **** Dequantizer ****
Dequantizer deq;
try
{
deq = hd.createDequantizer(roids, depth, decSpec);
}
catch (ArgumentException e)
{
throw new ApplicationException("Cannot instantiate dequantizer.", e);
}
// **** Inverse wavelet transform ***
InverseWT invWT;
try
{
// full page inverse wavelet transform
invWT = InverseWT.createInstance(deq, decSpec);
}
catch (ArgumentException e)
{
throw new ApplicationException("Cannot instantiate inverse wavelet transform.", e);
}
int res = breader.ImgRes;
invWT.ImgResLevel = res;
// **** Data converter **** (after inverse transform module)
ImgDataConverter converter = new ImgDataConverter(invWT, 0);
// **** Inverse component transformation ****
InvCompTransf ictransf = new InvCompTransf(converter, decSpec, depth, pl);
// **** Color space mapping ****
BlkImgDataSrc color;
if (ff.JP2FFUsed && pl.getParameter("nocolorspace").Equals("off"))
{
try
{
ColorSpace csMap = new ColorSpace(in_stream, hd, pl);
BlkImgDataSrc channels = hd.createChannelDefinitionMapper(ictransf, csMap);
BlkImgDataSrc resampled = hd.createResampler(channels, csMap);
BlkImgDataSrc palettized = hd.createPalettizedColorSpaceMapper(resampled, csMap);
color = hd.createColorSpaceMapper(palettized, csMap);
}
catch (ArgumentException e)
{
throw new ApplicationException("Could not instantiate ICC profiler.", e);
}
catch (ColorSpaceException e)
{
throw new ApplicationException("Error processing ColorSpace information.", e);
}
}
else
{ // Skip colorspace mapping
color = ictransf;
}
// This is the last image in the decoding chain and should be
// assigned by the last transformation:
BlkImgDataSrc decodedImage = color;
if (color == null)
{
decodedImage = ictransf;
}
int numComps = decodedImage.NumComps;
int bytesPerPixel = numComps; // Assuming 8-bit components
// **** Copy to Bitmap ****
PixelFormat pixelFormat;
switch (numComps)
{
case 1:
pixelFormat = PixelFormat.Format24bppRgb; break;
case 3:
pixelFormat = PixelFormat.Format24bppRgb; break;
case 4:
case 5:
pixelFormat = PixelFormat.Format32bppArgb; break;
default:
throw new ApplicationException("Unsupported PixelFormat. " + numComps + " components.");
}
Bitmap dst = new Bitmap(decodedImage.ImgWidth, decodedImage.ImgHeight, pixelFormat);
Coord numTiles = decodedImage.getNumTiles(null);
int tIdx = 0;
for (int y = 0; y < numTiles.y; y++)
{
// Loop on horizontal tiles
for (int x = 0; x < numTiles.x; x++, tIdx++)
{
decodedImage.setTile(x, y);
int height = decodedImage.getTileCompHeight(tIdx, 0);
int width = decodedImage.getTileCompWidth(tIdx, 0);
int tOffx = decodedImage.getCompULX(0) -
(int)Math.Ceiling(decodedImage.ImgULX /
(double)decodedImage.getCompSubsX(0));
int tOffy = decodedImage.getCompULY(0) -
(int)Math.Ceiling(decodedImage.ImgULY /
(double)decodedImage.getCompSubsY(0));
DataBlkInt[] db = new DataBlkInt[numComps];
int[] ls = new int[numComps];
int[] mv = new int[numComps];
int[] fb = new int[numComps];
for (int i = 0; i < numComps; i++)
{
db[i] = new DataBlkInt();
ls[i] = 1 << (decodedImage.getNomRangeBits(0) - 1);
mv[i] = (1 << decodedImage.getNomRangeBits(0)) - 1;
fb[i] = decodedImage.getFixedPoint(0);
}
for (int l = 0; l < height; l++)
{
for (int i = numComps - 1; i >= 0; i--)
{
db[i].ulx = 0;
db[i].uly = l;
db[i].w = width;
db[i].h = 1;
decodedImage.getInternCompData(db[i], i);
}
int[] k = new int[numComps];
for (int i = numComps - 1; i >= 0; i--) k[i] = db[i].offset + width - 1;
int outputBytesPerPixel = Math.Max(3, Math.Min(4, bytesPerPixel));
byte[] rowvalues = new byte[width * outputBytesPerPixel];
for (int i = width - 1; i >= 0; i--)
{
int[] tmp = new int[numComps];
for (int j = numComps - 1; j >= 0; j--)
{
tmp[j] = (db[j].data_array[k[j]--] >> fb[j]) + ls[j];
tmp[j] = (tmp[j] < 0) ? 0 : ((tmp[j] > mv[j]) ? mv[j] : tmp[j]);
if (decodedImage.getNomRangeBits(j) != 8)
tmp[j] = (int)Math.Round(((double)tmp[j] / Math.Pow(2D, (double)decodedImage.getNomRangeBits(j))) * 255D);
}
int offset = i * outputBytesPerPixel;
switch (numComps)
{
case 1:
rowvalues[offset + 0] = (byte)tmp[0];
rowvalues[offset + 1] = (byte)tmp[0];
rowvalues[offset + 2] = (byte)tmp[0];
break;
case 3:
rowvalues[offset + 0] = (byte)tmp[2];
rowvalues[offset + 1] = (byte)tmp[1];
rowvalues[offset + 2] = (byte)tmp[0];
break;
case 4:
case 5:
rowvalues[offset + 0] = (byte)tmp[2];
rowvalues[offset + 1] = (byte)tmp[1];
rowvalues[offset + 2] = (byte)tmp[0];
rowvalues[offset + 3] = (byte)tmp[3];
break;
}
}
BitmapData dstdata = dst.LockBits(
new System.Drawing.Rectangle(tOffx, tOffy + l, width, 1),
ImageLockMode.WriteOnly, pixelFormat);
IntPtr ptr = dstdata.Scan0;
System.Runtime.InteropServices.Marshal.Copy(rowvalues, 0, ptr, rowvalues.Length);
dst.UnlockBits(dstdata);
}
}
}
return dst;
}
public static List<int> GetLayerBoundaries(Stream stream)
{
RandomAccessIO in_stream = new ISRandomAccessIO(stream);
// Create parameter list using defaults
ParameterList pl = new ParameterList(GetDefaultParameterList(decoder_pinfo));
// **** File Format ****
// If the codestream is wrapped in the jp2 fileformat, Read the
// file format wrapper
FileFormatReader ff = new FileFormatReader(in_stream);
ff.readFileFormat();
if (ff.JP2FFUsed)
{
in_stream.seek(ff.FirstCodeStreamPos);
}
// +----------------------------+
// | Instantiate decoding chain |
// +----------------------------+
// **** Header decoder ****
// Instantiate header decoder and read main header
HeaderInfo hi = new HeaderInfo();
HeaderDecoder hd;
try
{
hd = new HeaderDecoder(in_stream, pl, hi);
}
catch (EndOfStreamException e)
{
throw new ArgumentException("Codestream too short or bad header, unable to decode.", e);
}
int nCompCod = hd.NumComps;
int nTiles = hi.sizValue.NumTiles;
DecoderSpecs decSpec = hd.DecoderSpecs;
// Get demixed bitdepths
int[] depth = new int[nCompCod];
for (int i = 0; i < nCompCod; i++)
{
depth[i] = hd.getOriginalBitDepth(i);
}
// **** Bit stream reader ****
BitstreamReaderAgent breader;
try
{
breader = BitstreamReaderAgent.createInstance(in_stream, hd, pl, decSpec, false, hi);
}
catch (IOException e)
{
throw new ArgumentException("Error while reading bit stream header or parsing packets.", e);
}
catch (ArgumentException e)
{
throw new ArgumentException("Cannot instantiate bit stream reader.", e);
}
breader.setTile(0, 0);
return ((FileBitstreamReaderAgent)breader).layerStarts;
}
#endregion
#region Static Encoder Methods
public static void ToFile(Bitmap bitmap, string filename)
{
using (FileStream stream = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
ToStream(bitmap, stream);
}
}
public static byte[] ToArray(Bitmap bitmap)
{
using (MemoryStream stream = new MemoryStream())
{
ToStream(bitmap, stream);
return stream.ToArray();
}
}
public static void ToStream(Bitmap bitmap, Stream stream)
{
throw new NotImplementedException();
}
#endregion
#region Default Parameter Loader
public static ParameterList GetDefaultParameterList(string[][] pinfo)
{
ParameterList pl = new ParameterList();
string[][] str;
str = BitstreamReaderAgent.ParameterInfo;
if (str != null) for (int i = str.Length - 1; i >= 0; i--)
pl.Set(str[i][0], str[i][3]);
str = EntropyDecoder.ParameterInfo;
if (str != null) for (int i = str.Length - 1; i >= 0; i--)
pl.Set(str[i][0], str[i][3]);
str = ROIDeScaler.ParameterInfo;
if (str != null) for (int i = str.Length - 1; i >= 0; i--)
pl.Set(str[i][0], str[i][3]);
str = Dequantizer.ParameterInfo;
if (str != null) for (int i = str.Length - 1; i >= 0; i--)
pl.Set(str[i][0], str[i][3]);
str = InvCompTransf.ParameterInfo;
if (str != null) for (int i = str.Length - 1; i >= 0; i--)
pl.Set(str[i][0], str[i][3]);
str = HeaderDecoder.ParameterInfo;
if (str != null) for (int i = str.Length - 1; i >= 0; i--)
pl.Set(str[i][0], str[i][3]);
str = ICCProfiler.ParameterInfo;
if (str != null) for (int i = str.Length - 1; i >= 0; i--)
pl.Set(str[i][0], str[i][3]);
str = pinfo;
if (str != null) for (int i = str.Length - 1; i >= 0; i--)
pl.Set(str[i][0], str[i][3]);
return pl;
}
#endregion
#region Decoder Parameters
private static String[][] decoder_pinfo = {
new string[] { "u", "[on|off]",
"Prints usage information. "+
"If specified all other arguments (except 'v') are ignored","off"},
new string[] { "v", "[on|off]",
"Prints version and copyright information","off"},
new string[] { "verbose", "[on|off]",
"Prints information about the decoded codestream","on"},
new string[] { "pfile", "<filename>",
"Loads the arguments from the specified file. Arguments that are "+
"specified on the command line override the ones from the file.\n"+
"The arguments file is a simple text file with one argument per "+
"line of the following form:\n" +
" <argument name>=<argument value>\n"+
"If the argument is of boolean type (i.e. its presence turns a "+
"feature on), then the 'on' value turns it on, while the 'off' "+
"value turns it off. The argument name does not include the '-' "+
"or '+' character. Long lines can be broken into several lines "+
"by terminating them with '\\'. Lines starting with '#' are "+
"considered as comments. This option is not recursive: any 'pfile' "+
"argument appearing in the file is ignored.",null},
new string[] { "res", "<resolution level index>",
"The resolution level at which to reconstruct the image "+
" (0 means the lowest available resolution whereas the maximum "+
"resolution level corresponds to the original image resolution). "+
"If the given index"+
" is greater than the number of available resolution levels of the "+
"compressed image, the image is reconstructed at its highest "+
"resolution (among all tile-components). Note that this option"+
" affects only the inverse wavelet transform and not the number "+
" of bytes read by the codestream parser: this number of bytes "+
"depends only on options '-nbytes' or '-rate'.", null},
new string[] { "i", "<filename or url>",
"The file containing the JPEG 2000 compressed data. This can be "+
"either a JPEG 2000 codestream or a JP2 file containing a "+
"JPEG 2000 "+
"codestream. In the latter case the first codestream in the file "+
"will be decoded. If an URL is specified (e.g., http://...) "+
"the data will be downloaded and cached in memory before decoding. "+
"This is intended for easy use in applets, but it is not a very "+
"efficient way of decoding network served data.", null},
new string[] { "o", "<filename>",
"This is the name of the file to which the decompressed image "+
"is written. If no output filename is given, the image is "+
"displayed on the screen. "+
"Output file format is PGX by default. If the extension"+
" is '.pgm' then a PGM file is written as output, however this is "+
"only permitted if the component bitdepth does not exceed 8. If "+
"the extension is '.ppm' then a PPM file is written, however this "+
"is only permitted if there are 3 components and none of them has "+
"a bitdepth of more than 8. If there is more than 1 component, "+
"suffices '-1', '-2', '-3', ... are added to the file name, just "+
"before the extension, except for PPM files where all three "+
"components are written to the same file.",null},
new string[] { "rate","<decoding rate in bpp>",
"Specifies the decoding rate in bits per pixel (bpp) where the "+
"number of pixels is related to the image's original size (Note:"+
" this number is not affected by the '-res' option). If it is equal"+
"to -1, the whole codestream is decoded. "+
"The codestream is either parsed (default) or truncated depending "+
"the command line option '-parsing'. To specify the decoding "+
"rate in bytes, use '-nbytes' options instead.","-1"},
new string[] { "nbytes","<decoding rate in bytes>",
"Specifies the decoding rate in bytes. "+
"The codestream is either parsed (default) or truncated depending "+
"the command line option '-parsing'. To specify the decoding "+
"rate in bits per pixel, use '-rate' options instead.","-1"},
new string[] { "parsing", null,
"Enable or not the parsing mode when decoding rate is specified "+
"('-nbytes' or '-rate' options). If it is false, the codestream "+
"is decoded as if it were truncated to the given rate. If it is "+
"true, the decoder creates, truncates and decodes a virtual layer"+
" progressive codestream with the same truncation points in each "+
"code-block.","on"},
new string[] { "ncb_quit","<max number of code blocks>",
"Use the ncb and lbody quit conditions. If state information is "+
"found for more code blocks than is indicated with this option, "+
"the decoder "+
"will decode using only information found before that point. "+
"Using this otion implies that the 'rate' or 'nbyte' parameter "+
"is used to indicate the lbody parameter which is the number of "+
"packet body bytes the decoder will decode.","-1"},
new string[] { "l_quit","<max number of layers>",
"Specifies the maximum number of layers to decode for any code-"+
"block","-1"},
new string[] { "m_quit","<max number of bit planes>",
"Specifies the maximum number of bit planes to decode for any code"+
"-block","-1"},
new string[] { "poc_quit",null,
"Specifies the whether the decoder should only decode code-blocks "+
"included in the first progression order.","off"},
new string[] { "one_tp",null,
"Specifies whether the decoder should only decode the first "+
"tile part of each tile.","off"},
new string[] { "comp_transf",null,
"Specifies whether the component transform indicated in the "+
"codestream should be used.","on"},
new string[] { "debug", null,
"Print debugging messages when an error is encountered.","off"},
new string[] { "cdstr_info", null,
"Display information about the codestream. This information is: "+
"\n- Marker segments value in main and tile-part headers,"+
"\n- Tile-part length and position within the code-stream.", "off"},
new string[] { "nocolorspace",null,
"Ignore any colorspace information in the image.","off"},
new string[] { "colorspace_debug", null,
"Print debugging messages when an error is encountered in the"+
" colorspace module.","off"}
};
#endregion
#region Encoder Parameters
private static String[][] encoder_pinfo = {
new string[] { "debug", null,
"Print debugging messages when an error is encountered.","off"},
new string[] { "disable_jp2_extension", "[on|off]",
"JJ2000 automatically adds .jp2 extension when using 'file_format'"+
"option. This option disables it when on.", "off"},
new string[] { "file_format", "[on|off]",
"Puts the JPEG 2000 codestream in a JP2 file format wrapper.","off"},
new string[] { "pph_tile", "[on|off]",
"Packs the packet headers in the tile headers.","off"},
new string[] { "pph_main", "[on|off]",
"Packs the packet headers in the main header.","off"},
new string[] { "pfile", "<filename of arguments file>",
"Loads the arguments from the specified file. Arguments that are "+
"specified on the command line override the ones from the file.\n"+
"The arguments file is a simple text file with one argument per "+
"line of the following form:\n" +
" <argument name>=<argument value>\n"+
"If the argument is of boolean type (i.e. its presence turns a "+
"feature on), then the 'on' value turns it on, while the 'off' "+
"value turns it off. The argument name does not include the '-' "+
"or '+' character. Long lines can be broken into several lines "+
"by terminating them with '\'. Lines starting with '#' are "+
"considered as comments. This option is not recursive: any 'pfile' "+
"argument appearing in the file is ignored.",null},
new string[] { "tile_parts", "<packets per tile-part>",
"This option specifies the maximum number of packets to have in "+
"one tile-part. 0 means include all packets in first tile-part "+
"of each tile","0"},
new string[] { "tiles", "<nominal tile width> <nominal tile height>",
"This option specifies the maximum tile dimensions to use. "+
"If both dimensions are 0 then no tiling is used.","0 0"},
new string[] { "ref", "<x> <y>",
"Sets the origin of the image in the canvas system. It sets the "+
"coordinate of the top-left corner of the image reference grid, "+
"with respect to the canvas origin","0 0"},
new string[] { "tref", "<x> <y>",
"Sets the origin of the tile partitioning on the reference grid, "+
"with respect to the canvas origin. The value of 'x' ('y') "+
"specified can not be larger than the 'x' one specified in the ref "+
"option.","0 0"},
new string[] { "rate", "<output bitrate in bpp>",
"This is the output bitrate of the codestream in bits per pixel."+
" When equal to -1, no image information (beside quantization "+
"effects) is discarded during compression.\n"+
"Note: In the case where '-file_format' option is used, the "+
"resulting file may have a larger bitrate.","-1"},
new string[] { "lossless", "[on|off]",
"Specifies a lossless compression for the encoder. This options"+
" is equivalent to use reversible quantization ('-Qtype "+
"reversible')"+
" and 5x3 wavelet filters pair ('-Ffilters w5x3'). Note that "+
"this option cannot be used with '-rate'. When this option is "+
"off, the quantization type and the filters pair is defined by "+
"'-Qtype' and '-Ffilters' respectively.","off"},
new string[] { "i", "<image file> [,<image file> [,<image file> ... ]]",
"Mandatory argument. This option specifies the name of the input "+
"image files. If several image files are provided, they have to be"+
" separated by commas in the command line. Supported formats are "+
"PGM (raw), PPM (raw) and PGX, "+
"which is a simple extension of the PGM file format for single "+
"component data supporting arbitrary bitdepths. If the extension "+
"is '.pgm', PGM-raw file format is assumed, if the extension is "+
"'.ppm', PPM-raw file format is assumed, otherwise PGX file "+
"format is assumed. PGM and PPM files are assumed to be 8 bits "+
"deep. A multi-component image can be specified by either "+
"specifying several PPM and/or PGX files, or by specifying one "+
"PPM file.",null},
new string[] { "o", "<file name>",
"Mandatory argument. This option specifies the name of the output "+
"file to which the codestream will be written.",null},
new string[] { "verbose", null,
"Prints information about the obtained bit stream.","on"},
new string[] { "v", "[on|off]",
"Prints version and copyright information.","off"},
new string[] { "u", "[on|off]",
"Prints usage information. "+
"If specified all other arguments (except 'v') are ignored","off"},
};
#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 Xunit;
using Xunit.Abstractions;
using System;
using System.Collections;
using System.Xml.Schema;
namespace System.Xml.Tests
{
//[TestCase(Name = "TC_SchemaSet_RemoveRecursive", Desc = "")]
public class TC_SchemaSet_RemoveRecursive
{
private ITestOutputHelper _output;
public TC_SchemaSet_RemoveRecursive(ITestOutputHelper output)
{
_output = output;
}
public bool bWarningCallback = false;
public bool bErrorCallback = false;
public void ValidationCallback(object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Warning)
{
_output.WriteLine("WARNING: ");
bWarningCallback = true;
}
else if (args.Severity == XmlSeverityType.Error)
{
_output.WriteLine("ERROR: ");
bErrorCallback = true;
}
_output.WriteLine(args.Message); // Print the error to the screen.
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v1 - RemoveRecursive with null", Priority = 0)]
[InlineData()]
[Theory]
public void v1()
{
try
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.RemoveRecursive(null);
}
catch (ArgumentNullException)
{
// GLOBALIZATION
return;
}
Assert.True(false);
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v2 - RemoveRecursive with just added schema", Priority = 0)]
[InlineData()]
[Theory]
public void v2()
{
XmlSchemaSet sc = new XmlSchemaSet();
//remove after compile
XmlSchema Schema1 = sc.Add(null, TestData._XsdAuthor);
sc.Compile();
sc.RemoveRecursive(Schema1);
CError.Compare(sc.Count, 0, "Count");
ICollection Col = sc.Schemas();
CError.Compare(Col.Count, 0, "ICollection.Count");
//remove before compile
Schema1 = sc.Add(null, TestData._XsdAuthor);
sc.RemoveRecursive(Schema1);
CError.Compare(sc.Count, 0, "Count");
Col = sc.Schemas();
CError.Compare(Col.Count, 0, "ICollection.Count"); return;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v3 - RemoveRecursive first added schema, check the rest")]
[InlineData()]
[Theory]
public void v3()
{
XmlSchemaSet sc = new XmlSchemaSet();
XmlSchema Schema1 = sc.Add(null, TestData._XsdAuthor);
XmlSchema Schema2 = sc.Add("test", TestData._XsdNoNs);
sc.Compile();
sc.RemoveRecursive(Schema1);
CError.Compare(sc.Count, 1, "Count");
ICollection Col = sc.Schemas();
CError.Compare(Col.Count, 1, "ICollection.Count");
CError.Compare(sc.Contains("test"), true, "Contains");
return;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v4.6 - RemoveRecursive A(ns-a) include B(ns-a) which includes C(ns-a) ", Priority = 1, Params = new object[] { "include_v7_a.xsd" })]
[InlineData("include_v7_a.xsd")]
//[Variation(Desc = "v4.5 - RemoveRecursive: A with NS includes B and C with no NS", Priority = 1, Params = new object[] { "include_v6_a.xsd" })]
[InlineData("include_v6_a.xsd")]
//[Variation(Desc = "v4.4 - RemoveRecursive: A with NS includes B and C with no NS, B also includes C", Priority = 1, Params = new object[] { "include_v5_a.xsd" })]
[InlineData("include_v5_a.xsd")]
//[Variation(Desc = "v4.3 - RemoveRecursive: A with NS includes B with no NS, which includes C with no NS", Priority = 1, Params = new object[] { "include_v4_a.xsd" })]
[InlineData("include_v4_a.xsd")]
//[Variation(Desc = "v4.2 - RemoveRecursive: A with no NS includes B with no NS", Params = new object[] { "include_v3_a.xsd" })]
[InlineData("include_v3_a.xsd")]
//[Variation(Desc = "v4.1 - RemoveRecursive: A with NS includes B with no NS", Params = new object[] { "include_v1_a.xsd", })]
[InlineData("include_v1_a.xsd")]
[Theory]
public void v4(string fileName)
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
try
{
// remove after compile
XmlSchema Schema1 = sc.Add(null, TestData._XsdAuthor);
XmlSchema Schema2 = sc.Add(null, TestData._Root + fileName); // param as filename
sc.Compile();
sc.RemoveRecursive(Schema2);
CError.Compare(sc.Count, 1, "Count");
ICollection Col = sc.Schemas();
CError.Compare(Col.Count, 1, "ICollection.Count");
//remove before compile
Schema2 = sc.Add(null, TestData._Root + fileName); // param as filename
CError.Compare(sc.Count, 2, "Count");
sc.RemoveRecursive(Schema2);
CError.Compare(sc.Count, 1, "Count");
Col = sc.Schemas();
CError.Compare(Col.Count, 1, "ICollection.Count");
}
catch (Exception e)
{
_output.WriteLine(e.ToString());
Assert.True(false);
}
return;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v5.2 - Remove: A(ns-a) improts B (ns-b)", Priority = 1, Params = new object[] { "import_v2_a.xsd", 1 })]
[InlineData("import_v2_a.xsd", 1)]
//[Variation(Desc = "v5.1 - Remove: A with NS imports B with no NS", Priority = 1, Params = new object[] { "import_v1_a.xsd", 1 })]
[InlineData("import_v1_a.xsd", 1)]
[Theory]
public void v5(object param0, object param1)
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
try
{
XmlSchema Schema1 = sc.Add(null, TestData._XsdAuthor);
//remove after compile
XmlSchema Schema2 = sc.Add(null, TestData._Root + param0.ToString()); // param as filename
sc.Compile();
sc.RemoveRecursive(Schema2);
CError.Compare(sc.Count, param1, "Count");
ICollection Col = sc.Schemas();
CError.Compare(Col.Count, param1, "ICollection.Count");
//remove before compile
Schema2 = sc.Add(null, TestData._Root + param0.ToString()); // param as filename
sc.RemoveRecursive(Schema2);
CError.Compare(sc.Count, param1, "Count");
Col = sc.Schemas();
CError.Compare(Col.Count, param1, "ICollection.Count");
}
catch (Exception e)
{
_output.WriteLine(e.ToString());
Assert.True(false);
}
return;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v6 - Remove: Add B(NONS) to a namespace, Add A(ns-a) which imports B, Remove B(ns-b) then A(ns-a)", Priority = 1)]
[InlineData()]
[Theory]
public void v6()
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
try
{
//after compile
XmlSchema Schema1 = sc.Add("ns-b", TestData._Root + "import_v4_b.xsd");
XmlSchema Schema2 = sc.Add(null, TestData._Root + "import_v5_a.xsd"); // param as filename
sc.Compile();
sc.RemoveRecursive(Schema1);
CError.Compare(sc.Count, 2, "Count");
CError.Compare(sc.Contains("ns-b"), false, "Contains");
CError.Compare(sc.Contains(String.Empty), true, "Contains");
CError.Compare(sc.Contains("ns-a"), true, "Contains");
sc.RemoveRecursive(Schema2);
ICollection Col = sc.Schemas();
CError.Compare(Col.Count, 0, "ICollection.Count");
CError.Compare(sc.Contains("ns-b"), false, "Contains");
CError.Compare(sc.Contains(String.Empty), false, "Contains");
CError.Compare(sc.Contains("ns-a"), false, "Contains");
//before compile
Schema1 = sc.Add("ns-b", TestData._Root + "import_v4_b.xsd");
Schema2 = sc.Add(null, TestData._Root + "import_v5_a.xsd"); // param as filename
sc.RemoveRecursive(Schema1);
CError.Compare(sc.Count, 2, "Count");
CError.Compare(sc.Contains("ns-b"), false, "Contains");
CError.Compare(sc.Contains(String.Empty), true, "Contains");
CError.Compare(sc.Contains("ns-a"), true, "Contains");
sc.RemoveRecursive(Schema2);
Col = sc.Schemas();
CError.Compare(Col.Count, 0, "ICollection.Count");
CError.Compare(sc.Contains("ns-b"), false, "Contains");
CError.Compare(sc.Contains(String.Empty), false, "Contains");
CError.Compare(sc.Contains("ns-a"), false, "Contains");
}
catch (Exception e)
{
_output.WriteLine(e.ToString());
Assert.True(false);
}
return;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v7.2 - Remove: A(ns-a) imports B(NO NS) imports C (ns-c)", Priority = 1, Params = new object[] { "import_v10_a.xsd", "ns-a", "", "ns-c" })]
[InlineData("import_v10_a.xsd", "ns-a", "", "ns-c")]
//[Variation(Desc = "v7.1 - Remove: A(ns-a) imports B(ns-b) imports C (ns-c)", Priority = 1, Params = new object[] { "import_v9_a.xsd", "ns-a", "ns-b", "ns-c" })]
[InlineData("import_v9_a.xsd", "ns-a", "ns-b", "ns-c")]
[Theory]
public void v7(object param0, object param1, object param2, object param3)
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
try
{
//after compile
XmlSchema Schema1 = sc.Add(null, TestData._Root + param0.ToString());
sc.Compile();
CError.Compare(sc.Count, 3, "Count");
sc.RemoveRecursive(Schema1);
CError.Compare(sc.Count, 0, "Count");
CError.Compare(sc.Contains(param1.ToString()), false, "Contains");
CError.Compare(sc.Contains(param2.ToString()), false, "Contains");
CError.Compare(sc.Contains(param3.ToString()), false, "Contains");
//before compile
Schema1 = sc.Add(null, TestData._Root + param0.ToString());
CError.Compare(sc.Count, 3, "Count");
sc.RemoveRecursive(Schema1);
CError.Compare(sc.Count, 0, "Count");
CError.Compare(sc.Contains(param1.ToString()), false, "Contains");
CError.Compare(sc.Contains(param2.ToString()), false, "Contains");
CError.Compare(sc.Contains(param3.ToString()), false, "Contains");
}
catch (Exception e)
{
_output.WriteLine(e.ToString());
Assert.True(false);
}
return;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v8 - Remove: A imports B and B and C, B imports C and D, C imports D and A", Priority = 1, Params = new object[] { "import_v13_a.xsd" })]
[InlineData("import_v13_a.xsd")]
[Theory]
public void v8(object param0)
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
try
{
//after compile
XmlSchema Schema1 = sc.Add(null, TestData._Root + param0.ToString());
sc.Compile();
CError.Compare(sc.Count, 4, "Count");
sc.RemoveRecursive(Schema1);
CError.Compare(sc.Count, 0, "Count");
CError.Compare(sc.Contains("ns-d"), false, "Contains");
CError.Compare(sc.Contains("ns-c"), false, "Contains");
CError.Compare(sc.Contains("ns-b"), false, "Contains");
CError.Compare(sc.Contains("ns-a"), false, "Contains");
//before compile
Schema1 = sc.Add(null, TestData._Root + param0.ToString());
CError.Compare(sc.Count, 4, "Count");
sc.RemoveRecursive(Schema1);
CError.Compare(sc.Count, 0, "Count");
CError.Compare(sc.Contains("ns-d"), false, "Contains");
CError.Compare(sc.Contains("ns-c"), false, "Contains");
CError.Compare(sc.Contains("ns-b"), false, "Contains");
CError.Compare(sc.Contains("ns-a"), false, "Contains");
}
catch (Exception e)
{
_output.WriteLine(e.ToString());
Assert.True(false);
}
return;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v9 - Import: B(ns-b) added, A(ns-a) imports B's NS", Priority = 2)]
[InlineData()]
[Theory]
public void v9()
{
try
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.Add(null, TestData._Root + "import_v16_b.xsd");
//before compile
XmlSchema parent = sc.Add(null, TestData._Root + "import_v16_a.xsd");
sc.Compile();
sc.RemoveRecursive(parent);
CError.Compare(sc.Count, 1, "Count");
CError.Compare(sc.Contains("ns-b"), true, "Contains");
//after compile
parent = sc.Add(null, TestData._Root + "import_v16_a.xsd");
sc.RemoveRecursive(parent);
CError.Compare(sc.Count, 1, "Count");
CError.Compare(sc.Contains("ns-b"), true, "Contains");
return;
}
catch (XmlSchemaException e)
{
_output.WriteLine("Exception : " + e.Message);
}
Assert.True(false);
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v10.8 - Remove: A imports B and B and C, B imports C and D, C imports D and A, E imports A's NS, Remove A", Priority = 1, Params = new object[] { "import_v13_a.xsd", "remove_v10_e8.xsd" })]
[InlineData("import_v13_a.xsd", "remove_v10_e8.xsd")]
//[Variation(Desc = "v10.7 - Remove: A imports B and B and C, B imports C and D, C imports D and A, E imports C's NS, Remove A", Priority = 1, Params = new object[] { "import_v13_a.xsd", "remove_v10_e7.xsd" })]
[InlineData("import_v13_a.xsd", "remove_v10_e7.xsd")]
//[Variation(Desc = "v10.6 - Remove: A imports B and B and C, B imports C and D, C imports D and A, E imports D's NS, Remove A", Priority = 1, Params = new object[] { "import_v13_a.xsd", "remove_v10_e6.xsd" })]
[InlineData("import_v13_a.xsd", "remove_v10_e6.xsd")]
//[Variation(Desc = "v10.5 - Remove: A imports B and B and C, B imports C and D, C imports D and A, E imports B's NS, Remove A", Priority = 1, Params = new object[] { "import_v13_a.xsd", "remove_v10_e5.xsd" })]
[InlineData("import_v13_a.xsd", "remove_v10_e5.xsd")]
//[Variation(Desc = "v10.4 - Remove: A imports B and B and C, B imports C and D, C imports D and A, E imports A, Remove A", Priority = 1, Params = new object[] { "import_v13_a.xsd", "remove_v10_e4.xsd" })]
[InlineData("import_v13_a.xsd", "remove_v10_e4.xsd")]
//[Variation(Desc = "v10.3 - Remove: A imports B and B and C, B imports C and D, C imports D and A, E imports C, Remove A", Priority = 1, Params = new object[] { "import_v13_a.xsd", "remove_v10_e3.xsd" })]
[InlineData("import_v13_a.xsd", "remove_v10_e3.xsd")]
//[Variation(Desc = "v10.2 - Remove: A imports B and B and C, B imports C and D, C imports D and A, E imports D, Remove A", Priority = 1, Params = new object[] { "import_v13_a.xsd", "remove_v10_e2.xsd" })]
[InlineData("import_v13_a.xsd", "remove_v10_e2.xsd")]
//[Variation(Desc = "v10.1 - Remove: A imports B and B and C, B imports C and D, C imports D and A, E imports B, Remove A", Priority = 1, Params = new object[] { "import_v13_a.xsd", "remove_v10_e1.xsd" })]
[InlineData("import_v13_a.xsd", "remove_v10_e1.xsd")]
[Theory]
public void v10(object param0, object param1)
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
sc.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
bWarningCallback = false;
bErrorCallback = false;
try
{
//after compile
XmlSchema Schema1 = sc.Add(null, TestData._Root + param0.ToString());
XmlSchema Schema2 = sc.Add(null, TestData._Root + param1.ToString());
sc.Compile();
CError.Compare(sc.Count, 5, "Count");
sc.RemoveRecursive(Schema1);
CError.Compare(sc.Count, 5, "Count");
CError.Compare(bWarningCallback, true, "Warning Callback");
CError.Compare(bErrorCallback, false, "Error Callback");
//reinit
bWarningCallback = false;
bErrorCallback = false;
sc.Remove(Schema2);
sc.RemoveRecursive(Schema1);
CError.Compare(sc.Count, 0, "Count");
CError.Compare(bWarningCallback, false, "Warning Callback");
CError.Compare(bErrorCallback, false, "Error Callback");
//before compile
Schema1 = sc.Add(null, TestData._Root + param0.ToString());
Schema2 = sc.Add(null, TestData._Root + param1.ToString());
CError.Compare(sc.Count, 5, "Count");
sc.RemoveRecursive(Schema1);
CError.Compare(sc.Count, 5, "Count");
CError.Compare(bWarningCallback, true, "Warning Callback");
CError.Compare(bErrorCallback, false, "Error Callback");
}
catch (Exception e)
{
_output.WriteLine(e.ToString());
Assert.True(false);
}
return;
}
//[Variation(Desc = "v11 - Remove: A imports B and C, B imports C, C imports B and D, Remove A", Priority = 1, Params = new object[] { "remove_v11_a.xsd" })]
[InlineData("remove_v11_a.xsd")]
[Theory]
public void v11(object param0)
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
sc.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
bWarningCallback = false;
bErrorCallback = false;
try
{
//after compile
XmlSchema Schema1 = sc.Add(null, TestData._Root + param0.ToString());
sc.Compile();
CError.Compare(sc.Count, 4, "Count");
sc.RemoveRecursive(Schema1);
sc.Compile();
CError.Compare(sc.Count, 0, "Count");
CError.Compare(sc.GlobalElements.Count, 0, "Global Elements Count");
CError.Compare(sc.GlobalTypes.Count, 0, "Global Types Count");//should contain xs:anyType
//before compile
Schema1 = sc.Add(null, TestData._Root + param0.ToString());
CError.Compare(sc.Count, 4, "Count");
sc.RemoveRecursive(Schema1);
CError.Compare(sc.Count, 0, "Count");
CError.Compare(sc.GlobalElements.Count, 0, "Global Elements Count");
CError.Compare(sc.GlobalTypes.Count, 0, "Global Types Count"); //should contain xs:anyType
}
catch (Exception e)
{
_output.WriteLine(e.ToString());
Assert.True(false);
}
return;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Hjson
{
using JsonPair=KeyValuePair<string, JsonValue>;
internal class HjsonWriter
{
bool writeWsc;
bool emitRootBraces;
IEnumerable<IHjsonDsfProvider> dsfProviders=Enumerable.Empty<IHjsonDsfProvider>();
static Regex needsEscapeName=new Regex(@"[,\{\[\}\]\s:#""']|\/\/|\/\*|'''");
public HjsonWriter(HjsonOptions options)
{
if (options!=null)
{
writeWsc=options.KeepWsc;
emitRootBraces=options.EmitRootBraces;
dsfProviders=options.DsfProviders;
}
else emitRootBraces=true;
}
void nl(TextWriter tw, int level)
{
tw.Write(JsonValue.eol);
tw.Write(new string(' ', level*2));
}
string getWsc(string str)
{
if (string.IsNullOrEmpty(str)) return "";
for (int i=0; i<str.Length; i++)
{
char c=str[i];
if (c=='\n' ||
c=='#' ||
c=='/' && i+1<str.Length && (str[i+1]=='/' || str[i+1]=='*')) break;
if (c>' ') return " # "+str;
}
return str;
}
string getWsc(Dictionary<string, string> white, string key) { return white.ContainsKey(key)?getWsc(white[key]):""; }
string getWsc(List<string> white, int index) { return white.Count>index?getWsc(white[index]):""; }
bool testWsc(string str) { return str.Length>0 && str[str[0]=='\r' && str.Length>1?1:0]!='\n'; }
public void Save(JsonValue value, TextWriter tw, int level, bool hasComment, string separator, bool noIndent=false, bool isRootObject=false)
{
if (value==null)
{
tw.Write(separator);
tw.Write("null");
return;
}
// check for DSF
string dsfValue=HjsonDsf.Stringify(dsfProviders, value);
if (dsfValue!=null)
{
tw.Write(separator);
tw.Write(dsfValue);
return;
}
switch (value.JsonType)
{
case JsonType.Object:
var obj=value.Qo();
WscJsonObject kw=writeWsc?obj as WscJsonObject:null;
bool showBraces=!isRootObject || (kw!=null?kw.RootBraces:emitRootBraces);
if (!noIndent) { if (obj.Count>0) nl(tw, level); else tw.Write(separator); }
if (showBraces) tw.Write('{');
else level--; // reduce level for root
if (kw!=null)
{
var kwl=getWsc(kw.Comments, "");
foreach (string key in kw.Order.Concat(kw.Keys).Distinct())
{
if (!obj.ContainsKey(key)) continue;
var val=obj[key];
tw.Write(kwl);
nl(tw, level+1);
kwl=getWsc(kw.Comments, key);
tw.Write(escapeName(key));
tw.Write(":");
Save(val, tw, level+1, testWsc(kwl), " ");
}
tw.Write(kwl);
if (showBraces) nl(tw, level);
}
else
{
bool skipFirst=!showBraces;
foreach (JsonPair pair in obj)
{
if (!skipFirst) nl(tw, level+1); else skipFirst=false;
tw.Write(escapeName(pair.Key));
tw.Write(":");
Save(pair.Value, tw, level+1, false, " ");
}
if (showBraces && obj.Count>0) nl(tw, level);
}
if (showBraces) tw.Write('}');
break;
case JsonType.Array:
int i=0, n=value.Count;
if (!noIndent) { if (n>0) nl(tw, level); else tw.Write(separator); }
tw.Write('[');
WscJsonArray whiteL=null;
string wsl=null;
if (writeWsc)
{
whiteL=value as WscJsonArray;
if (whiteL!=null) wsl=getWsc(whiteL.Comments, 0);
}
for (; i<n; i++)
{
var v=value[i];
if (whiteL!=null)
{
tw.Write(wsl);
wsl=getWsc(whiteL.Comments, i+1);
}
nl(tw, level+1);
Save(v, tw, level+1, wsl!=null && testWsc(wsl), "", true);
}
if (whiteL!=null) tw.Write(wsl);
if (n>0) nl(tw, level);
tw.Write(']');
break;
case JsonType.Boolean:
tw.Write(separator);
tw.Write((bool)value?"true":"false");
break;
case JsonType.String:
writeString(((JsonPrimitive)value).GetRawString(), tw, level, hasComment, separator);
break;
default:
tw.Write(separator);
tw.Write(((JsonPrimitive)value).GetRawString());
break;
}
}
static string escapeName(string name)
{
if (name.Length==0 || needsEscapeName.IsMatch(name))
return "\""+JsonWriter.EscapeString(name)+"\"";
else
return name;
}
void writeString(string value, TextWriter tw, int level, bool hasComment, string separator)
{
if (value=="") { tw.Write(separator+"\"\""); return; }
char left=value[0], right=value[value.Length-1];
char left1=value.Length>1?value[1]:'\0', left2=value.Length>2?value[2]:'\0';
bool doEscape=hasComment || value.Any(c => needsQuotes(c));
JsonValue dummy;
if (doEscape ||
BaseReader.IsWhite(left) || BaseReader.IsWhite(right) ||
left=='"' ||
left=='\'' ||
left=='#' ||
left=='/' && (left1=='*' || left1=='/') ||
HjsonValue.IsPunctuatorChar(left) ||
HjsonReader.TryParseNumericLiteral(value, true, out dummy) ||
startsWithKeyword(value))
{
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we first check if the string can be expressed in multiline
// format or we must replace the offending characters with safe escape
// sequences.
if (!value.Any(c => needsEscape(c))) tw.Write(separator+"\""+value+"\"");
else if (!value.Any(c => needsEscapeML(c)) && !value.Contains("'''") && !value.All(c => BaseReader.IsWhite(c))) writeMLString(value, tw, level, separator);
else tw.Write(separator+"\""+JsonWriter.EscapeString(value)+"\"");
}
else tw.Write(separator+value);
}
void writeMLString(string value, TextWriter tw, int level, string separator)
{
var lines=value.Replace("\r", "").Split('\n');
if (lines.Length==1)
{
tw.Write(separator+"'''");
tw.Write(lines[0]);
tw.Write("'''");
}
else
{
level++;
nl(tw, level);
tw.Write("'''");
foreach (var line in lines)
{
nl(tw, !string.IsNullOrEmpty(line)?level:0);
tw.Write(line);
}
nl(tw, level);
tw.Write("'''");
}
}
static bool startsWithKeyword(string text)
{
int p;
if (text.StartsWith("true") || text.StartsWith("null")) p=4;
else if (text.StartsWith("false")) p=5;
else return false;
while (p<text.Length && BaseReader.IsWhite(text[p])) p++;
if (p==text.Length) return true;
char ch=text[p];
return ch==',' || ch=='}' || ch==']' || ch=='#' || ch=='/' && (text.Length>p+1 && (text[p+1]=='/' || text[p+1]=='*'));
}
static bool needsQuotes(char c)
{
switch (c)
{
case '\t':
case '\f':
case '\b':
case '\n':
case '\r':
return true;
default:
return false;
}
}
static bool needsEscape(char c)
{
switch (c)
{
case '\"':
case '\\':
return true;
default:
return needsQuotes(c);
}
}
static bool needsEscapeML(char c)
{
switch (c)
{
case '\n':
case '\r':
case '\t':
return false;
default:
return needsQuotes(c);
}
}
}
}
| |
#region Foreign-License
/*
Copyright (c) 1997 Sun Microsystems, Inc.
Copyright (c) 2012 Sky Morey
See the file "license.terms" for information on usage and redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
*/
#endregion
using System;
using System.Text;
namespace Tcl.Lang
{
/// <summary> This class implements the basic notion of an "object" in Tcl. The
/// fundamental representation of an object is its string value. However,
/// an object can also have an internal representation, which is a "cached"
/// reprsentation of this object in another form. The type of the internal
/// rep of Tcl objects can mutate. This class provides the storage of the
/// string rep and the internal rep, as well as the facilities for mutating
/// the internal rep.
/// </summary>
public class TclObject
{
/// <summary> Returns the handle to the current internal rep. This method should be
/// called only by an InternalRep implementation.
/// the handle to the current internal rep.
/// Change the internal rep of the object. The old internal rep
/// will be deallocated as a result. This method should be
/// called only by an InternalRep implementation.
/// </summary>
/// <param name="rep">the new internal rep.
/// </param>
public IInternalRep InternalRep
{
get
{
disposedCheck();
return internalRep;
}
set
{
disposedCheck();
if (value == null)
{
throw new TclRuntimeError("null InternalRep");
}
if (value == internalRep)
{
return;
}
// In the special case where the internal representation is a CObject,
// we want to call the special interface to convert the underlying
// native object into a reference to the Java TclObject. Note that
// this test will always fail if we are not using the native
// implementation. Also note that the makeReference method
// will do nothing in the case where the Tcl_Obj inside the
// CObject was originally allocated in Java. When converting
// to a CObject we need to break the link made earlier.
if ((internalRep is CObject) && !(value is CObject))
{
// We must ensure that the string rep is copied into Java
// before we lose the reference to the underlying CObject.
// Otherwise we will lose the original string information
// when the backpointer is lost.
if ((System.Object)stringRep == null)
{
stringRep = internalRep.ToString();
}
((CObject)internalRep).MakeReference(this);
}
//System.out.println("TclObject setInternalRep for \"" + stringRep + "\"");
//System.out.println("from \"" + internalRep.getClass().getName() +
// "\" to \"" + rep.getClass().getName() + "\"");
internalRep.Dispose();
internalRep = value;
}
}
/// <summary> Returns true if the TclObject is shared, false otherwise.</summary>
/// <returns> true if the TclObject is shared, false otherwise.
/// </returns>
public bool Shared
{
get
{
disposedCheck();
return (refCount > 1);
}
}
/// <summary> Returns the refCount of this object.
///
/// </summary>
/// <returns> refCount.
/// </returns>
public int RefCount
{
get
{
return refCount;
}
}
/// <summary> Returns the Tcl_Obj* objPtr member for a CObject or TclList.
/// This method is only called from Tcl Blend.
/// </summary>
internal long CObjectPtr
{
get
{
if (internalRep is CObject)
{
return ((CObject)internalRep).CObjectPtr;
}
else
{
return 0;
}
}
}
/// <summary> Returns 2 if the internal rep is a TclList.
/// Returns 1 if the internal rep is a CObject.
/// Otherwise returns 0.
/// This method provides an optimization over
/// invoking getInternalRep() and two instanceof
/// checks via JNI. It is only used by Tcl Blend.
/// </summary>
internal int CObjectInst
{
get
{
if (internalRep is CObject)
{
if (internalRep is TclList)
return 2;
else
return 1;
}
else
{
return 0;
}
}
}
// Internal representation of the object.
protected internal IInternalRep internalRep;
// Reference count of this object. When 0 the object will be deallocated.
protected internal int refCount;
// String representation of the object.
protected internal string stringRep;
// Return true if the TclObject contains a TclList.
public bool isListType()
{
return (internalRep.GetType().ToString().Contains("TclList"));
}
/// <summary> Creates a TclObject with the given InternalRep. This method should be
/// called only by an InternalRep implementation.
///
/// </summary>
/// <param name="rep">the initial InternalRep for this object.
/// </param>
public TclObject(IInternalRep rep)
{
if (rep == null)
{
throw new TclRuntimeError("null InternalRep");
}
internalRep = rep;
stringRep = null;
refCount = 0;
}
/// <summary> Creates a TclObject with the given InternalRep and stringRep.
/// This constructor is used by the TclString class only. No other place
/// should call this constructor.
///
/// </summary>
/// <param name="rep">the initial InternalRep for this object.
/// </param>
/// <param name="s">the initial string rep for this object.
/// </param>
protected internal TclObject(TclString rep, string s)
{
if (rep == null)
{
throw new TclRuntimeError("null InternalRep");
}
internalRep = rep;
stringRep = s;
refCount = 0;
}
/// <summary> Returns the string representation of the object.
///
/// </summary>
/// <returns> the string representation of the object.
/// </returns>
public override string ToString()
{
disposedCheck();
if ((System.Object)stringRep == null)
{
stringRep = internalRep.ToString().Replace("Infinity", "inf");
}
return stringRep;
}
/// <summary> Returns the UTF8 byte representation of the object.
///
/// </summary>
/// <returns> the string representation of the object.
/// </returns>
public byte[] ToBytes()
{
disposedCheck();
if ((System.Object)stringRep == null)
{
stringRep = internalRep.ToString();
}
return Encoding.UTF8.GetBytes(stringRep);
}
/// <summary> Sets the string representation of the object to null. Next
/// time when toString() is called, getInternalRep().toString() will
/// be called. This method should be called ONLY when an InternalRep
/// is about to modify the value of a TclObject.
///
/// </summary>
/// <exception cref=""> TclRuntimeError if object is not exclusively owned.
/// </exception>
public void invalidateStringRep()
{
disposedCheck();
if (refCount > 1)
{
throw new TclRuntimeError("string representation of object \"" + ToString() + "\" cannot be invalidated: refCount = " + refCount);
}
stringRep = null;
}
/// <summary> Tcl_DuplicateObj -> duplicate
///
/// Duplicate a TclObject, this method provides the preferred
/// means to deal with modification of a shared TclObject.
/// It should be invoked in conjunction with isShared instead
/// of using the deprecated takeExclusive method.
///
/// Example:
///
/// if (tobj.isShared()) {
/// tobj = tobj.duplicate();
/// }
/// TclString.append(tobj, "hello");
///
/// </summary>
/// <returns> an TclObject with a refCount of 0.
/// </returns>
public TclObject duplicate()
{
disposedCheck();
if (internalRep is TclString)
{
if ((System.Object)stringRep == null)
{
stringRep = internalRep.ToString();
}
}
TclObject newObj = new TclObject(internalRep.Duplicate());
newObj.stringRep = this.stringRep;
newObj.refCount = 0;
return newObj;
}
/// <deprecated> The takeExclusive method has been deprecated
/// in favor of the new duplicate() method. The takeExclusive
/// method would modify the ref count of the original object
/// and return an object with a ref count of 1 instead of 0.
/// These two behaviors lead to lots of useless duplication
/// of objects that could be modified directly.
/// </deprecated>
public TclObject takeExclusive()
{
disposedCheck();
if (refCount == 1)
{
return this;
}
else if (refCount > 1)
{
if (internalRep is TclString)
{
if ((System.Object)stringRep == null)
{
stringRep = internalRep.ToString();
}
}
TclObject newObj = new TclObject(internalRep.Duplicate());
newObj.stringRep = this.stringRep;
newObj.refCount = 1;
refCount--;
return newObj;
}
else
{
throw new TclRuntimeError("takeExclusive() called on object \"" + ToString() + "\" with: refCount = 0");
}
}
/// <summary> Tcl_IncrRefCount -> preserve
///
/// Increments the refCount to indicate the caller's intent to
/// preserve the value of this object. Each preserve() call must be matched
/// by a corresponding release() call.
///
/// </summary>
/// <exception cref=""> TclRuntimeError if the object has already been deallocated.
/// </exception>
public void Preserve()
{
disposedCheck();
if (internalRep is CObject)
{
((CObject)internalRep).IncrRefCount();
}
_preserve();
}
/// <summary> _preserve
///
/// Private implementation of preserve() method.
/// This method will be invoked from Native code
/// to change the TclObject's ref count without
/// effecting the ref count of a CObject.
/// </summary>
private void _preserve()
{
refCount++;
}
/// <summary> Tcl_DecrRefCount -> release
///
/// Decrements the refCount to indicate that the caller is no longer
/// interested in the value of this object. If the refCount reaches 0,
/// the obejct will be deallocated.
/// </summary>
public void Release()
{
disposedCheck();
if (internalRep is CObject)
{
((CObject)internalRep).DecrRefCount();
}
_release();
}
/// <summary> _release
///
/// Private implementation of preserve() method.
/// This method will be invoked from Native code
/// to change the TclObject's ref count without
/// effecting the ref count of a CObject.
/// </summary>
private void _release()
{
refCount--;
if (refCount <= 0)
{
internalRep.Dispose();
// Setting these to null will ensure that any attempt to use
// this object will result in a Java NullPointerException.
internalRep = null;
stringRep = null;
}
}
/// <summary> Raise a TclRuntimeError if this TclObject has been
/// disposed of before the last ref was released.
/// </summary>
private void disposedCheck()
{
if (internalRep == null)
{
throw new TclRuntimeError("TclObject has been deallocated");
}
}
/// <summary> Return string describing type.</summary>
public string typePtr
{
get
{
if (this.internalRep == null)
return "null";
string sType = this.internalRep.GetType().ToString().Replace("tcl.lang.Tcl", "").ToLower();
if (sType == "integer")
return "int";
if (sType == "long")
return "int";
return sType;
}
}
}
}
| |
// 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 Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// RouteFilterRulesOperations operations.
/// </summary>
internal partial class RouteFilterRulesOperations : IServiceOperations<NetworkManagementClient>, IRouteFilterRulesOperations
{
/// <summary>
/// Initializes a new instance of the RouteFilterRulesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal RouteFilterRulesOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// Deletes the specified rule from a route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the rule.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, routeFilterName, ruleName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified rule from a route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the rule.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<RouteFilterRule>> GetWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeFilterName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterName");
}
if (ruleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "ruleName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-06-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeFilterName", routeFilterName);
tracingParameters.Add("ruleName", ruleName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeFilterName}", System.Uri.EscapeDataString(routeFilterName));
_url = _url.Replace("{ruleName}", System.Uri.EscapeDataString(ruleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<RouteFilterRule>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<RouteFilterRule>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a route in the specified route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the route filter rule.
/// </param>
/// <param name='routeFilterRuleParameters'>
/// Parameters supplied to the create or update route filter rule operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<RouteFilterRule>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, RouteFilterRule routeFilterRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<RouteFilterRule> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Updates a route in the specified route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the route filter rule.
/// </param>
/// <param name='routeFilterRuleParameters'>
/// Parameters supplied to the update route filter rule operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<RouteFilterRule>> UpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, PatchRouteFilterRule routeFilterRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<RouteFilterRule> _response = await BeginUpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all RouteFilterRules in a route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<RouteFilterRule>>> ListByRouteFilterWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeFilterName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-06-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeFilterName", routeFilterName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByRouteFilter", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeFilterName}", System.Uri.EscapeDataString(routeFilterName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RouteFilterRule>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RouteFilterRule>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified rule from a route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the rule.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeFilterName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterName");
}
if (ruleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "ruleName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-06-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeFilterName", routeFilterName);
tracingParameters.Add("ruleName", ruleName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeFilterName}", System.Uri.EscapeDataString(routeFilterName));
_url = _url.Replace("{ruleName}", System.Uri.EscapeDataString(ruleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202 && (int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a route in the specified route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the route filter rule.
/// </param>
/// <param name='routeFilterRuleParameters'>
/// Parameters supplied to the create or update route filter rule operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<RouteFilterRule>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, RouteFilterRule routeFilterRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeFilterName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterName");
}
if (ruleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "ruleName");
}
if (routeFilterRuleParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterRuleParameters");
}
if (routeFilterRuleParameters != null)
{
routeFilterRuleParameters.Validate();
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (routeFilterRuleParameters == null)
{
routeFilterRuleParameters = new RouteFilterRule();
}
string apiVersion = "2017-06-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeFilterName", routeFilterName);
tracingParameters.Add("ruleName", ruleName);
tracingParameters.Add("routeFilterRuleParameters", routeFilterRuleParameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeFilterName}", System.Uri.EscapeDataString(routeFilterName));
_url = _url.Replace("{ruleName}", System.Uri.EscapeDataString(ruleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(routeFilterRuleParameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(routeFilterRuleParameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<RouteFilterRule>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<RouteFilterRule>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<RouteFilterRule>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Updates a route in the specified route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the route filter rule.
/// </param>
/// <param name='routeFilterRuleParameters'>
/// Parameters supplied to the update route filter rule operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<RouteFilterRule>> BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, PatchRouteFilterRule routeFilterRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeFilterName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterName");
}
if (ruleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "ruleName");
}
if (routeFilterRuleParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterRuleParameters");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (routeFilterRuleParameters == null)
{
routeFilterRuleParameters = new PatchRouteFilterRule();
}
string apiVersion = "2017-06-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeFilterName", routeFilterName);
tracingParameters.Add("ruleName", ruleName);
tracingParameters.Add("routeFilterRuleParameters", routeFilterRuleParameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeFilterName}", System.Uri.EscapeDataString(routeFilterName));
_url = _url.Replace("{ruleName}", System.Uri.EscapeDataString(ruleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(routeFilterRuleParameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(routeFilterRuleParameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<RouteFilterRule>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<RouteFilterRule>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all RouteFilterRules in a route filter.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<RouteFilterRule>>> ListByRouteFilterNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByRouteFilterNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RouteFilterRule>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RouteFilterRule>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections;
using System.Globalization;
using System.Reflection;
using System.Text;
using log4net.Core;
using log4net.Util.TypeConverters;
namespace log4net.Util
{
/// <summary>
/// A convenience class to convert property values to specific types.
/// </summary>
/// <remarks>
/// <para>
/// Utility functions for converting types and parsing values.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public sealed class OptionConverter
{
#region Private Instance Constructors
/// <summary>
/// Initializes a new instance of the <see cref="OptionConverter" /> class.
/// </summary>
/// <remarks>
/// <para>
/// Uses a private access modifier to prevent instantiation of this class.
/// </para>
/// </remarks>
private OptionConverter()
{
}
#endregion Private Instance Constructors
#region Public Static Methods
// /// <summary>
// /// Concatenates two string arrays.
// /// </summary>
// /// <param name="l">Left array.</param>
// /// <param name="r">Right array.</param>
// /// <returns>Array containing both left and right arrays.</returns>
// public static string[] ConcatenateArrays(string[] l, string[] r)
// {
// return (string[])ConcatenateArrays(l, r);
// }
// /// <summary>
// /// Concatenates two arrays.
// /// </summary>
// /// <param name="l">Left array</param>
// /// <param name="r">Right array</param>
// /// <returns>Array containing both left and right arrays.</returns>
// public static Array ConcatenateArrays(Array l, Array r)
// {
// if (l == null)
// {
// throw new ArgumentNullException("l");
// }
// if (r == null)
// {
// throw new ArgumentNullException("r");
// }
//
// int len = l.Length + r.Length;
// Array a = Array.CreateInstance(l.GetType(), len);
//
// Array.Copy(l, 0, a, 0, l.Length);
// Array.Copy(r, 0, a, l.Length, r.Length);
//
// return a;
// }
// /// <summary>
// /// Converts string escape characters back to their correct values.
// /// </summary>
// /// <param name="s">String to convert.</param>
// /// <returns>Converted result.</returns>
// public static string ConvertSpecialChars(string s)
// {
// if (s == null)
// {
// throw new ArgumentNullException("s");
// }
// char c;
// int len = s.Length;
// StringBuilder buf = new StringBuilder(len);
//
// int i = 0;
// while(i < len)
// {
// c = s[i++];
// if (c == '\\')
// {
// c = s[i++];
// if (c == 'n') c = '\n';
// else if (c == 'r') c = '\r';
// else if (c == 't') c = '\t';
// else if (c == 'f') c = '\f';
// else if (c == '\b') c = '\b';
// else if (c == '\"') c = '\"';
// else if (c == '\'') c = '\'';
// else if (c == '\\') c = '\\';
// }
// buf.Append(c);
// }
// return buf.ToString();
// }
/// <summary>
/// Converts a string to a <see cref="bool" /> value.
/// </summary>
/// <param name="argValue">String to convert.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The <see cref="bool" /> value of <paramref name="argValue" />.</returns>
/// <remarks>
/// <para>
/// If <paramref name="argValue"/> is "true", then <c>true</c> is returned.
/// If <paramref name="argValue"/> is "false", then <c>false</c> is returned.
/// Otherwise, <paramref name="defaultValue"/> is returned.
/// </para>
/// </remarks>
public static bool ToBoolean(string argValue, bool defaultValue)
{
if (argValue != null && argValue.Length > 0)
{
try
{
return bool.Parse(argValue);
}
catch(Exception e)
{
LogLog.Error(declaringType, "[" + argValue + "] is not in proper bool form.", e);
}
}
return defaultValue;
}
// /// <summary>
// /// Converts a string to an integer.
// /// </summary>
// /// <param name="argValue">String to convert.</param>
// /// <param name="defaultValue">The default value.</param>
// /// <returns>The <see cref="int" /> value of <paramref name="argValue" />.</returns>
// /// <remarks>
// /// <para>
// /// <paramref name="defaultValue"/> is returned when <paramref name="argValue"/>
// /// cannot be converted to a <see cref="int" /> value.
// /// </para>
// /// </remarks>
// public static int ToInt(string argValue, int defaultValue)
// {
// if (argValue != null)
// {
// string s = argValue.Trim();
// try
// {
// return int.Parse(s, NumberFormatInfo.InvariantInfo);
// }
// catch (Exception e)
// {
// LogLog.Error(declaringType, "OptionConverter: [" + s + "] is not in proper int form.", e);
// }
// }
// return defaultValue;
// }
/// <summary>
/// Parses a file size into a number.
/// </summary>
/// <param name="argValue">String to parse.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The <see cref="long" /> value of <paramref name="argValue" />.</returns>
/// <remarks>
/// <para>
/// Parses a file size of the form: number[KB|MB|GB] into a
/// long value. It is scaled with the appropriate multiplier.
/// </para>
/// <para>
/// <paramref name="defaultValue"/> is returned when <paramref name="argValue"/>
/// cannot be converted to a <see cref="long" /> value.
/// </para>
/// </remarks>
public static long ToFileSize(string argValue, long defaultValue)
{
if (argValue == null)
{
return defaultValue;
}
string s = argValue.Trim().ToUpper(CultureInfo.InvariantCulture);
long multiplier = 1;
int index;
if ((index = s.IndexOf("KB")) != -1)
{
multiplier = 1024;
s = s.Substring(0, index);
}
else if ((index = s.IndexOf("MB")) != -1)
{
multiplier = 1024 * 1024;
s = s.Substring(0, index);
}
else if ((index = s.IndexOf("GB")) != -1)
{
multiplier = 1024 * 1024 * 1024;
s = s.Substring(0, index);
}
if (s != null)
{
// Try again to remove whitespace between the number and the size specifier
s = s.Trim();
long longVal;
if (SystemInfo.TryParse(s, out longVal))
{
return longVal * multiplier;
}
else
{
LogLog.Error(declaringType, "OptionConverter: ["+ s +"] is not in the correct file size syntax.");
}
}
return defaultValue;
}
/// <summary>
/// Converts a string to an object.
/// </summary>
/// <param name="target">The target type to convert to.</param>
/// <param name="txt">The string to convert to an object.</param>
/// <returns>
/// The object converted from a string or <c>null</c> when the
/// conversion failed.
/// </returns>
/// <remarks>
/// <para>
/// Converts a string to an object. Uses the converter registry to try
/// to convert the string value into the specified target type.
/// </para>
/// </remarks>
public static object ConvertStringTo(Type target, string txt)
{
if (target == null)
{
throw new ArgumentNullException("target");
}
// If we want a string we already have the correct type
if (typeof(string) == target || typeof(object) == target)
{
return txt;
}
// First lets try to find a type converter
IConvertFrom typeConverter = ConverterRegistry.GetConvertFrom(target);
if (typeConverter != null && typeConverter.CanConvertFrom(typeof(string)))
{
// Found appropriate converter
return typeConverter.ConvertFrom(txt);
}
else
{
if (target.IsEnum)
{
// Target type is an enum.
// Use the Enum.Parse(EnumType, string) method to get the enum value
return ParseEnum(target, txt, true);
}
else
{
// We essentially make a guess that to convert from a string
// to an arbitrary type T there will be a static method defined on type T called Parse
// that will take an argument of type string. i.e. T.Parse(string)->T we call this
// method to convert the string to the type required by the property.
System.Reflection.MethodInfo meth = target.GetMethod("Parse", new Type[] {typeof(string)});
if (meth != null)
{
// Call the Parse method
return meth.Invoke(null, BindingFlags.InvokeMethod, null, new object[] {txt}, CultureInfo.InvariantCulture);
}
else
{
// No Parse() method found.
}
}
}
return null;
}
// /// <summary>
// /// Looks up the <see cref="IConvertFrom"/> for the target type.
// /// </summary>
// /// <param name="target">The type to lookup the converter for.</param>
// /// <returns>The converter for the specified type.</returns>
// public static IConvertFrom GetTypeConverter(Type target)
// {
// IConvertFrom converter = ConverterRegistry.GetConverter(target);
// if (converter == null)
// {
// throw new InvalidOperationException("No type converter defined for [" + target + "]");
// }
// return converter;
// }
/// <summary>
/// Checks if there is an appropriate type conversion from the source type to the target type.
/// </summary>
/// <param name="sourceType">The type to convert from.</param>
/// <param name="targetType">The type to convert to.</param>
/// <returns><c>true</c> if there is a conversion from the source type to the target type.</returns>
/// <remarks>
/// Checks if there is an appropriate type conversion from the source type to the target type.
/// <para>
/// </para>
/// </remarks>
public static bool CanConvertTypeTo(Type sourceType, Type targetType)
{
if (sourceType == null || targetType == null)
{
return false;
}
// Check if we can assign directly from the source type to the target type
if (targetType.IsAssignableFrom(sourceType))
{
return true;
}
// Look for a To converter
IConvertTo tcSource = ConverterRegistry.GetConvertTo(sourceType, targetType);
if (tcSource != null)
{
if (tcSource.CanConvertTo(targetType))
{
return true;
}
}
// Look for a From converter
IConvertFrom tcTarget = ConverterRegistry.GetConvertFrom(targetType);
if (tcTarget != null)
{
if (tcTarget.CanConvertFrom(sourceType))
{
return true;
}
}
return false;
}
/// <summary>
/// Converts an object to the target type.
/// </summary>
/// <param name="sourceInstance">The object to convert to the target type.</param>
/// <param name="targetType">The type to convert to.</param>
/// <returns>The converted object.</returns>
/// <remarks>
/// <para>
/// Converts an object to the target type.
/// </para>
/// </remarks>
public static object ConvertTypeTo(object sourceInstance, Type targetType)
{
Type sourceType = sourceInstance.GetType();
// Check if we can assign directly from the source type to the target type
if (targetType.IsAssignableFrom(sourceType))
{
return sourceInstance;
}
// Look for a TO converter
IConvertTo tcSource = ConverterRegistry.GetConvertTo(sourceType, targetType);
if (tcSource != null)
{
if (tcSource.CanConvertTo(targetType))
{
return tcSource.ConvertTo(sourceInstance, targetType);
}
}
// Look for a FROM converter
IConvertFrom tcTarget = ConverterRegistry.GetConvertFrom(targetType);
if (tcTarget != null)
{
if (tcTarget.CanConvertFrom(sourceType))
{
return tcTarget.ConvertFrom(sourceInstance);
}
}
throw new ArgumentException("Cannot convert source object [" + sourceInstance.ToString() + "] to target type [" + targetType.Name + "]", "sourceInstance");
}
// /// <summary>
// /// Finds the value corresponding to <paramref name="key"/> in
// /// <paramref name="props"/> and then perform variable substitution
// /// on the found value.
// /// </summary>
// /// <param name="key">The key to lookup.</param>
// /// <param name="props">The association to use for lookups.</param>
// /// <returns>The substituted result.</returns>
// public static string FindAndSubst(string key, System.Collections.IDictionary props)
// {
// if (props == null)
// {
// throw new ArgumentNullException("props");
// }
//
// string v = props[key] as string;
// if (v == null)
// {
// return null;
// }
//
// try
// {
// return SubstituteVariables(v, props);
// }
// catch(Exception e)
// {
// LogLog.Error(declaringType, "OptionConverter: Bad option value [" + v + "].", e);
// return v;
// }
// }
/// <summary>
/// Instantiates an object given a class name.
/// </summary>
/// <param name="className">The fully qualified class name of the object to instantiate.</param>
/// <param name="superClass">The class to which the new object should belong.</param>
/// <param name="defaultValue">The object to return in case of non-fulfillment.</param>
/// <returns>
/// An instance of the <paramref name="className"/> or <paramref name="defaultValue"/>
/// if the object could not be instantiated.
/// </returns>
/// <remarks>
/// <para>
/// Checks that the <paramref name="className"/> is a subclass of
/// <paramref name="superClass"/>. If that test fails or the object could
/// not be instantiated, then <paramref name="defaultValue"/> is returned.
/// </para>
/// </remarks>
public static object InstantiateByClassName(string className, Type superClass, object defaultValue)
{
if (className != null)
{
try
{
Type classObj = SystemInfo.GetTypeFromString(className, true, true);
if (!superClass.IsAssignableFrom(classObj))
{
LogLog.Error(declaringType, "OptionConverter: A [" + className + "] object is not assignable to a [" + superClass.FullName + "] variable.");
return defaultValue;
}
return Activator.CreateInstance(classObj);
}
catch (Exception e)
{
LogLog.Error(declaringType, "Could not instantiate class [" + className + "].", e);
}
}
return defaultValue;
}
/// <summary>
/// Performs variable substitution in string <paramref name="val"/> from the
/// values of keys found in <paramref name="props"/>.
/// </summary>
/// <param name="value">The string on which variable substitution is performed.</param>
/// <param name="props">The dictionary to use to lookup variables.</param>
/// <returns>The result of the substitutions.</returns>
/// <remarks>
/// <para>
/// The variable substitution delimiters are <b>${</b> and <b>}</b>.
/// </para>
/// <para>
/// For example, if props contains <c>key=value</c>, then the call
/// </para>
/// <para>
/// <code lang="C#">
/// string s = OptionConverter.SubstituteVariables("Value of key is ${key}.");
/// </code>
/// </para>
/// <para>
/// will set the variable <c>s</c> to "Value of key is value.".
/// </para>
/// <para>
/// If no value could be found for the specified key, then substitution
/// defaults to an empty string.
/// </para>
/// <para>
/// For example, if system properties contains no value for the key
/// "nonExistentKey", then the call
/// </para>
/// <para>
/// <code lang="C#">
/// string s = OptionConverter.SubstituteVariables("Value of nonExistentKey is [${nonExistentKey}]");
/// </code>
/// </para>
/// <para>
/// will set <s>s</s> to "Value of nonExistentKey is []".
/// </para>
/// <para>
/// An Exception is thrown if <paramref name="value"/> contains a start
/// delimiter "${" which is not balanced by a stop delimiter "}".
/// </para>
/// </remarks>
public static string SubstituteVariables(string value, System.Collections.IDictionary props)
{
StringBuilder buf = new StringBuilder();
int i = 0;
int j, k;
while(true)
{
j = value.IndexOf(DELIM_START, i);
if (j == -1)
{
if (i == 0)
{
return value;
}
else
{
buf.Append(value.Substring(i, value.Length - i));
return buf.ToString();
}
}
else
{
buf.Append(value.Substring(i, j - i));
k = value.IndexOf(DELIM_STOP, j);
if (k == -1)
{
throw new LogException("[" + value + "] has no closing brace. Opening brace at position [" + j + "]");
}
else
{
j += DELIM_START_LEN;
string key = value.Substring(j, k - j);
string replacement = props[key] as string;
if (replacement != null)
{
buf.Append(replacement);
}
i = k + DELIM_STOP_LEN;
}
}
}
}
#endregion Public Static Methods
#region Private Static Methods
/// <summary>
/// Converts the string representation of the name or numeric value of one or
/// more enumerated constants to an equivalent enumerated object.
/// </summary>
/// <param name="enumType">The type to convert to.</param>
/// <param name="value">The enum string value.</param>
/// <param name="ignoreCase">If <c>true</c>, ignore case; otherwise, regard case.</param>
/// <returns>An object of type <paramref name="enumType" /> whose value is represented by <paramref name="value" />.</returns>
private static object ParseEnum(System.Type enumType, string value, bool ignoreCase)
{
#if !NETCF
return Enum.Parse(enumType, value, ignoreCase);
#else
FieldInfo[] fields = enumType.GetFields(BindingFlags.Public | BindingFlags.Static);
string[] names = value.Split(new char[] {','});
for (int i = 0; i < names.Length; ++i)
{
names[i] = names [i].Trim();
}
long retVal = 0;
try
{
// Attempt to convert to numeric type
return Enum.ToObject(enumType, Convert.ChangeType(value, typeof(long), CultureInfo.InvariantCulture));
}
catch {}
foreach (string name in names)
{
bool found = false;
foreach(FieldInfo field in fields)
{
if (String.Compare(name, field.Name, ignoreCase) == 0)
{
retVal |= ((IConvertible) field.GetValue(null)).ToInt64(CultureInfo.InvariantCulture);
found = true;
break;
}
}
if (!found)
{
throw new ArgumentException("Failed to lookup member [" + name + "] from Enum type [" + enumType.Name + "]");
}
}
return Enum.ToObject(enumType, retVal);
#endif
}
#endregion Private Static Methods
#region Private Static Fields
/// <summary>
/// The fully qualified type of the OptionConverter class.
/// </summary>
/// <remarks>
/// Used by the internal logger to record the Type of the
/// log message.
/// </remarks>
private readonly static Type declaringType = typeof(OptionConverter);
private const string DELIM_START = "${";
private const char DELIM_STOP = '}';
private const int DELIM_START_LEN = 2;
private const int DELIM_STOP_LEN = 1;
#endregion Private Static Fields
}
}
| |
#region license
// Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org)
// 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 Rodrigo B. de Oliveira 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.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using Boo.Lang.Compiler.Ast;
using Boo.Lang.Compiler.TypeSystem.Core;
using Boo.Lang.Compiler.TypeSystem.Generics;
using Boo.Lang.Compiler.TypeSystem.Internal;
using Boo.Lang.Compiler.TypeSystem.Reflection;
using Boo.Lang.Compiler.TypeSystem.Services;
using Boo.Lang.Compiler.Util;
using Boo.Lang.Environments;
using Attribute = System.Attribute;
using Module = Boo.Lang.Compiler.Ast.Module;
namespace Boo.Lang.Compiler.TypeSystem
{
public class TypeSystemServices
{
public static readonly IType ErrorEntity = Error.Default;
public IType ArrayType;
public IType BoolType;
public IType BuiltinsType;
public IType CharType;
public IType ConditionalAttribute;
public IType DateTimeType;
public IType DecimalType;
public IType DelegateType;
public IType DoubleType;
public IType DuckType;
public IType EnumType;
public IType HashType;
public IType IAstGeneratorMacroType;
public IType IAstMacroType;
public IType ICallableType;
public IType ICollectionGenericType;
public IType ICollectionType;
public IType IDisposableType;
public IType IEnumerableGenericType;
public IType IEnumerableType;
public IType IListGenericType;
public IType IListType;
public IType IEnumeratorGenericType;
public IType IEnumeratorType;
public IType IQuackFuType;
public IType SByteType;
public IType ShortType;
public IType IntType;
public IType IntPtrType;
public IType LongType;
public IType ByteType;
public IType UShortType;
public IType UIntType;
public IType UIntPtrType;
public IType ULongType;
public IType ListType;
public IType MulticastDelegateType;
public IArrayType ObjectArrayType;
public IType ObjectType;
public IType RegexType;
public IType RuntimeServicesType;
public IType SingleType;
public IType StringType;
public IType SystemAttribute;
public IType TimeSpanType;
public IType TypeType;
public IType ValueTypeType;
public IType VoidType;
private Module _compilerGeneratedTypesModule;
private readonly Set<string> _literalPrimitives = new Set<string>();
private readonly Dictionary<string, IEntity> _primitives = new Dictionary<string, IEntity>(StringComparer.Ordinal);
private DowncastPermissions _downcastPermissions;
private readonly MemoizedFunction<IType, IType, IMethod> _findImplicitConversionOperator;
private readonly MemoizedFunction<IType, IType, IMethod> _findExplicitConversionOperator;
private readonly MemoizedFunction<IType, IType, bool> _canBeReachedByPromotion;
private readonly AnonymousCallablesManager _anonymousCallablesManager;
private readonly CompilerContext _context;
public TypeSystemServices() : this(CompilerContext.Current)
{
}
public TypeSystemServices(CompilerContext context)
{
if (null == context) throw new ArgumentNullException("context");
_context = context;
_anonymousCallablesManager = new AnonymousCallablesManager(this);
_findImplicitConversionOperator =
new MemoizedFunction<IType, IType, IMethod>((fromType, toType) => FindConversionOperator("op_Implicit", fromType, toType));
_findExplicitConversionOperator =
new MemoizedFunction<IType, IType, IMethod>((fromType, toType) => FindConversionOperator("op_Explicit", fromType, toType));
My<CurrentScope>.Instance.Changed += (sender, args) => ClearScopeDependentMemoizedFunctions();
_canBeReachedByPromotion = new MemoizedFunction<IType, IType, bool>(CanBeReachedByPromotionImpl);
DuckType = Map(typeof(Builtins.duck));
IQuackFuType = Map(typeof(IQuackFu));
VoidType = Map(Types.Void);
ObjectType = Map(Types.Object);
RegexType = Map(Types.Regex);
ValueTypeType = Map(typeof(ValueType));
EnumType = Map(typeof(Enum));
ArrayType = Map(Types.Array);
TypeType = Map(Types.Type);
StringType = Map(Types.String);
BoolType = Map(Types.Bool);
SByteType = Map(Types.SByte);
CharType = Map(Types.Char);
ShortType = Map(Types.Short);
IntType = Map(Types.Int);
LongType = Map(Types.Long);
ByteType = Map(Types.Byte);
UShortType = Map(Types.UShort);
UIntType = Map(Types.UInt);
ULongType = Map(Types.ULong);
SingleType = Map(Types.Single);
DoubleType = Map(Types.Double);
DecimalType = Map(Types.Decimal);
TimeSpanType = Map(Types.TimeSpan);
DateTimeType = Map(Types.DateTime);
RuntimeServicesType = Map(Types.RuntimeServices);
BuiltinsType = Map(Types.Builtins);
ListType = Map(Types.List);
HashType = Map(Types.Hash);
ICallableType = Map(Types.ICallable);
IEnumerableType = Map(Types.IEnumerable);
IEnumeratorType = Map(typeof(IEnumerator));
ICollectionType = Map(Types.ICollection);
IDisposableType = Map(typeof(IDisposable));
IntPtrType = Map(Types.IntPtr);
UIntPtrType = Map(Types.UIntPtr);
MulticastDelegateType = Map(Types.MulticastDelegate);
DelegateType = Map(Types.Delegate);
SystemAttribute = Map(typeof(Attribute));
ConditionalAttribute = Map(typeof(ConditionalAttribute));
IEnumerableGenericType = Map(Types.IEnumerableGeneric);
IEnumeratorGenericType = Map(typeof(IEnumerator<>));
ICollectionGenericType = Map(typeof(ICollection<>));
IListGenericType = Map(typeof (IList<>));
IListType = Map(typeof (IList));
IAstMacroType = Map(typeof(IAstMacro));
IAstGeneratorMacroType = Map(typeof(IAstGeneratorMacro));
ObjectArrayType = ObjectType.MakeArrayType(1);
PreparePrimitives();
PrepareBuiltinFunctions();
}
private void ClearScopeDependentMemoizedFunctions()
{
_findImplicitConversionOperator.Clear();
_findExplicitConversionOperator.Clear();
}
public CompilerContext Context
{
get { return _context; }
}
public BooCodeBuilder CodeBuilder
{
get { return _context.CodeBuilder; }
}
public virtual IType ExceptionType
{
get { return Map(typeof(Exception)); }
}
public bool IsGenericGeneratorReturnType(IType returnType)
{
return returnType.ConstructedInfo != null &&
(returnType.ConstructedInfo.GenericDefinition == IEnumerableGenericType ||
returnType.ConstructedInfo.GenericDefinition == IEnumeratorGenericType);
}
public IType GetMostGenericType(ExpressionCollection args)
{
IType type = GetConcreteExpressionType(args[0]);
for (int i = 1; i < args.Count; ++i)
{
IType newType = GetConcreteExpressionType(args[i]);
if (type == newType)
continue;
type = GetMostGenericType(type, newType);
if (IsSystemObject(type))
break;
}
return type;
}
public IType GetMostGenericType(IType current, IType candidate)
{
if (null == current && null == candidate)
throw new ArgumentNullException("current", "Both 'current' and 'candidate' are null");
if (null == current)
return candidate;
if (null == candidate)
return current;
if (IsAssignableFrom(current, candidate))
return current;
if (IsAssignableFrom(candidate, current))
return candidate;
if (IsNumberOrBool(current) && IsNumberOrBool(candidate))
return GetPromotedNumberType(current, candidate);
if (IsCallableType(current) && IsCallableType(candidate))
return ICallableType;
if (current.IsClass && candidate.IsClass)
{
if (current == ObjectType || candidate == ObjectType)
return ObjectType;
if (current.GetTypeDepth() < candidate.GetTypeDepth())
return GetMostGenericType(current.BaseType, candidate);
return GetMostGenericType(current, candidate.BaseType);
}
return ObjectType;
}
public IType GetPromotedNumberType(IType left, IType right)
{
if (left == DecimalType || right == DecimalType)
return DecimalType;
if (left == DoubleType || right == DoubleType)
return DoubleType;
if (left == SingleType || right == SingleType)
return SingleType;
if (left == ULongType)
{
if (IsSignedInteger(right))
{
// This is against the C# spec but allows expressions like:
// ulong x = 4
// y = x + 1
// y will be long.
// C# disallows mixing ulongs and signed numbers
// but in the above case it promotes the constant to ulong
// and the result is ulong.
// Since its too late here to promote the constant,
// maybe we should return LongType. I didn't chose ULongType
// because in other cases <unsigned> <op> <signed> returns <signed>.
return LongType;
}
return ULongType;
}
if (right == ULongType)
{
if (IsSignedInteger(left))
{
// This is against the C# spec but allows expressions like:
// ulong x = 4
// y = 1 + x
// y will be long.
// C# disallows mixing ulongs and signed numbers
// but in the above case it promotes the constant to ulong
// and the result is ulong.
// Since its too late here to promote the constant,
// maybe we should return LongType. I didn't chose ULongType
// because in other cases <signed> <op> <unsigned> returns <signed>.
return LongType;
}
return ULongType;
}
if (left == LongType || right == LongType)
return LongType;
if (left == UIntType)
{
if (right == SByteType || right == ShortType || right == IntType)
{
// This is allowed per C# spec and y is long:
// uint x = 4
// y = x + 1
// C# promotes <uint> <op> <signed> to <long> also
// but in the above case it promotes the constant to uint first
// and the result of "x + 1" is uint.
// Since its too late here to promote the constant,
// "y = x + 1" will be long in boo.
return LongType;
}
return UIntType;
}
if (right == UIntType)
{
if (left == SByteType || left == ShortType || left == IntType)
{
// This is allowed per C# spec and y is long:
// uint x = 4
// y = 1 + x
// C# promotes <signed> <op> <uint> to <long> also
// but in the above case it promotes the constant to uint first
// and the result of "1 + x" is uint.
// Since its too late here to promote the constant,
// "y = x + 1" will be long in boo.
return LongType;
}
return UIntType;
}
if (left == IntType ||
right == IntType ||
left == ShortType ||
right == ShortType ||
left == UShortType ||
right == UShortType ||
left == ByteType ||
right == ByteType ||
left == SByteType ||
right == SByteType)
return IntType;
return left;
}
private bool IsSignedInteger(IType right)
{
return right == SByteType || right == ShortType || right == IntType || right == LongType;
}
public static bool IsReadOnlyField(IField field)
{
return field.IsInitOnly || field.IsLiteral;
}
public bool IsCallable(IType type)
{
return (TypeType == type) || IsCallableType(type) || IsDuckType(type);
}
public virtual bool IsDuckTyped(Expression expression)
{
IType type = expression.ExpressionType;
return type != null && IsDuckType(type);
}
public bool IsQuackBuiltin(Expression node)
{
return IsQuackBuiltin(node.Entity);
}
public bool IsQuackBuiltin(IEntity entity)
{
return BuiltinFunction.Quack == entity;
}
public bool IsDuckType(IType type)
{
if (type == null) throw new ArgumentNullException("type");
if (type == DuckType) return true;
if (type == ObjectType && _context.Parameters.Ducky) return true;
return KnowsQuackFu(type);
}
public bool KnowsQuackFu(IType type)
{
return type.IsSubclassOf(IQuackFuType);
}
private bool IsCallableType(IType type)
{
return (IsAssignableFrom(ICallableType, type)) || (type is ICallableType);
}
public ICallableType GetCallableType(IMethodBase method)
{
var signature = new CallableSignature(method);
return GetCallableType(signature);
}
public ICallableType GetCallableType(CallableSignature signature)
{
return _anonymousCallablesManager.GetCallableType(signature);
}
public virtual IType GetConcreteCallableType(Node sourceNode, CallableSignature signature)
{
return _anonymousCallablesManager.GetConcreteCallableType(sourceNode, signature);
}
public virtual IType GetConcreteCallableType(Node sourceNode, AnonymousCallableType anonymousType)
{
return _anonymousCallablesManager.GetConcreteCallableType(sourceNode, anonymousType);
}
public IType GetEnumeratorItemType(IType iteratorType)
{
// Arrays are enumerators of their element type
if (iteratorType.IsArray) return iteratorType.ElementType;
// String are enumerators of char
if (StringType == iteratorType) return CharType;
// Try to use an EnumerableItemType attribute
if (iteratorType.IsClass)
{
IType enumeratorItemType = GetEnumeratorItemTypeFromAttribute(iteratorType);
if (null != enumeratorItemType) return enumeratorItemType;
}
// Try to use a generic IEnumerable interface
IType genericItemType = GetGenericEnumerableItemType(iteratorType);
if (null != genericItemType) return genericItemType;
// If none of these work, the type is an enumerator of object
return ObjectType;
}
public static IType GetExpressionType(Expression node)
{
return node.ExpressionType ?? Error.Default;
}
public IType GetConcreteExpressionType(Expression expression)
{
var type = GetExpressionType(expression);
var anonymousType = type as AnonymousCallableType;
if (null != anonymousType)
{
IType concreteType = GetConcreteCallableType(expression, anonymousType);
expression.ExpressionType = concreteType;
return concreteType;
}
return type;
}
public void MapToConcreteExpressionTypes(ExpressionCollection items)
{
foreach (Expression item in items)
GetConcreteExpressionType(item);
}
public IEntity GetDefaultMember(IType type)
{
// Search for a default member on this type or any of its non-interface basetypes
for (IType t = type; t != null; t = t.BaseType)
{
IEntity member = t.GetDefaultMember();
if (member != null) return member;
}
// Search for default members on the type's interfaces
var buffer = new Set<IEntity>();
foreach (IType interfaceType in type.GetInterfaces())
{
IEntity member = GetDefaultMember(interfaceType);
if (member != null) buffer.Add(member);
}
return Entities.EntityFromList(buffer);
}
public void AddCompilerGeneratedType(TypeDefinition type)
{
GetCompilerGeneratedTypesModule().Members.Add(type);
}
public Module GetCompilerGeneratedTypesModule()
{
return _compilerGeneratedTypesModule ?? (_compilerGeneratedTypesModule = NewModule("CompilerGenerated"));
}
private Module NewModule(string nameSpace)
{
return NewModule(nameSpace, nameSpace);
}
private Module NewModule(string nameSpace, string moduleName)
{
Module module = CodeBuilder.CreateModule(moduleName, nameSpace);
_context.CompileUnit.Modules.Add(module);
return module;
}
public bool CanBeReachedFrom(IType expectedType, IType actualType)
{
bool byDowncast;
return CanBeReachedFrom(expectedType, actualType, out byDowncast);
}
public bool CanBeReachedFrom(IType expectedType, IType actualType, out bool byDowncast)
{
bool considerExplicitConversionOperators = !InStrictMode();
return CanBeReachedFrom(expectedType, actualType, considerExplicitConversionOperators, out byDowncast);
}
public bool CanBeReachedFrom(IType expectedType, IType actualType, bool considerExplicitConversionOperators, out bool byDowncast)
{
byDowncast = false;
return IsAssignableFrom(expectedType, actualType)
|| CanBeReachedByPromotion(expectedType, actualType)
|| FindImplicitConversionOperator(actualType, expectedType) != null
|| (considerExplicitConversionOperators && FindExplicitConversionOperator(actualType, expectedType) != null)
|| (byDowncast = DowncastPermissions().CanBeReachedByDowncast(expectedType, actualType));
}
private DowncastPermissions DowncastPermissions()
{
return _downcastPermissions ?? (_downcastPermissions = My<DowncastPermissions>.Instance);
}
private bool InStrictMode()
{
return _context.Parameters.Strict;
}
public IMethod FindExplicitConversionOperator(IType fromType, IType toType)
{
return _findExplicitConversionOperator.Invoke(fromType, toType);
}
public IMethod FindImplicitConversionOperator(IType fromType, IType toType)
{
return _findImplicitConversionOperator.Invoke(fromType, toType);
}
private IMethod FindConversionOperator(string name, IType fromType, IType toType)
{
while (fromType != ObjectType)
{
IMethod method = FindConversionOperator(name, fromType, toType, fromType.GetMembers());
if (null != method) return method;
method = FindConversionOperator(name, fromType, toType, toType.GetMembers());
if (null != method) return method;
method = FindConversionOperator(name, fromType, toType, FindExtension(fromType, name));
if (null != method) return method;
fromType = fromType.BaseType;
if (null == fromType) break;
}
return null;
}
private IEntity[] FindExtension(IType fromType, string name)
{
IEntity extension = NameResolutionService.ResolveExtension(fromType, name);
if (null == extension) return Ambiguous.NoEntities;
var a = extension as Ambiguous;
if (null != a) return a.Entities;
return new[] {extension};
}
private IMethod FindConversionOperator(string name, IType fromType, IType toType, IEnumerable<IEntity> candidates)
{
foreach (IMethod method in NameResolutionService.Select<IMethod>(candidates, name, EntityType.Method))
if (IsConversionOperator(method, fromType, toType)) return method;
return null;
}
protected NameResolutionService NameResolutionService
{
get { return _nameResolutionService; }
}
EnvironmentProvision<NameResolutionService> _nameResolutionService = new EnvironmentProvision<NameResolutionService>();
private static bool IsConversionOperator(IMethod method, IType fromType, IType toType)
{
if (!method.IsStatic) return false;
if (method.ReturnType != toType) return false;
IParameter[] parameters = method.GetParameters();
return (1 == parameters.Length && fromType == parameters[0].Type);
}
public bool IsCallableTypeAssignableFrom(ICallableType lhs, IType rhs)
{
if (lhs == rhs) return true;
if (rhs.IsNull()) return true;
var other = rhs as ICallableType;
if (null == other) return false;
CallableSignature lvalue = lhs.GetSignature();
CallableSignature rvalue = other.GetSignature();
if (lvalue == rvalue) return true;
IParameter[] lparams = lvalue.Parameters;
IParameter[] rparams = rvalue.Parameters;
if (lparams.Length < rparams.Length) return false;
for (int i = 0; i < rparams.Length; ++i)
if (!CanBeReachedFrom(lparams[i].Type, rparams[i].Type))
return false;
return CompatibleReturnTypes(lvalue, rvalue);
}
private bool CompatibleReturnTypes(CallableSignature lvalue, CallableSignature rvalue)
{
if (VoidType != lvalue.ReturnType && VoidType != rvalue.ReturnType)
return CanBeReachedFrom(lvalue.ReturnType, rvalue.ReturnType);
return true;
}
public static bool CheckOverrideSignature(IMethod impl, IMethod baseMethod)
{
if (!GenericsServices.AreOfSameGenerity(impl, baseMethod))
return false;
CallableSignature baseSignature = GetOverriddenSignature(baseMethod, impl);
return CheckOverrideSignature(impl.GetParameters(), baseSignature.Parameters);
}
public static bool CheckOverrideSignature(IParameter[] implParameters, IParameter[] baseParameters)
{
return CallableSignature.AreSameParameters(implParameters, baseParameters);
}
public static CallableSignature GetOverriddenSignature(IMethod baseMethod, IMethod impl)
{
if (baseMethod.GenericInfo != null && GenericsServices.AreOfSameGenerity(baseMethod, impl))
return baseMethod.GenericInfo.ConstructMethod(impl.GenericInfo.GenericParameters).CallableType.GetSignature();
return baseMethod.CallableType.GetSignature();
}
public virtual bool CanBeReachedByDownCastOrPromotion(IType expectedType, IType actualType)
{
return DowncastPermissions().CanBeReachedByDowncast(expectedType, actualType)
|| CanBeReachedByPromotion(expectedType, actualType);
}
public virtual bool CanBeReachedByPromotion(IType expectedType, IType actualType)
{
return _canBeReachedByPromotion.Invoke(expectedType, actualType);
}
private bool CanBeReachedByPromotionImpl(IType expectedType, IType actualType)
{
if (IsNullable(expectedType) && actualType.IsNull())
return true;
if (IsIntegerNumber(actualType) && CanBeExplicitlyCastToInteger(expectedType))
return true;
if (IsIntegerNumber(expectedType) && CanBeExplicitlyCastToInteger(actualType))
return true;
return (expectedType.IsValueType && IsNumber(expectedType) && IsNumber(actualType));
}
public bool CanBeExplicitlyCastToInteger(IType type)
{
return type.IsEnum || type == CharType;
}
public static bool ContainsMethodsOnly(ICollection<IEntity> members)
{
return members.All(member => EntityType.Method == member.EntityType);
}
public bool IsIntegerNumber(IType type)
{
return IsSignedInteger(type) || IsUnsignedInteger(type);
}
private bool IsUnsignedInteger(IType type)
{
return (type == UShortType ||
type == UIntType ||
type == ULongType ||
type == ByteType);
}
public bool IsIntegerOrBool(IType type)
{
return BoolType == type || IsIntegerNumber(type);
}
public bool IsNumberOrBool(IType type)
{
return BoolType == type || IsNumber(type);
}
public bool IsNumber(IType type)
{
return IsPrimitiveNumber(type) || type == DecimalType;
}
public bool IsPrimitiveNumber(IType type)
{
return IsIntegerNumber(type) || type == DoubleType || type == SingleType;
}
public bool IsSignedNumber(IType type)
{
return IsNumber(type) && !IsUnsignedInteger(type);
}
/// <summary>
/// Returns true if the type is a reference type or a generic parameter
/// type that is constrained to represent a reference type.
/// </summary>
public static bool IsReferenceType(IType type)
{
var gp = type as IGenericParameter;
if (null == gp)
return !type.IsValueType;
if (gp.IsClass)
return true;
foreach (IType tc in gp.GetTypeConstraints())
if (!tc.IsValueType && !tc.IsInterface)
return true;
return false;
}
/// <summary>
/// Returns true if the type can be either a reference type or a value type.
/// Currently it returns true only for an unconstrained generic parameter type.
/// </summary>
public static bool IsAnyType(IType type)
{
var gp = type as IGenericParameter;
return (null != gp && !gp.IsClass && !gp.IsValueType && 0 == gp.GetTypeConstraints().Length);
}
public static bool IsNullable(IType type)
{
var et = type as ExternalType;
return (null != et && et.ActualType.IsGenericType && et.ActualType.GetGenericTypeDefinition() == Types.Nullable);
}
public IType GetNullableUnderlyingType(IType type)
{
var et = type as ExternalType;
return Map(Nullable.GetUnderlyingType(et.ActualType));
}
public static bool IsUnknown(Expression node)
{
var type = node.ExpressionType;
return null != type && IsUnknown(type);
}
public static bool IsUnknown(IType type)
{
return EntityType.Unknown == type.EntityType;
}
public static bool IsError(Expression node)
{
var type = node.ExpressionType;
return null != type && IsError(type);
}
public static bool IsErrorAny(ExpressionCollection collection)
{
return collection.Any(IsError);
}
public bool IsBuiltin(IEntity entity)
{
if (EntityType.Method == entity.EntityType)
return BuiltinsType == ((IMethod) entity).DeclaringType;
return false;
}
public static bool IsError(IEntity entity)
{
return EntityType.Error == entity.EntityType;
}
public static TypeMemberModifiers GetAccess(IAccessibleMember member)
{
if (member.IsPublic)
return TypeMemberModifiers.Public;
if (member.IsProtected)
{
if (member.IsInternal)
return TypeMemberModifiers.Protected | TypeMemberModifiers.Internal;
return TypeMemberModifiers.Protected;
}
if (member.IsInternal)
return TypeMemberModifiers.Internal;
return TypeMemberModifiers.Private;
}
[Obsolete("Use Node.Entity instead.")]
public static IEntity GetOptionalEntity(Node node)
{
return node.Entity;
}
public static IEntity GetEntity(Node node)
{
var entity = node.Entity;
if (entity != null)
return entity;
if (My<CompilerParameters>.Instance.Pipeline.BreakOnErrors)
InvalidNode(node);
return Error.Default;
}
public static IType GetReferencedType(Expression typeref)
{
switch (typeref.NodeType)
{
case NodeType.TypeofExpression:
return GetType(((TypeofExpression) typeref).Type);
case NodeType.ReferenceExpression:
case NodeType.MemberReferenceExpression:
case NodeType.GenericReferenceExpression:
return typeref.Entity as IType;
}
return null;
}
public bool IsAttribute(IType type)
{
return type.IsSubclassOf(SystemAttribute);
}
public static IType GetType(Node node)
{
return ((ITypedEntity) GetEntity(node)).Type;
}
public IType Map(Type type)
{
return TypeSystemProvider().Map(type);
}
private IReflectionTypeSystemProvider TypeSystemProvider()
{
return _typeSystemProvider.Instance;
}
private EnvironmentProvision<IReflectionTypeSystemProvider> _typeSystemProvider;
public IParameter[] Map(ParameterInfo[] parameters)
{
return TypeSystemProvider().Map(parameters);
}
public IConstructor Map(ConstructorInfo constructor)
{
return (IConstructor) Map((MemberInfo) constructor);
}
public IMethod Map(MethodInfo method)
{
return (IMethod) Map((MemberInfo) method);
}
public IEntity Map(MemberInfo[] members)
{
return TypeSystemProvider().Map(members);
}
public IEntity Map(MemberInfo mi)
{
return TypeSystemProvider().Map(mi);
}
public static string GetSignature(IEntityWithParameters method)
{
return My<EntityFormatter>.Instance.FormatSignature(method);
}
public IEntity ResolvePrimitive(string name)
{
IEntity result;
if (_primitives.TryGetValue(name, out result))
return result;
return null;
}
public bool IsPrimitive(string name)
{
return _primitives.ContainsKey(name);
}
public bool IsLiteralPrimitive(IType type)
{
var typ = type as ExternalType;
return typ != null
&& typ.PrimitiveName != null
&& _literalPrimitives.Contains(typ.PrimitiveName);
}
/// <summary>
/// checks if the passed type will be equivalente to
/// System.Object in runtime (accounting for the presence
/// of duck typing).
/// </summary>
public bool IsSystemObject(IType type)
{
return type == ObjectType || type == DuckType;
}
public bool IsPointerCompatible(IType type)
{
return IsPrimitiveNumber(type) || (type.IsValueType && 0 != SizeOf(type));
}
protected virtual void PreparePrimitives()
{
AddPrimitiveType("duck", DuckType);
AddPrimitiveType("void", VoidType);
AddPrimitiveType("object", ObjectType);
AddPrimitiveType("callable", ICallableType);
AddPrimitiveType("decimal", DecimalType);
AddPrimitiveType("date", DateTimeType);
AddLiteralPrimitiveType("bool", BoolType);
AddLiteralPrimitiveType("sbyte", SByteType);
AddLiteralPrimitiveType("byte", ByteType);
AddLiteralPrimitiveType("short", ShortType);
AddLiteralPrimitiveType("ushort", UShortType);
AddLiteralPrimitiveType("int", IntType);
AddLiteralPrimitiveType("uint", UIntType);
AddLiteralPrimitiveType("long", LongType);
AddLiteralPrimitiveType("ulong", ULongType);
AddLiteralPrimitiveType("single", SingleType);
AddLiteralPrimitiveType("double", DoubleType);
AddLiteralPrimitiveType("char", CharType);
AddLiteralPrimitiveType("string", StringType);
AddLiteralPrimitiveType("regex", RegexType);
AddLiteralPrimitiveType("timespan", TimeSpanType);
}
protected virtual void PrepareBuiltinFunctions()
{
AddBuiltin(BuiltinFunction.Len);
AddBuiltin(BuiltinFunction.AddressOf);
AddBuiltin(BuiltinFunction.Eval);
AddBuiltin(BuiltinFunction.Switch);
}
protected void AddPrimitiveType(string name, IType type)
{
_primitives[name] = type;
((ExternalType) type).PrimitiveName = name;
}
protected void AddLiteralPrimitiveType(string name, IType type)
{
AddPrimitiveType(name, type);
_literalPrimitives.Add(name);
}
protected void AddBuiltin(BuiltinFunction function)
{
_primitives[function.Name] = function;
}
public IConstructor GetDefaultConstructor(IType type)
{
return type.GetConstructors().FirstOrDefault(constructor => 0 == constructor.GetParameters().Length);
}
private IType GetExternalEnumeratorItemType(IType iteratorType)
{
Type type = ((ExternalType) iteratorType).ActualType;
var attribute = (EnumeratorItemTypeAttribute) Attribute.GetCustomAttribute(type, typeof(EnumeratorItemTypeAttribute));
return null != attribute ? Map(attribute.ItemType) : null;
}
private IType GetEnumeratorItemTypeFromAttribute(IType iteratorType)
{
// If iterator type is external get its attributes via reflection
if (iteratorType is ExternalType)
return GetExternalEnumeratorItemType(iteratorType);
// If iterator type is a generic constructed type, get its attribute from its definition
// and map generic parameters
if (iteratorType.ConstructedInfo != null)
{
IType definitionItemType = GetEnumeratorItemType(iteratorType.ConstructedInfo.GenericDefinition);
return iteratorType.ConstructedInfo.Map(definitionItemType);
}
// If iterator type is internal get its attributes from its type definition
var internalType = (AbstractInternalType) iteratorType;
IType enumeratorItemTypeAttribute = Map(typeof(EnumeratorItemTypeAttribute));
foreach (Ast.Attribute attribute in internalType.TypeDefinition.Attributes)
{
var constructor = GetEntity(attribute) as IConstructor;
if (null != constructor && constructor.DeclaringType == enumeratorItemTypeAttribute)
return GetType(attribute.Arguments[0]);
}
return null;
}
public IType GetGenericEnumerableItemType(IType iteratorType)
{
// Arrays implicitly implement IEnumerable[of element type]
if (iteratorType is ArrayType) return iteratorType.ElementType;
// If type is not an array, try to find IEnumerable[of some type] in its interfaces
IType itemType = null;
foreach (IType type in GenericsServices.FindConstructedTypes(iteratorType, IEnumerableGenericType))
{
IType candidateItemType = type.ConstructedInfo.GenericArguments[0];
if (itemType != null)
itemType = GetMostGenericType(itemType, candidateItemType);
else
itemType = candidateItemType;
}
return itemType;
}
private static void InvalidNode(Node node)
{
throw CompilerErrorFactory.InvalidNode(node);
}
public virtual bool IsValidException(IType type)
{
return IsAssignableFrom(ExceptionType, type);
}
private static bool IsAssignableFrom(IType expectedType, IType actualType)
{
return TypeCompatibilityRules.IsAssignableFrom(expectedType, actualType);
}
public virtual IConstructor GetStringExceptionConstructor()
{
return Map(typeof(Exception).GetConstructor(new[] {typeof(string)}));
}
public virtual bool IsMacro(IType type)
{
return type.IsSubclassOf(IAstMacroType) || type.IsSubclassOf(IAstGeneratorMacroType);
}
public virtual int SizeOf(IType type)
{
if (type.IsPointer)
type = type.ElementType;
if (null == type || !type.IsValueType)
return 0;
var et = type as ExternalType;
if (null != et)
return Marshal.SizeOf(et.ActualType);
int size = 0;
var it = type as InternalClass;
if (null == it)
return 0;
//FIXME: TODO: warning if no predefined size => StructLayoutAttribute
foreach (Field f in it.TypeDefinition.Members.OfType<Field>())
{
int fsize = SizeOf(f.Type.Entity as IType);
if (0 == fsize)
return 0; //cannot be unmanaged
size += fsize;
}
return size;
}
}
}
| |
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Security.Principal;
using System.Web.DynamicData.ModelProviders;
using System.Web.DynamicData.Util;
using System.Web.Resources;
using System.Web.Routing;
using System.Web.UI;
using System.Web.UI.WebControls;
using AttributeCollection = System.ComponentModel.AttributeCollection;
namespace System.Web.DynamicData {
/// <summary>
/// Represents a database table for use by dynamic data pages
/// </summary>
public class MetaTable : IMetaTable {
private const int DefaultColumnOrder = 10000;
private Dictionary<string, MetaColumn> _columnsByName;
private HttpContextBase _context;
private MetaColumn _displayColumn;
private string _foreignKeyColumnsNames;
private bool? _hasToStringOverride;
private MetaTableMetadata _metadata;
private ReadOnlyCollection<MetaColumn> _primaryKeyColumns;
private string[] _primaryKeyColumnNames;
private bool _scaffoldDefaultValue;
private MetaColumn _sortColumn;
private bool _sortColumnProcessed;
private TableProvider _tableProvider;
private string _listActionPath;
/// <summary>
/// A collection of attributes declared on this entity type (i.e. class-level attributes).
/// </summary>
public AttributeCollection Attributes {
get {
return Metadata.Attributes;
}
}
/// <summary>
/// All columns
/// </summary>
public ReadOnlyCollection<MetaColumn> Columns {
get;
// internal for unit testing
internal set;
}
// for unit testing
internal HttpContextBase Context {
private get {
return _context ?? new HttpContextWrapper(HttpContext.Current);
}
set {
_context = value;
}
}
/// <summary>
/// Name of table coming from the property on the data context. E.g. the value is "Products" for a table that is part of
/// the NorthwindDataContext.Products collection.
/// </summary>
public string DataContextPropertyName {
get {
return _tableProvider.DataContextPropertyName;
}
}
/// <summary>
/// The type of the data context this table belongs to.
/// </summary>
public Type DataContextType {
get {
return Provider.DataModel.ContextType;
}
}
/// <summary>
/// Returns the column being used for display values when entries in this table are used as parents in foreign key relationships.
/// Which column to use can be specified using DisplayColumnAttribute. If the attribute is not present, the following heuristic is used:
/// 1. First non-PK string column
/// 2. First PK string column
/// 3. First PK non-string column
/// 4. First column
/// </summary>
public virtual MetaColumn DisplayColumn {
get {
// use a local to avoid a null value if ResetMetadata gets called
var displayColumn = _displayColumn;
if (displayColumn == null) {
displayColumn = GetDisplayColumnFromMetadata() ?? GetDisplayColumnFromHeuristic();
_displayColumn = displayColumn;
}
return displayColumn;
}
}
/// <summary>
/// Gets the string to be user-friendly string representing this table. Defaults to the value of the Name property.
/// Can be customized using DisplayNameAttribute.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2119:SealMethodsThatSatisfyPrivateInterfaces",
Justification = "Interface denotes existence of property, not used for security.")]
public virtual string DisplayName {
get {
return Metadata.DisplayName ?? Name;
}
}
/// <summary>
/// Return the type of the Entity represented by this table (e.g. Product)
/// </summary>
public Type EntityType {
get {
return Provider.EntityType;
}
}
/// <summary>
/// Get a comma separated list of foreign key names. This is useful to set the IncludePaths on an EntityDataSource
/// </summary>
public string ForeignKeyColumnsNames {
get {
if (_foreignKeyColumnsNames == null) {
var fkColumnNamesArray = Columns.OfType<MetaForeignKeyColumn>().Select(column => column.Name).ToArray();
_foreignKeyColumnsNames = String.Join(",", fkColumnNamesArray);
}
return _foreignKeyColumnsNames;
}
}
/// <summary>
/// Returns true if the table has a primary key
/// </summary>
public bool HasPrimaryKey {
get {
// Some of the columns may be primary keys, but if this is a view, it doesn't "have"
// any primary keys, so PrimaryKey is null.
return PrimaryKeyColumns.Count > 0;
}
}
private bool HasToStringOverride {
get {
// Check if the entity type overrides ToString()
//
if (!_hasToStringOverride.HasValue) {
MethodInfo toStringMethod = EntityType.GetMethod("ToString");
_hasToStringOverride = (toStringMethod.DeclaringType != typeof(object));
}
return _hasToStringOverride.Value;
}
}
/// <summary>
/// Returns true if this is a read-only table or view(has not PK).
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2119:SealMethodsThatSatisfyPrivateInterfaces",
Justification = "Interface denotes existence of property, not used for security.")]
public virtual bool IsReadOnly {
get {
return Metadata.IsReadOnly || !HasPrimaryKey;
}
}
/// <summary>
/// Gets the action path to the list action for this table
/// </summary>
public string ListActionPath {
get {
return _listActionPath ?? GetActionPath(PageAction.List);
}
internal set {
_listActionPath = value;
}
}
private MetaTableMetadata Metadata {
get {
// use a local to avoid returning null if ResetMetadata gets called
var metadata = _metadata;
if (metadata == null) {
metadata = new MetaTableMetadata(this);
_metadata = metadata;
}
return metadata;
}
}
/// <summary>
/// The model this table belongs to.
/// </summary>
public MetaModel Model { get; private set; }
/// <summary>
/// Unique name of table. This name is unique within a given data context. (e.g. "MyCustomName_Products")
/// </summary>
public string Name {
get;
private set;
}
/// <summary>
/// Columns that constitute the primary key of this table
/// </summary>
public ReadOnlyCollection<MetaColumn> PrimaryKeyColumns {
get {
if (_primaryKeyColumns == null) {
_primaryKeyColumns = Columns.Where(c => c.IsPrimaryKey).ToList().AsReadOnly();
}
return _primaryKeyColumns;
}
}
internal string[] PrimaryKeyNames {
get {
if (_primaryKeyColumnNames == null) {
_primaryKeyColumnNames = PrimaryKeyColumns.Select(c => c.Name).ToArray();
}
return _primaryKeyColumnNames;
}
}
/// <summary>
/// The underlying provider for this column
/// </summary>
public TableProvider Provider { get { return _tableProvider; } }
/// <summary>
/// Return the root type of this entity's inheritance hierarchy; if the type is at the top
/// of an inheritance hierarchy or does not have any inheritance, will return EntityType.
/// </summary>
public Type RootEntityType {
get {
return Provider.RootEntityType;
}
}
/// <summary>
/// Whether or not to scaffold. This can be customized using ScaffoldAttribute
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2119:SealMethodsThatSatisfyPrivateInterfaces",
Justification = "Interface denotes existence of property, not used for security.")]
public virtual bool Scaffold {
get {
return Metadata.ScaffoldTable ?? _scaffoldDefaultValue;
}
}
/// <summary>
/// Gets the column used as the sorting column when used FK relationships. Defaults to the same column that is returned by DisplayColumn.
/// Can be customized using options on DisplayColumnAttribute.
/// </summary>
public virtual MetaColumn SortColumn {
get {
if (!_sortColumnProcessed) {
var displayColumnAttribute = Metadata.DisplayColumnAttribute;
if (displayColumnAttribute != null && !String.IsNullOrEmpty(displayColumnAttribute.SortColumn)) {
if (!TryGetColumn(displayColumnAttribute.SortColumn, out _sortColumn)) {
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
DynamicDataResources.MetaTable_CantFindSortColumn,
displayColumnAttribute.SortColumn,
Name));
}
if (_sortColumn is MetaChildrenColumn) {
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
DynamicDataResources.MetaTable_CantUseChildrenColumnAsSortColumn,
_sortColumn.Name,
Name));
}
}
_sortColumnProcessed = true;
}
return _sortColumn;
}
}
/// <summary>
/// Returns true if the entries in this column are meant to be sorted in a descending order when used as parents in a FK relationship.
/// Can be declared using options on DisplayColumnAttribute
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2119:SealMethodsThatSatisfyPrivateInterfaces",
Justification = "Interface denotes existence of property, not used for security.")]
public virtual bool SortDescending {
get {
return Metadata.SortDescending;
}
}
public MetaTable(MetaModel metaModel, TableProvider tableProvider) {
_tableProvider = tableProvider;
Model = metaModel;
}
/// <summary>
/// Build the attribute collection, made publicly available through the Attributes property
/// </summary>
protected virtual AttributeCollection BuildAttributeCollection() {
return Provider.Attributes;
}
/// <summary>
/// Returns whether the passed in user is allowed to delete items from the table
/// </summary>
public virtual bool CanDelete(IPrincipal principal) {
return Provider.CanDelete(principal);
}
/// <summary>
/// Returns whether the passed in user is allowed to insert into the table
/// </summary>
public virtual bool CanInsert(IPrincipal principal) {
return Provider.CanInsert(principal);
}
/// <summary>
/// Returns whether the passed in user is allowed to read from the table
/// </summary>
public virtual bool CanRead(IPrincipal principal) {
return Provider.CanRead(principal);
}
/// <summary>
/// Returns whether the passed in user is allowed to make changes tothe table
/// </summary>
public virtual bool CanUpdate(IPrincipal principal) {
return Provider.CanUpdate(principal);
}
public static MetaTable CreateTable(Type entityType) {
return MetaModel.CreateSimpleModel(entityType).Tables.First();
}
public static MetaTable CreateTable(ICustomTypeDescriptor typeDescriptor) {
return MetaModel.CreateSimpleModel(typeDescriptor).Tables.First();
}
/// <summary>
/// Instantiate a MetaChildrenColumn object. Can be overridden to instantiate a derived type
/// </summary>
/// <returns></returns>
protected virtual MetaChildrenColumn CreateChildrenColumn(ColumnProvider columnProvider) {
return new MetaChildrenColumn(this, columnProvider);
}
/// <summary>
/// Instantiate a MetaColumn object. Can be overridden to instantiate a derived type
/// </summary>
/// <returns></returns>
protected virtual MetaColumn CreateColumn(ColumnProvider columnProvider) {
return new MetaColumn(this, columnProvider);
}
private MetaColumn CreateColumnInternal(ColumnProvider columnProvider) {
if (columnProvider.Association != null) {
switch (columnProvider.Association.Direction) {
case AssociationDirection.OneToOne:
case AssociationDirection.ManyToOne:
return CreateForeignKeyColumn(columnProvider);
case AssociationDirection.ManyToMany:
case AssociationDirection.OneToMany:
return CreateChildrenColumn(columnProvider);
}
Debug.Assert(false);
}
return CreateColumn(columnProvider);
}
internal void CreateColumns() {
var columns = new List<MetaColumn>();
_columnsByName = new Dictionary<string, MetaColumn>(StringComparer.OrdinalIgnoreCase);
foreach (ColumnProvider columnProvider in Provider.Columns) {
MetaColumn column = CreateColumnInternal(columnProvider);
columns.Add(column);
if (_columnsByName.ContainsKey(column.Name)) {
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, DynamicDataResources.MetaTable_ColumnNameConflict,
column.Name, Provider.Name));
}
_columnsByName.Add(column.Name, column);
}
Columns = new ReadOnlyCollection<MetaColumn>(columns);
}
/// <summary>
/// Instantiate a data context that this table belongs to. Uses the instatiotion method specified when the context was registered.
/// </summary>
/// <returns></returns>
public virtual object CreateContext() {
return Provider.DataModel.CreateContext();
}
/// <summary>
/// Instantiate a MetaForeignKeyColumn object. Can be overridden to instantiate a derived type
/// </summary>
/// <returns></returns>
protected virtual MetaForeignKeyColumn CreateForeignKeyColumn(ColumnProvider columnProvider) {
return new MetaForeignKeyColumn(this, columnProvider);
}
/// <summary>
/// Gets the action path for the given row (to get primary key values for query string filters, etc.)
/// </summary>
/// <param name="action"></param>
/// <param name="row">the instance of the row</param>
/// <returns></returns>
public string GetActionPath(string action, object row) {
// Delegate to the overload that takes an array of primary key values
return GetActionPath(action, GetPrimaryKeyValues(row));
}
/// <summary>
/// Gets the action path for the given row (to get primary key values for query string filters, etc.)
/// </summary>
/// <param name="action"></param>
/// <param name="row">the instance of the row</param>
/// <param name="path"></param>
/// <returns></returns>
public string GetActionPath(string action, object row, string path) {
// Delegate to the overload that takes an array of primary key values
return GetActionPath(action, GetPrimaryKeyValues(row), path);
}
/// <summary>
/// Gets the action path for the current table and the passed in action
/// </summary>
public string GetActionPath(string action) {
return GetActionPath(action, (IList<object>)null);
}
/// <summary>
/// Gets the action path for the current table and the passed in action. Also, include all the passed in
/// route values in the path
/// </summary>
/// <returns></returns>
public string GetActionPath(string action, RouteValueDictionary routeValues) {
routeValues.Add(DynamicDataRoute.TableToken, Name);
routeValues.Add(DynamicDataRoute.ActionToken, action);
// Try to get the path from the route
return GetActionPathFromRoutes(routeValues);
}
/// <summary>
/// Gets the action path for the current table and the passed in action. Also, include the passed in
/// primary key as part of the route.
/// </summary>
/// <returns></returns>
public string GetActionPath(string action, IList<object> primaryKeyValues) {
var routeValues = new RouteValueDictionary();
routeValues.Add(DynamicDataRoute.TableToken, Name);
routeValues.Add(DynamicDataRoute.ActionToken, action);
GetRouteValuesFromPK(routeValues, primaryKeyValues);
// Try to get the path from the route
return GetActionPathFromRoutes(routeValues);
}
/// <summary>
/// Use the passed in path and append to it query string parameters for the passed in primary key values
/// </summary>
public string GetActionPath(string action, IList<object> primaryKeyValues, string path) {
// If there is no path, use standard routing
if (String.IsNullOrEmpty(path)) {
return GetActionPath(action, primaryKeyValues);
}
// Get all the PK values in a dictionary
var routeValues = new RouteValueDictionary();
GetRouteValuesFromPK(routeValues, primaryKeyValues);
// Create a query string from it and Add it to the path
return QueryStringHandler.AddFiltersToPath(path, routeValues);
}
private string GetActionPathFromRoutes(RouteValueDictionary routeValues) {
RequestContext requestContext = DynamicDataRouteHandler.GetRequestContext(Context);
string path = null;
if (requestContext != null) {
// Add the model to the route values so that the route can make sure it only
// gets matched if it is meant to work with that model
routeValues.Add(DynamicDataRoute.ModelToken, Model);
VirtualPathData vpd = RouteTable.Routes.GetVirtualPath(requestContext, routeValues);
if (vpd != null) {
path = vpd.VirtualPath;
}
}
// If the virtual path is null, then there is no page to link to
return path ?? String.Empty;
}
/// <summary>
/// Looks up a column by the given name. If no column is found, an exception is thrown.
/// </summary>
/// <param name="columnName"></param>
/// <returns></returns>
public MetaColumn GetColumn(string columnName) {
MetaColumn column;
if (!TryGetColumn(columnName, out column)) {
throw new InvalidOperationException(String.Format(
CultureInfo.CurrentCulture,
DynamicDataResources.MetaTable_NoSuchColumn,
Name,
columnName));
}
return column;
}
private static int GetColumnOrder(MetaColumn column) {
var displayAttribute = column.Metadata.DisplayAttribute;
if (displayAttribute != null && displayAttribute.GetOrder() != null) {
return displayAttribute.GetOrder().Value;
}
return DefaultColumnOrder;
}
private static int GetColumnOrder(MetaColumn column, IDictionary<string, int> groupings) {
var displayAttribute = column.Metadata.DisplayAttribute;
int order;
if (displayAttribute != null) {
string groupName = displayAttribute.GetGroupName();
if (!String.IsNullOrEmpty(groupName) && groupings.TryGetValue(groupName, out order)) {
return order;
}
}
return GetColumnOrder(column);
}
/// <summary>
/// Look for this table's primary key in the route values (i.e. typically the query string).
/// If they're all found, return a DataKey containing the primary key values. Otherwise return null.
/// </summary>
public DataKey GetDataKeyFromRoute() {
var queryStringKeys = new OrderedDictionary(PrimaryKeyNames.Length);
foreach (MetaColumn key in PrimaryKeyColumns) {
// Try to find the PK in the route values. If any PK is not found, return null
string value = Misc.GetRouteValue(key.Name);
if (string.IsNullOrEmpty(value))
return null;
queryStringKeys[key.Name] = Misc.ChangeType(value, key.ColumnType);
}
return new DataKey(queryStringKeys, PrimaryKeyNames);
}
private MetaColumn GetDisplayColumnFromHeuristic() {
// Pick best available option (except for columns based on custom properties)
// 1. First non-PK string column
// 2. First PK string column
// 3. First PK non-string column
// 4. First column (from all columns)
var serverSideColumns = Columns.Where(c => !c.IsCustomProperty).ToList();
return serverSideColumns.FirstOrDefault(c => c.IsString && !c.IsPrimaryKey) ??
serverSideColumns.FirstOrDefault(c => c.IsString) ??
serverSideColumns.FirstOrDefault(c => c.IsPrimaryKey) ??
Columns.First();
}
private MetaColumn GetDisplayColumnFromMetadata() {
var displayColumnAttribute = Metadata.DisplayColumnAttribute;
if (displayColumnAttribute == null) {
return null;
}
MetaColumn displayColumn = null;
if (!TryGetColumn(displayColumnAttribute.DisplayColumn, out displayColumn)) {
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
DynamicDataResources.MetaTable_CantFindDisplayColumn,
displayColumnAttribute.DisplayColumn,
Name));
}
return displayColumn;
}
/// <summary>
/// Gets the value to be used as the display string for an instance of a row of this table when used in FK relationships.
/// If the row is null, returns an empty string. If the entity class has an overidden ToString() method, returns the result
/// of that method. Otherwise, returns the ToString representation of the value of the display column (as returned by the DisplayColumn
/// property) for the given row.
/// </summary>
/// <param name="row">the instance of the row</param>
/// <returns></returns>
public virtual string GetDisplayString(object row) {
if (row == null)
return String.Empty;
// Make sure it's of the right type, and handle collections
row = PreprocessRowObject(row);
// If there is a ToString() override, use it
if (HasToStringOverride) {
return row.ToString();
}
// Otherwise, use the 'display column'
object displayObject = DataBinder.GetPropertyValue(row, DisplayColumn.Name);
return displayObject == null ? String.Empty : displayObject.ToString();
}
/// <summary>
/// Returns an enumeration of columns that are filterable by default. A column is filterable if it
/// <ul>
/// <li>is decorated with FilterAttribte with Enabled=true</li>
/// <li>is scaffold, is not a custom property, and is either a FK column or a Bool column</li>
/// </ul>
/// The enumeration is ordered by the value of the FilterAttribute.Order property. If a column
/// does not have that attribute, the value 0 is used.
/// </summary>
/// <returns></returns>
public virtual IEnumerable<MetaColumn> GetFilteredColumns() {
IDictionary<string, int> columnGroupOrder = GetColumnGroupingOrder();
return Columns.Where(c => IsFilterableColumn(c, Context.User))
.OrderBy(c => GetColumnOrder(c, columnGroupOrder))
.ThenBy(c => GetColumnOrder(c));
}
private IDictionary<string, int> GetColumnGroupingOrder() {
// Group columns that have groups by group names. Then put them into a dictionary from group name ->
// minimum column order so that groups are "stick" close together.
return Columns.Where(c => c.Metadata.DisplayAttribute != null && !String.IsNullOrEmpty(c.Metadata.DisplayAttribute.GetGroupName()))
.GroupBy(c => c.Metadata.DisplayAttribute.GetGroupName())
.ToDictionary(cg => cg.Key,
cg => cg.Min(c => GetColumnOrder(c)));
}
/// <summary>
/// Get a dictionary of primary key names and their values for the given row instance
/// </summary>
/// <param name="row"></param>
/// <returns></returns>
public IDictionary<string, object> GetPrimaryKeyDictionary(object row) {
row = PreprocessRowObject(row);
Dictionary<string, object> result = new Dictionary<string, object>();
foreach (MetaColumn pkMember in PrimaryKeyColumns) {
result.Add(pkMember.Name, DataBinder.GetPropertyValue(row, pkMember.Name));
}
return result;
}
/// <summary>
/// Get a comma separated list of values representing the primary key for the given row instance
/// </summary>
/// <param name="row"></param>
/// <returns></returns>
public string GetPrimaryKeyString(object row) {
// Make sure it's of the right type, and handle collections
row = PreprocessRowObject(row);
return GetPrimaryKeyString(GetPrimaryKeyValues(row));
}
/// <summary>
/// Get a comma separated list of values representing the primary key
/// </summary>
/// <param name="primaryKeyValues"></param>
/// <returns></returns>
public string GetPrimaryKeyString(IList<object> primaryKeyValues) {
return Misc.PersistListToCommaSeparatedString(primaryKeyValues);
}
/// <summary>
/// Get the value of the primary key components for a given row
/// </summary>
/// <param name="row"></param>
/// <returns></returns>
public IList<object> GetPrimaryKeyValues(object row) {
if (row == null)
return null;
// Make sure it's of the right type, and handle collections
row = PreprocessRowObject(row);
return Misc.GetKeyValues(PrimaryKeyColumns, row);
}
/// <summary>
/// Get the IQueryable for the entity type represented by this table (i.e. IQueryable of Product). Retrieves it from a new context
/// instantiated using the CreateContext().
/// </summary>
/// <returns></returns>
public IQueryable GetQuery() {
return GetQuery(null);
}
/// <summary>
/// Get the IQueryable for the entity type represented by this table (i.e. IQueryable of Product). Retrieves it from the provided
/// context instance, or instantiates a new context using the CreateContext().
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public virtual IQueryable GetQuery(object context) {
if (context == null) {
context = CreateContext();
}
IQueryable query = Provider.GetQuery(context);
if (EntityType != RootEntityType) {
Expression ofTypeExpression = Expression.Call(typeof(Queryable), "OfType", new[] { EntityType }, query.Expression);
query = query.Provider.CreateQuery(ofTypeExpression);
}
// Return the sorted query if there is a sort column
if (SortColumn != null) {
return Misc.BuildSortQueryable(query, this);
}
return query;
}
private void GetRouteValuesFromPK(RouteValueDictionary routeValues, IList<object> primaryKeyValues) {
if (primaryKeyValues != null) {
for (int i = 0; i < PrimaryKeyNames.Length; i++) {
routeValues.Add(PrimaryKeyNames[i], Misc.SanitizeQueryStringValue(primaryKeyValues[i]));
}
}
}
/// <summary>
/// Returns an enumeration of columns that are to be displayed in a scaffolded context. By default all columns with the Scaffold
/// property set to true are included, with the exception of:
/// <ul>
/// <li>Long-string columns (IsLongString property set to true) when the inListControl flag is true</li>
/// <li>Children columns when mode is equal to Insert</li>
/// </ul>
/// </summary>
/// <param name="mode">The mode, such as ReadOnly, Edit, or Insert.</param>
/// <param name="inListControl">A flag indicating if the table is being displayed as an individual entity or as part of list-grid.</param>
/// <returns></returns>
public virtual IEnumerable<MetaColumn> GetScaffoldColumns(DataBoundControlMode mode, ContainerType containerType) {
IDictionary<string, int> columnGroupOrder = GetColumnGroupingOrder();
return Columns.Where(c => IsScaffoldColumn(c, mode, containerType))
.OrderBy(c => GetColumnOrder(c, columnGroupOrder))
.ThenBy(c => GetColumnOrder(c));
}
/// <summary>
/// Gets the table associated with the given type, regardless of which model it belongs to.
/// </summary>
public static MetaTable GetTable(Type entityType) {
MetaTable table;
if (!TryGetTable(entityType, out table)) {
throw new InvalidOperationException(String.Format(
CultureInfo.CurrentCulture,
DynamicDataResources.MetaModel_EntityTypeDoesNotBelongToModel,
entityType.FullName));
}
return table;
}
/// <summary>
/// Perform initialization logic for this table
/// </summary>
internal protected virtual void Initialize() {
foreach (MetaColumn column in Columns) {
column.Initialize();
}
}
internal static bool IsFilterableColumn(IMetaColumn column, IPrincipal user) {
Debug.Assert(column != null);
var displayAttribute = column.Attributes.FirstOrDefault<DisplayAttribute>();
if (displayAttribute != null && displayAttribute.GetAutoGenerateFilter().HasValue) {
return displayAttribute.GetAutoGenerateFilter().Value;
}
if (!String.IsNullOrEmpty(column.FilterUIHint)) {
return true;
}
// non-scaffolded columns should not be displayed by default
if (!column.Scaffold) {
return false;
}
// custom properties won't be queryable by the server
if (column.IsCustomProperty) {
return false;
}
var fkColumn = column as IMetaForeignKeyColumn;
if (fkColumn != null) {
// Only allow if the user has access to the parent table
return fkColumn.ParentTable.CanRead(user);
}
if (column.ColumnType == typeof(bool)) {
return true;
}
if (column.GetEnumType() != null) {
return true;
}
return false;
}
private bool IsScaffoldColumn(IMetaColumn column, DataBoundControlMode mode, ContainerType containerType) {
if (!column.Scaffold) {
return false;
}
// 1:Many children columns don't make sense for new rows, so ignore them in Insert mode
if (mode == DataBoundControlMode.Insert) {
var childrenColumn = column as IMetaChildrenColumn;
if (childrenColumn != null && !childrenColumn.IsManyToMany) {
return false;
}
}
var fkColumn = column as IMetaForeignKeyColumn;
if (fkColumn != null) {
// Ignore the FK column if the user doesn't have access to the parent table
if (!fkColumn.ParentTable.CanRead(Context.User)) {
return false;
}
}
return true;
}
public IDictionary<string, object> GetColumnValuesFromRoute(HttpContext context) {
return GetColumnValuesFromRoute(context.ToWrapper());
}
internal IDictionary<string, object> GetColumnValuesFromRoute(HttpContextBase context) {
RouteValueDictionary routeValues = DynamicDataRouteHandler.GetRequestContext(context).RouteData.Values;
Dictionary<string, object> columnValues = new Dictionary<string, object>();
foreach (var column in Columns) {
if (Misc.IsColumnInDictionary(column, routeValues)) {
MetaForeignKeyColumn foreignKeyColumn = column as MetaForeignKeyColumn;
if (foreignKeyColumn != null) {
// Add all the foreign keys to the column values.
foreach (var fkName in foreignKeyColumn.ForeignKeyNames) {
columnValues[fkName] = routeValues[fkName];
}
}
else {
// Convert the value to the correct type.
columnValues[column.Name] = Misc.ChangeType(routeValues[column.Name], column.ColumnType);
}
}
}
return columnValues;
}
private object PreprocessRowObject(object row) {
// If null, nothing to do
if (row == null)
return null;
// If it's of the correct entity type, we're done
if (EntityType.IsAssignableFrom(row.GetType())) {
return row;
}
// If it's a list, try using the first item
var rowCollection = row as IList;
if (rowCollection != null) {
if (rowCollection.Count >= 1) {
Debug.Assert(rowCollection.Count == 1);
return PreprocessRowObject(rowCollection[0]);
}
}
// We didn't recoginze the object, so return it unchanged
return row;
}
/// <summary>
/// Resets cached table metadata (i.e. information coming from attributes) as well as metadata of all columns.
/// The metadata cache will be rebuilt the next time any metadata-derived information gets requested.
/// </summary>
public void ResetMetadata() {
_metadata = null;
_displayColumn = null;
_sortColumnProcessed = false;
foreach (var column in Columns) {
column.ResetMetadata();
}
}
internal void SetScaffoldAndName(bool scaffoldDefaultValue, string nameOverride) {
if (!String.IsNullOrEmpty(nameOverride)) {
Name = nameOverride;
}
else if (Provider != null) {
Name = Provider.Name;
}
_scaffoldDefaultValue = scaffoldDefaultValue;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
[SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
public override string ToString() {
return Name;
}
/// <summary>
/// Tries to find a column by the given name. If a column is found, it is assigned to the column
/// variable and the method returns true. Otherwise, it returns false and column is null.
/// </summary>
/// <param name="columnName"></param>
/// <param name="column"></param>
/// <returns></returns>
public bool TryGetColumn(string columnName, out MetaColumn column) {
if (columnName == null) {
throw new ArgumentNullException("columnName");
}
return _columnsByName.TryGetValue(columnName, out column);
}
/// <summary>
/// Gets the table associated with the given type, regardless of which model it belongs to.
/// </summary>
public static bool TryGetTable(Type entityType, out MetaTable table) {
MetaModel.CheckForRegistrationException();
if (entityType == null) {
throw new ArgumentNullException("entityType");
}
return System.Web.DynamicData.MetaModel.MetaModelManager.TryGetTable(entityType, out table);
}
#region IMetaTable Members
string[] IMetaTable.PrimaryKeyNames {
get {
return PrimaryKeyNames;
}
}
object IMetaTable.CreateContext() {
return CreateContext();
}
string IMetaTable.GetDisplayString(object row) {
return GetDisplayString(row);
}
IQueryable IMetaTable.GetQuery(object context) {
return GetQuery(context);
}
#endregion
private class MetaTableMetadata {
private DisplayNameAttribute _displayNameAttribute;
private ReadOnlyAttribute _readOnlyAttribute;
public MetaTableMetadata(MetaTable table) {
Debug.Assert(table != null);
Attributes = table.BuildAttributeCollection();
_readOnlyAttribute = Attributes.FirstOrDefault<ReadOnlyAttribute>();
_displayNameAttribute = Attributes.FirstOrDefault<DisplayNameAttribute>();
DisplayColumnAttribute = Attributes.FirstOrDefault<DisplayColumnAttribute>();
ScaffoldTable = Attributes.GetAttributePropertyValue<ScaffoldTableAttribute, bool?>(a => a.Scaffold, null);
}
public AttributeCollection Attributes { get; private set; }
public DisplayColumnAttribute DisplayColumnAttribute {
get;
private set;
}
public string DisplayName {
get {
return _displayNameAttribute.GetPropertyValue(a => a.DisplayName, null);
}
}
public bool? ScaffoldTable {
get;
private set;
}
public bool SortDescending {
get {
return DisplayColumnAttribute.GetPropertyValue(a => a.SortDescending, false);
}
}
public bool IsReadOnly {
get {
return _readOnlyAttribute.GetPropertyValue(a => a.IsReadOnly, false);
}
}
}
ReadOnlyCollection<IMetaColumn> IMetaTable.Columns {
get {
// Covariance only supported on interfaces
return Columns.OfType<IMetaColumn>().ToList().AsReadOnly();
}
}
IMetaModel IMetaTable.Model {
get {
return Model;
}
}
IMetaColumn IMetaTable.DisplayColumn {
get { return DisplayColumn; }
}
IMetaColumn IMetaTable.GetColumn(string columnName) {
return GetColumn(columnName);
}
IEnumerable<IMetaColumn> IMetaTable.GetFilteredColumns() {
// We can remove the of type when we get rid of the Vnext solution since interface covariance support
// was only added in 4.0
return GetFilteredColumns().OfType<IMetaColumn>();
}
IEnumerable<IMetaColumn> IMetaTable.GetScaffoldColumns(DataBoundControlMode mode, ContainerType containerType) {
// We can remove the of type when we get rid of the Vnext solution since interface covariance support
// was only added in 4.0
return GetScaffoldColumns(mode, containerType).OfType<IMetaColumn>();
}
ReadOnlyCollection<IMetaColumn> IMetaTable.PrimaryKeyColumns {
get {
return PrimaryKeyColumns.OfType<IMetaColumn>().ToList().AsReadOnly();
}
}
IMetaColumn IMetaTable.SortColumn {
get {
return SortColumn;
}
}
bool IMetaTable.TryGetColumn(string columnName, out IMetaColumn column) {
MetaColumn metaColumn;
column = null;
if (TryGetColumn(columnName, out metaColumn)) {
column = metaColumn;
return true;
}
return false;
}
bool IMetaTable.CanDelete(IPrincipal principal) {
return CanDelete(principal);
}
bool IMetaTable.CanInsert(IPrincipal principal) {
return CanInsert(principal);
}
bool IMetaTable.CanRead(IPrincipal principal) {
return CanRead(principal);
}
bool IMetaTable.CanUpdate(IPrincipal principal) {
return CanUpdate(principal);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Text;
using System.Xml;
using Microsoft.Build.Framework;
using Microsoft.Build.BuildEngine.Shared;
namespace Microsoft.Build.BuildEngine
{
/// <summary>
/// This class is a wrapper used to contain the data needed to execute a task. This class
/// is initially instantiated on the engine side by the scheduler and submitted to the node.
/// The node completes the class instantiating by providing the object with node side data.
/// This class is distinct from the task engine in that it (possibly) travels cross process
/// between the engine and the node carrying with it the data needed to instantiate the task
/// engine. The task engine can't subsume this class because the task engine is bound to the
/// node process and can't travel cross process.
/// </summary>
internal class TaskExecutionState
{
#region Constructors
/// <summary>
/// The constructor obtains the state information and the
/// callback delegate.
/// </summary>
internal TaskExecutionState
(
TaskExecutionMode howToExecuteTask,
Lookup lookupForInference,
Lookup lookupForExecution,
XmlElement taskXmlNode,
ITaskHost hostObject,
string projectFileOfTaskNode,
string parentProjectFullFileName,
string executionDirectory,
int handleId,
BuildEventContext buildEventContext
)
{
ErrorUtilities.VerifyThrow(taskXmlNode != null, "Must have task node");
this.howToExecuteTask = howToExecuteTask;
this.lookupForInference = lookupForInference;
this.lookupForExecution = lookupForExecution;
this.hostObject = hostObject;
this.projectFileOfTaskNode = projectFileOfTaskNode;
this.parentProjectFullFileName = parentProjectFullFileName;
this.executionDirectory = executionDirectory;
this.handleId = handleId;
this.buildEventContext = buildEventContext;
this.taskXmlNode = taskXmlNode;
}
#endregion
#region Properties
internal int HandleId
{
get
{
return this.handleId;
}
set
{
this.handleId = value;
}
}
internal EngineLoggingServices LoggingService
{
get
{
return this.loggingService;
}
set
{
this.loggingService = value;
}
}
internal TaskExecutionModule ParentModule
{
get
{
return this.parentModule;
}
set
{
this.parentModule = value;
}
}
internal string ExecutionDirectory
{
get
{
return this.executionDirectory;
}
}
internal bool ProfileExecution
{
get
{
return this.profileExecution;
}
set
{
this.profileExecution = value;
}
}
#endregion
#region Methods
/// <summary>
/// The thread procedure executes the tasks and calls callback once it is done
/// </summary>
virtual internal void ExecuteTask()
{
bool taskExecutedSuccessfully = true;
Exception thrownException = null;
bool dontPostOutputs = false;
if (profileExecution)
{
startTime = DateTime.Now.Ticks;
}
try
{
TaskEngine taskEngine = new TaskEngine(
taskXmlNode,
hostObject,
projectFileOfTaskNode,
parentProjectFullFileName,
loggingService,
handleId,
parentModule,
buildEventContext);
// Set the directory to the one appropriate for the task
if (FileUtilities.GetCurrentDirectoryStaticBuffer(currentDirectoryBuffer) != executionDirectory)
{
Directory.SetCurrentDirectory(executionDirectory);
}
// if we're skipping task execution because the target is up-to-date, we
// need to go ahead and infer all the outputs that would have been emitted;
// alternatively, if we're doing an incremental build, we need to infer the
// outputs that would have been produced if all the up-to-date items had
// been built by the task
if ((howToExecuteTask & TaskExecutionMode.InferOutputsOnly) != TaskExecutionMode.Invalid)
{
bool targetInferenceSuccessful = TaskEngineExecuteTask
(taskEngine,
TaskExecutionMode.InferOutputsOnly,
lookupForInference);
ErrorUtilities.VerifyThrow(targetInferenceSuccessful, "A task engine should never fail to infer its task's up-to-date outputs.");
}
// execute the task using the items that need to be (re)built
if ((howToExecuteTask & TaskExecutionMode.ExecuteTaskAndGatherOutputs) != TaskExecutionMode.Invalid)
{
taskExecutedSuccessfully =
TaskEngineExecuteTask
( taskEngine,
TaskExecutionMode.ExecuteTaskAndGatherOutputs,
lookupForExecution
);
}
}
// We want to catch all exceptions and pass them on to the engine
catch (Exception e)
{
thrownException = e;
taskExecutedSuccessfully = false;
// In single threaded mode the exception can be thrown on the current thread
if (parentModule.RethrowTaskExceptions())
{
dontPostOutputs = true;
throw;
}
}
finally
{
if (!dontPostOutputs)
{
long executionTime = profileExecution ? DateTime.Now.Ticks - startTime : 0;
// Post the outputs to the engine
parentModule.PostTaskOutputs(handleId, taskExecutedSuccessfully, thrownException, executionTime);
}
}
}
/// <summary>
/// This method is called to adjust the execution time for the task by subtracting the time
/// spent waiting for results
/// </summary>
/// <param name="entryTime"></param>
internal void NotifyOfWait(long waitStartTime)
{
// Move the start time forward by the period of the wait
startTime += (DateTime.Now.Ticks - waitStartTime);
}
#region MethodsNeededForUnitTesting
/// <summary>
/// Since we could not derrive from TaskEngine and have no Interface, we need to overide the method in here and
/// replace the calls when testing the class because of the calls to TaskEngine. If at a future time we get a mock task
/// engine, Interface or a non sealed TaskEngine these methods can disappear.
/// </summary>
/// <returns></returns>
virtual internal bool TaskEngineExecuteTask(
TaskEngine taskEngine,
TaskExecutionMode howTaskShouldBeExecuted,
Lookup lookup
)
{
return taskEngine.ExecuteTask
(
howTaskShouldBeExecuted,
lookup
);
}
#endregion
#endregion
#region Fields set by the Engine thread
private TaskExecutionMode howToExecuteTask;
private Lookup lookupForInference;
private Lookup lookupForExecution;
private ITaskHost hostObject;
private string projectFileOfTaskNode;
private string parentProjectFullFileName;
private string executionDirectory;
private int handleId;
private BuildEventContext buildEventContext;
#endregion
#region Fields set by the Task thread
private TaskExecutionModule parentModule;
private EngineLoggingServices loggingService;
private XmlElement taskXmlNode;
private long startTime;
private bool profileExecution;
private static StringBuilder currentDirectoryBuffer = new StringBuilder(270);
#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 TestMixOnesZerosInt16()
{
var test = new BooleanTwoComparisonOpTest__TestMixOnesZerosInt16();
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 BooleanTwoComparisonOpTest__TestMixOnesZerosInt16
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Int16);
private const int Op2ElementCount = VectorSize / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector128<Int16> _clsVar1;
private static Vector128<Int16> _clsVar2;
private Vector128<Int16> _fld1;
private Vector128<Int16> _fld2;
private BooleanTwoComparisonOpTest__DataTable<Int16, Int16> _dataTable;
static BooleanTwoComparisonOpTest__TestMixOnesZerosInt16()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize);
}
public BooleanTwoComparisonOpTest__TestMixOnesZerosInt16()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
_dataTable = new BooleanTwoComparisonOpTest__DataTable<Int16, Int16>(_data1, _data2, VectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse41.TestMixOnesZeros(
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
var result = Sse41.TestMixOnesZeros(
Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse41.TestMixOnesZeros(
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
var method = typeof(Sse41).GetMethod(nameof(Sse41.TestMixOnesZeros), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunReflectionScenario_Load()
{
var method = typeof(Sse41).GetMethod(nameof(Sse41.TestMixOnesZeros), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunReflectionScenario_LoadAligned()
{var method = typeof(Sse41).GetMethod(nameof(Sse41.TestMixOnesZeros), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunClsVarScenario()
{
var result = Sse41.TestMixOnesZeros(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr);
var result = Sse41.TestMixOnesZeros(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr));
var result = Sse41.TestMixOnesZeros(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr));
var result = Sse41.TestMixOnesZeros(left, right);
ValidateResult(left, right, result);
}
public void RunLclFldScenario()
{
var test = new BooleanTwoComparisonOpTest__TestMixOnesZerosInt16();
var result = Sse41.TestMixOnesZeros(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunFldScenario()
{
var result = Sse41.TestMixOnesZeros(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Int16> left, Vector128<Int16> right, bool result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* left, void* right, bool result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Int16[] left, Int16[] right, bool result, [CallerMemberName] string method = "")
{
var expectedResult1 = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult1 &= (((left[i] & right[i]) == 0));
}
var expectedResult2 = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult2 &= (((~left[i] & right[i]) == 0));
}
if (((expectedResult1 == false) && (expectedResult2 == false)) != result)
{
Succeeded = false;
Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.TestMixOnesZeros)}<Int16>(Vector128<Int16>, Vector128<Int16>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.Scripting.Utils;
namespace Microsoft.Scripting {
#if !FEATURE_PROCESS
public class ExitProcessException : Exception {
public int ExitCode { get { return exitCode; } }
int exitCode;
public ExitProcessException(int exitCode) {
this.exitCode = exitCode;
}
}
#endif
/// <summary>
/// Abstracts system operations that are used by DLR and could potentially be platform specific.
/// The host can implement its PAL to adapt DLR to the platform it is running on.
/// For example, the Silverlight host adapts some file operations to work against files on the server.
/// </summary>
[Serializable]
public class PlatformAdaptationLayer {
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly PlatformAdaptationLayer Default = new PlatformAdaptationLayer();
[Obsolete("This will be removed in the the future.")]
public static readonly bool IsCompactFramework = false;
public static bool IsNativeModule { get; } = _IsNativeModule();
private static bool _IsNativeModule() {
return typeof(void).Assembly.Modules.FirstOrDefault()?.ToString() == "<Unknown>";
}
#region Assembly Loading
public virtual Assembly LoadAssembly(string name) {
return Assembly.Load(name);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFile")]
public virtual Assembly LoadAssemblyFromPath(string path) {
#if FEATURE_FILESYSTEM
return Assembly.LoadFile(path);
#else
throw new NotImplementedException();
#endif
}
public virtual void TerminateScriptExecution(int exitCode) {
#if FEATURE_PROCESS
System.Environment.Exit(exitCode);
#else
throw new ExitProcessException(exitCode);
#endif
}
#endregion
#region Virtual File System
public virtual bool IsSingleRootFileSystem {
get {
#if FEATURE_FILESYSTEM
return Environment.OSVersion.Platform == PlatformID.Unix
|| Environment.OSVersion.Platform == PlatformID.MacOSX;
#else
return true;
#endif
}
}
public virtual StringComparer PathComparer {
get {
#if FEATURE_FILESYSTEM
return Environment.OSVersion.Platform == PlatformID.Unix ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase;
#else
return StringComparer.OrdinalIgnoreCase;
#endif
}
}
public virtual bool FileExists(string path) {
#if FEATURE_FILESYSTEM
return File.Exists(path);
#else
throw new NotImplementedException();
#endif
}
public virtual bool DirectoryExists(string path) {
#if FEATURE_FILESYSTEM
return Directory.Exists(path);
#else
throw new NotImplementedException();
#endif
}
// TODO: better APIs
public virtual Stream OpenFileStream(string path, FileMode mode = FileMode.OpenOrCreate, FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.Read, int bufferSize = 8192) {
#if FEATURE_FILESYSTEM
if (string.Equals("nul", path, StringComparison.InvariantCultureIgnoreCase)) {
return Stream.Null;
}
return new FileStream(path, mode, access, share, bufferSize);
#else
throw new NotImplementedException();
#endif
}
// TODO: better APIs
public virtual Stream OpenInputFileStream(string path, FileMode mode = FileMode.Open, FileAccess access = FileAccess.Read, FileShare share = FileShare.Read, int bufferSize = 8192) {
return OpenFileStream(path, mode, access, share, bufferSize);
}
// TODO: better APIs
public virtual Stream OpenOutputFileStream(string path) {
return OpenFileStream(path, FileMode.Create, FileAccess.Write);
}
public virtual void DeleteFile(string path, bool deleteReadOnly) {
#if FEATURE_FILESYSTEM
FileInfo info = new FileInfo(path);
if (deleteReadOnly && info.IsReadOnly) {
info.IsReadOnly = false;
}
info.Delete();
#else
throw new NotImplementedException();
#endif
}
public string[] GetFiles(string path, string searchPattern) {
return GetFileSystemEntries(path, searchPattern, true, false);
}
public string[] GetDirectories(string path, string searchPattern) {
return GetFileSystemEntries(path, searchPattern, false, true);
}
public string[] GetFileSystemEntries(string path, string searchPattern) {
return GetFileSystemEntries(path, searchPattern, true, true);
}
public virtual string[] GetFileSystemEntries(string path, string searchPattern, bool includeFiles, bool includeDirectories) {
#if FEATURE_FILESYSTEM
if (includeFiles && includeDirectories) {
return Directory.GetFileSystemEntries(path, searchPattern);
}
if (includeFiles) {
return Directory.GetFiles(path, searchPattern);
}
if (includeDirectories) {
return Directory.GetDirectories(path, searchPattern);
}
return ArrayUtils.EmptyStrings;
#else
throw new NotImplementedException();
#endif
}
/// <exception cref="ArgumentException">Invalid path.</exception>
public virtual string GetFullPath(string path) {
#if FEATURE_FILESYSTEM
try {
return Path.GetFullPath(path);
} catch (Exception) {
throw Error.InvalidPath();
}
#else
throw new NotImplementedException();
#endif
}
public virtual string CombinePaths(string path1, string path2) {
return Path.Combine(path1, path2);
}
public virtual string GetFileName(string path) {
return Path.GetFileName(path);
}
public virtual string GetDirectoryName(string path) {
return Path.GetDirectoryName(path);
}
public virtual string GetExtension(string path) {
return Path.GetExtension(path);
}
public virtual string GetFileNameWithoutExtension(string path) {
return Path.GetFileNameWithoutExtension(path);
}
/// <exception cref="ArgumentException">Invalid path.</exception>
public virtual bool IsAbsolutePath(string path) {
#if FEATURE_FILESYSTEM
// GetPathRoot returns either :
// "" -> relative to the current dir
// "\" -> relative to the drive of the current dir
// "X:" -> relative to the current dir, possibly on a different drive
// "X:\" -> absolute
if (IsSingleRootFileSystem) {
return Path.IsPathRooted(path);
}
var root = Path.GetPathRoot(path);
return root.EndsWith(@":\", StringComparison.Ordinal) || root.EndsWith(@":/", StringComparison.Ordinal);
#else
throw new NotImplementedException();
#endif
}
public virtual string CurrentDirectory {
get {
#if FEATURE_FILESYSTEM
return Directory.GetCurrentDirectory();
#else
throw new NotImplementedException();
#endif
}
set {
#if FEATURE_FILESYSTEM
Directory.SetCurrentDirectory(value);
#else
throw new NotImplementedException();
#endif
}
}
public virtual void CreateDirectory(string path) {
#if FEATURE_FILESYSTEM
Directory.CreateDirectory(path);
#else
throw new NotImplementedException();
#endif
}
public virtual void DeleteDirectory(string path, bool recursive) {
#if FEATURE_FILESYSTEM
Directory.Delete(path, recursive);
#else
throw new NotImplementedException();
#endif
}
public virtual void MoveFileSystemEntry(string sourcePath, string destinationPath) {
#if FEATURE_FILESYSTEM
Directory.Move(sourcePath, destinationPath);
#else
throw new NotImplementedException();
#endif
}
#endregion
#region Environmental Variables
public virtual string GetEnvironmentVariable(string key) {
#if FEATURE_PROCESS
return Environment.GetEnvironmentVariable(key);
#else
throw new NotImplementedException();
#endif
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")]
public virtual void SetEnvironmentVariable(string key, string value) {
#if FEATURE_PROCESS
if (value != null && value.Length == 0) {
SetEmptyEnvironmentVariable(key);
} else {
Environment.SetEnvironmentVariable(key, value);
}
#else
throw new NotImplementedException();
#endif
}
#if FEATURE_PROCESS
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2149:TransparentMethodsMustNotCallNativeCodeFxCopRule")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2140:TransparentMethodsMustNotReferenceCriticalCodeFxCopRule")]
[MethodImpl(MethodImplOptions.NoInlining)]
private static void SetEmptyEnvironmentVariable(string key) {
// System.Environment.SetEnvironmentVariable interprets an empty value string as
// deleting the environment variable. So we use the native SetEnvironmentVariable
// function here which allows setting of the value to an empty string.
// This will require high trust and will fail in sandboxed environments
if (!NativeMethods.SetEnvironmentVariable(key, String.Empty)) {
throw new ExternalException("SetEnvironmentVariable failed", Marshal.GetLastWin32Error());
}
}
#endif
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
public virtual Dictionary<string, string> GetEnvironmentVariables() {
#if FEATURE_PROCESS
var result = new Dictionary<string, string>();
foreach (DictionaryEntry entry in Environment.GetEnvironmentVariables())
{
result.Add((string)entry.Key, (string)entry.Value);
}
return result;
#else
throw new NotImplementedException();
#endif
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#nullable enable
using System;
using System.Collections.Generic;
using System.Management.Automation.Internal;
using System.Management.Automation.Language;
using System.Threading;
using System.Threading.Tasks;
namespace System.Management.Automation.Subsystem.Prediction
{
/// <summary>
/// The class represents the prediction result from a predictor.
/// </summary>
public sealed class PredictionResult
{
/// <summary>
/// Gets the Id of the predictor.
/// </summary>
public Guid Id { get; }
/// <summary>
/// Gets the name of the predictor.
/// </summary>
public string Name { get; }
/// <summary>
/// Gets the mini-session id that represents a specific invocation to the <see cref="ICommandPredictor.GetSuggestion"/> API of the predictor.
/// When it's not specified, it's considered by a client that the predictor doesn't expect feedback.
/// </summary>
public uint? Session { get; }
/// <summary>
/// Gets the suggestions.
/// </summary>
public IReadOnlyList<PredictiveSuggestion> Suggestions { get; }
internal PredictionResult(Guid id, string name, uint? session, List<PredictiveSuggestion> suggestions)
{
Id = id;
Name = name;
Session = session;
Suggestions = suggestions;
}
}
/// <summary>
/// Provides a set of possible predictions for given input.
/// </summary>
public static class CommandPrediction
{
/// <summary>
/// Collect the predictive suggestions from registered predictors using the default timeout.
/// </summary>
/// <param name="client">Represents the client that initiates the call.</param>
/// <param name="ast">The <see cref="Ast"/> object from parsing the current command line input.</param>
/// <param name="astTokens">The <see cref="Token"/> objects from parsing the current command line input.</param>
/// <returns>A list of <see cref="PredictionResult"/> objects.</returns>
public static Task<List<PredictionResult>?> PredictInputAsync(PredictionClient client, Ast ast, Token[] astTokens)
{
return PredictInputAsync(client, ast, astTokens, millisecondsTimeout: 20);
}
/// <summary>
/// Collect the predictive suggestions from registered predictors using the specified timeout.
/// </summary>
/// <param name="client">Represents the client that initiates the call.</param>
/// <param name="ast">The <see cref="Ast"/> object from parsing the current command line input.</param>
/// <param name="astTokens">The <see cref="Token"/> objects from parsing the current command line input.</param>
/// <param name="millisecondsTimeout">The milliseconds to timeout.</param>
/// <returns>A list of <see cref="PredictionResult"/> objects.</returns>
public static async Task<List<PredictionResult>?> PredictInputAsync(PredictionClient client, Ast ast, Token[] astTokens, int millisecondsTimeout)
{
Requires.Condition(millisecondsTimeout > 0, nameof(millisecondsTimeout));
var predictors = SubsystemManager.GetSubsystems<ICommandPredictor>();
if (predictors.Count == 0)
{
return null;
}
var context = new PredictionContext(ast, astTokens);
var tasks = new Task<PredictionResult?>[predictors.Count];
using var cancellationSource = new CancellationTokenSource();
Func<object?, PredictionResult?> callBack = GetCallBack(client, context, cancellationSource);
for (int i = 0; i < predictors.Count; i++)
{
ICommandPredictor predictor = predictors[i];
tasks[i] = Task.Factory.StartNew(
callBack,
predictor,
cancellationSource.Token,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
}
await Task.WhenAny(
Task.WhenAll(tasks),
Task.Delay(millisecondsTimeout, cancellationSource.Token)).ConfigureAwait(false);
cancellationSource.Cancel();
var resultList = new List<PredictionResult>(predictors.Count);
foreach (Task<PredictionResult?> task in tasks)
{
if (task.IsCompletedSuccessfully)
{
PredictionResult? result = task.Result;
if (result != null)
{
resultList.Add(result);
}
}
}
return resultList;
// A local helper function to avoid creating an instance of the generated delegate helper class
// when no predictor is registered.
static Func<object?, PredictionResult?> GetCallBack(
PredictionClient client,
PredictionContext context,
CancellationTokenSource cancellationSource)
{
return state =>
{
var predictor = (ICommandPredictor)state!;
SuggestionPackage pkg = predictor.GetSuggestion(client, context, cancellationSource.Token);
return pkg.SuggestionEntries?.Count > 0 ? new PredictionResult(predictor.Id, predictor.Name, pkg.Session, pkg.SuggestionEntries) : null;
};
}
}
/// <summary>
/// Allow registered predictors to do early processing when a command line is accepted.
/// </summary>
/// <param name="client">Represents the client that initiates the call.</param>
/// <param name="history">History command lines provided as references for prediction.</param>
public static void OnCommandLineAccepted(PredictionClient client, IReadOnlyList<string> history)
{
Requires.NotNull(history, nameof(history));
var predictors = SubsystemManager.GetSubsystems<ICommandPredictor>();
if (predictors.Count == 0)
{
return;
}
Action<ICommandPredictor>? callBack = null;
foreach (ICommandPredictor predictor in predictors)
{
if (predictor.CanAcceptFeedback(client, PredictorFeedbackKind.CommandLineAccepted))
{
callBack ??= GetCallBack(client, history);
ThreadPool.QueueUserWorkItem<ICommandPredictor>(callBack, predictor, preferLocal: false);
}
}
// A local helper function to avoid creating an instance of the generated delegate helper class
// when no predictor is registered, or no registered predictor accepts this feedback.
static Action<ICommandPredictor> GetCallBack(PredictionClient client, IReadOnlyList<string> history)
{
return predictor => predictor.OnCommandLineAccepted(client, history);
}
}
/// <summary>
/// Allow registered predictors to know the execution result (success/failure) of the last accepted command line.
/// </summary>
/// <param name="client">Represents the client that initiates the call.</param>
/// <param name="commandLine">The last accepted command line.</param>
/// <param name="success">Whether the execution of the last command line was successful.</param>
public static void OnCommandLineExecuted(PredictionClient client, string commandLine, bool success)
{
var predictors = SubsystemManager.GetSubsystems<ICommandPredictor>();
if (predictors.Count == 0)
{
return;
}
Action<ICommandPredictor>? callBack = null;
foreach (ICommandPredictor predictor in predictors)
{
if (predictor.CanAcceptFeedback(client, PredictorFeedbackKind.CommandLineExecuted))
{
callBack ??= GetCallBack(client, commandLine, success);
ThreadPool.QueueUserWorkItem<ICommandPredictor>(callBack, predictor, preferLocal: false);
}
}
// A local helper function to avoid creating an instance of the generated delegate helper class
// when no predictor is registered, or no registered predictor accepts this feedback.
static Action<ICommandPredictor> GetCallBack(PredictionClient client, string commandLine, bool success)
{
return predictor => predictor.OnCommandLineExecuted(client, commandLine, success);
}
}
/// <summary>
/// Send feedback to a predictor when one or more suggestions from it were displayed to the user.
/// </summary>
/// <param name="client">Represents the client that initiates the call.</param>
/// <param name="predictorId">The identifier of the predictor whose prediction result was accepted.</param>
/// <param name="session">The mini-session where the displayed suggestions came from.</param>
/// <param name="countOrIndex">
/// When the value is greater than 0, it's the number of displayed suggestions from the list returned in <paramref name="session"/>, starting from the index 0.
/// When the value is less than or equal to 0, it means a single suggestion from the list got displayed, and the index is the absolute value.
/// </param>
public static void OnSuggestionDisplayed(PredictionClient client, Guid predictorId, uint session, int countOrIndex)
{
var predictors = SubsystemManager.GetSubsystems<ICommandPredictor>();
if (predictors.Count == 0)
{
return;
}
foreach (ICommandPredictor predictor in predictors)
{
if (predictor.Id == predictorId)
{
if (predictor.CanAcceptFeedback(client, PredictorFeedbackKind.SuggestionDisplayed))
{
Action<ICommandPredictor> callBack = GetCallBack(client, session, countOrIndex);
ThreadPool.QueueUserWorkItem<ICommandPredictor>(callBack, predictor, preferLocal: false);
}
break;
}
}
// A local helper function to avoid creating an instance of the generated delegate helper class
// when no predictor is registered, or no registered predictor accepts this feedback.
static Action<ICommandPredictor> GetCallBack(PredictionClient client, uint session, int countOrIndex)
{
return predictor => predictor.OnSuggestionDisplayed(client, session, countOrIndex);
}
}
/// <summary>
/// Send feedback to a predictor when a suggestion from it was accepted.
/// </summary>
/// <param name="client">Represents the client that initiates the call.</param>
/// <param name="predictorId">The identifier of the predictor whose prediction result was accepted.</param>
/// <param name="session">The mini-session where the accepted suggestion came from.</param>
/// <param name="suggestionText">The accepted suggestion text.</param>
public static void OnSuggestionAccepted(PredictionClient client, Guid predictorId, uint session, string suggestionText)
{
Requires.NotNullOrEmpty(suggestionText, nameof(suggestionText));
var predictors = SubsystemManager.GetSubsystems<ICommandPredictor>();
if (predictors.Count == 0)
{
return;
}
foreach (ICommandPredictor predictor in predictors)
{
if (predictor.Id == predictorId)
{
if (predictor.CanAcceptFeedback(client, PredictorFeedbackKind.SuggestionAccepted))
{
Action<ICommandPredictor> callBack = GetCallBack(client, session, suggestionText);
ThreadPool.QueueUserWorkItem<ICommandPredictor>(callBack, predictor, preferLocal: false);
}
break;
}
}
// A local helper function to avoid creating an instance of the generated delegate helper class
// when no predictor is registered, or no registered predictor accepts this feedback.
static Action<ICommandPredictor> GetCallBack(PredictionClient client, uint session, string suggestionText)
{
return predictor => predictor.OnSuggestionAccepted(client, session, suggestionText);
}
}
}
}
| |
using ChainUtils.BouncyCastle.Crypto.Utilities;
namespace ChainUtils.BouncyCastle.Crypto.Engines
{
/**
* A class that provides CAST6 key encryption operations,
* such as encoding data and generating keys.
*
* All the algorithms herein are from the Internet RFC
*
* RFC2612 - CAST6 (128bit block, 128-256bit key)
*
* and implement a simplified cryptography interface.
*/
public sealed class Cast6Engine
: Cast5Engine
{
//====================================
// Useful constants
//====================================
private const int ROUNDS = 12;
private const int BLOCK_SIZE = 16; // bytes = 128 bits
/*
* Put the round and mask keys into an array.
* Kr0[i] => _Kr[i*4 + 0]
*/
private int []_Kr = new int[ROUNDS*4]; // the rotating round key(s)
private uint []_Km = new uint[ROUNDS*4]; // the masking round key(s)
/*
* Key setup
*/
private int []_Tr = new int[24 * 8];
private uint []_Tm = new uint[24 * 8];
private uint[] _workingKey = new uint[8];
public Cast6Engine()
{
}
public override string AlgorithmName
{
get { return "CAST6"; }
}
public override void Reset()
{
}
public override int GetBlockSize()
{
return BLOCK_SIZE;
}
//==================================
// Private Implementation
//==================================
/*
* Creates the subkeys using the same nomenclature
* as described in RFC2612.
*
* See section 2.4
*/
internal override void SetKey(
byte[] key)
{
uint Cm = 0x5a827999;
uint Mm = 0x6ed9eba1;
var Cr = 19;
var Mr = 17;
/*
* Determine the key size here, if required
*
* if keysize < 256 bytes, pad with 0
*
* Typical key sizes => 128, 160, 192, 224, 256
*/
for (var i=0; i< 24; i++)
{
for (var j=0; j< 8; j++)
{
_Tm[i*8 + j] = Cm;
Cm += Mm; //mod 2^32;
_Tr[i*8 + j] = Cr;
Cr = (Cr + Mr) & 0x1f; // mod 32
}
}
var tmpKey = new byte[64];
key.CopyTo(tmpKey, 0);
// now create ABCDEFGH
for (var i = 0; i < 8; i++)
{
_workingKey[i] = Pack.BE_To_UInt32(tmpKey, i*4);
}
// Generate the key schedule
for (var i = 0; i < 12; i++)
{
// KAPPA <- W2i(KAPPA)
var i2 = i*2 *8;
_workingKey[6] ^= F1(_workingKey[7], _Tm[i2], _Tr[i2]);
_workingKey[5] ^= F2(_workingKey[6], _Tm[i2+1], _Tr[i2+1]);
_workingKey[4] ^= F3(_workingKey[5], _Tm[i2+2], _Tr[i2+2]);
_workingKey[3] ^= F1(_workingKey[4], _Tm[i2+3], _Tr[i2+3]);
_workingKey[2] ^= F2(_workingKey[3], _Tm[i2+4], _Tr[i2+4]);
_workingKey[1] ^= F3(_workingKey[2], _Tm[i2+5], _Tr[i2+5]);
_workingKey[0] ^= F1(_workingKey[1], _Tm[i2+6], _Tr[i2+6]);
_workingKey[7] ^= F2(_workingKey[0], _Tm[i2+7], _Tr[i2+7]);
// KAPPA <- W2i+1(KAPPA)
i2 = (i*2 + 1)*8;
_workingKey[6] ^= F1(_workingKey[7], _Tm[i2], _Tr[i2]);
_workingKey[5] ^= F2(_workingKey[6], _Tm[i2+1], _Tr[i2+1]);
_workingKey[4] ^= F3(_workingKey[5], _Tm[i2+2], _Tr[i2+2]);
_workingKey[3] ^= F1(_workingKey[4], _Tm[i2+3], _Tr[i2+3]);
_workingKey[2] ^= F2(_workingKey[3], _Tm[i2+4], _Tr[i2+4]);
_workingKey[1] ^= F3(_workingKey[2], _Tm[i2+5], _Tr[i2+5]);
_workingKey[0] ^= F1(_workingKey[1], _Tm[i2+6], _Tr[i2+6]);
_workingKey[7] ^= F2(_workingKey[0], _Tm[i2+7], _Tr[i2+7]);
// Kr_(i) <- KAPPA
_Kr[i*4] = (int)(_workingKey[0] & 0x1f);
_Kr[i*4 + 1] = (int)(_workingKey[2] & 0x1f);
_Kr[i*4 + 2] = (int)(_workingKey[4] & 0x1f);
_Kr[i*4 + 3] = (int)(_workingKey[6] & 0x1f);
// Km_(i) <- KAPPA
_Km[i*4] = _workingKey[7];
_Km[i*4 + 1] = _workingKey[5];
_Km[i*4 + 2] = _workingKey[3];
_Km[i*4 + 3] = _workingKey[1];
}
}
/**
* Encrypt the given input starting at the given offset and place
* the result in the provided buffer starting at the given offset.
*
* @param src The plaintext buffer
* @param srcIndex An offset into src
* @param dst The ciphertext buffer
* @param dstIndex An offset into dst
*/
internal override int EncryptBlock(
byte[] src,
int srcIndex,
byte[] dst,
int dstIndex)
{
// process the input block
// batch the units up into 4x32 bit chunks and go for it
var A = Pack.BE_To_UInt32(src, srcIndex);
var B = Pack.BE_To_UInt32(src, srcIndex + 4);
var C = Pack.BE_To_UInt32(src, srcIndex + 8);
var D = Pack.BE_To_UInt32(src, srcIndex + 12);
var result = new uint[4];
CAST_Encipher(A, B, C, D, result);
// now stuff them into the destination block
Pack.UInt32_To_BE(result[0], dst, dstIndex);
Pack.UInt32_To_BE(result[1], dst, dstIndex + 4);
Pack.UInt32_To_BE(result[2], dst, dstIndex + 8);
Pack.UInt32_To_BE(result[3], dst, dstIndex + 12);
return BLOCK_SIZE;
}
/**
* Decrypt the given input starting at the given offset and place
* the result in the provided buffer starting at the given offset.
*
* @param src The plaintext buffer
* @param srcIndex An offset into src
* @param dst The ciphertext buffer
* @param dstIndex An offset into dst
*/
internal override int DecryptBlock(
byte[] src,
int srcIndex,
byte[] dst,
int dstIndex)
{
// process the input block
// batch the units up into 4x32 bit chunks and go for it
var A = Pack.BE_To_UInt32(src, srcIndex);
var B = Pack.BE_To_UInt32(src, srcIndex + 4);
var C = Pack.BE_To_UInt32(src, srcIndex + 8);
var D = Pack.BE_To_UInt32(src, srcIndex + 12);
var result = new uint[4];
CAST_Decipher(A, B, C, D, result);
// now stuff them into the destination block
Pack.UInt32_To_BE(result[0], dst, dstIndex);
Pack.UInt32_To_BE(result[1], dst, dstIndex + 4);
Pack.UInt32_To_BE(result[2], dst, dstIndex + 8);
Pack.UInt32_To_BE(result[3], dst, dstIndex + 12);
return BLOCK_SIZE;
}
/**
* Does the 12 quad rounds rounds to encrypt the block.
*
* @param A the 00-31 bits of the plaintext block
* @param B the 32-63 bits of the plaintext block
* @param C the 64-95 bits of the plaintext block
* @param D the 96-127 bits of the plaintext block
* @param result the resulting ciphertext
*/
private void CAST_Encipher(
uint A,
uint B,
uint C,
uint D,
uint[] result)
{
for (var i = 0; i < 6; i++)
{
var x = i*4;
// BETA <- Qi(BETA)
C ^= F1(D, _Km[x], _Kr[x]);
B ^= F2(C, _Km[x + 1], _Kr[x + 1]);
A ^= F3(B, _Km[x + 2], _Kr[x + 2]);
D ^= F1(A, _Km[x + 3], _Kr[x + 3]);
}
for (var i = 6; i < 12; i++)
{
var x = i*4;
// BETA <- QBARi(BETA)
D ^= F1(A, _Km[x + 3], _Kr[x + 3]);
A ^= F3(B, _Km[x + 2], _Kr[x + 2]);
B ^= F2(C, _Km[x + 1], _Kr[x + 1]);
C ^= F1(D, _Km[x], _Kr[x]);
}
result[0] = A;
result[1] = B;
result[2] = C;
result[3] = D;
}
/**
* Does the 12 quad rounds rounds to decrypt the block.
*
* @param A the 00-31 bits of the ciphertext block
* @param B the 32-63 bits of the ciphertext block
* @param C the 64-95 bits of the ciphertext block
* @param D the 96-127 bits of the ciphertext block
* @param result the resulting plaintext
*/
private void CAST_Decipher(
uint A,
uint B,
uint C,
uint D,
uint[] result)
{
for (var i = 0; i < 6; i++)
{
var x = (11-i)*4;
// BETA <- Qi(BETA)
C ^= F1(D, _Km[x], _Kr[x]);
B ^= F2(C, _Km[x + 1], _Kr[x + 1]);
A ^= F3(B, _Km[x + 2], _Kr[x + 2]);
D ^= F1(A, _Km[x + 3], _Kr[x + 3]);
}
for (var i=6; i<12; i++)
{
var x = (11-i)*4;
// BETA <- QBARi(BETA)
D ^= F1(A, _Km[x + 3], _Kr[x + 3]);
A ^= F3(B, _Km[x + 2], _Kr[x + 2]);
B ^= F2(C, _Km[x + 1], _Kr[x + 1]);
C ^= F1(D, _Km[x], _Kr[x]);
}
result[0] = A;
result[1] = B;
result[2] = C;
result[3] = D;
}
}
}
| |
// Copyright (c) Martin Costello, 2017. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
using System.Security.Claims;
using MartinCostello.LondonTravel.Site.Identity;
using MartinCostello.LondonTravel.Site.Options;
using MartinCostello.LondonTravel.Site.Telemetry;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using NodaTime;
namespace MartinCostello.LondonTravel.Site.Controllers;
[Authorize]
[Route("account", Name = SiteRoutes.Account)]
public partial class AccountController : Controller
{
/// <summary>
/// The names of the authentication schemes that are disallowed for
/// sign-in to link Alexa to an account. This field is read-only.
/// </summary>
private static readonly string[] AuthenticationSchemesDisabledForAlexa = { "apple", "github", "google" };
private readonly UserManager<LondonTravelUser> _userManager;
private readonly SignInManager<LondonTravelUser> _signInManager;
private readonly ISiteTelemetry _telemetry;
private readonly IClock _clock;
private readonly bool _isEnabled;
private readonly ILogger _logger;
public AccountController(
UserManager<LondonTravelUser> userManager,
SignInManager<LondonTravelUser> signInManager,
ISiteTelemetry telemetry,
IClock clock,
SiteOptions siteOptions,
ILogger<AccountController> logger)
{
_userManager = userManager;
_signInManager = signInManager;
_telemetry = telemetry;
_clock = clock;
_logger = logger;
_isEnabled =
siteOptions?.Authentication?.IsEnabled == true &&
siteOptions?.Authentication.ExternalProviders?.Any((p) => p.Value?.IsEnabled == true) == true;
}
[AllowAnonymous]
[HttpGet]
[Route("sign-in", Name = SiteRoutes.SignIn)]
public async Task<IActionResult> SignIn(string? returnUrl = null)
{
if (!_isEnabled)
{
return NotFound();
}
if (User?.Identity?.IsAuthenticated == true)
{
return RedirectToPage(SiteRoutes.Home);
}
Uri? returnUri = null;
if (returnUrl != null &&
!Uri.TryCreate(returnUrl, UriKind.Relative, out returnUri))
{
return RedirectToPage(SiteRoutes.Home);
}
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
ViewData["ReturnUrl"] = returnUrl;
string viewName = nameof(SignIn);
if (IsRedirectAlexaAuthorization(returnUri?.ToString()))
{
viewName += "Alexa";
ViewData["AuthenticationSchemesToHide"] = AuthenticationSchemesDisabledForAlexa;
}
return View(viewName);
}
[HttpPost]
[Route("sign-out", Name = SiteRoutes.SignOut)]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SignOutPost()
{
if (!_isEnabled)
{
return NotFound();
}
string userId = _userManager.GetUserId(User);
await _signInManager.SignOutAsync();
Log.UserSignedOut(_logger, userId);
_telemetry.TrackSignOut(userId);
return RedirectToPage(SiteRoutes.Home);
}
[AllowAnonymous]
[HttpPost]
[Route("external-sign-in", Name = SiteRoutes.ExternalSignIn)]
[ValidateAntiForgeryToken]
public IActionResult ExternalSignIn(string? provider, string? returnUrl = null)
{
if (string.IsNullOrWhiteSpace(provider))
{
return BadRequest();
}
if (!_isEnabled)
{
return NotFound();
}
string? redirectUrl = Url.RouteUrl(SiteRoutes.ExternalSignInCallback, new { ReturnUrl = returnUrl });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
string errorRedirectUrl = GetErrorRedirectUrl();
SiteContext.SetErrorRedirect(properties, errorRedirectUrl);
return Challenge(properties, provider);
}
[AllowAnonymous]
[Route("external-sign-in-callback", Name = SiteRoutes.ExternalSignInCallback)]
[HttpGet]
public async Task<IActionResult> ExternalSignInCallback(string? returnUrl = null, string? remoteError = null)
{
if (!_isEnabled)
{
return NotFound();
}
if (remoteError != null)
{
Log.RemoteSignInError(_logger, remoteError);
return View(nameof(SignIn));
}
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return RedirectToRoute(SiteRoutes.SignIn);
}
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: true);
if (result.Succeeded)
{
string userId = _userManager.GetUserId(info.Principal);
Log.UserSignedIn(_logger, userId, info.LoginProvider);
_telemetry.TrackSignIn(userId, info.LoginProvider);
return RedirectToLocal(returnUrl);
}
if (result.IsLockedOut)
{
return View("LockedOut");
}
else
{
LondonTravelUser? user = CreateSystemUser(info);
if (!Uri.TryCreate(returnUrl, UriKind.Relative, out Uri? returnUri))
{
returnUri = null;
}
if (string.IsNullOrEmpty(user?.Email))
{
ViewData["Message"] = nameof(SiteMessage.PermissionDenied);
ViewData["ReturnUrl"] = returnUri?.ToString();
return View("SignIn");
}
var identityResult = await _userManager.CreateAsync(user);
if (identityResult.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: true);
Log.UserCreated(_logger, user.Id, info.LoginProvider);
_telemetry.TrackAccountCreated(user.Id!, user.Email, info.LoginProvider);
if (returnUri != null && IsRedirectAlexaAuthorization(returnUri.ToString()))
{
return Redirect(returnUri.ToString());
}
else
{
return RedirectToPage(SiteRoutes.Home, new { Message = SiteMessage.AccountCreated });
}
}
bool isUserAlreadyRegistered = identityResult.Errors.Any((p) => p.Code.StartsWith("Duplicate", StringComparison.Ordinal));
AddErrors(identityResult);
if (isUserAlreadyRegistered)
{
ViewData["Message"] = nameof(SiteMessage.AlreadyRegistered);
ViewData["ReturnUrl"] = Url.RouteUrl("Manage");
}
else
{
ViewData["ReturnUrl"] = returnUrl;
}
return View("SignIn");
}
}
private static bool IsRedirectAlexaAuthorization(string? returnUrl) => IsUrlOtherUrl(returnUrl, "/alexa/authorize");
private static bool IsUrlOtherUrl(string? url, string targetUrl)
{
if (string.IsNullOrWhiteSpace(url) ||
!Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out Uri? uri))
{
return false;
}
if (uri.IsAbsoluteUri)
{
return string.Equals(uri.AbsolutePath, targetUrl, StringComparison.OrdinalIgnoreCase);
}
else
{
int indexOfQuery = url.IndexOf('?', StringComparison.Ordinal);
if (indexOfQuery > -1)
{
url = url[..indexOfQuery];
}
return string.Equals(url.TrimEnd('/'), targetUrl!.TrimEnd('/'), StringComparison.OrdinalIgnoreCase);
}
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
Log.IdentityError(_logger, error.Code, error.Description);
ModelState.AddModelError(string.Empty, error.Description);
}
}
private IActionResult RedirectToLocal(string? returnUrl)
{
if (returnUrl != null && Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToPage(SiteRoutes.Home);
}
}
private LondonTravelUser? CreateSystemUser(ExternalLoginInfo info)
{
string? email = info.Principal.FindFirstValue(ClaimTypes.Email);
if (string.IsNullOrEmpty(email))
{
return null;
}
string? givenName = info.Principal.FindFirstValue(ClaimTypes.GivenName);
string? surname = info.Principal.FindFirstValue(ClaimTypes.Surname);
var user = new LondonTravelUser()
{
CreatedAt = _clock.GetCurrentInstant().ToDateTimeUtc(),
Email = email,
GivenName = givenName,
Surname = surname,
UserName = email,
EmailConfirmed = false,
};
user.Logins.Add(LondonTravelLoginInfo.FromUserLoginInfo(info));
foreach (var claim in info.Principal.Claims)
{
user.RoleClaims.Add(LondonTravelRole.FromClaim(claim));
}
return user;
}
private string GetErrorRedirectUrl()
{
return (IsReferrerRegistrationPage() ? Url.Page(SiteRoutes.Register) : Url.RouteUrl(SiteRoutes.SignIn))!;
}
private bool IsReferrerRegistrationPage() => IsReferrerPageOrRoute(SiteRoutes.Register);
private bool IsReferrerPageOrRoute(string routeName)
{
return IsUrlPageOrRoute(HttpContext.Request.Headers["referer"], routeName);
}
private bool IsUrlPageOrRoute(string? url, string pageOrRouteName)
{
if (string.IsNullOrWhiteSpace(url) ||
!Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out Uri? uri))
{
return false;
}
string? targetUrl = Url.RouteUrl(pageOrRouteName);
if (targetUrl is null)
{
targetUrl = Url.Page(pageOrRouteName);
}
if (uri.IsAbsoluteUri)
{
return string.Equals(uri.AbsolutePath, targetUrl, StringComparison.OrdinalIgnoreCase);
}
else
{
int indexOfQuery = url.IndexOf('?', StringComparison.Ordinal);
if (indexOfQuery > -1)
{
url = url[..indexOfQuery];
}
return string.Equals(url.TrimEnd('/'), targetUrl!.TrimEnd('/'), StringComparison.OrdinalIgnoreCase);
}
}
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
private static partial class Log
{
[LoggerMessage(
EventId = 1,
Level = LogLevel.Information,
Message = "User Id {UserId} signed out.")]
public static partial void UserSignedOut(ILogger logger, string userId);
[LoggerMessage(
EventId = 2,
Level = LogLevel.Warning,
Message = "Error from external provider. {RemoteError}")]
public static partial void RemoteSignInError(ILogger logger, string remoteError);
[LoggerMessage(
EventId = 3,
Level = LogLevel.Information,
Message = "User Id {UserId} signed in with provider {LoginProvider}.")]
public static partial void UserSignedIn(ILogger logger, string userId, string loginProvider);
[LoggerMessage(
EventId = 4,
Level = LogLevel.Information,
Message = "New user account {UserId} created through {LoginProvider}.")]
public static partial void UserCreated(ILogger logger, string? userId, string loginProvider);
[LoggerMessage(
EventId = 5,
Level = LogLevel.Warning,
Message = "{ErrorCode}: {ErrorDescription}")]
public static partial void IdentityError(ILogger logger, string errorCode, string errorDescription);
}
}
| |
// 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;
#if ES_BUILD_STANDALONE
using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment;
namespace Microsoft.Diagnostics.Tracing
#else
namespace System.Diagnostics.Tracing
#endif
{
/// <summary>
/// TraceLogging: used when implementing a custom TraceLoggingTypeInfo.
/// An instance of this type is provided to the TypeInfo.WriteMetadata method.
/// </summary>
internal class TraceLoggingMetadataCollector
{
private readonly Impl impl;
private readonly FieldMetadata currentGroup;
private int bufferedArrayFieldCount = int.MinValue;
/// <summary>
/// Creates a root-level collector.
/// </summary>
internal TraceLoggingMetadataCollector()
{
this.impl = new Impl();
}
/// <summary>
/// Creates a collector for a group.
/// </summary>
/// <param name="other">Parent collector</param>
/// <param name="group">The field that starts the group</param>
private TraceLoggingMetadataCollector(
TraceLoggingMetadataCollector other,
FieldMetadata group)
{
this.impl = other.impl;
this.currentGroup = group;
}
/// <summary>
/// The field tags to be used for the next field.
/// This will be reset to None each time a field is written.
/// </summary>
internal EventFieldTags Tags
{
get;
set;
}
internal int ScratchSize
{
get { return this.impl.scratchSize; }
}
internal int DataCount
{
get { return this.impl.dataCount; }
}
internal int PinCount
{
get { return this.impl.pinCount; }
}
private bool BeginningBufferedArray
{
get { return this.bufferedArrayFieldCount == 0; }
}
/// <summary>
/// Call this method to add a group to the event and to return
/// a new metadata collector that can be used to add fields to the
/// group. After all of the fields in the group have been written,
/// switch back to the original metadata collector to add fields
/// outside of the group.
/// Special-case: if name is null, no group is created, and AddGroup
/// returns the original metadata collector. This is useful when
/// adding the top-level group for an event.
/// Note: do not use the original metadata collector while the group's
/// metadata collector is in use, and do not use the group's metadata
/// collector after switching back to the original.
/// </summary>
/// <param name="name">
/// The name of the group. If name is null, the call to AddGroup is a
/// no-op (collector.AddGroup(null) returns collector).
/// </param>
/// <returns>
/// A new metadata collector that can be used to add fields to the group.
/// </returns>
public TraceLoggingMetadataCollector AddGroup(string name)
{
TraceLoggingMetadataCollector result = this;
if (name != null || // Normal.
this.BeginningBufferedArray) // Error, FieldMetadata's constructor will throw the appropriate exception.
{
var newGroup = new FieldMetadata(
name,
TraceLoggingDataType.Struct,
0,
this.BeginningBufferedArray);
this.AddField(newGroup);
result = new TraceLoggingMetadataCollector(this, newGroup);
}
return result;
}
/// <summary>
/// Adds a scalar field to an event.
/// </summary>
/// <param name="name">
/// The name to use for the added field. This value must not be null.
/// </param>
/// <param name="type">
/// The type code for the added field. This must be a fixed-size type
/// (e.g. string types are not supported).
/// </param>
public void AddScalar(string name, TraceLoggingDataType type)
{
int size;
switch ((TraceLoggingDataType)((int)type & Statics.InTypeMask))
{
case TraceLoggingDataType.Int8:
case TraceLoggingDataType.UInt8:
case TraceLoggingDataType.Char8:
size = 1;
break;
case TraceLoggingDataType.Int16:
case TraceLoggingDataType.UInt16:
case TraceLoggingDataType.Char16:
size = 2;
break;
case TraceLoggingDataType.Int32:
case TraceLoggingDataType.UInt32:
case TraceLoggingDataType.HexInt32:
case TraceLoggingDataType.Float:
case TraceLoggingDataType.Boolean32:
size = 4;
break;
case TraceLoggingDataType.Int64:
case TraceLoggingDataType.UInt64:
case TraceLoggingDataType.HexInt64:
case TraceLoggingDataType.Double:
case TraceLoggingDataType.FileTime:
size = 8;
break;
case TraceLoggingDataType.Guid:
case TraceLoggingDataType.SystemTime:
size = 16;
break;
default:
throw new ArgumentOutOfRangeException("type");
}
this.impl.AddScalar(size);
this.AddField(new FieldMetadata(name, type, this.Tags, this.BeginningBufferedArray));
}
/// <summary>
/// Adds a binary-format field to an event.
/// Compatible with core types: Binary, CountedUtf16String, CountedMbcsString.
/// Compatible with dataCollector methods: AddBinary(string), AddArray(Any8bitType[]).
/// </summary>
/// <param name="name">
/// The name to use for the added field. This value must not be null.
/// </param>
/// <param name="type">
/// The type code for the added field. This must be a Binary or CountedString type.
/// </param>
public void AddBinary(string name, TraceLoggingDataType type)
{
switch ((TraceLoggingDataType)((int)type & Statics.InTypeMask))
{
case TraceLoggingDataType.Binary:
case TraceLoggingDataType.CountedMbcsString:
case TraceLoggingDataType.CountedUtf16String:
break;
default:
throw new ArgumentOutOfRangeException("type");
}
this.impl.AddScalar(2);
this.impl.AddNonscalar();
this.AddField(new FieldMetadata(name, type, this.Tags, this.BeginningBufferedArray));
}
/// <summary>
/// Adds an array field to an event.
/// </summary>
/// <param name="name">
/// The name to use for the added field. This value must not be null.
/// </param>
/// <param name="type">
/// The type code for the added field. This must be a fixed-size type
/// or a string type. In the case of a string type, this adds an array
/// of characters, not an array of strings.
/// </param>
public void AddArray(string name, TraceLoggingDataType type)
{
switch ((TraceLoggingDataType)((int)type & Statics.InTypeMask))
{
case TraceLoggingDataType.Utf16String:
case TraceLoggingDataType.MbcsString:
case TraceLoggingDataType.Int8:
case TraceLoggingDataType.UInt8:
case TraceLoggingDataType.Int16:
case TraceLoggingDataType.UInt16:
case TraceLoggingDataType.Int32:
case TraceLoggingDataType.UInt32:
case TraceLoggingDataType.Int64:
case TraceLoggingDataType.UInt64:
case TraceLoggingDataType.Float:
case TraceLoggingDataType.Double:
case TraceLoggingDataType.Boolean32:
case TraceLoggingDataType.Guid:
case TraceLoggingDataType.FileTime:
case TraceLoggingDataType.HexInt32:
case TraceLoggingDataType.HexInt64:
case TraceLoggingDataType.Char16:
case TraceLoggingDataType.Char8:
break;
default:
throw new ArgumentOutOfRangeException("type");
}
if (this.BeginningBufferedArray)
{
throw new NotSupportedException(Environment.GetResourceString("EventSource_NotSupportedNestedArraysEnums"));
}
this.impl.AddScalar(2);
this.impl.AddNonscalar();
this.AddField(new FieldMetadata(name, type, this.Tags, true));
}
public void BeginBufferedArray()
{
if (this.bufferedArrayFieldCount >= 0)
{
throw new NotSupportedException(Environment.GetResourceString("EventSource_NotSupportedNestedArraysEnums"));
}
this.bufferedArrayFieldCount = 0;
this.impl.BeginBuffered();
}
public void EndBufferedArray()
{
if (this.bufferedArrayFieldCount != 1)
{
throw new InvalidOperationException(Environment.GetResourceString("EventSource_IncorrentlyAuthoredTypeInfo"));
}
this.bufferedArrayFieldCount = int.MinValue;
this.impl.EndBuffered();
}
/// <summary>
/// Adds a custom-serialized field to an event.
/// </summary>
/// <param name="name">
/// The name to use for the added field. This value must not be null.
/// </param>
/// <param name="type">The encoding type for the field.</param>
/// <param name="metadata">Additional information needed to decode the field, if any.</param>
public void AddCustom(string name, TraceLoggingDataType type, byte[] metadata)
{
if (this.BeginningBufferedArray)
{
throw new NotSupportedException(Environment.GetResourceString("EventSource_NotSupportedCustomSerializedData"));
}
this.impl.AddScalar(2);
this.impl.AddNonscalar();
this.AddField(new FieldMetadata(
name,
type,
this.Tags,
metadata));
}
internal byte[] GetMetadata()
{
var size = this.impl.Encode(null);
var metadata = new byte[size];
this.impl.Encode(metadata);
return metadata;
}
private void AddField(FieldMetadata fieldMetadata)
{
this.Tags = EventFieldTags.None;
this.bufferedArrayFieldCount++;
this.impl.fields.Add(fieldMetadata);
if (this.currentGroup != null)
{
this.currentGroup.IncrementStructFieldCount();
}
}
private class Impl
{
internal readonly List<FieldMetadata> fields = new List<FieldMetadata>();
internal short scratchSize;
internal sbyte dataCount;
internal sbyte pinCount;
private int bufferNesting;
private bool scalar;
public void AddScalar(int size)
{
if (this.bufferNesting == 0)
{
if (!this.scalar)
{
this.dataCount = checked((sbyte)(this.dataCount + 1));
}
this.scalar = true;
this.scratchSize = checked((short)(this.scratchSize + size));
}
}
public void AddNonscalar()
{
if (this.bufferNesting == 0)
{
this.scalar = false;
this.pinCount = checked((sbyte)(this.pinCount + 1));
this.dataCount = checked((sbyte)(this.dataCount + 1));
}
}
public void BeginBuffered()
{
if (this.bufferNesting == 0)
{
this.AddNonscalar();
}
this.bufferNesting++;
}
public void EndBuffered()
{
this.bufferNesting--;
}
public int Encode(byte[] metadata)
{
int size = 0;
foreach (var field in this.fields)
{
field.Encode(ref size, metadata);
}
return size;
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using Test.Utilities;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.NetCore.Analyzers.ImmutableCollections.DoNotCallToImmutableCollectionOnAnImmutableCollectionValueAnalyzer,
Microsoft.NetCore.Analyzers.ImmutableCollections.DoNotCallToImmutableCollectionOnAnImmutableCollectionValueFixer>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Microsoft.NetCore.Analyzers.ImmutableCollections.DoNotCallToImmutableCollectionOnAnImmutableCollectionValueAnalyzer,
Microsoft.NetCore.Analyzers.ImmutableCollections.DoNotCallToImmutableCollectionOnAnImmutableCollectionValueFixer>;
namespace Microsoft.NetCore.Analyzers.ImmutableCollections.UnitTests
{
public class DoNotCallToImmutableCollectionOnAnImmutableCollectionValueTests
{
public static readonly TheoryData<string> CollectionNames_Arity1 = new()
{
nameof(ImmutableArray),
nameof(ImmutableHashSet),
nameof(ImmutableList),
nameof(ImmutableSortedSet)
};
public static readonly TheoryData<string> CollectionNames_Arity2 = new()
{
nameof(ImmutableDictionary),
nameof(ImmutableSortedDictionary)
};
#region No Diagnostic Tests
[Theory, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")]
[MemberData(nameof(CollectionNames_Arity1))]
public async Task NoDiagnosticCases_Arity1(string collectionName)
{
await VerifyCS.VerifyAnalyzerAsync($@"
using System.Collections.Generic;
using System.Collections.Immutable;
using static System.Collections.Immutable.{collectionName};
static class Extensions
{{
public static {collectionName}<TSource> To{collectionName}<TSource>(this IEnumerable<TSource> items)
{{
return default({collectionName}<TSource>);
}}
public static {collectionName}<TSource> To{collectionName}<TSource>(this IEnumerable<TSource> items, IEqualityComparer<TSource> comparer)
{{
return default({collectionName}<TSource>);
}}
}}
class C
{{
public void M(IEnumerable<int> p1, List<int> p2, {collectionName}<int> p3, IEqualityComparer<int> comparer)
{{
// Allowed
p1.To{collectionName}();
p2.To{collectionName}();
p3.To{collectionName}(comparer); // Potentially modifies the collection
Extensions.To{collectionName}(p1);
Extensions.To{collectionName}(p2);
Extensions.To{collectionName}(p3, comparer); // Potentially modifies the collection
// No dataflow
IEnumerable<int> l1 = p3;
l1.To{collectionName}();
Extensions.To{collectionName}(l1);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
Imports System.Collections.Generic
Imports System.Collections.Immutable
Module Extensions
<System.Runtime.CompilerServices.Extension> _
Public Function To{collectionName}(Of TSource)(items As IEnumerable(Of TSource)) As {collectionName}(Of TSource)
Return Nothing
End Function
<System.Runtime.CompilerServices.Extension> _
Public Function To{collectionName}(Of TSource)(items As IEnumerable(Of TSource), comparer as IEqualityComparer(Of TSource)) As {collectionName}(Of TSource)
Return Nothing
End Function
End Module
Class C
Public Sub M(p1 As IEnumerable(Of Integer), p2 As List(Of Integer), p3 As {collectionName}(Of Integer), comparer As IEqualityComparer(Of Integer))
' Allowed
p1.To{collectionName}()
p2.To{collectionName}()
p3.To{collectionName}(comparer) ' Potentially modifies the collection
Extensions.To{collectionName}(p1)
Extensions.To{collectionName}(p2)
Extensions.To{collectionName}(p3, comparer) ' Potentially modifies the collection
' No dataflow
Dim l1 As IEnumerable(Of Integer) = p3
l1.To{collectionName}()
Extensions.To{collectionName}(l1)
End Sub
End Class
");
}
[Theory, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")]
[MemberData(nameof(CollectionNames_Arity2))]
public async Task NoDiagnosticCases_Arity2(string collectionName)
{
await VerifyCS.VerifyAnalyzerAsync($@"
using System.Collections.Generic;
using System.Collections.Immutable;
using static System.Collections.Immutable.{collectionName};
static class Extensions
{{
public static {collectionName}<TKey, TValue> To{collectionName}<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> items)
{{
return default({collectionName}<TKey, TValue>);
}}
public static {collectionName}<TKey, TValue> To{collectionName}<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> items, IEqualityComparer<TKey> keyComparer)
{{
return default({collectionName}<TKey, TValue>);
}}
}}
class C
{{
public void M(IEnumerable<KeyValuePair<int, int>> p1, List<KeyValuePair<int, int>> p2, {collectionName}<int, int> p3, IEqualityComparer<int> keyComparer)
{{
// Allowed
p1.To{collectionName}();
p2.To{collectionName}();
p3.To{collectionName}(keyComparer); // Potentially modifies the collection
Extensions.To{collectionName}(p1);
Extensions.To{collectionName}(p2);
Extensions.To{collectionName}(p3, keyComparer); // Potentially modifies the collection
// No dataflow
IEnumerable<KeyValuePair<int, int>> l1 = p3;
l1.To{collectionName}();
Extensions.To{collectionName}(l1);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
Imports System.Collections.Generic
Imports System.Collections.Immutable
Module Extensions
<System.Runtime.CompilerServices.Extension> _
Public Function To{collectionName}(Of TKey, TValue)(items As IEnumerable(Of KeyValuePair(Of TKey, TValue))) As {collectionName}(Of TKey, TValue)
Return Nothing
End Function
<System.Runtime.CompilerServices.Extension> _
Public Function To{collectionName}(Of TKey, TValue)(items As IEnumerable(Of KeyValuePair(Of TKey, TValue)), keyComparer As IEqualityComparer(Of TKey)) As {collectionName}(Of TKey, TValue)
Return Nothing
End Function
End Module
Class C
Public Sub M(p1 As IEnumerable(Of KeyValuePair(Of Integer, Integer)), p2 As List(Of KeyValuePair(Of Integer, Integer)), p3 As {collectionName}(Of Integer, Integer), keyComparer As IEqualityComparer(Of Integer))
' Allowed
p1.To{collectionName}()
p2.To{collectionName}()
p3.To{collectionName}(keyComparer) ' Potentially modifies the collection
Extensions.To{collectionName}(p1)
Extensions.To{collectionName}(p2)
Extensions.To{collectionName}(p3, keyComparer) ' Potentially modifies the collection
' No dataflow
Dim l1 As IEnumerable(Of KeyValuePair(Of Integer, Integer)) = p3
l1.To{collectionName}()
Extensions.To{collectionName}(l1)
End Sub
End Class
");
}
#endregion
#region Diagnostic Tests
[Theory]
[MemberData(nameof(CollectionNames_Arity1))]
public async Task DiagnosticCases_Arity1(string collectionName)
{
await VerifyCS.VerifyAnalyzerAsync($@"
using System.Collections.Generic;
using System.Collections.Immutable;
static class Extensions
{{
public static {collectionName}<TSource> To{collectionName}<TSource>(this IEnumerable<TSource> items)
{{
return default({collectionName}<TSource>);
}}
}}
class C
{{
public void M(IEnumerable<int> p1, List<int> p2, {collectionName}<int> p3)
{{
p1.To{collectionName}().To{collectionName}();
p3.To{collectionName}();
Extensions.To{collectionName}(Extensions.To{collectionName}(p1));
Extensions.To{collectionName}(p3);
}}
}}
",
// Test0.cs(18,9): warning CA2009: Do not call ToImmutableCollection on an ImmutableCollection value
GetCSharpResultAt(17, 9, collectionName),
// Test0.cs(19,9): warning CA2009: Do not call ToImmutableCollection on an ImmutableCollection value
GetCSharpResultAt(18, 9, collectionName),
// Test0.cs(20,9): warning CA2009: Do not call ToImmutableCollection on an ImmutableCollection value
GetCSharpResultAt(20, 9, collectionName),
// Test0.cs(21,9): warning CA2009: Do not call ToImmutableCollection on an ImmutableCollection value
GetCSharpResultAt(21, 9, collectionName));
await VerifyVB.VerifyAnalyzerAsync($@"
Imports System.Collections.Generic
Imports System.Collections.Immutable
Module Extensions
<System.Runtime.CompilerServices.Extension> _
Public Function To{collectionName}(Of TSource)(items As IEnumerable(Of TSource)) As {collectionName}(Of TSource)
Return Nothing
End Function
End Module
Class C
Public Sub M(p1 As IEnumerable(Of Integer), p2 As List(Of Integer), p3 As {collectionName}(Of Integer))
p1.To{collectionName}().To{collectionName}()
p3.To{collectionName}()
Extensions.To{collectionName}(Extensions.To{collectionName}(p1))
Extensions.To{collectionName}(p3)
End Sub
End Class
",
// Test0.vb(14,3): warning CA2009: Do not call ToImmutableCollection on an ImmutableCollection value
GetBasicResultAt(14, 3, collectionName),
// Test0.vb(15,3): warning CA2009: Do not call ToImmutableCollection on an ImmutableCollection value
GetBasicResultAt(15, 3, collectionName),
// Test0.vb(17,3): warning CA2009: Do not call ToImmutableCollection on an ImmutableCollection value
GetBasicResultAt(17, 3, collectionName),
// Test0.vb(18,3): warning CA2009: Do not call ToImmutableCollection on an ImmutableCollection value
GetBasicResultAt(18, 3, collectionName));
}
[Theory]
[MemberData(nameof(CollectionNames_Arity2))]
public async Task DiagnosticCases_Arity2(string collectionName)
{
await VerifyCS.VerifyAnalyzerAsync($@"
using System.Collections.Generic;
using System.Collections.Immutable;
static class Extensions
{{
public static {collectionName}<TKey, TValue> To{collectionName}<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> items)
{{
return default({collectionName}<TKey, TValue>);
}}
}}
class C
{{
public void M(IEnumerable<KeyValuePair<int, int>> p1, List<KeyValuePair<int, int>> p2, {collectionName}<int, int> p3)
{{
p1.To{collectionName}().To{collectionName}();
p3.To{collectionName}();
Extensions.To{collectionName}(Extensions.To{collectionName}(p1));
Extensions.To{collectionName}(p3);
}}
}}
",
// Test0.cs(18,9): warning CA2009: Do not call ToImmutableCollection on an ImmutableCollection value
GetCSharpResultAt(17, 9, collectionName),
// Test0.cs(19,9): warning CA2009: Do not call ToImmutableCollection on an ImmutableCollection value
GetCSharpResultAt(18, 9, collectionName),
// Test0.cs(20,9): warning CA2009: Do not call ToImmutableCollection on an ImmutableCollection value
GetCSharpResultAt(20, 9, collectionName),
// Test0.cs(21,9): warning CA2009: Do not call ToImmutableCollection on an ImmutableCollection value
GetCSharpResultAt(21, 9, collectionName));
await VerifyVB.VerifyAnalyzerAsync($@"
Imports System.Collections.Generic
Imports System.Collections.Immutable
Module Extensions
<System.Runtime.CompilerServices.Extension> _
Public Function To{collectionName}(Of TKey, TValue)(items As IEnumerable(Of KeyValuePair(Of TKey, TValue))) As {collectionName}(Of TKey, TValue)
Return Nothing
End Function
End Module
Class C
Public Sub M(p1 As IEnumerable(Of KeyValuePair(Of Integer, Integer)), p2 As List(Of KeyValuePair(Of Integer, Integer)), p3 As {collectionName}(Of Integer, Integer))
p1.To{collectionName}().To{collectionName}()
p3.To{collectionName}()
Extensions.To{collectionName}(Extensions.To{collectionName}(p1))
Extensions.To{collectionName}(p3)
End Sub
End Class
",
// Test0.vb(14, 3): warning CA2009: Do not call ToImmutableCollection on an ImmutableCollection value
GetBasicResultAt(14, 3, collectionName),
// Test0.vb(15,3): warning CA2009: Do not call ToImmutableCollection on an ImmutableCollection value
GetBasicResultAt(15, 3, collectionName),
// Test0.vb(17,3): warning CA2009: Do not call ToImmutableCollection on an ImmutableCollection value
GetBasicResultAt(17, 3, collectionName),
// Test0.vb(18,3): warning CA2009: Do not call ToImmutableCollection on an ImmutableCollection value
GetBasicResultAt(18, 3, collectionName));
}
#endregion
private static DiagnosticResult GetCSharpResultAt(int line, int column, string collectionName)
{
#pragma warning disable RS0030 // Do not used banned APIs
return VerifyCS.Diagnostic(DoNotCallToImmutableCollectionOnAnImmutableCollectionValueAnalyzer.Rule).WithLocation(line, column).WithArguments($"To{collectionName}", collectionName);
#pragma warning restore RS0030 // Do not used banned APIs
}
private static DiagnosticResult GetBasicResultAt(int line, int column, string collectionName)
{
#pragma warning disable RS0030 // Do not used banned APIs
return VerifyVB.Diagnostic(DoNotCallToImmutableCollectionOnAnImmutableCollectionValueAnalyzer.Rule).WithLocation(line, column).WithArguments($"To{collectionName}", collectionName);
#pragma warning restore RS0030 // Do not used banned APIs
}
}
}
| |
namespace Xilium.CefGlue
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Xilium.CefGlue.Interop;
/// <summary>
/// Implement this interface to handle events related to browser requests. The
/// methods of this class will be called on the thread indicated.
/// </summary>
public abstract unsafe partial class CefRequestHandler
{
private int on_before_resource_load(cef_request_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, cef_request_t* request)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
var m_frame = CefFrame.FromNative(frame);
var m_request = CefRequest.FromNative(request);
var result = OnBeforeResourceLoad(m_browser, m_frame, m_request);
m_request.Dispose();
return result ? 1 : 0;
}
/// <summary>
/// Called on the IO thread before a resource request is loaded. The |request|
/// object may be modified. To cancel the request return true otherwise return
/// false.
/// </summary>
protected virtual bool OnBeforeResourceLoad(CefBrowser browser, CefFrame frame, CefRequest request)
{
return false;
}
private cef_resource_handler_t* get_resource_handler(cef_request_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, cef_request_t* request)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
var m_frame = CefFrame.FromNative(frame);
var m_request = CefRequest.FromNative(request);
var handler = GetResourceHandler(m_browser, m_frame, m_request);
m_request.Dispose();
return handler != null ? handler.ToNative() : null;
}
/// <summary>
/// Called on the IO thread before a resource is loaded. To allow the resource
/// to load normally return NULL. To specify a handler for the resource return
/// a CefResourceHandler object. The |request| object should not be modified in
/// this callback.
/// </summary>
protected virtual CefResourceHandler GetResourceHandler(CefBrowser browser, CefFrame frame, CefRequest request)
{
return null;
}
private void on_resource_redirect(cef_request_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, cef_string_t* old_url, cef_string_t* new_url)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
var m_frame = CefFrame.FromNative(frame);
var m_oldUrl = cef_string_t.ToString(old_url);
var m_newUrl = cef_string_t.ToString(new_url);
var o_newUrl = m_newUrl;
OnResourceRedirect(m_browser, m_frame, m_oldUrl, ref m_newUrl);
if ((object)m_newUrl != (object)o_newUrl)
{
cef_string_t.Copy(m_newUrl, new_url);
}
}
/// <summary>
/// Called on the IO thread when a resource load is redirected. The |old_url|
/// parameter will contain the old URL. The |new_url| parameter will contain
/// the new URL and can be changed if desired.
/// </summary>
protected virtual void OnResourceRedirect(CefBrowser browser, CefFrame frame, string oldUrl, ref string newUrl)
{
}
private int get_auth_credentials(cef_request_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, int isProxy, cef_string_t* host, int port, cef_string_t* realm, cef_string_t* scheme, cef_auth_callback_t* callback)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
var m_frame = CefFrame.FromNative(frame);
var m_host = cef_string_t.ToString(host);
var m_realm = cef_string_t.ToString(realm);
var m_scheme = cef_string_t.ToString(scheme);
var m_callback = CefAuthCallback.FromNative(callback);
var result = GetAuthCredentials(m_browser, m_frame, isProxy != 0, m_host, port, m_realm, m_scheme, m_callback);
return result ? 1 : 0;
}
/// <summary>
/// Called on the IO thread when the browser needs credentials from the user.
/// |isProxy| indicates whether the host is a proxy server. |host| contains the
/// hostname and |port| contains the port number. Return true to continue the
/// request and call CefAuthCallback::Continue() when the authentication
/// information is available. Return false to cancel the request.
/// </summary>
protected virtual bool GetAuthCredentials(CefBrowser browser, CefFrame frame, bool isProxy, string host, int port, string realm, string scheme, CefAuthCallback callback)
{
return false;
}
private int on_quota_request(cef_request_handler_t* self, cef_browser_t* browser, cef_string_t* origin_url, long new_size, cef_quota_callback_t* callback)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
var m_origin_url = cef_string_t.ToString(origin_url);
var m_callback = CefQuotaCallback.FromNative(callback);
var result = OnQuotaRequest(m_browser, m_origin_url, new_size, m_callback);
return result ? 1 : 0;
}
/// <summary>
/// Called on the IO thread when JavaScript requests a specific storage quota
/// size via the webkitStorageInfo.requestQuota function. |origin_url| is the
/// origin of the page making the request. |new_size| is the requested quota
/// size in bytes. Return true and call CefQuotaCallback::Continue() either in
/// this method or at a later time to grant or deny the request. Return false
/// to cancel the request.
/// </summary>
protected abstract bool OnQuotaRequest(CefBrowser browser, string originUrl, long newSize, CefQuotaCallback callback);
private cef_cookie_manager_t* get_cookie_manager(cef_request_handler_t* self, cef_browser_t* browser, cef_string_t* main_url)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
var m_mainUrl = cef_string_t.ToString(main_url);
var manager = GetCookieManager(m_browser, m_mainUrl);
return manager != null ? manager.ToNative() : null;
}
/// <summary>
/// Called on the IO thread to retrieve the cookie manager. |main_url| is the
/// URL of the top-level frame. Cookies managers can be unique per browser or
/// shared across multiple browsers. The global cookie manager will be used if
/// this method returns NULL.
/// </summary>
protected virtual CefCookieManager GetCookieManager(CefBrowser browser, string mainUrl)
{
return null;
}
private void on_protocol_execution(cef_request_handler_t* self, cef_browser_t* browser, cef_string_t* url, int* allow_os_execution)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
var m_url = cef_string_t.ToString(url);
bool m_allow_os_execution;
OnProtocolExecution(m_browser, m_url, out m_allow_os_execution);
*allow_os_execution = m_allow_os_execution ? 1 : 0;
}
/// <summary>
/// Called on the UI thread to handle requests for URLs with an unknown
/// protocol component. Set |allow_os_execution| to true to attempt execution
/// via the registered OS protocol handler, if any.
/// SECURITY WARNING: YOU SHOULD USE THIS METHOD TO ENFORCE RESTRICTIONS BASED
/// ON SCHEME, HOST OR OTHER URL ANALYSIS BEFORE ALLOWING OS EXECUTION.
/// </summary>
protected virtual void OnProtocolExecution(CefBrowser browser, string url, out bool allowOSExecution)
{
allowOSExecution = true;
}
private int on_before_plugin_load(cef_request_handler_t* self, cef_browser_t* browser, cef_string_t* url, cef_string_t* policy_url, cef_web_plugin_info_t* info)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
var m_url = cef_string_t.ToString(url);
var m_policy_url = cef_string_t.ToString(policy_url);
var m_info = CefWebPluginInfo.FromNative(info);
var result = OnBeforePluginLoad(m_browser, m_url, m_policy_url, m_info);
return result ? 1 : 0;
}
/// <summary>
/// Called on the browser process IO thread before a plugin is loaded. Return
/// true to block loading of the plugin.
/// </summary>
protected virtual bool OnBeforePluginLoad(CefBrowser browser, string url, string policyUrl, CefWebPluginInfo info)
{
return false;
}
private int on_certificate_error(cef_request_handler_t* self, CefErrorCode cert_error, cef_string_t* request_url, cef_allow_certificate_error_callback_t* callback)
{
CheckSelf(self);
var m_requestUrl = cef_string_t.ToString(request_url);
var m_callback = CefAllowCertificateErrorCallback.FromNative(callback);
var m_result = OnCertificateError(cert_error, m_requestUrl, m_callback);
return m_result ? 1 : 0;
}
/// <summary>
/// Called on the UI thread to handle requests for URLs with an invalid
/// SSL certificate. Return true and call CefAllowCertificateErrorCallback::
/// Continue() either in this method or at a later time to continue or cancel
/// the request. Return false to cancel the request immediately. If |callback|
/// is empty the error cannot be recovered from and the request will be
/// canceled automatically. If CefSettings.ignore_certificate_errors is set
/// all invalid certificates will be accepted without calling this method.
/// </summary>
protected virtual bool OnCertificateError(CefErrorCode certError, string requestUrl, CefAllowCertificateErrorCallback callback)
{
return false;
}
}
}
| |
namespace Petstore
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
/// <summary>
/// The Storage Management Client.
/// </summary>
public partial class StorageManagementClient : ServiceClient<StorageManagementClient>, IStorageManagementClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft Azure
/// subscription. The subscription ID forms part of the URI for every service
/// call.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// Client Api Version.
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IStorageAccountsOperations.
/// </summary>
public virtual IStorageAccountsOperations StorageAccounts { get; private set; }
/// <summary>
/// Gets the IUsageOperations.
/// </summary>
public virtual IUsageOperations Usage { get; private set; }
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected StorageManagementClient(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected StorageManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected StorageManagementClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected StorageManagementClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public StorageManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public StorageManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public StorageManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public StorageManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
StorageAccounts = new StorageAccountsOperations(this);
Usage = new UsageOperations(this);
BaseUri = new System.Uri("https://management.azure.com");
ApiVersion = "2015-06-15";
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
namespace Scintilla.Forms.Configuration
{
partial class StyleConfigControl
{
/// <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 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()
{
this.comboBoxSample = new System.Windows.Forms.ComboBox();
this.groupBoxSample = new System.Windows.Forms.GroupBox();
this.labelSample = new System.Windows.Forms.Label();
this.radioButtonGlobal = new System.Windows.Forms.RadioButton();
this.radioButtonLexer = new System.Windows.Forms.RadioButton();
this.radioButtonLanguage = new System.Windows.Forms.RadioButton();
this.groupBoxConfig = new System.Windows.Forms.GroupBox();
this.comboBoxLanguage = new System.Windows.Forms.ComboBox();
this.comboBoxLexer = new System.Windows.Forms.ComboBox();
this.checkedListBoxAvailableStyles = new System.Windows.Forms.CheckedListBox();
this.checkBoxEolFilled = new System.Windows.Forms.CheckBox();
this.checkBoxItalics = new System.Windows.Forms.CheckBox();
this.checkBoxBold = new System.Windows.Forms.CheckBox();
this.groupBoxStyleSettings = new System.Windows.Forms.GroupBox();
this.textBoxBackColor = new System.Windows.Forms.TextBox();
this.textBoxForeColor = new System.Windows.Forms.TextBox();
this.checkBoxUnderline = new System.Windows.Forms.CheckBox();
this.labelBackground = new System.Windows.Forms.Label();
this.labelForeground = new System.Windows.Forms.Label();
this.comboBoxFontSize = new System.Windows.Forms.ComboBox();
this.labelFont = new System.Windows.Forms.Label();
this.panelSelectedColor = new System.Windows.Forms.Panel();
this.panelColor = new System.Windows.Forms.Panel();
this.numericUpDownGreen = new System.Windows.Forms.NumericUpDown();
this.textBoxHexColor = new System.Windows.Forms.TextBox();
this.labelColor = new System.Windows.Forms.Label();
this.numericUpDownRed = new System.Windows.Forms.NumericUpDown();
this.numericUpDownBlue = new System.Windows.Forms.NumericUpDown();
this.panelBrightness = new System.Windows.Forms.Panel();
this.labelRGBSelector = new System.Windows.Forms.Label();
this.fontBrowserFont = new Scintilla.Forms.Configuration.FontBrowser();
this.scintillaControlSample = new Scintilla.ScintillaControl();
this.groupBoxSample.SuspendLayout();
this.groupBoxConfig.SuspendLayout();
this.groupBoxStyleSettings.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownGreen)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownRed)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownBlue)).BeginInit();
this.SuspendLayout();
//
// comboBoxSample
//
this.comboBoxSample.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.comboBoxSample.FormattingEnabled = true;
this.comboBoxSample.Location = new System.Drawing.Point(54, 19);
this.comboBoxSample.Name = "comboBoxSample";
this.comboBoxSample.Size = new System.Drawing.Size(548, 21);
this.comboBoxSample.TabIndex = 1;
this.comboBoxSample.SelectedIndexChanged += new System.EventHandler(this.comboBoxSample_SelectedIndexChanged);
//
// groupBoxSample
//
this.groupBoxSample.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBoxSample.Controls.Add(this.labelSample);
this.groupBoxSample.Controls.Add(this.comboBoxSample);
this.groupBoxSample.Controls.Add(this.scintillaControlSample);
this.groupBoxSample.Location = new System.Drawing.Point(6, 252);
this.groupBoxSample.Name = "groupBoxSample";
this.groupBoxSample.Size = new System.Drawing.Size(611, 218);
this.groupBoxSample.TabIndex = 3;
this.groupBoxSample.TabStop = false;
this.groupBoxSample.Text = "Sample";
//
// labelSample
//
this.labelSample.AutoSize = true;
this.labelSample.Location = new System.Drawing.Point(6, 22);
this.labelSample.Name = "labelSample";
this.labelSample.Size = new System.Drawing.Size(42, 13);
this.labelSample.TabIndex = 4;
this.labelSample.Text = "Sample";
//
// radioButtonGlobal
//
this.radioButtonGlobal.AutoSize = true;
this.radioButtonGlobal.Location = new System.Drawing.Point(6, 19);
this.radioButtonGlobal.Name = "radioButtonGlobal";
this.radioButtonGlobal.Size = new System.Drawing.Size(55, 17);
this.radioButtonGlobal.TabIndex = 4;
this.radioButtonGlobal.TabStop = true;
this.radioButtonGlobal.Text = "Global";
this.radioButtonGlobal.UseVisualStyleBackColor = true;
this.radioButtonGlobal.CheckedChanged += new System.EventHandler(this.radioButtonStyleLevel_CheckedChanged);
//
// radioButtonLexer
//
this.radioButtonLexer.AutoSize = true;
this.radioButtonLexer.Location = new System.Drawing.Point(6, 42);
this.radioButtonLexer.Name = "radioButtonLexer";
this.radioButtonLexer.Size = new System.Drawing.Size(51, 17);
this.radioButtonLexer.TabIndex = 5;
this.radioButtonLexer.TabStop = true;
this.radioButtonLexer.Text = "Lexer";
this.radioButtonLexer.UseVisualStyleBackColor = true;
this.radioButtonLexer.CheckedChanged += new System.EventHandler(this.radioButtonStyleLevel_CheckedChanged);
//
// radioButtonLanguage
//
this.radioButtonLanguage.AutoSize = true;
this.radioButtonLanguage.Location = new System.Drawing.Point(6, 65);
this.radioButtonLanguage.Name = "radioButtonLanguage";
this.radioButtonLanguage.Size = new System.Drawing.Size(73, 17);
this.radioButtonLanguage.TabIndex = 6;
this.radioButtonLanguage.TabStop = true;
this.radioButtonLanguage.Text = "Language";
this.radioButtonLanguage.UseVisualStyleBackColor = true;
this.radioButtonLanguage.CheckedChanged += new System.EventHandler(this.radioButtonStyleLevel_CheckedChanged);
//
// groupBoxConfig
//
this.groupBoxConfig.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.groupBoxConfig.Controls.Add(this.comboBoxLanguage);
this.groupBoxConfig.Controls.Add(this.comboBoxLexer);
this.groupBoxConfig.Controls.Add(this.radioButtonGlobal);
this.groupBoxConfig.Controls.Add(this.radioButtonLanguage);
this.groupBoxConfig.Controls.Add(this.radioButtonLexer);
this.groupBoxConfig.Location = new System.Drawing.Point(178, 19);
this.groupBoxConfig.Name = "groupBoxConfig";
this.groupBoxConfig.Size = new System.Drawing.Size(217, 92);
this.groupBoxConfig.TabIndex = 7;
this.groupBoxConfig.TabStop = false;
this.groupBoxConfig.Text = "Configuration Type";
//
// comboBoxLanguage
//
this.comboBoxLanguage.FormattingEnabled = true;
this.comboBoxLanguage.Location = new System.Drawing.Point(77, 61);
this.comboBoxLanguage.Name = "comboBoxLanguage";
this.comboBoxLanguage.Size = new System.Drawing.Size(134, 21);
this.comboBoxLanguage.TabIndex = 9;
this.comboBoxLanguage.SelectedIndexChanged += new System.EventHandler(this.comboBoxLanguage_SelectedIndexChanged);
//
// comboBoxLexer
//
this.comboBoxLexer.FormattingEnabled = true;
this.comboBoxLexer.Location = new System.Drawing.Point(77, 38);
this.comboBoxLexer.Name = "comboBoxLexer";
this.comboBoxLexer.Size = new System.Drawing.Size(134, 21);
this.comboBoxLexer.TabIndex = 8;
this.comboBoxLexer.SelectedIndexChanged += new System.EventHandler(this.comboBoxLexer_SelectedIndexChanged);
//
// checkedListBoxAvailableStyles
//
this.checkedListBoxAvailableStyles.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.checkedListBoxAvailableStyles.FormattingEnabled = true;
this.checkedListBoxAvailableStyles.Location = new System.Drawing.Point(6, 19);
this.checkedListBoxAvailableStyles.Name = "checkedListBoxAvailableStyles";
this.checkedListBoxAvailableStyles.Size = new System.Drawing.Size(166, 214);
this.checkedListBoxAvailableStyles.TabIndex = 10;
this.checkedListBoxAvailableStyles.SelectedIndexChanged += new System.EventHandler(this.checkedListBoxAvailableStyles_SelectedIndexChanged);
//
// checkBoxEolFilled
//
this.checkBoxEolFilled.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.checkBoxEolFilled.Font = new System.Drawing.Font("Verdana", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.checkBoxEolFilled.Location = new System.Drawing.Point(269, 177);
this.checkBoxEolFilled.Name = "checkBoxEolFilled";
this.checkBoxEolFilled.Size = new System.Drawing.Size(120, 20);
this.checkBoxEolFilled.TabIndex = 76;
this.checkBoxEolFilled.Text = "EOL Filled";
this.checkBoxEolFilled.ThreeState = true;
//
// checkBoxItalics
//
this.checkBoxItalics.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.checkBoxItalics.Font = new System.Drawing.Font("Verdana", 8.25F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.checkBoxItalics.Location = new System.Drawing.Point(269, 197);
this.checkBoxItalics.Name = "checkBoxItalics";
this.checkBoxItalics.Size = new System.Drawing.Size(120, 20);
this.checkBoxItalics.TabIndex = 75;
this.checkBoxItalics.Text = "Italics";
this.checkBoxItalics.ThreeState = true;
//
// checkBoxBold
//
this.checkBoxBold.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.checkBoxBold.Font = new System.Drawing.Font("Verdana", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.checkBoxBold.Location = new System.Drawing.Point(269, 157);
this.checkBoxBold.Name = "checkBoxBold";
this.checkBoxBold.Size = new System.Drawing.Size(120, 20);
this.checkBoxBold.TabIndex = 74;
this.checkBoxBold.Text = "Bold";
this.checkBoxBold.ThreeState = true;
//
// groupBoxStyleSettings
//
this.groupBoxStyleSettings.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBoxStyleSettings.Controls.Add(this.textBoxBackColor);
this.groupBoxStyleSettings.Controls.Add(this.textBoxForeColor);
this.groupBoxStyleSettings.Controls.Add(this.checkBoxBold);
this.groupBoxStyleSettings.Controls.Add(this.checkBoxEolFilled);
this.groupBoxStyleSettings.Controls.Add(this.checkBoxUnderline);
this.groupBoxStyleSettings.Controls.Add(this.fontBrowserFont);
this.groupBoxStyleSettings.Controls.Add(this.checkBoxItalics);
this.groupBoxStyleSettings.Controls.Add(this.labelBackground);
this.groupBoxStyleSettings.Controls.Add(this.groupBoxConfig);
this.groupBoxStyleSettings.Controls.Add(this.labelForeground);
this.groupBoxStyleSettings.Controls.Add(this.comboBoxFontSize);
this.groupBoxStyleSettings.Controls.Add(this.labelFont);
this.groupBoxStyleSettings.Controls.Add(this.checkedListBoxAvailableStyles);
this.groupBoxStyleSettings.Location = new System.Drawing.Point(216, 3);
this.groupBoxStyleSettings.Name = "groupBoxStyleSettings";
this.groupBoxStyleSettings.Size = new System.Drawing.Size(401, 243);
this.groupBoxStyleSettings.TabIndex = 77;
this.groupBoxStyleSettings.TabStop = false;
this.groupBoxStyleSettings.Text = "Style Settings";
//
// textBoxBackColor
//
this.textBoxBackColor.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.textBoxBackColor.Cursor = System.Windows.Forms.Cursors.Default;
this.textBoxBackColor.Location = new System.Drawing.Point(180, 209);
this.textBoxBackColor.Name = "textBoxBackColor";
this.textBoxBackColor.ReadOnly = true;
this.textBoxBackColor.Size = new System.Drawing.Size(73, 20);
this.textBoxBackColor.TabIndex = 98;
this.textBoxBackColor.Enter += new System.EventHandler(this.TextBoxColor_Enter);
//
// textBoxForeColor
//
this.textBoxForeColor.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.textBoxForeColor.Cursor = System.Windows.Forms.Cursors.IBeam;
this.textBoxForeColor.Location = new System.Drawing.Point(180, 170);
this.textBoxForeColor.Name = "textBoxForeColor";
this.textBoxForeColor.ReadOnly = true;
this.textBoxForeColor.Size = new System.Drawing.Size(73, 20);
this.textBoxForeColor.TabIndex = 97;
this.textBoxForeColor.Enter += new System.EventHandler(this.TextBoxColor_Enter);
//
// checkBoxUnderline
//
this.checkBoxUnderline.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.checkBoxUnderline.Font = new System.Drawing.Font("Verdana", 8.25F, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.checkBoxUnderline.Location = new System.Drawing.Point(269, 217);
this.checkBoxUnderline.Name = "checkBoxUnderline";
this.checkBoxUnderline.Size = new System.Drawing.Size(120, 20);
this.checkBoxUnderline.TabIndex = 96;
this.checkBoxUnderline.Text = "Underline";
this.checkBoxUnderline.ThreeState = true;
//
// labelBackground
//
this.labelBackground.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.labelBackground.AutoSize = true;
this.labelBackground.Location = new System.Drawing.Point(178, 193);
this.labelBackground.Name = "labelBackground";
this.labelBackground.Size = new System.Drawing.Size(65, 13);
this.labelBackground.TabIndex = 94;
this.labelBackground.Text = "Background";
//
// labelForeground
//
this.labelForeground.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.labelForeground.AutoSize = true;
this.labelForeground.Location = new System.Drawing.Point(178, 154);
this.labelForeground.Name = "labelForeground";
this.labelForeground.Size = new System.Drawing.Size(61, 13);
this.labelForeground.TabIndex = 93;
this.labelForeground.Text = "Foreground";
//
// comboBoxFontSize
//
this.comboBoxFontSize.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.comboBoxFontSize.FormattingEnabled = true;
this.comboBoxFontSize.Location = new System.Drawing.Point(339, 130);
this.comboBoxFontSize.Name = "comboBoxFontSize";
this.comboBoxFontSize.Size = new System.Drawing.Size(56, 21);
this.comboBoxFontSize.TabIndex = 79;
//
// labelFont
//
this.labelFont.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.labelFont.AutoSize = true;
this.labelFont.Location = new System.Drawing.Point(178, 114);
this.labelFont.Name = "labelFont";
this.labelFont.Size = new System.Drawing.Size(28, 13);
this.labelFont.TabIndex = 78;
this.labelFont.Text = "Font";
//
// panelSelectedColor
//
this.panelSelectedColor.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.panelSelectedColor.Location = new System.Drawing.Point(38, 185);
this.panelSelectedColor.Name = "panelSelectedColor";
this.panelSelectedColor.Size = new System.Drawing.Size(67, 20);
this.panelSelectedColor.TabIndex = 97;
this.panelSelectedColor.Visible = false;
//
// panelColor
//
this.panelColor.Location = new System.Drawing.Point(6, 12);
this.panelColor.Name = "panelColor";
this.panelColor.Size = new System.Drawing.Size(170, 170);
this.panelColor.TabIndex = 95;
this.panelColor.Visible = false;
//
// numericUpDownGreen
//
this.numericUpDownGreen.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.numericUpDownGreen.Location = new System.Drawing.Point(86, 208);
this.numericUpDownGreen.Maximum = new decimal(new int[] {
255,
0,
0,
0});
this.numericUpDownGreen.Name = "numericUpDownGreen";
this.numericUpDownGreen.Size = new System.Drawing.Size(42, 22);
this.numericUpDownGreen.TabIndex = 91;
this.numericUpDownGreen.ValueChanged += new System.EventHandler(this.HandleRGBChange);
//
// textBoxHexColor
//
this.textBoxHexColor.CharacterCasing = System.Windows.Forms.CharacterCasing.Lower;
this.textBoxHexColor.Location = new System.Drawing.Point(111, 185);
this.textBoxHexColor.MaxLength = 8;
this.textBoxHexColor.Name = "textBoxHexColor";
this.textBoxHexColor.Size = new System.Drawing.Size(65, 20);
this.textBoxHexColor.TabIndex = 98;
this.textBoxHexColor.Text = "0x000000";
this.textBoxHexColor.Leave += new System.EventHandler(this.textBoxHexColor_Leave);
//
// labelColor
//
this.labelColor.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F);
this.labelColor.Location = new System.Drawing.Point(3, 185);
this.labelColor.Name = "labelColor";
this.labelColor.Size = new System.Drawing.Size(48, 20);
this.labelColor.TabIndex = 94;
this.labelColor.Text = "Color:";
this.labelColor.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// numericUpDownRed
//
this.numericUpDownRed.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.numericUpDownRed.Location = new System.Drawing.Point(38, 208);
this.numericUpDownRed.Maximum = new decimal(new int[] {
255,
0,
0,
0});
this.numericUpDownRed.Name = "numericUpDownRed";
this.numericUpDownRed.Size = new System.Drawing.Size(42, 22);
this.numericUpDownRed.TabIndex = 90;
this.numericUpDownRed.ValueChanged += new System.EventHandler(this.HandleRGBChange);
//
// numericUpDownBlue
//
this.numericUpDownBlue.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.numericUpDownBlue.Location = new System.Drawing.Point(134, 208);
this.numericUpDownBlue.Maximum = new decimal(new int[] {
255,
0,
0,
0});
this.numericUpDownBlue.Name = "numericUpDownBlue";
this.numericUpDownBlue.Size = new System.Drawing.Size(42, 22);
this.numericUpDownBlue.TabIndex = 92;
this.numericUpDownBlue.ValueChanged += new System.EventHandler(this.HandleRGBChange);
//
// panelBrightness
//
this.panelBrightness.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.panelBrightness.Location = new System.Drawing.Point(182, 12);
this.panelBrightness.Name = "panelBrightness";
this.panelBrightness.Size = new System.Drawing.Size(16, 170);
this.panelBrightness.TabIndex = 96;
this.panelBrightness.Visible = false;
//
// labelRGBSelector
//
this.labelRGBSelector.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F);
this.labelRGBSelector.Location = new System.Drawing.Point(3, 208);
this.labelRGBSelector.Name = "labelRGBSelector";
this.labelRGBSelector.Size = new System.Drawing.Size(48, 23);
this.labelRGBSelector.TabIndex = 93;
this.labelRGBSelector.Text = "RGB:";
this.labelRGBSelector.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// fontBrowserFont
//
this.fontBrowserFont.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.fontBrowserFont.Location = new System.Drawing.Point(180, 130);
this.fontBrowserFont.Name = "fontBrowserFont";
this.fontBrowserFont.SampleText = "Scintilla.Net";
this.fontBrowserFont.SelectedFont = "";
this.fontBrowserFont.ShowName = false;
this.fontBrowserFont.ShowSample = true;
this.fontBrowserFont.Size = new System.Drawing.Size(153, 21);
this.fontBrowserFont.Style = Scintilla.Forms.Configuration.FontBrowser.Styles.DropdownListBox;
this.fontBrowserFont.TabIndex = 95;
//
// scintillaControlSample
//
this.scintillaControlSample.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.scintillaControlSample.ConfigurationLanguage = null;
this.scintillaControlSample.IsBraceMatching = false;
this.scintillaControlSample.Location = new System.Drawing.Point(6, 46);
this.scintillaControlSample.Name = "scintillaControlSample";
this.scintillaControlSample.Size = new System.Drawing.Size(596, 166);
this.scintillaControlSample.SmartIndentType = Scintilla.Enums.SmartIndent.None;
this.scintillaControlSample.TabIndex = 0;
//
// StyleConfigControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.panelSelectedColor);
this.Controls.Add(this.panelColor);
this.Controls.Add(this.numericUpDownGreen);
this.Controls.Add(this.textBoxHexColor);
this.Controls.Add(this.labelColor);
this.Controls.Add(this.numericUpDownRed);
this.Controls.Add(this.numericUpDownBlue);
this.Controls.Add(this.panelBrightness);
this.Controls.Add(this.labelRGBSelector);
this.Controls.Add(this.groupBoxStyleSettings);
this.Controls.Add(this.groupBoxSample);
this.MinimumSize = new System.Drawing.Size(620, 473);
this.Name = "StyleConfigControl";
this.Size = new System.Drawing.Size(620, 473);
this.Load += new System.EventHandler(this.StyleConfigControl_Load);
this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.HandleMouse);
this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.HandleMouse);
this.Paint += new System.Windows.Forms.PaintEventHandler(this.StyleConfigControl_Paint);
this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.HandleMouseUp);
this.groupBoxSample.ResumeLayout(false);
this.groupBoxSample.PerformLayout();
this.groupBoxConfig.ResumeLayout(false);
this.groupBoxConfig.PerformLayout();
this.groupBoxStyleSettings.ResumeLayout(false);
this.groupBoxStyleSettings.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownGreen)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownRed)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownBlue)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private ScintillaControl scintillaControlSample;
private System.Windows.Forms.ComboBox comboBoxSample;
private System.Windows.Forms.GroupBox groupBoxSample;
private System.Windows.Forms.Label labelSample;
private System.Windows.Forms.RadioButton radioButtonGlobal;
private System.Windows.Forms.RadioButton radioButtonLexer;
private System.Windows.Forms.RadioButton radioButtonLanguage;
private System.Windows.Forms.GroupBox groupBoxConfig;
private System.Windows.Forms.ComboBox comboBoxLanguage;
private System.Windows.Forms.ComboBox comboBoxLexer;
private System.Windows.Forms.CheckedListBox checkedListBoxAvailableStyles;
private System.Windows.Forms.CheckBox checkBoxEolFilled;
private System.Windows.Forms.CheckBox checkBoxItalics;
private System.Windows.Forms.CheckBox checkBoxBold;
private System.Windows.Forms.GroupBox groupBoxStyleSettings;
private System.Windows.Forms.Label labelFont;
private System.Windows.Forms.Label labelBackground;
private System.Windows.Forms.Label labelForeground;
private System.Windows.Forms.ComboBox comboBoxFontSize;
private FontBrowser fontBrowserFont;
internal System.Windows.Forms.Panel panelSelectedColor;
internal System.Windows.Forms.Panel panelColor;
internal System.Windows.Forms.NumericUpDown numericUpDownGreen;
private System.Windows.Forms.TextBox textBoxHexColor;
internal System.Windows.Forms.Label labelColor;
internal System.Windows.Forms.NumericUpDown numericUpDownRed;
internal System.Windows.Forms.NumericUpDown numericUpDownBlue;
internal System.Windows.Forms.Panel panelBrightness;
internal System.Windows.Forms.Label labelRGBSelector;
private System.Windows.Forms.CheckBox checkBoxUnderline;
private System.Windows.Forms.TextBox textBoxForeColor;
private System.Windows.Forms.TextBox textBoxBackColor;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
** Purpose: Create a stream over unmanaged memory, mostly
** useful for memory-mapped files.
**
**
===========================================================*/
using System;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Threading.Tasks;
namespace System.IO
{
/*
* This class is used to access a contiguous block of memory, likely outside
* the GC heap (or pinned in place in the GC heap, but a MemoryStream may
* make more sense in those cases). It's great if you have a pointer and
* a length for a section of memory mapped in by someone else and you don't
* want to copy this into the GC heap. UnmanagedMemoryStream assumes these
* two things:
*
* 1) All the memory in the specified block is readable or writable,
* depending on the values you pass to the constructor.
* 2) The lifetime of the block of memory is at least as long as the lifetime
* of the UnmanagedMemoryStream.
* 3) You clean up the memory when appropriate. The UnmanagedMemoryStream
* currently will do NOTHING to free this memory.
* 4) All calls to Write and WriteByte may not be threadsafe currently.
*
* It may become necessary to add in some sort of
* DeallocationMode enum, specifying whether we unmap a section of memory,
* call free, run a user-provided delegate to free the memory, etc.
* We'll suggest user write a subclass of UnmanagedMemoryStream that uses
* a SafeHandle subclass to hold onto the memory.
* Check for problems when using this in the negative parts of a
* process's address space. We may need to use unsigned longs internally
* and change the overflow detection logic.
*
* -----SECURITY MODEL AND SILVERLIGHT-----
* A few key notes about exposing UMS in silverlight:
* 1. No ctors are exposed to transparent code. This version of UMS only
* supports byte* (not SafeBuffer). Therefore, framework code can create
* a UMS and hand it to transparent code. Transparent code can use most
* operations on a UMS, but not operations that directly expose a
* pointer.
*
* 2. Scope of "unsafe" and non-CLS compliant operations reduced: The
* Whidbey version of this class has CLSCompliant(false) at the class
* level and unsafe modifiers at the method level. These were reduced to
* only where the unsafe operation is performed -- i.e. immediately
* around the pointer manipulation. Note that this brings UMS in line
* with recent changes in pu/clr to support SafeBuffer.
*
* 3. Currently, the only caller that creates a UMS is ResourceManager,
* which creates read-only UMSs, and therefore operations that can
* change the length will throw because write isn't supported. A
* conservative option would be to formalize the concept that _only_
* read-only UMSs can be creates, and enforce this by making WriteX and
* SetLength SecurityCritical. However, this is a violation of
* security inheritance rules, so we must keep these safe. The
* following notes make this acceptable for future use.
* a. a race condition in WriteX that could have allowed a thread to
* read from unzeroed memory was fixed
* b. memory region cannot be expanded beyond _capacity; in other
* words, a UMS creator is saying a writable UMS is safe to
* write to anywhere in the memory range up to _capacity, specified
* in the ctor. Even if the caller doesn't specify a capacity, then
* length is used as the capacity.
*/
public class UnmanagedMemoryStream : Stream
{
private const long UnmanagedMemStreamMaxLength = Int64.MaxValue;
private SafeBuffer _buffer;
private unsafe byte* _mem;
private long _length;
private long _capacity;
private long _position;
private long _offset;
private FileAccess _access;
internal bool _isOpen;
[NonSerialized]
private Task<Int32> _lastReadTask; // The last successful task returned from ReadAsync
// Needed for subclasses that need to map a file, etc.
protected UnmanagedMemoryStream()
{
unsafe
{
_mem = null;
}
_isOpen = false;
}
public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length)
{
Initialize(buffer, offset, length, FileAccess.Read);
}
public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length, FileAccess access)
{
Initialize(buffer, offset, length, access);
}
protected void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (buffer.ByteLength < (ulong)(offset + length))
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSafeBufferOffLen"));
}
if (access < FileAccess.Read || access > FileAccess.ReadWrite)
{
throw new ArgumentOutOfRangeException(nameof(access));
}
Contract.EndContractBlock();
if (_isOpen)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CalledTwice"));
}
// check for wraparound
unsafe
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
buffer.AcquirePointer(ref pointer);
if ((pointer + offset + length) < pointer)
{
throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamWrapAround"));
}
}
finally
{
if (pointer != null)
{
buffer.ReleasePointer();
}
}
}
_offset = offset;
_buffer = buffer;
_length = length;
_capacity = length;
_access = access;
_isOpen = true;
}
[CLSCompliant(false)]
public unsafe UnmanagedMemoryStream(byte* pointer, long length)
{
Initialize(pointer, length, length, FileAccess.Read);
}
[CLSCompliant(false)]
public unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access)
{
Initialize(pointer, length, capacity, access);
}
[CLSCompliant(false)]
protected unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access)
{
if (pointer == null)
throw new ArgumentNullException(nameof(pointer));
if (length < 0 || capacity < 0)
throw new ArgumentOutOfRangeException((length < 0) ? nameof(length) : nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (length > capacity)
throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_LengthGreaterThanCapacity"));
Contract.EndContractBlock();
// Check for wraparound.
if (((byte*)((long)pointer + capacity)) < pointer)
throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamWrapAround"));
if (access < FileAccess.Read || access > FileAccess.ReadWrite)
throw new ArgumentOutOfRangeException(nameof(access), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
if (_isOpen)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CalledTwice"));
_mem = pointer;
_offset = 0;
_length = length;
_capacity = capacity;
_access = access;
_isOpen = true;
}
public override bool CanRead
{
[Pure]
get { return _isOpen && (_access & FileAccess.Read) != 0; }
}
public override bool CanSeek
{
[Pure]
get { return _isOpen; }
}
public override bool CanWrite
{
[Pure]
get { return _isOpen && (_access & FileAccess.Write) != 0; }
}
protected override void Dispose(bool disposing)
{
_isOpen = false;
unsafe { _mem = null; }
// Stream allocates WaitHandles for async calls. So for correctness
// call base.Dispose(disposing) for better perf, avoiding waiting
// for the finalizers to run on those types.
base.Dispose(disposing);
}
public override void Flush()
{
if (!_isOpen) __Error.StreamIsClosed();
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
try
{
Flush();
return Task.CompletedTask;
}
catch (Exception ex)
{
return Task.FromException(ex);
}
}
public override long Length
{
get
{
if (!_isOpen) __Error.StreamIsClosed();
return Interlocked.Read(ref _length);
}
}
public long Capacity
{
get
{
if (!_isOpen) __Error.StreamIsClosed();
return _capacity;
}
}
public override long Position
{
get
{
if (!CanSeek) __Error.StreamIsClosed();
Contract.EndContractBlock();
return Interlocked.Read(ref _position);
}
set
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
if (!CanSeek) __Error.StreamIsClosed();
#if !BIT64
unsafe {
// On 32 bit machines, ensure we don't wrap around.
if (value > (long) Int32.MaxValue || _mem + value < _mem)
throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
}
#endif
Interlocked.Exchange(ref _position, value);
}
}
[CLSCompliant(false)]
public unsafe byte* PositionPointer
{
get
{
if (_buffer != null)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer"));
}
// Use a temp to avoid a race
long pos = Interlocked.Read(ref _position);
if (pos > _capacity)
throw new IndexOutOfRangeException(Environment.GetResourceString("IndexOutOfRange_UMSPosition"));
byte* ptr = _mem + pos;
if (!_isOpen) __Error.StreamIsClosed();
return ptr;
}
set
{
if (_buffer != null)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer"));
if (!_isOpen) __Error.StreamIsClosed();
// Note: subtracting pointers returns an Int64. Working around
// to avoid hitting compiler warning CS0652 on this line.
if (new IntPtr(value - _mem).ToInt64() > UnmanagedMemStreamMaxLength)
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamLength"));
if (value < _mem)
throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
Interlocked.Exchange(ref _position, value - _mem);
}
}
internal unsafe byte* Pointer
{
get
{
if (_buffer != null)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer"));
return _mem;
}
}
public override int Read([In, Out] byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock(); // Keep this in sync with contract validation in ReadAsync
if (!_isOpen) __Error.StreamIsClosed();
if (!CanRead) __Error.ReadNotSupported();
// Use a local variable to avoid a race where another thread
// changes our position after we decide we can read some bytes.
long pos = Interlocked.Read(ref _position);
long len = Interlocked.Read(ref _length);
long n = len - pos;
if (n > count)
n = count;
if (n <= 0)
return 0;
int nInt = (int)n; // Safe because n <= count, which is an Int32
if (nInt < 0)
return 0; // _position could be beyond EOF
Debug.Assert(pos + nInt >= 0, "_position + n >= 0"); // len is less than 2^63 -1.
unsafe
{
fixed (byte* pBuffer = buffer)
{
if (_buffer != null)
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
Buffer.Memcpy(pBuffer + offset, pointer + pos + _offset, nInt);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
else
{
Buffer.Memcpy(pBuffer + offset, _mem + pos, nInt);
}
}
}
Interlocked.Exchange(ref _position, pos + n);
return nInt;
}
public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock(); // contract validation copied from Read(...)
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled<Int32>(cancellationToken);
try
{
Int32 n = Read(buffer, offset, count);
Task<Int32> t = _lastReadTask;
return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<Int32>(n));
}
catch (Exception ex)
{
Debug.Assert(!(ex is OperationCanceledException));
return Task.FromException<Int32>(ex);
}
}
public override int ReadByte()
{
if (!_isOpen) __Error.StreamIsClosed();
if (!CanRead) __Error.ReadNotSupported();
long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition
long len = Interlocked.Read(ref _length);
if (pos >= len)
return -1;
Interlocked.Exchange(ref _position, pos + 1);
int result;
if (_buffer != null)
{
unsafe
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
result = *(pointer + pos + _offset);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
}
else
{
unsafe
{
result = _mem[pos];
}
}
return result;
}
public override long Seek(long offset, SeekOrigin loc)
{
if (!_isOpen) __Error.StreamIsClosed();
if (offset > UnmanagedMemStreamMaxLength)
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamLength"));
switch (loc)
{
case SeekOrigin.Begin:
if (offset < 0)
throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
Interlocked.Exchange(ref _position, offset);
break;
case SeekOrigin.Current:
long pos = Interlocked.Read(ref _position);
if (offset + pos < 0)
throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
Interlocked.Exchange(ref _position, offset + pos);
break;
case SeekOrigin.End:
long len = Interlocked.Read(ref _length);
if (len + offset < 0)
throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
Interlocked.Exchange(ref _position, len + offset);
break;
default:
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSeekOrigin"));
}
long finalPos = Interlocked.Read(ref _position);
Debug.Assert(finalPos >= 0, "_position >= 0");
return finalPos;
}
public override void SetLength(long value)
{
if (value < 0)
throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
if (_buffer != null)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer"));
if (!_isOpen) __Error.StreamIsClosed();
if (!CanWrite) __Error.WriteNotSupported();
if (value > _capacity)
throw new IOException(Environment.GetResourceString("IO.IO_FixedCapacity"));
long pos = Interlocked.Read(ref _position);
long len = Interlocked.Read(ref _length);
if (value > len)
{
unsafe
{
Buffer.ZeroMemory(_mem + len, value - len);
}
}
Interlocked.Exchange(ref _length, value);
if (pos > value)
{
Interlocked.Exchange(ref _position, value);
}
}
public override void Write(byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock(); // Keep contract validation in sync with WriteAsync(..)
if (!_isOpen) __Error.StreamIsClosed();
if (!CanWrite) __Error.WriteNotSupported();
long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition
long len = Interlocked.Read(ref _length);
long n = pos + count;
// Check for overflow
if (n < 0)
throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong"));
if (n > _capacity)
{
throw new NotSupportedException(Environment.GetResourceString("IO.IO_FixedCapacity"));
}
if (_buffer == null)
{
// Check to see whether we are now expanding the stream and must
// zero any memory in the middle.
if (pos > len)
{
unsafe
{
Buffer.ZeroMemory(_mem + len, pos - len);
}
}
// set length after zeroing memory to avoid race condition of accessing unzeroed memory
if (n > len)
{
Interlocked.Exchange(ref _length, n);
}
}
unsafe
{
fixed (byte* pBuffer = buffer)
{
if (_buffer != null)
{
long bytesLeft = _capacity - pos;
if (bytesLeft < count)
{
throw new ArgumentException(Environment.GetResourceString("Arg_BufferTooSmall"));
}
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
Buffer.Memcpy(pointer + pos + _offset, pBuffer + offset, count);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
else
{
Buffer.Memcpy(_mem + pos, pBuffer + offset, count);
}
}
}
Interlocked.Exchange(ref _position, n);
return;
}
public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock(); // contract validation copied from Write(..)
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
try
{
Write(buffer, offset, count);
return Task.CompletedTask;
}
catch (Exception ex)
{
Debug.Assert(!(ex is OperationCanceledException));
return Task.FromException<Int32>(ex);
}
}
public override void WriteByte(byte value)
{
if (!_isOpen) __Error.StreamIsClosed();
if (!CanWrite) __Error.WriteNotSupported();
long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition
long len = Interlocked.Read(ref _length);
long n = pos + 1;
if (pos >= len)
{
// Check for overflow
if (n < 0)
throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong"));
if (n > _capacity)
throw new NotSupportedException(Environment.GetResourceString("IO.IO_FixedCapacity"));
// Check to see whether we are now expanding the stream and must
// zero any memory in the middle.
// don't do if created from SafeBuffer
if (_buffer == null)
{
if (pos > len)
{
unsafe
{
Buffer.ZeroMemory(_mem + len, pos - len);
}
}
// set length after zeroing memory to avoid race condition of accessing unzeroed memory
Interlocked.Exchange(ref _length, n);
}
}
if (_buffer != null)
{
unsafe
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
*(pointer + pos + _offset) = value;
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
}
else
{
unsafe
{
_mem[pos] = value;
}
}
Interlocked.Exchange(ref _position, n);
}
}
}
| |
// Copyright (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.Xml.Linq;
using Microsoft.CodeAnalysis.Editor.Commands;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Operations;
using Roslyn.Test.Utilities;
using Xunit;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.Editor.UnitTests
{
internal abstract class AbstractCommandHandlerTestState : IDisposable
{
public readonly TestWorkspace Workspace;
public readonly IEditorOperations EditorOperations;
public readonly ITextUndoHistoryRegistry UndoHistoryRegistry;
private readonly ITextView _textView;
private readonly ITextBuffer _subjectBuffer;
public AbstractCommandHandlerTestState(
XElement workspaceElement,
ComposableCatalog extraParts = null,
bool useMinimumCatalog = false,
string workspaceKind = null)
: this(workspaceElement, GetExportProvider(useMinimumCatalog, extraParts), workspaceKind)
{
}
/// <summary>
/// This can use input files with an (optionally) annotated span 'Selection' and a cursor position ($$),
/// and use it to create a selected span in the TextView.
///
/// For instance, the following will create a TextView that has a multiline selection with the cursor at the end.
///
/// Sub Foo
/// {|Selection:SomeMethodCall()
/// AnotherMethodCall()$$|}
/// End Sub
///
/// You can use multiple selection spans to create box selections.
///
/// Sub Foo
/// {|Selection:$$box|}11111
/// {|Selection:sel|}111
/// {|Selection:ect|}1
/// {|Selection:ion|}1111111
/// End Sub
/// </summary>
public AbstractCommandHandlerTestState(
XElement workspaceElement,
ExportProvider exportProvider,
string workspaceKind)
{
this.Workspace = TestWorkspace.CreateWorkspace(
workspaceElement,
exportProvider: exportProvider,
workspaceKind: workspaceKind);
var cursorDocument = this.Workspace.Documents.First(d => d.CursorPosition.HasValue);
_textView = cursorDocument.GetTextView();
_subjectBuffer = cursorDocument.GetTextBuffer();
if (cursorDocument.AnnotatedSpans.TryGetValue("Selection", out var selectionSpanList))
{
var firstSpan = selectionSpanList.First();
var lastSpan = selectionSpanList.Last();
var cursorPosition = cursorDocument.CursorPosition.Value;
Assert.True(cursorPosition == firstSpan.Start || cursorPosition == firstSpan.End
|| cursorPosition == lastSpan.Start || cursorPosition == lastSpan.End,
"cursorPosition wasn't at an endpoint of the 'Selection' annotated span");
_textView.Selection.Mode = selectionSpanList.Length > 1
? TextSelectionMode.Box
: TextSelectionMode.Stream;
SnapshotPoint boxSelectionStart, boxSelectionEnd;
bool isReversed;
if (cursorPosition == firstSpan.Start || cursorPosition == lastSpan.End)
{
// Top-left and bottom-right corners used as anchor points.
boxSelectionStart = new SnapshotPoint(_subjectBuffer.CurrentSnapshot, firstSpan.Start);
boxSelectionEnd = new SnapshotPoint(_subjectBuffer.CurrentSnapshot, lastSpan.End);
isReversed = cursorPosition == firstSpan.Start;
}
else
{
// Top-right and bottom-left corners used as anchor points.
boxSelectionStart = new SnapshotPoint(_subjectBuffer.CurrentSnapshot, firstSpan.End);
boxSelectionEnd = new SnapshotPoint(_subjectBuffer.CurrentSnapshot, lastSpan.Start);
isReversed = cursorPosition == firstSpan.End;
}
_textView.Selection.Select(
new SnapshotSpan(boxSelectionStart, boxSelectionEnd),
isReversed: isReversed);
}
else
{
_textView.Caret.MoveTo(
new SnapshotPoint(
_textView.TextBuffer.CurrentSnapshot,
cursorDocument.CursorPosition.Value));
}
this.EditorOperations = GetService<IEditorOperationsFactoryService>().GetEditorOperations(_textView);
this.UndoHistoryRegistry = GetService<ITextUndoHistoryRegistry>();
}
public void Dispose()
{
Workspace.Dispose();
}
public T GetService<T>()
{
return Workspace.GetService<T>();
}
private static ExportProvider GetExportProvider(bool useMinimumCatalog, ComposableCatalog extraParts)
{
var baseCatalog = useMinimumCatalog
? TestExportProvider.MinimumCatalogWithCSharpAndVisualBasic
: TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic;
if (extraParts == null)
{
return MinimalTestExportProvider.CreateExportProvider(baseCatalog);
}
return MinimalTestExportProvider.CreateExportProvider(baseCatalog.WithParts(extraParts));
}
public virtual ITextView TextView
{
get { return _textView; }
}
public virtual ITextBuffer SubjectBuffer
{
get { return _subjectBuffer; }
}
#region MEF
public Lazy<TExport, TMetadata> GetExport<TExport, TMetadata>()
{
return (Lazy<TExport, TMetadata>)(object)Workspace.ExportProvider.GetExport<TExport, TMetadata>();
}
public IEnumerable<Lazy<TExport, TMetadata>> GetExports<TExport, TMetadata>()
{
return Workspace.ExportProvider.GetExports<TExport, TMetadata>();
}
public T GetExportedValue<T>()
{
return Workspace.ExportProvider.GetExportedValue<T>();
}
public IEnumerable<T> GetExportedValues<T>()
{
return Workspace.ExportProvider.GetExportedValues<T>();
}
protected static IEnumerable<Lazy<TProvider, OrderableLanguageMetadata>> CreateLazyProviders<TProvider>(
TProvider[] providers,
string languageName)
{
if (providers == null)
{
return Array.Empty<Lazy<TProvider, OrderableLanguageMetadata>>();
}
return providers.Select(p =>
new Lazy<TProvider, OrderableLanguageMetadata>(
() => p,
new OrderableLanguageMetadata(
new Dictionary<string, object> {
{"Language", languageName },
{"Name", string.Empty }}),
true));
}
protected static IEnumerable<Lazy<TProvider, OrderableLanguageAndRoleMetadata>> CreateLazyProviders<TProvider>(
TProvider[] providers,
string languageName,
string[] roles)
{
if (providers == null)
{
return Array.Empty<Lazy<TProvider, OrderableLanguageAndRoleMetadata>>();
}
return providers.Select(p =>
new Lazy<TProvider, OrderableLanguageAndRoleMetadata>(
() => p,
new OrderableLanguageAndRoleMetadata(
new Dictionary<string, object> {
{"Language", languageName },
{"Name", string.Empty },
{"Roles", roles }}),
true));
}
#endregion
#region editor related operation
public void SendBackspace()
{
EditorOperations.Backspace();
}
public void SendDelete()
{
EditorOperations.Delete();
}
public void SendRightKey(bool extendSelection = false)
{
EditorOperations.MoveToNextCharacter(extendSelection);
}
public void SendLeftKey(bool extendSelection = false)
{
EditorOperations.MoveToPreviousCharacter(extendSelection);
}
public void SendMoveToPreviousCharacter(bool extendSelection = false)
{
EditorOperations.MoveToPreviousCharacter(extendSelection);
}
public void SendDeleteWordToLeft()
{
EditorOperations.DeleteWordToLeft();
}
public void SendUndo(int count = 1)
{
var history = UndoHistoryRegistry.GetHistory(SubjectBuffer);
history.Undo(count);
}
#endregion
#region test/information/verification
public ITextSnapshotLine GetLineFromCurrentCaretPosition()
{
var caretPosition = GetCaretPoint();
return SubjectBuffer.CurrentSnapshot.GetLineFromPosition(caretPosition.BufferPosition);
}
public string GetLineTextFromCaretPosition()
{
var caretPosition = Workspace.Documents.Single(d => d.CursorPosition.HasValue).CursorPosition.Value;
return SubjectBuffer.CurrentSnapshot.GetLineFromPosition(caretPosition).GetText();
}
public string GetDocumentText()
{
return SubjectBuffer.CurrentSnapshot.GetText();
}
public CaretPosition GetCaretPoint()
{
return TextView.Caret.Position;
}
/// <summary>
/// Used in synchronous methods to ensure all outstanding <see cref="IAsyncToken"/> work has been
/// completed.
/// </summary>
public void AssertNoAsynchronousOperationsRunning()
{
var waiters = Workspace.ExportProvider.GetExportedValues<IAsynchronousOperationWaiter>();
Assert.False(waiters.Any(x => x.HasPendingWork), "IAsyncTokens unexpectedly alive. Call WaitForAsynchronousOperationsAsync before this method");
}
public async Task WaitForAsynchronousOperationsAsync()
{
var waiters = Workspace.ExportProvider.GetExportedValues<IAsynchronousOperationWaiter>();
await waiters.WaitAllAsync();
}
public void AssertMatchesTextStartingAtLine(int line, string text)
{
var lines = text.Split('\r');
foreach (var expectedLine in lines)
{
Assert.Equal(expectedLine.Trim(), SubjectBuffer.CurrentSnapshot.GetLineFromLineNumber(line).GetText().Trim());
line += 1;
}
}
#endregion
#region command handler
public void SendBackspace(Action<BackspaceKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new BackspaceKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendDelete(Action<DeleteKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new DeleteKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendWordDeleteToStart(Action<WordDeleteToStartCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new WordDeleteToStartCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendEscape(Action<EscapeKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new EscapeKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendUpKey(Action<UpKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new UpKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendDownKey(Action<DownKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new DownKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendTab(Action<TabKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new TabKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendBackTab(Action<BackTabKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new BackTabKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendReturn(Action<ReturnKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new ReturnKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendPageUp(Action<PageUpKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new PageUpKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendPageDown(Action<PageDownKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new PageDownKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendCut(Action<CutCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new CutCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendPaste(Action<PasteCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new PasteCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendInvokeCompletionList(Action<InvokeCompletionListCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new InvokeCompletionListCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendCommitUniqueCompletionListItem(Action<CommitUniqueCompletionListItemCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new CommitUniqueCompletionListItemCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendInsertSnippetCommand(Action<InsertSnippetCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new InsertSnippetCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendSurroundWithCommand(Action<SurroundWithCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new SurroundWithCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendInvokeSignatureHelp(Action<InvokeSignatureHelpCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new InvokeSignatureHelpCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendTypeChar(char typeChar, Action<TypeCharCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new TypeCharCommandArgs(TextView, SubjectBuffer, typeChar), nextHandler);
}
public void SendTypeChars(string typeChars, Action<TypeCharCommandArgs, Action> commandHandler)
{
foreach (var ch in typeChars)
{
var localCh = ch;
SendTypeChar(ch, commandHandler, () => EditorOperations.InsertText(localCh.ToString()));
}
}
public void SendSave(Action<SaveCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new SaveCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendSelectAll(Action<SelectAllCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new SelectAllCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendToggleCompletionMode(Action<ToggleCompletionModeCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new ToggleCompletionModeCommandArgs(TextView, SubjectBuffer), nextHandler);
}
#endregion
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Game.Audio;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Edit.Checks;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Tests.Editing.Checks
{
[TestFixture]
public class CheckMutedObjectsTest
{
private CheckMutedObjects check;
private ControlPointInfo cpi;
private const int volume_regular = 50;
private const int volume_low = 15;
private const int volume_muted = 5;
[SetUp]
public void Setup()
{
check = new CheckMutedObjects();
cpi = new ControlPointInfo();
cpi.Add(0, new SampleControlPoint { SampleVolume = volume_regular });
cpi.Add(1000, new SampleControlPoint { SampleVolume = volume_low });
cpi.Add(2000, new SampleControlPoint { SampleVolume = volume_muted });
}
[Test]
public void TestNormalControlPointVolume()
{
var hitcircle = new HitCircle
{
StartTime = 0,
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) }
};
hitcircle.ApplyDefaults(cpi, new BeatmapDifficulty());
assertOk(new List<HitObject> { hitcircle });
}
[Test]
public void TestLowControlPointVolume()
{
var hitcircle = new HitCircle
{
StartTime = 1000,
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) }
};
hitcircle.ApplyDefaults(cpi, new BeatmapDifficulty());
assertLowVolume(new List<HitObject> { hitcircle });
}
[Test]
public void TestMutedControlPointVolume()
{
var hitcircle = new HitCircle
{
StartTime = 2000,
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) }
};
hitcircle.ApplyDefaults(cpi, new BeatmapDifficulty());
assertMuted(new List<HitObject> { hitcircle });
}
[Test]
public void TestNormalSampleVolume()
{
// The sample volume should take precedence over the control point volume.
var hitcircle = new HitCircle
{
StartTime = 2000,
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL, volume: volume_regular) }
};
hitcircle.ApplyDefaults(cpi, new BeatmapDifficulty());
assertOk(new List<HitObject> { hitcircle });
}
[Test]
public void TestLowSampleVolume()
{
var hitcircle = new HitCircle
{
StartTime = 2000,
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL, volume: volume_low) }
};
hitcircle.ApplyDefaults(cpi, new BeatmapDifficulty());
assertLowVolume(new List<HitObject> { hitcircle });
}
[Test]
public void TestMutedSampleVolume()
{
var hitcircle = new HitCircle
{
StartTime = 0,
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL, volume: volume_muted) }
};
hitcircle.ApplyDefaults(cpi, new BeatmapDifficulty());
assertMuted(new List<HitObject> { hitcircle });
}
[Test]
public void TestNormalSampleVolumeSlider()
{
var sliderHead = new SliderHeadCircle
{
StartTime = 0,
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) }
};
sliderHead.ApplyDefaults(cpi, new BeatmapDifficulty());
var sliderTick = new SliderTick
{
StartTime = 250,
Samples = new List<HitSampleInfo> { new HitSampleInfo("slidertick", volume: volume_muted) } // Should be fine.
};
sliderTick.ApplyDefaults(cpi, new BeatmapDifficulty());
var slider = new MockNestableHitObject(new List<HitObject> { sliderHead, sliderTick, }, startTime: 0, endTime: 500)
{
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) }
};
slider.ApplyDefaults(cpi, new BeatmapDifficulty());
assertOk(new List<HitObject> { slider });
}
[Test]
public void TestMutedSampleVolumeSliderHead()
{
var sliderHead = new SliderHeadCircle
{
StartTime = 0,
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL, volume: volume_muted) }
};
sliderHead.ApplyDefaults(cpi, new BeatmapDifficulty());
var sliderTick = new SliderTick
{
StartTime = 250,
Samples = new List<HitSampleInfo> { new HitSampleInfo("slidertick") }
};
sliderTick.ApplyDefaults(cpi, new BeatmapDifficulty());
var slider = new MockNestableHitObject(new List<HitObject> { sliderHead, sliderTick, }, startTime: 0, endTime: 500)
{
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) } // Applies to the tail.
};
slider.ApplyDefaults(cpi, new BeatmapDifficulty());
assertMuted(new List<HitObject> { slider });
}
[Test]
public void TestMutedSampleVolumeSliderTail()
{
var sliderHead = new SliderHeadCircle
{
StartTime = 0,
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) }
};
sliderHead.ApplyDefaults(cpi, new BeatmapDifficulty());
var sliderTick = new SliderTick
{
StartTime = 250,
Samples = new List<HitSampleInfo> { new HitSampleInfo("slidertick") }
};
sliderTick.ApplyDefaults(cpi, new BeatmapDifficulty());
var slider = new MockNestableHitObject(new List<HitObject> { sliderHead, sliderTick, }, startTime: 0, endTime: 2500)
{
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL, volume: volume_muted) } // Applies to the tail.
};
slider.ApplyDefaults(cpi, new BeatmapDifficulty());
assertMutedPassive(new List<HitObject> { slider });
}
[Test]
public void TestMutedControlPointVolumeSliderHead()
{
var sliderHead = new SliderHeadCircle
{
StartTime = 2000,
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) }
};
sliderHead.ApplyDefaults(cpi, new BeatmapDifficulty());
var sliderTick = new SliderTick
{
StartTime = 2250,
Samples = new List<HitSampleInfo> { new HitSampleInfo("slidertick") }
};
sliderTick.ApplyDefaults(cpi, new BeatmapDifficulty());
var slider = new MockNestableHitObject(new List<HitObject> { sliderHead, sliderTick, }, startTime: 2000, endTime: 2500)
{
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL, volume: volume_regular) }
};
slider.ApplyDefaults(cpi, new BeatmapDifficulty());
assertMuted(new List<HitObject> { slider });
}
[Test]
public void TestMutedControlPointVolumeSliderTail()
{
var sliderHead = new SliderHeadCircle
{
StartTime = 0,
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) }
};
sliderHead.ApplyDefaults(cpi, new BeatmapDifficulty());
var sliderTick = new SliderTick
{
StartTime = 250,
Samples = new List<HitSampleInfo> { new HitSampleInfo("slidertick") }
};
sliderTick.ApplyDefaults(cpi, new BeatmapDifficulty());
// Ends after the 5% control point.
var slider = new MockNestableHitObject(new List<HitObject> { sliderHead, sliderTick, }, startTime: 0, endTime: 2500)
{
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) }
};
slider.ApplyDefaults(cpi, new BeatmapDifficulty());
assertMutedPassive(new List<HitObject> { slider });
}
private void assertOk(List<HitObject> hitObjects)
{
Assert.That(check.Run(getContext(hitObjects)), Is.Empty);
}
private void assertLowVolume(List<HitObject> hitObjects, int count = 1)
{
var issues = check.Run(getContext(hitObjects)).ToList();
Assert.That(issues, Has.Count.EqualTo(count));
Assert.That(issues.All(issue => issue.Template is CheckMutedObjects.IssueTemplateLowVolumeActive));
}
private void assertMuted(List<HitObject> hitObjects, int count = 1)
{
var issues = check.Run(getContext(hitObjects)).ToList();
Assert.That(issues, Has.Count.EqualTo(count));
Assert.That(issues.All(issue => issue.Template is CheckMutedObjects.IssueTemplateMutedActive));
}
private void assertMutedPassive(List<HitObject> hitObjects)
{
var issues = check.Run(getContext(hitObjects)).ToList();
Assert.That(issues, Has.Count.EqualTo(1));
Assert.That(issues.Any(issue => issue.Template is CheckMutedObjects.IssueTemplateMutedPassive));
}
private BeatmapVerifierContext getContext(List<HitObject> hitObjects)
{
var beatmap = new Beatmap<HitObject>
{
ControlPointInfo = cpi,
HitObjects = hitObjects
};
return new BeatmapVerifierContext(beatmap, new TestWorkingBeatmap(beatmap));
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp
{
/// <summary>
/// A matrix of type bool with 4 columns and 2 rows.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct bmat4x2 : IEnumerable<bool>, IEquatable<bmat4x2>
{
#region Fields
/// <summary>
/// Column 0, Rows 0
/// </summary>
public bool m00;
/// <summary>
/// Column 0, Rows 1
/// </summary>
public bool m01;
/// <summary>
/// Column 1, Rows 0
/// </summary>
public bool m10;
/// <summary>
/// Column 1, Rows 1
/// </summary>
public bool m11;
/// <summary>
/// Column 2, Rows 0
/// </summary>
public bool m20;
/// <summary>
/// Column 2, Rows 1
/// </summary>
public bool m21;
/// <summary>
/// Column 3, Rows 0
/// </summary>
public bool m30;
/// <summary>
/// Column 3, Rows 1
/// </summary>
public bool m31;
#endregion
#region Constructors
/// <summary>
/// Component-wise constructor
/// </summary>
public bmat4x2(bool m00, bool m01, bool m10, bool m11, bool m20, bool m21, bool m30, bool m31)
{
this.m00 = m00;
this.m01 = m01;
this.m10 = m10;
this.m11 = m11;
this.m20 = m20;
this.m21 = m21;
this.m30 = m30;
this.m31 = m31;
}
/// <summary>
/// Constructs this matrix from a bmat2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public bmat4x2(bmat2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = false;
this.m21 = false;
this.m30 = false;
this.m31 = false;
}
/// <summary>
/// Constructs this matrix from a bmat3x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public bmat4x2(bmat3x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = m.m20;
this.m21 = m.m21;
this.m30 = false;
this.m31 = false;
}
/// <summary>
/// Constructs this matrix from a bmat4x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public bmat4x2(bmat4x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = m.m20;
this.m21 = m.m21;
this.m30 = m.m30;
this.m31 = m.m31;
}
/// <summary>
/// Constructs this matrix from a bmat2x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public bmat4x2(bmat2x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = false;
this.m21 = false;
this.m30 = false;
this.m31 = false;
}
/// <summary>
/// Constructs this matrix from a bmat3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public bmat4x2(bmat3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = m.m20;
this.m21 = m.m21;
this.m30 = false;
this.m31 = false;
}
/// <summary>
/// Constructs this matrix from a bmat4x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public bmat4x2(bmat4x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = m.m20;
this.m21 = m.m21;
this.m30 = m.m30;
this.m31 = m.m31;
}
/// <summary>
/// Constructs this matrix from a bmat2x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public bmat4x2(bmat2x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = false;
this.m21 = false;
this.m30 = false;
this.m31 = false;
}
/// <summary>
/// Constructs this matrix from a bmat3x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public bmat4x2(bmat3x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = m.m20;
this.m21 = m.m21;
this.m30 = false;
this.m31 = false;
}
/// <summary>
/// Constructs this matrix from a bmat4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public bmat4x2(bmat4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = m.m20;
this.m21 = m.m21;
this.m30 = m.m30;
this.m31 = m.m31;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public bmat4x2(bvec2 c0, bvec2 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m10 = c1.x;
this.m11 = c1.y;
this.m20 = false;
this.m21 = false;
this.m30 = false;
this.m31 = false;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public bmat4x2(bvec2 c0, bvec2 c1, bvec2 c2)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m10 = c1.x;
this.m11 = c1.y;
this.m20 = c2.x;
this.m21 = c2.y;
this.m30 = false;
this.m31 = false;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public bmat4x2(bvec2 c0, bvec2 c1, bvec2 c2, bvec2 c3)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m10 = c1.x;
this.m11 = c1.y;
this.m20 = c2.x;
this.m21 = c2.y;
this.m30 = c3.x;
this.m31 = c3.y;
}
#endregion
#region Properties
/// <summary>
/// Creates a 2D array with all values (address: Values[x, y])
/// </summary>
public bool[,] Values => new[,] { { m00, m01 }, { m10, m11 }, { m20, m21 }, { m30, m31 } };
/// <summary>
/// Creates a 1D array with all values (internal order)
/// </summary>
public bool[] Values1D => new[] { m00, m01, m10, m11, m20, m21, m30, m31 };
/// <summary>
/// Gets or sets the column nr 0
/// </summary>
public bvec2 Column0
{
get
{
return new bvec2(m00, m01);
}
set
{
m00 = value.x;
m01 = value.y;
}
}
/// <summary>
/// Gets or sets the column nr 1
/// </summary>
public bvec2 Column1
{
get
{
return new bvec2(m10, m11);
}
set
{
m10 = value.x;
m11 = value.y;
}
}
/// <summary>
/// Gets or sets the column nr 2
/// </summary>
public bvec2 Column2
{
get
{
return new bvec2(m20, m21);
}
set
{
m20 = value.x;
m21 = value.y;
}
}
/// <summary>
/// Gets or sets the column nr 3
/// </summary>
public bvec2 Column3
{
get
{
return new bvec2(m30, m31);
}
set
{
m30 = value.x;
m31 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 0
/// </summary>
public bvec4 Row0
{
get
{
return new bvec4(m00, m10, m20, m30);
}
set
{
m00 = value.x;
m10 = value.y;
m20 = value.z;
m30 = value.w;
}
}
/// <summary>
/// Gets or sets the row nr 1
/// </summary>
public bvec4 Row1
{
get
{
return new bvec4(m01, m11, m21, m31);
}
set
{
m01 = value.x;
m11 = value.y;
m21 = value.z;
m31 = value.w;
}
}
#endregion
#region Static Properties
/// <summary>
/// Predefined all-zero matrix
/// </summary>
public static bmat4x2 Zero { get; } = new bmat4x2(false, false, false, false, false, false, false, false);
/// <summary>
/// Predefined all-ones matrix
/// </summary>
public static bmat4x2 Ones { get; } = new bmat4x2(true, true, true, true, true, true, true, true);
/// <summary>
/// Predefined identity matrix
/// </summary>
public static bmat4x2 Identity { get; } = new bmat4x2(true, false, false, true, false, false, false, false);
#endregion
#region Functions
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
public IEnumerator<bool> GetEnumerator()
{
yield return m00;
yield return m01;
yield return m10;
yield return m11;
yield return m20;
yield return m21;
yield return m30;
yield return m31;
}
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
#endregion
/// <summary>
/// Returns the number of Fields (4 x 2 = 8).
/// </summary>
public int Count => 8;
/// <summary>
/// Gets/Sets a specific indexed component (a bit slower than direct access).
/// </summary>
public bool this[int fieldIndex]
{
get
{
switch (fieldIndex)
{
case 0: return m00;
case 1: return m01;
case 2: return m10;
case 3: return m11;
case 4: return m20;
case 5: return m21;
case 6: return m30;
case 7: return m31;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
set
{
switch (fieldIndex)
{
case 0: this.m00 = value; break;
case 1: this.m01 = value; break;
case 2: this.m10 = value; break;
case 3: this.m11 = value; break;
case 4: this.m20 = value; break;
case 5: this.m21 = value; break;
case 6: this.m30 = value; break;
case 7: this.m31 = value; break;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
}
/// <summary>
/// Gets/Sets a specific 2D-indexed component (a bit slower than direct access).
/// </summary>
public bool this[int col, int row]
{
get
{
return this[col * 2 + row];
}
set
{
this[col * 2 + row] = value;
}
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public bool Equals(bmat4x2 rhs) => (((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && (m10.Equals(rhs.m10) && m11.Equals(rhs.m11))) && ((m20.Equals(rhs.m20) && m21.Equals(rhs.m21)) && (m30.Equals(rhs.m30) && m31.Equals(rhs.m31))));
/// <summary>
/// Returns true iff this equals rhs type- and component-wise.
/// </summary>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is bmat4x2 && Equals((bmat4x2) obj);
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public static bool operator ==(bmat4x2 lhs, bmat4x2 rhs) => lhs.Equals(rhs);
/// <summary>
/// Returns true iff this does not equal rhs (component-wise).
/// </summary>
public static bool operator !=(bmat4x2 lhs, bmat4x2 rhs) => !lhs.Equals(rhs);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
public override int GetHashCode()
{
unchecked
{
return ((((((((((((((m00.GetHashCode()) * 2) ^ m01.GetHashCode()) * 2) ^ m10.GetHashCode()) * 2) ^ m11.GetHashCode()) * 2) ^ m20.GetHashCode()) * 2) ^ m21.GetHashCode()) * 2) ^ m30.GetHashCode()) * 2) ^ m31.GetHashCode();
}
}
/// <summary>
/// Returns a transposed version of this matrix.
/// </summary>
public bmat2x4 Transposed => new bmat2x4(m00, m10, m20, m30, m01, m11, m21, m31);
/// <summary>
/// Returns the minimal component of this matrix.
/// </summary>
public bool MinElement => (((m00 && m01) && (m10 && m11)) && ((m20 && m21) && (m30 && m31)));
/// <summary>
/// Returns the maximal component of this matrix.
/// </summary>
public bool MaxElement => (((m00 || m01) || (m10 || m11)) || ((m20 || m21) || (m30 || m31)));
/// <summary>
/// Returns true if all component are true.
/// </summary>
public bool All => (((m00 && m01) && (m10 && m11)) && ((m20 && m21) && (m30 && m31)));
/// <summary>
/// Returns true if any component is true.
/// </summary>
public bool Any => (((m00 || m01) || (m10 || m11)) || ((m20 || m21) || (m30 || m31)));
/// <summary>
/// Executes a component-wise &&. (sorry for different overload but && cannot be overloaded directly)
/// </summary>
public static bmat4x2 operator&(bmat4x2 lhs, bmat4x2 rhs) => new bmat4x2(lhs.m00 && rhs.m00, lhs.m01 && rhs.m01, lhs.m10 && rhs.m10, lhs.m11 && rhs.m11, lhs.m20 && rhs.m20, lhs.m21 && rhs.m21, lhs.m30 && rhs.m30, lhs.m31 && rhs.m31);
/// <summary>
/// Executes a component-wise ||. (sorry for different overload but || cannot be overloaded directly)
/// </summary>
public static bmat4x2 operator|(bmat4x2 lhs, bmat4x2 rhs) => new bmat4x2(lhs.m00 || rhs.m00, lhs.m01 || rhs.m01, lhs.m10 || rhs.m10, lhs.m11 || rhs.m11, lhs.m20 || rhs.m20, lhs.m21 || rhs.m21, lhs.m30 || rhs.m30, lhs.m31 || rhs.m31);
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: helloworld.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Helloworld {
/// <summary>Holder for reflection information generated from helloworld.proto</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class HelloworldReflection {
#region Descriptor
/// <summary>File descriptor for helloworld.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static HelloworldReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChBoZWxsb3dvcmxkLnByb3RvEgpoZWxsb3dvcmxkIhwKDEhlbGxvUmVxdWVz",
"dBIMCgRuYW1lGAEgASgJIh0KCkhlbGxvUmVwbHkSDwoHbWVzc2FnZRgBIAEo",
"CTJJCgdHcmVldGVyEj4KCFNheUhlbGxvEhguaGVsbG93b3JsZC5IZWxsb1Jl",
"cXVlc3QaFi5oZWxsb3dvcmxkLkhlbGxvUmVwbHkiAEIYChBpby5ncnBjLmV4",
"YW1wbGVzogIDSExXYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] {
new pbr::GeneratedCodeInfo(typeof(global::Helloworld.HelloRequest), global::Helloworld.HelloRequest.Parser, new[]{ "Name" }, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::Helloworld.HelloReply), global::Helloworld.HelloReply.Parser, new[]{ "Message" }, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// The request message containing the user's name.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class HelloRequest : pb::IMessage<HelloRequest> {
private static readonly pb::MessageParser<HelloRequest> _parser = new pb::MessageParser<HelloRequest>(() => new HelloRequest());
public static pb::MessageParser<HelloRequest> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Helloworld.HelloworldReflection.Descriptor.MessageTypes[0]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public HelloRequest() {
OnConstruction();
}
partial void OnConstruction();
public HelloRequest(HelloRequest other) : this() {
name_ = other.name_;
}
public HelloRequest Clone() {
return new HelloRequest(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
public string Name {
get { return name_; }
set {
name_ = pb::Preconditions.CheckNotNull(value, "value");
}
}
public override bool Equals(object other) {
return Equals(other as HelloRequest);
}
public bool Equals(HelloRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
}
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
return size;
}
public void MergeFrom(HelloRequest other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Name = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// The response message containing the greetings
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class HelloReply : pb::IMessage<HelloReply> {
private static readonly pb::MessageParser<HelloReply> _parser = new pb::MessageParser<HelloReply>(() => new HelloReply());
public static pb::MessageParser<HelloReply> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Helloworld.HelloworldReflection.Descriptor.MessageTypes[1]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public HelloReply() {
OnConstruction();
}
partial void OnConstruction();
public HelloReply(HelloReply other) : this() {
message_ = other.message_;
}
public HelloReply Clone() {
return new HelloReply(this);
}
/// <summary>Field number for the "message" field.</summary>
public const int MessageFieldNumber = 1;
private string message_ = "";
public string Message {
get { return message_; }
set {
message_ = pb::Preconditions.CheckNotNull(value, "value");
}
}
public override bool Equals(object other) {
return Equals(other as HelloReply);
}
public bool Equals(HelloReply other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Message != other.Message) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Message.Length != 0) hash ^= Message.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Message.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Message);
}
}
public int CalculateSize() {
int size = 0;
if (Message.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Message);
}
return size;
}
public void MergeFrom(HelloReply other) {
if (other == null) {
return;
}
if (other.Message.Length != 0) {
Message = other.Message;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Message = input.ReadString();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Diagnostics;
using Microsoft.PythonTools.Parsing;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
namespace Microsoft.PythonTools.Editor.Core {
internal static class EditorExtensions {
public static bool CommentOrUncommentBlock(this ITextView view, bool comment) {
SnapshotPoint start, end;
SnapshotPoint? mappedStart, mappedEnd;
if (view.Selection.IsActive && !view.Selection.IsEmpty) {
// comment every line in the selection
start = view.Selection.Start.Position;
end = view.Selection.End.Position;
mappedStart = MapPoint(view, start);
var endLine = end.GetContainingLine();
if (endLine.Start == end) {
// http://pytools.codeplex.com/workitem/814
// User selected one extra line, but no text on that line. So let's
// back it up to the previous line. It's impossible that we're on the
// 1st line here because we have a selection, and we end at the start of
// a line. In normal selection this is only possible if we wrapped onto the
// 2nd line, and it's impossible to have a box selection with a single line.
end = end.Snapshot.GetLineFromLineNumber(endLine.LineNumber - 1).End;
}
mappedEnd = MapPoint(view, end);
} else {
// comment the current line
start = end = view.Caret.Position.BufferPosition;
mappedStart = mappedEnd = MapPoint(view, start);
}
if (mappedStart != null && mappedEnd != null &&
mappedStart.Value <= mappedEnd.Value) {
if (comment) {
CommentRegion(view, mappedStart.Value, mappedEnd.Value);
} else {
UncommentRegion(view, mappedStart.Value, mappedEnd.Value);
}
// TODO: select multiple spans?
// Select the full region we just commented, do not select if in projection buffer
// (the selection might span non-language buffer regions)
if (view.TextBuffer.IsPythonContent()) {
UpdateSelection(view, start, end);
}
return true;
}
return false;
}
internal static bool IsPythonContent(this ITextBuffer buffer) {
return buffer.ContentType.IsOfType(PythonCoreConstants.ContentType);
}
internal static bool IsPythonContent(this ITextSnapshot buffer) {
return buffer.ContentType.IsOfType(PythonCoreConstants.ContentType);
}
private static SnapshotPoint? MapPoint(ITextView view, SnapshotPoint point) {
return view.BufferGraph.MapDownToFirstMatch(
point,
PointTrackingMode.Positive,
IsPythonContent,
PositionAffinity.Successor
);
}
public static SnapshotPoint? MapDownToPythonBuffer(this ITextView view, SnapshotPoint point) => MapPoint(view, point);
/// <summary>
/// Maps down to the buffer using positive point tracking and successor position affinity
/// </summary>
public static SnapshotPoint? MapDownToBuffer(this ITextView textView, int position, ITextBuffer buffer)
{
if (textView.BufferGraph == null) {
// Unit test case
if (position <= buffer.CurrentSnapshot.Length) {
return new SnapshotPoint(buffer.CurrentSnapshot, position);
}
return null;
}
if (position <= textView.TextBuffer.CurrentSnapshot.Length) {
return textView.BufferGraph.MapDownToBuffer(
new SnapshotPoint(textView.TextBuffer.CurrentSnapshot, position),
PointTrackingMode.Positive,
buffer,
PositionAffinity.Successor
);
}
return null;
}
/// <summary>
/// Adds comment characters (#) to the start of each line. If there is a selection the comment is applied
/// to each selected line. Otherwise the comment is applied to the current line.
/// </summary>
/// <param name="view"></param>
private static void CommentRegion(ITextView view, SnapshotPoint start, SnapshotPoint end) {
Debug.Assert(start.Snapshot == end.Snapshot);
var snapshot = start.Snapshot;
using (var edit = snapshot.TextBuffer.CreateEdit()) {
int minColumn = Int32.MaxValue;
// first pass, determine the position to place the comment
for (int i = start.GetContainingLine().LineNumber; i <= end.GetContainingLine().LineNumber; i++) {
var curLine = snapshot.GetLineFromLineNumber(i);
var text = curLine.GetText();
int firstNonWhitespace = IndexOfNonWhitespaceCharacter(text);
if (firstNonWhitespace >= 0 && firstNonWhitespace < minColumn) {
// ignore blank lines
minColumn = firstNonWhitespace;
}
}
// second pass, place the comment
for (int i = start.GetContainingLine().LineNumber; i <= end.GetContainingLine().LineNumber; i++) {
var curLine = snapshot.GetLineFromLineNumber(i);
if (String.IsNullOrWhiteSpace(curLine.GetText())) {
continue;
}
Debug.Assert(curLine.Length >= minColumn);
edit.Insert(curLine.Start.Position + minColumn, "#");
}
edit.Apply();
}
}
private static int IndexOfNonWhitespaceCharacter(string text) {
for (int j = 0; j < text.Length; j++) {
if (!Char.IsWhiteSpace(text[j])) {
return j;
}
}
return -1;
}
/// <summary>
/// Removes a comment character (#) from the start of each line. If there is a selection the character is
/// removed from each selected line. Otherwise the character is removed from the current line. Uncommented
/// lines are ignored.
/// </summary>
private static void UncommentRegion(ITextView view, SnapshotPoint start, SnapshotPoint end) {
Debug.Assert(start.Snapshot == end.Snapshot);
var snapshot = start.Snapshot;
using (var edit = snapshot.TextBuffer.CreateEdit()) {
// first pass, determine the position to place the comment
for (int i = start.GetContainingLine().LineNumber; i <= end.GetContainingLine().LineNumber; i++) {
var curLine = snapshot.GetLineFromLineNumber(i);
DeleteFirstCommentChar(edit, curLine);
}
edit.Apply();
}
}
private static void UpdateSelection(ITextView view, SnapshotPoint start, SnapshotPoint end) {
view.Selection.Select(
new SnapshotSpan(
// translate to the new snapshot version:
start.GetContainingLine().Start.TranslateTo(view.TextBuffer.CurrentSnapshot, PointTrackingMode.Negative),
end.GetContainingLine().End.TranslateTo(view.TextBuffer.CurrentSnapshot, PointTrackingMode.Positive)
),
false
);
}
private static void DeleteFirstCommentChar(ITextEdit edit, ITextSnapshotLine curLine) {
var text = curLine.GetText();
for (int j = 0; j < text.Length; j++) {
if (!Char.IsWhiteSpace(text[j])) {
if (text[j] == '#') {
edit.Delete(curLine.Start.Position + j, 1);
}
break;
}
}
}
public static SourceLocation ToSourceLocation(this SnapshotPoint point) {
return new SourceLocation(
point.Position,
point.GetContainingLine().LineNumber + 1,
point.Position - point.GetContainingLine().Start.Position + 1
);
}
public static SourceSpan ToSourceSpan(this SnapshotSpan span) {
return new SourceSpan(
ToSourceLocation(span.Start),
ToSourceLocation(span.End)
);
}
public static SnapshotPoint ToSnapshotPoint(this SourceLocation location, ITextSnapshot snapshot) {
ITextSnapshotLine line;
if (location.Line < 1) {
return new SnapshotPoint(snapshot, 0);
}
try {
line = snapshot.GetLineFromLineNumber(location.Line - 1);
} catch (ArgumentOutOfRangeException) {
Debug.Assert(location.Line == snapshot.LineCount + 1 && location.Column == 1,
$"Out of range should only occur at end of snapshot ({snapshot.LineCount + 1}, 1), not at {location}");
return new SnapshotPoint(snapshot, snapshot.Length);
}
if (location.Column > line.LengthIncludingLineBreak) {
return line.EndIncludingLineBreak;
}
return line.Start + (location.Column - 1);
}
public static SnapshotSpan ToSnapshotSpan(this SourceSpan span, ITextSnapshot snapshot) {
return new SnapshotSpan(
ToSnapshotPoint(span.Start, snapshot),
ToSnapshotPoint(span.End, snapshot)
);
}
}
}
| |
using System.Collections.Generic;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph;
using UnityEngine.Experimental.Rendering.HDPipeline;
using UnityEngine.Rendering;
namespace UnityEditor.Experimental.Rendering.HDPipeline
{
class HDLitSubShader : IHDLitSubShader
{
Pass m_PassGBuffer = new Pass()
{
Name = "GBuffer",
LightMode = "GBuffer",
TemplateName = "HDLitPass.template",
MaterialName = "Lit",
ShaderPassName = "SHADERPASS_GBUFFER",
ExtraDefines = new List<string>()
{
"#pragma multi_compile _ DEBUG_DISPLAY",
"#pragma multi_compile _ LIGHTMAP_ON",
"#pragma multi_compile _ DIRLIGHTMAP_COMBINED",
"#pragma multi_compile _ DYNAMICLIGHTMAP_ON",
"#pragma multi_compile _ SHADOWS_SHADOWMASK",
"#pragma multi_compile DECALS_OFF DECALS_3RT DECALS_4RT",
"#pragma multi_compile _ LIGHT_LAYERS",
},
Includes = new List<string>()
{
"#include \"Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassGBuffer.hlsl\"",
},
RequiredFields = new List<string>()
{
"FragInputs.worldToTangent",
"FragInputs.positionRWS",
"FragInputs.texCoord1",
"FragInputs.texCoord2"
},
PixelShaderSlots = new List<int>()
{
HDLitMasterNode.AlbedoSlotId,
HDLitMasterNode.NormalSlotId,
HDLitMasterNode.BentNormalSlotId,
HDLitMasterNode.TangentSlotId,
HDLitMasterNode.SubsurfaceMaskSlotId,
HDLitMasterNode.ThicknessSlotId,
HDLitMasterNode.DiffusionProfileHashSlotId,
HDLitMasterNode.IridescenceMaskSlotId,
HDLitMasterNode.IridescenceThicknessSlotId,
HDLitMasterNode.SpecularColorSlotId,
HDLitMasterNode.CoatMaskSlotId,
HDLitMasterNode.MetallicSlotId,
HDLitMasterNode.EmissionSlotId,
HDLitMasterNode.SmoothnessSlotId,
HDLitMasterNode.AmbientOcclusionSlotId,
HDLitMasterNode.SpecularOcclusionSlotId,
HDLitMasterNode.AlphaSlotId,
HDLitMasterNode.AlphaThresholdSlotId,
HDLitMasterNode.AnisotropySlotId,
HDLitMasterNode.SpecularAAScreenSpaceVarianceSlotId,
HDLitMasterNode.SpecularAAThresholdSlotId,
HDLitMasterNode.RefractionIndexSlotId,
HDLitMasterNode.RefractionColorSlotId,
HDLitMasterNode.RefractionDistanceSlotId,
HDLitMasterNode.LightingSlotId,
HDLitMasterNode.BackLightingSlotId,
HDLitMasterNode.DepthOffsetSlotId,
},
VertexShaderSlots = new List<int>()
{
HDLitMasterNode.PositionSlotId
},
UseInPreview = true,
OnGeneratePassImpl = (IMasterNode node, ref Pass pass) =>
{
var masterNode = node as HDLitMasterNode;
HDSubShaderUtilities.GetStencilStateForGBuffer(masterNode.receiveSSR.isOn, masterNode.RequiresSplitLighting(), ref pass);
// When we have alpha test, we will force a depth prepass so we always bypass the clip instruction in the GBuffer
// Don't do it with debug display mode as it is possible there is no depth prepass in this case
// This remove is required otherwise the code generate several time the define...
pass.ExtraDefines.Remove("#ifndef DEBUG_DISPLAY\n#define SHADERPASS_GBUFFER_BYPASS_ALPHA_TEST\n#endif");
if (masterNode.surfaceType == SurfaceType.Opaque && masterNode.alphaTest.isOn)
{
pass.ExtraDefines.Add("#ifndef DEBUG_DISPLAY\n#define SHADERPASS_GBUFFER_BYPASS_ALPHA_TEST\n#endif");
pass.ZTestOverride = "ZTest Equal";
}
else
{
pass.ZTestOverride = null;
}
}
};
Pass m_PassMETA = new Pass()
{
Name = "META",
LightMode = "META",
TemplateName = "HDLitPass.template",
MaterialName = "Lit",
ShaderPassName = "SHADERPASS_LIGHT_TRANSPORT",
CullOverride = "Cull Off",
Includes = new List<string>()
{
"#include \"Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassLightTransport.hlsl\"",
},
RequiredFields = new List<string>()
{
"AttributesMesh.normalOS",
"AttributesMesh.tangentOS", // Always present as we require it also in case of Variants lighting
"AttributesMesh.uv0",
"AttributesMesh.uv1",
"AttributesMesh.color",
"AttributesMesh.uv2", // SHADERPASS_LIGHT_TRANSPORT always uses uv2
},
PixelShaderSlots = new List<int>()
{
HDLitMasterNode.AlbedoSlotId,
HDLitMasterNode.NormalSlotId,
HDLitMasterNode.BentNormalSlotId,
HDLitMasterNode.TangentSlotId,
HDLitMasterNode.SubsurfaceMaskSlotId,
HDLitMasterNode.ThicknessSlotId,
HDLitMasterNode.DiffusionProfileHashSlotId,
HDLitMasterNode.IridescenceMaskSlotId,
HDLitMasterNode.IridescenceThicknessSlotId,
HDLitMasterNode.SpecularColorSlotId,
HDLitMasterNode.CoatMaskSlotId,
HDLitMasterNode.MetallicSlotId,
HDLitMasterNode.EmissionSlotId,
HDLitMasterNode.SmoothnessSlotId,
HDLitMasterNode.AmbientOcclusionSlotId,
HDLitMasterNode.SpecularOcclusionSlotId,
HDLitMasterNode.AlphaSlotId,
HDLitMasterNode.AlphaThresholdSlotId,
HDLitMasterNode.AnisotropySlotId,
HDLitMasterNode.SpecularAAScreenSpaceVarianceSlotId,
HDLitMasterNode.SpecularAAThresholdSlotId,
HDLitMasterNode.RefractionIndexSlotId,
HDLitMasterNode.RefractionColorSlotId,
HDLitMasterNode.RefractionDistanceSlotId,
},
VertexShaderSlots = new List<int>()
{
//HDLitMasterNode.PositionSlotId
},
UseInPreview = false
};
Pass m_PassShadowCaster = new Pass()
{
Name = "ShadowCaster",
LightMode = "ShadowCaster",
TemplateName = "HDLitPass.template",
MaterialName = "Lit",
ShaderPassName = "SHADERPASS_SHADOWS",
BlendOverride = "Blend One Zero",
ZWriteOverride = "ZWrite On",
ColorMaskOverride = "ColorMask 0",
Includes = new List<string>()
{
"#include \"Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDepthOnly.hlsl\"",
},
PixelShaderSlots = new List<int>()
{
HDLitMasterNode.AlphaSlotId,
HDLitMasterNode.AlphaThresholdSlotId,
HDLitMasterNode.AlphaThresholdShadowSlotId,
HDLitMasterNode.DepthOffsetSlotId,
},
VertexShaderSlots = new List<int>()
{
HDLitMasterNode.PositionSlotId
},
UseInPreview = false
};
Pass m_SceneSelectionPass = new Pass()
{
Name = "SceneSelectionPass",
LightMode = "SceneSelectionPass",
TemplateName = "HDLitPass.template",
MaterialName = "Lit",
ShaderPassName = "SHADERPASS_DEPTH_ONLY",
ColorMaskOverride = "ColorMask 0",
ExtraDefines = new List<string>()
{
"#define SCENESELECTIONPASS",
},
Includes = new List<string>()
{
"#include \"Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDepthOnly.hlsl\"",
},
PixelShaderSlots = new List<int>()
{
HDLitMasterNode.AlphaSlotId,
HDLitMasterNode.AlphaThresholdSlotId,
HDLitMasterNode.DepthOffsetSlotId,
},
VertexShaderSlots = new List<int>()
{
HDLitMasterNode.PositionSlotId
},
UseInPreview = false
};
Pass m_PassDepthOnly = new Pass()
{
Name = "DepthOnly",
LightMode = "DepthOnly",
TemplateName = "HDLitPass.template",
MaterialName = "Lit",
ShaderPassName = "SHADERPASS_DEPTH_ONLY",
ZWriteOverride = "ZWrite On",
ExtraDefines = HDSubShaderUtilities.s_ExtraDefinesDepthOrMotion,
Includes = new List<string>()
{
"#include \"Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDepthOnly.hlsl\"",
},
PixelShaderSlots = new List<int>()
{
HDLitMasterNode.NormalSlotId,
HDLitMasterNode.SmoothnessSlotId,
HDLitMasterNode.AlphaSlotId,
HDLitMasterNode.AlphaThresholdSlotId,
HDLitMasterNode.DepthOffsetSlotId,
},
RequiredFields = new List<string>()
{
"AttributesMesh.normalOS",
"AttributesMesh.tangentOS", // Always present as we require it also in case of Variants lighting
"AttributesMesh.uv0",
"AttributesMesh.uv1",
"AttributesMesh.color",
"AttributesMesh.uv2", // SHADERPASS_LIGHT_TRANSPORT always uses uv2
"AttributesMesh.uv3", // DEBUG_DISPLAY
"FragInputs.worldToTangent",
"FragInputs.positionRWS",
"FragInputs.texCoord0",
"FragInputs.texCoord1",
"FragInputs.texCoord2",
"FragInputs.texCoord3",
"FragInputs.color",
},
VertexShaderSlots = new List<int>()
{
HDLitMasterNode.PositionSlotId
},
UseInPreview = true,
OnGeneratePassImpl = (IMasterNode node, ref Pass pass) =>
{
var masterNode = node as HDLitMasterNode;
HDSubShaderUtilities.GetStencilStateForDepthOrMV(false, masterNode.receiveSSR.isOn, false, ref pass);
}
};
Pass m_PassMotionVectors = new Pass()
{
Name = "MotionVectors",
LightMode = "MotionVectors",
TemplateName = "HDLitPass.template",
MaterialName = "Lit",
ShaderPassName = "SHADERPASS_MOTION_VECTORS",
ExtraDefines = HDSubShaderUtilities.s_ExtraDefinesDepthOrMotion,
Includes = new List<string>()
{
"#include \"Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassMotionVectors.hlsl\"",
},
RequiredFields = new List<string>()
{
"AttributesMesh.normalOS",
"AttributesMesh.tangentOS", // Always present as we require it also in case of Variants lighting
"AttributesMesh.uv0",
"AttributesMesh.uv1",
"AttributesMesh.color",
"AttributesMesh.uv2", // SHADERPASS_LIGHT_TRANSPORT always uses uv2
"AttributesMesh.uv3", // DEBUG_DISPLAY
"FragInputs.worldToTangent",
"FragInputs.positionRWS",
"FragInputs.texCoord0",
"FragInputs.texCoord1",
"FragInputs.texCoord2",
"FragInputs.texCoord3",
"FragInputs.color",
},
PixelShaderSlots = new List<int>()
{
HDLitMasterNode.NormalSlotId,
HDLitMasterNode.SmoothnessSlotId,
HDLitMasterNode.AlphaSlotId,
HDLitMasterNode.AlphaThresholdSlotId,
HDLitMasterNode.DepthOffsetSlotId,
},
VertexShaderSlots = new List<int>()
{
HDLitMasterNode.PositionSlotId
},
UseInPreview = false,
OnGeneratePassImpl = (IMasterNode node, ref Pass pass) =>
{
var masterNode = node as HDLitMasterNode;
HDSubShaderUtilities.GetStencilStateForDepthOrMV(false, masterNode.receiveSSR.isOn, true, ref pass);
}
};
Pass m_PassDistortion = new Pass()
{
Name = "DistortionVectors",
LightMode = "DistortionVectors",
TemplateName = "HDLitPass.template",
MaterialName = "Lit",
ShaderPassName = "SHADERPASS_DISTORTION",
ZWriteOverride = "ZWrite Off",
Includes = new List<string>()
{
"#include \"Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDistortion.hlsl\"",
},
StencilOverride = new List<string>()
{
"// Stencil setup",
"Stencil",
"{",
string.Format(" WriteMask {0}", (int)HDRenderPipeline.StencilBitMask.DistortionVectors),
string.Format(" Ref {0}", (int)HDRenderPipeline.StencilBitMask.DistortionVectors),
" Comp Always",
" Pass Replace",
"}"
},
PixelShaderSlots = new List<int>()
{
HDLitMasterNode.AlphaSlotId,
HDLitMasterNode.AlphaThresholdSlotId,
HDLitMasterNode.DistortionSlotId,
HDLitMasterNode.DistortionBlurSlotId,
},
VertexShaderSlots = new List<int>()
{
HDLitMasterNode.PositionSlotId
},
UseInPreview = true,
OnGeneratePassImpl = (IMasterNode node, ref Pass pass) =>
{
var masterNode = node as HDLitMasterNode;
if (masterNode.distortionDepthTest.isOn)
{
pass.ZTestOverride = "ZTest LEqual";
}
else
{
pass.ZTestOverride = "ZTest Always";
}
if (masterNode.distortionMode == DistortionMode.Add)
{
pass.BlendOverride = "Blend One One, One One";
pass.BlendOpOverride = "BlendOp Add, Add";
}
else if (masterNode.distortionMode == DistortionMode.Multiply)
{
pass.BlendOverride = "Blend DstColor Zero, DstAlpha Zero";
pass.BlendOpOverride = "BlendOp Add, Add";
}
else // (masterNode.distortionMode == DistortionMode.Replace)
{
pass.BlendOverride = "Blend One Zero, One Zero";
pass.BlendOpOverride = "BlendOp Add, Add";
}
}
};
Pass m_PassTransparentDepthPrepass = new Pass()
{
Name = "TransparentDepthPrepass",
LightMode = "TransparentDepthPrepass",
TemplateName = "HDLitPass.template",
MaterialName = "Lit",
ShaderPassName = "SHADERPASS_DEPTH_ONLY",
BlendOverride = "Blend One Zero",
ZWriteOverride = "ZWrite On",
ColorMaskOverride = "ColorMask 0",
ExtraDefines = new List<string>()
{
"#define CUTOFF_TRANSPARENT_DEPTH_PREPASS",
},
Includes = new List<string>()
{
"#include \"Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDepthOnly.hlsl\"",
},
PixelShaderSlots = new List<int>()
{
HDLitMasterNode.AlphaSlotId,
HDLitMasterNode.AlphaThresholdDepthPrepassSlotId,
HDLitMasterNode.DepthOffsetSlotId,
},
VertexShaderSlots = new List<int>()
{
HDLitMasterNode.PositionSlotId
},
UseInPreview = true
};
Pass m_PassTransparentBackface = new Pass()
{
Name = "TransparentBackface",
LightMode = "TransparentBackface",
TemplateName = "HDLitPass.template",
MaterialName = "Lit",
ShaderPassName = "SHADERPASS_FORWARD",
CullOverride = "Cull Front",
ExtraDefines = HDSubShaderUtilities.s_ExtraDefinesForwardTransparent,
ColorMaskOverride = "ColorMask [_ColorMaskTransparentVel] 1",
Includes = new List<string>()
{
"#include \"Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassForward.hlsl\"",
},
RequiredFields = new List<string>()
{
"FragInputs.worldToTangent",
"FragInputs.positionRWS",
"FragInputs.texCoord1",
"FragInputs.texCoord2"
},
PixelShaderSlots = new List<int>()
{
HDLitMasterNode.AlbedoSlotId,
HDLitMasterNode.NormalSlotId,
HDLitMasterNode.BentNormalSlotId,
HDLitMasterNode.TangentSlotId,
HDLitMasterNode.SubsurfaceMaskSlotId,
HDLitMasterNode.ThicknessSlotId,
HDLitMasterNode.DiffusionProfileHashSlotId,
HDLitMasterNode.IridescenceMaskSlotId,
HDLitMasterNode.IridescenceThicknessSlotId,
HDLitMasterNode.SpecularColorSlotId,
HDLitMasterNode.CoatMaskSlotId,
HDLitMasterNode.MetallicSlotId,
HDLitMasterNode.EmissionSlotId,
HDLitMasterNode.SmoothnessSlotId,
HDLitMasterNode.AmbientOcclusionSlotId,
HDLitMasterNode.SpecularOcclusionSlotId,
HDLitMasterNode.AlphaSlotId,
HDLitMasterNode.AlphaThresholdSlotId,
HDLitMasterNode.AnisotropySlotId,
HDLitMasterNode.SpecularAAScreenSpaceVarianceSlotId,
HDLitMasterNode.SpecularAAThresholdSlotId,
HDLitMasterNode.RefractionIndexSlotId,
HDLitMasterNode.RefractionColorSlotId,
HDLitMasterNode.RefractionDistanceSlotId,
HDLitMasterNode.DepthOffsetSlotId,
},
VertexShaderSlots = new List<int>()
{
HDLitMasterNode.PositionSlotId
},
UseInPreview = true
};
Pass m_PassForward = new Pass()
{
Name = "Forward",
LightMode = "Forward",
TemplateName = "HDLitPass.template",
MaterialName = "Lit",
ShaderPassName = "SHADERPASS_FORWARD",
// ExtraDefines are set when the pass is generated
Includes = new List<string>()
{
"#include \"Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassForward.hlsl\"",
},
RequiredFields = new List<string>()
{
"FragInputs.worldToTangent",
"FragInputs.positionRWS",
"FragInputs.texCoord1",
"FragInputs.texCoord2"
},
PixelShaderSlots = new List<int>()
{
HDLitMasterNode.AlbedoSlotId,
HDLitMasterNode.NormalSlotId,
HDLitMasterNode.BentNormalSlotId,
HDLitMasterNode.TangentSlotId,
HDLitMasterNode.SubsurfaceMaskSlotId,
HDLitMasterNode.ThicknessSlotId,
HDLitMasterNode.DiffusionProfileHashSlotId,
HDLitMasterNode.IridescenceMaskSlotId,
HDLitMasterNode.IridescenceThicknessSlotId,
HDLitMasterNode.SpecularColorSlotId,
HDLitMasterNode.CoatMaskSlotId,
HDLitMasterNode.MetallicSlotId,
HDLitMasterNode.EmissionSlotId,
HDLitMasterNode.SmoothnessSlotId,
HDLitMasterNode.AmbientOcclusionSlotId,
HDLitMasterNode.SpecularOcclusionSlotId,
HDLitMasterNode.AlphaSlotId,
HDLitMasterNode.AlphaThresholdSlotId,
HDLitMasterNode.AnisotropySlotId,
HDLitMasterNode.SpecularAAScreenSpaceVarianceSlotId,
HDLitMasterNode.SpecularAAThresholdSlotId,
HDLitMasterNode.RefractionIndexSlotId,
HDLitMasterNode.RefractionColorSlotId,
HDLitMasterNode.RefractionDistanceSlotId,
HDLitMasterNode.LightingSlotId,
HDLitMasterNode.BackLightingSlotId,
HDLitMasterNode.DepthOffsetSlotId,
},
VertexShaderSlots = new List<int>()
{
HDLitMasterNode.PositionSlotId
},
UseInPreview = true,
OnGeneratePassImpl = (IMasterNode node, ref Pass pass) =>
{
var masterNode = node as HDLitMasterNode;
HDSubShaderUtilities.GetStencilStateForForward(masterNode.RequiresSplitLighting(), ref pass);
pass.ExtraDefines.Remove("#ifndef DEBUG_DISPLAY\n#define SHADERPASS_FORWARD_BYPASS_ALPHA_TEST\n#endif");
pass.ColorMaskOverride = "ColorMask [_ColorMaskTransparentVel] 1";
if (masterNode.surfaceType == SurfaceType.Opaque && masterNode.alphaTest.isOn)
{
// In case of opaque we don't want to perform the alpha test, it is done in depth prepass and we use depth equal for ztest (setup from UI)
// Don't do it with debug display mode as it is possible there is no depth prepass in this case
pass.ExtraDefines.Add("#ifndef DEBUG_DISPLAY\n#define SHADERPASS_FORWARD_BYPASS_ALPHA_TEST\n#endif");
pass.ZTestOverride = "ZTest Equal";
}
else
{
pass.ZTestOverride = null;
}
if (masterNode.surfaceType == SurfaceType.Transparent && masterNode.backThenFrontRendering.isOn)
{
pass.CullOverride = "Cull Back";
}
else
{
pass.CullOverride = null;
}
}
};
Pass m_PassTransparentDepthPostpass = new Pass()
{
Name = "TransparentDepthPostpass",
LightMode = "TransparentDepthPostpass",
TemplateName = "HDLitPass.template",
MaterialName = "Lit",
ShaderPassName = "SHADERPASS_DEPTH_ONLY",
BlendOverride = "Blend One Zero",
ZWriteOverride = "ZWrite On",
ColorMaskOverride = "ColorMask 0",
ExtraDefines = new List<string>()
{
"#define CUTOFF_TRANSPARENT_DEPTH_POSTPASS",
},
Includes = new List<string>()
{
"#include \"Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDepthOnly.hlsl\"",
},
PixelShaderSlots = new List<int>()
{
HDLitMasterNode.AlphaSlotId,
HDLitMasterNode.AlphaThresholdDepthPostpassSlotId,
HDLitMasterNode.DepthOffsetSlotId,
},
VertexShaderSlots = new List<int>()
{
HDLitMasterNode.PositionSlotId
},
UseInPreview = true
};
Pass m_PassRaytracingIndirect = new Pass()
{
Name = "IndirectDXR",
LightMode = "IndirectDXR",
TemplateName = "HDLitRaytracingPass.template",
MaterialName = "Lit",
ShaderPassName = "SHADERPASS_RAYTRACING_INDIRECT",
ExtraDefines = new List<string>()
{
"#pragma multi_compile _ LIGHTMAP_ON",
"#pragma multi_compile _ DIRLIGHTMAP_COMBINED",
"#pragma multi_compile _ DYNAMICLIGHTMAP_ON",
"#pragma multi_compile _ DIFFUSE_LIGHTING_ONLY",
"#define SHADOW_LOW",
"#define SKIP_RASTERIZED_SHADOWS",
},
Includes = new List<string>()
{
"#include \"Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassRaytracingIndirect.hlsl\"",
},
PixelShaderSlots = new List<int>()
{
HDLitMasterNode.AlbedoSlotId,
HDLitMasterNode.NormalSlotId,
HDLitMasterNode.BentNormalSlotId,
HDLitMasterNode.TangentSlotId,
HDLitMasterNode.SubsurfaceMaskSlotId,
HDLitMasterNode.ThicknessSlotId,
HDLitMasterNode.DiffusionProfileHashSlotId,
HDLitMasterNode.IridescenceMaskSlotId,
HDLitMasterNode.IridescenceThicknessSlotId,
HDLitMasterNode.SpecularColorSlotId,
HDLitMasterNode.CoatMaskSlotId,
HDLitMasterNode.MetallicSlotId,
HDLitMasterNode.EmissionSlotId,
HDLitMasterNode.SmoothnessSlotId,
HDLitMasterNode.AmbientOcclusionSlotId,
HDLitMasterNode.SpecularOcclusionSlotId,
HDLitMasterNode.AlphaSlotId,
HDLitMasterNode.AlphaThresholdSlotId,
HDLitMasterNode.AnisotropySlotId,
HDLitMasterNode.SpecularAAScreenSpaceVarianceSlotId,
HDLitMasterNode.SpecularAAThresholdSlotId,
HDLitMasterNode.RefractionIndexSlotId,
HDLitMasterNode.RefractionColorSlotId,
HDLitMasterNode.RefractionDistanceSlotId,
},
VertexShaderSlots = new List<int>()
{
HDLitMasterNode.PositionSlotId
},
UseInPreview = false
};
Pass m_PassRaytracingVisibility = new Pass()
{
Name = "VisibilityDXR",
LightMode = "VisibilityDXR",
TemplateName = "HDLitRaytracingPass.template",
MaterialName = "Lit",
ShaderPassName = "SHADERPASS_RAYTRACING_VISIBILITY",
Includes = new List<string>()
{
"#include \"Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassRaytracingVisibility.hlsl\"",
},
PixelShaderSlots = new List<int>()
{
HDLitMasterNode.AlbedoSlotId,
HDLitMasterNode.NormalSlotId,
HDLitMasterNode.BentNormalSlotId,
HDLitMasterNode.TangentSlotId,
HDLitMasterNode.SubsurfaceMaskSlotId,
HDLitMasterNode.ThicknessSlotId,
HDLitMasterNode.DiffusionProfileHashSlotId,
HDLitMasterNode.IridescenceMaskSlotId,
HDLitMasterNode.IridescenceThicknessSlotId,
HDLitMasterNode.SpecularColorSlotId,
HDLitMasterNode.CoatMaskSlotId,
HDLitMasterNode.MetallicSlotId,
HDLitMasterNode.EmissionSlotId,
HDLitMasterNode.SmoothnessSlotId,
HDLitMasterNode.AmbientOcclusionSlotId,
HDLitMasterNode.SpecularOcclusionSlotId,
HDLitMasterNode.AlphaSlotId,
HDLitMasterNode.AlphaThresholdSlotId,
HDLitMasterNode.AnisotropySlotId,
HDLitMasterNode.SpecularAAScreenSpaceVarianceSlotId,
HDLitMasterNode.SpecularAAThresholdSlotId,
HDLitMasterNode.RefractionIndexSlotId,
HDLitMasterNode.RefractionColorSlotId,
HDLitMasterNode.RefractionDistanceSlotId,
},
VertexShaderSlots = new List<int>()
{
HDLitMasterNode.PositionSlotId
},
UseInPreview = false
};
Pass m_PassRaytracingForward = new Pass()
{
Name = "ForwardDXR",
LightMode = "ForwardDXR",
TemplateName = "HDLitRaytracingPass.template",
MaterialName = "Lit",
ShaderPassName = "SHADERPASS_RAYTRACING_FORWARD",
ExtraDefines = new List<string>()
{
"#pragma multi_compile _ LIGHTMAP_ON",
"#pragma multi_compile _ DIRLIGHTMAP_COMBINED",
"#pragma multi_compile _ DYNAMICLIGHTMAP_ON",
"#define SHADOW_LOW",
"#define SKIP_RASTERIZED_SHADOWS",
},
Includes = new List<string>()
{
"#include \"Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassRaytracingForward.hlsl\"",
},
PixelShaderSlots = new List<int>()
{
HDLitMasterNode.AlbedoSlotId,
HDLitMasterNode.NormalSlotId,
HDLitMasterNode.BentNormalSlotId,
HDLitMasterNode.TangentSlotId,
HDLitMasterNode.SubsurfaceMaskSlotId,
HDLitMasterNode.ThicknessSlotId,
HDLitMasterNode.DiffusionProfileHashSlotId,
HDLitMasterNode.IridescenceMaskSlotId,
HDLitMasterNode.IridescenceThicknessSlotId,
HDLitMasterNode.SpecularColorSlotId,
HDLitMasterNode.CoatMaskSlotId,
HDLitMasterNode.MetallicSlotId,
HDLitMasterNode.EmissionSlotId,
HDLitMasterNode.SmoothnessSlotId,
HDLitMasterNode.AmbientOcclusionSlotId,
HDLitMasterNode.SpecularOcclusionSlotId,
HDLitMasterNode.AlphaSlotId,
HDLitMasterNode.AlphaThresholdSlotId,
HDLitMasterNode.AnisotropySlotId,
HDLitMasterNode.SpecularAAScreenSpaceVarianceSlotId,
HDLitMasterNode.SpecularAAThresholdSlotId,
HDLitMasterNode.RefractionIndexSlotId,
HDLitMasterNode.RefractionColorSlotId,
HDLitMasterNode.RefractionDistanceSlotId,
},
VertexShaderSlots = new List<int>()
{
HDLitMasterNode.PositionSlotId
},
UseInPreview = false
};
public int GetPreviewPassIndex() { return 0; }
private static List<string> GetInstancingOptionsFromMasterNode(AbstractMaterialNode iMasterNode)
{
List<string> instancingOption = new List<string>();
HDLitMasterNode masterNode = iMasterNode as HDLitMasterNode;
if (masterNode.dotsInstancing.isOn)
{
instancingOption.Add("#pragma instancing_options nolightprobe");
instancingOption.Add("#pragma instancing_options nolodfade");
}
else
{
instancingOption.Add("#pragma instancing_options renderinglayer");
}
return instancingOption;
}
private static HashSet<string> GetActiveFieldsFromMasterNode(AbstractMaterialNode iMasterNode, Pass pass)
{
HashSet<string> activeFields = new HashSet<string>();
HDLitMasterNode masterNode = iMasterNode as HDLitMasterNode;
if (masterNode == null)
{
return activeFields;
}
if (masterNode.doubleSidedMode != DoubleSidedMode.Disabled)
{
activeFields.Add("DoubleSided");
if (pass.ShaderPassName != "SHADERPASS_MOTION_VECTORS") // HACK to get around lack of a good interpolator dependency system
{ // we need to be able to build interpolators using multiple input structs
// also: should only require isFrontFace if Normals are required...
if (masterNode.doubleSidedMode == DoubleSidedMode.FlippedNormals)
{
activeFields.Add("DoubleSided.Flip");
}
else if (masterNode.doubleSidedMode == DoubleSidedMode.MirroredNormals)
{
activeFields.Add("DoubleSided.Mirror");
}
// Important: the following is used in SharedCode.template.hlsl for determining the normal flip mode
activeFields.Add("FragInputs.isFrontFace");
}
}
switch (masterNode.materialType)
{
case HDLitMasterNode.MaterialType.Anisotropy:
activeFields.Add("Material.Anisotropy");
break;
case HDLitMasterNode.MaterialType.Iridescence:
activeFields.Add("Material.Iridescence");
break;
case HDLitMasterNode.MaterialType.SpecularColor:
activeFields.Add("Material.SpecularColor");
break;
case HDLitMasterNode.MaterialType.Standard:
activeFields.Add("Material.Standard");
break;
case HDLitMasterNode.MaterialType.SubsurfaceScattering:
{
if (masterNode.surfaceType != SurfaceType.Transparent)
{
activeFields.Add("Material.SubsurfaceScattering");
}
if (masterNode.sssTransmission.isOn)
{
activeFields.Add("Material.Transmission");
}
}
break;
case HDLitMasterNode.MaterialType.Translucent:
{
activeFields.Add("Material.Translucent");
activeFields.Add("Material.Transmission");
}
break;
default:
UnityEngine.Debug.LogError("Unknown material type: " + masterNode.materialType);
break;
}
if (masterNode.alphaTest.isOn)
{
int count = 0;
// If alpha test shadow is enable, we use it, otherwise we use the regular test
if (pass.PixelShaderUsesSlot(HDLitMasterNode.AlphaThresholdShadowSlotId) && masterNode.alphaTestShadow.isOn)
{
activeFields.Add("AlphaTestShadow");
++count;
}
else if (pass.PixelShaderUsesSlot(HDLitMasterNode.AlphaThresholdSlotId))
{
activeFields.Add("AlphaTest");
++count;
}
if (pass.PixelShaderUsesSlot(HDLitMasterNode.AlphaThresholdDepthPrepassSlotId))
{
activeFields.Add("AlphaTestPrepass");
++count;
}
if (pass.PixelShaderUsesSlot(HDLitMasterNode.AlphaThresholdDepthPostpassSlotId))
{
activeFields.Add("AlphaTestPostpass");
++count;
}
UnityEngine.Debug.Assert(count == 1, "Alpha test value not set correctly");
}
if (masterNode.surfaceType != SurfaceType.Opaque)
{
activeFields.Add("SurfaceType.Transparent");
if (masterNode.alphaMode == AlphaMode.Alpha)
{
activeFields.Add("BlendMode.Alpha");
}
else if (masterNode.alphaMode == AlphaMode.Premultiply)
{
activeFields.Add("BlendMode.Premultiply");
}
else if (masterNode.alphaMode == AlphaMode.Additive)
{
activeFields.Add("BlendMode.Add");
}
if (masterNode.blendPreserveSpecular.isOn)
{
activeFields.Add("BlendMode.PreserveSpecular");
}
if (masterNode.transparencyFog.isOn)
{
activeFields.Add("AlphaFog");
}
if (masterNode.transparentWritesMotionVec.isOn)
{
activeFields.Add("TransparentWritesMotionVec");
}
}
if (!masterNode.receiveDecals.isOn)
{
activeFields.Add("DisableDecals");
}
if (!masterNode.receiveSSR.isOn)
{
activeFields.Add("DisableSSR");
}
if (masterNode.specularAA.isOn && pass.PixelShaderUsesSlot(HDLitMasterNode.SpecularAAThresholdSlotId) && pass.PixelShaderUsesSlot(HDLitMasterNode.SpecularAAScreenSpaceVarianceSlotId))
{
activeFields.Add("Specular.AA");
}
if (masterNode.energyConservingSpecular.isOn)
{
activeFields.Add("Specular.EnergyConserving");
}
if (masterNode.HasRefraction())
{
activeFields.Add("Refraction");
switch (masterNode.refractionModel)
{
case ScreenSpaceRefraction.RefractionModel.Box:
activeFields.Add("RefractionBox");
break;
case ScreenSpaceRefraction.RefractionModel.Sphere:
activeFields.Add("RefractionSphere");
break;
default:
UnityEngine.Debug.LogError("Unknown refraction model: " + masterNode.refractionModel);
break;
}
}
if (masterNode.IsSlotConnected(HDLitMasterNode.BentNormalSlotId) && pass.PixelShaderUsesSlot(HDLitMasterNode.BentNormalSlotId))
{
activeFields.Add("BentNormal");
}
if (masterNode.IsSlotConnected(HDLitMasterNode.TangentSlotId) && pass.PixelShaderUsesSlot(HDLitMasterNode.TangentSlotId))
{
activeFields.Add("Tangent");
}
switch (masterNode.specularOcclusionMode)
{
case SpecularOcclusionMode.Off:
break;
case SpecularOcclusionMode.FromAO:
activeFields.Add("SpecularOcclusionFromAO");
break;
case SpecularOcclusionMode.FromAOAndBentNormal:
activeFields.Add("SpecularOcclusionFromAOBentNormal");
break;
case SpecularOcclusionMode.Custom:
activeFields.Add("SpecularOcclusionCustom");
break;
default:
break;
}
if (pass.PixelShaderUsesSlot(HDLitMasterNode.AmbientOcclusionSlotId))
{
var occlusionSlot = masterNode.FindSlot<Vector1MaterialSlot>(HDLitMasterNode.AmbientOcclusionSlotId);
bool connected = masterNode.IsSlotConnected(HDLitMasterNode.AmbientOcclusionSlotId);
if (connected || occlusionSlot.value != occlusionSlot.defaultValue)
{
activeFields.Add("AmbientOcclusion");
}
}
if (pass.PixelShaderUsesSlot(HDLitMasterNode.CoatMaskSlotId))
{
var coatMaskSlot = masterNode.FindSlot<Vector1MaterialSlot>(HDLitMasterNode.CoatMaskSlotId);
bool connected = masterNode.IsSlotConnected(HDLitMasterNode.CoatMaskSlotId);
if (connected || coatMaskSlot.value > 0.0f)
{
activeFields.Add("CoatMask");
}
}
if (masterNode.IsSlotConnected(HDLitMasterNode.LightingSlotId) && pass.PixelShaderUsesSlot(HDLitMasterNode.LightingSlotId))
{
activeFields.Add("LightingGI");
}
if (masterNode.IsSlotConnected(HDLitMasterNode.BackLightingSlotId) && pass.PixelShaderUsesSlot(HDLitMasterNode.LightingSlotId))
{
activeFields.Add("BackLightingGI");
}
if (masterNode.depthOffset.isOn && pass.PixelShaderUsesSlot(HDLitMasterNode.DepthOffsetSlotId))
activeFields.Add("DepthOffset");
return activeFields;
}
private static bool GenerateShaderPassLit(HDLitMasterNode masterNode, Pass pass, GenerationMode mode, ShaderGenerator result, List<string> sourceAssetDependencyPaths)
{
if (mode == GenerationMode.ForReals || pass.UseInPreview)
{
SurfaceMaterialOptions materialOptions = HDSubShaderUtilities.BuildMaterialOptions(masterNode.surfaceType, masterNode.alphaMode, masterNode.doubleSidedMode != DoubleSidedMode.Disabled, masterNode.HasRefraction(), masterNode.renderingPass == HDRenderQueue.RenderQueueType.LowTransparent);
pass.OnGeneratePass(masterNode);
// apply master node options to active fields
HashSet<string> activeFields = GetActiveFieldsFromMasterNode(masterNode, pass);
pass.ExtraInstancingOptions = GetInstancingOptionsFromMasterNode(masterNode);
// use standard shader pass generation
bool vertexActive = masterNode.IsSlotConnected(HDLitMasterNode.PositionSlotId);
return HDSubShaderUtilities.GenerateShaderPass(masterNode, pass, mode, materialOptions, activeFields, result, sourceAssetDependencyPaths, vertexActive);
}
else
{
return false;
}
}
public string GetSubshader(IMasterNode iMasterNode, GenerationMode mode, List<string> sourceAssetDependencyPaths = null)
{
if (sourceAssetDependencyPaths != null)
{
// HDLitSubShader.cs
sourceAssetDependencyPaths.Add(AssetDatabase.GUIDToAssetPath("bac1a9627cfec924fa2ea9c65af8eeca"));
// HDSubShaderUtilities.cs
sourceAssetDependencyPaths.Add(AssetDatabase.GUIDToAssetPath("713ced4e6eef4a44799a4dd59041484b"));
}
var masterNode = iMasterNode as HDLitMasterNode;
var subShader = new ShaderGenerator();
subShader.AddShaderChunk("SubShader", false);
subShader.AddShaderChunk("{", false);
subShader.Indent();
{
//Handle data migration here as we need to have a renderingPass already set with accurate data at this point.
if (masterNode.renderingPass == HDRenderQueue.RenderQueueType.Unknown)
{
switch (masterNode.surfaceType)
{
case SurfaceType.Opaque:
masterNode.renderingPass = HDRenderQueue.RenderQueueType.Opaque;
break;
case SurfaceType.Transparent:
#pragma warning disable CS0618 // Type or member is obsolete
if (masterNode.m_DrawBeforeRefraction)
{
masterNode.m_DrawBeforeRefraction = false;
#pragma warning restore CS0618 // Type or member is obsolete
masterNode.renderingPass = HDRenderQueue.RenderQueueType.PreRefraction;
}
else
{
masterNode.renderingPass = HDRenderQueue.RenderQueueType.Transparent;
}
break;
default:
throw new System.ArgumentException("Unknown SurfaceType");
}
}
HDMaterialTags materialTags = HDSubShaderUtilities.BuildMaterialTags(masterNode.renderingPass, masterNode.sortPriority, masterNode.alphaTest.isOn);
// Add tags at the SubShader level
{
var tagsVisitor = new ShaderStringBuilder();
materialTags.GetTags(tagsVisitor, HDRenderPipeline.k_ShaderTagName);
subShader.AddShaderChunk(tagsVisitor.ToString(), false);
}
// generate the necessary shader passes
bool opaque = (masterNode.surfaceType == SurfaceType.Opaque);
bool transparent = !opaque;
bool distortionActive = transparent && masterNode.distortion.isOn;
bool transparentBackfaceActive = transparent && masterNode.backThenFrontRendering.isOn;
bool transparentDepthPrepassActive = transparent && masterNode.alphaTest.isOn && masterNode.alphaTestDepthPrepass.isOn;
bool transparentDepthPostpassActive = transparent && masterNode.alphaTest.isOn && masterNode.alphaTestDepthPostpass.isOn;
GenerateShaderPassLit(masterNode, m_PassMETA, mode, subShader, sourceAssetDependencyPaths);
GenerateShaderPassLit(masterNode, m_PassShadowCaster, mode, subShader, sourceAssetDependencyPaths);
GenerateShaderPassLit(masterNode, m_SceneSelectionPass, mode, subShader, sourceAssetDependencyPaths);
if (opaque)
{
GenerateShaderPassLit(masterNode, m_PassDepthOnly, mode, subShader, sourceAssetDependencyPaths);
GenerateShaderPassLit(masterNode, m_PassGBuffer, mode, subShader, sourceAssetDependencyPaths);
GenerateShaderPassLit(masterNode, m_PassMotionVectors, mode, subShader, sourceAssetDependencyPaths);
}
if (distortionActive)
{
GenerateShaderPassLit(masterNode, m_PassDistortion, mode, subShader, sourceAssetDependencyPaths);
}
if (transparentBackfaceActive)
{
GenerateShaderPassLit(masterNode, m_PassTransparentBackface, mode, subShader, sourceAssetDependencyPaths);
}
// Assign define here based on opaque or transparent to save some variant
m_PassForward.ExtraDefines = opaque ? HDSubShaderUtilities.s_ExtraDefinesForwardOpaque : HDSubShaderUtilities.s_ExtraDefinesForwardTransparent;
GenerateShaderPassLit(masterNode, m_PassForward, mode, subShader, sourceAssetDependencyPaths);
if (transparentDepthPrepassActive)
{
GenerateShaderPassLit(masterNode, m_PassTransparentDepthPrepass, mode, subShader, sourceAssetDependencyPaths);
}
if (transparentDepthPostpassActive)
{
GenerateShaderPassLit(masterNode, m_PassTransparentDepthPostpass, mode, subShader, sourceAssetDependencyPaths);
}
}
subShader.Deindent();
subShader.AddShaderChunk("}", false);
#if ENABLE_RAYTRACING
if(mode == GenerationMode.ForReals)
{
subShader.AddShaderChunk("SubShader", false);
subShader.AddShaderChunk("{", false);
subShader.Indent();
{
GenerateShaderPassLit(masterNode, m_PassRaytracingIndirect, mode, subShader, sourceAssetDependencyPaths);
GenerateShaderPassLit(masterNode, m_PassRaytracingVisibility, mode, subShader, sourceAssetDependencyPaths);
GenerateShaderPassLit(masterNode, m_PassRaytracingForward, mode, subShader, sourceAssetDependencyPaths);
}
subShader.Deindent();
subShader.AddShaderChunk("}", false);
}
#endif
subShader.AddShaderChunk(@"CustomEditor ""UnityEditor.Experimental.Rendering.HDPipeline.HDLitGUI""");
return subShader.GetShaderString(0);
}
public bool IsPipelineCompatible(RenderPipelineAsset renderPipelineAsset)
{
return renderPipelineAsset is HDRenderPipelineAsset;
}
}
}
| |
using System;
using System.Runtime.InteropServices;
namespace R3E
{
class Constant
{
public const string SharedMemoryName = "$R3E";
enum VersionMajor
{
// Major version number to test against
R3E_VERSION_MAJOR = 2
};
enum VersionMinor
{
// Minor version number to test against
R3E_VERSION_MINOR = 11
};
enum Session
{
Unavailable = -1,
Practice = 0,
Qualify = 1,
Race = 2,
Warmup = 3,
};
enum SessionPhase
{
Unavailable = -1,
// Currently in garage
Garage = 1,
// Gridwalk or track walkthrough
Gridwalk = 2,
// Formation lap, rolling start etc.
Formation = 3,
// Countdown to race is ongoing
Countdown = 4,
// Race is ongoing
Green = 5,
// End of session
Checkered = 6,
};
enum Control
{
Unavailable = -1,
// Controlled by the actual player
Player = 0,
// Controlled by AI
AI = 1,
// Controlled by a network entity of some sort
Remote = 2,
// Controlled by a replay or ghost
Replay = 3,
};
enum PitWindow
{
Unavailable = -1,
// Pit stops are not enabled for this session
Disabled = 0,
// Pit stops are enabled, but you're not allowed to perform one right now
Closed = 1,
// Allowed to perform a pit stop now
Open = 2,
// Currently performing the pit stop changes (changing driver, etc.)
Stopped = 3,
// After the current mandatory pitstop have been completed
Completed = 4,
};
enum PitStopStatus
{
// No mandatory pitstops
Unavailable = -1,
// Mandatory pitstop for two tyres not served yet
UnservedTwoTyres = 0,
// Mandatory pitstop for four tyres not served yet
UnservedFourTyres = 1,
// Mandatory pitstop served
Served = 2,
};
enum FinishStatus
{
// N/A
Unavailable = -1,
// Still on track, not finished
None = 0,
// Finished session normally
Finished = 1,
// Did not finish
DNF = 2,
// Did not qualify
DNQ = 3,
// Did not start
DNS = 4,
// Disqualified
DQ = 5,
};
enum SessionLengthFormat
{
// N/A
Unavailable = -1,
TimeBased = 0,
LapBased = 1,
// Time and lap based session means there will be an extra lap after the time has run out
TimeAndLapBased = 2
};
enum PitMenuSelection
{
// Pit menu unavailable
Unavailable = -1,
// Pit menu preset
Preset = 0,
// Pit menu actions
Penalty = 1,
Driverchange = 2,
Fuel = 3,
Fronttires = 4,
Reartires = 5,
Frontwing = 6,
Rearwing = 7,
Suspension = 8,
// Pit menu buttons
ButtonTop = 9,
ButtonBottom = 10,
// Pit menu nothing selected
Max = 11
};
enum TireType
{
Unavailable = -1,
Option = 0,
Prime = 1,
};
enum TireSubtype
{
Unavailable = -1,
Primary = 0,
Alternate = 1,
Soft = 2,
Medium = 3,
Hard = 4
};
enum EngineType
{
COMBUSTION = 0,
ELECTRIC = 1,
HYBRID = 2,
};
}
namespace Data
{
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct RaceDuration<T>
{
public T Race1;
public T Race2;
public T Race3;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct Vector3<T>
{
public T X;
public T Y;
public T Z;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct Orientation<T>
{
public T Pitch;
public T Yaw;
public T Roll;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct SectorStarts<T>
{
public T Sector1;
public T Sector2;
public T Sector3;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct PlayerData
{
// Virtual physics time
// Unit: Ticks (1 tick = 1/400th of a second)
public Int32 GameSimulationTicks;
// Virtual physics time
// Unit: Seconds
public Double GameSimulationTime;
// Car world-space position
public Vector3<Double> Position;
// Car world-space velocity
// Unit: Meter per second (m/s)
public Vector3<Double> Velocity;
// Car local-space velocity
// Unit: Meter per second (m/s)
public Vector3<Double> LocalVelocity;
// Car world-space acceleration
// Unit: Meter per second squared (m/s^2)
public Vector3<Double> Acceleration;
// Car local-space acceleration
// Unit: Meter per second squared (m/s^2)
public Vector3<Double> LocalAcceleration;
// Car body orientation
// Unit: Euler angles
public Vector3<Double> Orientation;
// Car body rotation
public Vector3<Double> Rotation;
// Car body angular acceleration (torque divided by inertia)
public Vector3<Double> AngularAcceleration;
// Car world-space angular velocity
// Unit: Radians per second
public Vector3<Double> AngularVelocity;
// Car local-space angular velocity
// Unit: Radians per second
public Vector3<Double> LocalAngularVelocity;
// Driver g-force local to car
public Vector3<Double> LocalGforce;
// Total steering force coming through steering bars
public Double SteeringForce;
public Double SteeringForcePercentage;
// Current engine torque
public Double EngineTorque;
// Current downforce
// Unit: Newtons (N)
public Double CurrentDownforce;
// Currently unused
public Double Voltage;
public Double ErsLevel;
public Double PowerMguH;
public Double PowerMguK;
public Double TorqueMguK;
// Car setup (radians, meters, meters per second)
public TireData<Double> SuspensionDeflection;
public TireData<Double> SuspensionVelocity;
public TireData<Double> Camber;
public TireData<Double> RideHeight;
public Double FrontWingHeight;
public Double FrontRollAngle;
public Double RearRollAngle;
public Double ThirdSpringSuspensionDeflectionFront;
public Double ThirdSpringSuspensionVelocityFront;
public Double ThirdSpringSuspensionDeflectionRear;
public Double ThirdSpringSuspensionVelocityRear;
// Reserved data
public Double Unused1;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct Flags
{
// Whether yellow flag is currently active
// -1 = no data
// 0 = not active
// 1 = active
public Int32 Yellow;
// Whether yellow flag was caused by current slot
// -1 = no data
// 0 = didn't cause it
// 1 = caused it
public Int32 YellowCausedIt;
// Whether overtake of car in front by current slot is allowed under yellow flag
// -1 = no data
// 0 = not allowed
// 1 = allowed
public Int32 YellowOvertake;
// Whether you have gained positions illegaly under yellow flag to give back
// -1 = no data
// 0 = no positions gained
// n = number of positions gained
public Int32 YellowPositionsGained;
// Yellow flag for each sector; -1 = no data, 0 = not active, 1 = active
public Sectors<Int32> SectorYellow;
// Distance into track for closest yellow, -1.0 if no yellow flag exists
// Unit: Meters (m)
public Single ClosestYellowDistanceIntoTrack;
// Whether blue flag is currently active
// -1 = no data
// 0 = not active
// 1 = active
public Int32 Blue;
// Whether black flag is currently active
// -1 = no data
// 0 = not active
// 1 = active
public Int32 Black;
// Whether green flag is currently active
// -1 = no data
// 0 = not active
// 1 = active
public Int32 Green;
// Whether checkered flag is currently active
// -1 = no data
// 0 = not active
// 1 = active
public Int32 Checkered;
// Whether white flag is currently active
// -1 = no data
// 0 = not active
// 1 = active
public Int32 White;
// Whether black and white flag is currently active and reason
// -1 = no data
// 0 = not active
// 1 = blue flag 1st warnings
// 2 = blue flag 2nd warnings
// 3 = wrong way
// 4 = cutting track
public Int32 BlackAndWhite;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct CarDamage
{
// Range: 0.0 - 1.0
// Note: -1.0 = N/A
public Single Engine;
// Range: 0.0 - 1.0
// Note: -1.0 = N/A
public Single Transmission;
// Range: 0.0 - 1.0
// Note: A bit arbitrary at the moment. 0.0 doesn't necessarily mean completely destroyed.
// Note: -1.0 = N/A
public Single Aerodynamics;
// Range: 0.0 - 1.0
// Note: -1.0 = N/A
public Single Suspension;
// Reserved data
public Single Unused1;
public Single Unused2;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct TireData<T>
{
public T FrontLeft;
public T FrontRight;
public T RearLeft;
public T RearRight;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct PitMenuState
{
// Pit menu preset
public Int32 Preset;
// Pit menu actions
public Int32 Penalty;
public Int32 Driverchange;
public Int32 Fuel;
public Int32 FrontTires;
public Int32 RearTires;
public Int32 FrontWing;
public Int32 RearWing;
public Int32 Suspension;
// Pit menu buttons
public Int32 ButtonTop;
public Int32 ButtonBottom;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct CutTrackPenalties
{
public Int32 DriveThrough;
public Int32 StopAndGo;
public Int32 PitStop;
public Int32 TimeDeduction;
public Int32 SlowDown;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct DRS
{
// If DRS is equipped and allowed
// 0 = No, 1 = Yes, -1 = N/A
public Int32 Equipped;
// Got DRS activation left
// 0 = No, 1 = Yes, -1 = N/A
public Int32 Available;
// Number of DRS activations left this lap
// Note: In sessions with 'endless' amount of drs activations per lap this value starts at int32::max
// -1 = N/A
public Int32 NumActivationsLeft;
// DRS engaged
// 0 = No, 1 = Yes, -1 = N/A
public Int32 Engaged;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct PushToPass
{
public Int32 Available;
public Int32 Engaged;
public Int32 AmountLeft;
public Single EngagedTimeLeft;
public Single WaitTimeLeft;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct TireTempInformation
{
public TireTemperature<Single> CurrentTemp;
public Single OptimalTemp;
public Single ColdTemp;
public Single HotTemp;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct BrakeTemp
{
public Single CurrentTemp;
public Single OptimalTemp;
public Single ColdTemp;
public Single HotTemp;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct TireTemperature<T>
{
public T Left;
public T Center;
public T Right;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct AidSettings
{
// ABS; -1 = N/A, 0 = off, 1 = on, 5 = currently active
public Int32 Abs;
// TC; -1 = N/A, 0 = off, 1 = on, 5 = currently active
public Int32 Tc;
// ESP; -1 = N/A, 0 = off, 1 = on low, 2 = on medium, 3 = on high, 5 = currently active
public Int32 Esp;
// Countersteer; -1 = N/A, 0 = off, 1 = on, 5 = currently active
public Int32 Countersteer;
// Cornering; -1 = N/A, 0 = off, 1 = on, 5 = currently active
public Int32 Cornering;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct Sectors<T>
{
public T Sector1;
public T Sector2;
public T Sector3;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct DriverInfo
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]
public byte[] Name; // UTF-8
public Int32 CarNumber;
public Int32 ClassId;
public Int32 ModelId;
public Int32 TeamId;
public Int32 LiveryId;
public Int32 ManufacturerId;
public Int32 UserId;
public Int32 SlotId;
public Int32 ClassPerformanceIndex;
// Note: See the EngineType enum
public Int32 EngineType;
public Int32 Unused1;
public Int32 Unused2;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct DriverData
{
public DriverInfo DriverInfo;
// Note: See the R3E.Constant.FinishStatus enum
public Int32 FinishStatus;
public Int32 Place;
// Based on performance index
public Int32 PlaceClass;
public Single LapDistance;
public Vector3<Single> Position;
public Int32 TrackSector;
public Int32 CompletedLaps;
public Int32 CurrentLapValid;
public Single LapTimeCurrentSelf;
public Sectors<Single> SectorTimeCurrentSelf;
public Sectors<Single> SectorTimePreviousSelf;
public Sectors<Single> SectorTimeBestSelf;
public Single TimeDeltaFront;
public Single TimeDeltaBehind;
// Note: See the R3E.Constant.PitStopStatus enum
public Int32 PitStopStatus;
public Int32 InPitlane;
public Int32 NumPitstops;
public CutTrackPenalties Penalties;
public Single CarSpeed;
// Note: See the R3E.Constant.TireType enum
public Int32 TireTypeFront;
public Int32 TireTypeRear;
// Note: See the R3E.Constant.TireSubtype enum
public Int32 TireSubtypeFront;
public Int32 TireSubtypeRear;
public Single BasePenaltyWeight;
public Single AidPenaltyWeight;
// -1 unavailable, 0 = not engaged, 1 = engaged
public Int32 DrsState;
public Int32 PtpState;
// -1 unavailable, DriveThrough = 0, StopAndGo = 1, Pitstop = 2, Time = 3, Slowdown = 4, Disqualify = 5,
public Int32 PenaltyType;
// Based on the PenaltyType you can assume the reason is:
// DriveThroughPenaltyInvalid = 0,
// DriveThroughPenaltyCutTrack = 1,
// DriveThroughPenaltyPitSpeeding = 2,
// DriveThroughPenaltyFalseStart = 3,
// DriveThroughPenaltyIgnoredBlue = 4,
// DriveThroughPenaltyDrivingTooSlow = 5,
// DriveThroughPenaltyIllegallyPassedBeforeGreen = 6,
// DriveThroughPenaltyIllegallyPassedBeforeFinish = 7,
// DriveThroughPenaltyIllegallyPassedBeforePitEntrance = 8,
// DriveThroughPenaltyIgnoredSlowDown = 9,
// DriveThroughPenaltyMax = 10
// StopAndGoPenaltyInvalid = 0,
// StopAndGoPenaltyCutTrack1st = 1,
// StopAndGoPenaltyCutTrackMult = 2,
// StopAndGoPenaltyYellowFlagOvertake = 3,
// StopAndGoPenaltyMax = 4
// PitstopPenaltyInvalid = 0,
// PitstopPenaltyIgnoredPitstopWindow = 1,
// PitstopPenaltyMax = 2
// ServableTimePenaltyInvalid = 0,
// ServableTimePenaltyServedMandatoryPitstopLate = 1,
// ServableTimePenaltyIgnoredMinimumPitstopDuration = 2,
// ServableTimePenaltyMax = 3
// SlowDownPenaltyInvalid = 0,
// SlowDownPenaltyCutTrack1st = 1,
// SlowDownPenaltyCutTrackMult = 2,
// SlowDownPenaltyMax = 3
// DisqualifyPenaltyInvalid = -1,
// DisqualifyPenaltyFalseStart = 0,
// DisqualifyPenaltyPitlaneSpeeding = 1,
// DisqualifyPenaltyWrongWay = 2,
// DisqualifyPenaltyEnteringPitsUnderRed = 3,
// DisqualifyPenaltyExitingPitsUnderRed = 4,
// DisqualifyPenaltyFailedDriverChange = 5,
// DisqualifyPenaltyThreeDriveThroughsInLap = 6,
// DisqualifyPenaltyLappedFieldMultipleTimes = 7,
// DisqualifyPenaltyIgnoredDriveThroughPenalty = 8,
// DisqualifyPenaltyIgnoredStopAndGoPenalty = 9,
// DisqualifyPenaltyIgnoredPitStopPenalty = 10,
// DisqualifyPenaltyIgnoredTimePenalty = 11,
// DisqualifyPenaltyExcessiveCutting = 12,
// DisqualifyPenaltyIgnoredBlueFlag = 13,
// DisqualifyPenaltyMax = 14
public Int32 PenaltyReason;
// -1 unavailable, 0 = ignition off, 1 = ignition on but not running, 2 = ignition on and running
public Int32 EngineState;
// Reserved data
public Int32 Unused1;
public Single Unused2;
public Single Unused3;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct Shared
{
//////////////////////////////////////////////////////////////////////////
// Version
//////////////////////////////////////////////////////////////////////////
public Int32 VersionMajor;
public Int32 VersionMinor;
public Int32 AllDriversOffset; // Offset to NumCars variable
public Int32 DriverDataSize; // Size of DriverData
//////////////////////////////////////////////////////////////////////////
// Game State
//////////////////////////////////////////////////////////////////////////
public Int32 GamePaused;
public Int32 GameInMenus;
public Int32 GameInReplay;
public Int32 GameUsingVr;
public Int32 GameUnused1;
//////////////////////////////////////////////////////////////////////////
// High Detail
//////////////////////////////////////////////////////////////////////////
// High precision data for player's vehicle only
public PlayerData Player;
//////////////////////////////////////////////////////////////////////////
// Event And Session
//////////////////////////////////////////////////////////////////////////
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]
public byte[] TrackName; // UTF-8
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]
public byte[] LayoutName; // UTF-8
public Int32 TrackId;
public Int32 LayoutId;
// Layout length in meters
public Single LayoutLength;
public SectorStarts<Single> SectorStartFactors;
// Race session durations
// Note: Index 0-2 = race 1-3
// Note: Value -1 = N/A
// Note: If both laps and minutes are more than 0, race session starts with minutes then adds laps
public RaceDuration<Int32> RaceSessionLaps;
public RaceDuration<Int32> RaceSessionMinutes;
// The current race event index, for championships with multiple events
// Note: 0-indexed, -1 = N/A
public Int32 EventIndex;
// Which session the player is in (practice, qualifying, race, etc.)
// Note: See the R3E.Constant.Session enum
public Int32 SessionType;
// The current iteration of the current type of session (second qualifying session, etc.)
// Note: 1 = first, 2 = second etc, -1 = N/A
public Int32 SessionIteration;
// If the session is time based, lap based or time based with an extra lap at the end
public Int32 SessionLengthFormat;
// Unit: Meter per second (m/s)
public Single SessionPitSpeedLimit;
// Which phase the current session is in (gridwalk, countdown, green flag, etc.)
// Note: See the R3E.Constant.SessionPhase enum
public Int32 SessionPhase;
// Which phase start lights are in; -1 = unavailable, 0 = off, 1-5 = redlight on and counting down, 6 = greenlight on
// Note: See the r3e_session_phase enum
public Int32 StartLights;
// -1 = no data available
// 0 = not active
// 1 = active
// 2 = 2x
// 3 = 3x
// 4 = 4x
public Int32 TireWearActive;
// -1 = no data
// 0 = not active
// 1 = active
// 2 = 2x
// 3 = 3x
// 4 = 4x
public Int32 FuelUseActive;
// Total number of laps in the race, or -1 if player is not in race mode (practice, test mode, etc.)
public Int32 NumberOfLaps;
// Amount of time and time remaining for the current session
// Note: Only available in time-based sessions, -1.0 = N/A
// Units: Seconds
public Single SessionTimeDuration;
public Single SessionTimeRemaining;
// Server max incident points, -1 = N/A
public Int32 MaxIncidentPoints;
// Reserved data
public Single EventUnused2;
//////////////////////////////////////////////////////////////////////////
// Pit
//////////////////////////////////////////////////////////////////////////
// Current status of the pit stop
// Note: See the R3E.Constant.PitWindow enum
public Int32 PitWindowStatus;
// The minute/lap from which you're obligated to pit (-1 = N/A)
// Unit: Minutes in time-based sessions, otherwise lap
public Int32 PitWindowStart;
// The minute/lap into which you need to have pitted (-1 = N/A)
// Unit: Minutes in time-based sessions, otherwise lap
public Int32 PitWindowEnd;
// If current vehicle is in pitline (-1 = N/A)
public Int32 InPitlane;
// What is currently selected in pit menu, and array of states (preset/buttons: -1 = not selectable, 1 = selectable) (actions: -1 = N/A, 0 = unmarked for fix, 1 = marked for fix)
public Int32 PitMenuSelection;
public PitMenuState PitMenuState;
// Current vehicle pit state (-1 = N/A, 0 = None, 1 = Requested stop, 2 = Entered pitlane heading for pitspot, 3 = Stopped at pitspot, 4 = Exiting pitspot heading for pit exit)
public Int32 PitState;
// Current vehicle pitstop actions duration
public Single PitTotalDuration;
public Single PitElapsedTime;
// Current vehicle pit action (-1 = N/A, 0 = None, 1 = Preparing, (combination of 2 = Penalty serve, 4 = Driver change, 8 = Refueling, 16 = Front tires, 32 = Rear tires, 64 = Body, 128 = Front wing, 256 = Rear wing, 512 = Suspension))
public Int32 PitAction;
// Number of pitstops the current vehicle has performed (-1 = N/A)
public Int32 NumPitstopsPerformed;
public Single PitMinDurationTotal;
public Single PitMinDurationLeft;
//////////////////////////////////////////////////////////////////////////
// Scoring & Timings
//////////////////////////////////////////////////////////////////////////
// The current state of each type of flag
public Flags Flags;
// Current position (1 = first place)
public Int32 Position;
// Based on performance index
public Int32 PositionClass;
// Note: See the R3E.Constant.FinishStatus enum
public Int32 FinishStatus;
// Total number of cut track warnings (-1 = N/A)
public Int32 CutTrackWarnings;
// The number of penalties the car currently has pending of each type (-1 = N/A)
public CutTrackPenalties Penalties;
// Total number of penalties pending for the car
// Note: See the 'penalties' field
public Int32 NumPenalties;
// How many laps the player has completed. If this value is 6, the player is on his 7th lap. -1 = n/a
public Int32 CompletedLaps;
public Int32 CurrentLapValid;
public Int32 TrackSector;
public Single LapDistance;
// fraction of lap completed, 0.0-1.0, -1.0 = N/A
public Single LapDistanceFraction;
// The current best lap time for the leader of the session (-1.0 = N/A)
public Single LapTimeBestLeader;
// The current best lap time for the leader of the player's class in the current session (-1.0 = N/A)
public Single LapTimeBestLeaderClass;
// Sector times of fastest lap by anyone in session
// Unit: Seconds (-1.0 = N/A)
public Sectors<Single> SectorTimesSessionBestLap;
// Unit: Seconds (-1.0 = none)
public Single LapTimeBestSelf;
public Sectors<Single> SectorTimesBestSelf;
// Unit: Seconds (-1.0 = none)
public Single LapTimePreviousSelf;
public Sectors<Single> SectorTimesPreviousSelf;
// Unit: Seconds (-1.0 = none)
public Single LapTimeCurrentSelf;
public Sectors<Single> SectorTimesCurrentSelf;
// The time delta between the player's time and the leader of the current session (-1.0 = N/A)
public Single LapTimeDeltaLeader;
// The time delta between the player's time and the leader of the player's class in the current session (-1.0 = N/A)
public Single LapTimeDeltaLeaderClass;
// Time delta between the player and the car placed in front (-1.0 = N/A)
// Units: Seconds
public Single TimeDeltaFront;
// Time delta between the player and the car placed behind (-1.0 = N/A)
// Units: Seconds
public Single TimeDeltaBehind;
// Time delta between this car's current laptime and this car's best laptime
// Unit: Seconds (-1000.0 = N/A)
public Single TimeDeltaBestSelf;
// Best time for each individual sector no matter lap
// Unit: Seconds (-1.0 = N/A)
public Sectors<Single> BestIndividualSectorTimeSelf;
public Sectors<Single> BestIndividualSectorTimeLeader;
public Sectors<Single> BestIndividualSectorTimeLeaderClass;
public Int32 IncidentPoints;
// -1 = N/A, 0 = this and next lap valid, 1 = this lap invalid, 2 = this and next lap invalid
public Int32 LapValidState;
// Reserved data
public Single ScoreUnused1;
public Single ScoreUnused2;
//////////////////////////////////////////////////////////////////////////
// Vehicle information
//////////////////////////////////////////////////////////////////////////
public DriverInfo VehicleInfo;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]
public byte[] PlayerName; // UTF-8
//////////////////////////////////////////////////////////////////////////
// Vehicle State
//////////////////////////////////////////////////////////////////////////
// Which controller is currently controlling the player's car (AI, player, remote, etc.)
// Note: See the R3E.Constant.Control enum
public Int32 ControlType;
// Unit: Meter per second (m/s)
public Single CarSpeed;
// Unit: Radians per second (rad/s)
public Single EngineRps;
public Single MaxEngineRps;
public Single UpshiftRps;
// -2 = N/A, -1 = reverse, 0 = neutral, 1 = first gear, ...
public Int32 Gear;
// -1 = N/A
public Int32 NumGears;
// Physical location of car's center of gravity in world space (X, Y, Z) (Y = up)
public Vector3<Single> CarCgLocation;
// Pitch, yaw, roll
// Unit: Radians (rad)
public Orientation<Single> CarOrientation;
// Acceleration in three axes (X, Y, Z) of car body in local-space.
// From car center, +X=left, +Y=up, +Z=back.
// Unit: Meter per second squared (m/s^2)
public Vector3<Single> LocalAcceleration;
// Unit: Kilograms (kg)
// Note: Car + penalty weight + fuel
public Single TotalMass;
// Unit: Liters (l)
// Note: Fuel per lap show estimation when not enough data, then max recorded fuel per lap
// Note: Not valid for remote players
public Single FuelLeft;
public Single FuelCapacity;
public Single FuelPerLap;
// Unit: Celsius (C)
// Note: Not valid for AI or remote players
public Single EngineWaterTemp;
public Single EngineOilTemp;
// Unit: Kilopascals (KPa)
// Note: Not valid for AI or remote players
public Single FuelPressure;
// Unit: Kilopascals (KPa)
// Note: Not valid for AI or remote players
public Single EngineOilPressure;
// Unit: (Bar)
// Note: Not valid for AI or remote players (-1.0 = N/A)
public Single TurboPressure;
// How pressed the throttle pedal is
// Range: 0.0 - 1.0 (-1.0 = N/A)
// Note: Not valid for AI or remote players
public Single Throttle;
public Single ThrottleRaw;
// How pressed the brake pedal is
// Range: 0.0 - 1.0 (-1.0 = N/A)
// Note: Not valid for AI or remote players
public Single Brake;
public Single BrakeRaw;
// How pressed the clutch pedal is
// Range: 0.0 - 1.0 (-1.0 = N/A)
// Note: Not valid for AI or remote players
public Single Clutch;
public Single ClutchRaw;
// How much the steering wheel is turned
// Range: -1.0 - 1.0
// Note: Not valid for AI or remote players
public Single SteerInputRaw;
// How many degrees in steer lock (center to full lock)
// Note: Not valid for AI or remote players
public Int32 SteerLockDegrees;
// How many degrees in wheel range (degrees full left to rull right)
// Note: Not valid for AI or remote players
public Int32 SteerWheelRangeDegrees;
// Aid settings
public AidSettings AidSettings;
// DRS data
public DRS Drs;
// Pit limiter (-1 = N/A, 0 = inactive, 1 = active)
public Int32 PitLimiter;
// Push to pass data
public PushToPass PushToPass;
// How much the vehicle's brakes are biased towards the back wheels (0.3 = 30%, etc.) (-1.0 = N/A)
// Note: Not valid for AI or remote players
public Single BrakeBias;
// DRS activations available in total (-1 = N/A or endless)
public Int32 DrsNumActivationsTotal;
// PTP activations available in total (-1 = N/A, or there's no restriction per lap, or endless)
public Int32 PtpNumActivationsTotal;
// Reserved data
public Single VehicleUnused1;
public Single VehicleUnused2;
Orientation<Single> VehicleUnused3;
//////////////////////////////////////////////////////////////////////////
// Tires
//////////////////////////////////////////////////////////////////////////
// Which type of tires the player's car has (option, prime, etc.)
// Note: See the R3E.Constant.TireType enum, deprecated - use the values further down instead
public Int32 TireType;
// Rotation speed
// Uint: Radians per second
public TireData<Single> TireRps;
// Wheel speed
// Uint: Meters per second
public TireData<Single> TireSpeed;
// Range: 0.0 - 1.0 (-1.0 = N/A)
public TireData<Single> TireGrip;
// Range: 0.0 - 1.0 (-1.0 = N/A)
public TireData<Single> TireWear;
// (-1 = N/A, 0 = false, 1 = true)
public TireData<Int32> TireFlatspot;
// Unit: Kilopascals (KPa) (-1.0 = N/A)
// Note: Not valid for AI or remote players
public TireData<Single> TirePressure;
// Percentage of dirt on tire (-1.0 = N/A)
// Range: 0.0 - 1.0
public TireData<Single> TireDirt;
// Current temperature of three points across the tread of the tire (-1.0 = N/A)
// Optimum temperature
// Cold temperature
// Hot temperature
// Unit: Celsius (C)
// Note: Not valid for AI or remote players
public TireData<TireTempInformation> TireTemp;
// Which type of tires the car has (option, prime, etc.)
// Note: See the R3E.Constant.TireType enum
public Int32 TireTypeFront;
public Int32 TireTypeRear;
// Which subtype of tires the car has
// Note: See the R3E.Constant.TireSubtype enum
public Int32 TireSubtypeFront;
public Int32 TireSubtypeRear;
// Current brake temperature (-1.0 = N/A)
// Optimum temperature
// Cold temperature
// Hot temperature
// Unit: Celsius (C)
// Note: Not valid for AI or remote players
public TireData<BrakeTemp> BrakeTemp;
// Brake pressure (-1.0 = N/A)
// Unit: Kilo Newtons (kN)
// Note: Not valid for AI or remote players
public TireData<Single> BrakePressure;
// Reserved data
public Int32 TractionControlSetting;
public Int32 EngineMapSetting;
public Int32 EngineBrakeSetting;
// -1.0 = N/A, 0.0 -> 100.0 percent
public Single TractionControlPercent;
public TireData<Single> TireUnused1;
// Tire load (N)
// -1.0 = N/A
public TireData<Single> TireLoad;
//////////////////////////////////////////////////////////////////////////
// Damage
//////////////////////////////////////////////////////////////////////////
// The current state of various parts of the car
// Note: Not valid for AI or remote players
public CarDamage CarDamage;
//////////////////////////////////////////////////////////////////////////
// Driver Info
//////////////////////////////////////////////////////////////////////////
// Number of cars (including the player) in the race
public Int32 NumCars;
// Contains name and basic vehicle info for all drivers in place order
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
public DriverData[] DriverData;
}
}
}
| |
// Project Orleans Cloud Service SDK ver. 1.0
//
// Copyright (c) .NET Foundation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using Orleans.CodeGeneration.Serialization;
using Orleans.Runtime;
namespace Orleans.CodeGeneration
{
/// <summary>
/// Generates factory, grain reference, and invoker classes for grain interfaces.
/// Generates state object classes for grain implementation classes.
/// </summary>
public class GrainClientGenerator : MarshalByRefObject
{
[Serializable]
internal class CodeGenOptions
{
public bool ServerGen;
public FileInfo InputLib;
public FileInfo SigningKey;
public bool LanguageConflict;
public Language? TargetLanguage;
public List<string> ReferencedAssemblies = new List<string>();
public List<string> SourceFiles = new List<string>();
public List<string> Defines = new List<string>();
public List<string> Imports = new List<string>();
public string RootNamespace;
public string FSharpCompilerPath;
public string CodeGenFile;
public string SourcesDir;
public string WorkingDirectory;
public string Config;
// VB-specific options
public string MyType;
public string OptionExplicit;
public string OptionCompare;
public string OptionStrict;
public string OptionInfer;
}
[Serializable]
internal class GrainClientGeneratorFlags
{
internal static bool Verbose = false;
internal static bool FailOnPathNotFound = false;
}
private static readonly int[] suppressCompilerWarnings =
{
162, // CS0162 - Unreachable code detected.
219, // CS0219 - The variable 'V' is assigned but its value is never used.
414, // CS0414 - The private field 'F' is assigned but its value is never used.
649, // CS0649 - Field 'F' is never assigned to, and will always have its default value.
693, // CS0693 - Type parameter 'type parameter' has the same name as the type parameter from outer type 'T'
1591, // CS1591 - Missing XML comment for publicly visible type or member 'Type_or_Member'
1998 // CS1998 - This async method lacks 'await' operators and will run synchronously
};
/// <summary>
/// Generates one GrainReference class for each Grain Type in the inputLib file
/// and output one GrainClient.dll under outputLib directory
/// </summary>
private static bool CreateGrainClientAssembly(CodeGenOptions options)
{
AppDomain appDomain = null;
try
{
// Create AppDomain.
var appDomainSetup = new AppDomainSetup
{
ApplicationBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
DisallowBindingRedirects = false,
ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile
};
appDomain = AppDomain.CreateDomain("Orleans-CodeGen Domain", null, appDomainSetup);
// Set up assembly resolver
var refResolver = new ReferenceResolver(options.ReferencedAssemblies);
appDomain.AssemblyResolve += refResolver.ResolveAssembly;
// Create an instance
var generator = (GrainClientGenerator) appDomain.CreateInstanceAndUnwrap(
Assembly.GetExecutingAssembly().FullName,
typeof(GrainClientGenerator).FullName);
// Call a method
return generator.CreateGrainClient(options);
}
finally
{
if (appDomain != null)
AppDomain.Unload(appDomain); // Unload the AppDomain
}
}
/// <summary>
/// Generate one GrainReference class for each Grain Type in the inputLib file
/// and output one GrainClient.dll under outputLib directory
/// </summary>
private bool CreateGrainClient(CodeGenOptions options)
{
SerializerGenerationManager.Init();
PlacementStrategy.Initialize();
var namespaceDictionary = new Dictionary<string, NamespaceGenerator>();
// Load input assembly
var assemblyName = AssemblyName.GetAssemblyName(options.InputLib.FullName);
var grainAssembly = (Path.GetFileName(options.InputLib.FullName) != "Orleans.dll") ?
Assembly.LoadFrom(options.InputLib.FullName) :
Assembly.Load(assemblyName); // special case Orleans.dll because there is a circular dependency.
// Process input assembly
if (!ProcessInputAssembly(grainAssembly, namespaceDictionary, assemblyName.Name, options)) return false;
if (namespaceDictionary.Keys.Count == 0)
{
ConsoleText.WriteStatus("This {0} does not contain any public and non-abstract grain class" + Environment.NewLine, options.InputLib);
return true;
}
// Create sources directory
if (!Directory.Exists(options.SourcesDir))
Directory.CreateDirectory(options.SourcesDir);
// Generate source
var suffix = (options.TargetLanguage == Language.CSharp) ? ".codegen.cs" :
(options.TargetLanguage == Language.VisualBasic) ? ".codegen.vb" : ".codegen.fs";
var outputFileName = Path.Combine(options.SourcesDir, Path.GetFileNameWithoutExtension(options.InputLib.Name) + suffix);
ConsoleText.WriteStatus("Orleans-CodeGen - Generating file {0}", outputFileName);
using (var sourceWriter = new StreamWriter(outputFileName))
{
if (options.TargetLanguage != Language.FSharp)
{
var unit = new CodeCompileUnit();
foreach (NamespaceGenerator grainNamespace in namespaceDictionary.Values)
OutputReferenceSourceFile(unit, grainNamespace, options);
var cgOptions = new CodeGeneratorOptions {BracingStyle = "C"};
using (var codeProvider = CodeGeneratorBase.GetCodeProvider(options.TargetLanguage.Value))
codeProvider.GenerateCodeFromCompileUnit(unit, sourceWriter, cgOptions);
}
else
{
foreach (NamespaceGenerator grainNamespace in namespaceDictionary.Values)
((FSharpCodeGenerator) grainNamespace).Output(sourceWriter);
}
}
ConsoleText.WriteStatus("Orleans-CodeGen - Generated file written {0}", outputFileName);
// Post process
ConsoleText.WriteStatus("Orleans-CodeGen - Post-processing file {0}", outputFileName);
PostProcessSourceFiles(outputFileName, options);
// Copy intermediate file to permanent location, if newer.
ConsoleText.WriteStatus("Orleans-CodeGen - Updating IntelliSense file {0} -> {1}", outputFileName, options.CodeGenFile);
UpdateIntellisenseFile(options.CodeGenFile, outputFileName);
return true;
}
private static void DisableWarnings(TextWriter sourceWriter, IEnumerable<int> warnings)
{
foreach (var warningNum in warnings)
sourceWriter.WriteLine("#pragma warning disable {0}", warningNum);
}
private static void RestoreWarnings(TextWriter sourceWriter, IEnumerable<int> warnings)
{
foreach (var warningNum in warnings)
sourceWriter.WriteLine("#pragma warning restore {0}", warningNum);
}
/// <summary>
/// Updates the source file in the project if required.
/// </summary>
/// <param name="sourceFileToBeUpdated">Path to file to be updated.</param>
/// <param name="outputFileGenerated">File that was updated.</param>
private static void UpdateIntellisenseFile(string sourceFileToBeUpdated, string outputFileGenerated)
{
if (string.IsNullOrEmpty(sourceFileToBeUpdated)) throw new ArgumentNullException("sourceFileToBeUpdated", "Output file must not be blank");
if (string.IsNullOrEmpty(outputFileGenerated)) throw new ArgumentNullException("outputFileGenerated", "Generated file must already exist");
var sourceToUpdateFileInfo = new FileInfo(sourceFileToBeUpdated);
var generatedFileInfo = new FileInfo(outputFileGenerated);
if (!generatedFileInfo.Exists) throw new Exception("Generated file must already exist");
if (File.Exists(sourceFileToBeUpdated))
{
bool filesMatch = CheckFilesMatch(generatedFileInfo, sourceToUpdateFileInfo);
if (filesMatch)
{
ConsoleText.WriteStatus("Orleans-CodeGen - No changes to the generated file {0}", sourceFileToBeUpdated);
return;
}
// we come here only if files don't match
sourceToUpdateFileInfo.Attributes = sourceToUpdateFileInfo.Attributes & (~FileAttributes.ReadOnly); // remove read only attribute
ConsoleText.WriteStatus("Orleans-CodeGen - copying file {0} to {1}", outputFileGenerated, sourceFileToBeUpdated);
File.Copy(outputFileGenerated, sourceFileToBeUpdated, true);
filesMatch = CheckFilesMatch(generatedFileInfo, sourceToUpdateFileInfo);
ConsoleText.WriteStatus("Orleans-CodeGen - After copying file {0} to {1} Matchs={2}", outputFileGenerated, sourceFileToBeUpdated, filesMatch);
}
else
{
var dir = Path.GetDirectoryName(sourceFileToBeUpdated);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
ConsoleText.WriteStatus("Orleans-CodeGen - copying file {0} to {1}", outputFileGenerated, sourceFileToBeUpdated);
File.Copy(outputFileGenerated, sourceFileToBeUpdated, true);
bool filesMatch = CheckFilesMatch(generatedFileInfo, sourceToUpdateFileInfo);
ConsoleText.WriteStatus("Orleans-CodeGen - After copying file {0} to {1} Matchs={2}", outputFileGenerated, sourceFileToBeUpdated, filesMatch);
}
}
private static bool CheckFilesMatch(FileInfo file1, FileInfo file2)
{
bool isMatching;
long len1 = -1;
long len2 = -1;
if (file1.Exists)
len1 = file1.Length;
if (file2.Exists)
len2 = file2.Length;
if (len1 <= 0 || len2 <= 0)
{
isMatching = false;
}
else if (len1 != len2)
{
isMatching = false;
}
else
{
byte[] arr1 = File.ReadAllBytes(file1.FullName);
byte[] arr2 = File.ReadAllBytes(file2.FullName);
isMatching = true; // initially assume files match
for (int i = 0; i < arr1.Length; i++)
{
if (arr1[i] != arr2[i])
{
isMatching = false; // unless we know they don't match
break;
}
}
}
if (GrainClientGeneratorFlags.Verbose)
ConsoleText.WriteStatus("Orleans-CodeGen - CheckFilesMatch = {0} File1 = {1} Len = {2} File2 = {3} Len = {4}",
isMatching, file1, len1, file2, len2);
return isMatching;
}
/// <summary>
/// Read a grain assembly and extract codegen info for each Orleans grain / service interface
/// </summary>
/// <param name="inputAssembly">Input grain assembly</param>
/// <param name="namespaceDictionary">output list of grain namespace</param>
/// <param name="outputAssemblyName">Output assembly being generated</param>
/// <param name="options">Code generation options</param>
internal bool ProcessInputAssembly(
Assembly inputAssembly,
Dictionary<string, NamespaceGenerator> namespaceDictionary,
string outputAssemblyName,
CodeGenOptions options)
{
if(!Debugger.IsAttached)
ReferenceResolver.AssertUniqueLoadForEachAssembly();
var processedGrainTypes = new List<string>();
bool success = true;
ConsoleText.WriteStatus("Orleans-CodeGen - Adding grain namespaces from input Assembly " + inputAssembly.GetName());
foreach (var type in inputAssembly.GetTypes())
{
if (!type.IsNested && !type.IsGenericParameter && type.IsSerializable)
SerializerGenerationManager.RecordTypeToGenerate(type);
if (!options.ServerGen && GrainInterfaceData.IsGrainInterface(type))
{
NamespaceGenerator grainNamespace = RegisterNamespace(inputAssembly, namespaceDictionary, type, options.TargetLanguage.Value);
processedGrainTypes.Add(type.FullName);
try
{
var grainInterfaceData = new GrainInterfaceData(options.TargetLanguage.Value, type);
grainNamespace.AddReferenceClass(grainInterfaceData);
}
catch (GrainInterfaceData.RulesViolationException rve)
{
foreach (var v in rve.Violations)
NamespaceGenerator.ReportError(v);
success = false;
}
}
if (options.ServerGen && !type.IsAbstract && (GrainInterfaceData.IsAddressable(type)))
{
var grainNamespace = RegisterNamespace(inputAssembly, namespaceDictionary, type, options.TargetLanguage.Value);
try
{
var grainInterfaceData = GrainInterfaceData.FromGrainClass(type, options.TargetLanguage.Value);
}
catch (GrainInterfaceData.RulesViolationException rve)
{
//Note: I have a separate try/catch here since we are issuing warnings instead of compile error unlike the Grain Interface validations above.
//Question: Should we instead throw compile errors?
//Question: What warning number should we use? Standard C# warning/error numbers are listed here: https://msdn.microsoft.com/en-us/library/ms228296(v=vs.90).aspx
foreach (var v in rve.Violations)
NamespaceGenerator.ReportWarning(string.Format("CS0184 : {0}", v));
}
}
}
if (!success) return false;
ConsoleText.WriteStatus("Orleans-CodeGen - Processed grain classes: ");
foreach (string name in processedGrainTypes)
ConsoleText.WriteStatus("\t" + name);
// Generate serializers for types we encountered along the way
SerializerGenerationManager.GenerateSerializers(inputAssembly, namespaceDictionary, outputAssemblyName, options.TargetLanguage.Value);
return true;
}
private static NamespaceGenerator RegisterNamespace(
Assembly grainAssembly,
IDictionary<string, NamespaceGenerator> namespaceDictionary,
Type type,
Language outputLanguage)
{
NamespaceGenerator grainNamespace;
if (!namespaceDictionary.ContainsKey(type.Namespace))
{
switch (outputLanguage)
{
case Language.CSharp:
grainNamespace = new CSharpCodeGenerator(grainAssembly, type.Namespace);
break;
case Language.VisualBasic:
grainNamespace = new VBCodeGenerator(grainAssembly, type.Namespace);
break;
case Language.FSharp:
grainNamespace = new FSharpCodeGenerator(grainAssembly, type.Namespace);
break;
default:
throw new ArgumentException("Error: Output language unknown");
}
ConsoleText.WriteStatus("\t" + type.Namespace);
namespaceDictionary.Add(type.Namespace, grainNamespace);
}
else
{
grainNamespace = namespaceDictionary[type.Namespace];
}
return grainNamespace;
}
/// <summary>
/// Codedom does not directly support extension methods therefore
/// we must post process source files to do token
/// </summary>
/// <param name="source"></param>
/// <param name="options"></param>
private static void PostProcessSourceFiles(string source, CodeGenOptions options)
{
if (options.TargetLanguage != Language.CSharp) return;
using (StreamWriter output = File.CreateText(source + ".copy"))
{
using (StreamReader input = File.OpenText(source))
{
bool headerWritten = false;
var line = input.ReadLine();
while (line != null)
{
if (line.StartsWith("//"))
{
// pass through
}
else
{
// Now past the header comment lines
if (!headerWritten)
{
// Write Header
// surround the generated code with defines so that we can conditionally exclude it elsewhere
output.WriteLine("#if !EXCLUDE_CODEGEN");
// Write pragmas to disable selected compiler warnings in generated code
DisableWarnings(output, suppressCompilerWarnings);
headerWritten = true;
}
}
output.WriteLine(line);
line = input.ReadLine();
}
}
// Write Footer
RestoreWarnings(output, suppressCompilerWarnings);
output.WriteLine("#endif");
}
File.Delete(source);
File.Move(source + ".copy", source);
}
/// <summary>
/// output grain reference source file for debug issue
/// </summary>
private static void OutputReferenceSourceFile(CodeCompileUnit unit, NamespaceGenerator grainNamespace, CodeGenOptions options)
{
CodeNamespace referenceNameSpace = grainNamespace.ReferencedNamespace;
// add referrenced named spaces
foreach (string referredNamespace in grainNamespace.ReferencedNamespaces)
if (referredNamespace != referenceNameSpace.Name)
if (!string.IsNullOrEmpty(referredNamespace))
{
referenceNameSpace.Imports.Add(new CodeNamespaceImport(referredNamespace));
}
if (options.TargetLanguage == Language.VisualBasic && referenceNameSpace.Name.StartsWith(options.RootNamespace))
{
// Strip the root namespace off the name in the generated code for VB
referenceNameSpace.Name = referenceNameSpace.Name.Substring(options.RootNamespace.Length);
if (!string.IsNullOrEmpty(referenceNameSpace.Name) && referenceNameSpace.Name[0] == '.')
referenceNameSpace.Name = referenceNameSpace.Name.Substring(1);
}
unit.Namespaces.Add(referenceNameSpace);
}
private static readonly string CodeGenFileRelativePathCSharp = Path.Combine("Properties", "orleans.codegen.cs");
private static readonly string CodeGenFileRelativePathFSharp = Path.Combine("GeneratedFiles", "orleans.codegen.fs");
private static readonly string CodeGenFileRelativePathVB = Path.Combine("GeneratedFiles", "orleans.codegen.vb");
internal static void BuildInputAssembly(CodeGenOptions options)
{
ConsoleText.WriteStatus("Orleans-CodeGen - Generating assembly for preprocessing.");
var compilerParams = new CompilerParameters {OutputAssembly = options.InputLib.FullName};
var path = options.TargetLanguage == Language.CSharp ? CodeGenFileRelativePathCSharp :
options.TargetLanguage == Language.FSharp ? CodeGenFileRelativePathFSharp : CodeGenFileRelativePathVB;
var newArgs = new StringBuilder();
switch (options.TargetLanguage)
{
case Language.VisualBasic:
// TODO: capture all this from the project file, instead.
options.Defines.Add(string.Format("Config=\"{0}\"", options.Config));
options.Defines.Add("DEBUG=-1");
options.Defines.Add("TRACE=-1");
options.Defines.Add(string.Format("_MyType=\"{0}\"", options.MyType));
newArgs.Append(" /nostdlib ");
newArgs.AppendFormat(" /rootnamespace:{0} ", options.RootNamespace);
newArgs.AppendFormat(" /optioncompare:{0} ", options.OptionCompare.ToLowerInvariant());
newArgs.AppendFormat(options.OptionExplicit.ToLowerInvariant() == "on" ? " /optionexplicit+ " : " /optionexplicit- ");
newArgs.AppendFormat(options.OptionExplicit.ToLowerInvariant() == "on" ? " /optioninfer+ " : " /optioninfer- ");
switch (options.OptionExplicit.ToLowerInvariant())
{
case "on":
newArgs.AppendFormat(" /optionstrict+ ");
break;
case "off":
newArgs.AppendFormat(" /optionstrict- ");
break;
default:
newArgs.AppendFormat(" /optionstrict:custom ");
break;
}
newArgs.AppendFormat(" /optionstrict:custom ");
break;
case Language.FSharp:
newArgs.AppendFormat(" -o:\"{0}\" ", options.InputLib.FullName);
newArgs.AppendFormat(" -g ");
newArgs.AppendFormat(" --debug:full ");
newArgs.AppendFormat(" --noframework ");
newArgs.AppendFormat(" --optimize- ");
newArgs.AppendFormat(" --tailcalls- ");
newArgs.AppendFormat(" -g ");
foreach (var def in options.Defines)
newArgs.AppendFormat(" --define:{0} ", def);
foreach (var def in options.ReferencedAssemblies)
newArgs.AppendFormat(" -r:\"{0}\" ", def);
newArgs.AppendFormat(" --target:library ");
newArgs.AppendFormat(" --warn:3 ");
newArgs.AppendFormat(" --warnaserror:76 ");
newArgs.AppendFormat(" --fullpaths ");
newArgs.AppendFormat(" --flaterrors ");
newArgs.AppendFormat(" --subsystemversion:6.00 ");
newArgs.AppendFormat(" --highentropyva+ ");
if (null != options.SigningKey)
newArgs.AppendFormat(" --keyfile:\"{0}\"", options.SigningKey.FullName);
foreach (var source in options.SourceFiles)
{
if (source.EndsWith(path, StringComparison.InvariantCultureIgnoreCase)) continue;
newArgs.AppendFormat(" \"{0}\" ", source);
}
break;
default:
newArgs.Append(" /nostdlib ");
break;
}
if (options.TargetLanguage == Language.FSharp)
{
// There is no CodeDom provider for F#, so we have to take an entirely different approach
// to code generation for that language.
var cmdLine = newArgs.ToString();
ConsoleText.WriteStatus("{0} {1}", options.FSharpCompilerPath, cmdLine);
if (!options.InputLib.Directory.Exists)
options.InputLib.Directory.Create();
var info = new ProcessStartInfo(options.FSharpCompilerPath)
{
Arguments = cmdLine,
RedirectStandardOutput = false,
RedirectStandardError = false,
UseShellExecute = false,
WorkingDirectory = options.WorkingDirectory
};
var proc = Process.Start(info);
proc.WaitForExit();
return;
}
if (null != options.SigningKey)
newArgs.AppendFormat(" \"/keyfile:{0}\"", options.SigningKey.FullName);
foreach (var source in options.SourceFiles)
{
if (source.EndsWith(path, StringComparison.InvariantCultureIgnoreCase)) continue;
newArgs.AppendFormat(" \"{0}\" ", source);
}
compilerParams.CompilerOptions += newArgs.ToString();
var references = new HashSet<string>();
foreach (string refPath in options.ReferencedAssemblies)
if (!references.Contains(refPath)) references.Add(refPath);
foreach (string refPath in references)
compilerParams.CompilerOptions += string.Format(" /reference:\"{0}\" ", refPath);
foreach (string def in options.Defines)
compilerParams.CompilerOptions += string.Format(" /define:{0} ", def);
if (options.TargetLanguage == Language.VisualBasic)
foreach (string imp in options.Imports)
compilerParams.CompilerOptions += string.Format(" /imports:{0} ", imp);
compilerParams.CompilerOptions += " /define:EXCLUDE_CODEGEN ";
using (CodeDomProvider codeProvider = CodeGeneratorBase.GetCodeProvider(options.TargetLanguage.Value, true))
{
CompilerResults results = codeProvider.CompileAssemblyFromFile(compilerParams);
//Check compile errors
if (results.Errors.Count == 0) return;
var errorsString = string.Empty;
foreach (CompilerError error in results.Errors)
{
Console.WriteLine(error.ToString());
errorsString += string.Format("{0} Line {1},{2} - {3} {4} -- {5}",
error.FileName,
error.Line,
error.Column,
error.IsWarning ? "Warning" : "ERROR",
error.ErrorNumber,
error.ErrorText)
+ Environment.NewLine;
}
string errMsg = string.Format(
"Error: ClientGenerator could not compile and generate " + options.TargetLanguage.Value
+ " -- encountered " + results.Errors.Count + " compilation warnings/errors."
+ Environment.NewLine + "ErrorList = "
+ Environment.NewLine + errorsString);
throw new Exception(errMsg);
}
}
public int RunMain(string[] args)
{
ConsoleText.WriteStatus("Orleans-CodeGen - command-line = {0}", Environment.CommandLine);
if (args.Length < 1)
{
Console.WriteLine("Usage: ClientGenerator.exe <grain interface dll path> [<client dll path>] [<key file>] [<referenced assemblies>]");
Console.WriteLine(" ClientGenerator.exe /server <grain dll path> [<factory dll path>] [<key file>] [<referenced assemblies>]");
return 1;
}
try
{
var options = new CodeGenOptions();
bool bootstrap = false; // Used to handle circular dependencies building the runtime
// STEP 1 : Parse parameters
if (args.Length == 1 && args[0].StartsWith("@"))
{
// Read command line args from file
string arg = args[0];
string argsFile = arg.Trim('"').Substring(1).Trim('"');
Console.WriteLine("Orleans-CodeGen - Reading code-gen params from file={0}", argsFile);
AssertWellFormed(argsFile, true);
args = File.ReadAllLines(argsFile);
}
int i = 1;
foreach (string a in args)
{
string arg = a.Trim('"').Trim().Trim('"');
if (GrainClientGeneratorFlags.Verbose)
Console.WriteLine("Orleans-CodeGen - arg #{0}={1}", i++, arg);
if (string.IsNullOrEmpty(arg) || string.IsNullOrWhiteSpace(arg))
continue;
if (arg.StartsWith("/"))
{
if (arg == "/server" || arg == "/svr")
{
options.ServerGen = true;
}
else if (arg.StartsWith("/reference:") || arg.StartsWith("/r:"))
{
// list of references passed from from project file. separator =';'
string refstr = arg.Substring(arg.IndexOf(':') + 1);
string[] references = refstr.Split(';');
foreach (string rp in references)
{
AssertWellFormed(rp, true);
options.ReferencedAssemblies.Add(rp);
}
}
else if (arg.StartsWith("/cwd:"))
{
options.WorkingDirectory = arg.Substring(arg.IndexOf(':') + 1);
}
else if (arg.StartsWith("/in:"))
{
var infile = arg.Substring(arg.IndexOf(':') + 1);
AssertWellFormed(infile);
options.InputLib = new FileInfo(infile);
}
else if (arg.StartsWith("/keyfile:") || arg.StartsWith("/key:"))
{
string keyFile = arg.Substring(arg.IndexOf(':') + 1);
if (!string.IsNullOrWhiteSpace(keyFile))
{
AssertWellFormed(keyFile, true);
options.SigningKey = new FileInfo(keyFile);
}
}
else if ( arg.StartsWith("/config:"))
{
options.Config = arg.Substring(arg.IndexOf(':') + 1);
}
else if (arg.StartsWith("/fsharp:"))
{
var path = arg.Substring(arg.IndexOf(':') + 1);
if (!string.IsNullOrEmpty(path))
{
Console.WriteLine("F# compiler path = '{0}' ", path);
options.FSharpCompilerPath = path;
}
else
{
Console.WriteLine("F# compiler path not set.");
}
}
else if (arg.StartsWith("/rootns:") || arg.StartsWith("/rns:"))
{
options.RootNamespace = arg.Substring(arg.IndexOf(':') + 1);
}
else if (arg.StartsWith("/bootstrap") || arg.StartsWith("/boot"))
{
// special case for building circular dependecy in preprocessing:
// Do not build the input assembly, assume that some other build step
bootstrap = true;
options.CodeGenFile = Path.GetFullPath(CodeGenFileRelativePathCSharp);
if (GrainClientGeneratorFlags.Verbose)
Console.WriteLine("Orleans-CodeGen - Set CodeGenFile={0} from bootstrap", options.CodeGenFile);
options.ServerGen = false;
}
else if (arg.StartsWith("/define:") || arg.StartsWith("/d:"))
{
// #define constants passed from project file. separator =';'
var definsStr = arg.Substring(arg.IndexOf(':') + 1);
if (!string.IsNullOrWhiteSpace(definsStr))
{
string[] defines = definsStr.Split(';');
foreach (var define in defines)
options.Defines.Add(define);
}
}
else if (arg.StartsWith("/imports:") || arg.StartsWith("/i:"))
{
// Standard VB imports passed from project file. separator =';'
string importsStr = arg.Substring(arg.IndexOf(':') + 1);
if (!string.IsNullOrWhiteSpace(importsStr))
{
string[] imports = importsStr.Split(';');
foreach (var import in imports)
options.Imports.Add(import);
}
}
else if (arg.StartsWith("/Option")) // VB-specific options
{
if (arg.StartsWith("/OptionExplicit:"))
options.OptionExplicit = arg.Substring(arg.IndexOf(':') + 1);
else if (arg.StartsWith("/OptionStrict:"))
options.OptionStrict = arg.Substring(arg.IndexOf(':') + 1);
else if (arg.StartsWith("/OptionInfer:"))
options.OptionInfer = arg.Substring(arg.IndexOf(':') + 1);
else if (arg.StartsWith("/OptionCompare:"))
options.OptionCompare = arg.Substring(arg.IndexOf(':') + 1);
}
else if (arg.StartsWith("/MyType:")) // VB-specific option
{
options.MyType = arg.Substring(arg.IndexOf(':') + 1);
}
else if (arg.StartsWith("/sources:") || arg.StartsWith("/src:"))
{
// C# sources passed from from project file. separator = ';'
//if (GrainClientGeneratorFlags.Verbose)
// Console.WriteLine("Orleans-CodeGen - Unpacking source file list arg={0}", arg);
var sourcesStr = arg.Substring(arg.IndexOf(':') + 1);
//if (GrainClientGeneratorFlags.Verbose)
// Console.WriteLine("Orleans-CodeGen - Splitting source file list={0}", sourcesStr);
string[] sources = sourcesStr.Split(';');
foreach (var source in sources)
AddSourceFile(options.SourceFiles, ref options.LanguageConflict, ref options.TargetLanguage, ref options.CodeGenFile, source);
}
}
else
{
// files passed in without associated flags , we'll make the best guess.
if (arg.ToLowerInvariant().EndsWith(".snk", StringComparison.InvariantCultureIgnoreCase))
options.SigningKey = new FileInfo(arg);
else
AddSourceFile(options.SourceFiles, ref options.LanguageConflict, ref options.TargetLanguage, ref options.CodeGenFile, arg);
}
}
if (!options.TargetLanguage.HasValue)
{
NamespaceGenerator.ReportError("Unable to determine source code language to use for code generation.");
return 2;
}
// STEP 2 : Validate and calculate unspecified parameters
if (options.InputLib == null)
{
Console.WriteLine("Orleans-CodeGen - no input file specified.");
return 2;
}
if (string.IsNullOrEmpty(options.CodeGenFile))
{
NamespaceGenerator.ReportError(string.Format("No codegen file. Add a file '{0}' to your project",
(options.TargetLanguage == Language.CSharp) ? Path.Combine("Properties", "orleans.codegen.cs") :
(options.TargetLanguage == Language.FSharp) ? Path.Combine("GeneratedFiles", "orleans.codegen.fs")
: Path.Combine("GeneratedFiles", "orleans.codegen.vb")));
return 2;
}
// STEP 3 : Check timestamps and skip if output is up-to-date wrt to all inputs
if (!bootstrap && IsProjectUpToDate(options.InputLib, options.SourceFiles, options.ReferencedAssemblies) && !Debugger.IsAttached)
{
Console.WriteLine("Orleans-CodeGen - Skipping because all output files are up-to-date with respect to the input files.");
return 0;
}
options.SourcesDir = Path.Combine(options.InputLib.DirectoryName, "Generated");
// STEP 4 : Dump useful info for debugging
Console.WriteLine("Orleans-CodeGen - Options " + Environment.NewLine
+ "\tInputLib={0} " + Environment.NewLine
+ "\tSigningKey={1} " + Environment.NewLine
+ "\tServerGen={2} " + Environment.NewLine
+ "\tCodeGenFile={3}",
options.InputLib.FullName,
options.SigningKey != null ? options.SigningKey.FullName : "",
options.ServerGen,
options.CodeGenFile);
if (options.ReferencedAssemblies != null)
{
Console.WriteLine("Orleans-CodeGen - Using referenced libraries:");
foreach (string assembly in options.ReferencedAssemblies)
Console.WriteLine("\t{0} => {1}", Path.GetFileName(assembly), assembly);
}
// STEP 5 :
if (!bootstrap)
BuildInputAssembly(options);
// STEP 6 : Finally call code generation
if (!CreateGrainClientAssembly(options))
return -1;
// DONE!
return 0;
}
catch (Exception ex)
{
NamespaceGenerator.ReportError("-- Code-gen FAILED -- ", ex);
return 3;
}
}
private static void SetLanguageIfMatchNoConflict(string arg, string extension, Language value, ref Language? language, ref bool conflict)
{
if (conflict) return;
if (arg.EndsWith(extension, StringComparison.InvariantCultureIgnoreCase))
{
if (language.HasValue && language != value)
{
language = null;
conflict = true;
}
else
{
language = value;
}
}
}
private static void AddSourceFile(List<string> sourceFiles, ref bool conflict, ref Language? language, ref string codeGenFile, string arg)
{
AssertWellFormed(arg, true);
sourceFiles.Add(arg);
SetLanguageIfMatchNoConflict(arg, ".cs", Language.CSharp, ref language, ref conflict);
SetLanguageIfMatchNoConflict(arg, ".vb", Language.VisualBasic, ref language, ref conflict);
SetLanguageIfMatchNoConflict(arg, ".fs", Language.FSharp, ref language, ref conflict);
if (conflict || !language.HasValue) return;
if (GrainClientGeneratorFlags.Verbose)
Console.WriteLine("Orleans-CodeGen - Added source file={0}", arg);
var path = language == Language.CSharp ? CodeGenFileRelativePathCSharp :
language == Language.FSharp ? CodeGenFileRelativePathFSharp : CodeGenFileRelativePathVB;
if (arg.EndsWith(path, StringComparison.InvariantCultureIgnoreCase))
{
codeGenFile = Path.GetFullPath(path);
if (GrainClientGeneratorFlags.Verbose)
Console.WriteLine("Orleans-CodeGen - Set CodeGenFile={0} from {1}", codeGenFile, arg);
}
}
private static bool IsProjectUpToDate(FileInfo inputLib, IReadOnlyCollection<string> sourceFiles, IEnumerable<string> referencedAssemblies)
{
if (inputLib == null) return false;
if (!inputLib.Exists) return false;
if (sourceFiles == null) return false;
if (sourceFiles.Count == 0) return false; // don't know so safer to say always out of date.
var dllDate = inputLib.LastWriteTimeUtc;
foreach (var source in sourceFiles)
{
var sourceInfo = new FileInfo(source);
// if any of the source files is newer than input lib then project is not up to date
if (sourceInfo.LastWriteTimeUtc > dllDate) return false;
}
foreach (var reference in referencedAssemblies)
{
var libInfo = new FileInfo(reference);
if (libInfo.Exists)
{
// if any of the reference files is newer than input lib then project is not up to date
if (libInfo.LastWriteTimeUtc > dllDate) return false;
}
}
return true;
}
private static void AssertWellFormed(string path, bool mustExist = false)
{
CheckPathNotStartWith(path, ":");
CheckPathNotStartWith(path, "\"");
CheckPathNotEndsWith(path, "\"");
CheckPathNotEndsWith(path, "/");
CheckPath(path, p => !string.IsNullOrWhiteSpace(p), "Empty path string");
bool exists = FileExists(path);
if (mustExist && GrainClientGeneratorFlags.FailOnPathNotFound)
CheckPath(path, p => exists, "Path not exists");
}
private static bool FileExists(string path)
{
bool exists = File.Exists(path) || Directory.Exists(path);
if (!exists)
Console.WriteLine("MISSING: Path not exists: {0}", path);
return exists;
}
private static void CheckPathNotStartWith(string path, string str)
{
CheckPath(path, p => !p.StartsWith(str), string.Format("Cannot start with '{0}'", str));
}
private static void CheckPathNotEndsWith(string path, string str)
{
CheckPath(path, p => !p.EndsWith(str, StringComparison.InvariantCultureIgnoreCase), string.Format("Cannot end with '{0}'", str));
}
private static void CheckPath(string path, Func<string, bool> condition, string what)
{
if (condition(path)) return;
var errMsg = string.Format("Bad path {0} Reason = {1}", path, what);
Console.WriteLine("CODEGEN-ERROR: " + errMsg);
throw new ArgumentException("FAILED: " + errMsg);
}
/// <summary>
/// Simple class that loads the reference assemblies upon the AppDomain.AssemblyResolve
/// </summary>
[Serializable]
internal class ReferenceResolver
{
/// <summary>
/// Dictionary : Assembly file name without extension -> full path
/// </summary>
private Dictionary<string, string> referenceAssemblyPaths = new Dictionary<string, string>();
/// <summary>
/// Needs to be public so can be serialized accross the the app domain.
/// </summary>
public Dictionary<string, string> ReferenceAssemblyPaths
{
get { return referenceAssemblyPaths; }
set { referenceAssemblyPaths = value; }
}
/// <summary>
/// Inits the resolver
/// </summary>
/// <param name="referencedAssemblies">Full paths of referenced assemblies</param>
public ReferenceResolver(IEnumerable<string> referencedAssemblies)
{
if (null == referencedAssemblies) return;
foreach (var assemblyPath in referencedAssemblies)
referenceAssemblyPaths[Path.GetFileNameWithoutExtension(assemblyPath)] = assemblyPath;
}
/// <summary>
/// Diagnostic method to verify that no duplicate types are loaded.
/// </summary>
/// <param name="message"></param>
public static void AssertUniqueLoadForEachAssembly(string message = null)
{
if (!string.IsNullOrWhiteSpace(message))
ConsoleText.WriteStatus(message);
ConsoleText.WriteStatus("Orleans-CodeGen - Assemblies loaded:");
var loaded = new Dictionary<string, string>();
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
var assemblyName = Path.GetFileName(assembly.Location);
ConsoleText.WriteStatus("\t{0} => {1}", assemblyName, assembly.Location);
if (!loaded.ContainsKey(assemblyName))
loaded.Add(assemblyName, assembly.Location);
else
throw new Exception(string.Format("Assembly already loaded.Possible internal error !!!. " + Environment.NewLine + "\t{0}" + Environment.NewLine + "\t{1}",
assembly.Location, loaded[assemblyName]));
}
}
/// <summary>
/// Handles System.AppDomain.AssemblyResolve event of an System.AppDomain
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="args">The event data.</param>
/// <returns>The assembly that resolves the type, assembly, or resource;
/// or null if theassembly cannot be resolved.
/// </returns>
public Assembly ResolveAssembly(object sender, ResolveEventArgs args)
{
Assembly assembly = null;
string path;
var asmName = new AssemblyName(args.Name);
if (referenceAssemblyPaths.TryGetValue(asmName.Name, out path))
assembly = Assembly.LoadFrom(path);
else
ConsoleText.WriteStatus("Could not resolve {0}:", asmName.Name);
return assembly;
}
}
}
}
| |
// Generated by ProtoGen, Version=2.4.1.521, Culture=neutral, PublicKeyToken=17b3b1f090c3ea48. 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 Google.ProtocolBuffers.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class UnitTestOptimizeForProtoFile {
#region Extension registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
registry.Add(global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize.TestExtension);
registry.Add(global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize.TestExtension2);
}
#endregion
#region Static variables
internal static pbd::MessageDescriptor internal__static_protobuf_unittest_TestOptimizedForSize__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize, global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize.Builder> internal__static_protobuf_unittest_TestOptimizedForSize__FieldAccessorTable;
internal static pbd::MessageDescriptor internal__static_protobuf_unittest_TestRequiredOptimizedForSize__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize, global::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize.Builder> internal__static_protobuf_unittest_TestRequiredOptimizedForSize__FieldAccessorTable;
internal static pbd::MessageDescriptor internal__static_protobuf_unittest_TestOptionalOptimizedForSize__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.TestOptionalOptimizedForSize, global::Google.ProtocolBuffers.TestProtos.TestOptionalOptimizedForSize.Builder> internal__static_protobuf_unittest_TestOptionalOptimizedForSize__FieldAccessorTable;
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static UnitTestOptimizeForProtoFile() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Citnb29nbGUvcHJvdG9idWYvdW5pdHRlc3Rfb3B0aW1pemVfZm9yLnByb3Rv",
"EhFwcm90b2J1Zl91bml0dGVzdBokZ29vZ2xlL3Byb3RvYnVmL2NzaGFycF9v",
"cHRpb25zLnByb3RvGh5nb29nbGUvcHJvdG9idWYvdW5pdHRlc3QucHJvdG8i",
"kgIKFFRlc3RPcHRpbWl6ZWRGb3JTaXplEgkKAWkYASABKAUSLgoDbXNnGBMg",
"ASgLMiEucHJvdG9idWZfdW5pdHRlc3QuRm9yZWlnbk1lc3NhZ2UqCQjoBxCA",
"gICAAjJACg50ZXN0X2V4dGVuc2lvbhInLnByb3RvYnVmX3VuaXR0ZXN0LlRl",
"c3RPcHRpbWl6ZWRGb3JTaXplGNIJIAEoBTJyCg90ZXN0X2V4dGVuc2lvbjIS",
"Jy5wcm90b2J1Zl91bml0dGVzdC5UZXN0T3B0aW1pemVkRm9yU2l6ZRjTCSAB",
"KAsyLy5wcm90b2J1Zl91bml0dGVzdC5UZXN0UmVxdWlyZWRPcHRpbWl6ZWRG",
"b3JTaXplIikKHFRlc3RSZXF1aXJlZE9wdGltaXplZEZvclNpemUSCQoBeBgB",
"IAIoBSJaChxUZXN0T3B0aW9uYWxPcHRpbWl6ZWRGb3JTaXplEjoKAW8YASAB",
"KAsyLy5wcm90b2J1Zl91bml0dGVzdC5UZXN0UmVxdWlyZWRPcHRpbWl6ZWRG",
"b3JTaXplQkZIAsI+QQohR29vZ2xlLlByb3RvY29sQnVmZmVycy5UZXN0UHJv",
"dG9zEhxVbml0VGVzdE9wdGltaXplRm9yUHJvdG9GaWxl"));
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_protobuf_unittest_TestOptimizedForSize__Descriptor = Descriptor.MessageTypes[0];
internal__static_protobuf_unittest_TestOptimizedForSize__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize, global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize.Builder>(internal__static_protobuf_unittest_TestOptimizedForSize__Descriptor,
new string[] { "I", "Msg", });
global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize.TestExtension = pb::GeneratedSingleExtension<int>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize.Descriptor.Extensions[0]);
global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize.TestExtension2 = pb::GeneratedSingleExtension<global::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize.Descriptor.Extensions[1]);
internal__static_protobuf_unittest_TestRequiredOptimizedForSize__Descriptor = Descriptor.MessageTypes[1];
internal__static_protobuf_unittest_TestRequiredOptimizedForSize__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize, global::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize.Builder>(internal__static_protobuf_unittest_TestRequiredOptimizedForSize__Descriptor,
new string[] { "X", });
internal__static_protobuf_unittest_TestOptionalOptimizedForSize__Descriptor = Descriptor.MessageTypes[2];
internal__static_protobuf_unittest_TestOptionalOptimizedForSize__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.TestOptionalOptimizedForSize, global::Google.ProtocolBuffers.TestProtos.TestOptionalOptimizedForSize.Builder>(internal__static_protobuf_unittest_TestOptionalOptimizedForSize__Descriptor,
new string[] { "O", });
pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance();
RegisterAllExtensions(registry);
global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.RegisterAllExtensions(registry);
global::Google.ProtocolBuffers.TestProtos.UnitTestProtoFile.RegisterAllExtensions(registry);
return registry;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.Descriptor,
global::Google.ProtocolBuffers.TestProtos.UnitTestProtoFile.Descriptor,
}, assigner);
}
#endregion
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class TestOptimizedForSize : pb::ExtendableMessage<TestOptimizedForSize, TestOptimizedForSize.Builder> {
private TestOptimizedForSize() { }
private static readonly TestOptimizedForSize defaultInstance = new TestOptimizedForSize().MakeReadOnly();
public static TestOptimizedForSize DefaultInstance {
get { return defaultInstance; }
}
public override TestOptimizedForSize DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override TestOptimizedForSize ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::Google.ProtocolBuffers.TestProtos.UnitTestOptimizeForProtoFile.internal__static_protobuf_unittest_TestOptimizedForSize__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<TestOptimizedForSize, TestOptimizedForSize.Builder> InternalFieldAccessors {
get { return global::Google.ProtocolBuffers.TestProtos.UnitTestOptimizeForProtoFile.internal__static_protobuf_unittest_TestOptimizedForSize__FieldAccessorTable; }
}
public const int TestExtensionFieldNumber = 1234;
public static pb::GeneratedExtensionBase<int> TestExtension;
public const int TestExtension2FieldNumber = 1235;
public static pb::GeneratedExtensionBase<global::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize> TestExtension2;
public const int IFieldNumber = 1;
private bool hasI;
private int i_;
public bool HasI {
get { return hasI; }
}
public int I {
get { return i_; }
}
public const int MsgFieldNumber = 19;
private bool hasMsg;
private global::Google.ProtocolBuffers.TestProtos.ForeignMessage msg_;
public bool HasMsg {
get { return hasMsg; }
}
public global::Google.ProtocolBuffers.TestProtos.ForeignMessage Msg {
get { return msg_ ?? global::Google.ProtocolBuffers.TestProtos.ForeignMessage.DefaultInstance; }
}
public static TestOptimizedForSize ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static TestOptimizedForSize ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static TestOptimizedForSize ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static TestOptimizedForSize ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static TestOptimizedForSize ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static TestOptimizedForSize ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static TestOptimizedForSize ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static TestOptimizedForSize ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static TestOptimizedForSize ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static TestOptimizedForSize ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private TestOptimizedForSize 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(TestOptimizedForSize prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::ExtendableBuilder<TestOptimizedForSize, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(TestOptimizedForSize cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private TestOptimizedForSize result;
private TestOptimizedForSize PrepareBuilder() {
if (resultIsReadOnly) {
TestOptimizedForSize original = result;
result = new TestOptimizedForSize();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override TestOptimizedForSize 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::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize.Descriptor; }
}
public override TestOptimizedForSize DefaultInstanceForType {
get { return global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize.DefaultInstance; }
}
public override TestOptimizedForSize BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public bool HasI {
get { return result.hasI; }
}
public int I {
get { return result.I; }
set { SetI(value); }
}
public Builder SetI(int value) {
PrepareBuilder();
result.hasI = true;
result.i_ = value;
return this;
}
public Builder ClearI() {
PrepareBuilder();
result.hasI = false;
result.i_ = 0;
return this;
}
public bool HasMsg {
get { return result.hasMsg; }
}
public global::Google.ProtocolBuffers.TestProtos.ForeignMessage Msg {
get { return result.Msg; }
set { SetMsg(value); }
}
public Builder SetMsg(global::Google.ProtocolBuffers.TestProtos.ForeignMessage value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasMsg = true;
result.msg_ = value;
return this;
}
public Builder SetMsg(global::Google.ProtocolBuffers.TestProtos.ForeignMessage.Builder builderForValue) {
pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue");
PrepareBuilder();
result.hasMsg = true;
result.msg_ = builderForValue.Build();
return this;
}
public Builder MergeMsg(global::Google.ProtocolBuffers.TestProtos.ForeignMessage value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
if (result.hasMsg &&
result.msg_ != global::Google.ProtocolBuffers.TestProtos.ForeignMessage.DefaultInstance) {
result.msg_ = global::Google.ProtocolBuffers.TestProtos.ForeignMessage.CreateBuilder(result.msg_).MergeFrom(value).BuildPartial();
} else {
result.msg_ = value;
}
result.hasMsg = true;
return this;
}
public Builder ClearMsg() {
PrepareBuilder();
result.hasMsg = false;
result.msg_ = null;
return this;
}
}
static TestOptimizedForSize() {
object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.UnitTestOptimizeForProtoFile.Descriptor, null);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class TestRequiredOptimizedForSize : pb::GeneratedMessage<TestRequiredOptimizedForSize, TestRequiredOptimizedForSize.Builder> {
private TestRequiredOptimizedForSize() { }
private static readonly TestRequiredOptimizedForSize defaultInstance = new TestRequiredOptimizedForSize().MakeReadOnly();
public static TestRequiredOptimizedForSize DefaultInstance {
get { return defaultInstance; }
}
public override TestRequiredOptimizedForSize DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override TestRequiredOptimizedForSize ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::Google.ProtocolBuffers.TestProtos.UnitTestOptimizeForProtoFile.internal__static_protobuf_unittest_TestRequiredOptimizedForSize__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<TestRequiredOptimizedForSize, TestRequiredOptimizedForSize.Builder> InternalFieldAccessors {
get { return global::Google.ProtocolBuffers.TestProtos.UnitTestOptimizeForProtoFile.internal__static_protobuf_unittest_TestRequiredOptimizedForSize__FieldAccessorTable; }
}
public const int XFieldNumber = 1;
private bool hasX;
private int x_;
public bool HasX {
get { return hasX; }
}
public int X {
get { return x_; }
}
public static TestRequiredOptimizedForSize ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static TestRequiredOptimizedForSize ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static TestRequiredOptimizedForSize ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static TestRequiredOptimizedForSize ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static TestRequiredOptimizedForSize ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static TestRequiredOptimizedForSize ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static TestRequiredOptimizedForSize ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static TestRequiredOptimizedForSize ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static TestRequiredOptimizedForSize ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static TestRequiredOptimizedForSize ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private TestRequiredOptimizedForSize 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(TestRequiredOptimizedForSize prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<TestRequiredOptimizedForSize, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(TestRequiredOptimizedForSize cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private TestRequiredOptimizedForSize result;
private TestRequiredOptimizedForSize PrepareBuilder() {
if (resultIsReadOnly) {
TestRequiredOptimizedForSize original = result;
result = new TestRequiredOptimizedForSize();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override TestRequiredOptimizedForSize 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::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize.Descriptor; }
}
public override TestRequiredOptimizedForSize DefaultInstanceForType {
get { return global::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize.DefaultInstance; }
}
public override TestRequiredOptimizedForSize BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public bool HasX {
get { return result.hasX; }
}
public int X {
get { return result.X; }
set { SetX(value); }
}
public Builder SetX(int value) {
PrepareBuilder();
result.hasX = true;
result.x_ = value;
return this;
}
public Builder ClearX() {
PrepareBuilder();
result.hasX = false;
result.x_ = 0;
return this;
}
}
static TestRequiredOptimizedForSize() {
object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.UnitTestOptimizeForProtoFile.Descriptor, null);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class TestOptionalOptimizedForSize : pb::GeneratedMessage<TestOptionalOptimizedForSize, TestOptionalOptimizedForSize.Builder> {
private TestOptionalOptimizedForSize() { }
private static readonly TestOptionalOptimizedForSize defaultInstance = new TestOptionalOptimizedForSize().MakeReadOnly();
public static TestOptionalOptimizedForSize DefaultInstance {
get { return defaultInstance; }
}
public override TestOptionalOptimizedForSize DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override TestOptionalOptimizedForSize ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::Google.ProtocolBuffers.TestProtos.UnitTestOptimizeForProtoFile.internal__static_protobuf_unittest_TestOptionalOptimizedForSize__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<TestOptionalOptimizedForSize, TestOptionalOptimizedForSize.Builder> InternalFieldAccessors {
get { return global::Google.ProtocolBuffers.TestProtos.UnitTestOptimizeForProtoFile.internal__static_protobuf_unittest_TestOptionalOptimizedForSize__FieldAccessorTable; }
}
public const int OFieldNumber = 1;
private bool hasO;
private global::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize o_;
public bool HasO {
get { return hasO; }
}
public global::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize O {
get { return o_ ?? global::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize.DefaultInstance; }
}
public static TestOptionalOptimizedForSize ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static TestOptionalOptimizedForSize ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static TestOptionalOptimizedForSize ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static TestOptionalOptimizedForSize ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static TestOptionalOptimizedForSize ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static TestOptionalOptimizedForSize ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static TestOptionalOptimizedForSize ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static TestOptionalOptimizedForSize ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static TestOptionalOptimizedForSize ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static TestOptionalOptimizedForSize ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private TestOptionalOptimizedForSize 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(TestOptionalOptimizedForSize prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<TestOptionalOptimizedForSize, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(TestOptionalOptimizedForSize cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private TestOptionalOptimizedForSize result;
private TestOptionalOptimizedForSize PrepareBuilder() {
if (resultIsReadOnly) {
TestOptionalOptimizedForSize original = result;
result = new TestOptionalOptimizedForSize();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override TestOptionalOptimizedForSize 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::Google.ProtocolBuffers.TestProtos.TestOptionalOptimizedForSize.Descriptor; }
}
public override TestOptionalOptimizedForSize DefaultInstanceForType {
get { return global::Google.ProtocolBuffers.TestProtos.TestOptionalOptimizedForSize.DefaultInstance; }
}
public override TestOptionalOptimizedForSize BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public bool HasO {
get { return result.hasO; }
}
public global::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize O {
get { return result.O; }
set { SetO(value); }
}
public Builder SetO(global::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasO = true;
result.o_ = value;
return this;
}
public Builder SetO(global::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize.Builder builderForValue) {
pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue");
PrepareBuilder();
result.hasO = true;
result.o_ = builderForValue.Build();
return this;
}
public Builder MergeO(global::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
if (result.hasO &&
result.o_ != global::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize.DefaultInstance) {
result.o_ = global::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize.CreateBuilder(result.o_).MergeFrom(value).BuildPartial();
} else {
result.o_ = value;
}
result.hasO = true;
return this;
}
public Builder ClearO() {
PrepareBuilder();
result.hasO = false;
result.o_ = null;
return this;
}
}
static TestOptionalOptimizedForSize() {
object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.UnitTestOptimizeForProtoFile.Descriptor, null);
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Collections.Generic;
using System.Data;
using FluentMigrator.Expressions;
using FluentMigrator.Model;
using FluentMigrator.Runner.Generators.Postgres;
using NUnit.Framework;
using NUnit.Should;
namespace FluentMigrator.Tests.Unit.Generators.Postgres
{
[TestFixture]
public class PostgresGeneratorTests
{
private PostgresGenerator generator;
public PostgresGeneratorTests()
{
generator = new PostgresGenerator();
}
[Test]
public void CanCreateSchema()
{
var expression = new CreateSchemaExpression { SchemaName = "Schema1" };
var sql = generator.Generate(expression);
sql.ShouldBe("CREATE SCHEMA \"Schema1\"");
}
[Test]
public void CanDropSchema()
{
var expression = new DeleteSchemaExpression() { SchemaName = "Schema1" };
var sql = generator.Generate(expression);
sql.ShouldBe("DROP SCHEMA \"Schema1\"");
}
[Test]
public void CanCreateTable()
{
string tableName = "NewTable";
CreateTableExpression expression = GetCreateTableExpression(tableName);
string sql = generator.Generate(expression);
sql.ShouldBe("CREATE TABLE \"public\".\"NewTable\" (\"ColumnName1\" text NOT NULL, \"ColumnName2\" integer NOT NULL)");
}
[Test]
public void CanCreateTableInSchema()
{
string tableName = "NewTable";
CreateTableExpression expression = GetCreateTableExpression(tableName);
expression.SchemaName = "wibble";
string sql = generator.Generate(expression);
sql.ShouldBe("CREATE TABLE \"wibble\".\"NewTable\" (\"ColumnName1\" text NOT NULL, \"ColumnName2\" integer NOT NULL)");
}
[Test]
public void CanCreateTableWithPrimaryKey()
{
string tableName = "NewTable";
CreateTableExpression expression = GetCreateTableExpression(tableName);
expression.Columns[0].IsPrimaryKey = true;
string sql = generator.Generate(expression);
sql.ShouldBe("CREATE TABLE \"public\".\"NewTable\" (\"ColumnName1\" text NOT NULL, \"ColumnName2\" integer NOT NULL, PRIMARY KEY (\"ColumnName1\"))");
}
[Test]
public void CanCreateTableWithPrimaryKeyNamed()
{
string tableName = "NewTable";
CreateTableExpression expression = GetCreateTableExpression(tableName);
expression.Columns[0].IsPrimaryKey = true;
expression.Columns[0].PrimaryKeyName = "PK_NewTable";
string sql = generator.Generate(expression);
sql.ShouldBe("CREATE TABLE \"public\".\"NewTable\" (\"ColumnName1\" text NOT NULL, \"ColumnName2\" integer NOT NULL, CONSTRAINT \"PK_NewTable\" PRIMARY KEY (\"ColumnName1\"))");
}
[Test]
public void CanCreateTableWithDefaultValue()
{
string tableName = "NewTable";
CreateTableExpression expression = GetCreateTableExpression(tableName);
expression.Columns[0].DefaultValue = "abc";
string sql = generator.Generate(expression);
sql.ShouldBe("CREATE TABLE \"public\".\"NewTable\" (\"ColumnName1\" text NOT NULL DEFAULT 'abc', \"ColumnName2\" integer NOT NULL)");
}
[Test]
public void CanCreateTableWithBoolDefaultValue()
{
string tableName = "NewTable";
CreateTableExpression expression = GetCreateTableExpression(tableName);
expression.Columns[0].DefaultValue = true;
string sql = generator.Generate(expression);
sql.ShouldBe("CREATE TABLE \"public\".\"NewTable\" (\"ColumnName1\" text NOT NULL DEFAULT true, \"ColumnName2\" integer NOT NULL)");
}
[Test]
public void CanCreateTableWithDefaultValueExplicitlySetToNull()
{
string tableName = "NewTable";
var expression = GetCreateTableExpression(tableName);
expression.Columns[0].DefaultValue = null;
var sql = generator.Generate(expression);
sql.ShouldBe(
"CREATE TABLE \"public\".\"NewTable\" (\"ColumnName1\" text NOT NULL DEFAULT NULL, \"ColumnName2\" integer NOT NULL)");
}
[Test]
public void CanCreateTableWithMultiColumnPrimaryKey()
{
string tableName = "NewTable";
CreateTableExpression expression = GetCreateTableExpression(tableName);
expression.Columns[0].IsPrimaryKey = true;
expression.Columns[1].IsPrimaryKey = true;
string sql = generator.Generate(expression);
sql.ShouldBe("CREATE TABLE \"public\".\"NewTable\" (\"ColumnName1\" text NOT NULL, \"ColumnName2\" integer NOT NULL, PRIMARY KEY (\"ColumnName1\",\"ColumnName2\"))");
}
[Test]
public void CanCreateTableWithMultiColumnPrimaryKeyNamed()
{
string tableName = "NewTable";
CreateTableExpression expression = GetCreateTableExpression(tableName);
expression.Columns[0].IsPrimaryKey = true;
expression.Columns[0].PrimaryKeyName = "wibble";
expression.Columns[1].IsPrimaryKey = true;
string sql = generator.Generate(expression);
sql.ShouldBe("CREATE TABLE \"public\".\"NewTable\" (\"ColumnName1\" text NOT NULL, \"ColumnName2\" integer NOT NULL, CONSTRAINT \"wibble\" PRIMARY KEY (\"ColumnName1\",\"ColumnName2\"))");
}
[Test]
public void CanDropTable()
{
string tableName = "NewTable";
DeleteTableExpression expression = GetDeleteTableExpression(tableName);
string sql = generator.Generate(expression);
sql.ShouldBe("DROP TABLE \"public\".\"NewTable\"");
}
[Test]
public void CanDropTableInSchema()
{
string tableName = "NewTable";
DeleteTableExpression expression = GetDeleteTableExpression(tableName);
expression.SchemaName = "wibble";
string sql = generator.Generate(expression);
sql.ShouldBe("DROP TABLE \"wibble\".\"NewTable\"");
}
[Test]
public void CanDropColumn()
{
string tableName = "NewTable";
string columnName = "NewColumn";
var expression = new DeleteColumnExpression();
expression.TableName = tableName;
expression.ColumnNames.Add(columnName);
string sql = generator.Generate(expression);
sql.ShouldBe("ALTER TABLE \"public\".\"NewTable\" DROP COLUMN \"NewColumn\"");
}
[Test]
public void CanDropMultipleColumns()
{
var expression = new DeleteColumnExpression();
expression.TableName = "NewTable";
expression.ColumnNames.Add("NewColumn");
expression.ColumnNames.Add("OtherColumn");
string sql = generator.Generate(expression);
sql.ShouldBe("ALTER TABLE \"public\".\"NewTable\" DROP COLUMN \"NewColumn\";\r\n" +
"ALTER TABLE \"public\".\"NewTable\" DROP COLUMN \"OtherColumn\"");
}
[Test]
public void CanAddColumn()
{
string tableName = "NewTable";
var columnDefinition = new ColumnDefinition();
columnDefinition.Name = "NewColumn";
columnDefinition.Size = 5;
columnDefinition.Type = DbType.String;
var expression = new CreateColumnExpression();
expression.Column = columnDefinition;
expression.TableName = tableName;
string sql = generator.Generate(expression);
sql.ShouldBe("ALTER TABLE \"public\".\"NewTable\" ADD \"NewColumn\" varchar(5) NOT NULL");
}
[Test]
public void CanAddIdentityColumn()
{
string tableName = "NewTable";
var columnDefinition = new ColumnDefinition();
columnDefinition.Name = "id";
columnDefinition.IsIdentity = true;
columnDefinition.Type = DbType.Int32;
var expression = new CreateColumnExpression();
expression.Column = columnDefinition;
expression.TableName = tableName;
string sql = generator.Generate(expression);
sql.ShouldBe("ALTER TABLE \"public\".\"NewTable\" ADD \"id\" serial NOT NULL");
}
[Test]
public void CanAddIdentityColumnForInt64()
{
string tableName = "NewTable";
var columnDefinition = new ColumnDefinition();
columnDefinition.Name = "id";
columnDefinition.IsIdentity = true;
columnDefinition.Type = DbType.Int64;
var expression = new CreateColumnExpression();
expression.Column = columnDefinition;
expression.TableName = tableName;
string sql = generator.Generate(expression);
sql.ShouldBe("ALTER TABLE \"public\".\"NewTable\" ADD \"id\" bigserial NOT NULL");
}
[Test]
public void CanAddDecimalColumn()
{
string tableName = "NewTable";
var columnDefinition = new ColumnDefinition();
columnDefinition.Name = "NewColumn";
columnDefinition.Size = 19;
columnDefinition.Precision = 2;
columnDefinition.Type = DbType.Decimal;
var expression = new CreateColumnExpression();
expression.Column = columnDefinition;
expression.TableName = tableName;
string sql = generator.Generate(expression);
sql.ShouldBe("ALTER TABLE \"public\".\"NewTable\" ADD \"NewColumn\" decimal(2,19) NOT NULL");
}
[Test]
public void CanRenameTable()
{
var expression = new RenameTableExpression();
expression.OldName = "Table1";
expression.NewName = "Table2";
string sql = generator.Generate(expression);
sql.ShouldBe("ALTER TABLE \"public\".\"Table1\" RENAME TO \"Table2\"");
}
[Test]
public void CanRenameColumn()
{
var expression = new RenameColumnExpression();
expression.TableName = "Table1";
expression.OldName = "Column1";
expression.NewName = "Column2";
string sql = generator.Generate(expression);
sql.ShouldBe("ALTER TABLE \"public\".\"Table1\" RENAME COLUMN \"Column1\" TO \"Column2\"");
}
[Test]
public void CanCreateIndex()
{
var expression = new CreateIndexExpression();
expression.Index.Name = "IX_TEST";
expression.Index.TableName = "TEST_TABLE";
expression.Index.Columns.Add(new IndexColumnDefinition { Direction = Direction.Ascending, Name = "Column1" });
expression.Index.Columns.Add(new IndexColumnDefinition { Direction = Direction.Descending, Name = "Column2" });
string sql = generator.Generate(expression);
sql.ShouldBe("CREATE INDEX \"IX_TEST\" ON \"public\".\"TEST_TABLE\" (\"Column1\" ASC,\"Column2\" DESC)");
}
[Test]
public void CanCreateUniqueIndex()
{
var expression = new CreateIndexExpression();
expression.Index.Name = "IX_TEST";
expression.Index.TableName = "TEST_TABLE";
expression.Index.IsUnique = true;
expression.Index.Columns.Add(new IndexColumnDefinition { Direction = Direction.Ascending, Name = "Column1" });
expression.Index.Columns.Add(new IndexColumnDefinition { Direction = Direction.Descending, Name = "Column2" });
string sql = generator.Generate(expression);
sql.ShouldBe("CREATE UNIQUE INDEX \"IX_TEST\" ON \"public\".\"TEST_TABLE\" (\"Column1\" ASC,\"Column2\" DESC)");
}
[Test]
public void CanDropIndex()
{
var expression = new DeleteIndexExpression();
expression.Index.Name = "IX_TEST";
expression.Index.TableName = "TEST_TABLE";
string sql = generator.Generate(expression);
sql.ShouldBe("DROP INDEX \"public\".\"IX_TEST\"");
}
[Test]
public void CanCreateForeignKey()
{
var expression = new CreateForeignKeyExpression();
expression.ForeignKey.Name = "FK_Test";
expression.ForeignKey.PrimaryTable = "TestPrimaryTable";
expression.ForeignKey.ForeignTable = "TestForeignTable";
expression.ForeignKey.PrimaryColumns = new[] { "Column1", "Column2" };
expression.ForeignKey.ForeignColumns = new[] { "Column3", "Column4" };
string sql = generator.Generate(expression);
sql.ShouldBe("ALTER TABLE \"public\".\"TestForeignTable\" ADD CONSTRAINT \"FK_Test\" FOREIGN KEY (\"Column3\",\"Column4\") REFERENCES \"public\".\"TestPrimaryTable\" (\"Column1\",\"Column2\")");
}
[Test]
public void CanCreateForeignKeyToDifferentSchema()
{
var expression = new CreateForeignKeyExpression();
expression.ForeignKey.Name = "FK_Test";
expression.ForeignKey.PrimaryTable = "TestPrimaryTable";
expression.ForeignKey.ForeignTable = "TestForeignTable";
expression.ForeignKey.PrimaryColumns = new[] { "Column1", "Column2" };
expression.ForeignKey.ForeignColumns = new[] { "Column3", "Column4" };
expression.ForeignKey.PrimaryTableSchema = "wibble";
string sql = generator.Generate(expression);
sql.ShouldBe("ALTER TABLE \"public\".\"TestForeignTable\" ADD CONSTRAINT \"FK_Test\" FOREIGN KEY (\"Column3\",\"Column4\") REFERENCES \"wibble\".\"TestPrimaryTable\" (\"Column1\",\"Column2\")");
}
[TestCase(Rule.SetDefault, "SET DEFAULT"), TestCase(Rule.SetNull, "SET NULL"), TestCase(Rule.Cascade, "CASCADE")]
public void CanCreateForeignKeyWithOnUpdateOptions(Rule rule, string output)
{
var expression = GeneratorTestHelper.GetCreateForeignKeyExpression();
expression.ForeignKey.OnUpdate = rule;
var sql = generator.Generate(expression);
sql.ShouldBe(
string.Format("ALTER TABLE \"public\".\"TestTable1\" ADD CONSTRAINT \"FK_Test\" FOREIGN KEY (\"TestColumn1\") REFERENCES \"public\".\"TestTable2\" (\"TestColumn2\") ON UPDATE {0}", output));
}
[TestCase(Rule.SetDefault, "SET DEFAULT"), TestCase(Rule.SetNull, "SET NULL"), TestCase(Rule.Cascade, "CASCADE")]
public void CanCreateForeignKeyWithOnDeleteOptions(Rule rule, string output)
{
var expression = GeneratorTestHelper.GetCreateForeignKeyExpression();
expression.ForeignKey.OnDelete = rule;
var sql = generator.Generate(expression);
sql.ShouldBe(
string.Format(
"ALTER TABLE \"public\".\"TestTable1\" ADD CONSTRAINT \"FK_Test\" FOREIGN KEY (\"TestColumn1\") REFERENCES \"public\".\"TestTable2\" (\"TestColumn2\") ON DELETE {0}",
output));
}
[Test]
public void CanCreateForeignKeyWithOnDeleteAndOnUpdateOptions()
{
var expression = GeneratorTestHelper.GetCreateForeignKeyExpression();
expression.ForeignKey.OnDelete = Rule.Cascade;
expression.ForeignKey.OnUpdate = Rule.SetDefault;
var sql = generator.Generate(expression);
sql.ShouldBe(
"ALTER TABLE \"public\".\"TestTable1\" ADD CONSTRAINT \"FK_Test\" FOREIGN KEY (\"TestColumn1\") REFERENCES \"public\".\"TestTable2\" (\"TestColumn2\") ON DELETE CASCADE ON UPDATE SET DEFAULT");
}
[Test]
public void CanCreateForeignKeyWithMultipleColumns()
{
var expression = GeneratorTestHelper.GetCreateForeignKeyExpression();
expression.ForeignKey.PrimaryColumns = new[] { "Column1", "Column2" };
expression.ForeignKey.ForeignColumns = new[] { "Column3", "Column4" };
string sql = generator.Generate(expression);
sql.ShouldBe("ALTER TABLE \"public\".\"TestTable1\" ADD CONSTRAINT \"FK_Test\" FOREIGN KEY (\"Column3\",\"Column4\") REFERENCES \"public\".\"TestTable2\" (\"Column1\",\"Column2\")");
}
[Test]
public void CanDropForeignKey()
{
var expression = new DeleteForeignKeyExpression();
expression.ForeignKey.Name = "FK_Test";
expression.ForeignKey.ForeignTable = "TestPrimaryTable";
string sql = generator.Generate(expression);
sql.ShouldBe("ALTER TABLE \"public\".\"TestPrimaryTable\" DROP CONSTRAINT \"FK_Test\"");
}
[Test]
public void CanInsertData()
{
var expression = new InsertDataExpression();
expression.TableName = "TestTable";
expression.Rows.Add(new InsertionDataDefinition
{
new KeyValuePair<string, object>("Id", 1),
new KeyValuePair<string, object>("Name", "Just'in"),
new KeyValuePair<string, object>("Website", "codethinked.com")
});
expression.Rows.Add(new InsertionDataDefinition
{
new KeyValuePair<string, object>("Id", 2),
new KeyValuePair<string, object>("Name", "Na\\te"),
new KeyValuePair<string, object>("Website", "kohari.org")
});
var sql = generator.Generate(expression);
var expected = "INSERT INTO \"public\".\"TestTable\" (\"Id\",\"Name\",\"Website\") VALUES (1,'Just''in','codethinked.com');";
expected += "INSERT INTO \"public\".\"TestTable\" (\"Id\",\"Name\",\"Website\") VALUES (2,'Na\\te','kohari.org');";
sql.ShouldBe(expected);
}
[Test]
public void CanInsertGuidData()
{
var gid = Guid.NewGuid();
var expression = new InsertDataExpression { TableName = "TestTable" };
expression.Rows.Add(new InsertionDataDefinition { new KeyValuePair<string, object>("guid", gid) });
var sql = generator.Generate(expression);
var expected = String.Format("INSERT INTO \"public\".\"TestTable\" (\"guid\") VALUES ('{0}');", gid);
sql.ShouldBe(expected);
}
[Test]
public void CanAlterSchema()
{
var expression = new AlterSchemaExpression
{
DestinationSchemaName = "DEST",
SourceSchemaName = "SOURCE",
TableName = "TABLE"
};
var sql = generator.Generate(expression);
sql.ShouldBe("ALTER TABLE \"SOURCE\".\"TABLE\" SET SCHEMA \"DEST\"");
}
[Test]
public void CanAlterColumn()
{
var expression = new AlterColumnExpression
{
Column = new ColumnDefinition { Type = DbType.String, Name = "Col1" },
SchemaName = "Schema1",
TableName = "Table1"
};
var sql = generator.Generate(expression);
sql.ShouldBe("ALTER TABLE \"Schema1\".\"Table1\" ALTER \"Col1\" TYPE text");
}
[Test]
public void CanDeleteAllData()
{
var expression = new DeleteDataExpression
{
IsAllRows = true,
TableName = "Table1"
};
var sql = generator.Generate(expression);
sql.ShouldBe("DELETE FROM \"public\".\"Table1\";");
}
[Test]
public void CanDeleteAllDataWithCondition()
{
var expression = new DeleteDataExpression
{
IsAllRows = false,
SchemaName = "public",
TableName = "Table1"
};
expression.Rows.Add(
new DeletionDataDefinition
{
new KeyValuePair<string, object>("description", "wibble")
});
var sql = generator.Generate(expression);
sql.ShouldBe("DELETE FROM \"public\".\"Table1\" WHERE \"description\" = 'wibble';");
}
[Test]
public void CanDeleteAllDataWithNullCondition()
{
var expression = new DeleteDataExpression
{
IsAllRows = false,
SchemaName = "public",
TableName = "Table1"
};
expression.Rows.Add(
new DeletionDataDefinition
{
new KeyValuePair<string, object>("description", null)
});
var sql = generator.Generate(expression);
sql.ShouldBe("DELETE FROM \"public\".\"Table1\" WHERE \"description\" IS NULL;");
}
[Test]
public void CanDeleteAllDataWithMultipleConditions()
{
var expression = new DeleteDataExpression
{
IsAllRows = false,
SchemaName = "public",
TableName = "Table1"
};
expression.Rows.Add(new DeletionDataDefinition
{
new KeyValuePair<string, object>("description", null),
new KeyValuePair<string, object>("id", 10)
});
var sql = generator.Generate(expression);
sql.ShouldBe("DELETE FROM \"public\".\"Table1\" WHERE \"description\" IS NULL AND \"id\" = 10;");
}
[Test]
public void CanCreateSequence()
{
var expression = new CreateSequenceExpression
{
Sequence =
{
Cache = 10,
Cycle = true,
Increment = 2,
MaxValue = 100,
MinValue = 0,
Name = "Sequence",
SchemaName = "Schema",
StartWith = 2
}
};
var sql = generator.Generate(expression);
sql.ShouldBe("CREATE SEQUENCE \"Schema\".\"Sequence\" INCREMENT 2 MINVALUE 0 MAXVALUE 100 START WITH 2 CACHE 10 CYCLE");
}
[Test]
public void CanDeleteSequence()
{
var expression = new DeleteSequenceExpression { SchemaName = "Schema", SequenceName = "Sequence" };
var sql = generator.Generate(expression);
sql.ShouldBe("DROP SEQUENCE \"Schema\".\"Sequence\"");
}
private DeleteTableExpression GetDeleteTableExpression(string tableName)
{
return new DeleteTableExpression { TableName = tableName };
}
private CreateTableExpression GetCreateTableExpression(string tableName)
{
string columnName1 = "ColumnName1";
string columnName2 = "ColumnName2";
var column1 = new ColumnDefinition { Name = columnName1, Type = DbType.String, TableName = tableName };
var column2 = new ColumnDefinition { Name = columnName2, Type = DbType.Int32, TableName = tableName };
var expression = new CreateTableExpression { TableName = tableName };
expression.Columns.Add(column1);
expression.Columns.Add(column2);
return expression;
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: stops.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace PokemonGoApi.Proto {
/// <summary>Holder for reflection information generated from stops.proto</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class StopsReflection {
#region Descriptor
/// <summary>File descriptor for stops.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static StopsReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CgtzdG9wcy5wcm90bxISUG9rZW1vbkdvQXBpLlByb3RvIt4BChNGb3J0RGV0",
"YWlsc091dFByb3RvEgoKAklkGAEgASgJEgwKBFRlYW0YAiABKAUSDAoETmFt",
"ZRgEIAEoCRIQCghJbWFnZVVybBgFIAEoCRIKCgJGcBgGIAEoBRIPCgdTdGFt",
"aW5hGAcgASgFEhIKCk1heFN0YW1pbmEYCCABKAUSEAoIRm9ydFR5cGUYCSAB",
"KAUSEAoITGF0aXR1ZGUYCiABKAMSEQoJTG9uZ2l0dWRlGAsgASgDEhMKC0Rl",
"c2NyaXB0aW9uGAwgASgJEhAKCE1vZGlmaWVyGA0gASgBIkMKEEZvcnREZXRh",
"aWxzUHJvdG8SCgoCSWQYASABKAkSEAoITGF0aXR1ZGUYAiABKAMSEQoJTG9u",
"Z2l0dWRlGAMgASgDYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::PokemonGoApi.Proto.FortDetailsOutProto), global::PokemonGoApi.Proto.FortDetailsOutProto.Parser, new[]{ "Id", "Team", "Name", "ImageUrl", "Fp", "Stamina", "MaxStamina", "FortType", "Latitude", "Longitude", "Description", "Modifier" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::PokemonGoApi.Proto.FortDetailsProto), global::PokemonGoApi.Proto.FortDetailsProto.Parser, new[]{ "Id", "Latitude", "Longitude" }, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// FORT SEARCH
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class FortDetailsOutProto : pb::IMessage<FortDetailsOutProto> {
private static readonly pb::MessageParser<FortDetailsOutProto> _parser = new pb::MessageParser<FortDetailsOutProto>(() => new FortDetailsOutProto());
public static pb::MessageParser<FortDetailsOutProto> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::PokemonGoApi.Proto.StopsReflection.Descriptor.MessageTypes[0]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public FortDetailsOutProto() {
OnConstruction();
}
partial void OnConstruction();
public FortDetailsOutProto(FortDetailsOutProto other) : this() {
id_ = other.id_;
team_ = other.team_;
name_ = other.name_;
imageUrl_ = other.imageUrl_;
fp_ = other.fp_;
stamina_ = other.stamina_;
maxStamina_ = other.maxStamina_;
fortType_ = other.fortType_;
latitude_ = other.latitude_;
longitude_ = other.longitude_;
description_ = other.description_;
modifier_ = other.modifier_;
}
public FortDetailsOutProto Clone() {
return new FortDetailsOutProto(this);
}
/// <summary>Field number for the "Id" field.</summary>
public const int IdFieldNumber = 1;
private string id_ = "";
public string Id {
get { return id_; }
set {
id_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "Team" field.</summary>
public const int TeamFieldNumber = 2;
private int team_;
public int Team {
get { return team_; }
set {
team_ = value;
}
}
/// <summary>Field number for the "Name" field.</summary>
public const int NameFieldNumber = 4;
private string name_ = "";
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "ImageUrl" field.</summary>
public const int ImageUrlFieldNumber = 5;
private string imageUrl_ = "";
public string ImageUrl {
get { return imageUrl_; }
set {
imageUrl_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "Fp" field.</summary>
public const int FpFieldNumber = 6;
private int fp_;
public int Fp {
get { return fp_; }
set {
fp_ = value;
}
}
/// <summary>Field number for the "Stamina" field.</summary>
public const int StaminaFieldNumber = 7;
private int stamina_;
public int Stamina {
get { return stamina_; }
set {
stamina_ = value;
}
}
/// <summary>Field number for the "MaxStamina" field.</summary>
public const int MaxStaminaFieldNumber = 8;
private int maxStamina_;
public int MaxStamina {
get { return maxStamina_; }
set {
maxStamina_ = value;
}
}
/// <summary>Field number for the "FortType" field.</summary>
public const int FortTypeFieldNumber = 9;
private int fortType_;
public int FortType {
get { return fortType_; }
set {
fortType_ = value;
}
}
/// <summary>Field number for the "Latitude" field.</summary>
public const int LatitudeFieldNumber = 10;
private long latitude_;
public long Latitude {
get { return latitude_; }
set {
latitude_ = value;
}
}
/// <summary>Field number for the "Longitude" field.</summary>
public const int LongitudeFieldNumber = 11;
private long longitude_;
public long Longitude {
get { return longitude_; }
set {
longitude_ = value;
}
}
/// <summary>Field number for the "Description" field.</summary>
public const int DescriptionFieldNumber = 12;
private string description_ = "";
public string Description {
get { return description_; }
set {
description_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "Modifier" field.</summary>
public const int ModifierFieldNumber = 13;
private double modifier_;
public double Modifier {
get { return modifier_; }
set {
modifier_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as FortDetailsOutProto);
}
public bool Equals(FortDetailsOutProto other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Id != other.Id) return false;
if (Team != other.Team) return false;
if (Name != other.Name) return false;
if (ImageUrl != other.ImageUrl) return false;
if (Fp != other.Fp) return false;
if (Stamina != other.Stamina) return false;
if (MaxStamina != other.MaxStamina) return false;
if (FortType != other.FortType) return false;
if (Latitude != other.Latitude) return false;
if (Longitude != other.Longitude) return false;
if (Description != other.Description) return false;
if (Modifier != other.Modifier) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Id.Length != 0) hash ^= Id.GetHashCode();
if (Team != 0) hash ^= Team.GetHashCode();
if (Name.Length != 0) hash ^= Name.GetHashCode();
if (ImageUrl.Length != 0) hash ^= ImageUrl.GetHashCode();
if (Fp != 0) hash ^= Fp.GetHashCode();
if (Stamina != 0) hash ^= Stamina.GetHashCode();
if (MaxStamina != 0) hash ^= MaxStamina.GetHashCode();
if (FortType != 0) hash ^= FortType.GetHashCode();
if (Latitude != 0L) hash ^= Latitude.GetHashCode();
if (Longitude != 0L) hash ^= Longitude.GetHashCode();
if (Description.Length != 0) hash ^= Description.GetHashCode();
if (Modifier != 0D) hash ^= Modifier.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Id.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Id);
}
if (Team != 0) {
output.WriteRawTag(16);
output.WriteInt32(Team);
}
if (Name.Length != 0) {
output.WriteRawTag(34);
output.WriteString(Name);
}
if (ImageUrl.Length != 0) {
output.WriteRawTag(42);
output.WriteString(ImageUrl);
}
if (Fp != 0) {
output.WriteRawTag(48);
output.WriteInt32(Fp);
}
if (Stamina != 0) {
output.WriteRawTag(56);
output.WriteInt32(Stamina);
}
if (MaxStamina != 0) {
output.WriteRawTag(64);
output.WriteInt32(MaxStamina);
}
if (FortType != 0) {
output.WriteRawTag(72);
output.WriteInt32(FortType);
}
if (Latitude != 0L) {
output.WriteRawTag(80);
output.WriteInt64(Latitude);
}
if (Longitude != 0L) {
output.WriteRawTag(88);
output.WriteInt64(Longitude);
}
if (Description.Length != 0) {
output.WriteRawTag(98);
output.WriteString(Description);
}
if (Modifier != 0D) {
output.WriteRawTag(105);
output.WriteDouble(Modifier);
}
}
public int CalculateSize() {
int size = 0;
if (Id.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Id);
}
if (Team != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Team);
}
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
if (ImageUrl.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ImageUrl);
}
if (Fp != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Fp);
}
if (Stamina != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Stamina);
}
if (MaxStamina != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(MaxStamina);
}
if (FortType != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(FortType);
}
if (Latitude != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Latitude);
}
if (Longitude != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Longitude);
}
if (Description.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Description);
}
if (Modifier != 0D) {
size += 1 + 8;
}
return size;
}
public void MergeFrom(FortDetailsOutProto other) {
if (other == null) {
return;
}
if (other.Id.Length != 0) {
Id = other.Id;
}
if (other.Team != 0) {
Team = other.Team;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
if (other.ImageUrl.Length != 0) {
ImageUrl = other.ImageUrl;
}
if (other.Fp != 0) {
Fp = other.Fp;
}
if (other.Stamina != 0) {
Stamina = other.Stamina;
}
if (other.MaxStamina != 0) {
MaxStamina = other.MaxStamina;
}
if (other.FortType != 0) {
FortType = other.FortType;
}
if (other.Latitude != 0L) {
Latitude = other.Latitude;
}
if (other.Longitude != 0L) {
Longitude = other.Longitude;
}
if (other.Description.Length != 0) {
Description = other.Description;
}
if (other.Modifier != 0D) {
Modifier = other.Modifier;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Id = input.ReadString();
break;
}
case 16: {
Team = input.ReadInt32();
break;
}
case 34: {
Name = input.ReadString();
break;
}
case 42: {
ImageUrl = input.ReadString();
break;
}
case 48: {
Fp = input.ReadInt32();
break;
}
case 56: {
Stamina = input.ReadInt32();
break;
}
case 64: {
MaxStamina = input.ReadInt32();
break;
}
case 72: {
FortType = input.ReadInt32();
break;
}
case 80: {
Latitude = input.ReadInt64();
break;
}
case 88: {
Longitude = input.ReadInt64();
break;
}
case 98: {
Description = input.ReadString();
break;
}
case 105: {
Modifier = input.ReadDouble();
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class FortDetailsProto : pb::IMessage<FortDetailsProto> {
private static readonly pb::MessageParser<FortDetailsProto> _parser = new pb::MessageParser<FortDetailsProto>(() => new FortDetailsProto());
public static pb::MessageParser<FortDetailsProto> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::PokemonGoApi.Proto.StopsReflection.Descriptor.MessageTypes[1]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public FortDetailsProto() {
OnConstruction();
}
partial void OnConstruction();
public FortDetailsProto(FortDetailsProto other) : this() {
id_ = other.id_;
latitude_ = other.latitude_;
longitude_ = other.longitude_;
}
public FortDetailsProto Clone() {
return new FortDetailsProto(this);
}
/// <summary>Field number for the "Id" field.</summary>
public const int IdFieldNumber = 1;
private string id_ = "";
public string Id {
get { return id_; }
set {
id_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "Latitude" field.</summary>
public const int LatitudeFieldNumber = 2;
private long latitude_;
public long Latitude {
get { return latitude_; }
set {
latitude_ = value;
}
}
/// <summary>Field number for the "Longitude" field.</summary>
public const int LongitudeFieldNumber = 3;
private long longitude_;
public long Longitude {
get { return longitude_; }
set {
longitude_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as FortDetailsProto);
}
public bool Equals(FortDetailsProto other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Id != other.Id) return false;
if (Latitude != other.Latitude) return false;
if (Longitude != other.Longitude) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Id.Length != 0) hash ^= Id.GetHashCode();
if (Latitude != 0L) hash ^= Latitude.GetHashCode();
if (Longitude != 0L) hash ^= Longitude.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Id.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Id);
}
if (Latitude != 0L) {
output.WriteRawTag(16);
output.WriteInt64(Latitude);
}
if (Longitude != 0L) {
output.WriteRawTag(24);
output.WriteInt64(Longitude);
}
}
public int CalculateSize() {
int size = 0;
if (Id.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Id);
}
if (Latitude != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Latitude);
}
if (Longitude != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Longitude);
}
return size;
}
public void MergeFrom(FortDetailsProto other) {
if (other == null) {
return;
}
if (other.Id.Length != 0) {
Id = other.Id;
}
if (other.Latitude != 0L) {
Latitude = other.Latitude;
}
if (other.Longitude != 0L) {
Longitude = other.Longitude;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Id = input.ReadString();
break;
}
case 16: {
Latitude = input.ReadInt64();
break;
}
case 24: {
Longitude = input.ReadInt64();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Diagnostics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Cocos2D
{
public class CCParticleSystemQuad : CCParticleSystem
{
private CCRawList<CCV3F_C4B_T2F_Quad> m_pQuads; // quads to be rendered
//implementation CCParticleSystemQuad
// overriding the init method
public override bool InitWithTotalParticles(int numberOfParticles)
{
// base initialization
base.InitWithTotalParticles(numberOfParticles);
// allocating data space
AllocMemory();
#if CC_TEXTURE_ATLAS_USE_VAO
setupVBOandVAO();
#else
setupVBO();
#endif
//setShaderProgram(CCShaderCache::sharedShaderCache().programForKey(kCCShader_PositionTextureColor));
// Need to listen the event only when not use batchnode, because it will use VBO
//CCNotificationCenter::sharedNotificationCenter().addObserver(this,
// callfuncO_selector(listenBackToForeground),
// EVNET_COME_TO_FOREGROUND,
// null);
return true;
}
public CCParticleSystemQuad (string plistFile) : base(plistFile)
{ }
public CCParticleSystemQuad (int numberOfParticles)
{
InitWithTotalParticles(numberOfParticles);
}
// pointRect should be in Texture coordinates, not pixel coordinates
private void InitTexCoordsWithRect(CCRect pointRect)
{
// convert to Tex coords
var rect = pointRect.PointsToPixels();
float wide = pointRect.Size.Width;
float high = pointRect.Size.Height;
if (m_pTexture != null)
{
wide = m_pTexture.PixelsWide;
high = m_pTexture.PixelsHigh;
}
#if CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL
float left = (rect.origin.x*2+1) / (wide*2);
float bottom = (rect.origin.y*2+1) / (high*2);
float right = left + (rect.size.width*2-2) / (wide*2);
float top = bottom + (rect.size.height*2-2) / (high*2);
#else
float left = rect.Origin.X / wide;
float bottom = rect.Origin.Y / high;
float right = left + rect.Size.Width / wide;
float top = bottom + rect.Size.Height / high;
#endif
// ! CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL
// Important. Texture in cocos2d are inverted, so the Y component should be inverted
float tmp = top;
top = bottom;
bottom = tmp;
CCV3F_C4B_T2F_Quad[] quads;
int start, end;
if (m_pBatchNode != null)
{
quads = m_pBatchNode.TextureAtlas.m_pQuads.Elements;
m_pBatchNode.TextureAtlas.Dirty = true;
start = m_uAtlasIndex;
end = m_uAtlasIndex + m_uTotalParticles;
}
else
{
quads = m_pQuads.Elements;
start = 0;
end = m_uTotalParticles;
}
for (int i = start; i < end; i++)
{
// bottom-left vertex:
quads[i].BottomLeft.TexCoords.U = left;
quads[i].BottomLeft.TexCoords.V = bottom;
// bottom-right vertex:
quads[i].BottomRight.TexCoords.U = right;
quads[i].BottomRight.TexCoords.V = bottom;
// top-left vertex:
quads[i].TopLeft.TexCoords.U = left;
quads[i].TopLeft.TexCoords.V = top;
// top-right vertex:
quads[i].TopRight.TexCoords.U = right;
quads[i].TopRight.TexCoords.V = top;
}
}
public void SetTextureWithRect(CCTexture2D texture, CCRect rect)
{
// Only update the texture if is different from the current one
if (m_pTexture == null || texture.Name != m_pTexture.Name)
{
base.Texture = texture;
}
InitTexCoordsWithRect(rect);
}
public override CCTexture2D Texture
{
set
{
CCSize s = value.ContentSize;
SetTextureWithRect(value, new CCRect(0, 0, s.Width, s.Height));
}
}
public void SetDisplayFrame(CCSpriteFrame spriteFrame)
{
Debug.Assert(spriteFrame.OffsetInPixels.Equals(CCPoint.Zero),
"QuadParticle only supports SpriteFrames with no offsets");
// update texture before updating texture rect
if (m_pTexture != null || spriteFrame.Texture.Name != m_pTexture.Name)
{
Texture = spriteFrame.Texture;
}
}
private static CCPoint s_currentPosition;
private void UpdateQuad(ref CCV3F_C4B_T2F_Quad quad, ref CCParticle particle)
{
CCPoint newPosition;
if (m_ePositionType == CCPositionType.Free || m_ePositionType == CCPositionType.Relative)
{
newPosition.X = particle.pos.X - (s_currentPosition.X - particle.startPos.X);
newPosition.Y = particle.pos.Y - (s_currentPosition.Y - particle.startPos.Y);
}
else
{
newPosition = particle.pos;
}
// translate newPos to correct position, since matrix transform isn't performed in batchnode
// don't update the particle with the new position information, it will interfere with the radius and tangential calculations
if (m_pBatchNode != null)
{
newPosition.X += m_obPosition.X;
newPosition.Y += m_obPosition.Y;
}
CCColor4B color;
if (m_bOpacityModifyRGB)
{
color.R = (byte) (particle.color.R * particle.color.A * 255);
color.G = (byte) (particle.color.G * particle.color.A * 255);
color.B = (byte) (particle.color.B * particle.color.A * 255);
color.A = (byte)(particle.color.A * 255);
}
else
{
color.R = (byte)(particle.color.R * 255);
color.G = (byte)(particle.color.G * 255);
color.B = (byte)(particle.color.B * 255);
color.A = (byte)(particle.color.A * 255);
}
quad.BottomLeft.Colors = color;
quad.BottomRight.Colors = color;
quad.TopLeft.Colors = color;
quad.TopRight.Colors = color;
// vertices
float size_2 = particle.size / 2;
if (particle.rotation != 0.0)
{
float x1 = -size_2;
float y1 = -size_2;
float x2 = size_2;
float y2 = size_2;
float x = newPosition.X;
float y = newPosition.Y;
float r = -CCMathHelper.ToRadians(particle.rotation);
float cr = CCMathHelper.Cos(r);
float sr = CCMathHelper.Sin(r);
float ax = x1 * cr - y1 * sr + x;
float ay = x1 * sr + y1 * cr + y;
float bx = x2 * cr - y1 * sr + x;
float by = x2 * sr + y1 * cr + y;
float cx = x2 * cr - y2 * sr + x;
float cy = x2 * sr + y2 * cr + y;
float dx = x1 * cr - y2 * sr + x;
float dy = x1 * sr + y2 * cr + y;
// bottom-left
quad.BottomLeft.Vertices.X = ax;
quad.BottomLeft.Vertices.Y = ay;
// bottom-right vertex:
quad.BottomRight.Vertices.X = bx;
quad.BottomRight.Vertices.Y = by;
// top-left vertex:
quad.TopLeft.Vertices.X = dx;
quad.TopLeft.Vertices.Y = dy;
// top-right vertex:
quad.TopRight.Vertices.X = cx;
quad.TopRight.Vertices.Y = cy;
}
else
{
// bottom-left vertex:
quad.BottomLeft.Vertices.X = newPosition.X - size_2;
quad.BottomLeft.Vertices.Y = newPosition.Y - size_2;
// bottom-right vertex:
quad.BottomRight.Vertices.X = newPosition.X + size_2;
quad.BottomRight.Vertices.Y = newPosition.Y - size_2;
// top-left vertex:
quad.TopLeft.Vertices.X = newPosition.X - size_2;
quad.TopLeft.Vertices.Y = newPosition.Y + size_2;
// top-right vertex:
quad.TopRight.Vertices.X = newPosition.X + size_2;
quad.TopRight.Vertices.Y = newPosition.Y + size_2;
}
}
public override void UpdateQuadsWithParticles()
{
if (!m_bVisible)
{
return;
}
s_currentPosition = CCPoint.Zero;
if (m_ePositionType == CCPositionType.Free)
{
s_currentPosition = ConvertToWorldSpace(CCPoint.Zero);
}
else if (m_ePositionType == CCPositionType.Relative)
{
s_currentPosition = m_obPosition;
}
CCV3F_C4B_T2F_Quad[] quads;
if (m_pBatchNode != null)
{
quads = m_pBatchNode.TextureAtlas.m_pQuads.Elements;
m_pBatchNode.TextureAtlas.Dirty = true;
}
else
{
quads = m_pQuads.Elements;
}
var particles = m_pParticles;
var count = m_uParticleCount;
if (m_pBatchNode != null)
{
for (int i = 0; i < count; i++)
{
UpdateQuad(ref quads[m_uAtlasIndex + particles[i].atlasIndex], ref particles[i]);
}
}
else
{
for (int i = 0; i < count; i++)
{
UpdateQuad(ref quads[i], ref particles[i]);
}
}
}
protected override void PostStep()
{
//glBindBuffer(GL_ARRAY_BUFFER, m_pBuffersVBO[0] );
//glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(m_pQuads[0]) * m_uParticleCount, m_pQuads);
//glBindBuffer(GL_ARRAY_BUFFER, 0);
//CHECK_GL_ERROR_DEBUG();
}
// overriding draw method
public override void Draw()
{
Debug.Assert(m_pBatchNode == null, "draw should not be called when added to a particleBatchNode");
//Debug.Assert(m_uParticleIdx == m_uParticleCount, "Abnormal error in particle quad");
//updateQuadsWithParticles();
CCDrawManager.BindTexture(m_pTexture);
CCDrawManager.BlendFunc(m_tBlendFunc);
CCDrawManager.DrawQuads(m_pQuads, 0, m_uParticleCount);
/*
CC_NODE_DRAW_SETUP();
ccGLBindTexture2D(m_pTexture.Name);
ccGLBlendFunc(m_tBlendFunc.src, m_tBlendFunc.dst);
#if CC_TEXTURE_ATLAS_USE_VAO
//
// Using VBO and VAO
//
glBindVertexArray( m_uVAOname );
#if CC_REBIND_INDICES_BUFFER
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_pBuffersVBO[1]);
#endif
glDrawElements(GL_TRIANGLES, (GLsizei) m_uParticleIdx*6, GL_UNSIGNED_SHORT, 0);
#if CC_REBIND_INDICES_BUFFER
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
#endif
glBindVertexArray( 0 );
#else
//
// Using VBO without VAO
//
#define kQuadSize sizeof(m_pQuads[0].bl)
ccGLEnableVertexAttribs(kCCVertexAttribFlag_PosColorTex);
glBindBuffer(GL_ARRAY_BUFFER, m_pBuffersVBO[0]);
// vertices
glVertexAttribPointer(kCCVertexAttrib_Position, 3, GL_FLOAT, GL_FALSE, kQuadSize,
(GLvoid*) offsetof(ccV3F_C4B_T2F, vertices));
// colors
glVertexAttribPointer(kCCVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize,
(GLvoid*) offsetof(ccV3F_C4B_T2F, colors));
// tex coords
glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, kQuadSize,
(GLvoid*) offsetof(ccV3F_C4B_T2F, texCoords));
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_pBuffersVBO[1]);
glDrawElements(GL_TRIANGLES, (GLsizei) m_uParticleIdx * 6, GL_UNSIGNED_SHORT, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
#endif
CC_INCREMENT_GL_DRAWS(1);
CHECK_GL_ERROR_DEBUG();
*/
}
public override int TotalParticles
{
set
{
// If we are setting the total numer of particles to a number higher
// than what is allocated, we need to allocate new arrays
if (value > m_uAllocatedParticles)
{
m_pParticles = new CCParticle[value];
if (m_pQuads == null)
{
m_pQuads = new CCRawList<CCV3F_C4B_T2F_Quad>(value);
}
else
{
m_pQuads.Capacity = value;
}
m_uTotalParticles = value;
// Init particles
if (m_pBatchNode != null)
{
for (int i = 0; i < m_uTotalParticles; i++)
{
m_pParticles[i].atlasIndex = i;
}
}
#if CC_TEXTURE_ATLAS_USE_VAO
setupVBOandVAO();
#else
setupVBO();
#endif
}
else
{
m_uTotalParticles = value;
}
}
}
#if CC_TEXTURE_ATLAS_USE_VAO
void setupVBOandVAO()
{
glGenVertexArrays(1, &m_uVAOname);
glBindVertexArray(m_uVAOname);
//#define kQuadSize sizeof(m_pQuads[0].bl)
glGenBuffers(2, &m_pBuffersVBO[0]);
glBindBuffer(GL_ARRAY_BUFFER, m_pBuffersVBO[0]);
glBufferData(GL_ARRAY_BUFFER, sizeof(m_pQuads[0]) * m_uTotalParticles, m_pQuads, GL_DYNAMIC_DRAW);
// vertices
glEnableVertexAttribArray(kCCVertexAttrib_Position);
glVertexAttribPointer(kCCVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof( ccV3F_C4B_T2F, vertices));
// colors
glEnableVertexAttribArray(kCCVertexAttrib_Color);
glVertexAttribPointer(kCCVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (GLvoid*) offsetof( ccV3F_C4B_T2F, colors));
// tex coords
glEnableVertexAttribArray(kCCVertexAttrib_TexCoords);
glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof( ccV3F_C4B_T2F, texCoords));
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_pBuffersVBO[1]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(m_pIndices[0]) * m_uTotalParticles * 6, m_pIndices, GL_STATIC_DRAW);
glBindVertexArray(0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
CHECK_GL_ERROR_DEBUG();
}
#else
private void setupVBO()
{
/*
glGenBuffers(2, &m_pBuffersVBO[0]);
glBindBuffer(GL_ARRAY_BUFFER, m_pBuffersVBO[0]);
glBufferData(GL_ARRAY_BUFFER, sizeof(m_pQuads[0]) * m_uTotalParticles, m_pQuads, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_pBuffersVBO[1]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(m_pIndices[0]) * m_uTotalParticles * 6, m_pIndices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
CHECK_GL_ERROR_DEBUG();
*/
}
#endif
private void ListenBackToForeground(object obj)
{
#if CC_TEXTURE_ATLAS_USE_VAO
setupVBOandVAO();
#else
setupVBO();
#endif
}
private bool AllocMemory()
{
Debug.Assert(m_pBatchNode == null, "Memory should not be alloced when not using batchNode");
Debug.Assert((m_pQuads == null), "Memory already alloced");
m_pQuads = new CCRawList<CCV3F_C4B_T2F_Quad>(m_uTotalParticles);
return true;
}
public override CCParticleBatchNode BatchNode
{
set
{
if (m_pBatchNode != value)
{
CCParticleBatchNode oldBatch = m_pBatchNode;
base.BatchNode = value;
// NEW: is self render ?
if (value == null)
{
AllocMemory();
Texture = oldBatch.Texture;
#if CC_TEXTURE_ATLAS_USE_VAO
setupVBOandVAO();
#else
setupVBO();
#endif
}
// OLD: was it self render ? cleanup
else if (oldBatch == null)
{
// copy current state to batch
var batchQuads = m_pBatchNode.TextureAtlas.m_pQuads.Elements;
m_pBatchNode.TextureAtlas.Dirty = true;
Array.Copy(m_pQuads.Elements, 0, batchQuads, m_uAtlasIndex, m_uTotalParticles);
m_pQuads = null;
//glDeleteBuffers(2, &m_pBuffersVBO[0]);
#if CC_TEXTURE_ATLAS_USE_VAO
glDeleteVertexArrays(1, &m_uVAOname);
#endif
}
}
}
}
public CCParticleSystemQuad () : base()
{ }
public CCParticleSystemQuad Clone()
{
var p = new CCParticleSystemQuad(m_uTotalParticles);
// angle
p.m_fAngle = m_fAngle;
p.m_fAngleVar = m_fAngleVar;
// duration
p.m_fDuration = m_fDuration;
// blend function
p.m_tBlendFunc = m_tBlendFunc;
// color
p.m_tStartColor = m_tStartColor;
p.m_tStartColorVar = m_tStartColorVar;
p.m_tEndColor = m_tEndColor;
p.m_tEndColorVar = m_tEndColorVar;
// particle size
p.m_fStartSize = m_fStartSize;
p.m_fStartSizeVar = m_fStartSizeVar;
p.m_fEndSize = m_fEndSize;
p.m_fEndSizeVar = m_fEndSizeVar;
// position
p.Position = Position;
p.m_tPosVar = m_tPosVar;
// Spinning
p.m_fStartSpin = m_fStartSpin;
p.m_fStartSpinVar = m_fStartSpinVar;
p.m_fEndSpin = m_fEndSpin;
p.m_fEndSpinVar = m_fEndSpinVar;
p.m_nEmitterMode = m_nEmitterMode;
p.modeA = modeA;
p.modeB = modeB;
// life span
p.m_fLife = m_fLife;
p.m_fLifeVar = m_fLifeVar;
// emission Rate
p.m_fEmissionRate = m_fEmissionRate;
p.m_bOpacityModifyRGB = m_bOpacityModifyRGB;
p.m_pTexture = m_pTexture;
p.AutoRemoveOnFinish = AutoRemoveOnFinish;
return p;
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: health.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Grpc.Health.V1 {
/// <summary>Holder for reflection information generated from health.proto</summary>
public static partial class HealthReflection {
#region Descriptor
/// <summary>File descriptor for health.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static HealthReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CgxoZWFsdGgucHJvdG8SDmdycGMuaGVhbHRoLnYxIiUKEkhlYWx0aENoZWNr",
"UmVxdWVzdBIPCgdzZXJ2aWNlGAEgASgJIpQBChNIZWFsdGhDaGVja1Jlc3Bv",
"bnNlEkEKBnN0YXR1cxgBIAEoDjIxLmdycGMuaGVhbHRoLnYxLkhlYWx0aENo",
"ZWNrUmVzcG9uc2UuU2VydmluZ1N0YXR1cyI6Cg1TZXJ2aW5nU3RhdHVzEgsK",
"B1VOS05PV04QABILCgdTRVJWSU5HEAESDwoLTk9UX1NFUlZJTkcQAjJaCgZI",
"ZWFsdGgSUAoFQ2hlY2sSIi5ncnBjLmhlYWx0aC52MS5IZWFsdGhDaGVja1Jl",
"cXVlc3QaIy5ncnBjLmhlYWx0aC52MS5IZWFsdGhDaGVja1Jlc3BvbnNlQhGq",
"Ag5HcnBjLkhlYWx0aC5WMWIGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Grpc.Health.V1.HealthCheckRequest), global::Grpc.Health.V1.HealthCheckRequest.Parser, new[]{ "Service" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Grpc.Health.V1.HealthCheckResponse), global::Grpc.Health.V1.HealthCheckResponse.Parser, new[]{ "Status" }, null, new[]{ typeof(global::Grpc.Health.V1.HealthCheckResponse.Types.ServingStatus) }, null)
}));
}
#endregion
}
#region Messages
public sealed partial class HealthCheckRequest : pb::IMessage<HealthCheckRequest> {
private static readonly pb::MessageParser<HealthCheckRequest> _parser = new pb::MessageParser<HealthCheckRequest>(() => new HealthCheckRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<HealthCheckRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Grpc.Health.V1.HealthReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public HealthCheckRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public HealthCheckRequest(HealthCheckRequest other) : this() {
service_ = other.service_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public HealthCheckRequest Clone() {
return new HealthCheckRequest(this);
}
/// <summary>Field number for the "service" field.</summary>
public const int ServiceFieldNumber = 1;
private string service_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Service {
get { return service_; }
set {
service_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as HealthCheckRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(HealthCheckRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Service != other.Service) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Service.Length != 0) hash ^= Service.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Service.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Service);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Service.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Service);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(HealthCheckRequest other) {
if (other == null) {
return;
}
if (other.Service.Length != 0) {
Service = other.Service;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Service = input.ReadString();
break;
}
}
}
}
}
public sealed partial class HealthCheckResponse : pb::IMessage<HealthCheckResponse> {
private static readonly pb::MessageParser<HealthCheckResponse> _parser = new pb::MessageParser<HealthCheckResponse>(() => new HealthCheckResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<HealthCheckResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Grpc.Health.V1.HealthReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public HealthCheckResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public HealthCheckResponse(HealthCheckResponse other) : this() {
status_ = other.status_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public HealthCheckResponse Clone() {
return new HealthCheckResponse(this);
}
/// <summary>Field number for the "status" field.</summary>
public const int StatusFieldNumber = 1;
private global::Grpc.Health.V1.HealthCheckResponse.Types.ServingStatus status_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Grpc.Health.V1.HealthCheckResponse.Types.ServingStatus Status {
get { return status_; }
set {
status_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as HealthCheckResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(HealthCheckResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Status != other.Status) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Status != 0) hash ^= Status.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Status != 0) {
output.WriteRawTag(8);
output.WriteEnum((int) Status);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Status != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Status);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(HealthCheckResponse other) {
if (other == null) {
return;
}
if (other.Status != 0) {
Status = other.Status;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
status_ = (global::Grpc.Health.V1.HealthCheckResponse.Types.ServingStatus) input.ReadEnum();
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the HealthCheckResponse message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
public enum ServingStatus {
[pbr::OriginalName("UNKNOWN")] Unknown = 0,
[pbr::OriginalName("SERVING")] Serving = 1,
[pbr::OriginalName("NOT_SERVING")] NotServing = 2,
}
}
#endregion
}
#endregion
}
#endregion Designer generated code
| |
// Copyright (C) 2014 dot42
//
// Original filename: Org.Apache.Http.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 Org.Apache.Http.Util
{
/// <summary>
/// <para>A set of utility methods to help produce consistent equals and hashCode methods.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/util/LangUtils
/// </java-name>
[Dot42.DexImport("org/apache/http/util/LangUtils", AccessFlags = 49)]
public sealed partial class LangUtils
/* scope: __dot42__ */
{
/// <java-name>
/// HASH_SEED
/// </java-name>
[Dot42.DexImport("HASH_SEED", "I", AccessFlags = 25)]
public const int HASH_SEED = 17;
/// <java-name>
/// HASH_OFFSET
/// </java-name>
[Dot42.DexImport("HASH_OFFSET", "I", AccessFlags = 25)]
public const int HASH_OFFSET = 37;
/// <summary>
/// <para>Disabled default constructor. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal LangUtils() /* MethodBuilder.Create */
{
}
/// <java-name>
/// hashCode
/// </java-name>
[Dot42.DexImport("hashCode", "(II)I", AccessFlags = 9)]
public static int GetHashCode(int int32, int int321) /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// hashCode
/// </java-name>
[Dot42.DexImport("hashCode", "(IZ)I", AccessFlags = 9)]
public static int GetHashCode(int int32, bool boolean) /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// hashCode
/// </java-name>
[Dot42.DexImport("hashCode", "(ILjava/lang/Object;)I", AccessFlags = 9)]
public static int GetHashCode(int int32, object @object) /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// equals
/// </java-name>
[Dot42.DexImport("equals", "(Ljava/lang/Object;Ljava/lang/Object;)Z", AccessFlags = 9)]
public static bool Equals(object @object, object object1) /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// equals
/// </java-name>
[Dot42.DexImport("equals", "([Ljava/lang/Object;[Ljava/lang/Object;)Z", AccessFlags = 9)]
public static bool Equals(object[] @object, object[] object1) /* MethodBuilder.Create */
{
return default(bool);
}
}
/// <summary>
/// <para>A resizable byte array.</para><para><para></para><para></para><title>Revision:</title><para>496070 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/util/ByteArrayBuffer
/// </java-name>
[Dot42.DexImport("org/apache/http/util/ByteArrayBuffer", AccessFlags = 49)]
public sealed partial class ByteArrayBuffer
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(I)V", AccessFlags = 1)]
public ByteArrayBuffer(int capacity) /* MethodBuilder.Create */
{
}
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "([BII)V", AccessFlags = 1)]
public void Append(sbyte[] b, int off, int len) /* MethodBuilder.Create */
{
}
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "([BII)V", AccessFlags = 1, IgnoreFromJava = true)]
public void Append(byte[] b, int off, int len) /* MethodBuilder.Create */
{
}
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "(I)V", AccessFlags = 1)]
public void Append(int b) /* MethodBuilder.Create */
{
}
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "([CII)V", AccessFlags = 1)]
public void Append(char[] b, int off, int len) /* MethodBuilder.Create */
{
}
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "(Lorg/apache/http/util/CharArrayBuffer;II)V", AccessFlags = 1)]
public void Append(global::Org.Apache.Http.Util.CharArrayBuffer b, int off, int len) /* MethodBuilder.Create */
{
}
/// <java-name>
/// clear
/// </java-name>
[Dot42.DexImport("clear", "()V", AccessFlags = 1)]
public void Clear() /* MethodBuilder.Create */
{
}
/// <java-name>
/// toByteArray
/// </java-name>
[Dot42.DexImport("toByteArray", "()[B", AccessFlags = 1)]
public sbyte[] JavaToByteArray() /* MethodBuilder.Create */
{
return default(sbyte[]);
}
/// <java-name>
/// toByteArray
/// </java-name>
[Dot42.DexImport("toByteArray", "()[B", AccessFlags = 1, IgnoreFromJava = true)]
public byte[] ToByteArray() /* MethodBuilder.Create */
{
return default(byte[]);
}
/// <java-name>
/// byteAt
/// </java-name>
[Dot42.DexImport("byteAt", "(I)I", AccessFlags = 1)]
public int ByteAt(int i) /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// capacity
/// </java-name>
[Dot42.DexImport("capacity", "()I", AccessFlags = 1)]
public int Capacity() /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// length
/// </java-name>
[Dot42.DexImport("length", "()I", AccessFlags = 1)]
public int Length() /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// buffer
/// </java-name>
[Dot42.DexImport("buffer", "()[B", AccessFlags = 1)]
public sbyte[] JavaBuffer() /* MethodBuilder.Create */
{
return default(sbyte[]);
}
/// <java-name>
/// buffer
/// </java-name>
[Dot42.DexImport("buffer", "()[B", AccessFlags = 1, IgnoreFromJava = true)]
public byte[] Buffer() /* MethodBuilder.Create */
{
return default(byte[]);
}
/// <java-name>
/// setLength
/// </java-name>
[Dot42.DexImport("setLength", "(I)V", AccessFlags = 1)]
public void SetLength(int len) /* MethodBuilder.Create */
{
}
/// <java-name>
/// isEmpty
/// </java-name>
[Dot42.DexImport("isEmpty", "()Z", AccessFlags = 1)]
public bool IsEmpty() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// isFull
/// </java-name>
[Dot42.DexImport("isFull", "()Z", AccessFlags = 1)]
public bool IsFull() /* MethodBuilder.Create */
{
return default(bool);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal ByteArrayBuffer() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <summary>
/// <para>The home for utility methods that handle various encoding tasks.</para><para><para>Michael Becke </para><simplesectsep></simplesectsep><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/util/EncodingUtils
/// </java-name>
[Dot42.DexImport("org/apache/http/util/EncodingUtils", AccessFlags = 49)]
public sealed partial class EncodingUtils
/* scope: __dot42__ */
{
/// <summary>
/// <para>This class should not be instantiated. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal EncodingUtils() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Converts the byte array of HTTP content characters to a string. If the specified charset is not supported, default system encoding is used.</para><para></para>
/// </summary>
/// <returns>
/// <para>The result of the conversion. </para>
/// </returns>
/// <java-name>
/// getString
/// </java-name>
[Dot42.DexImport("getString", "([BIILjava/lang/String;)Ljava/lang/String;", AccessFlags = 9)]
public static string GetString(sbyte[] data, int offset, int length, string charset) /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Converts the byte array of HTTP content characters to a string. If the specified charset is not supported, default system encoding is used.</para><para></para>
/// </summary>
/// <returns>
/// <para>The result of the conversion. </para>
/// </returns>
/// <java-name>
/// getString
/// </java-name>
[Dot42.DexImport("getString", "([BIILjava/lang/String;)Ljava/lang/String;", AccessFlags = 9, IgnoreFromJava = true)]
public static string GetString(byte[] data, int offset, int length, string charset) /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Converts the byte array of HTTP content characters to a string. If the specified charset is not supported, default system encoding is used.</para><para></para>
/// </summary>
/// <returns>
/// <para>The result of the conversion. </para>
/// </returns>
/// <java-name>
/// getString
/// </java-name>
[Dot42.DexImport("getString", "([BLjava/lang/String;)Ljava/lang/String;", AccessFlags = 9)]
public static string GetString(sbyte[] data, string charset) /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Converts the byte array of HTTP content characters to a string. If the specified charset is not supported, default system encoding is used.</para><para></para>
/// </summary>
/// <returns>
/// <para>The result of the conversion. </para>
/// </returns>
/// <java-name>
/// getString
/// </java-name>
[Dot42.DexImport("getString", "([BLjava/lang/String;)Ljava/lang/String;", AccessFlags = 9, IgnoreFromJava = true)]
public static string GetString(byte[] data, string charset) /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Converts the specified string to a byte array. If the charset is not supported the default system charset is used.</para><para></para>
/// </summary>
/// <returns>
/// <para>The resulting byte array. </para>
/// </returns>
/// <java-name>
/// getBytes
/// </java-name>
[Dot42.DexImport("getBytes", "(Ljava/lang/String;Ljava/lang/String;)[B", AccessFlags = 9)]
public static sbyte[] JavaGetBytes(string data, string charset) /* MethodBuilder.Create */
{
return default(sbyte[]);
}
/// <summary>
/// <para>Converts the specified string to a byte array. If the charset is not supported the default system charset is used.</para><para></para>
/// </summary>
/// <returns>
/// <para>The resulting byte array. </para>
/// </returns>
/// <java-name>
/// getBytes
/// </java-name>
[Dot42.DexImport("getBytes", "(Ljava/lang/String;Ljava/lang/String;)[B", AccessFlags = 9, IgnoreFromJava = true)]
public static byte[] GetBytes(string data, string charset) /* MethodBuilder.Create */
{
return default(byte[]);
}
/// <summary>
/// <para>Converts the specified string to byte array of ASCII characters.</para><para></para>
/// </summary>
/// <returns>
/// <para>The string as a byte array. </para>
/// </returns>
/// <java-name>
/// getAsciiBytes
/// </java-name>
[Dot42.DexImport("getAsciiBytes", "(Ljava/lang/String;)[B", AccessFlags = 9)]
public static sbyte[] JavaGetAsciiBytes(string data) /* MethodBuilder.Create */
{
return default(sbyte[]);
}
/// <summary>
/// <para>Converts the specified string to byte array of ASCII characters.</para><para></para>
/// </summary>
/// <returns>
/// <para>The string as a byte array. </para>
/// </returns>
/// <java-name>
/// getAsciiBytes
/// </java-name>
[Dot42.DexImport("getAsciiBytes", "(Ljava/lang/String;)[B", AccessFlags = 9, IgnoreFromJava = true)]
public static byte[] GetAsciiBytes(string data) /* MethodBuilder.Create */
{
return default(byte[]);
}
/// <summary>
/// <para>Converts the byte array of ASCII characters to a string. This method is to be used when decoding content of HTTP elements (such as response headers)</para><para></para>
/// </summary>
/// <returns>
/// <para>The string representation of the byte array </para>
/// </returns>
/// <java-name>
/// getAsciiString
/// </java-name>
[Dot42.DexImport("getAsciiString", "([BII)Ljava/lang/String;", AccessFlags = 9)]
public static string GetAsciiString(sbyte[] data, int offset, int length) /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Converts the byte array of ASCII characters to a string. This method is to be used when decoding content of HTTP elements (such as response headers)</para><para></para>
/// </summary>
/// <returns>
/// <para>The string representation of the byte array </para>
/// </returns>
/// <java-name>
/// getAsciiString
/// </java-name>
[Dot42.DexImport("getAsciiString", "([BII)Ljava/lang/String;", AccessFlags = 9, IgnoreFromJava = true)]
public static string GetAsciiString(byte[] data, int offset, int length) /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Converts the byte array of ASCII characters to a string. This method is to be used when decoding content of HTTP elements (such as response headers)</para><para></para>
/// </summary>
/// <returns>
/// <para>The string representation of the byte array </para>
/// </returns>
/// <java-name>
/// getAsciiString
/// </java-name>
[Dot42.DexImport("getAsciiString", "([B)Ljava/lang/String;", AccessFlags = 9)]
public static string GetAsciiString(sbyte[] data) /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Converts the byte array of ASCII characters to a string. This method is to be used when decoding content of HTTP elements (such as response headers)</para><para></para>
/// </summary>
/// <returns>
/// <para>The string representation of the byte array </para>
/// </returns>
/// <java-name>
/// getAsciiString
/// </java-name>
[Dot42.DexImport("getAsciiString", "([B)Ljava/lang/String;", AccessFlags = 9, IgnoreFromJava = true)]
public static string GetAsciiString(byte[] data) /* MethodBuilder.Create */
{
return default(string);
}
}
/// <summary>
/// <para>Static helpers for dealing with entities.</para><para><para></para><para></para><title>Revision:</title><para>569637 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/util/EntityUtils
/// </java-name>
[Dot42.DexImport("org/apache/http/util/EntityUtils", AccessFlags = 49)]
public sealed partial class EntityUtils
/* scope: __dot42__ */
{
/// <summary>
/// <para>Disabled default constructor. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal EntityUtils() /* MethodBuilder.Create */
{
}
/// <java-name>
/// toByteArray
/// </java-name>
[Dot42.DexImport("toByteArray", "(Lorg/apache/http/HttpEntity;)[B", AccessFlags = 9)]
public static sbyte[] JavaToByteArray(global::Org.Apache.Http.IHttpEntity entity) /* MethodBuilder.Create */
{
return default(sbyte[]);
}
/// <java-name>
/// toByteArray
/// </java-name>
[Dot42.DexImport("toByteArray", "(Lorg/apache/http/HttpEntity;)[B", AccessFlags = 9, IgnoreFromJava = true)]
public static byte[] ToByteArray(global::Org.Apache.Http.IHttpEntity entity) /* MethodBuilder.Create */
{
return default(byte[]);
}
/// <java-name>
/// getContentCharSet
/// </java-name>
[Dot42.DexImport("getContentCharSet", "(Lorg/apache/http/HttpEntity;)Ljava/lang/String;", AccessFlags = 9)]
public static string GetContentCharSet(global::Org.Apache.Http.IHttpEntity entity) /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "(Lorg/apache/http/HttpEntity;Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 9)]
public static string ToString(global::Org.Apache.Http.IHttpEntity entity, string defaultCharset) /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "(Lorg/apache/http/HttpEntity;)Ljava/lang/String;", AccessFlags = 9)]
public static string ToString(global::Org.Apache.Http.IHttpEntity entity) /* MethodBuilder.Create */
{
return default(string);
}
}
/// <summary>
/// <para>The home for utility methods that handle various exception-related tasks.</para><para><para> </para><simplesectsep></simplesectsep><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/util/ExceptionUtils
/// </java-name>
[Dot42.DexImport("org/apache/http/util/ExceptionUtils", AccessFlags = 49)]
public sealed partial class ExceptionUtils
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal ExceptionUtils() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>If we're running on JDK 1.4 or later, initialize the cause for the given throwable.</para><para></para>
/// </summary>
/// <java-name>
/// initCause
/// </java-name>
[Dot42.DexImport("initCause", "(Ljava/lang/Throwable;Ljava/lang/Throwable;)V", AccessFlags = 9)]
public static void InitCause(global::System.Exception throwable, global::System.Exception cause) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>Provides access to version information for HTTP components. Instances of this class provide version information for a single module or informal unit, as explained . Static methods are used to extract version information from property files that are automatically packaged with HTTP component release JARs. <br></br> All available version information is provided in strings, where the string format is informal and subject to change without notice. Version information is provided for debugging output and interpretation by humans, not for automated processing in applications.</para><para><para> </para><simplesectsep></simplesectsep><para>and others </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/util/VersionInfo
/// </java-name>
[Dot42.DexImport("org/apache/http/util/VersionInfo", AccessFlags = 33)]
public partial class VersionInfo
/* scope: __dot42__ */
{
/// <summary>
/// <para>A string constant for unavailable information. </para>
/// </summary>
/// <java-name>
/// UNAVAILABLE
/// </java-name>
[Dot42.DexImport("UNAVAILABLE", "Ljava/lang/String;", AccessFlags = 25)]
public const string UNAVAILABLE = "UNAVAILABLE";
/// <summary>
/// <para>The filename of the version information files. </para>
/// </summary>
/// <java-name>
/// VERSION_PROPERTY_FILE
/// </java-name>
[Dot42.DexImport("VERSION_PROPERTY_FILE", "Ljava/lang/String;", AccessFlags = 25)]
public const string VERSION_PROPERTY_FILE = "version.properties";
/// <java-name>
/// PROPERTY_MODULE
/// </java-name>
[Dot42.DexImport("PROPERTY_MODULE", "Ljava/lang/String;", AccessFlags = 25)]
public const string PROPERTY_MODULE = "info.module";
/// <java-name>
/// PROPERTY_RELEASE
/// </java-name>
[Dot42.DexImport("PROPERTY_RELEASE", "Ljava/lang/String;", AccessFlags = 25)]
public const string PROPERTY_RELEASE = "info.release";
/// <java-name>
/// PROPERTY_TIMESTAMP
/// </java-name>
[Dot42.DexImport("PROPERTY_TIMESTAMP", "Ljava/lang/String;", AccessFlags = 25)]
public const string PROPERTY_TIMESTAMP = "info.timestamp";
/// <summary>
/// <para>Instantiates version information.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/la" +
"ng/String;)V", AccessFlags = 4)]
protected internal VersionInfo(string pckg, string module, string release, string time, string clsldr) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Obtains the package name. The package name identifies the module or informal unit.</para><para></para>
/// </summary>
/// <returns>
/// <para>the package name, never <code>null</code> </para>
/// </returns>
/// <java-name>
/// getPackage
/// </java-name>
[Dot42.DexImport("getPackage", "()Ljava/lang/String;", AccessFlags = 17)]
public string GetPackage() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Obtains the name of the versioned module or informal unit. This data is read from the version information for the package.</para><para></para>
/// </summary>
/// <returns>
/// <para>the module name, never <code>null</code> </para>
/// </returns>
/// <java-name>
/// getModule
/// </java-name>
[Dot42.DexImport("getModule", "()Ljava/lang/String;", AccessFlags = 17)]
public string GetModule() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Obtains the release of the versioned module or informal unit. This data is read from the version information for the package.</para><para></para>
/// </summary>
/// <returns>
/// <para>the release version, never <code>null</code> </para>
/// </returns>
/// <java-name>
/// getRelease
/// </java-name>
[Dot42.DexImport("getRelease", "()Ljava/lang/String;", AccessFlags = 17)]
public string GetRelease() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Obtains the timestamp of the versioned module or informal unit. This data is read from the version information for the package.</para><para></para>
/// </summary>
/// <returns>
/// <para>the timestamp, never <code>null</code> </para>
/// </returns>
/// <java-name>
/// getTimestamp
/// </java-name>
[Dot42.DexImport("getTimestamp", "()Ljava/lang/String;", AccessFlags = 17)]
public string GetTimestamp() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Obtains the classloader used to read the version information. This is just the <code>toString</code> output of the classloader, since the version information should not keep a reference to the classloader itself. That could prevent garbage collection.</para><para></para>
/// </summary>
/// <returns>
/// <para>the classloader description, never <code>null</code> </para>
/// </returns>
/// <java-name>
/// getClassloader
/// </java-name>
[Dot42.DexImport("getClassloader", "()Ljava/lang/String;", AccessFlags = 17)]
public string GetClassloader() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Provides the version information in human-readable format.</para><para></para>
/// </summary>
/// <returns>
/// <para>a string holding this version information </para>
/// </returns>
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// loadVersionInfo
/// </java-name>
[Dot42.DexImport("loadVersionInfo", "([Ljava/lang/String;Ljava/lang/ClassLoader;)[Lorg/apache/http/util/VersionInfo;", AccessFlags = 25)]
public static global::Org.Apache.Http.Util.VersionInfo[] LoadVersionInfo(string[] @string, global::Java.Lang.ClassLoader classLoader) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Util.VersionInfo[]);
}
/// <java-name>
/// loadVersionInfo
/// </java-name>
[Dot42.DexImport("loadVersionInfo", "(Ljava/lang/String;Ljava/lang/ClassLoader;)Lorg/apache/http/util/VersionInfo;", AccessFlags = 25)]
public static global::Org.Apache.Http.Util.VersionInfo LoadVersionInfo(string @string, global::Java.Lang.ClassLoader classLoader) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Util.VersionInfo);
}
/// <summary>
/// <para>Instantiates version information from properties.</para><para></para>
/// </summary>
/// <returns>
/// <para>the version information </para>
/// </returns>
/// <java-name>
/// fromMap
/// </java-name>
[Dot42.DexImport("fromMap", "(Ljava/lang/String;Ljava/util/Map;Ljava/lang/ClassLoader;)Lorg/apache/http/util/V" +
"ersionInfo;", AccessFlags = 28)]
protected internal static global::Org.Apache.Http.Util.VersionInfo FromMap(string pckg, global::Java.Util.IMap<object, object> info, global::Java.Lang.ClassLoader clsldr) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Util.VersionInfo);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal VersionInfo() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para>Obtains the package name. The package name identifies the module or informal unit.</para><para></para>
/// </summary>
/// <returns>
/// <para>the package name, never <code>null</code> </para>
/// </returns>
/// <java-name>
/// getPackage
/// </java-name>
public string Package
{
[Dot42.DexImport("getPackage", "()Ljava/lang/String;", AccessFlags = 17)]
get{ return GetPackage(); }
}
/// <summary>
/// <para>Obtains the name of the versioned module or informal unit. This data is read from the version information for the package.</para><para></para>
/// </summary>
/// <returns>
/// <para>the module name, never <code>null</code> </para>
/// </returns>
/// <java-name>
/// getModule
/// </java-name>
public string Module
{
[Dot42.DexImport("getModule", "()Ljava/lang/String;", AccessFlags = 17)]
get{ return GetModule(); }
}
/// <summary>
/// <para>Obtains the release of the versioned module or informal unit. This data is read from the version information for the package.</para><para></para>
/// </summary>
/// <returns>
/// <para>the release version, never <code>null</code> </para>
/// </returns>
/// <java-name>
/// getRelease
/// </java-name>
public string Release
{
[Dot42.DexImport("getRelease", "()Ljava/lang/String;", AccessFlags = 17)]
get{ return GetRelease(); }
}
/// <summary>
/// <para>Obtains the timestamp of the versioned module or informal unit. This data is read from the version information for the package.</para><para></para>
/// </summary>
/// <returns>
/// <para>the timestamp, never <code>null</code> </para>
/// </returns>
/// <java-name>
/// getTimestamp
/// </java-name>
public string Timestamp
{
[Dot42.DexImport("getTimestamp", "()Ljava/lang/String;", AccessFlags = 17)]
get{ return GetTimestamp(); }
}
/// <summary>
/// <para>Obtains the classloader used to read the version information. This is just the <code>toString</code> output of the classloader, since the version information should not keep a reference to the classloader itself. That could prevent garbage collection.</para><para></para>
/// </summary>
/// <returns>
/// <para>the classloader description, never <code>null</code> </para>
/// </returns>
/// <java-name>
/// getClassloader
/// </java-name>
public string Classloader
{
[Dot42.DexImport("getClassloader", "()Ljava/lang/String;", AccessFlags = 17)]
get{ return GetClassloader(); }
}
}
/// <summary>
/// <para>A resizable char array.</para><para><para></para><para></para><title>Revision:</title><para>496070 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/util/CharArrayBuffer
/// </java-name>
[Dot42.DexImport("org/apache/http/util/CharArrayBuffer", AccessFlags = 49)]
public sealed partial class CharArrayBuffer
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(I)V", AccessFlags = 1)]
public CharArrayBuffer(int capacity) /* MethodBuilder.Create */
{
}
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "([CII)V", AccessFlags = 1)]
public void Append(char[] b, int off, int len) /* MethodBuilder.Create */
{
}
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "(Ljava/lang/String;)V", AccessFlags = 1)]
public void Append(string b) /* MethodBuilder.Create */
{
}
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "(Lorg/apache/http/util/CharArrayBuffer;II)V", AccessFlags = 1)]
public void Append(global::Org.Apache.Http.Util.CharArrayBuffer b, int off, int len) /* MethodBuilder.Create */
{
}
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "(Lorg/apache/http/util/CharArrayBuffer;)V", AccessFlags = 1)]
public void Append(global::Org.Apache.Http.Util.CharArrayBuffer b) /* MethodBuilder.Create */
{
}
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "(C)V", AccessFlags = 1)]
public void Append(char b) /* MethodBuilder.Create */
{
}
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "([BII)V", AccessFlags = 1)]
public void Append(sbyte[] b, int off, int len) /* MethodBuilder.Create */
{
}
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "([BII)V", AccessFlags = 1, IgnoreFromJava = true)]
public void Append(byte[] b, int off, int len) /* MethodBuilder.Create */
{
}
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "(Lorg/apache/http/util/ByteArrayBuffer;II)V", AccessFlags = 1)]
public void Append(global::Org.Apache.Http.Util.ByteArrayBuffer b, int off, int len) /* MethodBuilder.Create */
{
}
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "(Ljava/lang/Object;)V", AccessFlags = 1)]
public void Append(object b) /* MethodBuilder.Create */
{
}
/// <java-name>
/// clear
/// </java-name>
[Dot42.DexImport("clear", "()V", AccessFlags = 1)]
public void Clear() /* MethodBuilder.Create */
{
}
/// <java-name>
/// toCharArray
/// </java-name>
[Dot42.DexImport("toCharArray", "()[C", AccessFlags = 1)]
public char[] ToCharArray() /* MethodBuilder.Create */
{
return default(char[]);
}
/// <java-name>
/// charAt
/// </java-name>
[Dot42.DexImport("charAt", "(I)C", AccessFlags = 1)]
public char CharAt(int i) /* MethodBuilder.Create */
{
return default(char);
}
/// <java-name>
/// buffer
/// </java-name>
[Dot42.DexImport("buffer", "()[C", AccessFlags = 1)]
public char[] Buffer() /* MethodBuilder.Create */
{
return default(char[]);
}
/// <java-name>
/// capacity
/// </java-name>
[Dot42.DexImport("capacity", "()I", AccessFlags = 1)]
public int Capacity() /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// length
/// </java-name>
[Dot42.DexImport("length", "()I", AccessFlags = 1)]
public int Length() /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// ensureCapacity
/// </java-name>
[Dot42.DexImport("ensureCapacity", "(I)V", AccessFlags = 1)]
public void EnsureCapacity(int required) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setLength
/// </java-name>
[Dot42.DexImport("setLength", "(I)V", AccessFlags = 1)]
public void SetLength(int len) /* MethodBuilder.Create */
{
}
/// <java-name>
/// isEmpty
/// </java-name>
[Dot42.DexImport("isEmpty", "()Z", AccessFlags = 1)]
public bool IsEmpty() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// isFull
/// </java-name>
[Dot42.DexImport("isFull", "()Z", AccessFlags = 1)]
public bool IsFull() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// indexOf
/// </java-name>
[Dot42.DexImport("indexOf", "(III)I", AccessFlags = 1)]
public int IndexOf(int ch, int beginIndex, int endIndex) /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// indexOf
/// </java-name>
[Dot42.DexImport("indexOf", "(I)I", AccessFlags = 1)]
public int IndexOf(int ch) /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// substring
/// </java-name>
[Dot42.DexImport("substring", "(II)Ljava/lang/String;", AccessFlags = 1)]
public string Substring(int beginIndex, int endIndex) /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// substringTrimmed
/// </java-name>
[Dot42.DexImport("substringTrimmed", "(II)Ljava/lang/String;", AccessFlags = 1)]
public string SubstringTrimmed(int beginIndex, int endIndex) /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal CharArrayBuffer() /* TypeBuilder.AddDefaultConstructor */
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
namespace ETLStackBrowse
{
public partial class ETLTrace
{
// common field indexes in memory records
private const int fldProcessNamePID = 2;
private const int fldMemBaseAddr = 3;
private const int fldMemEndAddr = 4;
private const int fldFlags = 5;
// common field indexes for image start/end records
private const int fldImageBaseAddr = 3;
private const int fldImageEndAddr = 4;
private const int fldImageFileName = 8;
public const int memoryPlotColumns = 80;
public const int memoryPlotRows = standardPlotRows;
public class MemInfo
{
public uint cReserved;
public ulong cbReserved;
public uint cCommitted;
public ulong cbCommitted;
public uint cDecommitted;
public ulong cbDecommitted;
public uint cReleased;
public ulong cbReleased;
public byte[] processPid;
public RangeSet rsCommitted = new RangeSet();
public RangeSet rsReserved = new RangeSet();
public long[] reservedDistribution = new long[memoryPlotColumns];
public long[] committedDistribution = new long[memoryPlotColumns];
internal void Reset()
{
cReserved = 0;
cbReserved = 0;
cCommitted = 0;
cbCommitted = 0;
cDecommitted = 0;
cbDecommitted = 0;
cReleased = 0;
cbReleased = 0;
}
public MemInfo(byte[] processPid)
{
this.processPid = processPid;
}
}
private MemProcessor lastMemProcessor = null;
public MemProcessor LastMemProcessor
{
get { return lastMemProcessor; }
}
public string ComputeMemory(int intervals, bool fDumpRanges)
{
bool fFilterProcesses = itparms.EnableProcessFilter;
StringWriter sw = new StringWriter();
var mem = new MemProcessor(this);
ETWLineReader l = StandardLineReader();
long tDelta = (l.t1 - l.t0) / intervals;
long tStart = l.t0;
long tNext = l.t0 + tDelta;
int iInterval = 0;
bool fOut = false;
MemEffect effect = new MemEffect();
foreach (ByteWindow b in l.Lines())
{
if (l.t > tNext && iInterval < intervals - 1)
{
if (!mem.IsEmpty)
{
fOut = true;
DumpRangeTime(sw, tStart, tNext);
sw.WriteLine(mem.Dump());
}
mem.Reset();
tStart = tNext;
tNext += tDelta;
}
if (l.idType != mem.idAlloc && l.idType != mem.idFree)
{
continue;
}
if (fFilterProcesses && !l.MatchingProcess())
{
continue;
}
if (!l.MatchingTextFilter())
{
continue;
}
if (!l.MatchingMemory())
{
continue;
}
mem.ProcessMemRecord(l, b, effect);
}
if (!mem.IsEmpty)
{
fOut = true;
DumpRangeTime(sw, tStart, l.t1);
sw.WriteLine(mem.Dump());
}
sw.WriteLine(mem.DumpMemoryPlots());
if (fOut)
{
if (fDumpRanges)
{
sw.WriteLine();
sw.WriteLine(mem.DumpRanges());
}
}
else
{
sw.WriteLine("No activity");
}
lastMemProcessor = mem;
return sw.ToString();
}
private void DumpRangeTime(StringWriter sw, long tStart, long tEnd)
{
sw.WriteLine();
sw.WriteLine("Summary for time range {0:n0} to {1:n0}", tStart, tEnd);
sw.WriteLine();
}
public class MemEffect
{
public ulong reserved;
public ulong committed;
public ulong decommitted;
public ulong released;
}
public class MemProcessor
{
private ByteWindow bT = new ByteWindow();
public int idAlloc;
public int idFree;
private byte[] byRelease = ByteWindow.MakeBytes("RELEASE");
private byte[] byReserve = ByteWindow.MakeBytes("RESERVE");
private byte[] byCommit = ByteWindow.MakeBytes("COMMIT");
private byte[] byDecommit = ByteWindow.MakeBytes("DECOMMIT");
private byte[] byReserveCommit = ByteWindow.MakeBytes("RESERVE COMMIT");
private ETLTrace trace;
public MemInfo[] memInfos;
public MemProcessor(ETLTrace trace)
{
this.trace = trace;
idAlloc = trace.atomsRecords.Lookup("VirtualAlloc");
idFree = trace.atomsRecords.Lookup("VirtualFree");
memInfos = new MemInfo[trace.atomsProcesses.Count];
Reset();
}
public void Reset()
{
for (int i = 0; i < memInfos.Length; i++)
{
if (memInfos[i] == null)
{
memInfos[i] = new MemInfo(trace.processes[i].processPid);
}
else
{
memInfos[i].Reset();
}
}
}
public void ProcessMemRecord(ETWLineReader l, ByteWindow b, MemEffect memeffect)
{
// empty the net effect of this record
memeffect.released = memeffect.reserved = memeffect.committed = memeffect.decommitted = 0;
int interval = (int)((l.t - l.t0) / (double)(l.t1 - l.t0) * memoryPlotColumns);
// the above can overflow because time ranges might be out of order so clamp any overflows
// also we have to handle the case where l.t == l.t1 which would otherwise overflow
if (interval < 0)
{
interval = 0;
}
if (interval >= memoryPlotColumns)
{
interval = memoryPlotColumns - 1;
}
bT.Assign(b, fldProcessNamePID).Trim();
int idProcess = trace.atomsProcesses.Lookup(bT);
// bogus process, disregard
if (idProcess == -1)
{
return;
}
MemInfo p = memInfos[idProcess];
var rsReserved = p.rsReserved;
var rsCommitted = p.rsCommitted;
ulong addrBase = b.GetHex(fldMemBaseAddr);
ulong addrEnd = b.GetHex(fldMemEndAddr);
b.Field(fldFlags).Trim();
if (l.idType == idAlloc)
{
if (b.StartsWith(byReserveCommit))
{
memeffect.reserved = rsReserved.AddRange(addrBase, addrEnd);
p.cbReserved += memeffect.reserved;
p.reservedDistribution[interval] += (long)memeffect.reserved;
if (memeffect.reserved != 0)
{
p.cReserved++;
}
memeffect.committed = rsCommitted.AddRange(addrBase, addrEnd);
p.cbCommitted += memeffect.committed;
p.committedDistribution[interval] += (long)memeffect.committed;
if (memeffect.committed != 0)
{
p.cCommitted++;
}
}
else if (b.StartsWith(byReserve))
{
memeffect.reserved = rsReserved.AddRange(addrBase, addrEnd);
p.cbReserved += memeffect.reserved;
p.reservedDistribution[interval] += (long)memeffect.reserved;
if (memeffect.reserved != 0)
{
p.cReserved++;
}
}
else if (b.StartsWith(byCommit))
{
memeffect.committed = rsCommitted.AddRange(addrBase, addrEnd);
p.cbCommitted += memeffect.committed;
p.committedDistribution[interval] += (long)memeffect.committed;
if (memeffect.committed != 0)
{
p.cCommitted++;
}
}
}
if (l.idType == idFree)
{
if (b.StartsWith(byRelease))
{
memeffect.decommitted = rsCommitted.RemoveRange(addrBase, addrEnd);
p.cbDecommitted += memeffect.decommitted;
p.committedDistribution[interval] -= (long)memeffect.decommitted;
if (memeffect.decommitted != 0)
{
p.cDecommitted++;
}
memeffect.released = rsReserved.RemoveRange(addrBase, addrEnd);
p.cbReleased += memeffect.released;
p.reservedDistribution[interval] -= (long)memeffect.released;
if (memeffect.released != 0)
{
p.cReleased++;
}
}
else if (b.StartsWith(byDecommit))
{
memeffect.decommitted = rsCommitted.RemoveRange(addrBase, addrEnd);
p.cbDecommitted += memeffect.decommitted;
p.committedDistribution[interval] -= (long)memeffect.decommitted;
if (memeffect.decommitted != 0)
{
p.cDecommitted++;
}
}
}
}
public string DumpMemoryPlots()
{
if (sortedMemInfos == null || sortedMemInfos.Length < 1)
{
return "";
}
StringWriter sw = new StringWriter();
sw.WriteLine();
sw.WriteLine("VM PLOTS FOR SELECTED PROCESSES");
sw.WriteLine();
int count = 0;
foreach (int ipi in sortedMemInfos)
{
MemInfo p = memInfos[ipi];
if (p.cCommitted == 0 && p.cDecommitted == 0 && p.cReleased == 0 && p.cReserved == 0)
{
continue;
}
sw.WriteLine();
sw.WriteLine();
string xLabel = String.Format("Usage from {0}", ByteWindow.MakeString(p.processPid));
string yLabel = "Reserved Bytes";
sw.WriteLine(FormatOnePlot(memoryPlotRows, memoryPlotColumns, xLabel, yLabel, p.reservedDistribution));
sw.WriteLine();
sw.WriteLine();
xLabel = String.Format("Usage from {0}", ByteWindow.MakeString(p.processPid));
yLabel = "Committed Bytes";
sw.WriteLine(FormatOnePlot(memoryPlotRows, memoryPlotColumns, xLabel, yLabel, p.committedDistribution));
count++;
if (count >= 3)
{
break;
}
}
return sw.ToString();
}
public string DumpRanges()
{
StringWriter sw = new StringWriter();
foreach (int ipi in sortedMemInfos)
{
MemInfo p = memInfos[ipi];
if (p.cCommitted == 0 && p.cDecommitted == 0 && p.cReleased == 0 && p.cReserved == 0)
{
continue;
}
sw.WriteLine("Live ranges for {0}", ByteWindow.MakeString(p.processPid));
sw.WriteLine();
sw.WriteLine("RESERVED ({0} ranges)", p.rsReserved.RangeCount);
sw.WriteLine();
sw.WriteLine(p.rsReserved.Dump());
sw.WriteLine();
sw.WriteLine("COMMITTED ({0} ranges)", p.rsCommitted.RangeCount);
sw.WriteLine();
sw.WriteLine(p.rsCommitted.Dump());
sw.WriteLine();
}
return sw.ToString();
}
public int[] sortedMemInfos;
public bool IsEmpty
{
get
{
foreach (MemInfo p in memInfos)
{
if (p.cCommitted != 0 || p.cDecommitted != 0 || p.cReleased != 0 || p.cReserved != 0)
{
return false;
}
}
return true;
}
}
public string Dump()
{
StringWriter sw = new StringWriter();
SortMemInfos();
sw.WriteLine("VM CHANGES IN THIS INTERVAL");
sw.WriteLine();
sw.WriteLine("{8,-35} {0,14} {1,14} {2,14} {3,14} {4,14} {5,14} {6,14} {7,14}",
"Reserved", "Count",
"Committed", "Count",
"Decomitt", "Count",
"Released", "Count",
"Process");
sw.WriteLine("{8,-35} {0,14} {1,14} {2,14} {3,14} {4,14} {5,14} {6,14} {7,14}",
"---------", "-----",
"---------", "-----",
"--------", "-----",
"--------", "-----",
"-------");
foreach (int ipi in sortedMemInfos)
{
MemInfo p = memInfos[ipi];
if (p.cCommitted == 0 && p.cDecommitted == 0 && p.cReleased == 0 && p.cReserved == 0)
{
continue;
}
sw.WriteLine("{8,-35} {0,14:n0} {1,14:n0} {2,14:n0} {3,14:n0} {4,14:n0} {5,14:n0} {6,14:n0} {7,14:n0}"
, p.cbReserved
, p.cReserved
, p.cbCommitted
, p.cCommitted
, p.cbDecommitted
, p.cDecommitted
, p.cbReleased
, p.cReleased
, ByteWindow.MakeString(p.processPid)
);
}
sw.WriteLine();
sw.WriteLine("VM ALLOCATED AT END OF THIS INTERVAL");
sw.WriteLine();
sw.WriteLine("{4,-35} {0,14} {1,14} {2,14} {3,14}",
"Reserved", "Ranges",
"Committed", "Ranges",
"Process");
sw.WriteLine("{4,-35} {0,14} {1,14} {2,14} {3,14}",
"--------", "------",
"---------", "------",
"-------");
foreach (int ipi in sortedMemInfos)
{
MemInfo p = memInfos[ipi];
if (p.cCommitted == 0 && p.cDecommitted == 0 && p.cReleased == 0 && p.cReserved == 0)
{
continue;
}
sw.WriteLine("{4,-35} {0,14:n0} {1,14:n0} {2,14:n0} {3,14:n0}"
, p.rsReserved.Count
, p.rsReserved.RangeCount
, p.rsCommitted.Count
, p.rsCommitted.RangeCount
, ByteWindow.MakeString(p.processPid)
);
}
return sw.ToString();
}
private void SortMemInfos()
{
sortedMemInfos = new int[memInfos.Length];
for (int i = 0; i < sortedMemInfos.Length; i++)
{
sortedMemInfos[i] = i;
}
Array.Sort<int>(sortedMemInfos, delegate (int i, int j)
{
MemInfo a = memInfos[i];
MemInfo b = memInfos[j];
if (a.cbCommitted > b.cbCommitted)
{
return -1;
}
if (a.cbCommitted < b.cbCommitted)
{
return 1;
}
return 0;
}
);
}
}
}
public struct Range
{
public ulong lo;
public ulong hi;
}
public class RangeSet
{
private List<Range> ranges = new List<Range>();
public ulong AddRange(ulong lo, ulong hi)
{
// start with the base count, we'll subtract the overlaps to find the net size change
ulong count = hi - lo;
int iExtended = -1;
if (count == 0)
{
return 0;
}
int i = FirstAffectedRange(lo); ;
for (; i < ranges.Count; i++)
{
Range rMerge = ranges[i];
// this item is before the range
if (rMerge.hi < lo)
{
continue;
}
// this item is after the range, stop here
if (rMerge.lo > hi)
{
break;
}
// ok there is some overlap, so we have to do something
ulong olo = Math.Max(lo, rMerge.lo);
ulong ohi = Math.Min(hi, rMerge.hi);
ulong overlap = ohi - olo;
count -= overlap;
if (iExtended < 0)
{
rMerge.lo = Math.Min(lo, rMerge.lo);
rMerge.hi = Math.Max(hi, rMerge.hi);
// this is the first item that overlaps so we're going to extend it
ranges[i] = rMerge;
iExtended = i;
}
else
{
rMerge.lo = ranges[iExtended].lo;
rMerge.hi = Math.Max(hi, rMerge.hi);
// we have already extended something to cover the range so now what we're going to do is
// remove this guy and further extend the previous item
ranges[iExtended] = rMerge;
ranges.RemoveAt(i);
i--; // process i again, now that something has been removed
}
}
// add it
if (iExtended < 0)
{
var rNew = new Range();
rNew.lo = lo;
rNew.hi = hi;
ranges.Insert(i, rNew);
}
return count;
}
public void AddRangesFromString(string str)
{
StringReader sr = new StringReader(str);
string line = null;
char[] spacetab = new char[] { ' ', '\t' };
while ((line = sr.ReadLine()) != null)
{
line = line.Trim();
int ich = line.IndexOfAny(spacetab);
if (ich < 0)
{
continue;
}
ulong start = ETLTrace.ParseHex(line, 0);
ulong end = ETLTrace.ParseHex(line, ich);
if (start >= end)
{
continue;
}
AddRange(start, end);
}
}
public void AddRangeSet(RangeSet merge)
{
int c = merge.ranges.Count;
for (int i = 0; i < c; i++)
{
Range r = merge.ranges[i];
AddRange(r.lo, r.hi);
}
}
public void RemoveRangeSet(RangeSet merge)
{
int c = merge.ranges.Count;
for (int i = 0; i < c; i++)
{
Range r = merge.ranges[i];
RemoveRange(r.lo, r.hi);
}
}
public string Dump()
{
StringWriter sw = new StringWriter();
int c = ranges.Count;
for (int i = 0; i < c; i++)
{
Range r = ranges[i];
sw.WriteLine("0x{0:x} 0x{1:x}", r.lo, r.hi);
}
return sw.ToString();
}
public bool Equals(RangeSet rs)
{
int c = ranges.Count;
if (c != rs.ranges.Count)
{
return false;
}
for (int i = 0; i < c; i++)
{
Range r1 = ranges[i];
Range r2 = rs.ranges[i];
if (r1.lo != r2.lo)
{
return false;
}
if (r1.hi != r2.hi)
{
return false;
}
}
return true;
}
public RangeSet Union(RangeSet rs2)
{
RangeSet rOut = new RangeSet();
RangeSet rs1 = this;
int i1 = 0;
int i2 = 0;
// try to add them in order because appending is the fastest
while (i1 < rs1.RangeCount && i2 < rs2.RangeCount)
{
Range r1 = rs1.ranges[i1];
Range r2 = rs2.ranges[i2];
if (r1.hi < r2.hi)
{
rOut.AddRange(r1.lo, r1.hi);
i1++;
}
else
{
rOut.AddRange(r2.lo, r2.hi);
i2++;
}
}
// now add whatever is left, we could have just done this in the first place but we wanted them in order
while (i1 < rs1.RangeCount)
{
Range r1 = rs1.ranges[i1];
rOut.AddRange(r1.lo, r1.hi);
i1++;
}
while (i2 < rs2.RangeCount)
{
Range r2 = rs2.ranges[i2];
rOut.AddRange(r2.lo, r2.hi);
i2++;
}
return rOut;
}
public RangeSet Intersection(RangeSet rs2)
{
RangeSet rOut = new RangeSet();
RangeSet rs1 = this;
int i1 = 0;
int i2 = 0;
while (i1 < rs1.RangeCount && i2 < rs2.RangeCount)
{
Range r1 = rs1.ranges[i1];
Range r2 = rs2.ranges[i2];
ulong olo = Math.Max(r1.lo, r2.lo);
ulong ohi = Math.Min(r1.hi, r2.hi);
// if there is overlap in this section then we emit it
if (olo < ohi)
{
rOut.AddRange(olo, ohi);
}
if (r1.hi < r2.hi)
{
i1++;
}
else
{
i2++;
}
}
return rOut;
}
public ulong RemoveRange(ulong lo, ulong hi)
{
// start with zero and add overlaps to find the net size change
ulong count = 0;
if (lo == hi)
{
return 0;
}
int i = FirstAffectedRange(lo);
for (; i < ranges.Count; i++)
{
Range rMerge = ranges[i];
// this item is before the range
if (rMerge.hi < lo)
{
continue;
}
// this item is after the range, stop here
if (rMerge.lo > hi)
{
break;
}
// ok there is some overlap, so we have to do something
ulong olo = Math.Max(lo, rMerge.lo);
ulong ohi = Math.Min(hi, rMerge.hi);
ulong overlap = ohi - olo;
count += overlap;
if (overlap == rMerge.hi - rMerge.lo)
{
// this region is completely contained in the overlap
ranges.RemoveAt(i);
i--;
}
else if (overlap == (hi - lo) && rMerge.lo != lo && rMerge.hi != hi)
{
// the remove region is completely contained in this range
var rNew = new Range();
rNew.hi = lo;
rNew.lo = rMerge.lo;
ranges[i] = rNew;
rNew.lo = hi;
rNew.hi = rMerge.hi;
ranges.Insert(i + 1, rNew);
break;
}
else if (rMerge.lo < lo)
{
// partial overlap with the first item in a list of overlaps
rMerge.hi = lo;
ranges[i] = rMerge;
}
else
{
// partial overlap with the last item in a list of overlaps
rMerge.lo = hi;
ranges[i] = rMerge;
break;
}
}
return count;
}
public Range RangeAt(int i)
{
return ranges[i];
}
public int RangeCount { get { return ranges.Count; } }
public ulong Count
{
get
{
ulong count = 0;
int c = ranges.Count;
for (int i = 0; i < c; i++)
{
Range r = ranges[i];
count += r.hi - r.lo;
}
return count;
}
}
public string CheckValid()
{
if (RangeCount == 0)
{
return null;
}
ulong lasthi = 0;
for (int i = 0; i < ranges.Count; i++)
{
Range r = ranges[i];
if (r.lo == r.hi)
{
return "range has empty interval";
}
if (r.lo > r.hi)
{
return "range has hi/lo out of order";
}
if (i > 0 && r.lo <= lasthi)
{
return "range has intervals out of order or overlapping";
}
lasthi = r.hi;
}
return null;
}
private int FirstAffectedRange(ulong lo)
{
int c = ranges.Count;
// there's 0 or 1 in the set, just start at the beginning
if (c < 2)
{
return 0;
}
// the first one is already too big, have to start there
if (ranges[0].hi >= lo)
{
return 0;
}
// if we're at the end or past it, then skip it all
if (ranges[c - 1].hi < lo)
{
return c - 1;
}
int index = 0;
int delta = c / 2;
// keep trying to move forward, see if we can do so
while (delta > 0)
{
if (ranges[index + delta].hi < lo)
{
index = index + delta;
}
delta /= 2;
}
// index can be safely skipped, so we can start at index+1
return index + 1;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace System.Security.Principal
{
[Flags]
internal enum PolicyRights
{
POLICY_VIEW_LOCAL_INFORMATION = 0x00000001,
POLICY_VIEW_AUDIT_INFORMATION = 0x00000002,
POLICY_GET_PRIVATE_INFORMATION = 0x00000004,
POLICY_TRUST_ADMIN = 0x00000008,
POLICY_CREATE_ACCOUNT = 0x00000010,
POLICY_CREATE_SECRET = 0x00000020,
POLICY_CREATE_PRIVILEGE = 0x00000040,
POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x00000080,
POLICY_SET_AUDIT_REQUIREMENTS = 0x00000100,
POLICY_AUDIT_LOG_ADMIN = 0x00000200,
POLICY_SERVER_ADMIN = 0x00000400,
POLICY_LOOKUP_NAMES = 0x00000800,
POLICY_NOTIFICATION = 0x00001000,
}
internal static class Win32
{
internal const int FALSE = 0;
//
// Wrapper around advapi32.LsaOpenPolicy
//
internal static SafeLsaPolicyHandle LsaOpenPolicy(
string systemName,
PolicyRights rights)
{
uint ReturnCode;
SafeLsaPolicyHandle Result;
Interop.LSA_OBJECT_ATTRIBUTES Loa;
Loa.Length = Marshal.SizeOf<Interop.LSA_OBJECT_ATTRIBUTES>();
Loa.RootDirectory = IntPtr.Zero;
Loa.ObjectName = IntPtr.Zero;
Loa.Attributes = 0;
Loa.SecurityDescriptor = IntPtr.Zero;
Loa.SecurityQualityOfService = IntPtr.Zero;
if (0 == (ReturnCode = Interop.Advapi32.LsaOpenPolicy(systemName, ref Loa, (int)rights, out Result)))
{
return Result;
}
else if (ReturnCode == Interop.StatusOptions.STATUS_ACCESS_DENIED)
{
throw new UnauthorizedAccessException();
}
else if (ReturnCode == Interop.StatusOptions.STATUS_INSUFFICIENT_RESOURCES ||
ReturnCode == Interop.StatusOptions.STATUS_NO_MEMORY)
{
throw new OutOfMemoryException();
}
else
{
uint win32ErrorCode = Interop.Advapi32.LsaNtStatusToWinError(ReturnCode);
throw new Win32Exception(unchecked((int)win32ErrorCode));
}
}
internal static byte[] ConvertIntPtrSidToByteArraySid(IntPtr binaryForm)
{
byte[] ResultSid;
//
// Verify the revision (just sanity, should never fail to be 1)
//
byte Revision = Marshal.ReadByte(binaryForm, 0);
if (Revision != SecurityIdentifier.Revision)
{
throw new ArgumentException(SR.IdentityReference_InvalidSidRevision, nameof(binaryForm));
}
//
// Need the subauthority count in order to figure out how many bytes to read
//
byte SubAuthorityCount = Marshal.ReadByte(binaryForm, 1);
if (SubAuthorityCount < 0 ||
SubAuthorityCount > SecurityIdentifier.MaxSubAuthorities)
{
throw new ArgumentException(SR.Format(SR.IdentityReference_InvalidNumberOfSubauthorities, SecurityIdentifier.MaxSubAuthorities), nameof(binaryForm));
}
//
// Compute the size of the binary form of this SID and allocate the memory
//
int BinaryLength = 1 + 1 + 6 + SubAuthorityCount * 4;
ResultSid = new byte[BinaryLength];
//
// Extract the data from the returned pointer
//
Marshal.Copy(binaryForm, ResultSid, 0, BinaryLength);
return ResultSid;
}
//
// Wrapper around advapi32.ConvertStringSidToSidW
//
internal static int CreateSidFromString(
string stringSid,
out byte[] resultSid
)
{
int ErrorCode;
IntPtr ByteArray = IntPtr.Zero;
try
{
if (FALSE == Interop.Advapi32.ConvertStringSidToSid(stringSid, out ByteArray))
{
ErrorCode = Marshal.GetLastWin32Error();
goto Error;
}
resultSid = ConvertIntPtrSidToByteArraySid(ByteArray);
}
finally
{
//
// Now is a good time to get rid of the returned pointer
//
Interop.Kernel32.LocalFree(ByteArray);
}
//
// Now invoke the SecurityIdentifier factory method to create the result
//
return Interop.Errors.ERROR_SUCCESS;
Error:
resultSid = null;
return ErrorCode;
}
//
// Wrapper around advapi32.CreateWellKnownSid
//
internal static int CreateWellKnownSid(
WellKnownSidType sidType,
SecurityIdentifier domainSid,
out byte[] resultSid
)
{
//
// Passing an array as big as it can ever be is a small price to pay for
// not having to P/Invoke twice (once to get the buffer, once to get the data)
//
uint length = (uint)SecurityIdentifier.MaxBinaryLength;
resultSid = new byte[length];
if (FALSE != Interop.Advapi32.CreateWellKnownSid((int)sidType, domainSid == null ? null : domainSid.BinaryForm, resultSid, ref length))
{
return Interop.Errors.ERROR_SUCCESS;
}
else
{
resultSid = null;
return Marshal.GetLastWin32Error();
}
}
//
// Wrapper around advapi32.EqualDomainSid
//
internal static bool IsEqualDomainSid(SecurityIdentifier sid1, SecurityIdentifier sid2)
{
if (sid1 == null || sid2 == null)
{
return false;
}
else
{
bool result;
byte[] BinaryForm1 = new byte[sid1.BinaryLength];
sid1.GetBinaryForm(BinaryForm1, 0);
byte[] BinaryForm2 = new byte[sid2.BinaryLength];
sid2.GetBinaryForm(BinaryForm2, 0);
return (Interop.Advapi32.IsEqualDomainSid(BinaryForm1, BinaryForm2, out result) == FALSE ? false : result);
}
}
/// <summary>
/// Setup the size of the buffer Windows provides for an LSA_REFERENCED_DOMAIN_LIST
/// </summary>
internal static void InitializeReferencedDomainsPointer(SafeLsaMemoryHandle referencedDomains)
{
Debug.Assert(referencedDomains != null, "referencedDomains != null");
// We don't know the real size of the referenced domains yet, so we need to set an initial
// size based on the LSA_REFERENCED_DOMAIN_LIST structure, then resize it to include all of
// the domains.
referencedDomains.Initialize((uint)Marshal.SizeOf<Interop.LSA_REFERENCED_DOMAIN_LIST>());
Interop.LSA_REFERENCED_DOMAIN_LIST domainList = referencedDomains.Read<Interop.LSA_REFERENCED_DOMAIN_LIST>(0);
unsafe
{
byte* pRdl = null;
try
{
referencedDomains.AcquirePointer(ref pRdl);
// If there is a trust information list, then the buffer size is the end of that list minus
// the beginning of the domain list. Otherwise, then the buffer is just the size of the
// referenced domain list structure, which is what we defaulted to.
if (domainList.Domains != IntPtr.Zero)
{
Interop.LSA_TRUST_INFORMATION* pTrustInformation = (Interop.LSA_TRUST_INFORMATION*)domainList.Domains;
pTrustInformation = pTrustInformation + domainList.Entries;
long bufferSize = (byte*)pTrustInformation - pRdl;
Debug.Assert(bufferSize > 0, "bufferSize > 0");
referencedDomains.Initialize((ulong)bufferSize);
}
}
finally
{
if (pRdl != null)
referencedDomains.ReleasePointer();
}
}
}
//
// Wrapper around avdapi32.GetWindowsAccountDomainSid
//
internal static int GetWindowsAccountDomainSid(
SecurityIdentifier sid,
out SecurityIdentifier resultSid
)
{
//
// Passing an array as big as it can ever be is a small price to pay for
// not having to P/Invoke twice (once to get the buffer, once to get the data)
//
byte[] BinaryForm = new byte[sid.BinaryLength];
sid.GetBinaryForm(BinaryForm, 0);
uint sidLength = (uint)SecurityIdentifier.MaxBinaryLength;
byte[] resultSidBinary = new byte[sidLength];
if (FALSE != Interop.Advapi32.GetWindowsAccountDomainSid(BinaryForm, resultSidBinary, ref sidLength))
{
resultSid = new SecurityIdentifier(resultSidBinary, 0);
return Interop.Errors.ERROR_SUCCESS;
}
else
{
resultSid = null;
return Marshal.GetLastWin32Error();
}
}
//
// Wrapper around advapi32.IsWellKnownSid
//
internal static bool IsWellKnownSid(
SecurityIdentifier sid,
WellKnownSidType type
)
{
byte[] BinaryForm = new byte[sid.BinaryLength];
sid.GetBinaryForm(BinaryForm, 0);
if (FALSE == Interop.Advapi32.IsWellKnownSid(BinaryForm, (int)type))
{
return false;
}
else
{
return true;
}
}
}
}
| |
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Diagnostics;
using Lucene.Net.Support;
using System;
using System.Runtime.CompilerServices;
namespace Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using ByteBlockPool = Lucene.Net.Util.ByteBlockPool;
using BytesRef = Lucene.Net.Util.BytesRef;
using RamUsageEstimator = Lucene.Net.Util.RamUsageEstimator;
using TermVectorsWriter = Lucene.Net.Codecs.TermVectorsWriter;
internal sealed class TermVectorsConsumerPerField : TermsHashConsumerPerField
{
internal readonly TermsHashPerField termsHashPerField;
internal readonly TermVectorsConsumer termsWriter;
internal readonly FieldInfo fieldInfo;
internal readonly DocumentsWriterPerThread.DocState docState;
internal readonly FieldInvertState fieldState;
internal bool doVectors;
internal bool doVectorPositions;
internal bool doVectorOffsets;
internal bool doVectorPayloads;
internal int maxNumPostings;
internal IOffsetAttribute offsetAttribute;
internal IPayloadAttribute payloadAttribute;
internal bool hasPayloads; // if enabled, and we actually saw any for this field
public TermVectorsConsumerPerField(TermsHashPerField termsHashPerField, TermVectorsConsumer termsWriter, FieldInfo fieldInfo)
{
this.termsHashPerField = termsHashPerField;
this.termsWriter = termsWriter;
this.fieldInfo = fieldInfo;
docState = termsHashPerField.docState;
fieldState = termsHashPerField.fieldState;
}
internal override int StreamCount => 2;
internal override bool Start(IIndexableField[] fields, int count)
{
doVectors = false;
doVectorPositions = false;
doVectorOffsets = false;
doVectorPayloads = false;
hasPayloads = false;
for (int i = 0; i < count; i++)
{
IIndexableField field = fields[i];
if (field.IndexableFieldType.IsIndexed)
{
if (field.IndexableFieldType.StoreTermVectors)
{
doVectors = true;
doVectorPositions |= field.IndexableFieldType.StoreTermVectorPositions;
doVectorOffsets |= field.IndexableFieldType.StoreTermVectorOffsets;
if (doVectorPositions)
{
doVectorPayloads |= field.IndexableFieldType.StoreTermVectorPayloads;
}
else if (field.IndexableFieldType.StoreTermVectorPayloads)
{
// TODO: move this check somewhere else, and impl the other missing ones
throw new ArgumentException("cannot index term vector payloads without term vector positions (field=\"" + field.Name + "\")");
}
}
else
{
if (field.IndexableFieldType.StoreTermVectorOffsets)
{
throw new ArgumentException("cannot index term vector offsets when term vectors are not indexed (field=\"" + field.Name + "\")");
}
if (field.IndexableFieldType.StoreTermVectorPositions)
{
throw new ArgumentException("cannot index term vector positions when term vectors are not indexed (field=\"" + field.Name + "\")");
}
if (field.IndexableFieldType.StoreTermVectorPayloads)
{
throw new ArgumentException("cannot index term vector payloads when term vectors are not indexed (field=\"" + field.Name + "\")");
}
}
}
else
{
if (field.IndexableFieldType.StoreTermVectors)
{
throw new ArgumentException("cannot index term vectors when field is not indexed (field=\"" + field.Name + "\")");
}
if (field.IndexableFieldType.StoreTermVectorOffsets)
{
throw new ArgumentException("cannot index term vector offsets when field is not indexed (field=\"" + field.Name + "\")");
}
if (field.IndexableFieldType.StoreTermVectorPositions)
{
throw new ArgumentException("cannot index term vector positions when field is not indexed (field=\"" + field.Name + "\")");
}
if (field.IndexableFieldType.StoreTermVectorPayloads)
{
throw new ArgumentException("cannot index term vector payloads when field is not indexed (field=\"" + field.Name + "\")");
}
}
}
if (doVectors)
{
termsWriter.hasVectors = true;
if (termsHashPerField.bytesHash.Count != 0)
{
// Only necessary if previous doc hit a
// non-aborting exception while writing vectors in
// this field:
termsHashPerField.Reset();
}
}
// TODO: only if needed for performance
//perThread.postingsCount = 0;
return doVectors;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public void Abort()
{
}
/// <summary>
/// Called once per field per document if term vectors
/// are enabled, to write the vectors to
/// RAMOutputStream, which is then quickly flushed to
/// the real term vectors files in the Directory.
/// </summary>
internal override void Finish()
{
if (!doVectors || termsHashPerField.bytesHash.Count == 0)
{
return;
}
termsWriter.AddFieldToFlush(this);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal void FinishDocument()
{
if (Debugging.AssertsEnabled) Debugging.Assert(docState.TestPoint("TermVectorsTermsWriterPerField.finish start"));
int numPostings = termsHashPerField.bytesHash.Count;
BytesRef flushTerm = termsWriter.flushTerm;
if (Debugging.AssertsEnabled) Debugging.Assert(numPostings >= 0);
if (numPostings > maxNumPostings)
{
maxNumPostings = numPostings;
}
// this is called once, after inverting all occurrences
// of a given field in the doc. At this point we flush
// our hash into the DocWriter.
if (Debugging.AssertsEnabled) Debugging.Assert(termsWriter.VectorFieldsInOrder(fieldInfo));
TermVectorsPostingsArray postings = (TermVectorsPostingsArray)termsHashPerField.postingsArray;
TermVectorsWriter tv = termsWriter.writer;
int[] termIDs = termsHashPerField.SortPostings(tv.Comparer);
tv.StartField(fieldInfo, numPostings, doVectorPositions, doVectorOffsets, hasPayloads);
ByteSliceReader posReader = doVectorPositions ? termsWriter.vectorSliceReaderPos : null;
ByteSliceReader offReader = doVectorOffsets ? termsWriter.vectorSliceReaderOff : null;
ByteBlockPool termBytePool = termsHashPerField.termBytePool;
for (int j = 0; j < numPostings; j++)
{
int termID = termIDs[j];
int freq = postings.freqs[termID];
// Get BytesRef
termBytePool.SetBytesRef(flushTerm, postings.textStarts[termID]);
tv.StartTerm(flushTerm, freq);
if (doVectorPositions || doVectorOffsets)
{
if (posReader != null)
{
termsHashPerField.InitReader(posReader, termID, 0);
}
if (offReader != null)
{
termsHashPerField.InitReader(offReader, termID, 1);
}
tv.AddProx(freq, posReader, offReader);
}
tv.FinishTerm();
}
tv.FinishField();
termsHashPerField.Reset();
fieldInfo.SetStoreTermVectors();
}
internal void ShrinkHash()
{
termsHashPerField.ShrinkHash(maxNumPostings);
maxNumPostings = 0;
}
internal override void Start(IIndexableField f)
{
if (doVectorOffsets)
{
offsetAttribute = fieldState.AttributeSource.AddAttribute<IOffsetAttribute>();
}
else
{
offsetAttribute = null;
}
if (doVectorPayloads && fieldState.AttributeSource.HasAttribute<IPayloadAttribute>())
{
payloadAttribute = fieldState.AttributeSource.GetAttribute<IPayloadAttribute>();
}
else
{
payloadAttribute = null;
}
}
internal void WriteProx(TermVectorsPostingsArray postings, int termID)
{
if (doVectorOffsets)
{
int startOffset = fieldState.Offset + offsetAttribute.StartOffset;
int endOffset = fieldState.Offset + offsetAttribute.EndOffset;
termsHashPerField.WriteVInt32(1, startOffset - postings.lastOffsets[termID]);
termsHashPerField.WriteVInt32(1, endOffset - startOffset);
postings.lastOffsets[termID] = endOffset;
}
if (doVectorPositions)
{
BytesRef payload;
if (payloadAttribute == null)
{
payload = null;
}
else
{
payload = payloadAttribute.Payload;
}
int pos = fieldState.Position - postings.lastPositions[termID];
if (payload != null && payload.Length > 0)
{
termsHashPerField.WriteVInt32(0, (pos << 1) | 1);
termsHashPerField.WriteVInt32(0, payload.Length);
termsHashPerField.WriteBytes(0, payload.Bytes, payload.Offset, payload.Length);
hasPayloads = true;
}
else
{
termsHashPerField.WriteVInt32(0, pos << 1);
}
postings.lastPositions[termID] = fieldState.Position;
}
}
internal override void NewTerm(int termID)
{
if (Debugging.AssertsEnabled) Debugging.Assert(docState.TestPoint("TermVectorsTermsWriterPerField.newTerm start"));
TermVectorsPostingsArray postings = (TermVectorsPostingsArray)termsHashPerField.postingsArray;
postings.freqs[termID] = 1;
postings.lastOffsets[termID] = 0;
postings.lastPositions[termID] = 0;
WriteProx(postings, termID);
}
internal override void AddTerm(int termID)
{
if (Debugging.AssertsEnabled) Debugging.Assert(docState.TestPoint("TermVectorsTermsWriterPerField.addTerm start"));
TermVectorsPostingsArray postings = (TermVectorsPostingsArray)termsHashPerField.postingsArray;
postings.freqs[termID]++;
WriteProx(postings, termID);
}
[ExceptionToNetNumericConvention]
internal override void SkippingLongTerm()
{
}
internal override ParallelPostingsArray CreatePostingsArray(int size)
{
return new TermVectorsPostingsArray(size);
}
internal sealed class TermVectorsPostingsArray : ParallelPostingsArray
{
public TermVectorsPostingsArray(int size)
: base(size)
{
freqs = new int[size];
lastOffsets = new int[size];
lastPositions = new int[size];
}
internal int[] freqs; // How many times this term occurred in the current doc
internal int[] lastOffsets; // Last offset we saw
internal int[] lastPositions; // Last position where this term occurred
internal override ParallelPostingsArray NewInstance(int size)
{
return new TermVectorsPostingsArray(size);
}
internal override void CopyTo(ParallelPostingsArray toArray, int numToCopy)
{
if (Debugging.AssertsEnabled) Debugging.Assert(toArray is TermVectorsPostingsArray);
TermVectorsPostingsArray to = (TermVectorsPostingsArray)toArray;
base.CopyTo(toArray, numToCopy);
Array.Copy(freqs, 0, to.freqs, 0, size);
Array.Copy(lastOffsets, 0, to.lastOffsets, 0, size);
Array.Copy(lastPositions, 0, to.lastPositions, 0, size);
}
internal override int BytesPerPosting()
{
return base.BytesPerPosting() + 3 * RamUsageEstimator.NUM_BYTES_INT32;
}
}
}
}
| |
using System.Collections;
using System.Compiler;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.Zing
{
/// <summary>
/// Walk IR checking for semantic errors and repairing it so that subsequent walks need not do error checking
/// </summary>
internal sealed class Checker : System.Compiler.Checker
{
private Hashtable validChooses;
private Hashtable validMethodCalls;
private Hashtable validSetOperations;
private Hashtable validSelfAccess;
private bool insideAtomic;
private Stack selectStatementStack = new Stack();
private Select currentSelectStatement
{
get
{
if (selectStatementStack.Count > 0)
return (Select)selectStatementStack.Peek();
else
return null;
}
}
private void PushSelectStatement(Select select)
{
selectStatementStack.Push(select);
}
private void PopSelectStatement()
{
selectStatementStack.Pop();
}
internal Checker(ErrorHandler errorHandler, TypeSystem typeSystem, TrivialHashtable scopeFor, // LJW: added scopeFor
TrivialHashtable ambiguousTypes, TrivialHashtable referencedLabels)
: base(errorHandler, typeSystem, scopeFor, ambiguousTypes, referencedLabels)
{
this.validChooses = new Hashtable();
this.validMethodCalls = new Hashtable();
this.validSetOperations = new Hashtable();
this.validSelfAccess = new Hashtable();
}
private void HandleError(Node errorNode, Error error, params string[] messageParameters)
{
ErrorNode enode = new ZingErrorNode(error, messageParameters);
enode.SourceContext = errorNode.SourceContext;
this.ErrorHandler.Errors.Add(enode);
}
public override void SerializeContracts(TypeNode type)
{
// workaround for bug in the base class. Since we don't need contracts we can just
// do nothing here.
}
public override Node Visit(Node node)
{
if (node == null) return null;
switch (((ZingNodeType)node.NodeType))
{
case ZingNodeType.Array:
return this.VisitArray((ZArray)node);
case ZingNodeType.Accept:
return this.VisitAccept((AcceptStatement)node);
case ZingNodeType.Assert:
return this.VisitAssert((AssertStatement)node);
case ZingNodeType.Assume:
return this.VisitAssume((AssumeStatement)node);
case ZingNodeType.Async:
return this.VisitAsync((AsyncMethodCall)node);
case ZingNodeType.Atomic:
return this.VisitAtomic((AtomicBlock)node);
case ZingNodeType.AttributedStatement:
return this.VisitAttributedStatement((AttributedStatement)node);
case ZingNodeType.Chan:
return this.VisitChan((Chan)node);
case ZingNodeType.Choose:
return this.VisitChoose((UnaryExpression)node);
case ZingNodeType.EventPattern:
return this.VisitEventPattern((EventPattern)node);
case ZingNodeType.Event:
return this.VisitEventStatement((EventStatement)node);
case ZingNodeType.In:
return this.VisitBinaryExpression((BinaryExpression)node);
case ZingNodeType.JoinStatement:
return this.VisitJoinStatement((JoinStatement)node);
case ZingNodeType.InvokePlugin:
return this.VisitInvokePlugin((InvokePluginStatement)node);
case ZingNodeType.InvokeSched:
return this.VisitInvokeSched((InvokeSchedulerStatement)node);
case ZingNodeType.Range:
return this.VisitRange((Range)node);
case ZingNodeType.ReceivePattern:
return this.VisitReceivePattern((ReceivePattern)node);
case ZingNodeType.Select:
return this.VisitSelect((Select)node);
case ZingNodeType.Send:
return this.VisitSend((SendStatement)node);
case ZingNodeType.Self:
return this.VisitSelf((SelfExpression)node);
case ZingNodeType.Set:
return this.VisitSet((Set)node);
case ZingNodeType.TimeoutPattern:
return this.VisitTimeoutPattern((TimeoutPattern)node);
case ZingNodeType.Trace:
return this.VisitTrace((TraceStatement)node);
case ZingNodeType.Try:
return this.VisitZTry((ZTry)node);
case ZingNodeType.WaitPattern:
return this.VisitWaitPattern((WaitPattern)node);
case ZingNodeType.With:
return this.VisitWith((With)node);
case ZingNodeType.Yield:
return this.VisitYield((YieldStatement)node);
default:
return base.Visit(node);
}
}
//
// We support iteration over arrays and sets
//
public override Statement VisitForEach(ForEach forEach)
{
if (forEach == null) return null;
forEach.TargetVariableType = this.VisitTypeReference(forEach.TargetVariableType);
forEach.TargetVariable = this.VisitTargetExpression(forEach.TargetVariable);
forEach.SourceEnumerable = this.VisitExpression(forEach.SourceEnumerable);
if (forEach.TargetVariableType == null || forEach.TargetVariable == null || forEach.SourceEnumerable == null)
return null;
TypeNode collectionType = forEach.SourceEnumerable.Type;
Set setCollection = collectionType as Set;
ZArray arrayCollection = collectionType as ZArray;
TypeNode memberType = null;
if (setCollection != null)
memberType = setCollection.SetType;
if (arrayCollection != null)
memberType = arrayCollection.ElementType;
if (memberType == null)
{
this.HandleError(forEach.SourceEnumerable, Error.InvalidForeachSource);
return null;
}
if (memberType != forEach.TargetVariableType)
{
this.HandleError(forEach.TargetVariable, Error.InvalidForeachTargetType);
return null;
}
forEach.Body = this.VisitBlock(forEach.Body);
return forEach;
}
//
// Our notion of "sizeof" is more flexible - the operand can be either a type or
// an expression, so we don't want to use the base checker in that case.
//
public override Expression VisitUnaryExpression(UnaryExpression unaryExpression)
{
if (unaryExpression.NodeType != NodeType.Sizeof)
return base.VisitUnaryExpression(unaryExpression);
unaryExpression.Operand = (Expression)this.Visit(unaryExpression.Operand);
if (unaryExpression.Operand == null)
return null;
if (unaryExpression.Operand is Literal)
{
// If the operand is a literal, it must be an array type reference
Literal operand = (Literal)unaryExpression.Operand;
if (!(operand.Value is ZArray))
{
this.HandleError(unaryExpression.Operand, Error.InvalidSizeofOperand);
return null;
}
}
else
{
// If the operand is an expression, it must refer to an array, set, or channel.
TypeNode opndType = unaryExpression.Operand.Type;
if (!(opndType is ZArray) && !(opndType is Set) && !(opndType is Chan))
{
this.HandleError(unaryExpression.Operand, Error.InvalidSizeofOperand);
return null;
}
}
return unaryExpression;
}
public override Method VisitMethod(Method method)
{
ZMethod zMethod = base.VisitMethod(method) as ZMethod;
if (zMethod == null)
return null;
if (zMethod.Activated)
{
if (!zMethod.IsStatic)
{
this.HandleError(method, Error.ExpectedStaticMethod);
return null;
}
if (zMethod.ReturnType != SystemTypes.Void)
{
this.HandleError(zMethod, Error.ExpectedVoidMethod);
return null;
}
if (zMethod.Parameters.Count != 0)
{
this.HandleError(zMethod, Error.ExpectedParameterlessMethod);
return null;
}
}
return zMethod;
}
//
// For sets, we need to permit overloading of "+" and "-" but check for invalid combinations
// of set and element types.
//
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
public override Expression VisitBinaryExpression(BinaryExpression binaryExpression)
{
if (binaryExpression == null) return null;
Expression opnd1 = binaryExpression.Operand1 = this.VisitExpression(binaryExpression.Operand1);
Expression opnd2 = binaryExpression.Operand2 = this.VisitExpression(binaryExpression.Operand2);
if (opnd1 == null || opnd2 == null)
return null;
Set opnd1TypeAsSet = opnd1.Type as Set;
Set opnd2TypeAsSet = opnd2.Type as Set;
Literal lit1 = opnd1 as Literal;
Literal lit2 = opnd2 as Literal;
if ((opnd1TypeAsSet != null || opnd2TypeAsSet != null) &&
!this.validSetOperations.Contains(binaryExpression) &&
binaryExpression.NodeType != (NodeType)ZingNodeType.In)
{
this.HandleError(binaryExpression, Error.InvalidSetExpression);
return null;
}
switch (binaryExpression.NodeType)
{
case NodeType.Add:
case NodeType.Sub:
if (opnd1TypeAsSet != null)
{
if (opnd1TypeAsSet.SetType != opnd2.Type && opnd1.Type != opnd2.Type)
{
if (opnd2TypeAsSet != null)
this.HandleError(opnd1, Error.IncompatibleSetTypes);
else
this.HandleError(opnd2, Error.IncompatibleSetOperand);
return null;
}
return binaryExpression;
}
break;
case NodeType.LogicalAnd:
{
if (lit1 != null && lit1.Value is bool)
{
if (((bool)lit1.Value) == true)
return opnd2;
else
return opnd1;
}
if (lit2 != null && lit2.Value is bool)
{
if (((bool)lit2.Value) == true)
return opnd1;
else
return opnd2;
}
}
break;
case NodeType.LogicalOr:
{
if (lit1 != null && lit1.Value is bool)
{
if (((bool)lit1.Value) == false)
return opnd2;
else
return opnd1;
}
if (lit2 != null && lit2.Value is bool)
{
if (((bool)lit2.Value) == false)
return opnd1;
else
return opnd2;
}
}
break;
case (NodeType)ZingNodeType.In:
if (opnd2TypeAsSet == null)
{
this.HandleError(opnd2, Error.ExpectedSetType);
return null;
}
if (opnd2TypeAsSet.SetType != opnd1.Type)
{
this.HandleError(opnd1, Error.IncompatibleSetOperand);
return null;
}
return binaryExpression;
default:
break;
}
return base.CoerceBinaryExpressionOperands(binaryExpression, opnd1, opnd2);
}
public override Statement VisitThrow(Throw Throw)
{
// The base Checker will complain that we haven't resolved Throw.Expression
// but for us that's ok because exceptions are just names.
return Throw;
}
public override Statement VisitExpressionStatement(ExpressionStatement statement)
{
// Check for statements that require special handling
AssignmentExpression assignmentExpr = statement.Expression as AssignmentExpression;
AssignmentStatement assignmentStatement = null;
MethodCall methodCall = statement.Expression as MethodCall;
SelfExpression selfAccess = statement.Expression as SelfExpression;
UnaryExpression choose = null;
if (assignmentExpr != null)
{
assignmentStatement = assignmentExpr.AssignmentStatement as AssignmentStatement;
if (assignmentStatement != null && assignmentStatement.Source is MethodCall)
methodCall = (MethodCall)assignmentStatement.Source;
if (assignmentStatement != null && assignmentStatement.Source is UnaryExpression &&
assignmentStatement.Source.NodeType == (NodeType)ZingNodeType.Choose)
choose = (UnaryExpression)assignmentStatement.Source;
if (assignmentStatement != null && assignmentStatement.Source is BinaryExpression &&
assignmentStatement.Target.Type is Set)
{
BinaryExpression binaryExpression = (BinaryExpression)assignmentStatement.Source;
this.validSetOperations.Add(binaryExpression, null);
if (SameVariable(assignmentStatement.Target, binaryExpression.Operand1))
{
// all is well
}
else if (SameVariable(assignmentStatement.Target, binaryExpression.Operand2))
{
// swap operands to put the statement in its desired form
Expression tmp = binaryExpression.Operand1;
binaryExpression.Operand1 = binaryExpression.Operand2;
binaryExpression.Operand2 = tmp;
}
else
{
this.HandleError(statement, Error.InvalidSetAssignment);
return null;
}
}
//
// If the source and target types aren't equal, but both are numeric, then we
// insert an implied cast to the target type. If & when we add an explicit cast
// operator to Zing, then this can be removed.
//
if (assignmentStatement != null &&
assignmentStatement.Source != null && assignmentStatement.Source.Type != null &&
assignmentStatement.Target != null && assignmentStatement.Target.Type != null &&
assignmentStatement.Source.Type != assignmentStatement.Target.Type &&
assignmentStatement.Source.Type.IsPrimitiveNumeric &&
assignmentStatement.Target.Type.IsPrimitiveNumeric)
{
// Wrap a cast operator around the source expression
BinaryExpression binExpr = new BinaryExpression(assignmentStatement.Source,
new MemberBinding(null, assignmentStatement.Target.Type),
NodeType.Castclass, assignmentStatement.Source.SourceContext);
binExpr.Type = assignmentStatement.Target.Type;
assignmentStatement.Source = binExpr;
}
}
if (methodCall != null)
this.validMethodCalls.Add(methodCall, null);
if (selfAccess != null)
this.validSelfAccess.Add(selfAccess, null);
if (choose != null)
this.validChooses.Add(choose, null);
return base.VisitExpressionStatement(statement);
}
private static bool SameVariable(Expression expr1, Expression expr2)
{
MemberBinding mb1 = expr1 as MemberBinding;
MemberBinding mb2 = expr2 as MemberBinding;
if (mb1 == null || mb2 == null)
return false;
if (mb1.BoundMember.DeclaringType != mb2.BoundMember.DeclaringType)
return false;
if (mb1.BoundMember.Name != mb2.BoundMember.Name)
return false;
return true;
}
public override Expression VisitMethodCall(MethodCall call)
{
if (this.inWaitPattern)
{
MemberBinding mbCallee = call.Callee as MemberBinding;
ZMethod calleeMethod = null;
if (mbCallee != null)
calleeMethod = mbCallee.BoundMember as ZMethod;
if (mbCallee == null || calleeMethod == null)
return base.VisitMethodCall(call);
// Method must return bool (concrete) and have only input params
if (calleeMethod.ReturnType != SystemTypes.Boolean)
{
this.HandleError(call, Error.InvalidPredicateReturnType);
return null;
}
for (int i = 0, n = calleeMethod.Parameters.Count; i < n; i++)
{
if (calleeMethod.Parameters[i].IsOut)
{
this.HandleError(call, Error.UnexpectedPredicateOutputParameter);
return null;
}
}
}
else if (!this.validMethodCalls.Contains(call))
{
this.HandleError(call, Error.EmbeddedMethodCall);
return null;
}
return base.VisitMethodCall(call);
}
private UnaryExpression VisitChoose(UnaryExpression expr)
{
if (expr == null) return null;
if (!this.validChooses.Contains(expr))
{
this.HandleError(expr, Error.EmbeddedChoose);
return null;
}
return expr;
}
//
// We override VisitTypeReference because the base class will (incorrectly) hit an
// assertion failure on ArrayTypeExpression nodes.
//
public override TypeNode VisitTypeReference(TypeNode type)
{
if (type == null) return null;
if (type.NodeType == NodeType.ArrayTypeExpression) return type;
return base.VisitTypeReference(type);
}
private ZArray VisitArray(ZArray array)
{
if (array == null) return null;
array.domainType = this.VisitTypeReference(array.domainType);
return (ZArray)base.VisitTypeReference((TypeNode)array);
}
private AssertStatement VisitAssert(AssertStatement assert)
{
if (assert == null) return null;
assert.booleanExpr = this.VisitExpression(assert.booleanExpr);
if (assert.booleanExpr == null)
return null;
if (assert.booleanExpr.Type != SystemTypes.Boolean)
{
this.HandleError(assert, Error.BooleanExpressionRequired);
return null;
}
return assert;
}
private AcceptStatement VisitAccept(AcceptStatement accept)
{
if (accept == null) return null;
accept.booleanExpr = this.VisitExpression(accept.booleanExpr);
if (accept.booleanExpr == null)
return null;
if (accept.booleanExpr.Type != SystemTypes.Boolean)
{
this.HandleError(accept, Error.BooleanExpressionRequired);
return null;
}
return accept;
}
private EventPattern VisitEventPattern(EventPattern ep)
{
if (ep == null) return null;
if (!currentSelectStatement.visible)
{
this.HandleError(ep, Error.InvalidEventPattern);
return null;
}
ep.direction = this.VisitExpression(ep.direction);
if (ep.direction != null && ep.direction.Type != SystemTypes.Boolean)
{
this.HandleError(ep.direction, Error.BooleanExpressionRequired);
return null;
}
ep.channelNumber = this.VisitExpression(ep.channelNumber);
if (ep.channelNumber != null)
{
if (ep.channelNumber.Type == SystemTypes.UInt8)
{
ep.channelNumber = new BinaryExpression(ep.channelNumber, new MemberBinding(null, SystemTypes.Int32),
NodeType.Castclass, ep.channelNumber.SourceContext);
ep.channelNumber.Type = SystemTypes.Int32;
}
else if (ep.channelNumber.Type != SystemTypes.Int32)
{
this.HandleError(ep.channelNumber, Error.IntegerExpressionRequired);
return null;
}
}
ep.messageType = this.VisitExpression(ep.messageType);
if (ep.messageType != null)
{
if (ep.messageType.Type == SystemTypes.UInt8)
{
ep.messageType = new BinaryExpression(ep.messageType, new MemberBinding(null, SystemTypes.Int32),
NodeType.Castclass, ep.messageType.SourceContext);
ep.messageType.Type = SystemTypes.Int32;
}
else if (ep.messageType.Type != SystemTypes.Int32)
{
this.HandleError(ep.messageType, Error.IntegerExpressionRequired);
return null;
}
}
return ep;
}
private EventStatement VisitEventStatement(EventStatement Event)
{
if (Event == null) return null;
Event.direction = this.VisitExpression(Event.direction);
if (Event.direction != null && Event.direction.Type != SystemTypes.Boolean)
{
this.HandleError(Event.direction, Error.BooleanExpressionRequired);
return null;
}
Event.channelNumber = this.VisitExpression(Event.channelNumber);
if (Event.channelNumber != null)
{
if (Event.channelNumber.Type == SystemTypes.UInt8)
{
Event.channelNumber = new BinaryExpression(Event.channelNumber, new MemberBinding(null, SystemTypes.Int32),
NodeType.Castclass, Event.channelNumber.SourceContext);
Event.channelNumber.Type = SystemTypes.Int32;
}
else if (Event.channelNumber.Type != SystemTypes.Int32)
{
this.HandleError(Event.channelNumber, Error.IntegerExpressionRequired);
return null;
}
}
Event.messageType = this.VisitExpression(Event.messageType);
if (Event.messageType != null)
{
if (Event.messageType.Type == SystemTypes.UInt8)
{
Event.messageType = new BinaryExpression(Event.messageType, new MemberBinding(null, SystemTypes.Int32),
NodeType.Castclass, Event.messageType.SourceContext);
Event.messageType.Type = SystemTypes.Int32;
}
else if (Event.messageType.Type != SystemTypes.Int32)
{
this.HandleError(Event.messageType, Error.IntegerExpressionRequired);
return null;
}
}
return Event;
}
private TraceStatement VisitTrace(TraceStatement trace)
{
trace.Operands = base.VisitExpressionList(trace.Operands);
if (trace.Operands == null || trace.Operands.Count == 0)
{
this.HandleError(trace, Error.TraceExpectedArguments);
return null;
}
Expression arg0 = trace.Operands[0];
Literal lit0 = arg0 as Literal;
if (lit0 == null)
{
this.HandleError(trace, Error.ExpectedStringLiteral);
return null;
}
if (!(lit0.Value is string))
{
this.HandleError(lit0, Error.ExpectedStringLiteral);
return null;
}
return trace;
}
private InvokePluginStatement VisitInvokePlugin(InvokePluginStatement InvokePlugin)
{
InvokePlugin.Operands = base.VisitExpressionList(InvokePlugin.Operands);
if (InvokePlugin.Operands == null || InvokePlugin.Operands.Count == 0)
{
this.HandleError(InvokePlugin, Error.InvokePluginExpectedArguments);
return null;
}
Expression arg0 = InvokePlugin.Operands[0];
Literal lit0 = arg0 as Literal;
if (lit0 == null)
{
this.HandleError(InvokePlugin, Error.ExpectedPluginDllName);
return null;
}
if (!(lit0.Value is string))
{
this.HandleError(InvokePlugin, Error.ExpectedPluginDllName);
return null;
}
return InvokePlugin;
}
private InvokeSchedulerStatement VisitInvokeSched(InvokeSchedulerStatement InvokeShed)
{
InvokeShed.Operands = base.VisitExpressionList(InvokeShed.Operands);
return InvokeShed;
}
private AssumeStatement VisitAssume(AssumeStatement assume)
{
if (assume == null) return null;
assume.booleanExpr = this.VisitExpression(assume.booleanExpr);
if (assume.booleanExpr != null && assume.booleanExpr.Type != SystemTypes.Boolean)
{
this.HandleError(assume, Error.BooleanExpressionRequired);
return null;
}
return assume;
}
private SelfExpression VisitSelf(SelfExpression self)
{
if (self == null)
{
return null;
}
return self;
}
private YieldStatement VisitYield(YieldStatement yield)
{
if (yield == null) return null;
if (((ZMethod)this.currentMethod).Atomic)
{
this.HandleError(yield, Error.IllegalYieldInAtomicBlock);
return null;
}
return yield;
}
private AsyncMethodCall VisitAsync(AsyncMethodCall async)
{
if (async == null) return null;
async = (AsyncMethodCall)this.VisitExpressionStatement((ExpressionStatement)async);
if (async != null && async.Expression is MethodCall)
{
ZMethod method = (ZMethod)((MemberBinding)async.Callee).BoundMember;
if (method.ReturnType != SystemTypes.Void)
{
this.HandleError(async, Error.InvalidAsyncCallTarget);
//return null; // this is just a warning, for now
}
for (int i = 0, n = method.Parameters.Count; i < n; i++)
{
Parameter param = method.Parameters[i];
if ((param.Flags & ParameterFlags.Out) != 0)
{
this.HandleError(async, Error.InvalidAsyncCallTarget);
//return null; // this is just a warning, for now
}
}
}
return async;
}
private Block VisitAtomic(AtomicBlock atomic)
{
Block newAtomic = null;
if (atomic == null) return null;
if (((ZMethod)this.currentMethod).Atomic)
{
this.HandleError(atomic, Error.AtomicBlockInAtomicMethod);
return null;
}
if (this.insideAtomic)
{
this.HandleError(atomic, Error.AtomicBlockNested);
return null;
}
this.insideAtomic = true;
newAtomic = this.VisitBlock((Block)atomic);
this.insideAtomic = false;
return newAtomic;
}
private AttributedStatement VisitAttributedStatement(AttributedStatement attributedStmt)
{
if (attributedStmt == null) return null;
attributedStmt.Attributes = this.VisitAttributeList(attributedStmt.Attributes);
attributedStmt.Statement = (Statement)this.Visit(attributedStmt.Statement);
return attributedStmt;
}
public override AttributeList VisitAttributeList(AttributeList attributes)
{
if (attributes == null) return null;
AttributeList rval = new AttributeList();
for (int i = 0, n = attributes.Count; i < n; i++)
{
rval.Add(this.VisitAttributeNode(attributes[i]));
}
return rval;
}
public override AttributeNode VisitAttributeNode(AttributeNode attribute)
{
if (attribute == null) return null;
attribute.Constructor = this.VisitExpression(attribute.Constructor);
attribute.Expressions = this.VisitExpressionList(attribute.Expressions);
return attribute;
}
public override Expression VisitAttributeConstructor(AttributeNode attribute, Node target)
{
if (attribute == null) return null;
MemberBinding mb = attribute.Constructor as MemberBinding;
if (mb == null) { Debug.Assert(false); return null; }
InstanceInitializer cons = mb.BoundMember as InstanceInitializer;
if (cons == null) return null;
TypeNode t = cons.DeclaringType;
if (t.IsAssignableTo(SystemTypes.Attribute))
{
// NOTE: for Zing, we don't check the attribute target because we're putting
// attributes on statements, which CCI will never understand.
//if (!this.CheckAttributeTarget(attribute, target, mb, t)) return null;
//this.CheckForObsolesence(mb, cons);
return mb;
}
Debug.Assert(false);
this.HandleError(mb, System.Compiler.Error.NotAnAttribute, this.GetTypeName(t));
this.HandleRelatedError(t);
return null;
}
private Chan VisitChan(Chan chan)
{
if (chan == null) return null;
chan.ChannelType = this.VisitTypeReference(chan.ChannelType);
return chan;
}
private Range VisitRange(Range range)
{
if (range == null) return null;
range.Min = this.VisitExpression(range.Min);
range.Max = this.VisitExpression(range.Max);
return (Range)this.VisitConstrainedType((ConstrainedType)range);
}
private JoinStatement VisitJoinStatement(JoinStatement joinstmt)
{
if (joinstmt == null) return null;
JoinPatternList newJoinPatternList = new JoinPatternList();
for (int i = 0, n = joinstmt.joinPatternList.Length; i < n; i++)
{
if (joinstmt.joinPatternList[i] is TimeoutPattern && n != 1)
{
// If we've already see a timeout in this join statement, then
// skip any subsequent ones and report an error
HandleError(joinstmt.joinPatternList[i], Error.TimeoutNotAlone);
return null;
}
JoinPattern newJoinPattern = (JoinPattern)this.Visit(joinstmt.joinPatternList[i]);
if (newJoinPattern != null)
newJoinPatternList.Add(newJoinPattern);
}
joinstmt.joinPatternList = newJoinPatternList;
joinstmt.statement = (Statement)this.Visit(joinstmt.statement);
joinstmt.attributes = this.VisitAttributeList(joinstmt.attributes);
if (joinstmt.joinPatternList.Length == 0 || joinstmt.statement == null)
return null;
return joinstmt;
}
private ReceivePattern VisitReceivePattern(ReceivePattern rp)
{
if (rp == null) return null;
rp.channel = this.VisitExpression(rp.channel);
rp.data = this.VisitExpression(rp.data);
if (rp.channel == null || rp.data == null)
return null;
Chan chanType = rp.channel.Type as Chan;
if (chanType == null)
{
// The channel argument must refer to a channel type
this.HandleError(rp.channel, Error.ExpectedChannelType);
return null;
}
if (chanType.ChannelType != rp.data.Type)
{
// the data argument must match the message type of the channel
this.HandleError(rp.data, Error.InvalidMessageType);
return null;
}
return rp;
}
[SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters")]
private TimeoutPattern VisitTimeoutPattern(TimeoutPattern tp)
{
return tp;
}
private bool inWaitPattern;
private WaitPattern VisitWaitPattern(WaitPattern wp)
{
if (wp == null) return null;
inWaitPattern = true;
wp.expression = this.VisitExpression(wp.expression);
inWaitPattern = false;
return wp;
}
private Select VisitSelect(Select select)
{
if (select == null) return null;
PushSelectStatement(select);
JoinStatementList newJoinStatementList = new JoinStatementList();
int timeoutIndex = -1;
for (int i = 0, n = select.joinStatementList.Length; i < n; i++)
{
if (select.joinStatementList[i].joinPatternList[0] is TimeoutPattern)
{
if (timeoutIndex >= 0)
{
// If we've already seen a "timeout" join statement, then skip
// subsequent ones and report an error.
HandleError(select.joinStatementList[i], Error.TooManyTimeouts);
continue;
}
timeoutIndex = i;
}
JoinStatement newJoinStatement = (JoinStatement)this.VisitJoinStatement(select.joinStatementList[i]);
if (newJoinStatement != null)
newJoinStatementList.Add(newJoinStatement);
}
select.joinStatementList = newJoinStatementList;
// If a timeout is present and it isn't already last, move it to the
// end of the list. This will be helpful during code generation.
if (timeoutIndex >= 0 && timeoutIndex != (select.joinStatementList.Length - 1))
{
JoinStatement temp;
temp = select.joinStatementList[select.joinStatementList.Length - 1];
select.joinStatementList[select.joinStatementList.Length - 1] = select.joinStatementList[timeoutIndex];
select.joinStatementList[timeoutIndex] = temp;
}
if (select.joinStatementList.Length == 1)
select.deterministicSelection = true;
PopSelectStatement();
if (select.joinStatementList.Length == 0)
return null;
return select;
}
private SendStatement VisitSend(SendStatement send)
{
if (send == null) return null;
send.channel = this.VisitExpression(send.channel);
send.data = this.VisitExpression(send.data);
if (send.channel == null || send.data == null)
return null;
Chan chanType = send.channel.Type as Chan;
if (chanType == null)
{
// The channel argument must refer to a channel type
this.HandleError(send.channel, Error.ExpectedChannelType);
return null;
}
if (chanType.ChannelType != send.data.Type)
{
// the data argument must match the message type of the channel
this.HandleError(send.data, Error.InvalidMessageType);
return null;
}
return send;
}
private Set VisitSet(Set @set)
{
if (@set == null) return null;
@set.SetType = this.VisitTypeReference(@set.SetType);
return @set;
}
private ZTry VisitZTry(ZTry Try)
{
if (Try == null) return null;
Try.Body = this.VisitBlock(Try.Body);
WithList newCatchers = new WithList();
for (int i = 0, n = Try.Catchers.Length; i < n; i++)
newCatchers.Add(this.VisitWith(Try.Catchers[i]));
Try.Catchers = newCatchers;
return Try;
}
private With VisitWith(With with)
{
if (with == null) return null;
with.Block = this.VisitBlock(with.Block);
return with;
}
public override Expression VisitConstruct(Construct cons)
{
if (cons == null) return cons;
MemberBinding mb = cons.Constructor as MemberBinding;
if (mb == null)
return null;
//
// Verify that mb.BoundMember is a heap-allocated type
//
TypeNode tn = cons.Type;
ZArray arrayNode = tn as ZArray;
if (tn is Set || arrayNode != null || tn is Class || tn is Chan)
{
if (arrayNode != null)
{
ExpressionList el = cons.Operands;
Debug.Assert(el.Count <= 1);
if (arrayNode.Sizes == null)
{
// This is a variable-sized array. Check that there is exactly
// one argument to the constructor of integer type.
if (el.Count == 0)
{
this.HandleError(cons, Error.IntegerExpressionRequired);
return null;
}
Expression e = (Expression)el[0];
if (e.Type != SystemTypes.Int32)
{
this.HandleError(cons, Error.IntegerExpressionRequired);
return null;
}
}
else
{
// This is a constant-sized array. Check that there is no
// argument to the constructor.
if (el.Count == 1)
{
this.HandleError(cons, Error.UnexpectedToken, new string[] { el[0].ToString() });
return null;
}
}
}
return cons;
}
else
{
this.HandleError(cons, Error.ExpectedComplexType);
return null;
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.HDInsight.Models;
namespace Microsoft.Azure.Management.HDInsight
{
/// <summary>
/// Contains all the cluster operations.
/// </summary>
public partial interface IClusterOperations
{
/// <summary>
/// Begins configuring the HTTP settings on the specified cluster.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='clusterName'>
/// The name of the cluster.
/// </param>
/// <param name='httpSettingsParameters'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The cluster long running operation response.
/// </returns>
Task<HDInsightOperationResponse> BeginConfiguringHttpSettingsAsync(string resourceGroupName, string clusterName, HttpSettingsParameters httpSettingsParameters, CancellationToken cancellationToken);
/// <summary>
/// Begins configuring the RDP settings on the specified cluster.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='clusterName'>
/// The name of the cluster.
/// </param>
/// <param name='rdpParameters'>
/// The OS profile for RDP.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The cluster long running operation response.
/// </returns>
Task<HDInsightOperationResponse> BeginConfiguringRdpSettingsAsync(string resourceGroupName, string clusterName, RDPSettingsParameters rdpParameters, CancellationToken cancellationToken);
/// <summary>
/// Begins creating a new HDInsight cluster with the specified
/// parameters.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='clusterName'>
/// The name of the cluster.
/// </param>
/// <param name='clusterCreateParameters'>
/// The cluster create request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The CreateCluster operation response.
/// </returns>
Task<ClusterCreateResponse> BeginCreatingAsync(string resourceGroupName, string clusterName, ClusterCreateParametersExtended clusterCreateParameters, CancellationToken cancellationToken);
/// <summary>
/// Begins deleting the specified HDInsight cluster.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='clusterName'>
/// The name of the cluster.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The cluster long running operation response.
/// </returns>
Task<HDInsightOperationResponse> BeginDeletingAsync(string resourceGroupName, string clusterName, CancellationToken cancellationToken);
/// <summary>
/// Begins a resize operation on the specified HDInsight cluster.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='clusterName'>
/// The name of the cluster.
/// </param>
/// <param name='resizeParameters'>
/// The parameters for the resize operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The cluster long running operation response.
/// </returns>
Task<HDInsightOperationResponse> BeginResizingAsync(string resourceGroupName, string clusterName, ClusterResizeParameters resizeParameters, CancellationToken cancellationToken);
/// <summary>
/// Configures the HTTP settings on the specified cluster.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='clusterName'>
/// The name of the cluster.
/// </param>
/// <param name='httpSettingsParameters'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The cluster long running operation response.
/// </returns>
Task<HDInsightLongRunningOperationResponse> ConfigureHttpSettingsAsync(string resourceGroupName, string clusterName, HttpSettingsParameters httpSettingsParameters, CancellationToken cancellationToken);
/// <summary>
/// Configures the RDP settings on the specified cluster.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='clusterName'>
/// The name of the cluster.
/// </param>
/// <param name='rdpParameters'>
/// The OS profile for RDP. Use null to turn RDP off.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The cluster long running operation response.
/// </returns>
Task<HDInsightLongRunningOperationResponse> ConfigureRdpSettingsAsync(string resourceGroupName, string clusterName, RDPSettingsParameters rdpParameters, CancellationToken cancellationToken);
/// <summary>
/// Creates a new HDInsight cluster with the specified parameters.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='clusterName'>
/// The name of the cluster.
/// </param>
/// <param name='clusterCreateParameters'>
/// The cluster create request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The GetCluster operation response.
/// </returns>
Task<ClusterGetResponse> CreateAsync(string resourceGroupName, string clusterName, ClusterCreateParametersExtended clusterCreateParameters, CancellationToken cancellationToken);
/// <summary>
/// Deletes the specified HDInsight cluster.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='clusterName'>
/// The name of the cluster.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The GetCluster operation response.
/// </returns>
Task<ClusterGetResponse> DeleteAsync(string resourceGroupName, string clusterName, CancellationToken cancellationToken);
/// <summary>
/// Gets the specified cluster.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='clusterName'>
/// The name of the cluster.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The GetCluster operation response.
/// </returns>
Task<ClusterGetResponse> GetAsync(string resourceGroupName, string clusterName, CancellationToken cancellationToken);
/// <summary>
/// Gets the capabilities for the specified location.
/// </summary>
/// <param name='location'>
/// The location to get capabilities for.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Get Capabilities operation response.
/// </returns>
Task<CapabilitiesResponse> GetCapabilitiesAsync(string location, CancellationToken cancellationToken);
/// <summary>
/// Gets the connectivity settings for the specified cluster.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='clusterName'>
/// The name of the cluster.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The payload for a Configure HTTP settings request.
/// </returns>
Task<HttpConnectivitySettings> GetConnectivitySettingsAsync(string resourceGroupName, string clusterName, CancellationToken cancellationToken);
/// <summary>
/// Gets the status of the Create operation.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The GetCluster operation response.
/// </returns>
Task<ClusterGetResponse> GetCreateStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// Gets the status of the Delete operation.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The GetCluster operation response.
/// </returns>
Task<ClusterGetResponse> GetDeleteStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// Lists HDInsight clusters under the subscription.
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Cluster operation response.
/// </returns>
Task<ClusterListResponse> ListAsync(CancellationToken cancellationToken);
/// <summary>
/// List the HDInsight clusters in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Cluster operation response.
/// </returns>
Task<ClusterListResponse> ListByResourceGroupAsync(string resourceGroupName, CancellationToken cancellationToken);
/// <summary>
/// Resizes the specified HDInsight cluster.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='clusterName'>
/// The name of the cluster.
/// </param>
/// <param name='resizeParameters'>
/// The parameters for the resize operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The cluster long running operation response.
/// </returns>
Task<HDInsightLongRunningOperationResponse> ResizeAsync(string resourceGroupName, string clusterName, ClusterResizeParameters resizeParameters, CancellationToken cancellationToken);
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
namespace Amazon.ElasticTranscoder.Model
{
/// <summary>
///
/// </summary>
public class CreateJobOutput
{
private string key;
private string thumbnailPattern;
private string rotate;
private string presetId;
private string segmentDuration;
private List<JobWatermark> watermarks = new List<JobWatermark>();
/// <summary>
/// The name to assign to the transcoded file. Elastic Transcoder saves the file in the Amazon S3 bucket specified by the <c>OutputBucket</c>
/// object in the pipeline that is specified by the pipeline ID. If a file with the specified name already exists in the output bucket, the job
/// fails.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 255</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string Key
{
get { return this.key; }
set { this.key = value; }
}
/// <summary>
/// Sets the Key property
/// </summary>
/// <param name="key">The value to set for the Key property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateJobOutput WithKey(string key)
{
this.key = key;
return this;
}
// Check to see if Key property is set
internal bool IsSetKey()
{
return this.key != null;
}
/// <summary>
/// Whether you want Elastic Transcoder to create thumbnails for your videos and, if so, how you want Elastic Transcoder to name the files. If
/// you don't want Elastic Transcoder to create thumbnails, specify "". If you do want Elastic Transcoder to create thumbnails, specify the
/// information that you want to include in the file name for each thumbnail. You can specify the following values in any sequence: <ul> <li>
/// <b><c>{count}</c> (Required)</b>: If you want to create thumbnails, you must include <c>{count}</c> in the <c>ThumbnailPattern</c> object.
/// Wherever you specify <c>{count}</c>, Elastic Transcoder adds a five-digit sequence number (beginning with <b>00001</b>) to thumbnail file
/// names. The number indicates where a given thumbnail appears in the sequence of thumbnails for a transcoded file. <important>If you specify a
/// literal value and/or <c>{resolution}</c> but you omit <c>{count}</c>, Elastic Transcoder returns a validation error and does not create the
/// job.</important> </li> <li> <b>Literal values (Optional)</b>: You can specify literal values anywhere in the <c>ThumbnailPattern</c> object.
/// For example, you can include them as a file name prefix or as a delimiter between <c>{resolution}</c> and <c>{count}</c>. </li> <li>
/// <b><c>{resolution}</c> (Optional)</b>: If you want Elastic Transcoder to include the resolution in the file name, include
/// <c>{resolution}</c> in the <c>ThumbnailPattern</c> object. </li> </ul> When creating thumbnails, Elastic Transcoder automatically saves the
/// files in the format (.jpg or .png) that appears in the preset that you specified in the <c>PresetID</c> value of <c>CreateJobOutput</c>.
/// Elastic Transcoder also appends the applicable file name extension.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Pattern</term>
/// <description>(^$)|(^.*\{count\}.*$)</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string ThumbnailPattern
{
get { return this.thumbnailPattern; }
set { this.thumbnailPattern = value; }
}
/// <summary>
/// Sets the ThumbnailPattern property
/// </summary>
/// <param name="thumbnailPattern">The value to set for the ThumbnailPattern property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateJobOutput WithThumbnailPattern(string thumbnailPattern)
{
this.thumbnailPattern = thumbnailPattern;
return this;
}
// Check to see if ThumbnailPattern property is set
internal bool IsSetThumbnailPattern()
{
return this.thumbnailPattern != null;
}
/// <summary>
/// The number of degrees clockwise by which you want Elastic Transcoder to rotate the output relative to the input. Enter one of the following
/// values: <c>auto</c>, <c>0</c>, <c>90</c>, <c>180</c>, <c>270</c>. The value <c>auto</c> generally works only if the file that you're
/// transcoding contains rotation metadata.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Pattern</term>
/// <description>(^auto$)|(^0$)|(^90$)|(^180$)|(^270$)</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string Rotate
{
get { return this.rotate; }
set { this.rotate = value; }
}
/// <summary>
/// Sets the Rotate property
/// </summary>
/// <param name="rotate">The value to set for the Rotate property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateJobOutput WithRotate(string rotate)
{
this.rotate = rotate;
return this;
}
// Check to see if Rotate property is set
internal bool IsSetRotate()
{
return this.rotate != null;
}
/// <summary>
/// The <c>Id</c> of the preset to use for this job. The preset determines the audio, video, and thumbnail settings that Elastic Transcoder uses
/// for transcoding.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Pattern</term>
/// <description>^\d{13}-\w{6}$</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string PresetId
{
get { return this.presetId; }
set { this.presetId = value; }
}
/// <summary>
/// Sets the PresetId property
/// </summary>
/// <param name="presetId">The value to set for the PresetId property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateJobOutput WithPresetId(string presetId)
{
this.presetId = presetId;
return this;
}
// Check to see if PresetId property is set
internal bool IsSetPresetId()
{
return this.presetId != null;
}
/// <summary>
/// If you specify a preset in <c>PresetId</c> for which the value of <c>Container</c> is ts (MPEG-TS), SegmentDuration is the duration of each
/// .ts file in seconds. The range of valid values is 1 to 60 seconds.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Pattern</term>
/// <description>^\d{1,5}([.]\d{0,5})?$</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string SegmentDuration
{
get { return this.segmentDuration; }
set { this.segmentDuration = value; }
}
/// <summary>
/// Sets the SegmentDuration property
/// </summary>
/// <param name="segmentDuration">The value to set for the SegmentDuration property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateJobOutput WithSegmentDuration(string segmentDuration)
{
this.segmentDuration = segmentDuration;
return this;
}
// Check to see if SegmentDuration property is set
internal bool IsSetSegmentDuration()
{
return this.segmentDuration != null;
}
/// <summary>
///
///
/// </summary>
public List<JobWatermark> Watermarks
{
get { return this.watermarks; }
set { this.watermarks = value; }
}
/// <summary>
/// Adds elements to the Watermarks collection
/// </summary>
/// <param name="watermarks">The values to add to the Watermarks collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateJobOutput WithWatermarks(params JobWatermark[] watermarks)
{
foreach (JobWatermark element in watermarks)
{
this.watermarks.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the Watermarks collection
/// </summary>
/// <param name="watermarks">The values to add to the Watermarks collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateJobOutput WithWatermarks(IEnumerable<JobWatermark> watermarks)
{
foreach (JobWatermark element in watermarks)
{
this.watermarks.Add(element);
}
return this;
}
// Check to see if Watermarks property is set
internal bool IsSetWatermarks()
{
return this.watermarks.Count > 0;
}
}
}
| |
// Copyright 2011 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.
using System;
using System.Collections.Generic;
namespace Microsoft.Data.Edm.Library
{
/// <summary>
/// Represents a definition of an EDM entity type.
/// </summary>
public class EdmEntityType : EdmStructuredType, IEdmEntityType
{
private readonly string namespaceName;
private readonly string name;
private List<IEdmStructuralProperty> declaredKey;
/// <summary>
/// Initializes a new instance of the <see cref="EdmEntityType"/> class.
/// </summary>
/// <param name="namespaceName">Namespace the entity belongs to.</param>
/// <param name="name">Name of the entity.</param>
public EdmEntityType(string namespaceName, string name)
: this(namespaceName, name, null, false, false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="EdmEntityType"/> class.
/// </summary>
/// <param name="namespaceName">Namespace the entity belongs to.</param>
/// <param name="name">Name of the entity.</param>
/// <param name="baseType">The base type of this entity type.</param>
public EdmEntityType(string namespaceName, string name, IEdmEntityType baseType)
: this(namespaceName, name, baseType, false, false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="EdmEntityType"/> class.
/// </summary>
/// <param name="namespaceName">Namespace the entity belongs to.</param>
/// <param name="name">Name of the entity.</param>
/// <param name="baseType">The base type of this entity type.</param>
/// <param name="isAbstract">Denotes an entity that cannot be instantiated.</param>
/// <param name="isOpen">Denotes if the type is open.</param>
public EdmEntityType(string namespaceName, string name, IEdmEntityType baseType, bool isAbstract, bool isOpen)
: base(isAbstract, isOpen, baseType)
{
EdmUtil.CheckArgumentNull(namespaceName, "namespaceName");
EdmUtil.CheckArgumentNull(name, "name");
this.namespaceName = namespaceName;
this.name = name;
}
/// <summary>
/// Gets the structural properties of the entity type that make up the entity key.
/// </summary>
public virtual IEnumerable<IEdmStructuralProperty> DeclaredKey
{
get { return this.declaredKey; }
}
/// <summary>
/// Gets the kind of this schema element.
/// </summary>
public EdmSchemaElementKind SchemaElementKind
{
get { return EdmSchemaElementKind.TypeDefinition; }
}
/// <summary>
/// Gets the namespace this schema element belongs to.
/// </summary>
public string Namespace
{
get { return this.namespaceName; }
}
/// <summary>
/// Gets the name of this element.
/// </summary>
public string Name
{
get { return this.name; }
}
/// <summary>
/// Gets the kind of this type.
/// </summary>
public override EdmTypeKind TypeKind
{
get { return EdmTypeKind.Entity; }
}
/// <summary>
/// Gets the term kind of the entity type.
/// </summary>
public EdmTermKind TermKind
{
get { return EdmTermKind.Type; }
}
/// <summary>
/// Adds the <paramref name="keyProperties"/> to the key of this entity type.
/// </summary>
/// <param name="keyProperties">The key properties.</param>
public void AddKeys(params IEdmStructuralProperty[] keyProperties)
{
this.AddKeys((IEnumerable<IEdmStructuralProperty>)keyProperties);
}
/// <summary>
/// Adds the <paramref name="keyProperties"/> to the key of this entity type.
/// </summary>
/// <param name="keyProperties">The key properties.</param>
public void AddKeys(IEnumerable<IEdmStructuralProperty> keyProperties)
{
EdmUtil.CheckArgumentNull(keyProperties, "keyProperties");
foreach (IEdmStructuralProperty property in keyProperties)
{
if (this.declaredKey == null)
{
this.declaredKey = new List<IEdmStructuralProperty>();
}
this.declaredKey.Add(property);
}
}
/// <summary>
/// Creates and adds a unidirectional navigation property to this type.
/// Default partner property is created, but not added to the navigation target type.
/// </summary>
/// <param name="propertyInfo">Information to create the navigation property.</param>
/// <returns>Created navigation property.</returns>
public EdmNavigationProperty AddUnidirectionalNavigation(EdmNavigationPropertyInfo propertyInfo)
{
return AddUnidirectionalNavigation(propertyInfo, this.FixUpDefaultPartnerInfo(propertyInfo, null));
}
/// <summary>
/// Creates and adds a unidirectional navigation property to this type.
/// Navigation property partner is created, but not added to the navigation target type.
/// </summary>
/// <param name="propertyInfo">Information to create the navigation property.</param>
/// <param name="partnerInfo">Information to create the partner navigation property.</param>
/// <returns>Created navigation property.</returns>
public EdmNavigationProperty AddUnidirectionalNavigation(EdmNavigationPropertyInfo propertyInfo, EdmNavigationPropertyInfo partnerInfo)
{
EdmUtil.CheckArgumentNull(propertyInfo, "propertyInfo");
EdmNavigationProperty property = EdmNavigationProperty.CreateNavigationPropertyWithPartner(propertyInfo, this.FixUpDefaultPartnerInfo(propertyInfo, partnerInfo));
this.AddProperty(property);
return property;
}
/// <summary>
/// Creates and adds a navigation property to this type and adds its navigation partner to the navigation target type.
/// </summary>
/// <param name="propertyInfo">Information to create the navigation property.</param>
/// <param name="partnerInfo">Information to create the partner navigation property.</param>
/// <returns>Created navigation property.</returns>
public EdmNavigationProperty AddBidirectionalNavigation(EdmNavigationPropertyInfo propertyInfo, EdmNavigationPropertyInfo partnerInfo)
{
EdmUtil.CheckArgumentNull(propertyInfo, "propertyInfo");
EdmUtil.CheckArgumentNull(propertyInfo.Target, "propertyInfo.Target");
EdmEntityType targetType = propertyInfo.Target as EdmEntityType;
if (targetType == null)
{
throw new ArgumentException("propertyInfo.Target", Strings.Constructable_TargetMustBeStock(typeof(EdmEntityType).FullName));
}
EdmNavigationProperty property = EdmNavigationProperty.CreateNavigationPropertyWithPartner(propertyInfo, this.FixUpDefaultPartnerInfo(propertyInfo, partnerInfo));
this.AddProperty(property);
targetType.AddProperty(property.Partner);
return property;
}
/// <summary>
/// The puspose of this method is to make sure that some of the <paramref name="partnerInfo"/> fields are set to valid partner defaults.
/// For example if <paramref name="partnerInfo"/>.Target is null, it will be set to this entity type. If <paramref name="partnerInfo"/>.TargetMultiplicity
/// is unknown, it will be set to 0..1, etc.
/// Whenever this method applies new values to <paramref name="partnerInfo"/>, it will return a copy of it (thus won't modify the original).
/// If <paramref name="partnerInfo"/> is null, a new info object will be produced.
/// </summary>
/// <param name="propertyInfo">Primary navigation property info.</param>
/// <param name="partnerInfo">Partner navigation property info. May be null.</param>
/// <returns>Partner info.</returns>
private EdmNavigationPropertyInfo FixUpDefaultPartnerInfo(EdmNavigationPropertyInfo propertyInfo, EdmNavigationPropertyInfo partnerInfo)
{
EdmNavigationPropertyInfo partnerInfoOverride = null;
if (partnerInfo == null)
{
partnerInfo = partnerInfoOverride = new EdmNavigationPropertyInfo();
}
if (partnerInfo.Name == null)
{
if (partnerInfoOverride == null)
{
partnerInfoOverride = partnerInfo.Clone();
}
partnerInfoOverride.Name = (propertyInfo.Name ?? String.Empty) + "Partner";
}
if (partnerInfo.Target == null)
{
if (partnerInfoOverride == null)
{
partnerInfoOverride = partnerInfo.Clone();
}
partnerInfoOverride.Target = this;
}
if (partnerInfo.TargetMultiplicity == EdmMultiplicity.Unknown)
{
if (partnerInfoOverride == null)
{
partnerInfoOverride = partnerInfo.Clone();
}
partnerInfoOverride.TargetMultiplicity = EdmMultiplicity.ZeroOrOne;
}
return partnerInfoOverride ?? partnerInfo;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Monitoring;
using OpenSim.Framework.Servers;
using OpenSim.Region.CoreModules.Framework.Monitoring.Alerts;
using OpenSim.Region.CoreModules.Framework.Monitoring.Monitors;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using Mono.Addins;
namespace OpenSim.Region.CoreModules.Framework.Monitoring
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MonitorModule")]
public class MonitorModule : INonSharedRegionModule
{
/// <summary>
/// Is this module enabled?
/// </summary>
public bool Enabled { get; private set; }
private Scene m_scene;
/// <summary>
/// These are monitors where we know the static details in advance.
/// </summary>
/// <remarks>
/// Dynamic monitors also exist (we don't know any of the details of what stats we get back here)
/// but these are currently hardcoded.
/// </remarks>
private readonly List<IMonitor> m_staticMonitors = new List<IMonitor>();
private readonly List<IAlert> m_alerts = new List<IAlert>();
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public MonitorModule()
{
Enabled = true;
}
#region Implementation of INonSharedRegionModule
public void Initialise(IConfigSource source)
{
IConfig cnfg = source.Configs["Monitoring"];
if (cnfg != null)
Enabled = cnfg.GetBoolean("Enabled", true);
if (!Enabled)
return;
}
public void AddRegion(Scene scene)
{
if (!Enabled)
return;
m_scene = scene;
m_scene.AddCommand("General", this, "monitor report",
"monitor report",
"Returns a variety of statistics about the current region and/or simulator",
DebugMonitors);
MainServer.Instance.AddHTTPHandler("/monitorstats/" + m_scene.RegionInfo.RegionID, StatsPage);
MainServer.Instance.AddHTTPHandler(
"/monitorstats/" + Uri.EscapeDataString(m_scene.RegionInfo.RegionName), StatsPage);
AddMonitors();
RegisterStatsManagerRegionStatistics();
}
public void RemoveRegion(Scene scene)
{
if (!Enabled)
return;
MainServer.Instance.RemoveHTTPHandler("GET", "/monitorstats/" + m_scene.RegionInfo.RegionID);
MainServer.Instance.RemoveHTTPHandler("GET", "/monitorstats/" + Uri.EscapeDataString(m_scene.RegionInfo.RegionName));
UnRegisterStatsManagerRegionStatistics();
m_scene = null;
}
public void Close()
{
}
public string Name
{
get { return "Region Health Monitoring Module"; }
}
public void RegionLoaded(Scene scene)
{
}
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
public void AddMonitors()
{
m_staticMonitors.Add(new AgentCountMonitor(m_scene));
m_staticMonitors.Add(new ChildAgentCountMonitor(m_scene));
m_staticMonitors.Add(new GCMemoryMonitor());
m_staticMonitors.Add(new ObjectCountMonitor(m_scene));
m_staticMonitors.Add(new PhysicsFrameMonitor(m_scene));
m_staticMonitors.Add(new PhysicsUpdateFrameMonitor(m_scene));
m_staticMonitors.Add(new PWSMemoryMonitor());
m_staticMonitors.Add(new ThreadCountMonitor());
m_staticMonitors.Add(new TotalFrameMonitor(m_scene));
m_staticMonitors.Add(new EventFrameMonitor(m_scene));
m_staticMonitors.Add(new LandFrameMonitor(m_scene));
m_staticMonitors.Add(new LastFrameTimeMonitor(m_scene));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"TimeDilationMonitor",
"Time Dilation",
m => m.Scene.StatsReporter.LastReportedSimStats[0],
m => m.GetValue().ToString()));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"SimFPSMonitor",
"Sim FPS",
m => m.Scene.StatsReporter.LastReportedSimStats[1],
m => string.Format("{0}", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"PhysicsFPSMonitor",
"Physics FPS",
m => m.Scene.StatsReporter.LastReportedSimStats[2],
m => string.Format("{0}", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"AgentUpdatesPerSecondMonitor",
"Agent Updates",
m => m.Scene.StatsReporter.LastReportedSimStats[3],
m => string.Format("{0} per second", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"ActiveObjectCountMonitor",
"Active Objects",
m => m.Scene.StatsReporter.LastReportedSimStats[7],
m => string.Format("{0}", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"ActiveScriptsMonitor",
"Active Scripts",
m => m.Scene.StatsReporter.LastReportedSimStats[19],
m => string.Format("{0}", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"ScriptEventsPerSecondMonitor",
"Script Events",
m => m.Scene.StatsReporter.LastReportedSimStats[20],
m => string.Format("{0} per second", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"InPacketsPerSecondMonitor",
"In Packets",
m => m.Scene.StatsReporter.LastReportedSimStats[13],
m => string.Format("{0} per second", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"OutPacketsPerSecondMonitor",
"Out Packets",
m => m.Scene.StatsReporter.LastReportedSimStats[14],
m => string.Format("{0} per second", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"UnackedBytesMonitor",
"Unacked Bytes",
m => m.Scene.StatsReporter.LastReportedSimStats[15],
m => string.Format("{0}", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"PendingDownloadsMonitor",
"Pending Downloads",
m => m.Scene.StatsReporter.LastReportedSimStats[17],
m => string.Format("{0}", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"PendingUploadsMonitor",
"Pending Uploads",
m => m.Scene.StatsReporter.LastReportedSimStats[18],
m => string.Format("{0}", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"TotalFrameTimeMonitor",
"Total Frame Time",
m => m.Scene.StatsReporter.LastReportedSimStats[8],
m => string.Format("{0} ms", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"NetFrameTimeMonitor",
"Net Frame Time",
m => m.Scene.StatsReporter.LastReportedSimStats[9],
m => string.Format("{0} ms", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"PhysicsFrameTimeMonitor",
"Physics Frame Time",
m => m.Scene.StatsReporter.LastReportedSimStats[10],
m => string.Format("{0} ms", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"SimulationFrameTimeMonitor",
"Simulation Frame Time",
m => m.Scene.StatsReporter.LastReportedSimStats[12],
m => string.Format("{0} ms", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"AgentFrameTimeMonitor",
"Agent Frame Time",
m => m.Scene.StatsReporter.LastReportedSimStats[16],
m => string.Format("{0} ms", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"ImagesFrameTimeMonitor",
"Images Frame Time",
m => m.Scene.StatsReporter.LastReportedSimStats[11],
m => string.Format("{0} ms", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"SpareFrameTimeMonitor",
"Spare Frame Time",
m => m.Scene.StatsReporter.LastReportedSimStats[21],
m => string.Format("{0} ms", m.GetValue())));
m_alerts.Add(new DeadlockAlert(m_staticMonitors.Find(x => x is LastFrameTimeMonitor) as LastFrameTimeMonitor));
foreach (IAlert alert in m_alerts)
{
alert.OnTriggerAlert += OnTriggerAlert;
}
}
public void DebugMonitors(string module, string[] args)
{
foreach (IMonitor monitor in m_staticMonitors)
{
MainConsole.Instance.OutputFormat(
"[MONITOR MODULE]: {0} reports {1} = {2}",
m_scene.RegionInfo.RegionName, monitor.GetFriendlyName(), monitor.GetFriendlyValue());
}
foreach (KeyValuePair<string, float> tuple in m_scene.StatsReporter.GetExtraSimStats())
{
MainConsole.Instance.OutputFormat(
"[MONITOR MODULE]: {0} reports {1} = {2}",
m_scene.RegionInfo.RegionName, tuple.Key, tuple.Value);
}
}
public void TestAlerts()
{
foreach (IAlert alert in m_alerts)
{
alert.Test();
}
}
public Hashtable StatsPage(Hashtable request)
{
// If request was for a specific monitor
// eg url/?monitor=Monitor.Name
if (request.ContainsKey("monitor"))
{
string monID = (string) request["monitor"];
foreach (IMonitor monitor in m_staticMonitors)
{
string elemName = monitor.ToString();
if (elemName.StartsWith(monitor.GetType().Namespace))
elemName = elemName.Substring(monitor.GetType().Namespace.Length + 1);
if (elemName == monID || monitor.ToString() == monID)
{
Hashtable ereply3 = new Hashtable();
ereply3["int_response_code"] = 404; // 200 OK
ereply3["str_response_string"] = monitor.GetValue().ToString();
ereply3["content_type"] = "text/plain";
return ereply3;
}
}
// FIXME: Arguably this should also be done with dynamic monitors but I'm not sure what the above code
// is even doing. Why are we inspecting the type of the monitor???
// No monitor with that name
Hashtable ereply2 = new Hashtable();
ereply2["int_response_code"] = 404; // 200 OK
ereply2["str_response_string"] = "No such monitor";
ereply2["content_type"] = "text/plain";
return ereply2;
}
string xml = "<data>";
foreach (IMonitor monitor in m_staticMonitors)
{
string elemName = monitor.GetName();
xml += "<" + elemName + ">" + monitor.GetValue().ToString() + "</" + elemName + ">";
// m_log.DebugFormat("[MONITOR MODULE]: {0} = {1}", elemName, monitor.GetValue());
}
foreach (KeyValuePair<string, float> tuple in m_scene.StatsReporter.GetExtraSimStats())
{
xml += "<" + tuple.Key + ">" + tuple.Value + "</" + tuple.Key + ">";
}
xml += "</data>";
Hashtable ereply = new Hashtable();
ereply["int_response_code"] = 200; // 200 OK
ereply["str_response_string"] = xml;
ereply["content_type"] = "text/xml";
return ereply;
}
void OnTriggerAlert(System.Type reporter, string reason, bool fatal)
{
m_log.Error("[Monitor] " + reporter.Name + " for " + m_scene.RegionInfo.RegionName + " reports " + reason + " (Fatal: " + fatal + ")");
}
private List<Stat> registeredStats = new List<Stat>();
private void MakeStat(string pName, string pUnitName, Action<Stat> act)
{
Stat tempStat = new Stat(pName, pName, pName, pUnitName, "scene", m_scene.RegionInfo.RegionName, StatType.Pull, act, StatVerbosity.Info);
StatsManager.RegisterStat(tempStat);
registeredStats.Add(tempStat);
}
private void RegisterStatsManagerRegionStatistics()
{
MakeStat("RootAgents", "avatars", (s) => { s.Value = m_scene.SceneGraph.GetRootAgentCount(); });
MakeStat("ChildAgents", "avatars", (s) => { s.Value = m_scene.SceneGraph.GetChildAgentCount(); });
MakeStat("TotalPrims", "objects", (s) => { s.Value = m_scene.SceneGraph.GetTotalObjectsCount(); });
MakeStat("ActivePrims", "objects", (s) => { s.Value = m_scene.SceneGraph.GetActiveObjectsCount(); });
MakeStat("ActiveScripts", "scripts", (s) => { s.Value = m_scene.SceneGraph.GetActiveScriptsCount(); });
MakeStat("TimeDilation", "sec/sec", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[0]; });
MakeStat("SimFPS", "fps", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[1]; });
MakeStat("PhysicsFPS", "fps", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[2]; });
MakeStat("AgentUpdates", "updates/sec", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[3]; });
MakeStat("FrameTime", "ms/sec", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[8]; });
MakeStat("NetTime", "ms/sec", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[9]; });
MakeStat("OtherTime", "ms/sec", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[12]; });
MakeStat("PhysicsTime", "ms/sec", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[10]; });
MakeStat("AgentTime", "ms/sec", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[16]; });
MakeStat("ImageTime", "ms/sec", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[11]; });
MakeStat("ScriptLines", "lines/sec", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[20]; });
MakeStat("SimSpareMS", "ms/sec", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[21]; });
}
private void UnRegisterStatsManagerRegionStatistics()
{
foreach (Stat stat in registeredStats)
{
StatsManager.DeregisterStat(stat);
stat.Dispose();
}
registeredStats.Clear();
}
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine.Serialization;
using UnityEngine.Rendering;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
[Serializable]
public class HDPhysicalCamera
{
public const float kMinAperture = 1f;
public const float kMaxAperture = 32f;
public const int kMinBladeCount = 3;
public const int kMaxBladeCount = 11;
// Camera body
[SerializeField] [Min(1f)] int m_Iso = 200;
[SerializeField] [Min(0f)] float m_ShutterSpeed = 1f / 200f;
// Lens
// Note: focalLength is already defined in the regular camera component
[SerializeField] [Range(kMinAperture, kMaxAperture)] float m_Aperture = 16f;
// Aperture shape
[SerializeField] [Range(kMinBladeCount, kMaxBladeCount)] int m_BladeCount = 5;
[SerializeField] Vector2 m_Curvature = new Vector2(2f, 11f);
[SerializeField] [Range(0f, 1f)] float m_BarrelClipping = 0.25f;
[SerializeField] [Range(-1f, 1f)] float m_Anamorphism = 0f;
// Property binding / validation
public int iso
{
get => m_Iso;
set => m_Iso = Mathf.Max(value, 1);
}
public float shutterSpeed
{
get => m_ShutterSpeed;
set => m_ShutterSpeed = Mathf.Max(value, 0f);
}
public float aperture
{
get => m_Aperture;
set => m_Aperture = Mathf.Clamp(value, kMinAperture, kMaxAperture);
}
public int bladeCount
{
get => m_BladeCount;
set => m_BladeCount = Mathf.Clamp(value, kMinBladeCount, kMaxBladeCount);
}
public Vector2 curvature
{
get => m_Curvature;
set
{
m_Curvature.x = Mathf.Max(value.x, kMinAperture);
m_Curvature.y = Mathf.Min(value.y, kMaxAperture);
}
}
public float barrelClipping
{
get => m_BarrelClipping;
set => m_BarrelClipping = Mathf.Clamp01(value);
}
public float anamorphism
{
get => m_Anamorphism;
set => m_Anamorphism = Mathf.Clamp(value, -1f, 1f);
}
public void CopyTo(HDPhysicalCamera c)
{
c.iso = iso;
c.shutterSpeed = shutterSpeed;
c.aperture = aperture;
c.bladeCount = bladeCount;
c.curvature = curvature;
c.barrelClipping = barrelClipping;
c.anamorphism = anamorphism;
}
}
[DisallowMultipleComponent, ExecuteAlways]
[RequireComponent(typeof(Camera))]
public partial class HDAdditionalCameraData : MonoBehaviour
{
public enum FlipYMode
{
Automatic,
ForceFlipY
}
// The light culling use standard projection matrices (non-oblique)
// If the user overrides the projection matrix with an oblique one
// He must also provide a callback to get the equivalent non oblique for the culling
public delegate Matrix4x4 NonObliqueProjectionGetter(Camera camera);
Camera m_camera;
public enum ClearColorMode
{
Sky,
Color,
None
};
public enum AntialiasingMode
{
None,
FastApproximateAntialiasing,
TemporalAntialiasing,
SubpixelMorphologicalAntiAliasing
}
public enum SMAAQualityLevel
{
Low,
Medium,
High
}
public ClearColorMode clearColorMode = ClearColorMode.Sky;
[ColorUsage(true, true)]
public Color backgroundColorHDR = new Color(0.025f, 0.07f, 0.19f, 0.0f);
public bool clearDepth = true;
[Tooltip("LayerMask HDRP uses for Volume interpolation for this Camera.")]
public LayerMask volumeLayerMask = 1;
public Transform volumeAnchorOverride;
public AntialiasingMode antialiasing = AntialiasingMode.None;
public SMAAQualityLevel SMAAQuality = SMAAQualityLevel.High;
public bool dithering = false;
public bool stopNaNs = false;
// Physical parameters
public HDPhysicalCamera physicalParameters = new HDPhysicalCamera();
public FlipYMode flipYMode;
[Tooltip("Skips rendering settings to directly render in fullscreen (Useful for video).")]
public bool fullscreenPassthrough = false;
[Tooltip("Allows dynamic resolution on buffers linked to this camera.")]
public bool allowDynamicResolution = false;
[Tooltip("Allows you to override the default settings for this Renderer.")]
public bool customRenderingSettings = false;
public bool invertFaceCulling = false;
public LayerMask probeLayerMask = ~0;
// Event used to override HDRP rendering for this particular camera.
public event Action<ScriptableRenderContext, HDCamera> customRender;
public bool hasCustomRender { get { return customRender != null; } }
[SerializeField, FormerlySerializedAs("renderingPathCustomFrameSettings")]
FrameSettings m_RenderingPathCustomFrameSettings = FrameSettings.defaultCamera;
public FrameSettingsOverrideMask renderingPathCustomFrameSettingsOverrideMask;
public FrameSettingsRenderType defaultFrameSettings;
public ref FrameSettings renderingPathCustomFrameSettings => ref m_RenderingPathCustomFrameSettings;
AOVRequestDataCollection m_AOVRequestDataCollection = new AOVRequestDataCollection(null);
/// <summary>Set AOV requests to use.</summary>
/// <param name="aovRequests">Describes the requests to execute.</param>
/// <example>
/// <code>
/// using System.Collections.Generic;
/// using UnityEngine;
/// using UnityEngine.Experimental.Rendering;
/// using UnityEngine.Experimental.Rendering.HDPipeline;
/// using UnityEngine.Experimental.Rendering.HDPipeline.Attributes;
///
/// [ExecuteAlways]
/// [RequireComponent(typeof(Camera))]
/// [RequireComponent(typeof(HDAdditionalCameraData))]
/// public class SetupAOVCallbacks : MonoBehaviour
/// {
/// private static RTHandleSystem.RTHandle m_ColorRT;
///
/// [SerializeField] private Texture m_Target;
/// [SerializeField] private DebugFullScreen m_DebugFullScreen;
/// [SerializeField] private DebugLightFilterMode m_DebugLightFilter;
/// [SerializeField] private MaterialSharedProperty m_MaterialSharedProperty;
/// [SerializeField] private LightingProperty m_LightingProperty;
/// [SerializeField] private AOVBuffers m_BuffersToCopy;
/// [SerializeField] private List<GameObject> m_IncludedLights;
///
///
/// void OnEnable()
/// {
/// var aovRequest = new AOVRequest(AOVRequest.@default)
/// .SetLightFilter(m_DebugLightFilter);
/// if (m_DebugFullScreen != DebugFullScreen.None)
/// aovRequest = aovRequest.SetFullscreenOutput(m_DebugFullScreen);
/// if (m_MaterialSharedProperty != MaterialSharedProperty.None)
/// aovRequest = aovRequest.SetFullscreenOutput(m_MaterialSharedProperty);
/// if (m_LightingProperty != LightingProperty.None)
/// aovRequest = aovRequest.SetFullscreenOutput(m_LightingProperty);
///
/// var add = GetComponent<HDAdditionalCameraData>();
/// add.SetAOVRequests(
/// new AOVRequestBuilder()
/// .Add(
/// aovRequest,
/// bufferId => m_ColorRT ?? (m_ColorRT = RTHandles.Alloc(512, 512)),
/// m_IncludedLights.Count > 0 ? m_IncludedLights : null,
/// new []{ m_BuffersToCopy },
/// (cmd, textures, properties) =>
/// {
/// if (m_Target != null)
/// cmd.Blit(textures[0], m_Target);
/// })
/// .Build()
/// );
/// }
///
/// private void OnGUI()
/// {
/// GUI.DrawTexture(new Rect(10, 10, 512, 256), m_Target);
/// }
///
/// void OnDisable()
/// {
/// var add = GetComponent<HDAdditionalCameraData>();
/// add.SetAOVRequests(null);
/// }
///
/// void OnValidate()
/// {
/// OnDisable();
/// OnEnable();
/// }
/// }
/// </code>
///
/// Example use case:
/// * Export Normals: use MaterialSharedProperty.Normals and AOVBuffers.Color
/// * Export Color before post processing: use AOVBuffers.Color
/// * Export Color after post processing: use AOVBuffers.Output
/// * Export Depth stencil: use AOVBuffers.DepthStencil
/// * Export AO: use MaterialSharedProperty.AmbientOcclusion and AOVBuffers.Color
/// </example>
public void SetAOVRequests(AOVRequestDataCollection aovRequests)
=> m_AOVRequestDataCollection = aovRequests;
/// <summary>
/// Use this property to get the aov requests.
///
/// It is never null.
/// </summary>
public IEnumerable<AOVRequestData> aovRequests =>
m_AOVRequestDataCollection ?? (m_AOVRequestDataCollection = new AOVRequestDataCollection(null));
// Use for debug windows
// When camera name change we need to update the name in DebugWindows.
// This is the purpose of this class
bool m_IsDebugRegistered = false;
string m_CameraRegisterName;
public bool IsDebugRegistred()
{
return m_IsDebugRegistered;
}
// When we are a preview, there is no way inside Unity to make a distinction between camera preview and material preview.
// This property allow to say that we are an editor camera preview when the type is preview.
public bool isEditorCameraPreview { get; set; }
// This is use to copy data into camera for the Reset() workflow in camera editor
public void CopyTo(HDAdditionalCameraData data)
{
data.clearColorMode = clearColorMode;
data.backgroundColorHDR = backgroundColorHDR;
data.clearDepth = clearDepth;
data.customRenderingSettings = customRenderingSettings;
data.volumeLayerMask = volumeLayerMask;
data.volumeAnchorOverride = volumeAnchorOverride;
data.antialiasing = antialiasing;
data.dithering = dithering;
physicalParameters.CopyTo(data.physicalParameters);
data.renderingPathCustomFrameSettings = renderingPathCustomFrameSettings;
data.renderingPathCustomFrameSettingsOverrideMask = renderingPathCustomFrameSettingsOverrideMask;
data.defaultFrameSettings = defaultFrameSettings;
// We must not copy the following
//data.m_IsDebugRegistered = m_IsDebugRegistered;
//data.m_CameraRegisterName = m_CameraRegisterName;
//data.isEditorCameraPreview = isEditorCameraPreview;
}
// For custom projection matrices
// Set the proper getter
public NonObliqueProjectionGetter nonObliqueProjectionGetter = GeometryUtils.CalculateProjectionMatrix;
public Matrix4x4 GetNonObliqueProjection(Camera camera)
{
return nonObliqueProjectionGetter(camera);
}
void RegisterDebug()
{
if (!m_IsDebugRegistered)
{
// Note that we register FrameSettingsHistory, so manipulating FrameSettings in the Debug windows
// doesn't affect the serialized version
// Note camera's preview camera is registered with preview type but then change to game type that lead to issue.
// Do not attempt to not register them till this issue persist.
if (/*m_camera.cameraType != CameraType.Preview &&*/ m_camera.cameraType != CameraType.Reflection)
{
DebugDisplaySettings.RegisterCamera(m_camera, this);
}
m_CameraRegisterName = m_camera.name;
m_IsDebugRegistered = true;
}
}
void UnRegisterDebug()
{
if (m_camera == null)
return;
if (m_IsDebugRegistered)
{
// Note camera's preview camera is registered with preview type but then change to game type that lead to issue.
// Do not attempt to not register them till this issue persist.
if (/*m_camera.cameraType != CameraType.Preview &&*/ m_camera.cameraType != CameraType.Reflection)
{
DebugDisplaySettings.UnRegisterCamera(m_camera, this);
}
m_IsDebugRegistered = false;
}
}
void OnEnable()
{
// Be sure legacy HDR option is disable on camera as it cause banding in SceneView. Yes, it is a contradiction, but well, Unity...
// When HDR option is enabled, Unity render in FP16 then convert to 8bit with a stretch copy (this cause banding as it should be convert to sRGB (or other color appropriate color space)), then do a final shader with sRGB conversion
// When LDR, unity render in 8bitSRGB, then do a final shader with sRGB conversion
// What should be done is just in our Post process we convert to sRGB and store in a linear 10bit, but require C++ change...
m_camera = GetComponent<Camera>();
if (m_camera == null)
return;
m_camera.allowMSAA = false; // We don't use this option in HD (it is legacy MSAA) and it produce a warning in the inspector UI if we let it
m_camera.allowHDR = false;
RegisterDebug();
}
void Update()
{
// We need to detect name change in the editor and update debug windows accordingly
#if UNITY_EDITOR
// Caution: Object.name generate 48B of garbage at each frame here !
if (m_camera.name != m_CameraRegisterName)
{
UnRegisterDebug();
RegisterDebug();
}
#endif
}
void OnDisable()
{
UnRegisterDebug();
}
// This is called at the creation of the HD Additional Camera Data, to convert the legacy camera settings to HD
public static void InitDefaultHDAdditionalCameraData(HDAdditionalCameraData cameraData)
{
var camera = cameraData.gameObject.GetComponent<Camera>();
cameraData.clearDepth = camera.clearFlags != CameraClearFlags.Nothing;
if (camera.clearFlags == CameraClearFlags.Skybox)
cameraData.clearColorMode = ClearColorMode.Sky;
else if (camera.clearFlags == CameraClearFlags.SolidColor)
cameraData.clearColorMode = ClearColorMode.Color;
else // None
cameraData.clearColorMode = ClearColorMode.None;
}
public void ExecuteCustomRender(ScriptableRenderContext renderContext, HDCamera hdCamera)
{
if (customRender != null)
{
customRender(renderContext, hdCamera);
}
}
}
}
| |
// 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.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using Xunit;
namespace System.Net.Sockets.Tests
{
// TODO:
//
// - Connect(EndPoint):
// - disconnected socket
// - Accept(EndPoint):
// - disconnected socket
public class ArgumentValidation
{
// This type is used to test Socket.Select's argument validation.
private sealed class LargeList : IList
{
private const int MaxSelect = 65536;
public int Count { get { return MaxSelect + 1; } }
public bool IsFixedSize { get { return true; } }
public bool IsReadOnly { get { return true; } }
public bool IsSynchronized { get { return false; } }
public object SyncRoot { get { return null; } }
public object this[int index]
{
get { return null; }
set { }
}
public int Add(object value) { return -1; }
public void Clear() { }
public bool Contains(object value) { return false; }
public void CopyTo(Array array, int index) { }
public IEnumerator GetEnumerator() { return null; }
public int IndexOf(object value) { return -1; }
public void Insert(int index, object value) { }
public void Remove(object value) { }
public void RemoveAt(int index) { }
}
private readonly static byte[] s_buffer = new byte[1];
private readonly static IList<ArraySegment<byte>> s_buffers = new List<ArraySegment<byte>> { new ArraySegment<byte>(s_buffer) };
private readonly static SocketAsyncEventArgs s_eventArgs = new SocketAsyncEventArgs();
private readonly static Socket s_ipv4Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private readonly static Socket s_ipv6Socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
private static Socket GetSocket(AddressFamily addressFamily = AddressFamily.InterNetwork)
{
Debug.Assert(addressFamily == AddressFamily.InterNetwork || addressFamily == AddressFamily.InterNetworkV6);
return addressFamily == AddressFamily.InterNetwork ? s_ipv4Socket : s_ipv6Socket;
}
[Fact]
public void SetExclusiveAddressUse_BoundSocket_Throws_InvalidOperation()
{
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
Assert.Throws<InvalidOperationException>(() =>
{
socket.ExclusiveAddressUse = true;
});
}
}
[Fact]
public void SetReceiveBufferSize_Negative_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
GetSocket().ReceiveBufferSize = -1;
});
}
[Fact]
public void SetSendBufferSize_Negative_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
GetSocket().SendBufferSize = -1;
});
}
[Fact]
public void SetReceiveTimeout_LessThanNegativeOne_Throws_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
GetSocket().ReceiveTimeout = int.MinValue;
});
}
[Fact]
public void SetSendTimeout_LessThanNegativeOne_Throws_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
GetSocket().SendTimeout = int.MinValue;
});
}
[Fact]
public void SetTtl_OutOfRange_Throws_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
GetSocket().Ttl = -1;
});
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
GetSocket().Ttl = 256;
});
}
[Fact]
public void DontFragment_IPv6_Throws_NotSupported()
{
Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetworkV6).DontFragment);
}
[Fact]
public void SetDontFragment_Throws_NotSupported()
{
Assert.Throws<NotSupportedException>(() =>
{
GetSocket(AddressFamily.InterNetworkV6).DontFragment = true;
});
}
[Fact]
public void Bind_Throws_NullEndPoint_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().Bind(null));
}
[Fact]
public void Connect_EndPoint_NullEndPoint_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().Connect(null));
}
[Fact]
public void Connect_EndPoint_ListeningSocket_Throws_InvalidOperation()
{
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
socket.Listen(1);
Assert.Throws<InvalidOperationException>(() => socket.Connect(new IPEndPoint(IPAddress.Loopback, 1)));
}
}
[Fact]
public void Connect_IPAddress_NullIPAddress_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().Connect((IPAddress)null, 1));
}
[Fact]
public void Connect_IPAddress_InvalidPort_Throws_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(IPAddress.Loopback, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(IPAddress.Loopback, 65536));
}
[Fact]
public void Connect_IPAddress_InvalidAddressFamily_Throws_NotSupported()
{
Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).Connect(IPAddress.IPv6Loopback, 1));
Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetworkV6).Connect(IPAddress.Loopback, 1));
}
[Fact]
public void Connect_Host_NullHost_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().Connect((string)null, 1));
}
[Fact]
public void Connect_Host_InvalidPort_Throws_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect("localhost", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect("localhost", 65536));
}
[Fact]
public void Connect_IPAddresses_NullArray_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().Connect((IPAddress[])null, 1));
}
[Fact]
public void Connect_IPAddresses_EmptyArray_Throws_Argument()
{
Assert.Throws<ArgumentException>(() => GetSocket().Connect(new IPAddress[0], 1));
}
[Fact]
public void Connect_IPAddresses_InvalidPort_Throws_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(new[] { IPAddress.Loopback }, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(new[] { IPAddress.Loopback }, 65536));
}
[Fact]
public void Close_TimeoutLessThanNegativeOne_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Close(-2));
}
[Fact]
public void Accept_NotBound_Throws_InvalidOperation()
{
Assert.Throws<InvalidOperationException>(() => GetSocket().Accept());
}
[Fact]
public void Accept_NotListening_Throws_InvalidOperation()
{
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
Assert.Throws<InvalidOperationException>(() => socket.Accept());
}
}
[Fact]
public void Send_Buffer_NullBuffer_Throws_ArgumentNull()
{
SocketError errorCode;
Assert.Throws<ArgumentNullException>(() => GetSocket().Send(null, 0, 0, SocketFlags.None, out errorCode));
}
[Fact]
public void Send_Buffer_InvalidOffset_Throws_ArgumentOutOfRange()
{
SocketError errorCode;
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, -1, 0, SocketFlags.None, out errorCode));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, out errorCode));
}
[Fact]
public void Send_Buffer_InvalidCount_Throws_ArgumentOutOfRange()
{
SocketError errorCode;
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, 0, -1, SocketFlags.None, out errorCode));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, out errorCode));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, s_buffer.Length, 1, SocketFlags.None, out errorCode));
}
[Fact]
public void Send_Buffers_NullBuffers_Throws_ArgumentNull()
{
SocketError errorCode;
Assert.Throws<ArgumentNullException>(() => GetSocket().Send(null, SocketFlags.None, out errorCode));
}
[Fact]
public void Send_Buffers_EmptyBuffers_Throws_Argument()
{
SocketError errorCode;
Assert.Throws<ArgumentException>(() => GetSocket().Send(new List<ArraySegment<byte>>(), SocketFlags.None, out errorCode));
}
[Fact]
public void SendTo_NullBuffer_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().SendTo(null, 0, 0, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1)));
}
[Fact]
public void SendTo_NullEndPoint_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().SendTo(s_buffer, 0, 0, SocketFlags.None, null));
}
[Fact]
public void SendTo_InvalidOffset_Throws_ArgumentOutOfRange()
{
EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, -1, s_buffer.Length, SocketFlags.None, endpoint));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, endpoint));
}
[Fact]
public void SendTo_InvalidSize_Throws_ArgumentOutOfRange()
{
EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, 0, -1, SocketFlags.None, endpoint));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, endpoint));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, s_buffer.Length, 1, SocketFlags.None, endpoint));
}
[Fact]
public void Receive_Buffer_NullBuffer_Throws_ArgumentNull()
{
SocketError errorCode;
Assert.Throws<ArgumentNullException>(() => GetSocket().Receive(null, 0, 0, SocketFlags.None, out errorCode));
}
[Fact]
public void Receive_Buffer_InvalidOffset_Throws_ArgumentOutOfRange()
{
SocketError errorCode;
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, -1, 0, SocketFlags.None, out errorCode));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, out errorCode));
}
[Fact]
public void Receive_Buffer_InvalidCount_Throws_ArgumentOutOfRange()
{
SocketError errorCode;
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, 0, -1, SocketFlags.None, out errorCode));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, out errorCode));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, s_buffer.Length, 1, SocketFlags.None, out errorCode));
}
[Fact]
public void Receive_Buffers_NullBuffers_Throws_ArgumentNull()
{
SocketError errorCode;
Assert.Throws<ArgumentNullException>(() => GetSocket().Receive(null, SocketFlags.None, out errorCode));
}
[Fact]
public void Receive_Buffers_EmptyBuffers_Throws_Argument()
{
SocketError errorCode;
Assert.Throws<ArgumentException>(() => GetSocket().Receive(new List<ArraySegment<byte>>(), SocketFlags.None, out errorCode));
}
[Fact]
public void ReceiveFrom_NullBuffer_Throws_ArgumentNull()
{
EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFrom(null, 0, 0, SocketFlags.None, ref endpoint));
}
[Fact]
public void ReceiveFrom_NullEndPoint_Throws_ArgumentNull()
{
EndPoint endpoint = null;
Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint));
}
[Fact]
public void ReceiveFrom_AddressFamily_Throws_Argument()
{
EndPoint endpoint = new IPEndPoint(IPAddress.IPv6Loopback, 1);
Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).ReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint));
}
[Fact]
public void ReceiveFrom_InvalidOffset_Throws_ArgumentOutOfRange()
{
EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, -1, s_buffer.Length, SocketFlags.None, ref endpoint));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, ref endpoint));
}
[Fact]
public void ReceiveFrom_InvalidSize_Throws_ArgumentOutOfRange()
{
EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, 0, -1, SocketFlags.None, ref endpoint));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, ref endpoint));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, s_buffer.Length, 1, SocketFlags.None, ref endpoint));
}
[Fact]
public void ReceiveFrom_NotBound_Throws_InvalidOperation()
{
EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<InvalidOperationException>(() => GetSocket().ReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint));
}
[Fact]
public void ReceiveMessageFrom_NullBuffer_Throws_ArgumentNull()
{
SocketFlags flags = SocketFlags.None;
EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1);
IPPacketInformation packetInfo;
Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFrom(null, 0, 0, ref flags, ref remote, out packetInfo));
}
[Fact]
public void ReceiveMessageFrom_NullEndPoint_Throws_ArgumentNull()
{
SocketFlags flags = SocketFlags.None;
EndPoint remote = null;
IPPacketInformation packetInfo;
Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, 0, ref flags, ref remote, out packetInfo));
}
[Fact]
public void ReceiveMessageFrom_AddressFamily_Throws_Argument()
{
SocketFlags flags = SocketFlags.None;
EndPoint remote = new IPEndPoint(IPAddress.IPv6Loopback, 1);
IPPacketInformation packetInfo;
Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).ReceiveMessageFrom(s_buffer, 0, 0, ref flags, ref remote, out packetInfo));
}
[Fact]
public void ReceiveMessageFrom_InvalidOffset_Throws_ArgumentOutOfRange()
{
SocketFlags flags = SocketFlags.None;
EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1);
IPPacketInformation packetInfo;
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, -1, s_buffer.Length, ref flags, ref remote, out packetInfo));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, ref flags, ref remote, out packetInfo));
}
[Fact]
public void ReceiveMessageFrom_InvalidSize_Throws_ArgumentOutOfRange()
{
SocketFlags flags = SocketFlags.None;
EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1);
IPPacketInformation packetInfo;
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, -1, ref flags, ref remote, out packetInfo));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, s_buffer.Length + 1, ref flags, ref remote, out packetInfo));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, s_buffer.Length, 1, ref flags, ref remote, out packetInfo));
}
[Fact]
public void ReceiveMessageFrom_NotBound_Throws_InvalidOperation()
{
SocketFlags flags = SocketFlags.None;
EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1);
IPPacketInformation packetInfo;
Assert.Throws<InvalidOperationException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, 0, ref flags, ref remote, out packetInfo));
}
[Fact]
public void SetIPProtectionLevel_Unspecified_Throws_Argument()
{
Assert.Throws<ArgumentException>(() => GetSocket().SetIPProtectionLevel(IPProtectionLevel.Unspecified));
}
[Fact]
public void SetSocketOption_Object_ObjectNull_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, (object)null));
}
[Fact]
public void SetSocketOption_Linger_NotLingerOption_Throws_Argument()
{
Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new object()));
}
[Fact]
public void SetSocketOption_Linger_InvalidLingerTime_Throws_Argument()
{
Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, -1)));
Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, (int)ushort.MaxValue + 1)));
}
[Fact]
public void SetSocketOption_IPMulticast_NotIPMulticastOption_Throws_Argument()
{
Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new object()));
Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DropMembership, new object()));
}
[Fact]
public void SetSocketOption_IPv6Multicast_NotIPMulticastOption_Throws_Argument()
{
Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.AddMembership, new object()));
Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.DropMembership, new object()));
}
[Fact]
public void SetSocketOption_Object_InvalidOptionName_Throws_Argument()
{
Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, new object()));
}
// TODO: Select
[Fact]
public void Select_NullOrEmptyLists_Throws_ArgumentNull()
{
var emptyList = new List<Socket>();
Assert.Throws<ArgumentNullException>(() => Socket.Select(null, null, null, -1));
Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, null, null, -1));
Assert.Throws<ArgumentNullException>(() => Socket.Select(null, emptyList, null, -1));
Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, emptyList, null, -1));
Assert.Throws<ArgumentNullException>(() => Socket.Select(null, null, emptyList, -1));
Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, null, emptyList, -1));
Assert.Throws<ArgumentNullException>(() => Socket.Select(null, emptyList, emptyList, -1));
Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, emptyList, emptyList, -1));
}
[Fact]
public void Select_LargeList_Throws_ArgumentOutOfRange()
{
var largeList = new LargeList();
Assert.Throws<ArgumentOutOfRangeException>(() => Socket.Select(largeList, null, null, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => Socket.Select(null, largeList, null, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => Socket.Select(null, null, largeList, -1));
}
[Fact]
public void AcceptAsync_NullAsyncEventArgs_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().AcceptAsync(null));
}
[Fact]
public void AcceptAsync_BufferList_Throws_Argument()
{
var eventArgs = new SocketAsyncEventArgs {
BufferList = s_buffers
};
Assert.Throws<ArgumentException>(() => GetSocket().AcceptAsync(eventArgs));
}
[Fact]
public void AcceptAsync_NotBound_Throws_InvalidOperation()
{
Assert.Throws<InvalidOperationException>(() => GetSocket().AcceptAsync(s_eventArgs));
}
[Fact]
public void AcceptAsync_NotListening_Throws_InvalidOperation()
{
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
Assert.Throws<InvalidOperationException>(() => socket.AcceptAsync(s_eventArgs));
}
}
[Fact]
public void ConnectAsync_NullAsyncEventArgs_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().ConnectAsync(null));
}
[Fact]
public void ConnectAsync_BufferList_Throws_Argument()
{
var eventArgs = new SocketAsyncEventArgs {
BufferList = s_buffers
};
Assert.Throws<ArgumentException>(() => GetSocket().ConnectAsync(eventArgs));
}
[Fact]
public void ConnectAsync_NullRemoteEndPoint_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().ConnectAsync(s_eventArgs));
}
[Fact]
public void ConnectAsync_ListeningSocket_Throws_InvalidOperation()
{
var eventArgs = new SocketAsyncEventArgs {
RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, 1)
};
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
socket.Listen(1);
Assert.Throws<InvalidOperationException>(() => socket.ConnectAsync(eventArgs));
}
}
[Fact]
public void ConnectAsync_AddressFamily_Throws_NotSupported()
{
var eventArgs = new SocketAsyncEventArgs {
RemoteEndPoint = new DnsEndPoint("localhost", 1, AddressFamily.InterNetworkV6)
};
Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).ConnectAsync(eventArgs));
eventArgs.RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1);
Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).ConnectAsync(eventArgs));
}
[Fact]
public void ConnectAsync_Static_NullAsyncEventArgs_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, null));
}
[Fact]
public void ConnectAsync_Static_BufferList_Throws_Argument()
{
var eventArgs = new SocketAsyncEventArgs {
BufferList = s_buffers
};
Assert.Throws<ArgumentException>(() => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, eventArgs));
}
[Fact]
public void ConnectAsync_Static_NullRemoteEndPoint_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, s_eventArgs));
}
[Fact]
public void DisconnectAsync_NullAsyncEventArgs_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().DisconnectAsync(null));
}
[Fact]
public void ReceiveAsync_NullAsyncEventArgs_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveAsync(null));
}
[Fact]
public void ReceiveFromAsync_NullAsyncEventArgs_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFromAsync(null));
}
[Fact]
public void ReceiveFromAsync_NullRemoteEndPoint_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFromAsync(s_eventArgs));
}
[Fact]
public void ReceiveFromAsync_AddressFamily_Throws_Argument()
{
var eventArgs = new SocketAsyncEventArgs {
RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1)
};
Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).ReceiveFromAsync(eventArgs));
}
[Fact]
public void ReceiveMessageFromAsync_NullAsyncEventArgs_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFromAsync(null));
}
[Fact]
public void ReceiveMessageFromAsync_NullRemoteEndPoint_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFromAsync(s_eventArgs));
}
[Fact]
public void ReceiveMessageFromAsync_AddressFamily_Throws_Argument()
{
var eventArgs = new SocketAsyncEventArgs {
RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1)
};
Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).ReceiveMessageFromAsync(eventArgs));
}
[Fact]
public void SendAsync_NullAsyncEventArgs_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().SendAsync(null));
}
[Fact]
public void SendPacketsAsync_NullAsyncEventArgs_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().SendPacketsAsync(null));
}
[Fact]
public void SendPacketsAsync_NullSendPacketsElements_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().SendPacketsAsync(s_eventArgs));
}
[Fact]
public void SendPacketsAsync_NotConnected_Throws_NotSupported()
{
var eventArgs = new SocketAsyncEventArgs {
SendPacketsElements = new SendPacketsElement[0]
};
Assert.Throws<NotSupportedException>(() => GetSocket().SendPacketsAsync(eventArgs));
}
[Fact]
public void SendToAsync_NullAsyncEventArgs_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().SendToAsync(null));
}
[Fact]
public void SendToAsync_NullRemoteEndPoint_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().SendToAsync(s_eventArgs));
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Reflection;
using Newtonsoft.Json.Utilities;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#endif
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Maps a JSON property to a .NET member or constructor parameter.
/// </summary>
public class JsonProperty
{
internal Required? _required;
internal bool _hasExplicitDefaultValue;
private object _defaultValue;
private bool _hasGeneratedDefaultValue;
private string _propertyName;
internal bool _skipPropertyNameEscape;
private Type _propertyType;
// use to cache contract during deserialization
internal JsonContract PropertyContract { get; set; }
/// <summary>
/// Gets or sets the name of the property.
/// </summary>
/// <value>The name of the property.</value>
public string PropertyName
{
get { return _propertyName; }
set
{
_propertyName = value;
_skipPropertyNameEscape = !JavaScriptUtils.ShouldEscapeJavaScriptString(_propertyName, JavaScriptUtils.HtmlCharEscapeFlags);
}
}
/// <summary>
/// Gets or sets the type that declared this property.
/// </summary>
/// <value>The type that declared this property.</value>
public Type DeclaringType { get; set; }
/// <summary>
/// Gets or sets the order of serialization and deserialization of a member.
/// </summary>
/// <value>The numeric order of serialization or deserialization.</value>
public int? Order { get; set; }
/// <summary>
/// Gets or sets the name of the underlying member or parameter.
/// </summary>
/// <value>The name of the underlying member or parameter.</value>
public string UnderlyingName { get; set; }
/// <summary>
/// Gets the <see cref="IValueProvider"/> that will get and set the <see cref="JsonProperty"/> during serialization.
/// </summary>
/// <value>The <see cref="IValueProvider"/> that will get and set the <see cref="JsonProperty"/> during serialization.</value>
public IValueProvider ValueProvider { get; set; }
/// <summary>
/// Gets or sets the <see cref="IAttributeProvider"/> for this property.
/// </summary>
/// <value>The <see cref="IAttributeProvider"/> for this property.</value>
public IAttributeProvider AttributeProvider { get; set; }
/// <summary>
/// Gets or sets the type of the property.
/// </summary>
/// <value>The type of the property.</value>
public Type PropertyType
{
get { return _propertyType; }
set
{
if (_propertyType != value)
{
_propertyType = value;
_hasGeneratedDefaultValue = false;
}
}
}
/// <summary>
/// Gets or sets the <see cref="JsonConverter" /> for the property.
/// If set this converter takes presidence over the contract converter for the property type.
/// </summary>
/// <value>The converter.</value>
public JsonConverter Converter { get; set; }
/// <summary>
/// Gets or sets the member converter.
/// </summary>
/// <value>The member converter.</value>
public JsonConverter MemberConverter { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="JsonProperty"/> is ignored.
/// </summary>
/// <value><c>true</c> if ignored; otherwise, <c>false</c>.</value>
public bool Ignored { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="JsonProperty"/> is readable.
/// </summary>
/// <value><c>true</c> if readable; otherwise, <c>false</c>.</value>
public bool Readable { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="JsonProperty"/> is writable.
/// </summary>
/// <value><c>true</c> if writable; otherwise, <c>false</c>.</value>
public bool Writable { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="JsonProperty"/> has a member attribute.
/// </summary>
/// <value><c>true</c> if has a member attribute; otherwise, <c>false</c>.</value>
public bool HasMemberAttribute { get; set; }
/// <summary>
/// Gets the default value.
/// </summary>
/// <value>The default value.</value>
public object DefaultValue
{
get
{
if (!_hasExplicitDefaultValue)
return null;
return _defaultValue;
}
set
{
_hasExplicitDefaultValue = true;
_defaultValue = value;
}
}
internal object GetResolvedDefaultValue()
{
if (_propertyType == null)
return null;
if (!_hasExplicitDefaultValue && !_hasGeneratedDefaultValue)
{
_defaultValue = ReflectionUtils.GetDefaultValue(PropertyType);
_hasGeneratedDefaultValue = true;
}
return _defaultValue;
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="JsonProperty"/> is required.
/// </summary>
/// <value>A value indicating whether this <see cref="JsonProperty"/> is required.</value>
public Required Required
{
get { return _required ?? Required.Default; }
set { _required = value; }
}
/// <summary>
/// Gets or sets a value indicating whether this property preserves object references.
/// </summary>
/// <value>
/// <c>true</c> if this instance is reference; otherwise, <c>false</c>.
/// </value>
public bool? IsReference { get; set; }
/// <summary>
/// Gets or sets the property null value handling.
/// </summary>
/// <value>The null value handling.</value>
public NullValueHandling? NullValueHandling { get; set; }
/// <summary>
/// Gets or sets the property default value handling.
/// </summary>
/// <value>The default value handling.</value>
public DefaultValueHandling? DefaultValueHandling { get; set; }
/// <summary>
/// Gets or sets the property reference loop handling.
/// </summary>
/// <value>The reference loop handling.</value>
public ReferenceLoopHandling? ReferenceLoopHandling { get; set; }
/// <summary>
/// Gets or sets the property object creation handling.
/// </summary>
/// <value>The object creation handling.</value>
public ObjectCreationHandling? ObjectCreationHandling { get; set; }
/// <summary>
/// Gets or sets or sets the type name handling.
/// </summary>
/// <value>The type name handling.</value>
public TypeNameHandling? TypeNameHandling { get; set; }
/// <summary>
/// Gets or sets a predicate used to determine whether the property should be serialize.
/// </summary>
/// <value>A predicate used to determine whether the property should be serialize.</value>
public Predicate<object> ShouldSerialize { get; set; }
/// <summary>
/// Gets or sets a predicate used to determine whether the property should be deserialized.
/// </summary>
/// <value>A predicate used to determine whether the property should be deserialized.</value>
public Predicate<object> ShouldDeserialize { get; set; }
/// <summary>
/// Gets or sets a predicate used to determine whether the property should be serialized.
/// </summary>
/// <value>A predicate used to determine whether the property should be serialized.</value>
public Predicate<object> GetIsSpecified { get; set; }
/// <summary>
/// Gets or sets an action used to set whether the property has been deserialized.
/// </summary>
/// <value>An action used to set whether the property has been deserialized.</value>
public Action<object, object> SetIsSpecified { get; set; }
/// <summary>
/// Returns a <see cref="String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="String"/> that represents this instance.
/// </returns>
public override string ToString()
{
return PropertyName;
}
/// <summary>
/// Gets or sets the converter used when serializing the property's collection items.
/// </summary>
/// <value>The collection's items converter.</value>
public JsonConverter ItemConverter { get; set; }
/// <summary>
/// Gets or sets whether this property's collection items are serialized as a reference.
/// </summary>
/// <value>Whether this property's collection items are serialized as a reference.</value>
public bool? ItemIsReference { get; set; }
/// <summary>
/// Gets or sets the the type name handling used when serializing the property's collection items.
/// </summary>
/// <value>The collection's items type name handling.</value>
public TypeNameHandling? ItemTypeNameHandling { get; set; }
/// <summary>
/// Gets or sets the the reference loop handling used when serializing the property's collection items.
/// </summary>
/// <value>The collection's items reference loop handling.</value>
public ReferenceLoopHandling? ItemReferenceLoopHandling { get; set; }
internal void WritePropertyName(JsonWriter writer)
{
if (_skipPropertyNameEscape)
writer.WritePropertyName(PropertyName, false);
else
writer.WritePropertyName(PropertyName);
}
}
}
| |
/// Refly License
///
/// Copyright (c) 2004 Jonathan de Halleux, http://www.dotnetwiki.org
///
/// This software is provided 'as-is', without any express or implied warranty.
/// In no event will the authors be held liable for any damages arising from
/// the use of this software.
///
/// Permission is granted to anyone to use this software for any purpose,
/// including commercial applications, and to alter it and redistribute it
/// freely, subject to the following restrictions:
///
/// 1. The origin of this software must not be misrepresented;
/// you must not claim that you wrote the original software.
/// If you use this software in a product, an acknowledgment in the product
/// documentation would be appreciated but is not required.
///
/// 2. Altered source versions must be plainly marked as such,
/// and must not be misrepresented as being the original software.
///
///3. This notice may not be removed or altered from any source distribution.
using System;
using System.Reflection;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Specialized;
using System.Collections;
namespace Refly.CodeDom
{
using Refly.CodeDom.Collections;
/// <summary>
/// A namespace declaration
/// </summary>
public class NamespaceDeclaration : Declaration
{
private NamespaceDeclaration parent = null;
private StringSet imports = new StringSet();
private StringNamespaceDeclarationDictionary namespaces = new StringNamespaceDeclarationDictionary();
private StringClassDeclarationDictionary classes = new StringClassDeclarationDictionary();
private StringEnumDeclarationDictionary enums = new StringEnumDeclarationDictionary();
public NamespaceDeclaration(string name)
:base(name, new NameConformer())
{
this.imports.Add("System");
}
public NamespaceDeclaration(string name, NameConformer conformer)
:base(name,conformer)
{
this.imports.Add("System");
}
public NamespaceDeclaration Parent
{
get
{
return this.parent;
}
set
{
this.parent = value;
}
}
public StringNamespaceDeclarationDictionary Namespaces
{
get
{
return this.namespaces;
}
}
public StringClassDeclarationDictionary Classes
{
get
{
return this.classes;
}
}
public StringEnumDeclarationDictionary Enums
{
get
{
return this.enums;
}
}
public override String FullName
{
get
{
if (parent!=null)
return String.Format("{0}.{1}",
parent.FullName,
this.Name
);
else
return this.Name;
}
}
public virtual StringSet Imports
{
get
{
return this.imports;
}
}
public NamespaceDeclaration AddNamespace(string name)
{
if (name==null)
throw new ArgumentNullException("name");
if (this.namespaces.Contains(name))
throw new ApplicationException("namespace already created");
NamespaceDeclaration ns = new NamespaceDeclaration(
this.Conformer.ToCapitalized(name),
this.Conformer
);
ns.parent = this;
this.namespaces.Add(name,ns);
return ns;
}
public EnumDeclaration AddEnum(string name, bool flags)
{
if (name==null)
throw new ArgumentNullException("name");
if (this.enums.Contains(name))
throw new ArgumentException("enum already present");
EnumDeclaration e = new EnumDeclaration(name,this,flags);
this.enums.Add(e);
return e;
}
public ClassDeclaration AddClass(string name)
{
if (name==null)
throw new ArgumentNullException("name");
if (this.Classes.Contains(name))
throw new ArgumentException("class already existing in namespace");
ClassDeclaration c = new ClassDeclaration(name,this);
this.classes.Add(c);
return c;
}
public ClassDeclaration AddClass(string name, TypeAttributes attributes)
{
if (name==null)
throw new ArgumentNullException("name");
if (this.Classes.Contains(name))
throw new ArgumentException("class already existing in namespace");
ClassDeclaration c = new ClassDeclaration(name,this);
c.Attributes = attributes;
this.Classes.Add(c);
return c;
}
public IDictionary ToCodeDom()
{
Hashtable codeNs = new Hashtable();
// namespaces
foreach(NamespaceDeclaration ns in this.namespaces.Values)
{
foreach(DictionaryEntry de in ns.ToCodeDom())
{
codeNs.Add(de.Key,de.Value);
}
}
// classes
foreach(ClassDeclaration c in this.classes.Values)
{
CodeNamespace ns = new CodeNamespace(this.Name);
c.ToCodeDom(ns.Types);
StringCollection usings = new StringCollection();
foreach(String s in this.Imports)
usings.Add(s);
foreach(String import in c.Imports)
{
if (!usings.Contains(import))
usings.Add(import);
}
// imports
foreach(String import in usings)
{
ns.Imports.Add( new CodeNamespaceImport(import));
}
codeNs.Add(
new FileName(this.FullName,c.Name),
ns);
}
// enums
foreach(EnumDeclaration e in this.enums.Values)
{
CodeNamespace ns = new CodeNamespace(this.Name);
ns.Types.Add((CodeTypeDeclaration)e.ToCodeDom());
StringCollection usings = new StringCollection();
foreach(String s in this.imports)
usings.Add(s);
foreach(String import in usings)
{
ns.Imports.Add( new CodeNamespaceImport(import));
}
codeNs.Add(
new FileName(this.FullName,e.Name),
ns);
}
return codeNs;
}
}
public struct FileName
{
public FileName(string _namespace, string name)
{
this.Namespace =_namespace;
this.Name=name;
}
public string Namespace;
public string Name;
public string FullName
{
get
{
return String.Format("{0}\\{1}",this.Namespace, this.Name);
}
}
}
}
| |
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Diagnostics.CodeAnalysis;
namespace WeifenLuo.WinFormsUI.Docking
{
[ToolboxItem(false)]
public partial class DockPane : UserControl, IDockDragSource
{
public enum AppearanceStyle
{
ToolWindow,
Document
}
private enum HitTestArea
{
Caption,
TabStrip,
Content,
None
}
private struct HitTestResult
{
public HitTestArea HitArea;
public int Index;
public HitTestResult(HitTestArea hitTestArea, int index)
{
HitArea = hitTestArea;
Index = index;
}
}
private DockPaneCaptionBase m_captionControl;
private DockPaneCaptionBase CaptionControl
{
get { return m_captionControl; }
}
private DockPaneStripBase m_tabStripControl;
public DockPaneStripBase TabStripControl
{
get { return m_tabStripControl; }
}
internal protected DockPane(IDockContent content, DockState visibleState, bool show)
{
InternalConstruct(content, visibleState, false, Rectangle.Empty, null, DockAlignment.Right, 0.5, show);
}
[SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "1#")]
internal protected DockPane(IDockContent content, FloatWindow floatWindow, bool show)
{
if (floatWindow == null)
throw new ArgumentNullException("floatWindow");
InternalConstruct(content, DockState.Float, false, Rectangle.Empty, floatWindow.NestedPanes.GetDefaultPreviousPane(this), DockAlignment.Right, 0.5, show);
}
internal protected DockPane(IDockContent content, DockPane previousPane, DockAlignment alignment, double proportion, bool show)
{
if (previousPane == null)
throw (new ArgumentNullException("previousPane"));
InternalConstruct(content, previousPane.DockState, false, Rectangle.Empty, previousPane, alignment, proportion, show);
}
[SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "1#")]
internal protected DockPane(IDockContent content, Rectangle floatWindowBounds, bool show)
{
InternalConstruct(content, DockState.Float, true, floatWindowBounds, null, DockAlignment.Right, 0.5, show);
}
private void InternalConstruct(IDockContent content, DockState dockState, bool flagBounds, Rectangle floatWindowBounds, DockPane prevPane, DockAlignment alignment, double proportion, bool show)
{
if (dockState == DockState.Hidden || dockState == DockState.Unknown)
throw new ArgumentException(Strings.DockPane_SetDockState_InvalidState);
if (content == null)
throw new ArgumentNullException(Strings.DockPane_Constructor_NullContent);
if (content.DockHandler.DockPanel == null)
throw new ArgumentException(Strings.DockPane_Constructor_NullDockPanel);
SuspendLayout();
SetStyle(ControlStyles.Selectable, false);
m_isFloat = (dockState == DockState.Float);
m_contents = new DockContentCollection();
m_displayingContents = new DockContentCollection(this);
m_dockPanel = content.DockHandler.DockPanel;
m_dockPanel.AddPane(this);
m_splitter = content.DockHandler.DockPanel.Extender.DockPaneSplitterControlFactory.CreateSplitterControl(this);
m_nestedDockingStatus = new NestedDockingStatus(this);
m_captionControl = DockPanel.DockPaneCaptionFactory.CreateDockPaneCaption(this);
m_tabStripControl = DockPanel.DockPaneStripFactory.CreateDockPaneStrip(this);
Controls.AddRange(new Control[] { m_captionControl, m_tabStripControl });
DockPanel.SuspendLayout(true);
if (flagBounds)
FloatWindow = DockPanel.FloatWindowFactory.CreateFloatWindow(DockPanel, this, floatWindowBounds);
else if (prevPane != null)
DockTo(prevPane.NestedPanesContainer, prevPane, alignment, proportion);
SetDockState(dockState);
if (show)
content.DockHandler.Pane = this;
else if (this.IsFloat)
content.DockHandler.FloatPane = this;
else
content.DockHandler.PanelPane = this;
ResumeLayout();
DockPanel.ResumeLayout(true, true);
}
private bool m_isDisposing;
protected override void Dispose(bool disposing)
{
if (disposing)
{
// IMPORTANT: avoid nested call into this method on Mono.
// https://github.com/dockpanelsuite/dockpanelsuite/issues/16
if (Win32Helper.IsRunningOnMono)
{
if (m_isDisposing)
return;
m_isDisposing = true;
}
m_dockState = DockState.Unknown;
if (NestedPanesContainer != null)
NestedPanesContainer.NestedPanes.Remove(this);
if (DockPanel != null)
{
DockPanel.RemovePane(this);
m_dockPanel = null;
}
Splitter.Dispose();
if (m_autoHidePane != null)
m_autoHidePane.Dispose();
}
base.Dispose(disposing);
}
private IDockContent m_activeContent = null;
public virtual IDockContent ActiveContent
{
get { return m_activeContent; }
set
{
if (ActiveContent == value)
return;
if (value != null)
{
if (!DisplayingContents.Contains(value))
throw (new InvalidOperationException(Strings.DockPane_ActiveContent_InvalidValue));
}
else
{
if (DisplayingContents.Count != 0)
throw (new InvalidOperationException(Strings.DockPane_ActiveContent_InvalidValue));
}
IDockContent oldValue = m_activeContent;
if (DockPanel.ActiveAutoHideContent == oldValue)
DockPanel.ActiveAutoHideContent = null;
m_activeContent = value;
if (DockPanel.DocumentStyle == DocumentStyle.DockingMdi && DockState == DockState.Document)
{
if (m_activeContent != null)
m_activeContent.DockHandler.Form.BringToFront();
}
else
{
if (m_activeContent != null)
m_activeContent.DockHandler.SetVisible();
if (oldValue != null && DisplayingContents.Contains(oldValue))
oldValue.DockHandler.SetVisible();
if (IsActivated && m_activeContent != null)
m_activeContent.DockHandler.Activate();
}
if (FloatWindow != null)
FloatWindow.SetText();
if (DockPanel.DocumentStyle == DocumentStyle.DockingMdi &&
DockState == DockState.Document)
RefreshChanges(false); // delayed layout to reduce screen flicker
else
RefreshChanges();
if (m_activeContent != null)
TabStripControl.EnsureTabVisible(m_activeContent);
}
}
private bool m_allowDockDragAndDrop = true;
public virtual bool AllowDockDragAndDrop
{
get { return m_allowDockDragAndDrop; }
set { m_allowDockDragAndDrop = value; }
}
private IDisposable m_autoHidePane = null;
internal IDisposable AutoHidePane
{
get { return m_autoHidePane; }
set { m_autoHidePane = value; }
}
private object m_autoHideTabs = null;
internal object AutoHideTabs
{
get { return m_autoHideTabs; }
set { m_autoHideTabs = value; }
}
private object TabPageContextMenu
{
get
{
IDockContent content = ActiveContent;
if (content == null)
return null;
if (content.DockHandler.TabPageContextMenuStrip != null)
return content.DockHandler.TabPageContextMenuStrip;
else if (content.DockHandler.TabPageContextMenu != null)
return content.DockHandler.TabPageContextMenu;
else
return null;
}
}
internal bool HasTabPageContextMenu
{
get { return TabPageContextMenu != null; }
}
internal void ShowTabPageContextMenu(Control control, Point position)
{
object menu = TabPageContextMenu;
if (menu == null)
return;
ContextMenuStrip contextMenuStrip = menu as ContextMenuStrip;
if (contextMenuStrip != null)
{
contextMenuStrip.Show(control, position);
return;
}
ContextMenu contextMenu = menu as ContextMenu;
if (contextMenu != null)
contextMenu.Show(this, position);
}
private Rectangle CaptionRectangle
{
get
{
if (!HasCaption)
return Rectangle.Empty;
Rectangle rectWindow = DisplayingRectangle;
int x, y, width;
x = rectWindow.X;
y = rectWindow.Y;
width = rectWindow.Width;
int height = CaptionControl.MeasureHeight();
return new Rectangle(x, y, width, height);
}
}
internal Rectangle ContentRectangle
{
get
{
Rectangle rectWindow = DisplayingRectangle;
Rectangle rectCaption = CaptionRectangle;
Rectangle rectTabStrip = TabStripRectangle;
int x = rectWindow.X;
int y = rectWindow.Y + (rectCaption.IsEmpty ? 0 : rectCaption.Height);
if (DockState == DockState.Document && DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Top)
y += rectTabStrip.Height;
int width = rectWindow.Width;
int height = rectWindow.Height - rectCaption.Height - rectTabStrip.Height;
return new Rectangle(x, y, width, height);
}
}
internal Rectangle TabStripRectangle
{
get
{
if (Appearance == AppearanceStyle.ToolWindow)
return TabStripRectangle_ToolWindow;
else
return TabStripRectangle_Document;
}
}
private Rectangle TabStripRectangle_ToolWindow
{
get
{
if (DisplayingContents.Count <= 1 || IsAutoHide)
return Rectangle.Empty;
Rectangle rectWindow = DisplayingRectangle;
int width = rectWindow.Width;
int height = TabStripControl.MeasureHeight();
int x = rectWindow.X;
int y = rectWindow.Bottom - height;
Rectangle rectCaption = CaptionRectangle;
if (rectCaption.Contains(x, y))
y = rectCaption.Y + rectCaption.Height;
return new Rectangle(x, y, width, height);
}
}
private Rectangle TabStripRectangle_Document
{
get
{
if (DisplayingContents.Count == 0)
return Rectangle.Empty;
if (DisplayingContents.Count == 1 && DockPanel.DocumentStyle == DocumentStyle.DockingSdi)
return Rectangle.Empty;
Rectangle rectWindow = DisplayingRectangle;
int x = rectWindow.X;
int width = rectWindow.Width;
int height = TabStripControl.MeasureHeight();
int y = 0;
if (DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
y = rectWindow.Height - height;
else
y = rectWindow.Y;
return new Rectangle(x, y, width, height);
}
}
public virtual string CaptionText
{
get { return ActiveContent == null ? string.Empty : ActiveContent.DockHandler.TabText; }
}
private DockContentCollection m_contents;
public DockContentCollection Contents
{
get { return m_contents; }
}
private DockContentCollection m_displayingContents;
public DockContentCollection DisplayingContents
{
get { return m_displayingContents; }
}
private DockPanel m_dockPanel;
public DockPanel DockPanel
{
get { return m_dockPanel; }
}
private bool HasCaption
{
get
{
if (DockState == DockState.Document ||
DockState == DockState.Hidden ||
DockState == DockState.Unknown ||
(DockState == DockState.Float && FloatWindow.VisibleNestedPanes.Count <= 1))
return false;
else
return true;
}
}
private bool m_isActivated = false;
public bool IsActivated
{
get { return m_isActivated; }
}
internal void SetIsActivated(bool value)
{
if (m_isActivated == value)
return;
m_isActivated = value;
if (DockState != DockState.Document)
RefreshChanges(false);
OnIsActivatedChanged(EventArgs.Empty);
}
private bool m_isActiveDocumentPane = false;
public bool IsActiveDocumentPane
{
get { return m_isActiveDocumentPane; }
}
internal void SetIsActiveDocumentPane(bool value)
{
if (m_isActiveDocumentPane == value)
return;
m_isActiveDocumentPane = value;
if (DockState == DockState.Document)
RefreshChanges();
OnIsActiveDocumentPaneChanged(EventArgs.Empty);
}
public bool IsDockStateValid(DockState dockState)
{
foreach (IDockContent content in Contents)
if (!content.DockHandler.IsDockStateValid(dockState))
return false;
return true;
}
public bool IsAutoHide
{
get { return DockHelper.IsDockStateAutoHide(DockState); }
}
public AppearanceStyle Appearance
{
get { return (DockState == DockState.Document) ? AppearanceStyle.Document : AppearanceStyle.ToolWindow; }
}
public Rectangle DisplayingRectangle
{
get { return ClientRectangle; }
}
public void Activate()
{
if (DockHelper.IsDockStateAutoHide(DockState) && DockPanel.ActiveAutoHideContent != ActiveContent)
DockPanel.ActiveAutoHideContent = ActiveContent;
else if (!IsActivated && ActiveContent != null)
ActiveContent.DockHandler.Activate();
}
internal void AddContent(IDockContent content)
{
if (Contents.Contains(content))
return;
Contents.Add(content);
}
internal void Close()
{
Dispose();
}
public void CloseActiveContent()
{
CloseContent(ActiveContent);
}
internal void CloseContent(IDockContent content)
{
if (content == null)
return;
if (!content.DockHandler.CloseButton)
return;
DockPanel dockPanel = DockPanel;
dockPanel.SuspendLayout(true);
try
{
if (content.DockHandler.HideOnClose)
{
content.DockHandler.Hide();
NestedDockingStatus.NestedPanes.SwitchPaneWithFirstChild(this);
}
else
content.DockHandler.Close();
}
finally
{
dockPanel.ResumeLayout(true, true);
}
}
private HitTestResult GetHitTest(Point ptMouse)
{
Point ptMouseClient = PointToClient(ptMouse);
Rectangle rectCaption = CaptionRectangle;
if (rectCaption.Contains(ptMouseClient))
return new HitTestResult(HitTestArea.Caption, -1);
Rectangle rectContent = ContentRectangle;
if (rectContent.Contains(ptMouseClient))
return new HitTestResult(HitTestArea.Content, -1);
Rectangle rectTabStrip = TabStripRectangle;
if (rectTabStrip.Contains(ptMouseClient))
return new HitTestResult(HitTestArea.TabStrip, TabStripControl.HitTest(TabStripControl.PointToClient(ptMouse)));
return new HitTestResult(HitTestArea.None, -1);
}
private bool m_isHidden = true;
public bool IsHidden
{
get { return m_isHidden; }
}
private void SetIsHidden(bool value)
{
if (m_isHidden == value)
return;
m_isHidden = value;
if (DockHelper.IsDockStateAutoHide(DockState))
{
DockPanel.RefreshAutoHideStrip();
DockPanel.PerformLayout();
}
else if (NestedPanesContainer != null)
((Control)NestedPanesContainer).PerformLayout();
}
protected override void OnLayout(LayoutEventArgs levent)
{
SetIsHidden(DisplayingContents.Count == 0);
if (!IsHidden)
{
CaptionControl.Bounds = CaptionRectangle;
TabStripControl.Bounds = TabStripRectangle;
SetContentBounds();
foreach (IDockContent content in Contents)
{
if (DisplayingContents.Contains(content))
if (content.DockHandler.FlagClipWindow && content.DockHandler.Form.Visible)
content.DockHandler.FlagClipWindow = false;
}
}
base.OnLayout(levent);
}
internal void SetContentBounds()
{
Rectangle rectContent = ContentRectangle;
if (DockState == DockState.Document && DockPanel.DocumentStyle == DocumentStyle.DockingMdi)
rectContent = DockPanel.RectangleToMdiClient(RectangleToScreen(rectContent));
Rectangle rectInactive = new Rectangle(-rectContent.Width, rectContent.Y, rectContent.Width, rectContent.Height);
foreach (IDockContent content in Contents)
if (content.DockHandler.Pane == this)
{
if (content == ActiveContent)
content.DockHandler.Form.Bounds = rectContent;
else
content.DockHandler.Form.Bounds = rectInactive;
}
}
internal void RefreshChanges()
{
RefreshChanges(true);
}
private void RefreshChanges(bool performLayout)
{
if (IsDisposed)
return;
CaptionControl.RefreshChanges();
TabStripControl.RefreshChanges();
if (DockState == DockState.Float && FloatWindow != null)
FloatWindow.RefreshChanges();
if (DockHelper.IsDockStateAutoHide(DockState) && DockPanel != null)
{
DockPanel.RefreshAutoHideStrip();
DockPanel.PerformLayout();
}
if (performLayout)
PerformLayout();
}
internal void RemoveContent(IDockContent content)
{
if (!Contents.Contains(content))
return;
Contents.Remove(content);
}
public void SetContentIndex(IDockContent content, int index)
{
int oldIndex = Contents.IndexOf(content);
if (oldIndex == -1)
throw (new ArgumentException(Strings.DockPane_SetContentIndex_InvalidContent));
if (index < 0 || index > Contents.Count - 1)
if (index != -1)
throw (new ArgumentOutOfRangeException(Strings.DockPane_SetContentIndex_InvalidIndex));
if (oldIndex == index)
return;
if (oldIndex == Contents.Count - 1 && index == -1)
return;
Contents.Remove(content);
if (index == -1)
Contents.Add(content);
else if (oldIndex < index)
Contents.AddAt(content, index - 1);
else
Contents.AddAt(content, index);
RefreshChanges();
}
private void SetParent()
{
if (DockState == DockState.Unknown || DockState == DockState.Hidden)
{
SetParent(null);
Splitter.Parent = null;
}
else if (DockState == DockState.Float)
{
SetParent(FloatWindow);
Splitter.Parent = FloatWindow;
}
else if (DockHelper.IsDockStateAutoHide(DockState))
{
SetParent(DockPanel.AutoHideControl);
Splitter.Parent = null;
}
else
{
SetParent(DockPanel.DockWindows[DockState]);
Splitter.Parent = Parent;
}
}
private void SetParent(Control value)
{
if (Parent == value)
return;
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Workaround of .Net Framework bug:
// Change the parent of a control with focus may result in the first
// MDI child form get activated.
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
IDockContent contentFocused = GetFocusedContent();
if (contentFocused != null)
DockPanel.SaveFocus();
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Parent = value;
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Workaround of .Net Framework bug:
// Change the parent of a control with focus may result in the first
// MDI child form get activated.
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
if (contentFocused != null)
contentFocused.DockHandler.Activate();
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
public new void Show()
{
Activate();
}
internal void TestDrop(IDockDragSource dragSource, DockOutlineBase dockOutline)
{
if (!dragSource.CanDockTo(this))
return;
Point ptMouse = Control.MousePosition;
HitTestResult hitTestResult = GetHitTest(ptMouse);
if (hitTestResult.HitArea == HitTestArea.Caption)
dockOutline.Show(this, -1);
else if (hitTestResult.HitArea == HitTestArea.TabStrip && hitTestResult.Index != -1)
dockOutline.Show(this, hitTestResult.Index);
}
internal void ValidateActiveContent()
{
if (ActiveContent == null)
{
if (DisplayingContents.Count != 0)
ActiveContent = DisplayingContents[0];
return;
}
if (DisplayingContents.IndexOf(ActiveContent) >= 0)
return;
IDockContent prevVisible = null;
for (int i = Contents.IndexOf(ActiveContent) - 1; i >= 0; i--)
if (Contents[i].DockHandler.DockState == DockState)
{
prevVisible = Contents[i];
break;
}
IDockContent nextVisible = null;
for (int i = Contents.IndexOf(ActiveContent) + 1; i < Contents.Count; i++)
if (Contents[i].DockHandler.DockState == DockState)
{
nextVisible = Contents[i];
break;
}
if (prevVisible != null)
ActiveContent = prevVisible;
else if (nextVisible != null)
ActiveContent = nextVisible;
else
ActiveContent = null;
}
private static readonly object DockStateChangedEvent = new object();
public event EventHandler DockStateChanged
{
add { Events.AddHandler(DockStateChangedEvent, value); }
remove { Events.RemoveHandler(DockStateChangedEvent, value); }
}
protected virtual void OnDockStateChanged(EventArgs e)
{
EventHandler handler = (EventHandler)Events[DockStateChangedEvent];
if (handler != null)
handler(this, e);
}
private static readonly object IsActivatedChangedEvent = new object();
public event EventHandler IsActivatedChanged
{
add { Events.AddHandler(IsActivatedChangedEvent, value); }
remove { Events.RemoveHandler(IsActivatedChangedEvent, value); }
}
protected virtual void OnIsActivatedChanged(EventArgs e)
{
EventHandler handler = (EventHandler)Events[IsActivatedChangedEvent];
if (handler != null)
handler(this, e);
}
private static readonly object IsActiveDocumentPaneChangedEvent = new object();
public event EventHandler IsActiveDocumentPaneChanged
{
add { Events.AddHandler(IsActiveDocumentPaneChangedEvent, value); }
remove { Events.RemoveHandler(IsActiveDocumentPaneChangedEvent, value); }
}
protected virtual void OnIsActiveDocumentPaneChanged(EventArgs e)
{
EventHandler handler = (EventHandler)Events[IsActiveDocumentPaneChangedEvent];
if (handler != null)
handler(this, e);
}
public DockWindow DockWindow
{
get { return (m_nestedDockingStatus.NestedPanes == null) ? null : m_nestedDockingStatus.NestedPanes.Container as DockWindow; }
set
{
DockWindow oldValue = DockWindow;
if (oldValue == value)
return;
DockTo(value);
}
}
public FloatWindow FloatWindow
{
get { return (m_nestedDockingStatus.NestedPanes == null) ? null : m_nestedDockingStatus.NestedPanes.Container as FloatWindow; }
set
{
FloatWindow oldValue = FloatWindow;
if (oldValue == value)
return;
DockTo(value);
}
}
private NestedDockingStatus m_nestedDockingStatus;
public NestedDockingStatus NestedDockingStatus
{
get { return m_nestedDockingStatus; }
}
private bool m_isFloat;
public bool IsFloat
{
get { return m_isFloat; }
}
public INestedPanesContainer NestedPanesContainer
{
get
{
if (NestedDockingStatus.NestedPanes == null)
return null;
else
return NestedDockingStatus.NestedPanes.Container;
}
}
private DockState m_dockState = DockState.Unknown;
public DockState DockState
{
get { return m_dockState; }
set
{
SetDockState(value);
}
}
public DockPane SetDockState(DockState value)
{
if (value == DockState.Unknown || value == DockState.Hidden)
throw new InvalidOperationException(Strings.DockPane_SetDockState_InvalidState);
if ((value == DockState.Float) == this.IsFloat)
{
InternalSetDockState(value);
return this;
}
if (DisplayingContents.Count == 0)
return null;
IDockContent firstContent = null;
for (int i = 0; i < DisplayingContents.Count; i++)
{
IDockContent content = DisplayingContents[i];
if (content.DockHandler.IsDockStateValid(value))
{
firstContent = content;
break;
}
}
if (firstContent == null)
return null;
firstContent.DockHandler.DockState = value;
DockPane pane = firstContent.DockHandler.Pane;
DockPanel.SuspendLayout(true);
for (int i = 0; i < DisplayingContents.Count; i++)
{
IDockContent content = DisplayingContents[i];
if (content.DockHandler.IsDockStateValid(value))
content.DockHandler.Pane = pane;
}
DockPanel.ResumeLayout(true, true);
return pane;
}
private void InternalSetDockState(DockState value)
{
if (m_dockState == value)
return;
DockState oldDockState = m_dockState;
INestedPanesContainer oldContainer = NestedPanesContainer;
m_dockState = value;
SuspendRefreshStateChange();
IDockContent contentFocused = GetFocusedContent();
if (contentFocused != null)
DockPanel.SaveFocus();
if (!IsFloat)
DockWindow = DockPanel.DockWindows[DockState];
else if (FloatWindow == null)
FloatWindow = DockPanel.FloatWindowFactory.CreateFloatWindow(DockPanel, this);
if (contentFocused != null)
{
if (!Win32Helper.IsRunningOnMono)
{
DockPanel.ContentFocusManager.Activate(contentFocused);
}
}
ResumeRefreshStateChange(oldContainer, oldDockState);
}
private int m_countRefreshStateChange = 0;
private void SuspendRefreshStateChange()
{
m_countRefreshStateChange++;
DockPanel.SuspendLayout(true);
}
private void ResumeRefreshStateChange()
{
m_countRefreshStateChange--;
System.Diagnostics.Debug.Assert(m_countRefreshStateChange >= 0);
DockPanel.ResumeLayout(true, true);
}
private bool IsRefreshStateChangeSuspended
{
get { return m_countRefreshStateChange != 0; }
}
private void ResumeRefreshStateChange(INestedPanesContainer oldContainer, DockState oldDockState)
{
ResumeRefreshStateChange();
RefreshStateChange(oldContainer, oldDockState);
}
private void RefreshStateChange(INestedPanesContainer oldContainer, DockState oldDockState)
{
if (IsRefreshStateChangeSuspended)
return;
SuspendRefreshStateChange();
DockPanel.SuspendLayout(true);
IDockContent contentFocused = GetFocusedContent();
if (contentFocused != null)
DockPanel.SaveFocus();
SetParent();
if (ActiveContent != null)
ActiveContent.DockHandler.SetDockState(ActiveContent.DockHandler.IsHidden, DockState, ActiveContent.DockHandler.Pane);
foreach (IDockContent content in Contents)
{
if (content.DockHandler.Pane == this)
content.DockHandler.SetDockState(content.DockHandler.IsHidden, DockState, content.DockHandler.Pane);
}
if (oldContainer != null)
{
Control oldContainerControl = (Control)oldContainer;
if (oldContainer.DockState == oldDockState && !oldContainerControl.IsDisposed)
oldContainerControl.PerformLayout();
}
if (DockHelper.IsDockStateAutoHide(oldDockState))
DockPanel.RefreshActiveAutoHideContent();
if (NestedPanesContainer.DockState == DockState)
((Control)NestedPanesContainer).PerformLayout();
if (DockHelper.IsDockStateAutoHide(DockState))
DockPanel.RefreshActiveAutoHideContent();
if (DockHelper.IsDockStateAutoHide(oldDockState) ||
DockHelper.IsDockStateAutoHide(DockState))
{
DockPanel.RefreshAutoHideStrip();
DockPanel.PerformLayout();
}
ResumeRefreshStateChange();
if (contentFocused != null)
contentFocused.DockHandler.Activate();
DockPanel.ResumeLayout(true, true);
if (oldDockState != DockState)
OnDockStateChanged(EventArgs.Empty);
}
private IDockContent GetFocusedContent()
{
IDockContent contentFocused = null;
foreach (IDockContent content in Contents)
{
if (content.DockHandler.Form.ContainsFocus)
{
contentFocused = content;
break;
}
}
return contentFocused;
}
public DockPane DockTo(INestedPanesContainer container)
{
if (container == null)
throw new InvalidOperationException(Strings.DockPane_DockTo_NullContainer);
DockAlignment alignment;
if (container.DockState == DockState.DockLeft || container.DockState == DockState.DockRight)
alignment = DockAlignment.Bottom;
else
alignment = DockAlignment.Right;
return DockTo(container, container.NestedPanes.GetDefaultPreviousPane(this), alignment, 0.5);
}
public DockPane DockTo(INestedPanesContainer container, DockPane previousPane, DockAlignment alignment, double proportion)
{
if (container == null)
throw new InvalidOperationException(Strings.DockPane_DockTo_NullContainer);
if (container.IsFloat == this.IsFloat)
{
InternalAddToDockList(container, previousPane, alignment, proportion);
return this;
}
IDockContent firstContent = GetFirstContent(container.DockState);
if (firstContent == null)
return null;
DockPane pane;
DockPanel.DummyContent.DockPanel = DockPanel;
if (container.IsFloat)
pane = DockPanel.DockPaneFactory.CreateDockPane(DockPanel.DummyContent, (FloatWindow)container, true);
else
pane = DockPanel.DockPaneFactory.CreateDockPane(DockPanel.DummyContent, container.DockState, true);
pane.DockTo(container, previousPane, alignment, proportion);
SetVisibleContentsToPane(pane);
DockPanel.DummyContent.DockPanel = null;
return pane;
}
private void SetVisibleContentsToPane(DockPane pane)
{
SetVisibleContentsToPane(pane, ActiveContent);
}
private void SetVisibleContentsToPane(DockPane pane, IDockContent activeContent)
{
for (int i = 0; i < DisplayingContents.Count; i++)
{
IDockContent content = DisplayingContents[i];
if (content.DockHandler.IsDockStateValid(pane.DockState))
{
content.DockHandler.Pane = pane;
i--;
}
}
if (activeContent.DockHandler.Pane == pane)
pane.ActiveContent = activeContent;
}
private void InternalAddToDockList(INestedPanesContainer container, DockPane prevPane, DockAlignment alignment, double proportion)
{
if ((container.DockState == DockState.Float) != IsFloat)
throw new InvalidOperationException(Strings.DockPane_DockTo_InvalidContainer);
int count = container.NestedPanes.Count;
if (container.NestedPanes.Contains(this))
count--;
if (prevPane == null && count > 0)
throw new InvalidOperationException(Strings.DockPane_DockTo_NullPrevPane);
if (prevPane != null && !container.NestedPanes.Contains(prevPane))
throw new InvalidOperationException(Strings.DockPane_DockTo_NoPrevPane);
if (prevPane == this)
throw new InvalidOperationException(Strings.DockPane_DockTo_SelfPrevPane);
INestedPanesContainer oldContainer = NestedPanesContainer;
DockState oldDockState = DockState;
container.NestedPanes.Add(this);
NestedDockingStatus.SetStatus(container.NestedPanes, prevPane, alignment, proportion);
if (DockHelper.IsDockWindowState(DockState))
m_dockState = container.DockState;
RefreshStateChange(oldContainer, oldDockState);
}
public void SetNestedDockingProportion(double proportion)
{
NestedDockingStatus.SetStatus(NestedDockingStatus.NestedPanes, NestedDockingStatus.PreviousPane, NestedDockingStatus.Alignment, proportion);
if (NestedPanesContainer != null)
((Control)NestedPanesContainer).PerformLayout();
}
public DockPane Float()
{
DockPanel.SuspendLayout(true);
IDockContent activeContent = ActiveContent;
DockPane floatPane = GetFloatPaneFromContents();
if (floatPane == null)
{
IDockContent firstContent = GetFirstContent(DockState.Float);
if (firstContent == null)
{
DockPanel.ResumeLayout(true, true);
return null;
}
floatPane = DockPanel.DockPaneFactory.CreateDockPane(firstContent, DockState.Float, true);
}
SetVisibleContentsToPane(floatPane, activeContent);
DockPanel.ResumeLayout(true, true);
return floatPane;
}
private DockPane GetFloatPaneFromContents()
{
DockPane floatPane = null;
for (int i = 0; i < DisplayingContents.Count; i++)
{
IDockContent content = DisplayingContents[i];
if (!content.DockHandler.IsDockStateValid(DockState.Float))
continue;
if (floatPane != null && content.DockHandler.FloatPane != floatPane)
return null;
else
floatPane = content.DockHandler.FloatPane;
}
return floatPane;
}
private IDockContent GetFirstContent(DockState dockState)
{
for (int i = 0; i < DisplayingContents.Count; i++)
{
IDockContent content = DisplayingContents[i];
if (content.DockHandler.IsDockStateValid(dockState))
return content;
}
return null;
}
public void RestoreToPanel()
{
DockPanel.SuspendLayout(true);
IDockContent activeContent = DockPanel.ActiveContent;
for (int i = DisplayingContents.Count - 1; i >= 0; i--)
{
IDockContent content = DisplayingContents[i];
if (content.DockHandler.CheckDockState(false) != DockState.Unknown)
content.DockHandler.IsFloat = false;
}
DockPanel.ResumeLayout(true, true);
}
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
protected override void WndProc(ref Message m)
{
if (m.Msg == (int)Win32.Msgs.WM_MOUSEACTIVATE)
Activate();
base.WndProc(ref m);
}
#region IDockDragSource Members
#region IDragSource Members
Control IDragSource.DragControl
{
get { return this; }
}
public IDockContent MouseOverTab { get; set; }
#endregion
bool IDockDragSource.IsDockStateValid(DockState dockState)
{
return IsDockStateValid(dockState);
}
bool IDockDragSource.CanDockTo(DockPane pane)
{
if (!IsDockStateValid(pane.DockState))
return false;
if (pane == this)
return false;
return true;
}
Rectangle IDockDragSource.BeginDrag(Point ptMouse)
{
Point location = PointToScreen(new Point(0, 0));
Size size;
DockPane floatPane = ActiveContent.DockHandler.FloatPane;
if (DockState == DockState.Float || floatPane == null || floatPane.FloatWindow.NestedPanes.Count != 1)
size = DockPanel.DefaultFloatWindowSize;
else
size = floatPane.FloatWindow.Size;
if (ptMouse.X > location.X + size.Width)
location.X += ptMouse.X - (location.X + size.Width) + Measures.SplitterSize;
return new Rectangle(location, size);
}
void IDockDragSource.EndDrag()
{
}
public void FloatAt(Rectangle floatWindowBounds)
{
if (FloatWindow == null || FloatWindow.NestedPanes.Count != 1)
FloatWindow = DockPanel.FloatWindowFactory.CreateFloatWindow(DockPanel, this, floatWindowBounds);
else
FloatWindow.Bounds = floatWindowBounds;
DockState = DockState.Float;
NestedDockingStatus.NestedPanes.SwitchPaneWithFirstChild(this);
}
public void DockTo(DockPane pane, DockStyle dockStyle, int contentIndex)
{
if (dockStyle == DockStyle.Fill)
{
IDockContent activeContent = ActiveContent;
for (int i = Contents.Count - 1; i >= 0; i--)
{
IDockContent c = Contents[i];
if (c.DockHandler.DockState == DockState)
{
c.DockHandler.Pane = pane;
if (contentIndex != -1)
pane.SetContentIndex(c, contentIndex);
}
}
pane.ActiveContent = activeContent;
}
else
{
if (dockStyle == DockStyle.Left)
DockTo(pane.NestedPanesContainer, pane, DockAlignment.Left, 0.5);
else if (dockStyle == DockStyle.Right)
DockTo(pane.NestedPanesContainer, pane, DockAlignment.Right, 0.5);
else if (dockStyle == DockStyle.Top)
DockTo(pane.NestedPanesContainer, pane, DockAlignment.Top, 0.5);
else if (dockStyle == DockStyle.Bottom)
DockTo(pane.NestedPanesContainer, pane, DockAlignment.Bottom, 0.5);
DockState = pane.DockState;
}
}
public void DockTo(DockPanel panel, DockStyle dockStyle)
{
if (panel != DockPanel)
throw new ArgumentException(Strings.IDockDragSource_DockTo_InvalidPanel, "panel");
if (dockStyle == DockStyle.Top)
DockState = DockState.DockTop;
else if (dockStyle == DockStyle.Bottom)
DockState = DockState.DockBottom;
else if (dockStyle == DockStyle.Left)
DockState = DockState.DockLeft;
else if (dockStyle == DockStyle.Right)
DockState = DockState.DockRight;
else if (dockStyle == DockStyle.Fill)
DockState = DockState.Document;
}
#endregion
#region cachedLayoutArgs leak workaround
/// <summary>
/// There's a bug in the WinForms layout engine
/// that can result in a deferred layout to not
/// properly clear out the cached layout args after
/// the layout operation is performed.
/// Specifically, this bug is hit when the bounds of
/// the Pane change, initiating a layout on the parent
/// (DockWindow) which is where the bug hits.
/// To work around it, when a pane loses the DockWindow
/// as its parent, that parent DockWindow needs to
/// perform a layout to flush the cached args, if they exist.
/// </summary>
private DockWindow _lastParentWindow;
protected override void OnParentChanged(EventArgs e)
{
base.OnParentChanged(e);
var newParent = Parent as DockWindow;
if (newParent != _lastParentWindow)
{
if (_lastParentWindow != null)
_lastParentWindow.PerformLayout();
_lastParentWindow = newParent;
}
}
#endregion
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the 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.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using OpenMetaverse;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using log4net;
namespace OpenSim.Framework.Console
{
public class ConsoleConnection
{
public int last;
public long lastLineSeen;
public bool newConnection = true;
public AsyncHttpRequest request = null;
}
// A console that uses REST interfaces
//
public class RemoteConsole : CommandConsole
{
private IHttpServer m_Server;
private IConfigSource m_Config;
private List<string> m_Scrollback;
private ManualResetEvent m_DataEvent;
private List<string> m_InputData;
private long m_LineNumber;
private Dictionary<UUID, ConsoleConnection> m_Connections;
private string m_AllowedOrigin;
public RemoteConsole(string defaultPrompt) : base(defaultPrompt)
{
m_Server = null;
m_Config = null;
m_Scrollback = new List<string>();
m_DataEvent = new ManualResetEvent(false);
m_InputData = new List<string>();
m_LineNumber = 0;
m_Connections = new Dictionary<UUID, ConsoleConnection>();
m_AllowedOrigin = String.Empty;
}
public void ReadConfig(IConfigSource config)
{
m_Config = config;
IConfig netConfig = m_Config.Configs["Network"];
if (netConfig == null)
return;
m_AllowedOrigin = netConfig.GetString("ConsoleAllowedOrigin", String.Empty);
}
public void SetServer(IHttpServer server)
{
m_Server = server;
m_Server.AddHTTPHandler("/StartSession/", HandleHttpStartSession);
m_Server.AddHTTPHandler("/CloseSession/", HandleHttpCloseSession);
m_Server.AddHTTPHandler("/SessionCommand/", HandleHttpSessionCommand);
}
internal void ResponseReady()
{
List<AsyncHttpRequest> requests = new List<AsyncHttpRequest>();
lock (m_Connections)
{
foreach (KeyValuePair<UUID, ConsoleConnection> kvp in m_Connections)
{
ConsoleConnection connection = kvp.Value;
if (connection.request != null)
{
requests.Add(connection.request);
connection.request = null;
}
}
}
foreach (AsyncHttpRequest request in requests)
{
request.SendResponse(ProcessEvents(request));
}
}
public override void Output(string text, string level)
{
lock (m_Scrollback)
{
while (m_Scrollback.Count >= 1000)
m_Scrollback.RemoveAt(0);
m_LineNumber++;
m_Scrollback.Add(String.Format("{0}", m_LineNumber) + ":" + level + ":" + text);
}
FireOnOutput(text.Trim());
System.Console.WriteLine(text.Trim());
ResponseReady();
}
public override void Output(string text)
{
Output(text, "normal");
}
public override string ReadLine(string p, bool isCommand, bool e)
{
if (isCommand)
Output("+++" + p);
else
Output("-++" + p);
m_DataEvent.WaitOne();
string cmdinput;
lock (m_InputData)
{
if (m_InputData.Count == 0)
{
m_DataEvent.Reset();
return "";
}
cmdinput = m_InputData[0];
m_InputData.RemoveAt(0);
if (m_InputData.Count == 0)
m_DataEvent.Reset();
}
if (isCommand)
{
string[] cmd = Commands.Resolve(Parser.Parse(cmdinput));
if (cmd.Length != 0)
{
int i;
for (i = 0; i < cmd.Length; i++)
{
if (cmd[i].Contains(" "))
cmd[i] = "\"" + cmd[i] + "\"";
}
return String.Empty;
}
}
return cmdinput;
}
private Hashtable CheckOrigin(Hashtable result)
{
if (!string.IsNullOrEmpty(m_AllowedOrigin))
result["access_control_allow_origin"] = m_AllowedOrigin;
return result;
}
/* TODO: Figure out how PollServiceHTTPHandler can access the request headers
* in order to use m_AllowedOrigin as a regular expression
private Hashtable CheckOrigin(Hashtable headers, Hashtable result)
{
if (!string.IsNullOrEmpty(m_AllowedOrigin))
{
if (headers.ContainsKey("origin"))
{
string origin = headers["origin"].ToString();
if (Regex.IsMatch(origin, m_AllowedOrigin))
result["access_control_allow_origin"] = origin;
}
}
return result;
}
*/
private void DoExpire()
{
List<UUID> expired = new List<UUID>();
List<AsyncHttpRequest> requests = new List<AsyncHttpRequest>();
lock (m_Connections)
{
foreach (KeyValuePair<UUID, ConsoleConnection> kvp in m_Connections)
{
if (System.Environment.TickCount - kvp.Value.last > 500000)
expired.Add(kvp.Key);
}
foreach (UUID id in expired)
{
ConsoleConnection connection = m_Connections[id];
m_Connections.Remove(id);
CloseConnection(id);
if (connection.request != null)
{
requests.Add(connection.request);
connection.request = null;
}
}
}
foreach (AsyncHttpRequest request in requests)
{
request.SendResponse(ProcessEvents(request));
}
}
private Hashtable HandleHttpStartSession(Hashtable request)
{
DoExpire();
Hashtable post = DecodePostString(request["body"].ToString());
Hashtable reply = new Hashtable();
reply["str_response_string"] = "";
reply["int_response_code"] = 401;
reply["content_type"] = "text/plain";
string username = post["USER"].ToString();
string password = post["PASS"].ToString();
// Validate the username/password pair
if (Util.AuthenicateAsSystemUser(username, password) == false)
return reply;
ConsoleConnection c = new ConsoleConnection();
c.last = System.Environment.TickCount;
c.lastLineSeen = 0;
UUID sessionID = UUID.Random();
lock (m_Connections)
{
m_Connections[sessionID] = c;
}
string uri = "/ReadResponses/" + sessionID.ToString() + "/";
IRequestHandler handler = new AsyncRequestHandler("POST", uri, AsyncReadResponses);
m_Server.AddStreamHandler(handler);
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "", "");
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession", "");
xmldoc.AppendChild(rootElement);
XmlElement id = xmldoc.CreateElement("", "SessionID", "");
id.AppendChild(xmldoc.CreateTextNode(sessionID.ToString()));
rootElement.AppendChild(id);
XmlElement prompt = xmldoc.CreateElement("", "Prompt", "");
prompt.AppendChild(xmldoc.CreateTextNode(DefaultPrompt));
rootElement.AppendChild(prompt);
rootElement.AppendChild(MainConsole.Instance.Commands.GetXml(xmldoc));
reply["str_response_string"] = xmldoc.InnerXml;
reply["int_response_code"] = 200;
reply["content_type"] = "text/xml";
reply = CheckOrigin(reply);
return reply;
}
private Hashtable HandleHttpCloseSession(Hashtable request)
{
DoExpire();
Hashtable post = DecodePostString(request["body"].ToString());
Hashtable reply = new Hashtable();
reply["str_response_string"] = "";
reply["int_response_code"] = 404;
reply["content_type"] = "text/plain";
if (post["ID"] == null)
return reply;
UUID id;
if (!UUID.TryParse(post["ID"].ToString(), out id))
return reply;
lock (m_Connections)
{
if (m_Connections.ContainsKey(id))
{
ConsoleConnection connection = m_Connections[id];
m_Connections.Remove(id);
CloseConnection(id);
if (connection.request != null)
{
AsyncHttpRequest req = connection.request;
connection.request = null;
req.SendResponse(ProcessEvents(req));
}
}
}
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "", "");
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession", "");
xmldoc.AppendChild(rootElement);
XmlElement res = xmldoc.CreateElement("", "Result", "");
res.AppendChild(xmldoc.CreateTextNode("OK"));
rootElement.AppendChild(res);
reply["str_response_string"] = xmldoc.InnerXml;
reply["int_response_code"] = 200;
reply["content_type"] = "text/xml";
reply = CheckOrigin(reply);
return reply;
}
private Hashtable HandleHttpSessionCommand(Hashtable request)
{
DoExpire();
Hashtable post = DecodePostString(request["body"].ToString());
Hashtable reply = new Hashtable();
reply["str_response_string"] = "";
reply["int_response_code"] = 404;
reply["content_type"] = "text/plain";
if (post["ID"] == null)
return reply;
UUID id;
if (!UUID.TryParse(post["ID"].ToString(), out id))
return reply;
lock (m_Connections)
{
if (!m_Connections.ContainsKey(id))
return reply;
}
if (post["COMMAND"] == null)
return reply;
lock (m_InputData)
{
m_DataEvent.Set();
m_InputData.Add(post["COMMAND"].ToString());
}
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "", "");
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession", "");
xmldoc.AppendChild(rootElement);
XmlElement res = xmldoc.CreateElement("", "Result", "");
res.AppendChild(xmldoc.CreateTextNode("OK"));
rootElement.AppendChild(res);
reply["str_response_string"] = xmldoc.InnerXml;
reply["int_response_code"] = 200;
reply["content_type"] = "text/xml";
reply = CheckOrigin(reply);
return reply;
}
private Hashtable DecodePostString(string data)
{
Hashtable result = new Hashtable();
string[] terms = data.Split(new char[] { '&' });
foreach (string term in terms)
{
string[] elems = term.Split(new char[] { '=' });
if (elems.Length == 0)
continue;
string name = System.Web.HttpUtility.UrlDecode(elems[0]);
string value = String.Empty;
if (elems.Length > 1)
value = System.Web.HttpUtility.UrlDecode(elems[1]);
result[name] = value;
}
return result;
}
public void CloseConnection(UUID id)
{
try
{
string uri = "/ReadResponses/" + id.ToString() + "/";
m_Server.RemoveStreamHandler("POST", uri);
}
catch (Exception)
{
}
}
public void AsyncReadResponses(IHttpServer server, string path, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
int pos1 = path.IndexOf("/"); // /ReadResponses
int pos2 = path.IndexOf("/", pos1 + 1); // /ReadResponses/
int pos3 = path.IndexOf("/", pos2 + 1); // /ReadResponses/<UUID>/
int len = pos3 - pos2 - 1;
string uri_tmp = path.Substring(pos2 + 1, len);
UUID sessionID;
if (UUID.TryParse(uri_tmp, out sessionID) == false)
return;
// Create the new request
AsyncHttpRequest newRequest =
new AsyncHttpRequest(server, httpRequest, httpResponse, sessionID, TimeoutHandler, 60 * 1000);
AsyncHttpRequest currentRequest = null;
lock (m_Connections)
{
ConsoleConnection connection = null;
m_Connections.TryGetValue(sessionID, out connection);
if (connection == null)
return;
currentRequest = connection.request;
connection.request = newRequest;
}
// If there was a request already posted signal it
if (currentRequest != null)
{
currentRequest.SendResponse(ProcessEvents(currentRequest));
}
}
private void TimeoutHandler(AsyncHttpRequest pRequest)
{
UUID sessionid = pRequest.AgentID;
lock (m_Connections)
{
ConsoleConnection connection = null;
m_Connections.TryGetValue(sessionid, out connection);
if (connection == null)
return;
if (connection.request == pRequest)
connection.request = null;
}
pRequest.SendResponse(ProcessEvents(pRequest));
}
private Hashtable ProcessEvents(AsyncHttpRequest pRequest)
{
UUID sessionID = pRequest.AgentID;
// Is there data to send back? Then send it.
if (HasEvents(pRequest.RequestID, sessionID))
return (GetEvents(pRequest.RequestID, sessionID));
else
return (NoEvents(pRequest.RequestID, sessionID));
}
private bool HasEvents(UUID RequestID, UUID sessionID)
{
ConsoleConnection c = null;
lock (m_Connections)
{
if (!m_Connections.ContainsKey(sessionID))
return false;
c = m_Connections[sessionID];
}
c.last = System.Environment.TickCount;
if (c.lastLineSeen < m_LineNumber)
return true;
return false;
}
private Hashtable GetEvents(UUID RequestID, UUID sessionID)
{
ConsoleConnection c = null;
lock (m_Connections)
{
if (!m_Connections.ContainsKey(sessionID))
return NoEvents(RequestID, UUID.Zero);
c = m_Connections[sessionID];
}
c.last = System.Environment.TickCount;
if (c.lastLineSeen >= m_LineNumber)
return NoEvents(RequestID, UUID.Zero);
Hashtable result = new Hashtable();
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "", "");
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession", "");
if (c.newConnection)
{
c.newConnection = false;
Output("+++" + DefaultPrompt);
}
lock (m_Scrollback)
{
long startLine = m_LineNumber - m_Scrollback.Count;
long sendStart = startLine;
if (sendStart < c.lastLineSeen)
sendStart = c.lastLineSeen;
for (long i = sendStart; i < m_LineNumber; i++)
{
XmlElement res = xmldoc.CreateElement("", "Line", "");
long line = i + 1;
res.SetAttribute("Number", line.ToString());
res.AppendChild(xmldoc.CreateTextNode(m_Scrollback[(int)(i - startLine)]));
rootElement.AppendChild(res);
}
}
c.lastLineSeen = m_LineNumber;
xmldoc.AppendChild(rootElement);
result["str_response_string"] = xmldoc.InnerXml;
result["int_response_code"] = 200;
result["content_type"] = "application/xml";
result["keepalive"] = false;
result["reusecontext"] = false;
result = CheckOrigin(result);
return result;
}
private Hashtable NoEvents(UUID RequestID, UUID id)
{
Hashtable result = new Hashtable();
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "", "");
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession", "");
xmldoc.AppendChild(rootElement);
result["str_response_string"] = xmldoc.InnerXml;
result["int_response_code"] = 200;
result["content_type"] = "text/xml";
result["keepalive"] = false;
result["reusecontext"] = false;
result = CheckOrigin(result);
return result;
}
}
}
| |
using UnityEngine;
using System.Collections;
[System.Serializable]
public class Chip8
{
#region constants
/// <summary>
/// 5 bytes long digits from 0 to F. 8x5 pixels
/// </summary>
private readonly byte[] DIGITS = new byte[80]
{
0xF0, 0x90, 0x90, 0x90, 0xF0, // 0
0x20, 0x60, 0x20, 0x20, 0x70, // 1
0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2
0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3
0x90, 0x90, 0xF0, 0x10, 0x10, // 4
0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5
0xF0, 0x80, 0xF0, 0x90, 0xF0, // 6
0xF0, 0x10, 0x20, 0x40, 0x40, // 7
0xF0, 0x90, 0xF0, 0x90, 0xF0, // 8
0xF0, 0x90, 0xF0, 0x10, 0xF0, // 9
0xF0, 0x90, 0xF0, 0x90, 0x90, // A
0xE0, 0x90, 0xE0, 0x90, 0xE0, // B
0xF0, 0x80, 0x80, 0x80, 0xF0, // C
0xE0, 0x90, 0x90, 0x90, 0xE0, // D
0xF0, 0x80, 0xF0, 0x80, 0xF0, // E
0xF0, 0x80, 0xF0, 0x80, 0x80 // F
};
/// <summary>
/// Maximum number of cycles keypad input is active before it is read.
/// Key is reset if it is not read in INPUT_CYCLE_DURATION cycles.
/// </summary>
private const byte INPUT_CYCLE_DURATION = 100;
/// <summary>
/// Program counter starts at 0x200. It's the start position of most Chip-8 programs.
/// </summary>
private const ushort PC_START_POS = 0x200;
private const ushort SCREEN_HEIGHT = 32;
private const ushort SCREEN_WIDTH = 64;
#endregion
/// <summary>
/// Delay timer register value. Delay timer subtracts 1 when value is non-zero at a rate of 60Hz and deactivates when the value reaches 0.
/// </summary>
private byte delayReg;
/// <summary>
/// Index register
/// </summary>
private ushort indexReg;
/// <summary>
/// Hex keypad with keys 0 - F
/// </summary>
private byte[] keypad = new byte[16];
/// <summary>
/// 4K memory
/// </summary>
private byte[] memory = new byte[4096];
/// <summary>
/// 2 byte long opcode
/// </summary>
private ushort opcode;
/// <summary>
/// Program counter
/// </summary>
private ushort pc;
/// <summary>
/// Screen is refreshed when true
/// </summary>
private bool refreshScreen = false;
/// <summary>
/// Black and white screen with resolution of 64 x 32 (2048px)
/// </summary>
private BitArray screen = new BitArray(SCREEN_WIDTH * SCREEN_HEIGHT);
/// <summary>
/// Sound timer register value. Sound timer is active when value is non-zero. Decrements at every cycle.
/// As long as this value is greater than zero, the chip buzzer will sound.
/// </summary>
private byte soundReg;
/// <summary>
/// Stack pointer
/// </summary>
private ushort sp;
/// <summary>
/// Stack used to store the addresses that the interpreter should return to when finished a subroutine.
/// Up to 16 levels of nested subroutines are supported.
/// </summary>
private ushort[] stack = new ushort[16];
/// <summary>
/// CPU registers V0...VF
/// </summary>
private byte[] v = new byte[16];
public bool RefreshScreen { get { return refreshScreen; } set { refreshScreen = value; } }
public BitArray Screen { get { return screen; } }
public byte SoundReg { get { return soundReg; } }
public Chip8()
{
Initialize();
}
/// <summary>
/// Loads data into programs memory. Memory starts from PC_START_POS (0x200)
/// </summary>
/// <param name="data"></param>
public void LoadIntoMemory(byte[] data)
{
for (int i = 0; i < data.Length; i++)
{
memory[i + PC_START_POS] = data[i];
}
}
public void Initialize()
{
pc = PC_START_POS;
opcode = 0;
indexReg = 0;
sp = 0;
//Load digits to memory 0x000 to 0x1FF
for (int i = 0; i < DIGITS.Length; i++)
{
memory[i] = DIGITS[i];
}
//Reset registers
for (int i = 0; i < v.Length; i++)
{
v[i] = 0;
}
//Reset keypad
for (int i = 0; i < keypad.Length; i++)
{
keypad[i] = 0;
}
//Reset call stack
for (int i = 0; i < stack.Length; i++)
{
stack[i] = 0;
}
//Reset screen
for (int i = 0; i < screen.Count; i++)
{
screen[i] = false;
}
refreshScreen = true;
//Reset timers
delayReg = 0;
soundReg = 0;
}
public void SetKeys(BitArray keys)
{
//for (int i = 0; i < keypad.Count; i++)
for (int i = 0; i < keypad.Length; i++)
{
//Change value only when it's set to true. Keys are reset manually in RunCycle when a keypress is handled.
if(keys[i] == true)
keypad[i] = INPUT_CYCLE_DURATION;
}
}
public void RunCycle()
{
/* Opcode is 16-bit long. Fetch the data pointed by the pc and merge it with the next byte.
* In C# the second shift operand is always 32-bit int and therefore the result will also be a 32-bit int.
* The result can be casted to ushort however because the data is shifted only 8 bits and therefore the result should never exceed 16 bits.
*/
opcode = (ushort)(memory[pc] << 8 | memory[pc + 1]);
//Decode and execute opcode
switch(opcode & 0xF000)
{
case 0x0000: // 0x0???
switch(opcode & 0x0FFF)
{
//00E0 CLS - Clear the display
case 0x00E0:
for (int i = 0; i < screen.Length; i++)
{
screen[i] = false;
}
pc += 2;
refreshScreen = true;
break;
//00EE RET - Return from a subroutine
case 0x00EE:
sp--;
pc = stack[sp];
pc += 2;
break;
default:
Debug.LogError("Error! Unknown opcode: " + opcode.ToString("x2"));
break;
}
break;
case 0x1000: // 0x1???
//1nnn - JP addr - Jump to location nnn.
pc = (ushort)(opcode & 0x0FFF);
break;
case 0x2000: // 0x2???
//2nnn - CALL addr - Call subroutine at nnn.
stack[sp] = pc;
sp++;
pc = (ushort)(opcode & 0x0FFF);
break;
case 0x3000: // 0x3???
//3xkk - SE Vx, byte - Skip next instruction if Vx = kk.
//Shift 8 bits to right because there's 8 bits (kk) after x
if (v[(opcode & 0x0F00) >> 8] == (opcode & 0x00FF))
pc += 4;
else
pc += 2;
break;
case 0x4000: // 0x4???
//4xkk - SNE Vx, byte - Skip next instruction if Vx != kk.
if (v[(opcode & 0x0F00) >> 8] != (opcode & 0x0FF))
pc += 4;
else
pc += 2;
break;
case 0x5000: // 0x5???
//5xy0 - SE Vx, Vy - Skip next instruction if Vx = Vy.
if ((opcode & 0x000F) == 0x0000)
{
if (v[(opcode & 0x0F00) >> 8] == v[(opcode & 0x00F0) >> 4])
pc += 4;
else
pc += 2;
}
else
Debug.LogError("Error! Unknown opcode: " + opcode.ToString("x2"));
break;
case 0x6000: // 0x6???
//6xkk - LD Vx, byte - Set Vx = kk.
v[(opcode & 0x0F00) >> 8] = (byte)(opcode & 0x00FF);
pc += 2;
break;
case 0x7000: // 0x7???
//7xkk - ADD Vx, byte - Set Vx = Vx + kk.
v[(opcode & 0x0F00) >> 8] = (byte)(v[(opcode & 0x0F00) >> 8] + opcode & 0x00FF);
pc += 2;
break;
case 0x8000: // 0x8???
switch(opcode & 0x000F)
{
case 0x0000:
//8xy0 - LD Vx, Vy - Set Vx = Vy.
v[(opcode & 0x0F00) >> 8] = v[(opcode & 0x00F0) >> 4];
pc += 2;
break;
case 0x0001:
//8xy1 - OR Vx, Vy - Set Vx = Vx OR Vy.
v[(opcode & 0x0F00) >> 8] = (byte)(v[(opcode & 0x0F00) >> 8] | v[(opcode & 0x00F0) >> 4]);
pc += 2;
break;
case 0x0002:
//8xy2 - AND Vx, Vy - Set Vx = Vx AND Vy.
v[(opcode & 0x0F00) >> 8] = (byte)(v[(opcode & 0x0F00) >> 8] & v[(opcode & 0x00F0) >> 4]);
pc += 2;
break;
case 0x0003:
//8xy3 - XOR Vx, Vy - Set Vx = Vx XOR Vy.
v[(opcode & 0x0F00) >> 8] = (byte)(v[(opcode & 0x0F00) >> 8] ^ v[(opcode & 0x00F0) >> 4]);
pc += 2;
break;
case 0x0004:
//8xy4 - ADD Vx, Vy - Set Vx = Vx + Vy, set VF = carry.
int temp = v[(opcode & 0x0F00) >> 8] + v[(opcode & 0x00F0) >> 4];
//Set carry flag is result is greater than 8 bits
if (((temp >> 8) & 0xFFFF) >= 1)
v[0xF] = 1;
else
v[0xF] = 0;
//Only the lowest 8 bit are stored in v[x]
v[(opcode & 0x0F00) >> 8] = (byte)temp;
pc += 2;
break;
case 0x0005:
//8xy5 - SUB Vx, Vy - Set Vx = Vx - Vy, set VF = NOT borrow.
if (v[(opcode & 0x0F00) >> 8] > v[(opcode & 0x00F0) >> 4])
v[0xF] = 1;
else
v[0xF] = 0;
v[(opcode & 0x0F00) >> 8] = (byte)(v[(opcode & 0x0F00) >> 8] - v[(opcode & 0x00F0) >> 4]);
pc += 2;
break;
case 0x0006:
//8xy6 - SHR Vx {, Vy} - Set Vx = Vx SHR 1.
//Set v[F] to 1 if the least significant in v[x] bit is 1, otherwise 0.
v[0xF] = (byte)(v[(opcode & 0x0F00) >> 8] & 0x1);
//Right shift v[x]
v[(opcode & 0x0F00) >> 8] = (byte)(v[(opcode & 0x0F00) >> 8] >> 1);
pc += 2;
break;
case 0x0007:
//8xy7 - SUBN Vx, Vy - Set Vx = Vy - Vx, set VF = NOT borrow.
if (v[(opcode & 0x00F0) >> 4] > v[(opcode & 0x0F00) >> 8])
v[0xF] = 1;
else
v[0xF] = 0;
v[(opcode & 0x0F00) >> 8] = (byte)(v[(opcode & 0x00F0) >> 4] - v[(opcode & 0x0F00) >> 8]);
pc += 2;
break;
case 0x000E:
//8xyE - SHL Vx {, Vy} - Set Vx = Vx SHL 1.
//Set v[F] = 1 if the least significant bit in v[x] is 1, otherwise 0
v[0xF] = (byte)(v[(opcode & 0x0F00) >> 8] & 0x1);
//Left shift v[x]
v[(opcode & 0x0F00) >> 8] = (byte)(v[(opcode & 0x0F00) >> 8] >> 1);
pc += 2;
break;
default:
Debug.LogError("Error! Unknown opcode: " + opcode.ToString("x2"));
break;
}
break;
case 0x9000: // 0x9???
//9xy0 - SNE Vx, Vy - Skip next instruction if Vx != Vy.
if ((opcode & 0x000F) == 0x0000)
{
if (v[(opcode & 0x0F00) >> 8] != v[(opcode & 0x00F0) >> 4])
pc += 4;
else
pc += 2;
}
else
Debug.LogError("Error! Unknown opcode: " + opcode.ToString("x2"));
break;
case 0xA000: // 0xA???
//Annn - LD I, addr - Set I = nnn.
indexReg = (ushort)(opcode & 0x0FFF);
pc += 2;
break;
case 0xB000: // 0xB???
//Bnnn - JP V0, addr - Jump to location nnn + V0.
pc = (ushort)((opcode & 0x0FFF) + v[0]);
break;
case 0xC000: // 0xC???
//Cxkk - RND Vx, byte - Set Vx = random byte AND kk.
//Random.Next is inclusive, exclusive
v[(opcode & 0x0F00) >> 8] = (byte)((opcode & 0x00FF) & Random.Range(0x0, 0x100));
pc += 2;
break;
case 0xD000:// 0xD???
//Dxyn - DRW Vx, Vy, nibble - Display n-byte sprite starting at memory location I at (Vx, Vy), set VF = collision.
ushort length = (ushort)(opcode & 0x000F);
ushort x = v[(ushort)((opcode & 0x0F00) >> 8)];
ushort y = v[(ushort)((opcode & 0x00F0) >> 4)];
//Wrap sprites if they are completely outside the screen
x = (ushort)(x % SCREEN_WIDTH);
y = (ushort)(y % SCREEN_HEIGHT);
ushort sprite;
v[0xF] = 0;
//Cut of if part of sprite goes offscreen
int rowMax = length;
if (y + length > SCREEN_HEIGHT)
rowMax = SCREEN_HEIGHT - y;
//Loop over rows
for (int row = 0; row < rowMax; row++)
{
//Read sprite from memory
sprite = memory[indexReg + row];
//Screen bit position for x, y + row
int index = (y + row) * SCREEN_WIDTH + x;
//Cut of if part of sprite goes offscreen
int xMax = 8;
if (x + 8 > SCREEN_WIDTH)
xMax = SCREEN_WIDTH - x;
for (int xBit = 0; xBit < xMax; xBit++)
{
if ((sprite & 0x80 >> xBit) != 0)
{
int tempIndex = index + xBit;
bool value = (sprite & 0x80 >> xBit) != 0;
//Set collision flag if this pixel was already set
if(screen[tempIndex] == true)
v[0xF] = 1;
screen[tempIndex] ^= value;
}
}
}
refreshScreen = true;
pc += 2;
break;
case 0xE000:// 0xE???
if ((opcode & 0x00FF) == 0x009E)
{
//Ex9E - SKP Vx - Skip next instruction if key with the value of Vx is pressed.
if (keypad[v[(opcode & 0x0F00) >> 8]] > 0)
{
//Reset key
keypad[v[(opcode & 0x0F00) >> 8]] = 0;
pc += 4;
}
else
pc += 2;
}
else if ((opcode & 0x00FF) == 0x00A1)
{
//ExA1 - SKNP Vx - Skip next instruction if key with the value of Vx is not pressed.
if (keypad[v[(opcode & 0x0F00) >> 8]] == 0)
{
pc += 4;
}
else
{
//Reset key
keypad[v[(opcode & 0x0F00) >> 8]] = 0;
pc += 2;
}
}
else
Debug.LogError("Error! Unknown opcode: " + opcode.ToString("x2"));
break;
case 0xF000:// 0xF???
switch(opcode & 0x00FF)
{
case 0x0007:
//Fx07 - LD Vx, DT - Set Vx = delay timer value.
v[(opcode & 0x0F00) >> 8] = delayReg;
pc += 2;
break;
case 0x000A:
//Fx0A - LD Vx, K - Wait for a key press, store the value of the key in Vx.
bool keyPressed = false;
for (byte i = 0; i < keypad.Length; i++)
{
if (keypad[i] > 0)
{
keyPressed = true;
//Reset key
keypad[i] = 0;
v[(opcode & 0x0F00) >> 8] = i;
break;
}
}
//Wait for key press
if (keyPressed == false)
break;
else
pc += 2;
break;
case 0x0015:
//Fx15 - LD DT, Vx - Set delay timer = Vx.
delayReg = v[(opcode & 0x0F00) >> 8];
pc += 2;
break;
case 0x0018:
//Fx18 - LD ST, Vx - Set sound timer = Vx.
soundReg = v[(opcode & 0x0F00) >> 8];
pc += 2;
break;
case 0x001E:
//Fx1E - ADD I, Vx - Set I = I + Vx.
indexReg = (ushort)(indexReg + v[(opcode & 0x0F00) >> 8]);
//VF is set to 1 when range overflow (I+VX>0xFFF), and 0 when there isn't.
//This is undocumented feature of the CHIP-8 and used by Spacefight 2091! game. Source: https://en.wikipedia.org/wiki/CHIP-8
if (indexReg > 0xFFF)
v[0xF] = 1;
else
v[0xF] = 0;
pc += 2;
break;
case 0x0029:
//Fx29 - LD F, Vx - Set I = location of sprite for digit Vx.
indexReg = (ushort)(5 * v[(opcode & 0x0F00) >> 8]);
pc += 2;
break;
case 0x0033:
//Fx33 - LD B, Vx - Store BCD representation of Vx in memory locations I, I+1, and I+2.
byte value = v[(opcode & 0x0F00) >> 8];
memory[indexReg] = (byte)(value / 100);
memory[indexReg + 1] = (byte)((value / 10) % 10);
memory[indexReg + 2] = (byte)((value % 100) % 10);
pc += 2;
break;
case 0x0055:
//Fx55 - LD [I], Vx - Store registers V0 through Vx in memory starting at location I.
for (int i = 0; i <= ((opcode & 0x0F00) >> 8); i++)
{
memory[indexReg + i] = v[i];
}
pc += 2;
break;
case 0x0065:
//Fx65 - LD Vx, [I] - Read registers V0 through Vx from memory starting at location I.
for (int i = 0; i <= ((opcode & 0x0F00) >> 8); i++)
{
v[i] = memory[indexReg + i];
}
pc += 2;
break;
default:
Debug.LogError("Error! Unknown opcode: " + opcode.ToString("x2"));
break;
}
break;
default:
Debug.LogError("Error! Unknown opcode: " + opcode.ToString("x2"));
break;
}
//Update timers
if (delayReg > 0)
{
delayReg--;
}
if(soundReg > 0)
{
soundReg--;
}
ReduceKeypadCycles();
}
/// <summary>
/// Reduces positive keypad values by one.
/// Used for ignoring inputs that are set more than INPUT_CYCLE_DURATION cycles ago and not yet handled.
/// </summary>
private void ReduceKeypadCycles()
{
for (int i = 0; i < keypad.Length; i++)
{
if (keypad[i] > 0)
keypad[i]--;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Flurl.Http;
using Flurl.Http.Configuration;
using Flurl.Http.Testing;
using NUnit.Framework;
namespace Flurl.Test.Http
{
/// <summary>
/// Most HTTP tests in this project are with Flurl in fake mode. These are some real ones, mostly using http://httpbin.org.
/// </summary>
[TestFixture, Parallelizable]
public class RealHttpTests
{
[TestCase("gzip", "gzipped")]
[TestCase("deflate", "deflated"), Ignore("#474")]
public async Task decompresses_automatically(string encoding, string jsonKey) {
var result = await "https://httpbin.org"
.AppendPathSegment(encoding)
.WithHeader("Accept-encoding", encoding)
.GetJsonAsync<Dictionary<string, object>>();
Assert.AreEqual(true, result[jsonKey]);
}
[TestCase("https://httpbin.org/image/jpeg", null, "my-image.jpg", "my-image.jpg")]
// should use last path segment url-decoded (foo?bar:ding), then replace illegal path characters with _
[TestCase("https://httpbin.org/anything/foo%3Fbar%3Ading", null, null, "foo_bar_ding")]
// should use filename from content-disposition excluding any leading/trailing quotes
[TestCase("https://httpbin.org/response-headers", "attachment; filename=\"myfile.txt\"", null, "myfile.txt")]
// should prefer filename* over filename, per https://tools.ietf.org/html/rfc6266#section-4.3
[TestCase("https://httpbin.org/response-headers", "attachment; filename=filename.txt; filename*=utf-8''filenamestar.txt", null, "filenamestar.txt")]
// has Content-Disposition header but no filename in it, should use last part of URL
[TestCase("https://httpbin.org/response-headers", "attachment", null, "response-headers")]
public async Task can_download_file(string url, string contentDisposition, string suppliedFilename, string expectedFilename) {
var folder = Path.Combine(Path.GetTempPath(), $"flurl-test-{Guid.NewGuid()}"); // random so parallel tests don't trip over each other
try {
var path = await url.SetQueryParam("Content-Disposition", contentDisposition).DownloadFileAsync(folder, suppliedFilename);
var expected = Path.Combine(folder, expectedFilename);
Assert.AreEqual(expected, path);
Assert.That(File.Exists(expected));
}
finally {
Directory.Delete(folder, true);
}
}
[Test]
public async Task can_post_and_receive_json() {
var result = await "https://httpbin.org/post".PostJsonAsync(new { a = 1, b = 2 }).ReceiveJson();
Assert.AreEqual(result.json.a, 1);
Assert.AreEqual(result.json.b, 2);
}
[Test]
public async Task can_get_stream() {
using (var stream = await "https://www.google.com".GetStreamAsync())
using (var ms = new MemoryStream()) {
stream.CopyTo(ms);
Assert.Greater(ms.Length, 0);
}
}
[Test]
public async Task can_get_string() {
var s = await "https://www.google.com".GetStringAsync();
Assert.Greater(s.Length, 0);
}
[Test]
public async Task can_get_byte_array() {
var bytes = await "https://www.google.com".GetBytesAsync();
Assert.Greater(bytes.Length, 0);
}
[Test]
public void fails_on_non_success_status() {
Assert.ThrowsAsync<FlurlHttpException>(async () => await "https://httpbin.org/status/418".GetAsync());
}
[Test]
public async Task can_allow_non_success_status() {
var resp = await "https://httpbin.org/status/418".AllowHttpStatus("4xx").GetAsync();
Assert.AreEqual(418, resp.StatusCode);
}
[Test]
public async Task can_post_multipart() {
var folder = "c:\\flurl-test-" + Guid.NewGuid(); // random so parallel tests don't trip over each other
var path1 = Path.Combine(folder, "upload1.txt");
var path2 = Path.Combine(folder, "upload2.txt");
Directory.CreateDirectory(folder);
try {
File.WriteAllText(path1, "file contents 1");
File.WriteAllText(path2, "file contents 2");
using (var stream = File.OpenRead(path2)) {
var resp = await "https://httpbin.org/post"
.PostMultipartAsync(content => {
content
.AddStringParts(new { a = 1, b = 2 })
.AddString("DataField", "hello!")
.AddFile("File1", path1)
.AddFile("File2", stream, "foo.txt");
// hack to deal with #179. appears to be fixed on httpbin now.
// content.Headers.ContentLength = 735;
})
//.ReceiveString();
.ReceiveJson();
Assert.AreEqual("1", resp.form.a);
Assert.AreEqual("2", resp.form.b);
Assert.AreEqual("hello!", resp.form.DataField);
Assert.AreEqual("file contents 1", resp.files.File1);
Assert.AreEqual("file contents 2", resp.files.File2);
}
}
finally {
Directory.Delete(folder, true);
}
}
[Test]
public async Task can_handle_http_error() {
var handlerCalled = false;
try {
await "https://httpbin.org/status/500".ConfigureRequest(c => {
c.OnError = call => {
call.ExceptionHandled = true;
handlerCalled = true;
};
}).GetJsonAsync();
Assert.IsTrue(handlerCalled, "error handler should have been called.");
}
catch (FlurlHttpException) {
Assert.Fail("exception should have been suppressed.");
}
}
[Test]
public async Task can_handle_parsing_error() {
Exception ex = null;
try {
await "http://httpbin.org/image/jpeg".ConfigureRequest(c => {
c.OnError = call => {
ex = call.Exception;
call.ExceptionHandled = true;
};
}).GetJsonAsync();
Assert.IsNotNull(ex, "error handler should have been called.");
Assert.IsInstanceOf<FlurlParsingException>(ex);
}
catch (FlurlHttpException) {
Assert.Fail("exception should have been suppressed.");
}
}
[Test]
public async Task can_comingle_real_and_fake_tests() {
// do a fake call while a real call is running
var realTask = "https://www.google.com/".GetStringAsync();
using (var test = new HttpTest()) {
test.RespondWith("fake!");
var fake = await "https://www.google.com/".GetStringAsync();
Assert.AreEqual("fake!", fake);
}
Assert.AreNotEqual("fake!", await realTask);
}
[Test]
public void can_set_timeout() {
var ex = Assert.ThrowsAsync<FlurlHttpTimeoutException>(async () => {
await "https://httpbin.org/delay/5"
.WithTimeout(TimeSpan.FromMilliseconds(50))
.HeadAsync();
});
Assert.That(ex.InnerException is TaskCanceledException);
}
[Test]
public void can_cancel_request() {
var cts = new CancellationTokenSource();
var ex = Assert.ThrowsAsync<FlurlHttpException>(async () => {
var task = "https://httpbin.org/delay/5".GetAsync(cts.Token);
cts.Cancel();
await task;
});
Assert.That(ex.InnerException is TaskCanceledException);
}
[Test] // make sure the 2 tokens in play are playing nicely together
public void can_set_timeout_and_cancellation_token() {
// cancellation with timeout value set
var cts = new CancellationTokenSource();
var ex = Assert.ThrowsAsync<FlurlHttpException>(async () => {
var task = "https://httpbin.org/delay/5"
.WithTimeout(TimeSpan.FromMilliseconds(50))
.GetAsync(cts.Token);
cts.Cancel();
await task;
});
Assert.That(ex.InnerException is OperationCanceledException);
Assert.IsTrue(cts.Token.IsCancellationRequested);
// timeout with cancellation token set
cts = new CancellationTokenSource();
ex = Assert.ThrowsAsync<FlurlHttpTimeoutException>(async () => {
await "https://httpbin.org/delay/5"
.WithTimeout(TimeSpan.FromMilliseconds(50))
.GetAsync(cts.Token);
});
Assert.That(ex.InnerException is OperationCanceledException);
Assert.IsFalse(cts.Token.IsCancellationRequested);
}
[Test, Ignore("failing on AppVeyor, holding up bugfix release")]
public async Task connection_lease_timeout_doesnt_disrupt_calls() {
// testing this quickly is tricky. HttpClient will be replaced by a new instance after 1 timeout and disposed
// after another, so the timeout period (typically minutes in real-world scenarios) needs to be long enough
// that we don't dispose before the response from google is received. 1 second seems to work.
var cli = new FlurlClient("http://www.google.com");
cli.Settings.ConnectionLeaseTimeout = TimeSpan.FromMilliseconds(1000);
var httpClients = new List<HttpClient>();
var tasks = new List<Task>();
// ping google for about 2.5 seconds
for (var i = 0; i < 25; i++) {
if (!httpClients.Contains(cli.HttpClient))
httpClients.Add(cli.HttpClient);
tasks.Add(cli.Request().HeadAsync());
await Task.Delay(100);
}
await Task.WhenAll(tasks); // failed HTTP status, etc, would throw here and fail the test.
Assert.AreEqual(3, httpClients.Count);
// only the first one should be disposed, which isn't particularly simple to check
Assert.ThrowsAsync<ObjectDisposedException>(() => httpClients[0].GetAsync("http://www.google.com"));
await httpClients[1].GetAsync("http://www.google.com");
await httpClients[2].GetAsync("http://www.google.com");
}
[Test]
public async Task test_settings_override_client_settings() {
var cli1 = new FlurlClient();
cli1.Settings.HttpClientFactory = new DefaultHttpClientFactory();
var h = cli1.HttpClient; // force (lazy) instantiation
using (var test = new HttpTest()) {
test.Settings.Redirects.Enabled = false;
test.RespondWith("foo!");
var s = await cli1.Request("http://www.google.com")
.WithAutoRedirect(true) // test says redirects are off, and test should always win
.GetStringAsync();
Assert.AreEqual("foo!", s);
Assert.IsFalse(cli1.Settings.Redirects.Enabled);
var cli2 = new FlurlClient();
cli2.Settings.HttpClientFactory = new DefaultHttpClientFactory();
h = cli2.HttpClient;
test.RespondWith("foo 2!");
s = await cli2.Request("http://www.google.com")
.WithAutoRedirect(true) // test says redirects are off, and test should always win
.GetStringAsync();
Assert.AreEqual("foo 2!", s);
Assert.IsFalse(cli2.Settings.Redirects.Enabled);
}
}
[Test]
public async Task can_allow_real_http_in_test() {
using (var test = new HttpTest()) {
test.RespondWith("foo");
test.ForCallsTo("*httpbin*").AllowRealHttp();
Assert.AreEqual("foo", await "https://www.google.com".GetStringAsync());
Assert.AreNotEqual("foo", await "https://httpbin.org/get".GetStringAsync());
Assert.AreEqual("bar", (await "https://httpbin.org/get?x=bar".GetJsonAsync()).args.x);
Assert.AreEqual("foo", await "https://www.microsoft.com".GetStringAsync());
// real calls still get logged
Assert.AreEqual(4, test.CallLog.Count);
test.ShouldHaveCalled("https://httpbin*").Times(2);
}
}
[Test]
public async Task does_not_create_empty_content_for_forwarding_content_header() {
// Flurl was auto-creating an empty HttpContent object in order to forward content-level headers,
// and on .NET Framework a GET with a non-null HttpContent throws an exceptions (#583)
var calls = new List<FlurlCall>();
var resp = await "http://httpbingo.org/redirect-to?url=http%3A%2F%2Fexample.com%2F".ConfigureRequest(c => {
c.Redirects.ForwardHeaders = true;
c.BeforeCall = call => calls.Add(call);
}).PostUrlEncodedAsync("test=test");
Assert.AreEqual(2, calls.Count);
Assert.AreEqual(HttpMethod.Post, calls[0].Request.Verb);
Assert.IsNotNull(calls[0].HttpRequestMessage.Content);
Assert.AreEqual(HttpMethod.Get, calls[1].Request.Verb);
Assert.IsNull(calls[1].HttpRequestMessage.Content);
}
#region cookies
[Test]
public async Task can_send_cookies() {
var req = "https://httpbin.org/cookies".WithCookies(new { x = 1, y = 2 });
Assert.AreEqual(2, req.Cookies.Count());
Assert.IsTrue(req.Cookies.Contains(("x", "1")));
Assert.IsTrue(req.Cookies.Contains(("y", "2")));
var s = await req.GetStringAsync();
var resp = await req.WithAutoRedirect(false).GetJsonAsync();
// httpbin returns json representation of cookies that were sent
Assert.AreEqual("1", resp.cookies.x);
Assert.AreEqual("2", resp.cookies.y);
}
[Test]
public async Task can_receive_cookies() {
// endpoint does a redirect, so we need to disable auto-redirect in order to see the cookie in the response
var resp = await "https://httpbin.org/cookies/set?z=999".WithAutoRedirect(false).GetAsync();
Assert.AreEqual("999", resp.Cookies.FirstOrDefault(c => c.Name == "z")?.Value);
// but using WithCookies we can capture it even with redirects enabled
await "https://httpbin.org/cookies/set?z=999".WithCookies(out var cookies).GetAsync();
Assert.AreEqual("999", cookies.FirstOrDefault(c => c.Name == "z")?.Value);
// this works with redirects too
using (var session = new CookieSession("https://httpbin.org/cookies")) {
await session.Request("set?z=999").GetAsync();
Assert.AreEqual("999", session.Cookies.FirstOrDefault(c => c.Name == "z")?.Value);
}
}
[Test]
public async Task can_set_cookies_before_setting_url() {
var req = new FlurlRequest().WithCookie("z", "999");
req.Url = "https://httpbin.org/cookies";
var resp = await req.GetJsonAsync();
Assert.AreEqual("999", resp.cookies.z);
}
[Test]
public async Task can_send_different_cookies_per_request() {
var cli = new FlurlClient();
var req1 = cli.Request("https://httpbin.org/cookies").WithCookie("x", "123");
var req2 = cli.Request("https://httpbin.org/cookies").WithCookie("x", "abc");
var resp2 = await req2.GetJsonAsync();
var resp1 = await req1.GetJsonAsync();
Assert.AreEqual("123", resp1.cookies.x);
Assert.AreEqual("abc", resp2.cookies.x);
}
[Test]
public async Task can_receive_cookie_from_redirect_response_and_add_it_to_jar() {
// use httpbingo instead of httpbin because of redirect issue https://github.com/postmanlabs/httpbin/issues/617
var resp = await "https://httpbingo.org/redirect-to".SetQueryParam("url", "/cookies/set?x=foo").WithCookies(out var jar).GetJsonAsync();
Assert.AreEqual("foo", resp.x);
Assert.AreEqual(1, jar.Count);
}
#endregion
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Graphics.OpenGL;
using osu.Framework.Graphics.OpenGL.Textures;
using osu.Framework.IO.Stores;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
using osu.Framework.Extensions;
using osu.Framework.Logging;
using osuTK.Graphics.ES30;
namespace osu.Framework.Graphics.Textures
{
public class TextureStore : ResourceStore<TextureUpload>
{
private readonly Dictionary<string, Texture> textureCache = new Dictionary<string, Texture>();
private readonly All filteringMode;
private readonly bool manualMipmaps;
protected TextureAtlas Atlas;
private const int max_atlas_size = 1024;
/// <summary>
/// Decides at what resolution multiple this <see cref="TextureStore"/> is providing sprites at.
/// ie. if we are providing high resolution (at 2x the resolution of standard 1366x768) sprites this should be 2.
/// </summary>
public readonly float ScaleAdjust;
public TextureStore(IResourceStore<TextureUpload> store = null, bool useAtlas = true, All filteringMode = All.Linear, bool manualMipmaps = false, float scaleAdjust = 2)
: base(store)
{
this.filteringMode = filteringMode;
this.manualMipmaps = manualMipmaps;
ScaleAdjust = scaleAdjust;
AddExtension(@"png");
AddExtension(@"jpg");
if (useAtlas)
{
int size = Math.Min(max_atlas_size, GLWrapper.MaxTextureSize);
Atlas = new TextureAtlas(size, size, filteringMode: filteringMode, manualMipmaps: manualMipmaps);
}
}
private Texture getTexture(string name, WrapMode wrapModeS = WrapMode.None, WrapMode wrapModeT = WrapMode.None) => loadRaw(base.Get(name), wrapModeS, wrapModeT);
private Texture loadRaw(TextureUpload upload, WrapMode wrapModeS = WrapMode.None, WrapMode wrapModeT = WrapMode.None)
{
if (upload == null) return null;
TextureGL glTexture = null;
if (Atlas != null)
{
if ((glTexture = Atlas.Add(upload.Width, upload.Height, wrapModeS, wrapModeT)) == null)
{
Logger.Log(
$"Texture requested ({upload.Width}x{upload.Height}) which exceeds {nameof(TextureStore)}'s atlas size ({max_atlas_size}x{max_atlas_size}) - bypassing atlasing. Consider using {nameof(LargeTextureStore)}.",
LoggingTarget.Performance);
}
}
glTexture ??= new TextureGLSingle(upload.Width, upload.Height, manualMipmaps, filteringMode, wrapModeS, wrapModeT);
Texture tex = new Texture(glTexture) { ScaleAdjust = ScaleAdjust };
tex.SetData(upload);
return tex;
}
/// <summary>
/// Retrieves a texture from the store and adds it to the atlas.
/// </summary>
/// <param name="name">The name of the texture.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>The texture.</returns>
public new Task<Texture> GetAsync(string name, CancellationToken cancellationToken) => GetAsync(name, default, default, cancellationToken);
/// <summary>
/// Retrieves a texture from the store and adds it to the atlas.
/// </summary>
/// <param name="name">The name of the texture.</param>
/// <param name="wrapModeS">The texture wrap mode in horizontal direction.</param>
/// <param name="wrapModeT">The texture wrap mode in vertical direction.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>The texture.</returns>
public Task<Texture> GetAsync(string name, WrapMode wrapModeT, WrapMode wrapModeS, CancellationToken cancellationToken = default) =>
Task.Run(() => Get(name, wrapModeS, wrapModeT), cancellationToken); // TODO: best effort. need to re-think textureCache data structure to fix this.
/// <summary>
/// Retrieves a texture from the store and adds it to the atlas.
/// </summary>
/// <param name="name">The name of the texture.</param>
/// <returns>The texture.</returns>
public new Texture Get(string name) => Get(name, default, default);
private readonly Dictionary<string, Task> retrievalCompletionSources = new Dictionary<string, Task>();
/// <summary>
/// Retrieves a texture from the store and adds it to the atlas.
/// </summary>
/// <param name="name">The name of the texture.</param>
/// <param name="wrapModeS">The texture wrap mode in horizontal direction.</param>
/// <param name="wrapModeT">The texture wrap mode in vertical direction.</param>
/// <returns>The texture.</returns>
public virtual Texture Get(string name, WrapMode wrapModeS, WrapMode wrapModeT)
{
if (string.IsNullOrEmpty(name)) return null;
string key = $"{name}:wrap-{(int)wrapModeS}-{(int)wrapModeT}";
TaskCompletionSource<Texture> tcs = null;
Task task;
lock (retrievalCompletionSources)
{
// Check if the texture exists in the cache.
if (TryGetCached(key, out var cached))
return cached;
// check if an existing lookup was already started for this key.
if (!retrievalCompletionSources.TryGetValue(key, out task))
// if not, take responsibility for the lookup.
retrievalCompletionSources[key] = (tcs = new TaskCompletionSource<Texture>()).Task;
}
// handle the case where a lookup is already in progress.
if (task != null)
{
task.WaitSafely();
// always perform re-lookups through TryGetCached (see LargeTextureStore which has a custom implementation of this where it matters).
if (TryGetCached(key, out var cached))
return cached;
return null;
}
this.LogIfNonBackgroundThread(key);
Texture tex = null;
try
{
tex = getTexture(name, wrapModeS, wrapModeT);
if (tex != null)
tex.LookupKey = key;
return CacheAndReturnTexture(key, tex);
}
catch (TextureTooLargeForGLException)
{
Logger.Log($"Texture \"{name}\" exceeds the maximum size supported by this device ({GLWrapper.MaxTextureSize}px).", level: LogLevel.Error);
}
finally
{
// notify other lookups waiting on the same name lookup.
lock (retrievalCompletionSources)
{
Debug.Assert(tcs != null);
tcs.SetResult(tex);
retrievalCompletionSources.Remove(key);
}
}
return null;
}
/// <summary>
/// Attempts to retrieve an existing cached texture.
/// </summary>
/// <param name="lookupKey">The lookup key that uniquely identifies textures in the cache.</param>
/// <param name="texture">The returned texture. Null if the texture did not exist in the cache.</param>
/// <returns>Whether a cached texture was retrieved.</returns>
protected virtual bool TryGetCached([NotNull] string lookupKey, [CanBeNull] out Texture texture)
{
lock (textureCache)
return textureCache.TryGetValue(lookupKey, out texture);
}
/// <summary>
/// Caches and returns the given texture.
/// </summary>
/// <param name="lookupKey">The lookup key that uniquely identifies textures in the cache.</param>
/// <param name="texture">The texture to be cached and returned.</param>
/// <returns>The texture to be returned.</returns>
[CanBeNull]
protected virtual Texture CacheAndReturnTexture([NotNull] string lookupKey, [CanBeNull] Texture texture)
{
lock (textureCache)
return textureCache[lookupKey] = texture;
}
/// <summary>
/// Disposes and removes a texture from the cache.
/// </summary>
/// <param name="texture">The texture to purge from the cache.</param>
protected void Purge(Texture texture)
{
lock (textureCache)
{
if (textureCache.TryGetValue(texture.LookupKey, out var tex))
{
// we are doing this locally as right now, Textures don't dispose the underlying texture (leaving it to GC finalizers).
// in the case of a purge operation we are pretty sure this is the intended behaviour.
tex?.TextureGL?.Dispose();
tex?.Dispose();
}
textureCache.Remove(texture.LookupKey);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
//
// This file was autogenerated by a tool.
// Do not modify it.
//
namespace Microsoft.Azure.Batch
{
using Models = Microsoft.Azure.Batch.Protocol.Models;
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// The specification for a pool.
/// </summary>
public partial class PoolSpecification : ITransportObjectProvider<Models.PoolSpecification>, IPropertyMetadata
{
private class PropertyContainer : PropertyCollection
{
public readonly PropertyAccessor<IList<string>> ApplicationLicensesProperty;
public readonly PropertyAccessor<IList<ApplicationPackageReference>> ApplicationPackageReferencesProperty;
public readonly PropertyAccessor<bool?> AutoScaleEnabledProperty;
public readonly PropertyAccessor<TimeSpan?> AutoScaleEvaluationIntervalProperty;
public readonly PropertyAccessor<string> AutoScaleFormulaProperty;
public readonly PropertyAccessor<IList<CertificateReference>> CertificateReferencesProperty;
public readonly PropertyAccessor<CloudServiceConfiguration> CloudServiceConfigurationProperty;
public readonly PropertyAccessor<string> DisplayNameProperty;
public readonly PropertyAccessor<bool?> InterComputeNodeCommunicationEnabledProperty;
public readonly PropertyAccessor<int?> MaxTasksPerComputeNodeProperty;
public readonly PropertyAccessor<IList<MetadataItem>> MetadataProperty;
public readonly PropertyAccessor<NetworkConfiguration> NetworkConfigurationProperty;
public readonly PropertyAccessor<TimeSpan?> ResizeTimeoutProperty;
public readonly PropertyAccessor<StartTask> StartTaskProperty;
public readonly PropertyAccessor<int?> TargetDedicatedComputeNodesProperty;
public readonly PropertyAccessor<int?> TargetLowPriorityComputeNodesProperty;
public readonly PropertyAccessor<TaskSchedulingPolicy> TaskSchedulingPolicyProperty;
public readonly PropertyAccessor<IList<UserAccount>> UserAccountsProperty;
public readonly PropertyAccessor<VirtualMachineConfiguration> VirtualMachineConfigurationProperty;
public readonly PropertyAccessor<string> VirtualMachineSizeProperty;
public PropertyContainer() : base(BindingState.Unbound)
{
this.ApplicationLicensesProperty = this.CreatePropertyAccessor<IList<string>>("ApplicationLicenses", BindingAccess.Read | BindingAccess.Write);
this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor<IList<ApplicationPackageReference>>("ApplicationPackageReferences", BindingAccess.Read | BindingAccess.Write);
this.AutoScaleEnabledProperty = this.CreatePropertyAccessor<bool?>("AutoScaleEnabled", BindingAccess.Read | BindingAccess.Write);
this.AutoScaleEvaluationIntervalProperty = this.CreatePropertyAccessor<TimeSpan?>("AutoScaleEvaluationInterval", BindingAccess.Read | BindingAccess.Write);
this.AutoScaleFormulaProperty = this.CreatePropertyAccessor<string>("AutoScaleFormula", BindingAccess.Read | BindingAccess.Write);
this.CertificateReferencesProperty = this.CreatePropertyAccessor<IList<CertificateReference>>("CertificateReferences", BindingAccess.Read | BindingAccess.Write);
this.CloudServiceConfigurationProperty = this.CreatePropertyAccessor<CloudServiceConfiguration>("CloudServiceConfiguration", BindingAccess.Read | BindingAccess.Write);
this.DisplayNameProperty = this.CreatePropertyAccessor<string>("DisplayName", BindingAccess.Read | BindingAccess.Write);
this.InterComputeNodeCommunicationEnabledProperty = this.CreatePropertyAccessor<bool?>("InterComputeNodeCommunicationEnabled", BindingAccess.Read | BindingAccess.Write);
this.MaxTasksPerComputeNodeProperty = this.CreatePropertyAccessor<int?>("MaxTasksPerComputeNode", BindingAccess.Read | BindingAccess.Write);
this.MetadataProperty = this.CreatePropertyAccessor<IList<MetadataItem>>("Metadata", BindingAccess.Read | BindingAccess.Write);
this.NetworkConfigurationProperty = this.CreatePropertyAccessor<NetworkConfiguration>("NetworkConfiguration", BindingAccess.Read | BindingAccess.Write);
this.ResizeTimeoutProperty = this.CreatePropertyAccessor<TimeSpan?>("ResizeTimeout", BindingAccess.Read | BindingAccess.Write);
this.StartTaskProperty = this.CreatePropertyAccessor<StartTask>("StartTask", BindingAccess.Read | BindingAccess.Write);
this.TargetDedicatedComputeNodesProperty = this.CreatePropertyAccessor<int?>("TargetDedicatedComputeNodes", BindingAccess.Read | BindingAccess.Write);
this.TargetLowPriorityComputeNodesProperty = this.CreatePropertyAccessor<int?>("TargetLowPriorityComputeNodes", BindingAccess.Read | BindingAccess.Write);
this.TaskSchedulingPolicyProperty = this.CreatePropertyAccessor<TaskSchedulingPolicy>("TaskSchedulingPolicy", BindingAccess.Read | BindingAccess.Write);
this.UserAccountsProperty = this.CreatePropertyAccessor<IList<UserAccount>>("UserAccounts", BindingAccess.Read | BindingAccess.Write);
this.VirtualMachineConfigurationProperty = this.CreatePropertyAccessor<VirtualMachineConfiguration>("VirtualMachineConfiguration", BindingAccess.Read | BindingAccess.Write);
this.VirtualMachineSizeProperty = this.CreatePropertyAccessor<string>("VirtualMachineSize", BindingAccess.Read | BindingAccess.Write);
}
public PropertyContainer(Models.PoolSpecification protocolObject) : base(BindingState.Bound)
{
this.ApplicationLicensesProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CollectionToThreadSafeCollection(protocolObject.ApplicationLicenses, o => o),
"ApplicationLicenses",
BindingAccess.Read | BindingAccess.Write);
this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor(
ApplicationPackageReference.ConvertFromProtocolCollection(protocolObject.ApplicationPackageReferences),
"ApplicationPackageReferences",
BindingAccess.Read | BindingAccess.Write);
this.AutoScaleEnabledProperty = this.CreatePropertyAccessor(
protocolObject.EnableAutoScale,
"AutoScaleEnabled",
BindingAccess.Read | BindingAccess.Write);
this.AutoScaleEvaluationIntervalProperty = this.CreatePropertyAccessor(
protocolObject.AutoScaleEvaluationInterval,
"AutoScaleEvaluationInterval",
BindingAccess.Read | BindingAccess.Write);
this.AutoScaleFormulaProperty = this.CreatePropertyAccessor(
protocolObject.AutoScaleFormula,
"AutoScaleFormula",
BindingAccess.Read | BindingAccess.Write);
this.CertificateReferencesProperty = this.CreatePropertyAccessor(
CertificateReference.ConvertFromProtocolCollection(protocolObject.CertificateReferences),
"CertificateReferences",
BindingAccess.Read | BindingAccess.Write);
this.CloudServiceConfigurationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.CloudServiceConfiguration, o => new CloudServiceConfiguration(o)),
"CloudServiceConfiguration",
BindingAccess.Read | BindingAccess.Write);
this.DisplayNameProperty = this.CreatePropertyAccessor(
protocolObject.DisplayName,
"DisplayName",
BindingAccess.Read | BindingAccess.Write);
this.InterComputeNodeCommunicationEnabledProperty = this.CreatePropertyAccessor(
protocolObject.EnableInterNodeCommunication,
"InterComputeNodeCommunicationEnabled",
BindingAccess.Read);
this.MaxTasksPerComputeNodeProperty = this.CreatePropertyAccessor(
protocolObject.MaxTasksPerNode,
"MaxTasksPerComputeNode",
BindingAccess.Read | BindingAccess.Write);
this.MetadataProperty = this.CreatePropertyAccessor(
MetadataItem.ConvertFromProtocolCollection(protocolObject.Metadata),
"Metadata",
BindingAccess.Read | BindingAccess.Write);
this.NetworkConfigurationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.NetworkConfiguration, o => new NetworkConfiguration(o).Freeze()),
"NetworkConfiguration",
BindingAccess.Read);
this.ResizeTimeoutProperty = this.CreatePropertyAccessor(
protocolObject.ResizeTimeout,
"ResizeTimeout",
BindingAccess.Read | BindingAccess.Write);
this.StartTaskProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.StartTask, o => new StartTask(o)),
"StartTask",
BindingAccess.Read | BindingAccess.Write);
this.TargetDedicatedComputeNodesProperty = this.CreatePropertyAccessor(
protocolObject.TargetDedicatedNodes,
"TargetDedicatedComputeNodes",
BindingAccess.Read | BindingAccess.Write);
this.TargetLowPriorityComputeNodesProperty = this.CreatePropertyAccessor(
protocolObject.TargetLowPriorityNodes,
"TargetLowPriorityComputeNodes",
BindingAccess.Read | BindingAccess.Write);
this.TaskSchedulingPolicyProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.TaskSchedulingPolicy, o => new TaskSchedulingPolicy(o)),
"TaskSchedulingPolicy",
BindingAccess.Read | BindingAccess.Write);
this.UserAccountsProperty = this.CreatePropertyAccessor(
UserAccount.ConvertFromProtocolCollection(protocolObject.UserAccounts),
"UserAccounts",
BindingAccess.Read | BindingAccess.Write);
this.VirtualMachineConfigurationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.VirtualMachineConfiguration, o => new VirtualMachineConfiguration(o)),
"VirtualMachineConfiguration",
BindingAccess.Read | BindingAccess.Write);
this.VirtualMachineSizeProperty = this.CreatePropertyAccessor(
protocolObject.VmSize,
"VirtualMachineSize",
BindingAccess.Read | BindingAccess.Write);
}
}
private readonly PropertyContainer propertyContainer;
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="PoolSpecification"/> class.
/// </summary>
public PoolSpecification()
{
this.propertyContainer = new PropertyContainer();
}
internal PoolSpecification(Models.PoolSpecification protocolObject)
{
this.propertyContainer = new PropertyContainer(protocolObject);
}
#endregion Constructors
#region PoolSpecification
/// <summary>
/// Gets or sets the list of application licenses the Batch service will make available on each compute node in the
/// pool.
/// </summary>
/// <remarks>
/// The list of application licenses must be a subset of available Batch service application licenses.
/// </remarks>
public IList<string> ApplicationLicenses
{
get { return this.propertyContainer.ApplicationLicensesProperty.Value; }
set
{
this.propertyContainer.ApplicationLicensesProperty.Value = ConcurrentChangeTrackedList<string>.TransformEnumerableToConcurrentList(value);
}
}
/// <summary>
/// Gets or sets a list of application package references to be installed on each compute node in the pool.
/// </summary>
public IList<ApplicationPackageReference> ApplicationPackageReferences
{
get { return this.propertyContainer.ApplicationPackageReferencesProperty.Value; }
set
{
this.propertyContainer.ApplicationPackageReferencesProperty.Value = ConcurrentChangeTrackedModifiableList<ApplicationPackageReference>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets whether the pool size should automatically adjust over time.
/// </summary>
/// <remarks>
/// <para>If false, one of the <see cref="TargetDedicatedComputeNodes"/> or <see cref="TargetLowPriorityComputeNodes"/>
/// property is required.</para> <para>If true, the <see cref="AutoScaleFormula"/> property is required. The pool
/// automatically resizes according to the formula.</para> <para>The default value is false.</para>
/// </remarks>
public bool? AutoScaleEnabled
{
get { return this.propertyContainer.AutoScaleEnabledProperty.Value; }
set { this.propertyContainer.AutoScaleEnabledProperty.Value = value; }
}
/// <summary>
/// Gets or sets a time interval at which to automatically adjust the pool size according to the <see cref="AutoScaleFormula"/>.
/// </summary>
/// <remarks>
/// The default value is 15 minutes. The minimum allowed value is 5 minutes.
/// </remarks>
public TimeSpan? AutoScaleEvaluationInterval
{
get { return this.propertyContainer.AutoScaleEvaluationIntervalProperty.Value; }
set { this.propertyContainer.AutoScaleEvaluationIntervalProperty.Value = value; }
}
/// <summary>
/// Gets or sets a formula for the desired number of compute nodes in the pool.
/// </summary>
/// <remarks>
/// <para>For how to write autoscale formulas, see https://azure.microsoft.com/documentation/articles/batch-automatic-scaling/.
/// This property is required if <see cref="AutoScaleEnabled"/> is set to true. It must be null if AutoScaleEnabled
/// is false.</para><para>The formula is checked for validity before the pool is created. If the formula is not valid,
/// an exception is thrown when you try to commit the <see cref="PoolSpecification"/>.</para>
/// </remarks>
public string AutoScaleFormula
{
get { return this.propertyContainer.AutoScaleFormulaProperty.Value; }
set { this.propertyContainer.AutoScaleFormulaProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of certificates to be installed on each compute node in the pool.
/// </summary>
public IList<CertificateReference> CertificateReferences
{
get { return this.propertyContainer.CertificateReferencesProperty.Value; }
set
{
this.propertyContainer.CertificateReferencesProperty.Value = ConcurrentChangeTrackedModifiableList<CertificateReference>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the <see cref="CloudServiceConfiguration"/> for the pool.
/// </summary>
/// <remarks>
/// This property is mutually exclusive with <see cref="VirtualMachineConfiguration"/>.
/// </remarks>
public CloudServiceConfiguration CloudServiceConfiguration
{
get { return this.propertyContainer.CloudServiceConfigurationProperty.Value; }
set { this.propertyContainer.CloudServiceConfigurationProperty.Value = value; }
}
/// <summary>
/// Gets or sets the display name for the pool.
/// </summary>
public string DisplayName
{
get { return this.propertyContainer.DisplayNameProperty.Value; }
set { this.propertyContainer.DisplayNameProperty.Value = value; }
}
/// <summary>
/// Gets or sets whether the pool permits direct communication between its compute nodes.
/// </summary>
/// <remarks>
/// Enabling inter-node communication limits the maximum size of the pool due to deployment restrictions on the nodes
/// of the pool. This may result in the pool not reaching its desired size.
/// </remarks>
public bool? InterComputeNodeCommunicationEnabled
{
get { return this.propertyContainer.InterComputeNodeCommunicationEnabledProperty.Value; }
set { this.propertyContainer.InterComputeNodeCommunicationEnabledProperty.Value = value; }
}
/// <summary>
/// Gets or sets the maximum number of tasks that can run concurrently on a single compute node in the pool.
/// </summary>
/// <remarks>
/// The default value is 1. The maximum value of this setting depends on the size of the compute nodes in the pool
/// (the <see cref="VirtualMachineSize"/> property).
/// </remarks>
public int? MaxTasksPerComputeNode
{
get { return this.propertyContainer.MaxTasksPerComputeNodeProperty.Value; }
set { this.propertyContainer.MaxTasksPerComputeNodeProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of name-value pairs associated with the pool as metadata.
/// </summary>
public IList<MetadataItem> Metadata
{
get { return this.propertyContainer.MetadataProperty.Value; }
set
{
this.propertyContainer.MetadataProperty.Value = ConcurrentChangeTrackedModifiableList<MetadataItem>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the network configuration of the pool.
/// </summary>
public NetworkConfiguration NetworkConfiguration
{
get { return this.propertyContainer.NetworkConfigurationProperty.Value; }
set { this.propertyContainer.NetworkConfigurationProperty.Value = value; }
}
/// <summary>
/// Gets or sets the timeout for allocation of compute nodes to the pool.
/// </summary>
/// <remarks>
/// <para>This timeout applies only to manual scaling; it has no effect when <see cref="AutoScaleEnabled"/> is set
/// to true.</para><para>The default value is 15 minutes. The minimum value is 5 minutes.</para>
/// </remarks>
public TimeSpan? ResizeTimeout
{
get { return this.propertyContainer.ResizeTimeoutProperty.Value; }
set { this.propertyContainer.ResizeTimeoutProperty.Value = value; }
}
/// <summary>
/// Gets or sets a task to run on each compute node as it joins the pool. The task runs when the node is added to
/// the pool or when the node is restarted.
/// </summary>
public StartTask StartTask
{
get { return this.propertyContainer.StartTaskProperty.Value; }
set { this.propertyContainer.StartTaskProperty.Value = value; }
}
/// <summary>
/// Gets or sets the desired number of dedicated compute nodes in the pool.
/// </summary>
/// <remarks>
/// This setting cannot be specified if <see cref="AutoScaleEnabled"/> is set to true. At least one of this property
/// and <see cref="TargetLowPriorityComputeNodes"/> must be specified if <see cref="AutoScaleEnabled"/> is false.
/// If not specified, the default is 0.
/// </remarks>
public int? TargetDedicatedComputeNodes
{
get { return this.propertyContainer.TargetDedicatedComputeNodesProperty.Value; }
set { this.propertyContainer.TargetDedicatedComputeNodesProperty.Value = value; }
}
/// <summary>
/// Gets or sets the desired number of low-priority compute nodes in the pool.
/// </summary>
/// <remarks>
/// This setting cannot be specified if <see cref="AutoScaleEnabled"/> is set to true. At least one of <see cref="TargetDedicatedComputeNodes"/>
/// and this property must be specified if <see cref="AutoScaleEnabled"/> is false. If not specified, the default
/// is 0.
/// </remarks>
public int? TargetLowPriorityComputeNodes
{
get { return this.propertyContainer.TargetLowPriorityComputeNodesProperty.Value; }
set { this.propertyContainer.TargetLowPriorityComputeNodesProperty.Value = value; }
}
/// <summary>
/// Gets or sets how tasks are distributed among compute nodes in the pool.
/// </summary>
public TaskSchedulingPolicy TaskSchedulingPolicy
{
get { return this.propertyContainer.TaskSchedulingPolicyProperty.Value; }
set { this.propertyContainer.TaskSchedulingPolicyProperty.Value = value; }
}
/// <summary>
/// Gets or sets the list of user accounts to be created on each node in the pool.
/// </summary>
public IList<UserAccount> UserAccounts
{
get { return this.propertyContainer.UserAccountsProperty.Value; }
set
{
this.propertyContainer.UserAccountsProperty.Value = ConcurrentChangeTrackedModifiableList<UserAccount>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the <see cref="VirtualMachineConfiguration"/> of the pool.
/// </summary>
/// <remarks>
/// This property is mutually exclusive with <see cref="CloudServiceConfiguration"/>.
/// </remarks>
public VirtualMachineConfiguration VirtualMachineConfiguration
{
get { return this.propertyContainer.VirtualMachineConfigurationProperty.Value; }
set { this.propertyContainer.VirtualMachineConfigurationProperty.Value = value; }
}
/// <summary>
/// Gets or sets the size of the virtual machines in the pool. All virtual machines in a pool are the same size.
/// </summary>
/// <remarks>
/// <para>For information about available sizes of virtual machines for Cloud Services pools (pools created with
/// a <see cref="CloudServiceConfiguration"/>), see https://azure.microsoft.com/documentation/articles/cloud-services-sizes-specs/.
/// Batch supports all Cloud Services VM sizes except ExtraSmall.</para><para>For information about available VM
/// sizes for pools using images from the Virtual Machines Marketplace (pools created with a <see cref="VirtualMachineConfiguration"/>)
/// see https://azure.microsoft.com/documentation/articles/virtual-machines-linux-sizes/ or https://azure.microsoft.com/documentation/articles/virtual-machines-windows-sizes/.
/// Batch supports all Azure VM sizes except STANDARD_A0 and those with premium storage (for example STANDARD_GS,
/// STANDARD_DS, and STANDARD_DSV2 series).</para>
/// </remarks>
public string VirtualMachineSize
{
get { return this.propertyContainer.VirtualMachineSizeProperty.Value; }
set { this.propertyContainer.VirtualMachineSizeProperty.Value = value; }
}
#endregion // PoolSpecification
#region IPropertyMetadata
bool IModifiable.HasBeenModified
{
get { return this.propertyContainer.HasBeenModified; }
}
bool IReadOnly.IsReadOnly
{
get { return this.propertyContainer.IsReadOnly; }
set { this.propertyContainer.IsReadOnly = value; }
}
#endregion //IPropertyMetadata
#region Internal/private methods
/// <summary>
/// Return a protocol object of the requested type.
/// </summary>
/// <returns>The protocol object of the requested type.</returns>
Models.PoolSpecification ITransportObjectProvider<Models.PoolSpecification>.GetTransportObject()
{
Models.PoolSpecification result = new Models.PoolSpecification()
{
ApplicationLicenses = this.ApplicationLicenses,
ApplicationPackageReferences = UtilitiesInternal.ConvertToProtocolCollection(this.ApplicationPackageReferences),
EnableAutoScale = this.AutoScaleEnabled,
AutoScaleEvaluationInterval = this.AutoScaleEvaluationInterval,
AutoScaleFormula = this.AutoScaleFormula,
CertificateReferences = UtilitiesInternal.ConvertToProtocolCollection(this.CertificateReferences),
CloudServiceConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.CloudServiceConfiguration, (o) => o.GetTransportObject()),
DisplayName = this.DisplayName,
EnableInterNodeCommunication = this.InterComputeNodeCommunicationEnabled,
MaxTasksPerNode = this.MaxTasksPerComputeNode,
Metadata = UtilitiesInternal.ConvertToProtocolCollection(this.Metadata),
NetworkConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.NetworkConfiguration, (o) => o.GetTransportObject()),
ResizeTimeout = this.ResizeTimeout,
StartTask = UtilitiesInternal.CreateObjectWithNullCheck(this.StartTask, (o) => o.GetTransportObject()),
TargetDedicatedNodes = this.TargetDedicatedComputeNodes,
TargetLowPriorityNodes = this.TargetLowPriorityComputeNodes,
TaskSchedulingPolicy = UtilitiesInternal.CreateObjectWithNullCheck(this.TaskSchedulingPolicy, (o) => o.GetTransportObject()),
UserAccounts = UtilitiesInternal.ConvertToProtocolCollection(this.UserAccounts),
VirtualMachineConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.VirtualMachineConfiguration, (o) => o.GetTransportObject()),
VmSize = this.VirtualMachineSize,
};
return result;
}
#endregion // Internal/private methods
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
internal class A
{
public virtual int f0(int i)
{
return 1;
}
}
internal unsafe class B : A
{
public override int f0(int i)
{
return i;
}
public static int f1(ref int i)
{
return i;
}
public int f(int i)
{
return f1(ref i);
}
public static int F1downBy1ge(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 4; i >= 1; i -= 1)
{
Object c = new Object(); c = amount; sum += Convert.ToInt32(c);
}
return sum + i;
}
public static int F1downBy2ne(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 5; i != 1; i -= 2)
{
Object c = new Object(); c = amount; sum += Convert.ToInt32(c);
}
return sum + i;
}
public static int F1upBy1le(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 1; i <= 4; i += 1)
{
Object c = new Object(); c = amount; sum += Convert.ToInt32(c);
}
return sum + i;
}
public static int F1upBy1lt(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 1; i < 4; i += 1)
{
Object c = new Object(); c = amount; sum += Convert.ToInt32(c);
}
return sum + i;
}
public static int F1downBy1gt(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 5; i > 2; i -= 1)
{
Object c = new Object(); c = amount; sum += Convert.ToInt32(c);
}
return sum + i;
}
public static int F1upBy2le(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 1; i <= 5; i += 2)
{
Object c = new Object(); c = amount; sum += Convert.ToInt32(c);
}
return sum + i;
}
public static int F1downBy2ge(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 5; i >= 1; i -= 2)
{
Object c = new Object(); c = amount; sum += Convert.ToInt32(c);
}
return sum + i;
}
public static int F1upBy2lt(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 1; i < 5; i += 2)
{
Object c = new Object(); c = amount; sum += Convert.ToInt32(c);
}
return sum + i;
}
public static int F1downBy2gt(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 10; i > 2; i -= 2)
{
Object c = new Object(); c = amount; sum += Convert.ToInt32(c);
}
return sum + i;
}
public static int F1upBy1ne(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 1; i != 4; i += 1)
{
Object c = new Object(); c = amount; sum += Convert.ToInt32(c);
}
return sum + i;
}
public static int F1downBy1ne(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 5; i != 2; i -= 1)
{
Object c = new Object(); c = amount; sum += Convert.ToInt32(c);
}
return sum + i;
}
public static int F1upBy2ne(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 1; i != 5; i += 2)
{
Object c = new Object(); c = amount; sum += Convert.ToInt32(c);
}
return sum + i;
}
public static int F1upBy3neWrap(int amount)
{
short i;
int sum = 0;
B b = new B();
for (i = 1; i != 8; i += 3)
{
Object c = new Object(); c = amount; sum += Convert.ToInt32(c);
}
return sum + i;
}
public static int F1downBy3neWrap(int amount)
{
short i;
int sum = 0;
B b = new B();
for (i = 8; i != 1; i -= 3)
{
Object c = new Object(); c = amount; sum += Convert.ToInt32(c);
}
return sum + i;
}
public static int F2downBy1ge(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 4; i >= 1; i -= 1)
{
int* n = stackalloc int[1]; *n = amount; sum += amount;
}
return sum + i;
}
public static int F2downBy2ne(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 5; i != 1; i -= 2)
{
int* n = stackalloc int[1]; *n = amount; sum += amount;
}
return sum + i;
}
public static int F2upBy1le(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 1; i <= 4; i += 1)
{
int* n = stackalloc int[1]; *n = amount; sum += amount;
}
return sum + i;
}
public static int F2upBy1lt(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 1; i < 4; i += 1)
{
int* n = stackalloc int[1]; *n = amount; sum += amount;
}
return sum + i;
}
public static int F2downBy1gt(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 5; i > 2; i -= 1)
{
int* n = stackalloc int[1]; *n = amount; sum += amount;
}
return sum + i;
}
public static int F2upBy2le(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 1; i <= 5; i += 2)
{
int* n = stackalloc int[1]; *n = amount; sum += amount;
}
return sum + i;
}
public static int F2downBy2ge(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 5; i >= 1; i -= 2)
{
int* n = stackalloc int[1]; *n = amount; sum += amount;
}
return sum + i;
}
public static int F2upBy2lt(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 1; i < 5; i += 2)
{
int* n = stackalloc int[1]; *n = amount; sum += amount;
}
return sum + i;
}
public static int F2downBy2gt(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 10; i > 2; i -= 2)
{
int* n = stackalloc int[1]; *n = amount; sum += amount;
}
return sum + i;
}
public static int F2upBy1ne(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 1; i != 4; i += 1)
{
int* n = stackalloc int[1]; *n = amount; sum += amount;
}
return sum + i;
}
public static int F2downBy1ne(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 5; i != 2; i -= 1)
{
int* n = stackalloc int[1]; *n = amount; sum += amount;
}
return sum + i;
}
public static int F2upBy2ne(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 1; i != 5; i += 2)
{
int* n = stackalloc int[1]; *n = amount; sum += amount;
}
return sum + i;
}
public static int F2upBy3neWrap(int amount)
{
short i;
int sum = 0;
B b = new B();
for (i = 1; i != 8; i += 3)
{
int* n = stackalloc int[1]; *n = amount; sum += amount;
}
return sum + i;
}
public static int F2downBy3neWrap(int amount)
{
short i;
int sum = 0;
B b = new B();
for (i = 8; i != 1; i -= 3)
{
int* n = stackalloc int[1]; *n = amount; sum += amount;
}
return sum + i;
}
public static int F3downBy1ge(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 4; i >= 1; i -= 1)
{
int[] n = new int[i];
}
for (i = 4; i >= 1; i -= 1)
{
sum += amount;
}
return sum + i;
}
public static int F3downBy2ne(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 5; i != 1; i -= 2)
{
int[] n = new int[i];
}
for (i = 5; i != 1; i -= 2)
{
sum += amount;
}
return sum + i;
}
public static int F3upBy1le(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 1; i <= 4; i += 1)
{
int[] n = new int[i];
}
for (i = 1; i <= 4; i += 1)
{
sum += amount;
}
return sum + i;
}
public static int F3upBy1lt(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 1; i < 4; i += 1)
{
int[] n = new int[i];
}
for (i = 1; i < 4; i += 1)
{
sum += amount;
}
return sum + i;
}
public static int F3downBy1gt(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 5; i > 2; i -= 1)
{
int[] n = new int[i];
}
for (i = 5; i > 2; i -= 1)
{
sum += amount;
}
return sum + i;
}
public static int F3upBy2le(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 1; i <= 5; i += 2)
{
int[] n = new int[i];
}
for (i = 1; i <= 5; i += 2)
{
sum += amount;
}
return sum + i;
}
public static int F3downBy2ge(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 5; i >= 1; i -= 2)
{
int[] n = new int[i];
}
for (i = 5; i >= 1; i -= 2)
{
sum += amount;
}
return sum + i;
}
public static int F3upBy2lt(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 1; i < 5; i += 2)
{
int[] n = new int[i];
}
for (i = 1; i < 5; i += 2)
{
sum += amount;
}
return sum + i;
}
public static int F3downBy2gt(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 10; i > 2; i -= 2)
{
int[] n = new int[i];
}
for (i = 10; i > 2; i -= 2)
{
sum += amount;
}
return sum + i;
}
public static int F3upBy1ne(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 1; i != 4; i += 1)
{
int[] n = new int[i];
}
for (i = 1; i != 4; i += 1)
{
sum += amount;
}
return sum + i;
}
public static int F3downBy1ne(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 5; i != 2; i -= 1)
{
int[] n = new int[i];
}
for (i = 5; i != 2; i -= 1)
{
sum += amount;
}
return sum + i;
}
public static int F3upBy2ne(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 1; i != 5; i += 2)
{
int[] n = new int[i];
}
for (i = 1; i != 5; i += 2)
{
sum += amount;
}
return sum + i;
}
public static int F3upBy3neWrap(int amount)
{
short i;
int sum = 0;
B b = new B();
for (i = 1; i != 10; i += 3)
{
int[] n = new int[i];
}
for (i = 1; i != 8; i += 3)
{
sum += amount;
}
return sum + i;
}
public static int F3downBy3neWrap(int amount)
{
short i;
int sum = 0;
B b = new B();
for (i = 10; i != 1; i -= 3)
{
int[] n = new int[i];
}
for (i = 8; i != 1; i -= 3)
{
sum += amount;
}
return sum + i;
}
public static int F4downBy1ge(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 4; i >= 1; i -= 1)
{
TypedReference _ref = __makeref(sum); __refvalue(_ref, int) += amount;
}
return sum + i;
}
public static int F4downBy2ne(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 5; i != 1; i -= 2)
{
TypedReference _ref = __makeref(sum); __refvalue(_ref, int) += amount;
}
return sum + i;
}
public static int F4upBy1le(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 1; i <= 4; i += 1)
{
TypedReference _ref = __makeref(sum); __refvalue(_ref, int) += amount;
}
return sum + i;
}
public static int F4upBy1lt(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 1; i < 4; i += 1)
{
TypedReference _ref = __makeref(sum); __refvalue(_ref, int) += amount;
}
return sum + i;
}
public static int F4downBy1gt(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 5; i > 2; i -= 1)
{
TypedReference _ref = __makeref(sum); __refvalue(_ref, int) += amount;
}
return sum + i;
}
public static int F4upBy2le(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 1; i <= 5; i += 2)
{
TypedReference _ref = __makeref(sum); __refvalue(_ref, int) += amount;
}
return sum + i;
}
public static int F4downBy2ge(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 5; i >= 1; i -= 2)
{
TypedReference _ref = __makeref(sum); __refvalue(_ref, int) += amount;
}
return sum + i;
}
public static int F4upBy2lt(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 1; i < 5; i += 2)
{
TypedReference _ref = __makeref(sum); __refvalue(_ref, int) += amount;
}
return sum + i;
}
public static int F4downBy2gt(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 10; i > 2; i -= 2)
{
TypedReference _ref = __makeref(sum); __refvalue(_ref, int) += amount;
}
return sum + i;
}
public static int F4upBy1ne(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 1; i != 4; i += 1)
{
TypedReference _ref = __makeref(sum); __refvalue(_ref, int) += amount;
}
return sum + i;
}
public static int F4downBy1ne(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 5; i != 2; i -= 1)
{
TypedReference _ref = __makeref(sum); __refvalue(_ref, int) += amount;
}
return sum + i;
}
public static int F4upBy2ne(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 1; i != 5; i += 2)
{
TypedReference _ref = __makeref(sum); __refvalue(_ref, int) += amount;
}
return sum + i;
}
public static int F4upBy3neWrap(int amount)
{
short i;
int sum = 0;
B b = new B();
for (i = 1; i != 8; i += 3)
{
TypedReference _ref = __makeref(sum); __refvalue(_ref, int) += amount;
}
return sum + i;
}
public static int F4downBy3neWrap(int amount)
{
short i;
int sum = 0;
B b = new B();
for (i = 8; i != 1; i -= 3)
{
TypedReference _ref = __makeref(sum); __refvalue(_ref, int) += amount;
}
return sum + i;
}
public static int F5downBy1ge(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 4; i >= 1; i -= 1)
{
try { sum += amount; } catch { }
}
return sum + i;
}
public static int F5downBy2ne(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 5; i != 1; i -= 2)
{
try { sum += amount; } catch { }
}
return sum + i;
}
public static int F5upBy1le(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 1; i <= 4; i += 1)
{
try { sum += amount; } catch { }
}
return sum + i;
}
public static int F5upBy1lt(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 1; i < 4; i += 1)
{
try { sum += amount; } catch { }
}
return sum + i;
}
public static int F5downBy1gt(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 5; i > 2; i -= 1)
{
try { sum += amount; } catch { }
}
return sum + i;
}
public static int F5upBy2le(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 1; i <= 5; i += 2)
{
try { sum += amount; } catch { }
}
return sum + i;
}
public static int F5downBy2ge(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 5; i >= 1; i -= 2)
{
try { sum += amount; } catch { }
}
return sum + i;
}
public static int F5upBy2lt(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 1; i < 5; i += 2)
{
try { sum += amount; } catch { }
}
return sum + i;
}
public static int F5downBy2gt(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 10; i > 2; i -= 2)
{
try { sum += amount; } catch { }
}
return sum + i;
}
public static int F5upBy1ne(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 1; i != 4; i += 1)
{
try { sum += amount; } catch { }
}
return sum + i;
}
public static int F5downBy1ne(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 5; i != 2; i -= 1)
{
try { sum += amount; } catch { }
}
return sum + i;
}
public static int F5upBy2ne(int amount)
{
int i;
int sum = 0;
B b = new B();
for (i = 1; i != 5; i += 2)
{
try { sum += amount; } catch { }
}
return sum + i;
}
public static int F5upBy3neWrap(int amount)
{
short i;
int sum = 0;
B b = new B();
for (i = 1; i != 8; i += 3)
{
try { sum += amount; } catch { }
}
return sum + i;
}
public static int F5downBy3neWrap(int amount)
{
short i;
int sum = 0;
B b = new B();
for (i = 8; i != 1; i -= 3)
{
try { sum += amount; } catch { }
}
return sum + i;
}
public static int Main(String[] args)
{
bool failed = false;
if (F1upBy1le(10) != 45)
{
Console.WriteLine("F1upBy1le failed");
failed = true;
}
if (F1downBy1ge(10) != 40)
{
Console.WriteLine("F1downBy1ge failed");
failed = true;
}
if (F1upBy1lt(10) != 34)
{
Console.WriteLine("F1upBy1lt failed");
failed = true;
}
if (F1downBy1gt(10) != 32)
{
Console.WriteLine("F1downBy1gt failed");
failed = true;
}
if (F1upBy2le(10) != 37)
{
Console.WriteLine("F1upBy2le failed");
failed = true;
}
if (F1downBy2ge(10) != 29)
{
Console.WriteLine("F1downBy2ge failed");
failed = true;
}
if (F1upBy2lt(10) != 25)
{
Console.WriteLine("F1upBy2lt failed");
failed = true;
}
if (F1downBy2gt(10) != 42)
{
Console.WriteLine("F1downBy2gt failed");
failed = true;
}
if (F1upBy1ne(10) != 34)
{
Console.WriteLine("F1upBy1ne failed");
failed = true;
}
if (F1downBy1ne(10) != 32)
{
Console.WriteLine("F1downBy1ne failed");
failed = true;
}
if (F1upBy2ne(10) != 25)
{
Console.WriteLine("F1upBy2ne failed");
failed = true;
}
if (F1downBy2ne(10) != 21)
{
Console.WriteLine("F1downBy2ne failed");
failed = true;
}
if (F1upBy3neWrap(1) != 43701)
{
Console.WriteLine("F1upBy3neWrap failed");
failed = true;
}
if (F1downBy3neWrap(1) != 43694)
{
Console.WriteLine("F1downBy3neWrap failed");
failed = true;
}
if (F2upBy1le(10) != 45)
{
Console.WriteLine("F2upBy1le failed");
failed = true;
}
if (F2downBy1ge(10) != 40)
{
Console.WriteLine("F2downBy1ge failed");
failed = true;
}
if (F2upBy1lt(10) != 34)
{
Console.WriteLine("F2upBy1lt failed");
failed = true;
}
if (F2downBy1gt(10) != 32)
{
Console.WriteLine("F2downBy1gt failed");
failed = true;
}
if (F2upBy2le(10) != 37)
{
Console.WriteLine("F2upBy2le failed");
failed = true;
}
if (F2downBy2ge(10) != 29)
{
Console.WriteLine("F2downBy2ge failed");
failed = true;
}
if (F2upBy2lt(10) != 25)
{
Console.WriteLine("F2upBy2lt failed");
failed = true;
}
if (F2downBy2gt(10) != 42)
{
Console.WriteLine("F2downBy2gt failed");
failed = true;
}
if (F2upBy1ne(10) != 34)
{
Console.WriteLine("F2upBy1ne failed");
failed = true;
}
if (F2downBy1ne(10) != 32)
{
Console.WriteLine("F2downBy1ne failed");
failed = true;
}
if (F2upBy2ne(10) != 25)
{
Console.WriteLine("F2upBy2ne failed");
failed = true;
}
if (F2downBy2ne(10) != 21)
{
Console.WriteLine("F2downBy2ne failed");
failed = true;
}
if (F2upBy3neWrap(1) != 43701)
{
Console.WriteLine("F2upBy3neWrap failed");
failed = true;
}
if (F2downBy3neWrap(1) != 43694)
{
Console.WriteLine("F2downBy3neWrap failed");
failed = true;
}
if (F3upBy1le(10) != 45)
{
Console.WriteLine("F3upBy1le failed");
failed = true;
}
if (F3downBy1ge(10) != 40)
{
Console.WriteLine("F3downBy1ge failed");
failed = true;
}
if (F3upBy1lt(10) != 34)
{
Console.WriteLine("F3upBy1lt failed");
failed = true;
}
if (F3downBy1gt(10) != 32)
{
Console.WriteLine("F3downBy1gt failed");
failed = true;
}
if (F3upBy2le(10) != 37)
{
Console.WriteLine("F3upBy2le failed");
failed = true;
}
if (F3downBy2ge(10) != 29)
{
Console.WriteLine("F3downBy2ge failed");
failed = true;
}
if (F3upBy2lt(10) != 25)
{
Console.WriteLine("F3upBy2lt failed");
failed = true;
}
if (F3downBy2gt(10) != 42)
{
Console.WriteLine("F3downBy2gt failed");
failed = true;
}
if (F3upBy1ne(10) != 34)
{
Console.WriteLine("F3upBy1ne failed");
failed = true;
}
if (F3downBy1ne(10) != 32)
{
Console.WriteLine("F3downBy1ne failed");
failed = true;
}
if (F3upBy2ne(10) != 25)
{
Console.WriteLine("F3upBy2ne failed");
failed = true;
}
if (F3downBy2ne(10) != 21)
{
Console.WriteLine("F3downBy2ne failed");
failed = true;
}
if (F3upBy3neWrap(1) != 43701)
{
Console.WriteLine("F3upBy3neWrap failed");
failed = true;
}
if (F3downBy3neWrap(1) != 43694)
{
Console.WriteLine("F3downBy3neWrap failed");
failed = true;
}
if (F4upBy1le(10) != 45)
{
Console.WriteLine("F4upBy1le failed");
failed = true;
}
if (F4downBy1ge(10) != 40)
{
Console.WriteLine("F4downBy1ge failed");
failed = true;
}
if (F4upBy1lt(10) != 34)
{
Console.WriteLine("F4upBy1lt failed");
failed = true;
}
if (F4downBy1gt(10) != 32)
{
Console.WriteLine("F4downBy1gt failed");
failed = true;
}
if (F4upBy2le(10) != 37)
{
Console.WriteLine("F4upBy2le failed");
failed = true;
}
if (F4downBy2ge(10) != 29)
{
Console.WriteLine("F4downBy2ge failed");
failed = true;
}
if (F4upBy2lt(10) != 25)
{
Console.WriteLine("F4upBy2lt failed");
failed = true;
}
if (F4downBy2gt(10) != 42)
{
Console.WriteLine("F4downBy2gt failed");
failed = true;
}
if (F4upBy1ne(10) != 34)
{
Console.WriteLine("F4upBy1ne failed");
failed = true;
}
if (F4downBy1ne(10) != 32)
{
Console.WriteLine("F4downBy1ne failed");
failed = true;
}
if (F4upBy2ne(10) != 25)
{
Console.WriteLine("F4upBy2ne failed");
failed = true;
}
if (F4downBy2ne(10) != 21)
{
Console.WriteLine("F4downBy2ne failed");
failed = true;
}
if (F4upBy3neWrap(1) != 43701)
{
Console.WriteLine("F4upBy3neWrap failed");
failed = true;
}
if (F4downBy3neWrap(1) != 43694)
{
Console.WriteLine("F4downBy3neWrap failed");
failed = true;
}
if (F5upBy1le(10) != 45)
{
Console.WriteLine("F5upBy1le failed");
failed = true;
}
if (F5downBy1ge(10) != 40)
{
Console.WriteLine("F5downBy1ge failed");
failed = true;
}
if (F5upBy1lt(10) != 34)
{
Console.WriteLine("F5upBy1lt failed");
failed = true;
}
if (F5downBy1gt(10) != 32)
{
Console.WriteLine("F5downBy1gt failed");
failed = true;
}
if (F5upBy2le(10) != 37)
{
Console.WriteLine("F5upBy2le failed");
failed = true;
}
if (F5downBy2ge(10) != 29)
{
Console.WriteLine("F5downBy2ge failed");
failed = true;
}
if (F5upBy2lt(10) != 25)
{
Console.WriteLine("F5upBy2lt failed");
failed = true;
}
if (F5downBy2gt(10) != 42)
{
Console.WriteLine("F5downBy2gt failed");
failed = true;
}
if (F5upBy1ne(10) != 34)
{
Console.WriteLine("F5upBy1ne failed");
failed = true;
}
if (F5downBy1ne(10) != 32)
{
Console.WriteLine("F5downBy1ne failed");
failed = true;
}
if (F5upBy2ne(10) != 25)
{
Console.WriteLine("F5upBy2ne failed");
failed = true;
}
if (F5downBy2ne(10) != 21)
{
Console.WriteLine("F5downBy2ne failed");
failed = true;
}
if (F5upBy3neWrap(1) != 43701)
{
Console.WriteLine("F5upBy3neWrap failed");
failed = true;
}
if (F5downBy3neWrap(1) != 43694)
{
Console.WriteLine("F5downBy3neWrap failed");
failed = true;
}
if (!failed)
{
Console.WriteLine();
Console.WriteLine("Passed");
return 100;
}
else
{
Console.WriteLine();
Console.WriteLine("Failed");
return 1;
}
}
}
| |
/*
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.KnowledgeArticles
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using Adxstudio.Xrm.Cms;
using Adxstudio.Xrm.Core.Flighting;
using Adxstudio.Xrm.Feedback;
using Adxstudio.Xrm.Resources;
using Adxstudio.Xrm.Services.Query;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Messages;
using Microsoft.Xrm.Client.Security;
using Microsoft.Xrm.Portal.Configuration;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using Adxstudio.Xrm.Text;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Portal.Web;
using Microsoft.Xrm.Sdk.Query;
using Adxstudio.Xrm.Metadata;
using Adxstudio.Xrm.Notes;
using Adxstudio.Xrm.Services;
using Adxstudio.Xrm.Web;
using Adxstudio.Xrm.Web.UI.WebForms;
/// <summary>
/// Provides data operations for a single knowledge article, as represented by a KnowledgeArticle entity.
/// </summary>
public class KnowledgeArticleDataAdapter : IKnowledgeArticleDataAdapter, ICommentDataAdapter
{
private bool? _hasCommentModerationPermission;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="article">The article to get and set data for.</param>
/// <param name="code">Article language code</param>
/// <param name="portalName">The configured name of the portal to get and set data for.</param>
public KnowledgeArticleDataAdapter(EntityReference article, string code, string portalName = null) : this(article, code, new PortalConfigurationDataAdapterDependencies(portalName)) { }
/// <summary>
/// Constructor.
/// </summary>
/// <param name="article">The article to get and set data for.</param>
/// <param name="code">Article language code</param>
/// <param name="portalName">The configured name of the portal to get and set data for.</param>
public KnowledgeArticleDataAdapter(Entity article, string code = "", string portalName = null) : this(article.ToEntityReference(), code, portalName) { }
/// <summary>
/// Constructor.
/// </summary>
/// <param name="article">Knowledge Article Entity Reference</param>
/// <param name="code">Article language code</param>
/// <param name="dependencies">Data Adapter Dependencies</param>
public KnowledgeArticleDataAdapter(EntityReference article, string code, IDataAdapterDependencies dependencies)
{
article.ThrowOnNull("article");
article.AssertLogicalName("knowledgearticle");
dependencies.ThrowOnNull("dependencies");
this.KnowledgeArticle = article;
this.Dependencies = dependencies;
this.LanguageCode = code;
}
public virtual IKnowledgeArticle Select()
{
var article = GetArticleEntity(Dependencies.GetServiceContext());
return article == null
? null
: new KnowledgeArticleFactory(Dependencies).Create(new[] { article }).FirstOrDefault();
}
public IEnumerable<IRelatedArticle> SelectRelatedArticles(IEnumerable<EntityCollection> entityCollections)
{
var articleCollection = entityCollections.FirstOrDefault(e => e.EntityName.Equals("knowledgearticle"));
return this.ToRelatedArticles(articleCollection);
}
public virtual IEnumerable<IRelatedProduct> SelectRelatedProducts(IEnumerable<EntityCollection> entityCollections)
{
var productCollection = entityCollections.FirstOrDefault(e => e.EntityName.Equals("product"));
return this.ToRelatedProducts(productCollection);
}
public IEnumerable<EntityCollection> GetRelatedProductsAndArticles(IKnowledgeArticle article)
{
var serviceContext = this.Dependencies.GetServiceContext();
Fetch fetchRelatedProducts = null;
Fetch fetchRelatedArticles = null;
var articleConnectionRole = GetArticleConnectionRole(serviceContext, this.KnowledgeArticleConnectionRoleId);
var relatedProductConnectionRole = GetArticleConnectionRole(serviceContext, this.RelatedProductConnectionRoleId);
if (articleConnectionRole != null && relatedProductConnectionRole != null)
{
var relatedProductsFetchXml = string.Format(RelatedProductsFetchXmlFormat,
article.Id,
relatedProductConnectionRole.Id,
articleConnectionRole.Id);
fetchRelatedProducts = Fetch.Parse(relatedProductsFetchXml);
}
var languageCondition = string.Empty;
if (!string.IsNullOrWhiteSpace(this.LanguageCode))
{
languageCondition = "<condition entityname='language_locale' attribute='code' operator='eq' value = '" + this.LanguageCode + "' />";
}
var primaryArticleConnectionRole = GetArticleConnectionRole(serviceContext, this.PrimaryArticleConnectionRoleId);
var relatedArticleConnectionRole = GetArticleConnectionRole(serviceContext, this.RelatedArticleConnectionRoleId);
if (primaryArticleConnectionRole != null && relatedArticleConnectionRole != null)
{
var id = article.RootArticle == null ? article.Id : article.RootArticle.Id;
var relatedArticlesFetchXml = string.Format(RelatedArticlesFetchXmlFormat,
id,
primaryArticleConnectionRole.Id,
relatedArticleConnectionRole.Id,
languageCondition);
fetchRelatedArticles = Fetch.Parse(relatedArticlesFetchXml);
}
var products = new EntityCollection();
if (fetchRelatedProducts != null)
{
products = serviceContext.RetrieveMultiple(fetchRelatedProducts, RequestFlag.AllowStaleData);
}
var articles = new EntityCollection();
if (fetchRelatedArticles != null)
{
articles = serviceContext.RetrieveMultiple(fetchRelatedArticles, RequestFlag.AllowStaleData);
}
return new List<EntityCollection> { products, articles }.AsEnumerable();
}
private IEnumerable<IRelatedProduct> ToRelatedProducts(EntityCollection relatedProductsCollection)
{
var serviceContext = this.Dependencies.GetServiceContext();
var urlProvider = this.Dependencies.GetUrlProvider();
var relatedProducts = Enumerable.Empty<RelatedProduct>();
if (relatedProductsCollection != null && relatedProductsCollection.Entities.Count > 0)
{
int lcid = 0;
this.ProductLocalizationShouldOccur(out lcid);
relatedProducts =
relatedProductsCollection.Entities
.Select(e => new { Id = e.Id, Name = e.GetAttributeValue<string>("name"), Url = urlProvider.GetUrl(serviceContext, e) })
.Where(e => !(string.IsNullOrEmpty(e.Name)))
.Select(e => new RelatedProduct(e.Id, this.LocalizeProductLabels(serviceContext, lcid, e.Id, e.Name), e.Url))
.OrderBy(e => e.Name)
.AsParallel();
}
return relatedProducts;
}
private IEnumerable<IRelatedArticle> ToRelatedArticles(EntityCollection relatedArticlesCollection)
{
var serviceContext = this.Dependencies.GetServiceContext();
var securityProvider = this.Dependencies.GetSecurityProvider();
var urlProvider = this.Dependencies.GetUrlProvider();
var relatedArticles = Enumerable.Empty<RelatedArticle>();
if (relatedArticlesCollection != null && relatedArticlesCollection.Entities.Count > 0)
{
int lcid = 0;
this.ProductLocalizationShouldOccur(out lcid);
relatedArticles =
relatedArticlesCollection.Entities.Where(e => securityProvider.TryAssert(serviceContext, e, CrmEntityRight.Read))
.Select(e => new { Title = e.GetAttributeValue<string>("title"), Url = urlProvider.GetUrl(serviceContext, e) })
.Where(e => !(string.IsNullOrEmpty(e.Title) || string.IsNullOrEmpty(e.Url)))
.Select(e => new RelatedArticle(e.Title, e.Url))
.OrderBy(e => e.Title);
}
return relatedArticles;
}
public virtual IEnumerable<IRelatedNote> SelectRelatedNotes(IKnowledgeArticle article)
{
if (!IsAnnotationSearchEnabled)
{
return null;
}
var annotationDataAdapter = new AnnotationDataAdapter(this.Dependencies);
var webPrefix = GetNotesFilterPrefix;
var relatedNotes = annotationDataAdapter.GetDocuments(article.EntityReference, webPrefix: webPrefix);
return relatedNotes.Select(a => new RelatedNote(a.NoteText == null ? string.Empty : a.NoteText.ToString().Substring(webPrefix.Length), a.FileAttachment.FileName, a.FileAttachment.Url));
}
/// <summary>
/// Increments the View Count for the Knowledge Article by 1
/// </summary>
public void IncrementKnowledgeArticleViewCount(Uri urlReferrer)
{
if (!CaptureViewCountEnabled) return;
if ((CaptureKnowledgeArticleReferrer) && (ReferrerEnabledCrmVersion))
{
var keyValueReferrerAndHost = GetReferrerTypeAndHost(urlReferrer);
IncrementKnowledgeArticleReferrerViewCount((int)keyValueReferrerAndHost.Key, keyValueReferrerAndHost.Value);
}
else
{
var request = new IncrementKnowledgeArticleViewCountRequest()
{
Source = KnowledgeArticle,
Count = 1,
Location = KnowledgeArticleViewCountWebLocation,
ViewDate = DateTime.Now
};
var portalContext = PortalCrmConfigurationManager.CreatePortalContext();
portalContext.ServiceContext.Execute(request);
}
}
#region Private Methods
/// <summary>
/// Checks whether Product Localization should occur
/// </summary>
/// <param name="lcid">Lcid variable to instantiate for non-base requests</param>
/// <returns>True, if localization of Product should occur</returns>
private bool ProductLocalizationShouldOccur(out int lcid)
{
lcid = 0;
var contextLanguageInfo = HttpContext.Current.GetContextLanguageInfo();
if (!contextLanguageInfo.IsCrmMultiLanguageEnabled)
{
return false;
}
// If the user's ContextLanguage is not different than the base language, do not localize since the localization would return same Title's anyways.
var context = this.Dependencies.GetRequestContext().HttpContext;
var organizationBaseLanguageCode = context.GetPortalSolutionsDetails().OrganizationBaseLanguageCode;
if (contextLanguageInfo.ContextLanguage.CrmLcid == organizationBaseLanguageCode)
{
return false;
}
lcid = contextLanguageInfo.ContextLanguage.CrmLcid;
return true;
}
/// <summary>
/// Replaces Category labels with localized labels where available using specified <paramref name="languageCode"/>
/// </summary>
/// <param name="context">Organization Service Context</param>
/// <param name="languageCode">LCID for label request</param>
/// <param name="productId">Product ID</param>
/// <param name="fallbackProductLabel">base language Product label to fallback to</param>
private string LocalizeProductLabels(OrganizationServiceContext context, int languageCode, Guid productId, string fallbackProductLabel)
{
// If localization shouldn't occur, default to fallback label
if (languageCode == 0)
{
return fallbackProductLabel;
}
var localizedLabel = context.RetrieveLocalizedLabel(new EntityReference("product", productId), "name", languageCode);
if (!string.IsNullOrWhiteSpace(localizedLabel))
{
return localizedLabel;
}
return fallbackProductLabel;
}
private KeyValuePair<ReferrerType, string> GetReferrerTypeAndHost(Uri urlReferrer)
{
var portalHostName = string.Empty;
var url = GetPortalUrl("Search");
if (urlReferrer == null)
{
if (url != null)
{
portalHostName = url.Host;
}
return new KeyValuePair<ReferrerType, string>(ReferrerType.DirectLink, portalHostName);
}
// GetPortalUrl(...) will return URL without language code prefix, so in order to make comparison work, need to (if necessary) strip out
// language code prefix from urlReferrer as well.
string absoluteUri;
var contextLanguageInfo = HttpContext.Current.GetContextLanguageInfo();
if (contextLanguageInfo.IsCrmMultiLanguageEnabled)
{
absoluteUri = contextLanguageInfo.StripLanguageCodeFromAbsolutePath(urlReferrer.PathAndQuery);
}
else
{
absoluteUri = urlReferrer.AbsoluteUri;
}
if (url != null)
{
portalHostName = url.Host;
if (absoluteUri.Contains(url.Uri.ToString()))
{
return new KeyValuePair<ReferrerType, string>(ReferrerType.PortalSearch, url.Host);
}
}
url = GetPortalUrl("Create Case");
if (url != null)
{
portalHostName = url.Host;
if (absoluteUri.Contains(url.Uri.ToString()))
{
return new KeyValuePair<ReferrerType, string>(ReferrerType.PortalCaseDeflectionSearch, url.Host);
}
}
if (!string.IsNullOrEmpty(portalHostName))
{
if (absoluteUri.Contains(portalHostName))
{
return new KeyValuePair<ReferrerType, string>(ReferrerType.Browse, portalHostName);
}
}
var regEx = new Regex(ExternalSearchEngineString, RegexOptions.IgnoreCase);
var isSearch = regEx.Match(absoluteUri).Success;
return isSearch ? new KeyValuePair<ReferrerType, string>(ReferrerType.ExternalSearchEngine, portalHostName) : new KeyValuePair<ReferrerType, string>(ReferrerType.ExternalWebsite, portalHostName);
}
private static UrlBuilder GetPortalUrl(string siteMarkerName)
{
var portalContext = PortalCrmConfigurationManager.CreatePortalContext();
var page = portalContext.ServiceContext.GetPageBySiteMarkerName(portalContext.Website, siteMarkerName);
return page == null ? null : new UrlBuilder(portalContext.ServiceContext.GetUrl(page));
}
private bool ReferrerEnabledCrmVersion
{
get
{
var portalDetails = HttpContext.Current.GetPortalSolutionsDetails();
var enabledVersion = new Version("8.2.0.0");
return portalDetails != null && portalDetails.CrmVersion.CompareTo(enabledVersion) >= 0;
}
}
/// <summary>
/// Checks the Article/CaptureViewCount Site Setting to determine if capturing view count is enabled
/// </summary>
private bool CaptureViewCountEnabled
{
get
{
var portalContext = PortalCrmConfigurationManager.CreatePortalContext();
var captureViewCountEnabledString = portalContext.ServiceContext.GetSiteSettingValueByName(portalContext.Website, "KnowledgeManagement/Article/CaptureViewCount");
//By default, if the site setting isn't configured - don't capture view count
bool captureViewCountEnabled = false;
bool.TryParse(captureViewCountEnabledString, out captureViewCountEnabled);
return captureViewCountEnabled;
}
}
private bool CaptureKnowledgeArticleReferrer
{
get
{
var portalContext = PortalCrmConfigurationManager.CreatePortalContext();
var captureKnowledgeArticleReferrerString = portalContext.ServiceContext.GetSiteSettingValueByName(portalContext.Website, "KnowledgeManagement/Analytics/CaptureKnowledgeArticleReferrer");
bool captureKnowledgeArticleReferrerEnabled = false;
bool.TryParse(captureKnowledgeArticleReferrerString, out captureKnowledgeArticleReferrerEnabled);
return captureKnowledgeArticleReferrerEnabled;
}
}
private bool IsAnnotationSearchEnabled
{
get
{
var adapter = new SettingDataAdapter(new PortalConfigurationDataAdapterDependencies(), HttpContext.Current.GetWebsite());
return adapter.GetBooleanValue("KnowledgeManagement/DisplayNotes") ?? false;
}
}
private string GetNotesFilterPrefix
{
get
{
return HttpContext.Current.GetSiteSetting("KnowledgeManagement/NotesFilter") ?? string.Empty;
}
}
private string ExternalSearchEngineString
{
get
{
var portalContext = PortalCrmConfigurationManager.CreatePortalContext();
return portalContext.ServiceContext.GetSiteSettingValueByName(portalContext.Website, "KnowledgeManagement/Analytics/ExternalSearchEngines");
}
}
private Entity GetArticleEntity(OrganizationServiceContext serviceContext)
{
var article = serviceContext.RetrieveSingle("knowledgearticle",
FetchAttribute.All,
new Condition("knowledgearticleid", ConditionOperator.Equal, KnowledgeArticle.Id),
false,
false,
RequestFlag.AllowStaleData);
if (article == null)
{
throw new InvalidOperationException(
ResourceManager.GetString("Knowledge_Article_NotFound").FormatWith(KnowledgeArticle.Id));
}
return article;
}
private static Entity GetArticleConnectionRole(OrganizationServiceContext serviceContext, Guid connectionRoleId)
{
var connectionRole = serviceContext.RetrieveSingle("connectionrole",
FetchAttribute.All,
new Condition("connectionroleid", ConditionOperator.Equal, connectionRoleId));
return connectionRole;
}
#endregion Private methods
public IDictionary<string, object> GetCommentAttributes(
string content,
string authorName = null,
string authorEmail = null,
string authorUrl = null,
HttpContext context = null)
{
var article = Select();
if (article == null)
{
throw new InvalidOperationException(
ResourceManager.GetString("Knowledge_Article_With_EntityID_Load_Exception").FormatWith(KnowledgeArticle.Id));
}
var postedOn = DateTime.UtcNow;
var attributes = new Dictionary<string, object>
{
{ "regardingobjectid", KnowledgeArticle },
{ "createdon", postedOn },
{ "title", StringHelper.GetCommentTitleFromContent(content) },
{ "adx_createdbycontact", authorName },
{ "adx_contactemail", authorEmail },
{ "adx_approved", article.CommentPolicy == CommentPolicy.Open || article.CommentPolicy == CommentPolicy.OpenToAuthenticatedUsers },
{ "comments", content },
};
var portalUser = Dependencies.GetPortalUser();
if (portalUser != null && portalUser.LogicalName == "contact")
{
attributes[FeedbackMetadataAttributes.UserIdAttributeName] = portalUser;
}
else if (context != null && context.Profile != null)
{
attributes[FeedbackMetadataAttributes.VisitorAttributeName] = context.Profile.UserName;
}
return attributes;
}
/// <summary>
/// Returns comments that have been posted for the article this adapter applies to.
/// </summary>
public virtual IEnumerable<IComment> SelectComments()
{
return SelectComments(0);
}
/// <summary>
/// Returns comments that have been posted for the article this adapter applies to.
/// </summary>
/// <param name="startRowIndex">The row index of the first comment to be returned.</param>
/// <param name="maximumRows">The maximum number of comments to return.</param>
public virtual IEnumerable<IComment> SelectComments(int startRowIndex, int maximumRows = -1)
{
var comments = new List<Comment>();
if (!FeatureCheckHelper.IsFeatureEnabled(FeatureNames.Feedback) || maximumRows == 0)
{
return comments;
}
var query =
Cms.OrganizationServiceContextExtensions.SelectCommentsByPage(
Cms.OrganizationServiceContextExtensions.GetPageInfo(startRowIndex, maximumRows), KnowledgeArticle.Id,
true, ChronologicalComments);
var commentsEntitiesResult = Dependencies.GetServiceContext().RetrieveMultiple(query);
comments.AddRange(
commentsEntitiesResult.Entities.Select(
commentEntity =>
new Comment(commentEntity,
new Lazy<ApplicationPath>(() => Dependencies.GetEditPath(commentEntity.ToEntityReference()), LazyThreadSafetyMode.None),
new Lazy<ApplicationPath>(() => Dependencies.GetDeletePath(commentEntity.ToEntityReference()), LazyThreadSafetyMode.None),
new Lazy<bool>(() => true, LazyThreadSafetyMode.None))));
return comments;
}
/// <summary>
/// Returns the number of comments that have been posted for the article this adapter applies to.
/// </summary>
public virtual int SelectCommentCount()
{
if (!FeatureCheckHelper.IsFeatureEnabled(FeatureNames.Feedback))
{
return 0;
}
var serviceContext = Dependencies.GetServiceContext();
var includeUnapprovedComments = TryAssertCommentModerationPermission(serviceContext);
return serviceContext.FetchCount("feedback", "feedbackid", addCondition =>
{
addCondition("regardingobjectid", "eq", KnowledgeArticle.Id.ToString());
addCondition("statecode", "eq", "0");
if (!includeUnapprovedComments)
{
addCondition("adx_approved", "eq", "true");
}
},
null,
addBinaryFilterCondition =>
{
addBinaryFilterCondition("comments", "not-null");
});
}
protected virtual bool TryAssertCommentModerationPermission(OrganizationServiceContext serviceContext)
{
if (_hasCommentModerationPermission.HasValue)
{
return _hasCommentModerationPermission.Value;
}
var security = Dependencies.GetSecurityProvider();
_hasCommentModerationPermission = security.TryAssert(serviceContext, GetKnowledgeArticleEntity(serviceContext), CrmEntityRight.Change);
return _hasCommentModerationPermission.Value;
}
private Entity GetKnowledgeArticleEntity(OrganizationServiceContext serviceContext)
{
var article = serviceContext.RetrieveSingle("knowledgearticle",
FetchAttribute.All,
new Condition("knowledgearticleid", ConditionOperator.Equal, KnowledgeArticle.Id),
false,
false,
RequestFlag.AllowStaleData);
if (article == null)
{
throw new InvalidOperationException(string.Format("Can't find {0} having ID {1}.", "knowledgearticle", KnowledgeArticle.Id));
}
return article;
}
public string GetCommentLogicalName()
{
return "feedback";
}
public string GetCommentContentAttributeName()
{
return "comments";
}
public ICommentPolicyReader GetCommentPolicyReader()
{
throw new NotImplementedException();
}
/// <summary>
/// Post a comment for the knowledge article this adapter applies to.
/// </summary>
/// <param name="content">The comment copy.</param>
/// <param name="authorName">The name of the author for this comment (ignored if user is authenticated).</param>
/// <param name="authorEmail">The email of the author for this comment (ignored if user is authenticated).</param>
public virtual void CreateComment(string content, string authorName = null, string authorEmail = null)
{
content.ThrowOnNullOrWhitespace("content");
var title = StringHelper.GetCommentTitleFromContent(content);
title.ThrowOnNullOrWhitespace("title");
var author = Dependencies.GetPortalUser();
if (author == null)
{
authorName.ThrowOnNullOrWhitespace("authorName",
ResourceManager.GetString("ErrorInCreatingKnowledgeArticleComment_WithNullOrWhitespace"));
authorEmail.ThrowOnNullOrWhitespace("authorEmail",
ResourceManager.GetString("ErrorInCreatingKnowledgeArticleComment_WithNullOrWhitespace"));
}
var article = Select();
var feedback = new Entity("feedback");
feedback["title"] = title;
feedback["comments"] = content;
feedback["regardingobjectid"] = article.EntityReference;
feedback["adx_createdbycontact"] = authorName;
feedback["adx_contactemail"] = authorEmail;
feedback["adx_approved"] = article.CommentPolicy != CommentPolicy.Moderated;
feedback["source"] = new OptionSetValue((int)FeedbackSource.Portal);
if (author != null)
{
feedback["createdbycontact"] = author;
}
var context = Dependencies.GetServiceContextForWrite();
context.AddObject(feedback);
context.SaveChanges();
if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage))
{
PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.KnowledgeArticle, HttpContext.Current, "create_comment_article", 1, feedback.ToEntityReference(), "create");
}
}
/// <summary>
/// Creates or Updates Case Deflection Entity for the knowledgearticle.
/// </summary>
/// <param name="title">The title of article</param>
/// <param name="searchText">The deflection SearchText of Article</param>
/// <param name="isRatingEnabled">The KnowledgeArticle RatingEnabled</param>
/// <param name="context">The OrganizationServiceContext</param>
public virtual void CreateUpdateCaseDeflection(string title, string searchText, bool isRatingEnabled, OrganizationServiceContext context)
{
var author = Dependencies.GetPortalUser();
// Update if applicable
if (author != null)
{
var existing = context.CreateQuery("adx_casedeflection").FirstOrDefault(e => e.GetAttributeValue<Guid>("adx_knowledgearticle") == KnowledgeArticle.Id && e.GetAttributeValue<Guid>("adx_contact") == author.Id);
if (existing != null)
{
UpdateCaseDeflection(existing, title, searchText);
}
else
{
CreateCaseDeflection(title, searchText);
}
if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.Feedback) && isRatingEnabled)
{
CreateUpdateRating(Rating, MaxRating, MinRating);
}
}
}
/// <summary>
/// Creates Case Deflection Entity for the knowledgearticle.
/// </summary>
/// <param name="title">The title of article</param>
/// <param name="searchText">The searchText of article</param>
public virtual void CreateCaseDeflection(string title, string searchText)
{
var author = Dependencies.GetPortalUser();
var casedeflection = new Entity("adx_casedeflection");
casedeflection["adx_casetitle"] = searchText;
casedeflection["adx_name"] = title;
casedeflection["adx_contact"] = author;
casedeflection["adx_knowledgearticle"] = KnowledgeArticle;
var context = Dependencies.GetServiceContextForWrite();
context.AddObject(casedeflection);
context.SaveChanges();
}
/// <summary>
/// Updates Case Deflection Entity for the knowledgearticle.
/// </summary>
/// <param name="existingRecord">The Casedeflection record</param>
/// <param name="title">The title of knowledgeArticle</param>
/// <param name="searchText">The searchText of knowledgeArticle</param>
public virtual void UpdateCaseDeflection(Entity existingRecord, string title, string searchText)
{
var author = Dependencies.GetPortalUser();
Entity recordToUpdate = new Entity(existingRecord.LogicalName) { Id = existingRecord.Id };
recordToUpdate.Attributes[CaseDeflectionMetadataAttributes.CaseTitle] = searchText;
recordToUpdate.Attributes[CaseDeflectionMetadataAttributes.NameOfCaseDeflection] = title;
recordToUpdate.Attributes[CaseDeflectionMetadataAttributes.ContactName] = author;
recordToUpdate.Attributes[CaseDeflectionMetadataAttributes.KnowledgearticleIdAttributeName] = KnowledgeArticle;
var context = Dependencies.GetServiceContextForWrite();
if (!context.IsAttached(recordToUpdate))
{
context.Attach(recordToUpdate);
}
context.UpdateObject(recordToUpdate);
context.SaveChanges();
}
/// <summary>
/// Vote for the knowledge article this adapter applies to.
/// Creates or updates the current user's rating
/// </summary>
/// <param name="rating">Rating value.</param>
/// <param name="maxRating">Maximum rating value.</param>
/// <param name="minRating">Minimum rating value.</param>
public virtual void CreateUpdateRating(int rating, int maxRating, int minRating, string visitorID = null)
{
var author = Dependencies.GetPortalUser();
// Update if applicable
var article = Select();
var context = Dependencies.GetServiceContextForWrite();
Entity existing = null;
if (author != null)
{
existing = context.CreateQuery("feedback")
.FirstOrDefault(feedbackRecord => feedbackRecord["regardingobjectid"] == article.EntityReference
&& feedbackRecord["createdbycontact"] == author);
}
else if (!string.IsNullOrEmpty(visitorID))
{
existing = context.CreateQuery("feedback")
.FirstOrDefault(feedbackRecord => feedbackRecord["regardingobjectid"] == article.EntityReference
&& feedbackRecord.GetAttributeValue<string>(FeedbackMetadataAttributes.VisitorAttributeName) == visitorID);
}
if (existing != null)
{
UpdateRating(existing, rating, maxRating, minRating);
return;
}
CreateRating(rating, maxRating, minRating, visitorID);
}
/// <summary>
/// Vote for the knowledge article this adapter applies to.
/// </summary>
/// <param name="rating">Rating value.</param>
/// <param name="maxRating">Maximum rating value.</param>
/// <param name="minRating">Minimum rating value.</param>
private void CreateRating(int rating, int maxRating, int minRating, string visitorID = null)
{
var article = Select();
var author = Dependencies.GetPortalUser();
var context = Dependencies.GetServiceContextForWrite();
var articleMetadata = GetArticleEntityMetadata();
var displayName = articleMetadata != null ? articleMetadata.DisplayName.UserLocalizedLabel.Label : string.Empty;
var feedback = new Entity("feedback");
feedback["title"] = ResourceManager.GetString("Feedback_Default_Title").FormatWith(displayName, article.Title);
feedback["rating"] = rating;
feedback["minrating"] = minRating;
feedback["maxrating"] = maxRating;
feedback["regardingobjectid"] = article.EntityReference;
feedback["adx_approved"] = true;
feedback["source"] = new OptionSetValue((int)FeedbackSource.Portal);
if (author != null)
{
feedback["createdbycontact"] = author;
}
else if (!string.IsNullOrEmpty(visitorID))
{
feedback.Attributes[FeedbackMetadataAttributes.VisitorAttributeName] = visitorID;
}
context.AddObject(feedback);
context.SaveChanges();
if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage))
{
PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.KnowledgeArticle, HttpContext.Current, "create_rating_article", 1, feedback.ToEntityReference(), "create");
}
}
/// <summary>
/// Updates the given rating record with the new information
/// </summary>
/// <param name="rating">Rating value.</param>
/// <param name="maxRating">Maximum rating value.</param>
/// <param name="minRating">Minimum rating value.</param>
private void UpdateRating(Entity existingRecord, int rating, int maxRating, int minRating)
{
Entity recordToUpdate = new Entity(existingRecord.LogicalName) { Id = existingRecord.Id };
recordToUpdate.Attributes[FeedbackMetadataAttributes.RatingValueAttributeName] = rating;
recordToUpdate.Attributes[FeedbackMetadataAttributes.MaxRatingAttributeName] = maxRating;
recordToUpdate.Attributes[FeedbackMetadataAttributes.MinRatingAttributeName] = minRating;
var context = Dependencies.GetServiceContextForWrite();
if (!context.IsAttached(recordToUpdate))
{
context.Attach(recordToUpdate);
}
context.UpdateObject(recordToUpdate);
context.SaveChanges();
}
private void IncrementKnowledgeArticleReferrerViewCount(int referrer, string domainName)
{
var serviceContext = Dependencies.GetServiceContextForWrite();
Condition[] conditions = {
new Condition("knowledgearticleid", ConditionOperator.Equal, KnowledgeArticle.Id),
new Condition("viewdate", ConditionOperator.Today),
new Condition("adx_referrer", ConditionOperator.Equal, referrer)
};
var list = conditions.ToList();
if (!string.IsNullOrEmpty(domainName))
{
list.Add(new Condition("adx_domainname", ConditionOperator.Equal, domainName));
}
var kbViewsfetch = new Fetch
{
Distinct = true,
Entity = new FetchEntity
{
Name = "knowledgearticleviews",
Attributes = new List<FetchAttribute>
{
new FetchAttribute("knowledgearticleviewsid"),
new FetchAttribute("knowledgearticleview"),
},
Filters = new[]
{
new Filter
{
Type = LogicalOperator.And,
Conditions = list
}
},
}
};
var kbViewsEntity = kbViewsfetch.Execute(serviceContext as IOrganizationService, RequestFlag.AllowStaleData).Entities.FirstOrDefault();
if (kbViewsEntity == null)
{
var knowledgeArticleView = new Entity("knowledgearticleviews") { Id = Guid.NewGuid() };
knowledgeArticleView["knowledgearticleid"] = KnowledgeArticle;
knowledgeArticleView["viewdate"] = DateTime.Now;
knowledgeArticleView["adx_referrer"] = new OptionSetValue(referrer);
knowledgeArticleView["location"] = new OptionSetValue(KnowledgeArticleViewCountWebLocation);
knowledgeArticleView["knowledgearticleview"] = 1;
knowledgeArticleView["adx_domainname"] = string.IsNullOrEmpty(domainName) ? null : domainName;
serviceContext.AddObject(knowledgeArticleView);
serviceContext.SaveChanges();
}
else
{
var updateKnowledgeArticleView = new Entity("knowledgearticleviews") { Id = kbViewsEntity.Id };
updateKnowledgeArticleView["viewdate"] = DateTime.Now;
updateKnowledgeArticleView["knowledgearticleview"] = (int)kbViewsEntity.Attributes["knowledgearticleview"] + 1;
var updateServiceContext = Dependencies.GetServiceContextForWrite();
if (!updateServiceContext.IsAttached(updateKnowledgeArticleView))
{
updateServiceContext.Attach(updateKnowledgeArticleView);
}
updateServiceContext.UpdateObject(updateKnowledgeArticleView);
updateServiceContext.SaveChanges();
}
}
/// <summary>
/// Retrieve Knowledge Article EntityMetadata
/// </summary>
/// <returns>Knowledge Article EntityMetadata</returns>
private EntityMetadata GetArticleEntityMetadata()
{
var context = Dependencies.GetServiceContext();
var metadataRequest = new RetrieveEntityRequest()
{
EntityFilters = EntityFilters.All,
LogicalName = KnowledgeArticle.LogicalName,
RetrieveAsIfPublished = false
};
return ((RetrieveEntityResponse)context.Execute(metadataRequest)).EntityMetadata;
}
protected IDataAdapterDependencies Dependencies { get; set; }
protected EntityReference KnowledgeArticle { get; set; }
protected string LanguageCode { get; set; }
protected IOrganizationService PortalOrganizationService
{
get { return Dependencies.GetRequestContext().HttpContext.GetOrganizationService(); }
}
public bool? ChronologicalComments { get; set; }
private const int KnowledgeArticleViewCountWebLocation = 2;
enum ReferrerType
{
Browse = 1,
PortalSearch = 2,
ExternalSearchEngine = 3,
ExternalWebsite = 4,
PortalCaseDeflectionSearch = 5,
DirectLink = 6
}
private const int Rating = 5;
private const int MaxRating = 5;
private const int MinRating = 0;
private Guid KnowledgeArticleConnectionRoleId = new Guid("81BB2655-F19B-42B2-9C4B-D45B84C3F61C");
private Guid RelatedProductConnectionRoleId = new Guid("131F5D06-9F36-4B59-B8B7-A1F7D6C5C5EF");
private Guid PrimaryArticleConnectionRoleId = new Guid("5A18DFC8-0B8B-40C7-9381-CCE1C485822D");
private Guid RelatedArticleConnectionRoleId = new Guid("CFFE4A59-CE11-4FCA-B132-5985D3917D26");
private const string RelatedProductsFetchXmlFormat = @"
<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>
<entity name='product'>
<attribute name='productid' />
<attribute name='name' />
<attribute name='productnumber' />
<attribute name='description' />
<attribute name='statecode' />
<order attribute='productnumber' descending='false' />
<link-entity name='connection' from='record2id' to='productid' alias='ad'>
<filter type='and'>
<condition attribute='record1id' operator='eq' value='{0}' />
<condition attribute='record2roleid' operator='eq' uiname='Associated Product' uitype='connectionrole' value='{1}' />
<condition attribute='record1roleid' operator='eq' uiname='Knowledge Article' uitype='connectionrole' value='{2}' />
</filter>
</link-entity>
<filter type='and'>
<condition attribute='statecode' operator='eq' value='0' />
</filter>
</entity>
</fetch>";
private const string RelatedArticlesFetchXmlFormat = @"
<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>
<entity name='knowledgearticle'>
<attribute name='articlepublicnumber' />
<attribute name='knowledgearticleid' />
<attribute name='title' />
<attribute name='keywords' />
<attribute name='createdon' />
<attribute name='statecode' />
<attribute name='statuscode' />
<attribute name='isinternal' />
<attribute name='isrootarticle' />
<attribute name='knowledgearticleviews' />
<attribute name='languagelocaleid' />
<order attribute='articlepublicnumber' descending='false' />
<link-entity name='languagelocale' from='languagelocaleid' to='languagelocaleid' visible='false' link-type='outer' alias='language_locale'>
<attribute name='localeid' />
<attribute name='code' />
<attribute name='region' />
<attribute name='name' />
<attribute name='language' />
</link-entity>
<filter type='and'>
<condition attribute='isrootarticle' operator='eq' value='0' />
<condition attribute='statecode' operator='eq' value='3' />
<condition attribute='isinternal' operator='eq' value='0' />
{3}
</filter>
<link-entity name='connection' from='record2id' to='knowledgearticleid' alias='aj'>
<filter type='and'>
<condition attribute='record1id' operator='eq' value='{0}' />
<condition attribute='record1roleid' operator='eq' uiname='Primary Article' uitype='connectionrole' value='{1}' />
<condition attribute='record2roleid' operator='eq' uiname='Related Article' uitype='connectionrole' value='{2}' />
</filter>
</link-entity>
</entity>
</fetch>";
}
}
| |
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Graphics.Sprites;
namespace osu.Game.Graphics
{
public class TextAwesome : SpriteText
{
//public override FontFace FontFace => (int)Icon < 0xf000 ? FontFace.OsuFont : FontFace.FontAwesome;
private FontAwesome icon;
public FontAwesome Icon
{
get
{
return icon;
}
set
{
if (icon == value) return;
icon = value;
Text = ((char)icon).ToString();
}
}
public TextAwesome()
{
Origin = Framework.Graphics.Anchor.Centre;
}
}
public enum FontAwesome
{
fa_500px = 0xf26e,
fa_address_book = 0xf2b9,
fa_address_book_o = 0xf2ba,
fa_address_card = 0xf2bb,
fa_address_card_o = 0xf2bc,
fa_adjust = 0xf042,
fa_adn = 0xf170,
fa_align_center = 0xf037,
fa_align_justify = 0xf039,
fa_align_left = 0xf036,
fa_align_right = 0xf038,
fa_amazon = 0xf270,
fa_ambulance = 0xf0f9,
fa_american_sign_language_interpreting = 0xf2a3,
fa_anchor = 0xf13d,
fa_android = 0xf17b,
fa_angellist = 0xf209,
fa_angle_double_down = 0xf103,
fa_angle_double_left = 0xf100,
fa_angle_double_right = 0xf101,
fa_angle_double_up = 0xf102,
fa_angle_down = 0xf107,
fa_angle_left = 0xf104,
fa_angle_right = 0xf105,
fa_angle_up = 0xf106,
fa_apple = 0xf179,
fa_archive = 0xf187,
fa_area_chart = 0xf1fe,
fa_arrow_circle_down = 0xf0ab,
fa_arrow_circle_left = 0xf0a8,
fa_arrow_circle_o_down = 0xf01a,
fa_arrow_circle_o_left = 0xf190,
fa_arrow_circle_o_right = 0xf18e,
fa_arrow_circle_o_up = 0xf01b,
fa_arrow_circle_right = 0xf0a9,
fa_arrow_circle_up = 0xf0aa,
fa_arrow_down = 0xf063,
fa_arrow_left = 0xf060,
fa_arrow_right = 0xf061,
fa_arrow_up = 0xf062,
fa_arrows = 0xf047,
fa_arrows_alt = 0xf0b2,
fa_arrows_h = 0xf07e,
fa_arrows_v = 0xf07d,
fa_asl_interpreting = 0xf2a3,
fa_assistive_listening_systems = 0xf2a2,
fa_asterisk = 0xf069,
fa_at = 0xf1fa,
fa_audio_description = 0xf29e,
fa_automobile = 0xf1b9,
fa_backward = 0xf04a,
fa_balance_scale = 0xf24e,
fa_ban = 0xf05e,
fa_bandcamp = 0xf2d5,
fa_bank = 0xf19c,
fa_bar_chart = 0xf080,
fa_bar_chart_o = 0xf080,
fa_barcode = 0xf02a,
fa_bars = 0xf0c9,
fa_bath = 0xf2cd,
fa_bathtub = 0xf2cd,
fa_battery = 0xf240,
fa_battery_0 = 0xf244,
fa_battery_1 = 0xf243,
fa_battery_2 = 0xf242,
fa_battery_3 = 0xf241,
fa_battery_4 = 0xf240,
fa_battery_empty = 0xf244,
fa_battery_full = 0xf240,
fa_battery_half = 0xf242,
fa_battery_quarter = 0xf243,
fa_battery_three_quarters = 0xf241,
fa_bed = 0xf236,
fa_beer = 0xf0fc,
fa_behance = 0xf1b4,
fa_behance_square = 0xf1b5,
fa_bell = 0xf0f3,
fa_bell_o = 0xf0a2,
fa_bell_slash = 0xf1f6,
fa_bell_slash_o = 0xf1f7,
fa_bicycle = 0xf206,
fa_binoculars = 0xf1e5,
fa_birthday_cake = 0xf1fd,
fa_bitbucket = 0xf171,
fa_bitbucket_square = 0xf172,
fa_bitcoin = 0xf15a,
fa_black_tie = 0xf27e,
fa_blind = 0xf29d,
fa_bluetooth = 0xf293,
fa_bluetooth_b = 0xf294,
fa_bold = 0xf032,
fa_bolt = 0xf0e7,
fa_bomb = 0xf1e2,
fa_book = 0xf02d,
fa_bookmark = 0xf02e,
fa_bookmark_o = 0xf097,
fa_braille = 0xf2a1,
fa_briefcase = 0xf0b1,
fa_btc = 0xf15a,
fa_bug = 0xf188,
fa_building = 0xf1ad,
fa_building_o = 0xf0f7,
fa_bullhorn = 0xf0a1,
fa_bullseye = 0xf140,
fa_bus = 0xf207,
fa_buysellads = 0xf20d,
fa_cab = 0xf1ba,
fa_calculator = 0xf1ec,
fa_calendar = 0xf073,
fa_calendar_check_o = 0xf274,
fa_calendar_minus_o = 0xf272,
fa_calendar_o = 0xf133,
fa_calendar_plus_o = 0xf271,
fa_calendar_times_o = 0xf273,
fa_camera = 0xf030,
fa_camera_retro = 0xf083,
fa_car = 0xf1b9,
fa_caret_down = 0xf0d7,
fa_caret_left = 0xf0d9,
fa_caret_right = 0xf0da,
fa_caret_square_o_down = 0xf150,
fa_caret_square_o_left = 0xf191,
fa_caret_square_o_right = 0xf152,
fa_caret_square_o_up = 0xf151,
fa_caret_up = 0xf0d8,
fa_cart_arrow_down = 0xf218,
fa_cart_plus = 0xf217,
fa_cc = 0xf20a,
fa_cc_amex = 0xf1f3,
fa_cc_diners_club = 0xf24c,
fa_cc_discover = 0xf1f2,
fa_cc_jcb = 0xf24b,
fa_cc_mastercard = 0xf1f1,
fa_cc_paypal = 0xf1f4,
fa_cc_stripe = 0xf1f5,
fa_cc_visa = 0xf1f0,
fa_certificate = 0xf0a3,
fa_chain = 0xf0c1,
fa_chain_broken = 0xf127,
fa_check = 0xf00c,
fa_check_circle = 0xf058,
fa_check_circle_o = 0xf05d,
fa_check_square = 0xf14a,
fa_check_square_o = 0xf046,
fa_chevron_circle_down = 0xf13a,
fa_chevron_circle_left = 0xf137,
fa_chevron_circle_right = 0xf138,
fa_chevron_circle_up = 0xf139,
fa_chevron_down = 0xf078,
fa_chevron_left = 0xf053,
fa_chevron_right = 0xf054,
fa_chevron_up = 0xf077,
fa_child = 0xf1ae,
fa_chrome = 0xf268,
fa_circle = 0xf111,
fa_circle_o = 0xf10c,
fa_circle_o_notch = 0xf1ce,
fa_circle_thin = 0xf1db,
fa_clipboard = 0xf0ea,
fa_clock_o = 0xf017,
fa_clone = 0xf24d,
fa_close = 0xf00d,
fa_cloud = 0xf0c2,
fa_cloud_download = 0xf0ed,
fa_cloud_upload = 0xf0ee,
fa_cny = 0xf157,
fa_code = 0xf121,
fa_code_fork = 0xf126,
fa_codepen = 0xf1cb,
fa_codiepie = 0xf284,
fa_coffee = 0xf0f4,
fa_cog = 0xf013,
fa_cogs = 0xf085,
fa_columns = 0xf0db,
fa_comment = 0xf075,
fa_comment_o = 0xf0e5,
fa_commenting = 0xf27a,
fa_commenting_o = 0xf27b,
fa_comments = 0xf086,
fa_comments_o = 0xf0e6,
fa_compass = 0xf14e,
fa_compress = 0xf066,
fa_connectdevelop = 0xf20e,
fa_contao = 0xf26d,
fa_copy = 0xf0c5,
fa_copyright = 0xf1f9,
fa_creative_commons = 0xf25e,
fa_credit_card = 0xf09d,
fa_credit_card_alt = 0xf283,
fa_crop = 0xf125,
fa_crosshairs = 0xf05b,
fa_css3 = 0xf13c,
fa_cube = 0xf1b2,
fa_cubes = 0xf1b3,
fa_cut = 0xf0c4,
fa_cutlery = 0xf0f5,
fa_dashboard = 0xf0e4,
fa_dashcube = 0xf210,
fa_database = 0xf1c0,
fa_deaf = 0xf2a4,
fa_deafness = 0xf2a4,
fa_dedent = 0xf03b,
fa_delicious = 0xf1a5,
fa_desktop = 0xf108,
fa_deviantart = 0xf1bd,
fa_diamond = 0xf219,
fa_digg = 0xf1a6,
fa_dollar = 0xf155,
fa_dot_circle_o = 0xf192,
fa_download = 0xf019,
fa_dribbble = 0xf17d,
fa_drivers_license = 0xf2c2,
fa_drivers_license_o = 0xf2c3,
fa_dropbox = 0xf16b,
fa_drupal = 0xf1a9,
fa_edge = 0xf282,
fa_edit = 0xf044,
fa_eercast = 0xf2da,
fa_eject = 0xf052,
fa_ellipsis_h = 0xf141,
fa_ellipsis_v = 0xf142,
fa_empire = 0xf1d1,
fa_envelope = 0xf0e0,
fa_envelope_o = 0xf003,
fa_envelope_open = 0xf2b6,
fa_envelope_open_o = 0xf2b7,
fa_envelope_square = 0xf199,
fa_envira = 0xf299,
fa_eraser = 0xf12d,
fa_etsy = 0xf2d7,
fa_eur = 0xf153,
fa_euro = 0xf153,
fa_exchange = 0xf0ec,
fa_exclamation = 0xf12a,
fa_exclamation_circle = 0xf06a,
fa_exclamation_triangle = 0xf071,
fa_expand = 0xf065,
fa_expeditedssl = 0xf23e,
fa_external_link = 0xf08e,
fa_external_link_square = 0xf14c,
fa_eye = 0xf06e,
fa_eye_slash = 0xf070,
fa_eyedropper = 0xf1fb,
fa_fa = 0xf2b4,
fa_facebook = 0xf09a,
fa_facebook_f = 0xf09a,
fa_facebook_official = 0xf230,
fa_facebook_square = 0xf082,
fa_fast_backward = 0xf049,
fa_fast_forward = 0xf050,
fa_fax = 0xf1ac,
fa_feed = 0xf09e,
fa_female = 0xf182,
fa_fighter_jet = 0xf0fb,
fa_file = 0xf15b,
fa_file_archive_o = 0xf1c6,
fa_file_audio_o = 0xf1c7,
fa_file_code_o = 0xf1c9,
fa_file_excel_o = 0xf1c3,
fa_file_image_o = 0xf1c5,
fa_file_movie_o = 0xf1c8,
fa_file_o = 0xf016,
fa_file_pdf_o = 0xf1c1,
fa_file_photo_o = 0xf1c5,
fa_file_picture_o = 0xf1c5,
fa_file_powerpoint_o = 0xf1c4,
fa_file_sound_o = 0xf1c7,
fa_file_text = 0xf15c,
fa_file_text_o = 0xf0f6,
fa_file_video_o = 0xf1c8,
fa_file_word_o = 0xf1c2,
fa_file_zip_o = 0xf1c6,
fa_files_o = 0xf0c5,
fa_film = 0xf008,
fa_filter = 0xf0b0,
fa_fire = 0xf06d,
fa_fire_extinguisher = 0xf134,
fa_firefox = 0xf269,
fa_first_order = 0xf2b0,
fa_flag = 0xf024,
fa_flag_checkered = 0xf11e,
fa_flag_o = 0xf11d,
fa_flash = 0xf0e7,
fa_flask = 0xf0c3,
fa_flickr = 0xf16e,
fa_floppy_o = 0xf0c7,
fa_folder = 0xf07b,
fa_folder_o = 0xf114,
fa_folder_open = 0xf07c,
fa_folder_open_o = 0xf115,
fa_font = 0xf031,
fa_font_awesome = 0xf2b4,
fa_fonticons = 0xf280,
fa_fort_awesome = 0xf286,
fa_forumbee = 0xf211,
fa_forward = 0xf04e,
fa_foursquare = 0xf180,
fa_free_code_camp = 0xf2c5,
fa_frown_o = 0xf119,
fa_futbol_o = 0xf1e3,
fa_gamepad = 0xf11b,
fa_gavel = 0xf0e3,
fa_gbp = 0xf154,
fa_ge = 0xf1d1,
fa_gear = 0xf013,
fa_gears = 0xf085,
fa_genderless = 0xf22d,
fa_get_pocket = 0xf265,
fa_gg = 0xf260,
fa_gg_circle = 0xf261,
fa_gift = 0xf06b,
fa_git = 0xf1d3,
fa_git_square = 0xf1d2,
fa_github = 0xf09b,
fa_github_alt = 0xf113,
fa_github_square = 0xf092,
fa_gitlab = 0xf296,
fa_gittip = 0xf184,
fa_glass = 0xf000,
fa_glide = 0xf2a5,
fa_glide_g = 0xf2a6,
fa_globe = 0xf0ac,
fa_google = 0xf1a0,
fa_google_plus = 0xf0d5,
fa_google_plus_circle = 0xf2b3,
fa_google_plus_official = 0xf2b3,
fa_google_plus_square = 0xf0d4,
fa_google_wallet = 0xf1ee,
fa_graduation_cap = 0xf19d,
fa_gratipay = 0xf184,
fa_grav = 0xf2d6,
fa_group = 0xf0c0,
fa_h_square = 0xf0fd,
fa_hacker_news = 0xf1d4,
fa_hand_grab_o = 0xf255,
fa_hand_lizard_o = 0xf258,
fa_hand_o_down = 0xf0a7,
fa_hand_o_left = 0xf0a5,
fa_hand_o_right = 0xf0a4,
fa_hand_o_up = 0xf0a6,
fa_hand_paper_o = 0xf256,
fa_hand_peace_o = 0xf25b,
fa_hand_pointer_o = 0xf25a,
fa_hand_rock_o = 0xf255,
fa_hand_scissors_o = 0xf257,
fa_hand_spock_o = 0xf259,
fa_hand_stop_o = 0xf256,
fa_handshake_o = 0xf2b5,
fa_hard_of_hearing = 0xf2a4,
fa_hashtag = 0xf292,
fa_hdd_o = 0xf0a0,
fa_header = 0xf1dc,
fa_headphones = 0xf025,
fa_heart = 0xf004,
fa_heart_o = 0xf08a,
fa_heartbeat = 0xf21e,
fa_history = 0xf1da,
fa_home = 0xf015,
fa_hospital_o = 0xf0f8,
fa_hotel = 0xf236,
fa_hourglass = 0xf254,
fa_hourglass_1 = 0xf251,
fa_hourglass_2 = 0xf252,
fa_hourglass_3 = 0xf253,
fa_hourglass_end = 0xf253,
fa_hourglass_half = 0xf252,
fa_hourglass_o = 0xf250,
fa_hourglass_start = 0xf251,
fa_houzz = 0xf27c,
fa_html5 = 0xf13b,
fa_i_cursor = 0xf246,
fa_id_badge = 0xf2c1,
fa_id_card = 0xf2c2,
fa_id_card_o = 0xf2c3,
fa_ils = 0xf20b,
fa_image = 0xf03e,
fa_imdb = 0xf2d8,
fa_inbox = 0xf01c,
fa_indent = 0xf03c,
fa_industry = 0xf275,
fa_info = 0xf129,
fa_info_circle = 0xf05a,
fa_inr = 0xf156,
fa_instagram = 0xf16d,
fa_institution = 0xf19c,
fa_internet_explorer = 0xf26b,
fa_intersex = 0xf224,
fa_ioxhost = 0xf208,
fa_italic = 0xf033,
fa_joomla = 0xf1aa,
fa_jpy = 0xf157,
fa_jsfiddle = 0xf1cc,
fa_key = 0xf084,
fa_keyboard_o = 0xf11c,
fa_krw = 0xf159,
fa_language = 0xf1ab,
fa_laptop = 0xf109,
fa_lastfm = 0xf202,
fa_lastfm_square = 0xf203,
fa_leaf = 0xf06c,
fa_leanpub = 0xf212,
fa_legal = 0xf0e3,
fa_lemon_o = 0xf094,
fa_level_down = 0xf149,
fa_level_up = 0xf148,
fa_life_bouy = 0xf1cd,
fa_life_buoy = 0xf1cd,
fa_life_ring = 0xf1cd,
fa_life_saver = 0xf1cd,
fa_lightbulb_o = 0xf0eb,
fa_line_chart = 0xf201,
fa_link = 0xf0c1,
fa_linkedin = 0xf0e1,
fa_linkedin_square = 0xf08c,
fa_linode = 0xf2b8,
fa_linux = 0xf17c,
fa_list = 0xf03a,
fa_list_alt = 0xf022,
fa_list_ol = 0xf0cb,
fa_list_ul = 0xf0ca,
fa_location_arrow = 0xf124,
fa_lock = 0xf023,
fa_long_arrow_down = 0xf175,
fa_long_arrow_left = 0xf177,
fa_long_arrow_right = 0xf178,
fa_long_arrow_up = 0xf176,
fa_low_vision = 0xf2a8,
fa_magic = 0xf0d0,
fa_magnet = 0xf076,
fa_mail_forward = 0xf064,
fa_mail_reply = 0xf112,
fa_mail_reply_all = 0xf122,
fa_male = 0xf183,
fa_map = 0xf279,
fa_map_marker = 0xf041,
fa_map_o = 0xf278,
fa_map_pin = 0xf276,
fa_map_signs = 0xf277,
fa_mars = 0xf222,
fa_mars_double = 0xf227,
fa_mars_stroke = 0xf229,
fa_mars_stroke_h = 0xf22b,
fa_mars_stroke_v = 0xf22a,
fa_maxcdn = 0xf136,
fa_meanpath = 0xf20c,
fa_medium = 0xf23a,
fa_medkit = 0xf0fa,
fa_meetup = 0xf2e0,
fa_meh_o = 0xf11a,
fa_mercury = 0xf223,
fa_microchip = 0xf2db,
fa_microphone = 0xf130,
fa_microphone_slash = 0xf131,
fa_minus = 0xf068,
fa_minus_circle = 0xf056,
fa_minus_square = 0xf146,
fa_minus_square_o = 0xf147,
fa_mixcloud = 0xf289,
fa_mobile = 0xf10b,
fa_mobile_phone = 0xf10b,
fa_modx = 0xf285,
fa_money = 0xf0d6,
fa_moon_o = 0xf186,
fa_mortar_board = 0xf19d,
fa_motorcycle = 0xf21c,
fa_mouse_pointer = 0xf245,
fa_music = 0xf001,
fa_navicon = 0xf0c9,
fa_neuter = 0xf22c,
fa_newspaper_o = 0xf1ea,
fa_object_group = 0xf247,
fa_object_ungroup = 0xf248,
fa_odnoklassniki = 0xf263,
fa_odnoklassniki_square = 0xf264,
fa_opencart = 0xf23d,
fa_openid = 0xf19b,
fa_opera = 0xf26a,
fa_optin_monster = 0xf23c,
fa_outdent = 0xf03b,
fa_pagelines = 0xf18c,
fa_paint_brush = 0xf1fc,
fa_paper_plane = 0xf1d8,
fa_paper_plane_o = 0xf1d9,
fa_paperclip = 0xf0c6,
fa_paragraph = 0xf1dd,
fa_paste = 0xf0ea,
fa_pause = 0xf04c,
fa_pause_circle = 0xf28b,
fa_pause_circle_o = 0xf28c,
fa_paw = 0xf1b0,
fa_paypal = 0xf1ed,
fa_pencil = 0xf040,
fa_pencil_square = 0xf14b,
fa_pencil_square_o = 0xf044,
fa_percent = 0xf295,
fa_phone = 0xf095,
fa_phone_square = 0xf098,
fa_photo = 0xf03e,
fa_picture_o = 0xf03e,
fa_pie_chart = 0xf200,
fa_pied_piper = 0xf2ae,
fa_pied_piper_alt = 0xf1a8,
fa_pied_piper_pp = 0xf1a7,
fa_pinterest = 0xf0d2,
fa_pinterest_p = 0xf231,
fa_pinterest_square = 0xf0d3,
fa_plane = 0xf072,
fa_play = 0xf04b,
fa_play_circle = 0xf144,
fa_play_circle_o = 0xf01d,
fa_plug = 0xf1e6,
fa_plus = 0xf067,
fa_plus_circle = 0xf055,
fa_plus_square = 0xf0fe,
fa_plus_square_o = 0xf196,
fa_podcast = 0xf2ce,
fa_power_off = 0xf011,
fa_print = 0xf02f,
fa_product_hunt = 0xf288,
fa_puzzle_piece = 0xf12e,
fa_qq = 0xf1d6,
fa_qrcode = 0xf029,
fa_question = 0xf128,
fa_question_circle = 0xf059,
fa_question_circle_o = 0xf29c,
fa_quora = 0xf2c4,
fa_quote_left = 0xf10d,
fa_quote_right = 0xf10e,
fa_ra = 0xf1d0,
fa_random = 0xf074,
fa_ravelry = 0xf2d9,
fa_rebel = 0xf1d0,
fa_recycle = 0xf1b8,
fa_reddit = 0xf1a1,
fa_reddit_alien = 0xf281,
fa_reddit_square = 0xf1a2,
fa_refresh = 0xf021,
fa_registered = 0xf25d,
fa_remove = 0xf00d,
fa_renren = 0xf18b,
fa_reorder = 0xf0c9,
fa_repeat = 0xf01e,
fa_reply = 0xf112,
fa_reply_all = 0xf122,
fa_resistance = 0xf1d0,
fa_retweet = 0xf079,
fa_rmb = 0xf157,
fa_road = 0xf018,
fa_rocket = 0xf135,
fa_rotate_left = 0xf0e2,
fa_rotate_right = 0xf01e,
fa_rouble = 0xf158,
fa_rss = 0xf09e,
fa_rss_square = 0xf143,
fa_rub = 0xf158,
fa_ruble = 0xf158,
fa_rupee = 0xf156,
fa_s15 = 0xf2cd,
fa_safari = 0xf267,
fa_save = 0xf0c7,
fa_scissors = 0xf0c4,
fa_scribd = 0xf28a,
fa_search = 0xf002,
fa_search_minus = 0xf010,
fa_search_plus = 0xf00e,
fa_sellsy = 0xf213,
fa_send = 0xf1d8,
fa_send_o = 0xf1d9,
fa_server = 0xf233,
fa_share = 0xf064,
fa_share_alt = 0xf1e0,
fa_share_alt_square = 0xf1e1,
fa_share_square = 0xf14d,
fa_share_square_o = 0xf045,
fa_shekel = 0xf20b,
fa_sheqel = 0xf20b,
fa_shield = 0xf132,
fa_ship = 0xf21a,
fa_shirtsinbulk = 0xf214,
fa_shopping_bag = 0xf290,
fa_shopping_basket = 0xf291,
fa_shopping_cart = 0xf07a,
fa_shower = 0xf2cc,
fa_sign_in = 0xf090,
fa_sign_language = 0xf2a7,
fa_sign_out = 0xf08b,
fa_signal = 0xf012,
fa_signing = 0xf2a7,
fa_simplybuilt = 0xf215,
fa_sitemap = 0xf0e8,
fa_skyatlas = 0xf216,
fa_skype = 0xf17e,
fa_slack = 0xf198,
fa_sliders = 0xf1de,
fa_slideshare = 0xf1e7,
fa_smile_o = 0xf118,
fa_snapchat = 0xf2ab,
fa_snapchat_ghost = 0xf2ac,
fa_snapchat_square = 0xf2ad,
fa_snowflake_o = 0xf2dc,
fa_soccer_ball_o = 0xf1e3,
fa_sort = 0xf0dc,
fa_sort_alpha_asc = 0xf15d,
fa_sort_alpha_desc = 0xf15e,
fa_sort_amount_asc = 0xf160,
fa_sort_amount_desc = 0xf161,
fa_sort_asc = 0xf0de,
fa_sort_desc = 0xf0dd,
fa_sort_down = 0xf0dd,
fa_sort_numeric_asc = 0xf162,
fa_sort_numeric_desc = 0xf163,
fa_sort_up = 0xf0de,
fa_soundcloud = 0xf1be,
fa_space_shuttle = 0xf197,
fa_spinner = 0xf110,
fa_spoon = 0xf1b1,
fa_spotify = 0xf1bc,
fa_square = 0xf0c8,
fa_square_o = 0xf096,
fa_stack_exchange = 0xf18d,
fa_stack_overflow = 0xf16c,
fa_star = 0xf005,
fa_star_half = 0xf089,
fa_star_half_empty = 0xf123,
fa_star_half_full = 0xf123,
fa_star_half_o = 0xf123,
fa_star_o = 0xf006,
fa_steam = 0xf1b6,
fa_steam_square = 0xf1b7,
fa_step_backward = 0xf048,
fa_step_forward = 0xf051,
fa_stethoscope = 0xf0f1,
fa_sticky_note = 0xf249,
fa_sticky_note_o = 0xf24a,
fa_stop = 0xf04d,
fa_stop_circle = 0xf28d,
fa_stop_circle_o = 0xf28e,
fa_street_view = 0xf21d,
fa_strikethrough = 0xf0cc,
fa_stumbleupon = 0xf1a4,
fa_stumbleupon_circle = 0xf1a3,
fa_subscript = 0xf12c,
fa_subway = 0xf239,
fa_suitcase = 0xf0f2,
fa_sun_o = 0xf185,
fa_superpowers = 0xf2dd,
fa_superscript = 0xf12b,
fa_support = 0xf1cd,
fa_table = 0xf0ce,
fa_tablet = 0xf10a,
fa_tachometer = 0xf0e4,
fa_tag = 0xf02b,
fa_tags = 0xf02c,
fa_tasks = 0xf0ae,
fa_taxi = 0xf1ba,
fa_telegram = 0xf2c6,
fa_television = 0xf26c,
fa_tencent_weibo = 0xf1d5,
fa_terminal = 0xf120,
fa_text_height = 0xf034,
fa_text_width = 0xf035,
fa_th = 0xf00a,
fa_th_large = 0xf009,
fa_th_list = 0xf00b,
fa_themeisle = 0xf2b2,
fa_thermometer = 0xf2c7,
fa_thermometer_0 = 0xf2cb,
fa_thermometer_1 = 0xf2ca,
fa_thermometer_2 = 0xf2c9,
fa_thermometer_3 = 0xf2c8,
fa_thermometer_4 = 0xf2c7,
fa_thermometer_empty = 0xf2cb,
fa_thermometer_full = 0xf2c7,
fa_thermometer_half = 0xf2c9,
fa_thermometer_quarter = 0xf2ca,
fa_thermometer_three_quarters = 0xf2c8,
fa_thumb_tack = 0xf08d,
fa_thumbs_down = 0xf165,
fa_thumbs_o_down = 0xf088,
fa_thumbs_o_up = 0xf087,
fa_thumbs_up = 0xf164,
fa_ticket = 0xf145,
fa_times = 0xf00d,
fa_times_circle = 0xf057,
fa_times_circle_o = 0xf05c,
fa_times_rectangle = 0xf2d3,
fa_times_rectangle_o = 0xf2d4,
fa_tint = 0xf043,
fa_toggle_down = 0xf150,
fa_toggle_left = 0xf191,
fa_toggle_off = 0xf204,
fa_toggle_on = 0xf205,
fa_toggle_right = 0xf152,
fa_toggle_up = 0xf151,
fa_trademark = 0xf25c,
fa_train = 0xf238,
fa_transgender = 0xf224,
fa_transgender_alt = 0xf225,
fa_trash = 0xf1f8,
fa_trash_o = 0xf014,
fa_tree = 0xf1bb,
fa_trello = 0xf181,
fa_tripadvisor = 0xf262,
fa_trophy = 0xf091,
fa_truck = 0xf0d1,
fa_try = 0xf195,
fa_tty = 0xf1e4,
fa_tumblr = 0xf173,
fa_tumblr_square = 0xf174,
fa_turkish_lira = 0xf195,
fa_tv = 0xf26c,
fa_twitch = 0xf1e8,
fa_twitter = 0xf099,
fa_twitter_square = 0xf081,
fa_umbrella = 0xf0e9,
fa_underline = 0xf0cd,
fa_undo = 0xf0e2,
fa_universal_access = 0xf29a,
fa_university = 0xf19c,
fa_unlink = 0xf127,
fa_unlock = 0xf09c,
fa_unlock_alt = 0xf13e,
fa_unsorted = 0xf0dc,
fa_upload = 0xf093,
fa_usb = 0xf287,
fa_usd = 0xf155,
fa_user = 0xf007,
fa_user_circle = 0xf2bd,
fa_user_circle_o = 0xf2be,
fa_user_md = 0xf0f0,
fa_user_o = 0xf2c0,
fa_user_plus = 0xf234,
fa_user_secret = 0xf21b,
fa_user_times = 0xf235,
fa_users = 0xf0c0,
fa_vcard = 0xf2bb,
fa_vcard_o = 0xf2bc,
fa_venus = 0xf221,
fa_venus_double = 0xf226,
fa_venus_mars = 0xf228,
fa_viacoin = 0xf237,
fa_viadeo = 0xf2a9,
fa_viadeo_square = 0xf2aa,
fa_video_camera = 0xf03d,
fa_vimeo = 0xf27d,
fa_vimeo_square = 0xf194,
fa_vine = 0xf1ca,
fa_vk = 0xf189,
fa_volume_control_phone = 0xf2a0,
fa_volume_down = 0xf027,
fa_volume_off = 0xf026,
fa_volume_up = 0xf028,
fa_warning = 0xf071,
fa_wechat = 0xf1d7,
fa_weibo = 0xf18a,
fa_weixin = 0xf1d7,
fa_whatsapp = 0xf232,
fa_wheelchair = 0xf193,
fa_wheelchair_alt = 0xf29b,
fa_wifi = 0xf1eb,
fa_wikipedia_w = 0xf266,
fa_window_close = 0xf2d3,
fa_window_close_o = 0xf2d4,
fa_window_maximize = 0xf2d0,
fa_window_minimize = 0xf2d1,
fa_window_restore = 0xf2d2,
fa_windows = 0xf17a,
fa_won = 0xf159,
fa_wordpress = 0xf19a,
fa_wpbeginner = 0xf297,
fa_wpexplorer = 0xf2de,
fa_wpforms = 0xf298,
fa_wrench = 0xf0ad,
fa_xing = 0xf168,
fa_xing_square = 0xf169,
fa_y_combinator = 0xf23b,
fa_y_combinator_square = 0xf1d4,
fa_yahoo = 0xf19e,
fa_yc = 0xf23b,
fa_yc_square = 0xf1d4,
fa_yelp = 0xf1e9,
fa_yen = 0xf157,
fa_yoast = 0xf2b1,
fa_youtube = 0xf167,
fa_youtube_play = 0xf16a,
fa_youtube_square = 0xf166,
// gamemode icons in circles
fa_osu_osu_o = 0xe000,
fa_osu_mania_o = 0xe001,
fa_osu_fruits_o = 0xe002,
fa_osu_taiko_o = 0xe003,
// gamemode icons without circles
fa_osu_filled_circle = 0xe004,
fa_osu_cross_o = 0xe005,
fa_osu_logo = 0xe006,
fa_osu_chevron_down_o = 0xe007,
fa_osu_edit_o = 0xe033,
fa_osu_left_o = 0xe034,
fa_osu_right_o = 0xe035,
fa_osu_charts = 0xe036,
fa_osu_solo = 0xe037,
fa_osu_multi = 0xe038,
fa_osu_gear = 0xe039,
// misc icons
fa_osu_bat = 0xe008,
fa_osu_bubble = 0xe009,
fa_osu_bubble_pop = 0xe02e,
fa_osu_dice = 0xe011,
fa_osu_heart1 = 0xe02f,
fa_osu_heart1_break = 0xe030,
fa_osu_hot = 0xe031,
fa_osu_list_search = 0xe032,
//osu! playstyles
fa_osu_playstyle_tablet = 0xe02a,
fa_osu_playstyle_mouse = 0xe029,
fa_osu_playstyle_keyboard = 0xe02b,
fa_osu_playstyle_touch = 0xe02c,
// osu! difficulties
fa_osu_easy_osu = 0xe015,
fa_osu_normal_osu = 0xe016,
fa_osu_hard_osu = 0xe017,
fa_osu_insane_osu = 0xe018,
fa_osu_expert_osu = 0xe019,
// taiko difficulties
fa_osu_easy_taiko = 0xe01a,
fa_osu_normal_taiko = 0xe01b,
fa_osu_hard_taiko = 0xe01c,
fa_osu_insane_taiko = 0xe01d,
fa_osu_expert_taiko = 0xe01e,
// fruits difficulties
fa_osu_easy_fruits = 0xe01f,
fa_osu_normal_fruits = 0xe020,
fa_osu_hard_fruits = 0xe021,
fa_osu_insane_fruits = 0xe022,
fa_osu_expert_fruits = 0xe023,
// mania difficulties
fa_osu_easy_mania = 0xe024,
fa_osu_normal_mania = 0xe025,
fa_osu_hard_mania = 0xe026,
fa_osu_insane_mania = 0xe027,
fa_osu_expert_mania = 0xe028,
// mod icons
fa_osu_mod_perfect = 0xe02d,
fa_osu_mod_autopilot = 0xe03a,
fa_osu_mod_auto = 0xe03b,
fa_osu_mod_cinema = 0xe03c,
fa_osu_mod_doubletime = 0xe03d,
fa_osu_mod_easy = 0xe03e,
fa_osu_mod_flashlight = 0xe03f,
fa_osu_mod_halftime = 0xe040,
fa_osu_mod_hardrock = 0xe041,
fa_osu_mod_hidden = 0xe042,
fa_osu_mod_nightcore = 0xe043,
fa_osu_mod_nofail = 0xe044,
fa_osu_mod_relax = 0xe045,
fa_osu_mod_spunout = 0xe046,
fa_osu_mod_suddendeath = 0xe047,
fa_osu_mod_target = 0xe048,
fa_osu_mod_bg = 0xe049,
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace MediaUpload.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Copyright 2020 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
//
// 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 Debugger.Common;
using Debugger.RemoteValueRpc;
using DebuggerApi;
using System;
using System.Runtime.InteropServices;
using YetiCommon;
using RemoteValueRpcServiceClient =
Debugger.RemoteValueRpc.RemoteValueRpcService.RemoteValueRpcServiceClient;
using DebuggerGrpcClient.Implementations;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DebuggerGrpcClient
{
// Creates RemoteValue objects.
public class GrpcValueFactory
{
public virtual RemoteValue Create(
GrpcConnection connection, GrpcSbValue grpcSbValue)
{
return new RemoteValueProxy(connection, grpcSbValue);
}
}
// Implementation of the RemoteValue interface that uses GRPC to make RPCs to a remote
// endpoint.
class RemoteValueProxy : RemoteValue
{
readonly GrpcConnection connection;
readonly RemoteValueRpcServiceClient client;
readonly GrpcSbValue grpcSbValue;
readonly GrpcValueFactory valueFactory;
readonly GrpcErrorFactory errorFactory;
readonly GrpcTypeFactory typeFactory;
readonly CachedValueFactory cachedValueFactory;
readonly GCHandle gcHandle;
internal RemoteValueProxy(GrpcConnection connection, GrpcSbValue grpcSbValue)
: this(connection,
new RemoteValueRpcServiceClient(connection.CallInvoker), grpcSbValue,
new GrpcValueFactory(), new GrpcErrorFactory(), new GrpcTypeFactory(),
new CachedValueFactory())
{ }
internal RemoteValueProxy(
GrpcConnection connection, RemoteValueRpcServiceClient client,
GrpcSbValue grpcSbValue, GrpcValueFactory valueFactory, GrpcErrorFactory errorFactory,
GrpcTypeFactory typeFactory, CachedValueFactory cachedValueFactory)
{
this.connection = connection;
this.client = client;
this.grpcSbValue = grpcSbValue;
this.valueFactory = valueFactory;
this.errorFactory = errorFactory;
this.typeFactory = typeFactory;
this.cachedValueFactory = cachedValueFactory;
// Keep a handle to objects we need in the destructor.
gcHandle = GCHandle.Alloc(
new Tuple<GrpcConnection, RemoteValueRpcServiceClient, GrpcSbValue>(
connection, client, grpcSbValue));
}
~RemoteValueProxy()
{
connection
.GetOrCreateBulkDeleter<GrpcSbValue>()
.QueueForDeletion(grpcSbValue, (List<GrpcSbValue> values) =>
{
var request = new BulkDeleteRequest();
request.Values.AddRange(values);
connection.InvokeRpc(() =>
{
client.BulkDelete(request);
});
});
gcHandle.Free();
}
#region Prefetched properties
public string GetName()
{
return grpcSbValue.Name;
}
public SbError GetError()
{
return errorFactory.Create(grpcSbValue.Error);
}
#endregion
public GrpcSbValue GrpcValue => grpcSbValue;
public string GetValue(DebuggerApi.ValueFormat format)
{
GetValueResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.GetValue(
new GetValueRequest
{
Value = grpcSbValue,
Format = format.ConvertTo<Debugger.Common.ValueFormat>()
});
}))
{
return response.Value;
}
return "";
}
public SbType GetTypeInfo()
{
GetTypeInfoResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.GetTypeInfo(
new GetTypeInfoRequest { Value = grpcSbValue });
}))
{
if (response.Type != null && response.Type.Id != 0)
return typeFactory.Create(connection, response.Type);
}
return null;
}
public string GetTypeName()
{
GetTypeNameResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.GetTypeName(
new GetTypeNameRequest { Value = grpcSbValue });
}))
{
return response.TypeName;
}
return "";
}
public string GetSummary(DebuggerApi.ValueFormat format)
{
GetSummaryResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.GetSummary(
new GetSummaryRequest
{
Value = grpcSbValue,
Format = format.ConvertTo<Debugger.Common.ValueFormat>()
});
}))
{
return response.Summary;
}
return "";
}
public DebuggerApi.ValueType GetValueType()
{
GetValueTypeResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.GetValueType(
new GetValueTypeRequest { Value = grpcSbValue });
}))
{
return response.ValueType.ConvertTo<DebuggerApi.ValueType>();
}
return DebuggerApi.ValueType.Invalid;
}
public uint GetNumChildren()
{
GetNumChildrenResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.GetNumChildren(
new GetNumChildrenRequest { Value = grpcSbValue });
}))
{
return response.NumChildren;
}
return 0;
}
public List<RemoteValue> GetChildren(uint offset, uint count)
{
var values = Enumerable.Repeat<RemoteValue>(null, (int)count).ToList();
GetChildrenResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.GetChildren(
new GetChildrenRequest
{
Value = grpcSbValue,
Offset = offset,
Count = count
});
}))
{
for (uint n = 0; n < count; ++n)
{
GrpcSbValue sbValue;
if (response.Children != null &&
response.Children.TryGetValue(n + offset, out sbValue) &&
sbValue.Id != 0)
{
values[(int)n] = valueFactory.Create(connection, sbValue);
}
}
}
return values;
}
public RemoteValue CreateValueFromExpression(string name, string expression)
{
CreateValueFromExpressionResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.CreateValueFromExpression(
new CreateValueFromExpressionRequest
{ Value = grpcSbValue, Name = name, Expression = expression });
}))
{
if (response.ExpressionResult != null && response.ExpressionResult.Id != 0)
{
return valueFactory.Create(connection, response.ExpressionResult);
}
}
return null;
}
public RemoteValue CreateValueFromAddress(string name, ulong address, SbType type)
{
CreateValueFromAddressResponse response = null;
if (connection.InvokeRpc(() => {
response = client.CreateValueFromAddress(new CreateValueFromAddressRequest {
Value = grpcSbValue, Name = name, Address = address,
Type = new GrpcSbType { Id = type.GetId() }
});
}))
{
if (response.ExpressionResult != null && response.ExpressionResult.Id != 0)
{
return valueFactory.Create(connection, response.ExpressionResult);
}
}
return null;
}
public async Task<RemoteValue> CreateValueFromExpressionAsync(string name,
string expression)
{
CreateValueFromExpressionResponse response = null;
if (await connection.InvokeRpcAsync(async () =>
{
response = await client.CreateValueFromExpressionAsync(
new CreateValueFromExpressionRequest
{ Value = grpcSbValue, Name = name, Expression = expression });
}))
{
if (response.ExpressionResult != null && response.ExpressionResult.Id != 0)
{
return valueFactory.Create(connection, response.ExpressionResult);
}
}
return null;
}
public RemoteValue EvaluateExpression(string expression)
{
EvaluateExpressionResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.EvaluateExpression(
new EvaluateExpressionRequest
{ Value = grpcSbValue, Expression = expression });
}))
{
if (response.ExpressionResult != null && response.ExpressionResult.Id != 0)
{
return valueFactory.Create(connection, response.ExpressionResult);
}
}
return null;
}
public async Task<RemoteValue> EvaluateExpressionAsync(string expression)
{
EvaluateExpressionResponse response = null;
if (await connection.InvokeRpcAsync(async () =>
{
response = await client.EvaluateExpressionAsync(
new EvaluateExpressionRequest
{ Value = grpcSbValue, Expression = expression });
}))
{
if (response.ExpressionResult != null && response.ExpressionResult.Id != 0)
{
return valueFactory.Create(connection, response.ExpressionResult);
}
}
return null;
}
public async Task<RemoteValue> EvaluateExpressionLldbEvalAsync(
string expression, IDictionary<string, RemoteValue> contextVariables = null)
{
EvaluateExpressionLldbEvalRequest request =
new EvaluateExpressionLldbEvalRequest { Value = grpcSbValue,
Expression = expression };
if (contextVariables != null)
{
foreach (var variable in contextVariables)
{
request.ContextVariables.Add(
new ContextVariable { Name = variable.Key,
Value = variable.Value.GrpcValue });
}
}
EvaluateExpressionLldbEvalResponse response = null;
if (await connection.InvokeRpcAsync(async () => {
response = await client.EvaluateExpressionLldbEvalAsync(request);
}))
{
if (response.Value != null && response.Value.Id != 0)
{
return valueFactory.Create(connection, response.Value);
}
}
return null;
}
public RemoteValue Clone()
{
CloneResponse response = null;
if (connection.InvokeRpc(
() => { response = client.Clone(new CloneRequest { Value = grpcSbValue }); }))
{
if (response.CloneResult != null && response.CloneResult.Id != 0)
{
return valueFactory.Create(connection, response.CloneResult);
}
}
return null;
}
public RemoteValue Dereference()
{
DereferenceResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.Dereference(new DereferenceRequest{ Value = grpcSbValue });
}))
{
if (response.DereferenceResult != null && response.DereferenceResult.Id != 0)
{
return valueFactory.Create(connection, response.DereferenceResult);
}
}
return null;
}
public RemoteValue GetChildMemberWithName(string name)
{
GetChildMemberWithNameResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.GetChildMemberWithName(
new GetChildMemberWithNameRequest { Value = grpcSbValue, Name = name });
}))
{
if (response.Child != null && response.Child.Id != 0)
{
return valueFactory.Create(connection, response.Child);
}
}
return null;
}
public RemoteValue AddressOf()
{
AddressOfResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.AddressOf(
new AddressOfRequest { Value = grpcSbValue });
}))
{
if (response.AddressValue != null && response.AddressValue.Id != 0)
{
return valueFactory.Create(connection, response.AddressValue);
}
}
return null;
}
public bool TypeIsPointerType()
{
TypeIsPointerTypeResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.TypeIsPointerType(
new TypeIsPointerTypeRequest { Value = grpcSbValue });
}))
{
return response.IsPointer;
}
return false;
}
public RemoteValue GetValueForExpressionPath(string expressionPath)
{
GetValueForExpressionPathResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.GetValueForExpressionPath(
new GetValueForExpressionPathRequest
{
Value = grpcSbValue,
ExpressionPath = expressionPath
});
}))
{
if (response.Value != null && response.Value.Id != 0)
{
return valueFactory.Create(connection, response.Value);
}
}
return null;
}
public bool GetExpressionPath(out string path)
{
GetExpressionPathResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.GetExpressionPath(
new GetExpressionPathRequest { Value = grpcSbValue });
}))
{
path = response.Path;
return response.ReturnValue;
}
path = null;
return false;
}
public RemoteValue GetCachedView(DebuggerApi.ValueFormat format)
{
GetCachedViewResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.GetCachedView(
new GetCachedViewRequest
{
Value = grpcSbValue,
Format = format.ConvertTo<Debugger.Common.ValueFormat>()
});
}))
{
if (response.ValueInfo != null)
{
RemoteValue addressOf = null;
if (response.AddressValue != null && response.AddressValue.Id != 0)
{
addressOf = valueFactory.Create(connection, response.AddressValue);
if (response.AddressInfo != null)
{
// gRpc server does not set |format| on |addressOf|, so use default.
addressOf = CreateCachedValue(addressOf, response.AddressInfo, null,
DebuggerApi.ValueFormat.Default);
}
}
return CreateCachedValue(this, response.ValueInfo, addressOf, format);
}
}
return null;
}
public ulong GetByteSize()
{
GetByteSizeResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.GetByteSize(
new GetByteSizeRequest { Value = grpcSbValue });
}))
{
return response.ByteSize;
}
return 0;
}
public ulong GetValueAsUnsigned()
{
GetValueAsUnsignedResponse response = null;
if (connection.InvokeRpc(() => {
response = client.GetValueAsUnsigned(
new GetValueAsUnsignedRequest { Value = grpcSbValue });
}))
{
return response.Value;
}
return 0;
}
public byte[] GetPointeeAsByteString(uint charSize, uint maxStringSize, out string error)
{
GetPointeeAsByteStringResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.GetPointeeAsByteString(
new GetPointeeAsByteStringRequest
{
Value = grpcSbValue,
CharSize = charSize,
MaxStringSize = maxStringSize
});
}))
{
error = response.Error;
return response.Data.ToByteArray();
}
error = null;
return null;
}
private RemoteValue CreateCachedValue(
RemoteValue remoteProxy, GrpcValueInfo info, RemoteValue addressOf,
DebuggerApi.ValueFormat format) =>
cachedValueFactory.Create(
remoteProxy,
addressOf,
info.Type != null && info.Type.Id != 0 ?
typeFactory.Create(connection, info.Type) : null,
info.ExpressionPath,
info.HasExpressionPath,
info.NumChildren,
info.Summary,
info.TypeName,
info.Value,
EnumUtil.ConvertTo<DebuggerApi.ValueType>(info.ValueType),
info.IsPointerType,
format,
info.ByteSize);
}
}
| |
// MiniCpp.cs HDO, 2006-08-28
// ---------- SE, 2009-12-20
// Main program for MiniCpp compiler.
//=====================================|========================================
// *** start: not in Main.frm ***
#define GEN_SRC // (en|dis)able gen. of source text (with symbol table dump)
#define GEN_CIL_AS_TEXT // (en|dis)able CIL text generation and assembling to exe
#define GEN_CIL_REF_EMIT // (en|dis)able CIL generation with Reflection.Emit
#undef VERIFY_ASSEMBLY // (en|dis)able CIL verification with PEVerify.exe
#undef MEASURE_TIME // (en|dis)able time measurements for some phases
// *** end ***
using System;
using System.IO;
using Lex = MiniCppLex;
using Syn = MiniCppSyn;
public class MiniCpp {
private static String NAME = "MiniCpp";
private static void Abort(String abortKind, String moduleName,
String methName, String descr) {
Console.WriteLine();
Console.WriteLine("*** {0} in module {1} function {2}",
abortKind, moduleName, methName);
Console.WriteLine("*** {0}", descr);
Console.WriteLine();
Console.WriteLine();
Console.WriteLine(NAME + " aborted");
Utils.Modules(Utils.ModuleAction.cleanupModule);
Environment.Exit(Utils.EXIT_FAILURE);
} // Abort
private static void CompileFile(String srcFileName) {
try {
FileStream srcFs = new FileStream(srcFileName, FileMode.Open);
Lex.src = new StreamReader(srcFs);
} catch (Exception) {
Lex.src = null;
} // try/catch
if (Lex.src == null) {
Console.WriteLine("*** file \"{0}\" not found", srcFileName);
return;
} // if
Console.WriteLine("parsing \"" + srcFileName + "\" ...");
Syn.Parse();
Lex.src.Close();
Lex.src = null;
int extStart = srcFileName.LastIndexOf('.');
String lstFileName = srcFileName.Substring(0, extStart) + ".lst";
if (Errors.NumOfErrors() > 0) {
Console.WriteLine("{0} error(s) detected,", Errors.NumOfErrors());
Console.WriteLine(" listing to \"" + lstFileName + "\"...");
StreamWriter lst = null;
try {
FileStream lstFs = new FileStream(lstFileName, FileMode.Create);
lst = new StreamWriter(lstFs);
} catch (Exception) {
lst = null;
} // try/catch
if (lst == null) {
Utils.FatalError(NAME, "CompileFile", "file \"{0}\" not created", lstFileName);
return;
} // if
FileStream srcFs = new FileStream(srcFileName, FileMode.Open);
Lex.src = new StreamReader(srcFs);
lst.WriteLine(NAME + " (file: \"{0}\")", srcFileName);
Errors.GenerateListing(Lex.src, lst, Errors.ListingShape.longListing);
Lex.src.Close();
Lex.src = null;
lst.Close();
lst = null;
} else {
// *** start: not in Main.frm ***
if (File.Exists(lstFileName))
File.Delete(lstFileName);
String moduleName = (String)srcFileName.Clone();
String path = String.Empty;
int lastBackSlashIdx = moduleName.LastIndexOf('\\');
if (lastBackSlashIdx >= 0) {
path = moduleName.Substring(0, lastBackSlashIdx + 1);
moduleName = moduleName.Substring(lastBackSlashIdx + 1);
} // if
int periodIdx = moduleName.IndexOf('.');
if (periodIdx >= 0)
moduleName = moduleName.Substring(0, periodIdx);
#if GEN_SRC // symbol table gen. of source text with symbol table dump
StartTimer();
GenSrcText.DumpSymTabAndWriteSrcTxt(path, moduleName);
WriteElapsedTime("GenSrcText");
#endif
#if GEN_CIL_AS_TEXT // CIL generation to il-file and assembling to exe
StartTimer();
GenCilAsText.GenerateAssembly(path, moduleName + ".text");
WriteElapsedTime("GenCilAsText");
VerifyAssembly(path, moduleName);
#endif // GEN_CIL_AS_TEXT
#if GEN_CIL_REF_EMIT // CIL generation with Reflection.Emit
StartTimer();
GenCilByRefEmit.GenerateAssembly(path, moduleName+ ".emit");
WriteElapsedTime("GenCilByReflectionEmit");
VerifyAssembly(path, moduleName);
#endif
// *** end ***
Console.WriteLine("compilation completed successfully");
} // else
Utils.Modules(Utils.ModuleAction.resetModule);
} // CompileFile
// *** start: not in Main.frm ***
private static readonly System.Diagnostics.Stopwatch Timer =
new System.Diagnostics.Stopwatch();
[System.Diagnostics.Conditional("MEASURE_TIME")]
private static void WriteElapsedTime(string label) {
Console.WriteLine("elapsed time for '{0}': {1} ms",
label, Timer.ElapsedMilliseconds);
} // WriteElapsedTime
[System.Diagnostics.Conditional("MEASURE_TIME")]
private static void StartTimer() {
Timer.Reset();
Timer.Start();
} // StartTimer
[System.Diagnostics.Conditional("VERIFY_ASSEMBLY")]
private static void VerifyAssembly(string path, string moduleName) {
Console.WriteLine();
Console.WriteLine("PEverifying \"" + path + moduleName + ".exe ...");
string filename = moduleName;
if (!string.IsNullOrEmpty(path))
filename = path + moduleName;
using (System.Diagnostics.Process p = new System.Diagnostics.Process()) {
p.StartInfo.FileName = @"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\PEVerify.exe";
p.StartInfo.Arguments = "/NOLOGO " + filename + ".exe";
p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardOutput = true;
try {
p.Start();
String output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Console.Out.Write(output);
} catch (Exception e) {
Console.Out.WriteLine(e);
} // catch
} // using
Console.WriteLine();
} // VerifyAssembly
// *** end ***
public static void Main(String[] args) {
//-----------------------------------|----------------------------------------
// --- install modules ---
Utils.InstallModule("Utils", Utils.UtilsMethod);
Utils.InstallModule("Sets", Sets.SetsMethod);
Utils.InstallModule("Errors", Errors.ErrorsMethod);
Utils.InstallModule("MiniCppLex", MiniCppLex.MiniCppLexMethod);
Utils.InstallModule("MiniCppSem", MiniCppSem.MiniCppSemMethod);
Utils.InstallModule("MiniCppSyn", MiniCppSyn.MiniCppSynMethod);
// --- initialize modules ---
Utils.Modules(Utils.ModuleAction.initModule);
Errors.PushAbortMethod(Abort);
Console.WriteLine("--------------------------------");
Console.WriteLine(" {0} Compiler {1," + (5 - NAME.Length) +"} V. 3 2011 ", NAME, "");
Console.WriteLine(" Frontend generated with Coco-2");
Console.WriteLine("--------------------------------");
Console.WriteLine();
if (args.Length > 0) { // command line mode
Console.WriteLine();
int i = 0;
do {
Console.WriteLine("source file \"{0}\"", args[i]);
CompileFile(args[i]);
Console.WriteLine();
i++;
} while (i < args.Length);
} else { // args.Length == 0, interactive mode
for (;;) {
String srcFileName;
Utils.GetInputFileName("source file > ", out srcFileName);
if (srcFileName.Length > 0) {
// *** start: not in Main.frm ***
if (!srcFileName.EndsWith(".mcpp"))
srcFileName = srcFileName + ".mcpp";
if (!File.Exists(srcFileName)) {
srcFileName = ".\\#McppPrograms\\" + srcFileName;
if (!File.Exists(srcFileName)) {
srcFileName = "..\\..\\" + srcFileName;
} // if
} // if
// *** end ***
CompileFile(srcFileName);
} // if
char answerCh;
do {
Console.WriteLine();
Console.Write("[c]ontinue or [q]uit > ");
String answer = Console.ReadLine();
answerCh = answer.Length == 0 ? ' ' : Char.ToUpper(answer[0]);
} while (answerCh != 'C' && answerCh != 'Q');
if (answerCh == 'Q')
break;
Console.WriteLine();
} // for
} // else
Utils.Modules(Utils.ModuleAction.cleanupModule);
} // Main
} // MiniCpp
// End of MiniCpp.cs
//=====================================|========================================
| |
using System;
namespace Fixie.Tests.Lifecycle
{
public class CaseLifecycleTests : LifecycleTests
{
class Inner : CaseBehavior
{
public void Execute(Case @case, Action next)
{
Console.WriteLine("Inner Before");
next();
Console.WriteLine("Inner After");
}
}
class Outer : CaseBehavior
{
public void Execute(Case @case, Action next)
{
Console.WriteLine("Outer Before");
next();
Console.WriteLine("Outer After");
}
}
class DoNothing : CaseBehavior
{
public void Execute(Case @case, Action next)
{
//Behavior chooses not to invoke next().
//Since the cases are never invoked, they don't
//have the chance to throw exceptions, resulting
//in all 'passing'.
}
}
class ThrowException : CaseBehavior
{
public void Execute(Case @case, Action next)
{
Console.WriteLine("Unsafe case execution behavior");
throw new Exception("Unsafe case execution behavior threw!");
}
}
class ThrowPreservedException : CaseBehavior
{
public void Execute(Case @case, Action next)
{
Console.WriteLine("Unsafe case execution behavior");
try
{
throw new Exception("Unsafe case execution behavior threw!");
}
catch (Exception originalException)
{
throw new PreservedException(originalException);
}
}
}
public void ShouldAllowWrappingCaseWithBehaviorTypesWhenConstructingPerCase()
{
Convention.ClassExecution
.CreateInstancePerCase();
Convention.CaseExecution
.Wrap<Inner>()
.Wrap<Outer>();
var output = Run();
output.ShouldHaveResults(
"SampleTestClass.Pass passed.",
"SampleTestClass.Fail failed: 'Fail' failed!");
output.ShouldHaveLifecycle(
".ctor",
"Outer Before", "Inner Before",
"Pass",
"Inner After", "Outer After",
"Dispose",
".ctor",
"Outer Before", "Inner Before",
"Fail",
"Inner After", "Outer After",
"Dispose");
}
public void ShouldAllowWrappingCaseWithBehaviorTypesWhenConstructingPerClass()
{
Convention.ClassExecution
.CreateInstancePerClass();
Convention.CaseExecution
.Wrap<Inner>()
.Wrap<Outer>();
var output = Run();
output.ShouldHaveResults(
"SampleTestClass.Pass passed.",
"SampleTestClass.Fail failed: 'Fail' failed!");
output.ShouldHaveLifecycle(
".ctor",
"Outer Before", "Inner Before",
"Pass",
"Inner After", "Outer After",
"Outer Before", "Inner Before",
"Fail",
"Inner After", "Outer After",
"Dispose");
}
public void ShouldAllowWrappingCaseWithBehaviorInstancesWhenConstructingPerCase()
{
Convention.ClassExecution
.CreateInstancePerCase();
Convention.CaseExecution
.Wrap(new Inner())
.Wrap(new Outer());
var output = Run();
output.ShouldHaveResults(
"SampleTestClass.Pass passed.",
"SampleTestClass.Fail failed: 'Fail' failed!");
output.ShouldHaveLifecycle(
".ctor",
"Outer Before", "Inner Before",
"Pass",
"Inner After", "Outer After",
"Dispose",
".ctor",
"Outer Before", "Inner Before",
"Fail",
"Inner After", "Outer After",
"Dispose");
}
public void ShouldAllowWrappingCaseWithBehaviorInstancesWhenConstructingPerClass()
{
Convention.ClassExecution
.CreateInstancePerClass();
Convention.CaseExecution
.Wrap(new Inner())
.Wrap(new Outer());
var output = Run();
output.ShouldHaveResults(
"SampleTestClass.Pass passed.",
"SampleTestClass.Fail failed: 'Fail' failed!");
output.ShouldHaveLifecycle(
".ctor",
"Outer Before", "Inner Before",
"Pass",
"Inner After", "Outer After",
"Outer Before", "Inner Before",
"Fail",
"Inner After", "Outer After",
"Dispose");
}
public void ShouldAllowWrappingCaseWithBehaviorLambdasWhenConstructingPerCase()
{
Convention.ClassExecution
.CreateInstancePerCase();
Convention.CaseExecution
.Wrap((@case, next) =>
{
Console.WriteLine("Inner Before");
next();
Console.WriteLine("Inner After");
})
.Wrap((@case, next) =>
{
Console.WriteLine("Outer Before");
next();
Console.WriteLine("Outer After");
});
var output = Run();
output.ShouldHaveResults(
"SampleTestClass.Pass passed.",
"SampleTestClass.Fail failed: 'Fail' failed!");
output.ShouldHaveLifecycle(
".ctor",
"Outer Before", "Inner Before",
"Pass",
"Inner After", "Outer After",
"Dispose",
".ctor",
"Outer Before", "Inner Before",
"Fail",
"Inner After", "Outer After",
"Dispose");
}
public void ShouldAllowWrappingCaseWithBehaviorLambdasWhenConstructingPerClass()
{
Convention.ClassExecution
.CreateInstancePerClass();
Convention.CaseExecution
.Wrap((@case, next) =>
{
Console.WriteLine("Inner Before");
next();
Console.WriteLine("Inner After");
})
.Wrap((@case, next) =>
{
Console.WriteLine("Outer Before");
next();
Console.WriteLine("Outer After");
});
var output = Run();
output.ShouldHaveResults(
"SampleTestClass.Pass passed.",
"SampleTestClass.Fail failed: 'Fail' failed!");
output.ShouldHaveLifecycle(
".ctor",
"Outer Before", "Inner Before",
"Pass",
"Inner After", "Outer After",
"Outer Before", "Inner Before",
"Fail",
"Inner After", "Outer After",
"Dispose");
}
public void ShouldAllowCaseBehaviorsToShortCircuitInnerBehaviorWhenConstructingPerCase()
{
Convention.ClassExecution
.CreateInstancePerCase();
Convention.CaseExecution
.Wrap<DoNothing>();
var output = Run();
output.ShouldHaveResults(
"SampleTestClass.Pass passed.",
"SampleTestClass.Fail passed.");
output.ShouldHaveLifecycle(
".ctor",
"Dispose",
".ctor",
"Dispose");
}
public void ShouldAllowCaseBehaviorsToShortCircuitInnerBehaviorWhenConstructingPerClass()
{
Convention.ClassExecution
.CreateInstancePerClass();
Convention.CaseExecution
.Wrap<DoNothing>();
var output = Run();
output.ShouldHaveResults(
"SampleTestClass.Pass passed.",
"SampleTestClass.Fail passed.");
output.ShouldHaveLifecycle(
".ctor",
"Dispose");
}
public void ShouldFailCaseWhenConstructingPerCaseAndCaseBehaviorThrows()
{
Convention.ClassExecution
.CreateInstancePerCase();
Convention.CaseExecution
.Wrap<ThrowException>();
var output = Run();
output.ShouldHaveResults(
"SampleTestClass.Pass failed: Unsafe case execution behavior threw!",
"SampleTestClass.Fail failed: Unsafe case execution behavior threw!");
output.ShouldHaveLifecycle(
".ctor",
"Unsafe case execution behavior",
"Dispose",
".ctor",
"Unsafe case execution behavior",
"Dispose");
}
public void ShouldFailAllCasesWhenConstructingPerClassAndCaseBehaviorThrows()
{
Convention.ClassExecution
.CreateInstancePerClass();
Convention.CaseExecution
.Wrap<ThrowException>();
var output = Run();
output.ShouldHaveResults(
"SampleTestClass.Pass failed: Unsafe case execution behavior threw!",
"SampleTestClass.Fail failed: Unsafe case execution behavior threw!");
output.ShouldHaveLifecycle(
".ctor",
"Unsafe case execution behavior",
"Unsafe case execution behavior",
"Dispose");
}
public void ShouldFailCaseWithOriginalExceptionWhenConstructingPerCaseAndCaseBehaviorThrowsPreservedException()
{
Convention.ClassExecution
.CreateInstancePerCase();
Convention.CaseExecution
.Wrap<ThrowPreservedException>();
var output = Run();
output.ShouldHaveResults(
"SampleTestClass.Pass failed: Unsafe case execution behavior threw!",
"SampleTestClass.Fail failed: Unsafe case execution behavior threw!");
output.ShouldHaveLifecycle(
".ctor",
"Unsafe case execution behavior",
"Dispose",
".ctor",
"Unsafe case execution behavior",
"Dispose");
}
public void ShouldFailAllCasesWithOriginalExceptionWhenConstructingPerClassAndCaseBehaviorThrowsPreservedException()
{
Convention.ClassExecution
.CreateInstancePerClass();
Convention.CaseExecution
.Wrap<ThrowPreservedException>();
var output = Run();
output.ShouldHaveResults(
"SampleTestClass.Pass failed: Unsafe case execution behavior threw!",
"SampleTestClass.Fail failed: Unsafe case execution behavior threw!");
output.ShouldHaveLifecycle(
".ctor",
"Unsafe case execution behavior",
"Unsafe case execution behavior",
"Dispose");
}
public void ShouldAllowWrappingCaseWithSetUpTearDownBehaviorsWhenConstructingPerCase()
{
Convention.ClassExecution
.CreateInstancePerCase();
Convention.CaseExecution
.Wrap<CaseSetUpTearDown>();
var output = Run();
output.ShouldHaveResults(
"SampleTestClass.Pass passed.",
"SampleTestClass.Fail failed: 'Fail' failed!");
output.ShouldHaveLifecycle(
".ctor",
"CaseSetUp", "Pass", "CaseTearDown",
"Dispose",
".ctor",
"CaseSetUp", "Fail", "CaseTearDown",
"Dispose");
}
public void ShouldAllowWrappingCaseWithSetUpTearDownBehaviorsWhenConstructingPerClass()
{
Convention.ClassExecution
.CreateInstancePerClass();
Convention.CaseExecution
.Wrap<CaseSetUpTearDown>();
var output = Run();
output.ShouldHaveResults(
"SampleTestClass.Pass passed.",
"SampleTestClass.Fail failed: 'Fail' failed!");
output.ShouldHaveLifecycle(
".ctor",
"CaseSetUp", "Pass", "CaseTearDown",
"CaseSetUp", "Fail", "CaseTearDown",
"Dispose");
}
public void ShouldShortCircuitInnerBehaviorAndTearDownByFailingCaseWhenConstructingPerCaseAndCaseSetUpThrows()
{
FailDuring("CaseSetUp");
Convention.ClassExecution
.CreateInstancePerCase();
Convention.CaseExecution
.Wrap<CaseSetUpTearDown>();
var output = Run();
output.ShouldHaveResults(
"SampleTestClass.Pass failed: 'CaseSetUp' failed!",
"SampleTestClass.Fail failed: 'CaseSetUp' failed!");
output.ShouldHaveLifecycle(
".ctor",
"CaseSetUp",
"Dispose",
".ctor",
"CaseSetUp",
"Dispose");
}
public void ShouldShortCircuitInnerBehaviorAndTearDownByFailingAllCasesWhenConstructingPerClassAndCaseSetUpThrows()
{
FailDuring("CaseSetUp");
Convention.ClassExecution
.CreateInstancePerClass();
Convention.CaseExecution
.Wrap<CaseSetUpTearDown>();
var output = Run();
output.ShouldHaveResults(
"SampleTestClass.Pass failed: 'CaseSetUp' failed!",
"SampleTestClass.Fail failed: 'CaseSetUp' failed!");
output.ShouldHaveLifecycle(
".ctor",
"CaseSetUp",
"CaseSetUp",
"Dispose");
}
public void ShouldFailCaseWhenConstructingPerCaseAndCaseTearDownThrows()
{
FailDuring("CaseTearDown");
Convention.ClassExecution
.CreateInstancePerCase();
Convention.CaseExecution
.Wrap<CaseSetUpTearDown>();
var output = Run();
output.ShouldHaveResults(
"SampleTestClass.Pass failed: 'CaseTearDown' failed!",
"SampleTestClass.Fail failed: 'Fail' failed!" + Environment.NewLine +
" Secondary Failure: 'CaseTearDown' failed!");
output.ShouldHaveLifecycle(
".ctor",
"CaseSetUp", "Pass", "CaseTearDown",
"Dispose",
".ctor",
"CaseSetUp", "Fail", "CaseTearDown",
"Dispose");
}
public void ShouldFailAllCasesWhenConstructingPerClassAndCaseTearDownThrows()
{
FailDuring("CaseTearDown");
Convention.ClassExecution
.CreateInstancePerClass();
Convention.CaseExecution
.Wrap<CaseSetUpTearDown>();
var output = Run();
output.ShouldHaveResults(
"SampleTestClass.Pass failed: 'CaseTearDown' failed!",
"SampleTestClass.Fail failed: 'Fail' failed!" + Environment.NewLine +
" Secondary Failure: 'CaseTearDown' failed!");
output.ShouldHaveLifecycle(
".ctor",
"CaseSetUp", "Pass", "CaseTearDown",
"CaseSetUp", "Fail", "CaseTearDown",
"Dispose");
}
}
}
| |
// Copyright (C) 2004-2007 MySQL AB
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as published by
// the Free Software Foundation
//
// There are special exceptions to the terms and conditions of the GPL
// as it is applied to this software. View the full text of the
// exception in file EXCEPTIONS in the directory of this software
// distribution.
//
// 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
using System;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Text;
using IsolationLevel=System.Data.IsolationLevel;
using MySql.Data.Common;
using System.Diagnostics;
using MySql.Data.MySqlClient.Properties;
namespace MySql.Data.MySqlClient
{
/// <include file='docs/MySqlConnection.xml' path='docs/ClassSummary/*'/>
public sealed class MySqlConnection : DbConnection
{
internal ConnectionState connectionState;
internal Driver driver;
private MySqlDataReader dataReader;
private MySqlConnectionStringBuilder settings;
private UsageAdvisor advisor;
private bool hasBeenOpen;
private ProcedureCache procedureCache;
private bool isExecutingBuggyQuery;
private string database;
/// <include file='docs/MySqlConnection.xml' path='docs/InfoMessage/*'/>
public event MySqlInfoMessageEventHandler InfoMessage;
private static Cache<string, MySqlConnectionStringBuilder> connectionStringCache =
new Cache<string, MySqlConnectionStringBuilder>(0, 25);
/// <include file='docs/MySqlConnection.xml' path='docs/DefaultCtor/*'/>
public MySqlConnection()
{
//TODO: add event data to StateChange docs
settings = new MySqlConnectionStringBuilder();
advisor = new UsageAdvisor(this);
database = String.Empty;
}
/// <include file='docs/MySqlConnection.xml' path='docs/Ctor1/*'/>
public MySqlConnection(string connectionString)
: this()
{
ConnectionString = connectionString;
}
#region Interal Methods & Properties
internal ProcedureCache ProcedureCache
{
get { return procedureCache; }
}
internal MySqlConnectionStringBuilder Settings
{
get { return settings; }
}
internal MySqlDataReader Reader
{
get { return dataReader; }
set { dataReader = value; }
}
internal void OnInfoMessage(MySqlInfoMessageEventArgs args)
{
if (InfoMessage != null)
{
InfoMessage(this, args);
}
}
internal bool IsExecutingBuggyQuery
{
get { return isExecutingBuggyQuery; }
set { isExecutingBuggyQuery = value; }
}
internal bool SoftClosed
{
get
{
return false;
}
}
#endregion
#region Properties
internal UsageAdvisor UsageAdvisor
{
get { return advisor; }
}
internal DataTable GetSchema(string v, string[] restrictions)
{
throw new NotImplementedException();
}
/// <summary>
/// Returns the id of the server thread this connection is executing on
/// </summary>
public int ServerThread
{
get { return driver.ThreadID; }
}
/// <summary>
/// Gets the name of the MySQL server to which to connect.
/// </summary>
public override string DataSource
{
get { return settings.Server; }
}
/// <include file='docs/MySqlConnection.xml' path='docs/ConnectionTimeout/*'/>
public override int ConnectionTimeout
{
get { return (int) settings.ConnectionTimeout; }
}
/// <include file='docs/MySqlConnection.xml' path='docs/Database/*'/>
public override string Database
{
get { return database; }
}
/// <summary>
/// Indicates if this connection should use compression when communicating with the server.
/// </summary>
public bool UseCompression
{
get { return settings.UseCompression; }
}
/// <include file='docs/MySqlConnection.xml' path='docs/State/*'/>
public override ConnectionState State
{
get { return connectionState; }
}
/// <include file='docs/MySqlConnection.xml' path='docs/ServerVersion/*'/>
public override string ServerVersion
{
get { return driver.Version.ToString(); }
}
internal Encoding Encoding
{
get
{
if (driver == null)
return Encoding.UTF8;
else
return driver.Encoding;
}
}
/// <include file='docs/MySqlConnection.xml' path='docs/ConnectionString/*'/>
public override string ConnectionString
{
get
{
// Always return exactly what the user set.
// Security-sensitive information may be removed.
return settings.GetConnectionString(!hasBeenOpen || settings.PersistSecurityInfo);
}
set
{
if (State != ConnectionState.Closed)
throw new MySqlException(
"Not allowed to change the 'ConnectionString' property while the connection (state=" + State +
").");
MySqlConnectionStringBuilder newSettings;
lock (connectionStringCache)
{
if (value == null)
newSettings = new MySqlConnectionStringBuilder();
else
{
newSettings = (MySqlConnectionStringBuilder)connectionStringCache[value];
if (null == newSettings)
{
newSettings = new MySqlConnectionStringBuilder(value);
connectionStringCache.Add(value, newSettings);
}
}
}
settings = newSettings;
if (settings.Database != null && settings.Database.Length > 0)
this.database = settings.Database;
if (driver != null)
driver.Settings = newSettings;
}
}
#endregion
#region Transactions
/// <include file='docs/MySqlConnection.xml' path='docs/BeginTransaction/*'/>
public new MySqlTransaction BeginTransaction()
{
return BeginTransaction(IsolationLevel.RepeatableRead);
}
/// <include file='docs/MySqlConnection.xml' path='docs/BeginTransaction1/*'/>
public new MySqlTransaction BeginTransaction(IsolationLevel iso)
{
//TODO: check note in help
if (State != ConnectionState.Open)
throw new InvalidOperationException(Resources.ConnectionNotOpen);
// First check to see if we are in a current transaction
if ((driver.ServerStatus & ServerStatusFlags.InTransaction) != 0)
throw new InvalidOperationException(Resources.NoNestedTransactions);
MySqlTransaction t = new MySqlTransaction(this, iso);
MySqlCommand cmd = new MySqlCommand("", this);
cmd.CommandText = "SET SESSION TRANSACTION ISOLATION LEVEL ";
switch (iso)
{
case IsolationLevel.ReadCommitted:
cmd.CommandText += "READ COMMITTED";
break;
case IsolationLevel.ReadUncommitted:
cmd.CommandText += "READ UNCOMMITTED";
break;
case IsolationLevel.RepeatableRead:
cmd.CommandText += "REPEATABLE READ";
break;
case IsolationLevel.Serializable:
cmd.CommandText += "SERIALIZABLE";
break;
case IsolationLevel.Chaos:
throw new NotSupportedException(Resources.ChaosNotSupported);
}
cmd.ExecuteNonQuery();
cmd.CommandText = "BEGIN";
cmd.ExecuteNonQuery();
return t;
}
#endregion
/// <include file='docs/MySqlConnection.xml' path='docs/ChangeDatabase/*'/>
public override void ChangeDatabase(string databaseName)
{
if (databaseName == null || databaseName.Trim().Length == 0)
throw new ArgumentException(Resources.ParameterIsInvalid, "databaseName");
if (State != ConnectionState.Open)
throw new InvalidOperationException(Resources.ConnectionNotOpen);
driver.SetDatabase(databaseName);
this.database = databaseName;
}
internal void SetState(ConnectionState newConnectionState, bool broadcast)
{
if (newConnectionState == connectionState && !broadcast)
return;
ConnectionState oldConnectionState = connectionState;
connectionState = newConnectionState;
if (broadcast)
OnStateChange(new StateChangeEventArgs(oldConnectionState, connectionState));
}
/// <summary>
/// Ping
/// </summary>
/// <returns></returns>
public bool Ping()
{
if (driver != null && driver.Ping())
return true;
driver = null;
SetState(ConnectionState.Closed, true);
return false;
}
/// <include file='docs/MySqlConnection.xml' path='docs/Open/*'/>
public override void Open()
{
if (State == ConnectionState.Open)
throw new InvalidOperationException(Resources.ConnectionAlreadyOpen);
SetState(ConnectionState.Connecting, true);
try
{
if (settings.Pooling)
{
MySqlPool pool = MySqlPoolManager.GetPool(settings);
if (driver == null)
driver = pool.GetConnection();
procedureCache = pool.ProcedureCache;
}
else
{
if (driver == null)
driver = Driver.Create(settings);
procedureCache = new ProcedureCache((int) settings.ProcedureCacheSize);
}
}
catch (Exception)
{
SetState(ConnectionState.Closed, true);
throw;
}
// if the user is using old syntax, let them know
if (driver.Settings.UseOldSyntax)
Logger.LogWarning("You are using old syntax that will be removed in future versions");
SetState(ConnectionState.Open, false);
driver.Configure(this);
if (settings.Database != null && settings.Database != String.Empty)
ChangeDatabase(settings.Database);
// if we are opening up inside a current transaction, then autoenlist
// TODO: control this with a connection string option
hasBeenOpen = true;
SetState(ConnectionState.Open, true);
}
/// <include file='docs/MySqlConnection.xml' path='docs/CreateCommand/*'/>
public new MySqlCommand CreateCommand()
{
// Return a new instance of a command object.
MySqlCommand c = new MySqlCommand();
c.Connection = this;
return c;
}
#region IDisposeable
protected override void Dispose(bool disposing)
{
if (disposing && State == ConnectionState.Open)
Close();
base.Dispose(disposing);
}
#endregion
protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
{
if (isolationLevel == IsolationLevel.Unspecified)
return BeginTransaction();
return BeginTransaction(isolationLevel);
}
protected override DbCommand CreateDbCommand()
{
return CreateCommand();
}
internal void Abort()
{
try
{
if (settings.Pooling)
MySqlPoolManager.ReleaseConnection(driver);
else
driver.Close();
}
catch (Exception)
{
}
SetState(ConnectionState.Closed, true);
}
internal void CloseFully()
{
if (settings.Pooling && driver.IsOpen)
{
// if we are in a transaction, roll it back
if ((driver.ServerStatus & ServerStatusFlags.InTransaction) != 0)
{
MySqlTransaction t = new MySqlTransaction(this, IsolationLevel.Unspecified);
t.Rollback();
}
MySqlPoolManager.ReleaseConnection(driver);
}
else
driver.Close();
driver = null;
}
/// <include file='docs/MySqlConnection.xml' path='docs/Close/*'/>
public override void Close()
{
if (State == ConnectionState.Closed) return;
if (dataReader != null)
dataReader.Close();
// if the reader was opened with CloseConnection then driver
// will be null on the second time through
if (driver != null)
{
CloseFully();
}
SetState(ConnectionState.Closed, true);
}
internal string CurrentDatabase()
{
if (Database != null && Database.Length > 0)
return Database;
MySqlCommand cmd = new MySqlCommand("SELECT database()", this);
return cmd.ExecuteScalar().ToString();
}
#region Pool Routines
/// <include file='docs/MySqlConnection.xml' path='docs/ClearPool/*'/>
public static void ClearPool(MySqlConnection connection)
{
MySqlPoolManager.ClearPool(connection.Settings);
}
/// <include file='docs/MySqlConnection.xml' path='docs/ClearAllPools/*'/>
public static void ClearAllPools()
{
MySqlPoolManager.ClearAllPools();
}
#endregion
}
/// <summary>
/// Represents the method that will handle the <see cref="MySqlConnection.InfoMessage"/> event of a
/// <see cref="MySqlConnection"/>.
/// </summary>
public delegate void MySqlInfoMessageEventHandler(object sender, MySqlInfoMessageEventArgs args);
/// <summary>
/// Provides data for the InfoMessage event. This class cannot be inherited.
/// </summary>
public class MySqlInfoMessageEventArgs : EventArgs
{
/// <summary>
///
/// </summary>
public MySqlError[] errors;
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Runtime;
using Orleans.Streams;
namespace Orleans
{
/// <summary>
/// Client for communicating with clusters of Orleans silos.
/// </summary>
internal class ClusterClient : IInternalClusterClient
{
private readonly OutsideRuntimeClient runtimeClient;
private readonly ClusterClientLifecycle clusterClientLifecycle;
private readonly AsyncLock initLock = new AsyncLock();
private LifecycleState state = LifecycleState.Created;
private enum LifecycleState
{
Invalid,
Created,
Starting,
Started,
Disposing,
Disposed,
}
/// <summary>
/// Initializes a new instance of the <see cref="ClusterClient"/> class.
/// </summary>
/// <param name="runtimeClient">The runtime client.</param>
/// <param name="loggerFactory">Logger factory used to create loggers</param>
/// <param name="clientMessagingOptions">Messaging parameters</param>
public ClusterClient(OutsideRuntimeClient runtimeClient, ILoggerFactory loggerFactory, IOptions<ClientMessagingOptions> clientMessagingOptions)
{
this.runtimeClient = runtimeClient;
this.clusterClientLifecycle = new ClusterClientLifecycle(loggerFactory.CreateLogger<LifecycleSubject>());
//set PropagateActivityId flag from node cofnig
RequestContext.PropagateActivityId = clientMessagingOptions.Value.PropagateActivityId;
// register all lifecycle participants
IEnumerable<ILifecycleParticipant<IClusterClientLifecycle>> lifecycleParticipants = this.ServiceProvider.GetServices<ILifecycleParticipant<IClusterClientLifecycle>>();
foreach (ILifecycleParticipant<IClusterClientLifecycle> participant in lifecycleParticipants)
{
participant?.Participate(clusterClientLifecycle);
}
// register all named lifecycle participants
IKeyedServiceCollection<string, ILifecycleParticipant<IClusterClientLifecycle>> namedLifecycleParticipantCollections = this.ServiceProvider.GetService<IKeyedServiceCollection<string, ILifecycleParticipant<IClusterClientLifecycle>>>();
foreach (ILifecycleParticipant<IClusterClientLifecycle> participant in namedLifecycleParticipantCollections
?.GetServices(this.ServiceProvider)
?.Select(s => s?.GetService(this.ServiceProvider)))
{
participant?.Participate(clusterClientLifecycle);
}
}
/// <inheritdoc />
public bool IsInitialized => this.state == LifecycleState.Started;
/// <inheritdoc />
public IGrainFactory GrainFactory => this.InternalGrainFactory;
/// <inheritdoc />
public IServiceProvider ServiceProvider => this.runtimeClient.ServiceProvider;
/// <inheritdoc />
IStreamProviderRuntime IInternalClusterClient.StreamProviderRuntime => this.runtimeClient.CurrentStreamProviderRuntime;
/// <inheritdoc />
private IInternalGrainFactory InternalGrainFactory
{
get
{
this.ThrowIfDisposedOrNotInitialized();
return this.runtimeClient.InternalGrainFactory;
}
}
/// <summary>
/// Gets a value indicating whether or not this instance is being disposed.
/// </summary>
private bool IsDisposing => this.state == LifecycleState.Disposed ||
this.state == LifecycleState.Disposing;
/// <inheritdoc />
public IStreamProvider GetStreamProvider(string name)
{
this.ThrowIfDisposedOrNotInitialized();
if (string.IsNullOrWhiteSpace(name))
{
throw new ArgumentNullException(nameof(name));
}
return this.runtimeClient.ServiceProvider.GetRequiredServiceByName<IStreamProvider>(name);
}
/// <inheritdoc />
public async Task Connect(Func<Exception, Task<bool>> retryFilter = null)
{
this.ThrowIfDisposedOrAlreadyInitialized();
using (await this.initLock.LockAsync().ConfigureAwait(false))
{
this.ThrowIfDisposedOrAlreadyInitialized();
if (this.state == LifecycleState.Starting)
{
throw new InvalidOperationException("A prior connection attempt failed. This instance must be disposed.");
}
this.state = LifecycleState.Starting;
await this.runtimeClient.Start(retryFilter).ConfigureAwait(false);
await this.clusterClientLifecycle.OnStart().ConfigureAwait(false);
this.state = LifecycleState.Started;
}
}
/// <inheritdoc />
public Task Close() => this.Stop(gracefully: true);
/// <inheritdoc />
public void Abort()
{
this.Stop(gracefully: false).GetAwaiter().GetResult();
}
private async Task Stop(bool gracefully)
{
if (this.IsDisposing) return;
using (await this.initLock.LockAsync().ConfigureAwait(false))
{
if (this.state == LifecycleState.Disposed) return;
try
{
this.state = LifecycleState.Disposing;
CancellationToken canceled = CancellationToken.None;
if (!gracefully)
{
var cts = new CancellationTokenSource();
cts.Cancel();
canceled = cts.Token;
}
await this.clusterClientLifecycle.OnStop(canceled);
if (gracefully)
{
Utils.SafeExecute(() => this.runtimeClient.Disconnect());
}
Utils.SafeExecute(() => this.runtimeClient.Reset(gracefully));
this.Dispose(true);
}
finally
{
// If disposal failed, the system is in an invalid state.
if (this.state == LifecycleState.Disposing) this.state = LifecycleState.Invalid;
}
}
}
/// <inheritdoc />
void IDisposable.Dispose() => this.Abort();
/// <inheritdoc />
public TGrainInterface GetGrain<TGrainInterface>(Guid primaryKey, string grainClassNamePrefix = null)
where TGrainInterface : IGrainWithGuidKey
{
return this.InternalGrainFactory.GetGrain<TGrainInterface>(primaryKey, grainClassNamePrefix);
}
/// <inheritdoc />
public TGrainInterface GetGrain<TGrainInterface>(long primaryKey, string grainClassNamePrefix = null)
where TGrainInterface : IGrainWithIntegerKey
{
return this.InternalGrainFactory.GetGrain<TGrainInterface>(primaryKey, grainClassNamePrefix);
}
/// <inheritdoc />
public TGrainInterface GetGrain<TGrainInterface>(string primaryKey, string grainClassNamePrefix = null)
where TGrainInterface : IGrainWithStringKey
{
return this.InternalGrainFactory.GetGrain<TGrainInterface>(primaryKey, grainClassNamePrefix);
}
/// <inheritdoc />
public TGrainInterface GetGrain<TGrainInterface>(Guid primaryKey, string keyExtension, string grainClassNamePrefix = null)
where TGrainInterface : IGrainWithGuidCompoundKey
{
return this.InternalGrainFactory.GetGrain<TGrainInterface>(primaryKey, keyExtension, grainClassNamePrefix);
}
/// <inheritdoc />
public TGrainInterface GetGrain<TGrainInterface>(long primaryKey, string keyExtension, string grainClassNamePrefix = null)
where TGrainInterface : IGrainWithIntegerCompoundKey
{
return this.InternalGrainFactory.GetGrain<TGrainInterface>(primaryKey, keyExtension, grainClassNamePrefix);
}
/// <inheritdoc />
public Task<TGrainObserverInterface> CreateObjectReference<TGrainObserverInterface>(IGrainObserver obj)
where TGrainObserverInterface : IGrainObserver
{
return ((IGrainFactory) this.runtimeClient.InternalGrainFactory).CreateObjectReference<TGrainObserverInterface>(obj);
}
/// <inheritdoc />
public Task DeleteObjectReference<TGrainObserverInterface>(IGrainObserver obj) where TGrainObserverInterface : IGrainObserver
{
return this.InternalGrainFactory.DeleteObjectReference<TGrainObserverInterface>(obj);
}
/// <inheritdoc />
public void BindGrainReference(IAddressable grain)
{
this.InternalGrainFactory.BindGrainReference(grain);
}
/// <inheritdoc />
public TGrainObserverInterface CreateObjectReference<TGrainObserverInterface>(IAddressable obj)
where TGrainObserverInterface : IAddressable
{
return this.InternalGrainFactory.CreateObjectReference<TGrainObserverInterface>(obj);
}
/// <inheritdoc />
TGrainInterface IInternalGrainFactory.GetSystemTarget<TGrainInterface>(GrainId grainId, SiloAddress destination)
{
return this.InternalGrainFactory.GetSystemTarget<TGrainInterface>(grainId, destination);
}
/// <inheritdoc />
TGrainInterface IInternalGrainFactory.Cast<TGrainInterface>(IAddressable grain)
{
return this.InternalGrainFactory.Cast<TGrainInterface>(grain);
}
/// <inheritdoc />
object IInternalGrainFactory.Cast(IAddressable grain, Type interfaceType)
{
return this.InternalGrainFactory.Cast(grain, interfaceType);
}
/// <inheritdoc />
TGrainInterface IInternalGrainFactory.GetGrain<TGrainInterface>(GrainId grainId)
{
return this.InternalGrainFactory.GetGrain<TGrainInterface>(grainId);
}
/// <inheritdoc />
GrainReference IInternalGrainFactory.GetGrain(GrainId grainId, string genericArguments)
{
return this.InternalGrainFactory.GetGrain(grainId, genericArguments);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed")]
private void Dispose(bool disposing)
{
if (disposing)
{
Utils.SafeExecute(() => this.runtimeClient.Dispose());
this.state = LifecycleState.Disposed;
}
GC.SuppressFinalize(this);
}
private void ThrowIfDisposedOrNotInitialized()
{
this.ThrowIfDisposed();
if (!this.IsInitialized) throw new InvalidOperationException($"Client is not initialized. Current client state is {this.state}.");
}
private void ThrowIfDisposedOrAlreadyInitialized()
{
this.ThrowIfDisposed();
if (this.IsInitialized) throw new InvalidOperationException("Client is already initialized.");
}
private void ThrowIfDisposed()
{
if (this.IsDisposing)
throw new ObjectDisposedException(
nameof(ClusterClient),
$"Client has been disposed either by a call to {nameof(Dispose)} or because it has been stopped.");
}
}
}
| |
//
// Copyright (C) DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
namespace Cassandra
{
/// <summary>
/// <para>Represents the options related to connection pooling.</para>
/// <para>
/// For each host selected by the load balancing policy, the driver keeps a core amount of
/// connections open at all times
/// (<see cref="PoolingOptions.GetCoreConnectionsPerHost(HostDistance)"/>).
/// If the use of those connections reaches a configurable threshold
/// (<see cref="PoolingOptions.GetMaxSimultaneousRequestsPerConnectionTreshold(HostDistance)"/>),
/// more connections are created up to the configurable maximum number of connections
/// (<see cref="PoolingOptions.GetMaxConnectionPerHost(HostDistance)"/>).
/// </para>
/// <para>
/// The driver uses connections in an asynchronous manner and multiple requests can be
/// submitted on the same connection at the same time without waiting for a response.
/// This means that the driver only needs to maintain a relatively small number of connections
/// to each Cassandra host. The <see cref="PoolingOptions"/> allows you to to control how many
/// connections are kept per host.
/// </para>
/// <para>
/// Each of these parameters can be separately set for <see cref="HostDistance.Local"/> and
/// <see cref="HostDistance.Remote"/> hosts. For <see cref="HostDistance.Ignored"/> hosts,
/// the default for all those settings is 0 and cannot be changed.
/// </para>
/// <para>
/// The default amount of connections depend on the Cassandra version of the Cluster, as newer
/// versions of Cassandra (2.1 and above) support a higher number of in-flight requests.
/// </para>
/// <para>For Cassandra 2.1 and above, the default amount of connections per host are:</para>
/// <list type="bullet">
/// <item>Local datacenter: 1 core connection per host, with 2 connections as maximum when the simultaneous
/// requests threshold is reached.</item>
/// <item>Remote datacenter: 1 core connection per host (being 1 also max).</item>
/// </list>
/// <para>For older Cassandra versions (1.2 and 2.0), the default amount of connections per host are:</para>
/// <list type="bullet">
/// <item>Local datacenter: 2 core connection per host, with 8 connections as maximum when the simultaneous
/// requests threshold is reached.</item>
/// <item>Remote datacenter: 1 core connection per host (being 2 the maximum).</item>
/// </list>
/// </summary>
public class PoolingOptions
{
//the defaults target small number concurrent requests (protocol 1 and 2) and multiple connections to a host
private const int DefaultMinRequests = 25;
private const int DefaultMaxRequestsThreshold = 128;
private const int DefaultCorePoolLocal = 2;
private const int DefaultCorePoolRemote = 1;
private const int DefaultMaxPoolLocal = 8;
private const int DefaultMaxPoolRemote = 2;
/// <summary>
/// Default maximum amount of requests that can be in-flight on a single connection at the same time after
/// which the connection will start rejecting requests: 2048.
/// </summary>
public const int DefaultMaxRequestsPerConnection = 2048;
/// <summary>
/// The default heartbeat interval in milliseconds: 30000.
/// </summary>
public const int DefaultHeartBeatInterval = 30000;
private int _coreConnectionsForLocal = DefaultCorePoolLocal;
private int _coreConnectionsForRemote = DefaultCorePoolRemote;
private int _maxConnectionsForLocal = DefaultMaxPoolLocal;
private int _maxConnectionsForRemote = DefaultMaxPoolRemote;
private int _maxSimultaneousRequestsForLocal = DefaultMaxRequestsThreshold;
private int _maxSimultaneousRequestsForRemote = DefaultMaxRequestsThreshold;
private int _minSimultaneousRequestsForLocal = DefaultMinRequests;
private int _minSimultaneousRequestsForRemote = DefaultMinRequests;
private int _heartBeatInterval = DefaultHeartBeatInterval;
private int _maxRequestsPerConnection = DefaultMaxRequestsPerConnection;
private bool _warmup = true;
/// <summary>
/// DEPRECATED: It will be removed in future versions. Use <see cref="PoolingOptions.Create"/> instead.
/// <para>
/// Creates a new instance of <see cref="PoolingOptions"/> using defaults suitable for old server versions
/// (Apache Cassandra 2.0 and below) for compatibility reasons. It's recommended that you
/// use <see cref="PoolingOptions.Create"/> providing the server protocol version.
/// </para>
/// </summary>
public PoolingOptions()
{
}
/// <summary>
/// Number of simultaneous requests on a connection below which connections in
/// excess are reclaimed. <p> If an opened connection to an host at distance
/// <c>distance</c> handles less than this number of simultaneous requests
/// and there is more than <link>#GetCoreConnectionsPerHost</link> connections
/// open to this host, the connection is closed. </p><p> The default value for this
/// option is 25 for <c>Local</c> and <c>Remote</c> hosts.</p>
/// </summary>
/// <param name="distance"> the <c>HostDistance</c> for which to return this threshold.</param>
/// <returns>the configured threshold, or the default one if none have been set.</returns>
public int GetMinSimultaneousRequestsPerConnectionTreshold(HostDistance distance)
{
switch (distance)
{
case HostDistance.Local:
return _minSimultaneousRequestsForLocal;
case HostDistance.Remote:
return _minSimultaneousRequestsForRemote;
default:
return 0;
}
}
/// <summary>
/// Sets the number of simultaneous requests on a connection below which
/// connections in excess are reclaimed.
/// </summary>
/// <param name="distance"> the <see cref="HostDistance"/> for which to configure this
/// threshold. </param>
/// <param name="minSimultaneousRequests"> the value to set. </param>
///
/// <returns>this <c>PoolingOptions</c>. </returns>
public PoolingOptions SetMinSimultaneousRequestsPerConnectionTreshold(HostDistance distance, int minSimultaneousRequests)
{
switch (distance)
{
case HostDistance.Local:
_minSimultaneousRequestsForLocal = minSimultaneousRequests;
break;
case HostDistance.Remote:
_minSimultaneousRequestsForRemote = minSimultaneousRequests;
break;
default:
throw new ArgumentOutOfRangeException("Cannot set min streams per connection threshold for " + distance + " hosts");
}
return this;
}
/// <summary>
/// <para>
/// Number of simultaneous requests on each connections to a host after which more
/// connections are created.
/// </para>
/// <para>
/// If all the connections opened to a host are handling more than this number of simultaneous requests
/// and there is less than <see cref="GetMaxConnectionPerHost"/> connections open to this host,
/// a new connection is open.
/// </para>
/// </summary>
/// <param name="distance"> the <see cref="HostDistance"/> for which to return this threshold.</param>
/// <returns>the configured threshold, or the default one if none have been set.</returns>
public int GetMaxSimultaneousRequestsPerConnectionTreshold(HostDistance distance)
{
switch (distance)
{
case HostDistance.Local:
return _maxSimultaneousRequestsForLocal;
case HostDistance.Remote:
return _maxSimultaneousRequestsForRemote;
default:
return 0;
}
}
/// <summary>
/// Sets number of simultaneous requests on all connections to an host after
/// which more connections are created.
/// </summary>
/// <param name="distance">The <see cref="HostDistance"/> for which to configure this
/// threshold. </param>
/// <param name="maxSimultaneousRequests"> the value to set. </param>
/// <returns>this <c>PoolingOptions</c>. </returns>
/// <throws name="IllegalArgumentException"> if <c>distance == HostDistance.Ignore</c>.</throws>
public PoolingOptions SetMaxSimultaneousRequestsPerConnectionTreshold(HostDistance distance, int maxSimultaneousRequests)
{
switch (distance)
{
case HostDistance.Local:
_maxSimultaneousRequestsForLocal = maxSimultaneousRequests;
break;
case HostDistance.Remote:
_maxSimultaneousRequestsForRemote = maxSimultaneousRequests;
break;
default:
throw new ArgumentOutOfRangeException("Cannot set max streams per connection threshold for " + distance + " hosts");
}
return this;
}
/// <summary>
/// <para>
/// The core number of connections per host.
/// </para>
/// <para>
/// For the provided <see cref="HostDistance"/>, this correspond to the number of
/// connections initially created and kept open to each host of that distance.
/// </para>
/// </summary>
/// <param name="distance">The <see cref="HostDistance"/> for which to return this threshold.</param>
/// <returns>the core number of connections per host at distance <see cref="HostDistance"/>.</returns>
public int GetCoreConnectionsPerHost(HostDistance distance)
{
switch (distance)
{
case HostDistance.Local:
return _coreConnectionsForLocal;
case HostDistance.Remote:
return _coreConnectionsForRemote;
default:
return 0;
}
}
/// <summary>
/// Gets whether all connections to hosts in the local datacenter must be opened on connect. Default: true.
/// </summary>
public bool GetWarmup()
{
return _warmup;
}
/// <summary>
/// Sets the core number of connections per host.
/// </summary>
/// <param name="distance"> the <see cref="HostDistance"/> for which to set this threshold.</param>
/// <param name="coreConnections"> the value to set </param>
/// <returns>this <c>PoolingOptions</c>. </returns>
/// <throws name="IllegalArgumentException"> if <c>distance == HostDistance.Ignored</c>.</throws>
public PoolingOptions SetCoreConnectionsPerHost(HostDistance distance, int coreConnections)
{
switch (distance)
{
case HostDistance.Local:
_coreConnectionsForLocal = coreConnections;
break;
case HostDistance.Remote:
_coreConnectionsForRemote = coreConnections;
break;
default:
throw new ArgumentOutOfRangeException("Cannot set core connections per host for " + distance + " hosts");
}
return this;
}
/// <summary>
/// The maximum number of connections per host. <p> For the provided
/// <c>distance</c>, this correspond to the maximum number of connections
/// that can be created per host at that distance.</p>
/// </summary>
/// <param name="distance"> the <c>HostDistance</c> for which to return this threshold.
/// </param>
///
/// <returns>the maximum number of connections per host at distance
/// <c>distance</c>.</returns>
public int GetMaxConnectionPerHost(HostDistance distance)
{
switch (distance)
{
case HostDistance.Local:
return _maxConnectionsForLocal;
case HostDistance.Remote:
return _maxConnectionsForRemote;
default:
return 0;
}
}
/// <summary>
/// Sets the maximum number of connections per host.
/// </summary>
/// <param name="distance"> the <c>HostDistance</c> for which to set this threshold.
/// </param>
/// <param name="maxConnections"> the value to set </param>
///
/// <returns>this <c>PoolingOptions</c>. </returns>
public PoolingOptions SetMaxConnectionsPerHost(HostDistance distance, int maxConnections)
{
switch (distance)
{
case HostDistance.Local:
_maxConnectionsForLocal = maxConnections;
break;
case HostDistance.Remote:
_maxConnectionsForRemote = maxConnections;
break;
default:
throw new ArgumentOutOfRangeException("Cannot set max connections per host for " + distance + " hosts");
}
return this;
}
/// <summary>
/// Gets the amount of idle time in milliseconds that has to pass
/// before the driver issues a request on an active connection to avoid
/// idle time disconnections.
/// <remarks>
/// A value of <c>0</c> or <c>null</c> means that the heartbeat
/// functionality at connection level is disabled.
/// </remarks>
/// </summary>
public int? GetHeartBeatInterval()
{
return _heartBeatInterval;
}
/// <summary>
/// Sets the amount of idle time in milliseconds that has to pass
/// before the driver issues a request on an active connection to avoid
/// idle time disconnections.
/// <remarks>
/// When set to <c>0</c> the heartbeat functionality at connection
/// level is disabled.
/// </remarks>
/// </summary>
public PoolingOptions SetHeartBeatInterval(int value)
{
_heartBeatInterval = value;
return this;
}
/// <summary>
/// Gets the maximum amount of requests that can be in-flight on a single connection at the same time.
/// <para>
/// This setting acts as a fixed maximum, once this value is reached for a host the pool will start
/// rejecting requests, throwing <see cref="BusyPoolException"/> instances.
/// </para>
/// <para>
/// This setting should not be mistaken with <see cref="GetMaxSimultaneousRequestsPerConnectionTreshold"/>.
/// </para>
/// </summary>
public int GetMaxRequestsPerConnection()
{
return _maxRequestsPerConnection;
}
/// <summary>
/// Sets the maximum amount of requests that can be in-flight on a single connection at the same time.
/// <para>
/// This setting acts as a fixed maximum, once this value is reached for a host the pool will start
/// rejecting requests, throwing <see cref="BusyPoolException"/> instances.
/// </para>
/// <para>
/// This setting should not be mistaken with <see cref="SetMaxSimultaneousRequestsPerConnectionTreshold"/>.
/// </para>
/// </summary>
public PoolingOptions SetMaxRequestsPerConnection(int value)
{
_maxRequestsPerConnection = value;
return this;
}
/// <summary>
/// Sets whether all connections to hosts in the local datacenter must be opened on connect. Default: true.
/// </summary>
public PoolingOptions SetWarmup(bool doWarmup)
{
_warmup = doWarmup;
return this;
}
/// <summary>
/// Creates a new instance of <see cref="PoolingOptions"/> using the default amount of connections
/// and settings based on the protocol version.
/// <para>
/// For modern server versions (Apache Cassandra 2.1+) the amount of core connections are set to 1,
/// setting 2 for max local connections.
/// </para>
/// </summary>
/// <returns>A new instance of <see cref="PoolingOptions"/></returns>
/// <seealso cref="ProtocolVersion"/>
public static PoolingOptions Create(ProtocolVersion protocolVersion = ProtocolVersion.MaxSupported)
{
if (!protocolVersion.Uses2BytesStreamIds())
{
//New instance of pooling options with default values
return new PoolingOptions();
}
//New instance of pooling options with default values for high number of concurrent requests
return new PoolingOptions()
.SetCoreConnectionsPerHost(HostDistance.Local, 1)
.SetMaxConnectionsPerHost(HostDistance.Local, 2)
.SetCoreConnectionsPerHost(HostDistance.Remote, 1)
.SetMaxConnectionsPerHost(HostDistance.Remote, 1)
.SetMaxSimultaneousRequestsPerConnectionTreshold(HostDistance.Local, 1500)
.SetMaxSimultaneousRequestsPerConnectionTreshold(HostDistance.Remote, 1500);
}
}
}
| |
// This file has been generated by the GUI designer. Do not modify.
namespace LazerTagHostUI
{
public partial class PlayerSelectionScreen
{
private global::Gtk.HPaned hpaned1;
private global::Gtk.VBox vboxPanel;
private global::Gtk.Label labelTitle;
private global::LazerTagHostUI.PlayerSelector playerselector;
private global::Gtk.VBox vboxPlayerControls;
private global::Gtk.Button buttonDropPlayer;
private global::Gtk.ComboBoxEntry comboboxentryRenamePlayer;
private global::Gtk.Button buttonLateJoin;
private global::Gtk.ToggleButton togglebuttonRelativeScores;
private global::Gtk.HBox hboxBaseControls;
private global::Gtk.Button buttonNext;
private global::Gtk.Button buttonPause;
private global::Gtk.Button buttonAbortHost;
protected virtual void Build ()
{
global::Stetic.Gui.Initialize (this);
// Widget LazerTagHostUI.PlayerSelectionScreen
global::Stetic.BinContainer.Attach (this);
this.Name = "LazerTagHostUI.PlayerSelectionScreen";
// Container child LazerTagHostUI.PlayerSelectionScreen.Gtk.Container+ContainerChild
this.hpaned1 = new global::Gtk.HPaned ();
this.hpaned1.CanFocus = true;
this.hpaned1.Name = "hpaned1";
this.hpaned1.Position = 500;
this.hpaned1.BorderWidth = ((uint)(6));
// Container child hpaned1.Gtk.Paned+PanedChild
this.vboxPanel = new global::Gtk.VBox ();
this.vboxPanel.Name = "vboxPanel";
this.vboxPanel.Spacing = 6;
// Container child vboxPanel.Gtk.Box+BoxChild
this.labelTitle = new global::Gtk.Label ();
this.labelTitle.Name = "labelTitle";
this.labelTitle.LabelProp = global::Mono.Unix.Catalog.GetString ("Step Description Here");
this.vboxPanel.Add (this.labelTitle);
global::Gtk.Box.BoxChild w1 = ((global::Gtk.Box.BoxChild)(this.vboxPanel[this.labelTitle]));
w1.Position = 0;
w1.Expand = false;
w1.Fill = false;
// Container child vboxPanel.Gtk.Box+BoxChild
this.playerselector = new global::LazerTagHostUI.PlayerSelector ();
this.playerselector.Events = ((global::Gdk.EventMask)(256));
this.playerselector.Name = "playerselector";
this.vboxPanel.Add (this.playerselector);
global::Gtk.Box.BoxChild w2 = ((global::Gtk.Box.BoxChild)(this.vboxPanel[this.playerselector]));
w2.Position = 1;
this.hpaned1.Add (this.vboxPanel);
global::Gtk.Paned.PanedChild w3 = ((global::Gtk.Paned.PanedChild)(this.hpaned1[this.vboxPanel]));
w3.Resize = false;
// Container child hpaned1.Gtk.Paned+PanedChild
this.vboxPlayerControls = new global::Gtk.VBox ();
this.vboxPlayerControls.WidthRequest = 150;
this.vboxPlayerControls.Name = "vboxPlayerControls";
this.vboxPlayerControls.Spacing = 6;
// Container child vboxPlayerControls.Gtk.Box+BoxChild
this.buttonDropPlayer = new global::Gtk.Button ();
this.buttonDropPlayer.CanFocus = true;
this.buttonDropPlayer.Name = "buttonDropPlayer";
this.buttonDropPlayer.UseUnderline = true;
// Container child buttonDropPlayer.Gtk.Container+ContainerChild
global::Gtk.Alignment w4 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w5 = new global::Gtk.HBox ();
w5.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w6 = new global::Gtk.Image ();
w6.Pixbuf = global::Stetic.IconLoader.LoadIcon (this, "gtk-delete", global::Gtk.IconSize.Menu);
w5.Add (w6);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w8 = new global::Gtk.Label ();
w8.LabelProp = global::Mono.Unix.Catalog.GetString ("Drop Player");
w8.UseUnderline = true;
w5.Add (w8);
w4.Add (w5);
this.buttonDropPlayer.Add (w4);
this.vboxPlayerControls.Add (this.buttonDropPlayer);
global::Gtk.Box.BoxChild w12 = ((global::Gtk.Box.BoxChild)(this.vboxPlayerControls[this.buttonDropPlayer]));
w12.Position = 0;
w12.Expand = false;
w12.Fill = false;
// Container child vboxPlayerControls.Gtk.Box+BoxChild
this.comboboxentryRenamePlayer = global::Gtk.ComboBoxEntry.NewText ();
this.comboboxentryRenamePlayer.AppendText (global::Mono.Unix.Catalog.GetString ("Duckbob"));
this.comboboxentryRenamePlayer.AppendText (global::Mono.Unix.Catalog.GetString ("Raptor007"));
this.comboboxentryRenamePlayer.AppendText (global::Mono.Unix.Catalog.GetString ("ChubChub"));
this.comboboxentryRenamePlayer.AppendText (global::Mono.Unix.Catalog.GetString ("Nojoe"));
this.comboboxentryRenamePlayer.AppendText (global::Mono.Unix.Catalog.GetString ("Nein"));
this.comboboxentryRenamePlayer.AppendText (global::Mono.Unix.Catalog.GetString ("Sparhawk2k"));
this.comboboxentryRenamePlayer.AppendText (global::Mono.Unix.Catalog.GetString ("Blue"));
this.comboboxentryRenamePlayer.AppendText (global::Mono.Unix.Catalog.GetString ("Gold"));
this.comboboxentryRenamePlayer.Name = "comboboxentryRenamePlayer";
this.vboxPlayerControls.Add (this.comboboxentryRenamePlayer);
global::Gtk.Box.BoxChild w13 = ((global::Gtk.Box.BoxChild)(this.vboxPlayerControls[this.comboboxentryRenamePlayer]));
w13.Position = 1;
w13.Expand = false;
w13.Fill = false;
// Container child vboxPlayerControls.Gtk.Box+BoxChild
this.buttonLateJoin = new global::Gtk.Button ();
this.buttonLateJoin.CanFocus = true;
this.buttonLateJoin.Name = "buttonLateJoin";
this.buttonLateJoin.UseUnderline = true;
// Container child buttonLateJoin.Gtk.Container+ContainerChild
global::Gtk.Alignment w14 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w15 = new global::Gtk.HBox ();
w15.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w16 = new global::Gtk.Image ();
w16.Pixbuf = global::Stetic.IconLoader.LoadIcon (this, "gtk-add", global::Gtk.IconSize.Menu);
w15.Add (w16);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w18 = new global::Gtk.Label ();
w18.LabelProp = global::Mono.Unix.Catalog.GetString ("Late Join");
w18.UseUnderline = true;
w15.Add (w18);
w14.Add (w15);
this.buttonLateJoin.Add (w14);
this.vboxPlayerControls.Add (this.buttonLateJoin);
global::Gtk.Box.BoxChild w22 = ((global::Gtk.Box.BoxChild)(this.vboxPlayerControls[this.buttonLateJoin]));
w22.Position = 2;
w22.Expand = false;
w22.Fill = false;
// Container child vboxPlayerControls.Gtk.Box+BoxChild
this.togglebuttonRelativeScores = new global::Gtk.ToggleButton ();
this.togglebuttonRelativeScores.CanFocus = true;
this.togglebuttonRelativeScores.Name = "togglebuttonRelativeScores";
this.togglebuttonRelativeScores.UseUnderline = true;
// Container child togglebuttonRelativeScores.Gtk.Container+ContainerChild
global::Gtk.Alignment w23 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w24 = new global::Gtk.HBox ();
w24.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w25 = new global::Gtk.Image ();
w25.Pixbuf = global::Stetic.IconLoader.LoadIcon (this, "stock_calendar-view-month", global::Gtk.IconSize.Menu);
w24.Add (w25);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w27 = new global::Gtk.Label ();
w27.LabelProp = global::Mono.Unix.Catalog.GetString ("Show Relative Scores");
w27.UseUnderline = true;
w24.Add (w27);
w23.Add (w24);
this.togglebuttonRelativeScores.Add (w23);
this.vboxPlayerControls.Add (this.togglebuttonRelativeScores);
global::Gtk.Box.BoxChild w31 = ((global::Gtk.Box.BoxChild)(this.vboxPlayerControls[this.togglebuttonRelativeScores]));
w31.Position = 3;
w31.Expand = false;
w31.Fill = false;
// Container child vboxPlayerControls.Gtk.Box+BoxChild
this.hboxBaseControls = new global::Gtk.HBox ();
this.hboxBaseControls.Name = "hboxBaseControls";
this.hboxBaseControls.Spacing = 6;
// Container child hboxBaseControls.Gtk.Box+BoxChild
this.buttonNext = new global::Gtk.Button ();
this.buttonNext.CanFocus = true;
this.buttonNext.Name = "buttonNext";
this.buttonNext.UseUnderline = true;
// Container child buttonNext.Gtk.Container+ContainerChild
global::Gtk.Alignment w32 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w33 = new global::Gtk.HBox ();
w33.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w34 = new global::Gtk.Image ();
w34.Pixbuf = global::Stetic.IconLoader.LoadIcon (this, "gtk-apply", global::Gtk.IconSize.Menu);
w33.Add (w34);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w36 = new global::Gtk.Label ();
w36.LabelProp = global::Mono.Unix.Catalog.GetString ("_Next");
w36.UseUnderline = true;
w33.Add (w36);
w32.Add (w33);
this.buttonNext.Add (w32);
this.hboxBaseControls.Add (this.buttonNext);
global::Gtk.Box.BoxChild w40 = ((global::Gtk.Box.BoxChild)(this.hboxBaseControls[this.buttonNext]));
w40.PackType = ((global::Gtk.PackType)(1));
w40.Position = 2;
w40.Expand = false;
w40.Fill = false;
// Container child hboxBaseControls.Gtk.Box+BoxChild
this.buttonPause = new global::Gtk.Button ();
this.buttonPause.CanFocus = true;
this.buttonPause.Name = "buttonPause";
this.buttonPause.UseUnderline = true;
// Container child buttonPause.Gtk.Container+ContainerChild
global::Gtk.Alignment w41 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w42 = new global::Gtk.HBox ();
w42.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w43 = new global::Gtk.Image ();
w43.Pixbuf = global::Stetic.IconLoader.LoadIcon (this, "stock_appointment-reminder", global::Gtk.IconSize.Menu);
w42.Add (w43);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w45 = new global::Gtk.Label ();
w45.LabelProp = global::Mono.Unix.Catalog.GetString ("_Pause");
w45.UseUnderline = true;
w42.Add (w45);
w41.Add (w42);
this.buttonPause.Add (w41);
this.hboxBaseControls.Add (this.buttonPause);
global::Gtk.Box.BoxChild w49 = ((global::Gtk.Box.BoxChild)(this.hboxBaseControls[this.buttonPause]));
w49.PackType = ((global::Gtk.PackType)(1));
w49.Position = 3;
w49.Expand = false;
w49.Fill = false;
// Container child hboxBaseControls.Gtk.Box+BoxChild
this.buttonAbortHost = new global::Gtk.Button ();
this.buttonAbortHost.CanFocus = true;
this.buttonAbortHost.Name = "buttonAbortHost";
this.buttonAbortHost.UseUnderline = true;
// Container child buttonAbortHost.Gtk.Container+ContainerChild
global::Gtk.Alignment w50 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w51 = new global::Gtk.HBox ();
w51.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w52 = new global::Gtk.Image ();
w52.Pixbuf = global::Stetic.IconLoader.LoadIcon (this, "gtk-cancel", global::Gtk.IconSize.Menu);
w51.Add (w52);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w54 = new global::Gtk.Label ();
w54.LabelProp = global::Mono.Unix.Catalog.GetString ("_Abort Host");
w54.UseUnderline = true;
w51.Add (w54);
w50.Add (w51);
this.buttonAbortHost.Add (w50);
this.hboxBaseControls.Add (this.buttonAbortHost);
global::Gtk.Box.BoxChild w58 = ((global::Gtk.Box.BoxChild)(this.hboxBaseControls[this.buttonAbortHost]));
w58.PackType = ((global::Gtk.PackType)(1));
w58.Position = 4;
w58.Expand = false;
w58.Fill = false;
this.vboxPlayerControls.Add (this.hboxBaseControls);
global::Gtk.Box.BoxChild w59 = ((global::Gtk.Box.BoxChild)(this.vboxPlayerControls[this.hboxBaseControls]));
w59.PackType = ((global::Gtk.PackType)(1));
w59.Position = 5;
w59.Expand = false;
w59.Fill = false;
this.hpaned1.Add (this.vboxPlayerControls);
global::Gtk.Paned.PanedChild w60 = ((global::Gtk.Paned.PanedChild)(this.hpaned1[this.vboxPlayerControls]));
w60.Resize = false;
w60.Shrink = false;
this.Add (this.hpaned1);
if ((this.Child != null)) {
this.Child.ShowAll ();
}
this.Hide ();
this.togglebuttonRelativeScores.Toggled += new global::System.EventHandler (this.RelativeScoresToggled);
}
}
}
| |
// Copyright (c) 1995-2009 held by the author(s). All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1998
{
/// <summary>
/// 5.3.3.3. Information about elastic collisions in a DIS exercise shall be communicated using a Collision-Elastic PDU. COMPLETE
/// </summary>
[Serializable]
[XmlRoot]
[XmlInclude(typeof(EntityID))]
[XmlInclude(typeof(EventID))]
[XmlInclude(typeof(Vector3Float))]
public partial class CollisionElasticPdu : EntityInformationFamilyPdu, IEquatable<CollisionElasticPdu>
{
/// <summary>
/// ID of the entity that issued the collision PDU
/// </summary>
private EntityID _issuingEntityID = new EntityID();
/// <summary>
/// ID of entity that has collided with the issuing entity ID
/// </summary>
private EntityID _collidingEntityID = new EntityID();
/// <summary>
/// ID of event
/// </summary>
private EventID _collisionEventID = new EventID();
/// <summary>
/// some padding
/// </summary>
private short _pad;
/// <summary>
/// velocity at collision
/// </summary>
private Vector3Float _contactVelocity = new Vector3Float();
/// <summary>
/// mass of issuing entity
/// </summary>
private float _mass;
/// <summary>
/// Location with respect to entity the issuing entity collided with
/// </summary>
private Vector3Float _location = new Vector3Float();
/// <summary>
/// tensor values
/// </summary>
private float _collisionResultXX;
/// <summary>
/// tensor values
/// </summary>
private float _collisionResultXY;
/// <summary>
/// tensor values
/// </summary>
private float _collisionResultXZ;
/// <summary>
/// tensor values
/// </summary>
private float _collisionResultYY;
/// <summary>
/// tensor values
/// </summary>
private float _collisionResultYZ;
/// <summary>
/// tensor values
/// </summary>
private float _collisionResultZZ;
/// <summary>
/// This record shall represent the normal vector to the surface at the point of collision detection. The surface normal shall be represented in world coordinates.
/// </summary>
private Vector3Float _unitSurfaceNormal = new Vector3Float();
/// <summary>
/// This field shall represent the degree to which energy is conserved in a collision
/// </summary>
private float _coefficientOfRestitution;
/// <summary>
/// Initializes a new instance of the <see cref="CollisionElasticPdu"/> class.
/// </summary>
public CollisionElasticPdu()
{
PduType = (byte)66;
ProtocolFamily = (byte)1;
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(CollisionElasticPdu left, CollisionElasticPdu right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(CollisionElasticPdu left, CollisionElasticPdu right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public override int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize = base.GetMarshalledSize();
marshalSize += this._issuingEntityID.GetMarshalledSize(); // this._issuingEntityID
marshalSize += this._collidingEntityID.GetMarshalledSize(); // this._collidingEntityID
marshalSize += this._collisionEventID.GetMarshalledSize(); // this._collisionEventID
marshalSize += 2; // this._pad
marshalSize += this._contactVelocity.GetMarshalledSize(); // this._contactVelocity
marshalSize += 4; // this._mass
marshalSize += this._location.GetMarshalledSize(); // this._location
marshalSize += 4; // this._collisionResultXX
marshalSize += 4; // this._collisionResultXY
marshalSize += 4; // this._collisionResultXZ
marshalSize += 4; // this._collisionResultYY
marshalSize += 4; // this._collisionResultYZ
marshalSize += 4; // this._collisionResultZZ
marshalSize += this._unitSurfaceNormal.GetMarshalledSize(); // this._unitSurfaceNormal
marshalSize += 4; // this._coefficientOfRestitution
return marshalSize;
}
/// <summary>
/// Gets or sets the ID of the entity that issued the collision PDU
/// </summary>
[XmlElement(Type = typeof(EntityID), ElementName = "issuingEntityID")]
public EntityID IssuingEntityID
{
get
{
return this._issuingEntityID;
}
set
{
this._issuingEntityID = value;
}
}
/// <summary>
/// Gets or sets the ID of entity that has collided with the issuing entity ID
/// </summary>
[XmlElement(Type = typeof(EntityID), ElementName = "collidingEntityID")]
public EntityID CollidingEntityID
{
get
{
return this._collidingEntityID;
}
set
{
this._collidingEntityID = value;
}
}
/// <summary>
/// Gets or sets the ID of event
/// </summary>
[XmlElement(Type = typeof(EventID), ElementName = "collisionEventID")]
public EventID CollisionEventID
{
get
{
return this._collisionEventID;
}
set
{
this._collisionEventID = value;
}
}
/// <summary>
/// Gets or sets the some padding
/// </summary>
[XmlElement(Type = typeof(short), ElementName = "pad")]
public short Pad
{
get
{
return this._pad;
}
set
{
this._pad = value;
}
}
/// <summary>
/// Gets or sets the velocity at collision
/// </summary>
[XmlElement(Type = typeof(Vector3Float), ElementName = "contactVelocity")]
public Vector3Float ContactVelocity
{
get
{
return this._contactVelocity;
}
set
{
this._contactVelocity = value;
}
}
/// <summary>
/// Gets or sets the mass of issuing entity
/// </summary>
[XmlElement(Type = typeof(float), ElementName = "mass")]
public float Mass
{
get
{
return this._mass;
}
set
{
this._mass = value;
}
}
/// <summary>
/// Gets or sets the Location with respect to entity the issuing entity collided with
/// </summary>
[XmlElement(Type = typeof(Vector3Float), ElementName = "location")]
public Vector3Float Location
{
get
{
return this._location;
}
set
{
this._location = value;
}
}
/// <summary>
/// Gets or sets the tensor values
/// </summary>
[XmlElement(Type = typeof(float), ElementName = "collisionResultXX")]
public float CollisionResultXX
{
get
{
return this._collisionResultXX;
}
set
{
this._collisionResultXX = value;
}
}
/// <summary>
/// Gets or sets the tensor values
/// </summary>
[XmlElement(Type = typeof(float), ElementName = "collisionResultXY")]
public float CollisionResultXY
{
get
{
return this._collisionResultXY;
}
set
{
this._collisionResultXY = value;
}
}
/// <summary>
/// Gets or sets the tensor values
/// </summary>
[XmlElement(Type = typeof(float), ElementName = "collisionResultXZ")]
public float CollisionResultXZ
{
get
{
return this._collisionResultXZ;
}
set
{
this._collisionResultXZ = value;
}
}
/// <summary>
/// Gets or sets the tensor values
/// </summary>
[XmlElement(Type = typeof(float), ElementName = "collisionResultYY")]
public float CollisionResultYY
{
get
{
return this._collisionResultYY;
}
set
{
this._collisionResultYY = value;
}
}
/// <summary>
/// Gets or sets the tensor values
/// </summary>
[XmlElement(Type = typeof(float), ElementName = "collisionResultYZ")]
public float CollisionResultYZ
{
get
{
return this._collisionResultYZ;
}
set
{
this._collisionResultYZ = value;
}
}
/// <summary>
/// Gets or sets the tensor values
/// </summary>
[XmlElement(Type = typeof(float), ElementName = "collisionResultZZ")]
public float CollisionResultZZ
{
get
{
return this._collisionResultZZ;
}
set
{
this._collisionResultZZ = value;
}
}
/// <summary>
/// Gets or sets the This record shall represent the normal vector to the surface at the point of collision detection. The surface normal shall be represented in world coordinates.
/// </summary>
[XmlElement(Type = typeof(Vector3Float), ElementName = "unitSurfaceNormal")]
public Vector3Float UnitSurfaceNormal
{
get
{
return this._unitSurfaceNormal;
}
set
{
this._unitSurfaceNormal = value;
}
}
/// <summary>
/// Gets or sets the This field shall represent the degree to which energy is conserved in a collision
/// </summary>
[XmlElement(Type = typeof(float), ElementName = "coefficientOfRestitution")]
public float CoefficientOfRestitution
{
get
{
return this._coefficientOfRestitution;
}
set
{
this._coefficientOfRestitution = value;
}
}
/// <summary>
/// Automatically sets the length of the marshalled data, then calls the marshal method.
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
public override void MarshalAutoLengthSet(DataOutputStream dos)
{
// Set the length prior to marshalling data
this.Length = (ushort)this.GetMarshalledSize();
this.Marshal(dos);
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Marshal(DataOutputStream dos)
{
base.Marshal(dos);
if (dos != null)
{
try
{
this._issuingEntityID.Marshal(dos);
this._collidingEntityID.Marshal(dos);
this._collisionEventID.Marshal(dos);
dos.WriteShort((short)this._pad);
this._contactVelocity.Marshal(dos);
dos.WriteFloat((float)this._mass);
this._location.Marshal(dos);
dos.WriteFloat((float)this._collisionResultXX);
dos.WriteFloat((float)this._collisionResultXY);
dos.WriteFloat((float)this._collisionResultXZ);
dos.WriteFloat((float)this._collisionResultYY);
dos.WriteFloat((float)this._collisionResultYZ);
dos.WriteFloat((float)this._collisionResultZZ);
this._unitSurfaceNormal.Marshal(dos);
dos.WriteFloat((float)this._coefficientOfRestitution);
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Unmarshal(DataInputStream dis)
{
base.Unmarshal(dis);
if (dis != null)
{
try
{
this._issuingEntityID.Unmarshal(dis);
this._collidingEntityID.Unmarshal(dis);
this._collisionEventID.Unmarshal(dis);
this._pad = dis.ReadShort();
this._contactVelocity.Unmarshal(dis);
this._mass = dis.ReadFloat();
this._location.Unmarshal(dis);
this._collisionResultXX = dis.ReadFloat();
this._collisionResultXY = dis.ReadFloat();
this._collisionResultXZ = dis.ReadFloat();
this._collisionResultYY = dis.ReadFloat();
this._collisionResultYZ = dis.ReadFloat();
this._collisionResultZZ = dis.ReadFloat();
this._unitSurfaceNormal.Unmarshal(dis);
this._coefficientOfRestitution = dis.ReadFloat();
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Reflection(StringBuilder sb)
{
sb.AppendLine("<CollisionElasticPdu>");
base.Reflection(sb);
try
{
sb.AppendLine("<issuingEntityID>");
this._issuingEntityID.Reflection(sb);
sb.AppendLine("</issuingEntityID>");
sb.AppendLine("<collidingEntityID>");
this._collidingEntityID.Reflection(sb);
sb.AppendLine("</collidingEntityID>");
sb.AppendLine("<collisionEventID>");
this._collisionEventID.Reflection(sb);
sb.AppendLine("</collisionEventID>");
sb.AppendLine("<pad type=\"short\">" + this._pad.ToString(CultureInfo.InvariantCulture) + "</pad>");
sb.AppendLine("<contactVelocity>");
this._contactVelocity.Reflection(sb);
sb.AppendLine("</contactVelocity>");
sb.AppendLine("<mass type=\"float\">" + this._mass.ToString(CultureInfo.InvariantCulture) + "</mass>");
sb.AppendLine("<location>");
this._location.Reflection(sb);
sb.AppendLine("</location>");
sb.AppendLine("<collisionResultXX type=\"float\">" + this._collisionResultXX.ToString(CultureInfo.InvariantCulture) + "</collisionResultXX>");
sb.AppendLine("<collisionResultXY type=\"float\">" + this._collisionResultXY.ToString(CultureInfo.InvariantCulture) + "</collisionResultXY>");
sb.AppendLine("<collisionResultXZ type=\"float\">" + this._collisionResultXZ.ToString(CultureInfo.InvariantCulture) + "</collisionResultXZ>");
sb.AppendLine("<collisionResultYY type=\"float\">" + this._collisionResultYY.ToString(CultureInfo.InvariantCulture) + "</collisionResultYY>");
sb.AppendLine("<collisionResultYZ type=\"float\">" + this._collisionResultYZ.ToString(CultureInfo.InvariantCulture) + "</collisionResultYZ>");
sb.AppendLine("<collisionResultZZ type=\"float\">" + this._collisionResultZZ.ToString(CultureInfo.InvariantCulture) + "</collisionResultZZ>");
sb.AppendLine("<unitSurfaceNormal>");
this._unitSurfaceNormal.Reflection(sb);
sb.AppendLine("</unitSurfaceNormal>");
sb.AppendLine("<coefficientOfRestitution type=\"float\">" + this._coefficientOfRestitution.ToString(CultureInfo.InvariantCulture) + "</coefficientOfRestitution>");
sb.AppendLine("</CollisionElasticPdu>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as CollisionElasticPdu;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(CollisionElasticPdu obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
ivarsEqual = base.Equals(obj);
if (!this._issuingEntityID.Equals(obj._issuingEntityID))
{
ivarsEqual = false;
}
if (!this._collidingEntityID.Equals(obj._collidingEntityID))
{
ivarsEqual = false;
}
if (!this._collisionEventID.Equals(obj._collisionEventID))
{
ivarsEqual = false;
}
if (this._pad != obj._pad)
{
ivarsEqual = false;
}
if (!this._contactVelocity.Equals(obj._contactVelocity))
{
ivarsEqual = false;
}
if (this._mass != obj._mass)
{
ivarsEqual = false;
}
if (!this._location.Equals(obj._location))
{
ivarsEqual = false;
}
if (this._collisionResultXX != obj._collisionResultXX)
{
ivarsEqual = false;
}
if (this._collisionResultXY != obj._collisionResultXY)
{
ivarsEqual = false;
}
if (this._collisionResultXZ != obj._collisionResultXZ)
{
ivarsEqual = false;
}
if (this._collisionResultYY != obj._collisionResultYY)
{
ivarsEqual = false;
}
if (this._collisionResultYZ != obj._collisionResultYZ)
{
ivarsEqual = false;
}
if (this._collisionResultZZ != obj._collisionResultZZ)
{
ivarsEqual = false;
}
if (!this._unitSurfaceNormal.Equals(obj._unitSurfaceNormal))
{
ivarsEqual = false;
}
if (this._coefficientOfRestitution != obj._coefficientOfRestitution)
{
ivarsEqual = false;
}
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ base.GetHashCode();
result = GenerateHash(result) ^ this._issuingEntityID.GetHashCode();
result = GenerateHash(result) ^ this._collidingEntityID.GetHashCode();
result = GenerateHash(result) ^ this._collisionEventID.GetHashCode();
result = GenerateHash(result) ^ this._pad.GetHashCode();
result = GenerateHash(result) ^ this._contactVelocity.GetHashCode();
result = GenerateHash(result) ^ this._mass.GetHashCode();
result = GenerateHash(result) ^ this._location.GetHashCode();
result = GenerateHash(result) ^ this._collisionResultXX.GetHashCode();
result = GenerateHash(result) ^ this._collisionResultXY.GetHashCode();
result = GenerateHash(result) ^ this._collisionResultXZ.GetHashCode();
result = GenerateHash(result) ^ this._collisionResultYY.GetHashCode();
result = GenerateHash(result) ^ this._collisionResultYZ.GetHashCode();
result = GenerateHash(result) ^ this._collisionResultZZ.GetHashCode();
result = GenerateHash(result) ^ this._unitSurfaceNormal.GetHashCode();
result = GenerateHash(result) ^ this._coefficientOfRestitution.GetHashCode();
return result;
}
}
}
| |
using System.Data;
using Relisten.Api.Models;
using Dapper;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
namespace Relisten.Data
{
public class ShowService : RelistenDataServiceBase
{
private SourceService _sourceService { get; set; }
public ShowService(
DbService db,
SourceService sourceService
) : base(db)
{
_sourceService = sourceService;
}
public async Task<IEnumerable<T>> ShowsForCriteriaGeneric<T>(
Artist artist,
string where,
object parms,
int? limit = null,
string orderBy = null
) where T : Show
{
orderBy = orderBy == null ? "display_date ASC" : orderBy;
var limitClause = limit == null ? "" : "LIMIT " + limit;
return await db.WithConnection(con => con.QueryAsync<T, VenueWithShowCount, Tour, Era, Year, T>(@"
SELECT
s.*,
cnt.max_updated_at as most_recent_source_updated_at,
cnt.source_count,
cnt.has_soundboard_source,
cnt.has_flac as has_streamable_flac_source,
v.*,
venue_counts.shows_at_venue,
t.*,
e.*,
y.*
FROM
shows s
LEFT JOIN venues v ON s.venue_id = v.id
LEFT JOIN tours t ON s.tour_id = t.id
LEFT JOIN eras e ON s.era_id = e.id
LEFT JOIN years y ON s.year_id = y.id
INNER JOIN show_source_information cnt ON cnt.show_id = s.id
LEFT JOIN venue_show_counts venue_counts ON venue_counts.id = s.venue_id
WHERE
" + where + @"
ORDER BY
" + orderBy + @"
" + limitClause + @"
", (Show, venue, tour, era, year) =>
{
Show.venue = venue;
if (artist == null || artist.features.tours)
{
Show.tour = tour;
}
if (artist == null || artist.features.eras)
{
Show.era = era;
}
if (artist == null || artist.features.years)
{
Show.year = year;
}
return Show;
}, parms));
}
public async Task<IEnumerable<Show>> ShowsForCriteria(
Artist artist,
string where,
object parms,
int? limit = null,
string orderBy = null)
{
return await ShowsForCriteriaGeneric<Show>(artist, where, parms, limit, orderBy);
}
public async Task<IEnumerable<ShowWithArtist>> ShowsForCriteriaWithArtists(string where, object parms, int? limit = null, string orderBy = null)
{
orderBy = orderBy == null ? "display_date ASC" : orderBy;
var limitClause = limit == null ? "" : "LIMIT " + limit;
return await db.WithConnection(con => con.QueryAsync<ShowWithArtist, VenueWithShowCount, Tour, Era, Artist, Features, Year, ShowWithArtist>(@"
SELECT
s.*,
cnt.max_updated_at as most_recent_source_updated_at,
cnt.source_count,
cnt.has_soundboard_source,
cnt.has_flac as has_streamable_flac_source,
v.*,
COALESCE(venue_counts.shows_at_venue, 0) as shows_at_venue,
t.*,
e.*,
a.*,
y.*
FROM
shows s
LEFT JOIN venues v ON s.venue_id = v.id
LEFT JOIN tours t ON s.tour_id = t.id
LEFT JOIN eras e ON s.era_id = e.id
LEFT JOIN years y ON s.year_id = y.id
LEFT JOIN (
SELECT
arts.id as aid, arts.*, f.*
FROM
artists arts
INNER JOIN features f ON f.artist_id = arts.id
) a ON s.artist_id = a.aid
INNER JOIN show_source_information cnt ON cnt.show_id = s.id
LEFT JOIN venue_show_counts venue_counts ON venue_counts.id = s.venue_id
WHERE
" + where + @"
ORDER BY
" + orderBy + @"
" + limitClause + @"
", (Show, venue, tour, era, art, features, year) =>
{
art.features = features;
Show.artist = art;
Show.venue = venue;
Show.year = year;
if (art.features.tours)
{
Show.tour = tour;
}
if (art.features.eras)
{
Show.era = era;
}
return Show;
}, parms));
}
public async Task<IEnumerable<ShowWithArtist>> RecentlyPerformed(IReadOnlyList<Artist> artists = null, int? shows = null, int? days = null)
{
if(shows == null && days == null)
{
shows = 25;
}
if(shows > 250) {
shows = 250;
}
if(days > 90) {
days = 90;
}
if(days.HasValue) {
if(artists != null)
{
return await ShowsForCriteriaWithArtists($@"
s.artist_id = ANY(@artistIds)
AND s.date > (CURRENT_DATE - INTERVAL '{days}' day)
", new { artistIds= artists.Select(a => a.id).ToList() }, null, "s.display_date DESC");
}
return await ShowsForCriteriaWithArtists($@"
s.date > (CURRENT_DATE - INTERVAL '{days}' day)
", new { }, null, "s.display_date DESC");
}
if(artists != null)
{
return await ShowsForCriteriaWithArtists(@"
s.artist_id = ANY(@artistIds)
", new { artistIds = artists.Select(a => a.id).ToList() }, shows, "s.display_date DESC");
}
return await ShowsForCriteriaWithArtists(@"
", new { }, shows, "s.display_date DESC");
}
public async Task<IEnumerable<ShowWithArtist>> RecentlyUpdated(IReadOnlyList<Artist> artists = null, int? shows = null, int? days = null)
{
if(shows == null && days == null)
{
shows = 25;
}
if(shows > 250) {
shows = 250;
}
if(days > 90) {
days = 90;
}
if(days.HasValue) {
if(artists != null)
{
return await ShowsForCriteriaWithArtists($@"
s.artist_id = ANY(@artistIds)
AND s.updated_at > (CURRENT_DATE - INTERVAL '{days}' day)
", new { artistIds = artists.Select(a => a.id).ToList() }, null, "s.updated_at DESC");
}
return await ShowsForCriteriaWithArtists($@"
s.updated_at > (CURRENT_DATE - INTERVAL '{days}' day)
", new { }, null, "s.updated_at DESC");
}
if(artists != null)
{
return await ShowsForCriteriaWithArtists(@"
s.artist_id = ANY(@artistIds)
", new { artistIds = artists.Select(a => a.id).ToList() }, shows, "s.updated_at DESC");
}
return await ShowsForCriteriaWithArtists(@"
", new { }, shows, "s.updated_at DESC");
}
public async Task<ShowWithSources> ShowWithSourcesForArtistOnDate(Artist artist, string displayDate)
{
var shows = await ShowsForCriteriaGeneric<ShowWithSources>(artist,
"s.artist_id = @artistId AND s.display_date = @showDate",
new { artistId = artist.id, showDate = displayDate }
);
var show = shows.FirstOrDefault();
if (show == null)
{
return null;
}
show.sources = await _sourceService.FullSourcesForShow(artist, show);
return show;
}
public async Task<IEnumerable<Show>> AllSimpleForArtist(Artist artist)
{
return await db.WithConnection(con => con.QueryAsync<Show>(@"
SELECT
id, created_at, updated_at, date
FROM
setlist_shows
WHERE
artist_id = @id
", new { artist.id }));
}
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// 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 Google Inc. 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.
#endregion
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
using Grpc.Core.Internal;
using Grpc.Core.Utils;
using NUnit.Framework;
namespace Grpc.Core.Tests
{
public class ClientServerTest
{
const string Host = "127.0.0.1";
MockServiceHelper helper;
Server server;
Channel channel;
[SetUp]
public void Init()
{
helper = new MockServiceHelper(Host);
server = helper.GetServer();
server.Start();
channel = helper.GetChannel();
}
[TearDown]
public void Cleanup()
{
channel.ShutdownAsync().Wait();
server.ShutdownAsync().Wait();
}
[Test]
public async Task UnaryCall()
{
helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) =>
{
return request;
});
Assert.AreEqual("ABC", Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "ABC"));
Assert.AreEqual("ABC", await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "ABC"));
}
[Test]
public void UnaryCall_ServerHandlerThrows()
{
helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) =>
{
throw new Exception("This was thrown on purpose by a test");
});
var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc"));
Assert.AreEqual(StatusCode.Unknown, ex.Status.StatusCode);
var ex2 = Assert.Throws<RpcException>(async () => await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc"));
Assert.AreEqual(StatusCode.Unknown, ex2.Status.StatusCode);
}
[Test]
public void UnaryCall_ServerHandlerThrowsRpcException()
{
helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) =>
{
throw new RpcException(new Status(StatusCode.Unauthenticated, ""));
});
var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc"));
Assert.AreEqual(StatusCode.Unauthenticated, ex.Status.StatusCode);
var ex2 = Assert.Throws<RpcException>(async () => await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc"));
Assert.AreEqual(StatusCode.Unauthenticated, ex2.Status.StatusCode);
}
[Test]
public void UnaryCall_ServerHandlerSetsStatus()
{
helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) =>
{
context.Status = new Status(StatusCode.Unauthenticated, "");
return "";
});
var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc"));
Assert.AreEqual(StatusCode.Unauthenticated, ex.Status.StatusCode);
var ex2 = Assert.Throws<RpcException>(async () => await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc"));
Assert.AreEqual(StatusCode.Unauthenticated, ex2.Status.StatusCode);
}
[Test]
public async Task ClientStreamingCall()
{
helper.ClientStreamingHandler = new ClientStreamingServerMethod<string, string>(async (requestStream, context) =>
{
string result = "";
await requestStream.ForEachAsync(async (request) =>
{
result += request;
});
await Task.Delay(100);
return result;
});
var call = Calls.AsyncClientStreamingCall(helper.CreateClientStreamingCall());
await call.RequestStream.WriteAllAsync(new string[] { "A", "B", "C" });
Assert.AreEqual("ABC", await call.ResponseAsync);
}
[Test]
public async Task ClientStreamingCall_CancelAfterBegin()
{
var barrier = new TaskCompletionSource<object>();
helper.ClientStreamingHandler = new ClientStreamingServerMethod<string, string>(async (requestStream, context) =>
{
barrier.SetResult(null);
await requestStream.ToListAsync();
return "";
});
var cts = new CancellationTokenSource();
var call = Calls.AsyncClientStreamingCall(helper.CreateClientStreamingCall(new CallOptions(cancellationToken: cts.Token)));
await barrier.Task; // make sure the handler has started.
cts.Cancel();
var ex = Assert.Throws<RpcException>(async () => await call.ResponseAsync);
Assert.AreEqual(StatusCode.Cancelled, ex.Status.StatusCode);
}
[Test]
public async Task AsyncUnaryCall_EchoMetadata()
{
helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) =>
{
foreach (Metadata.Entry metadataEntry in context.RequestHeaders)
{
if (metadataEntry.Key != "user-agent")
{
context.ResponseTrailers.Add(metadataEntry);
}
}
return "";
});
var headers = new Metadata
{
{ "ascii-header", "abcdefg" },
{ "binary-header-bin", new byte[] { 1, 2, 3, 0, 0xff } }
};
var call = Calls.AsyncUnaryCall(helper.CreateUnaryCall(new CallOptions(headers: headers)), "ABC");
await call;
Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode);
var trailers = call.GetTrailers();
Assert.AreEqual(2, trailers.Count);
Assert.AreEqual(headers[0].Key, trailers[0].Key);
Assert.AreEqual(headers[0].Value, trailers[0].Value);
Assert.AreEqual(headers[1].Key, trailers[1].Key);
CollectionAssert.AreEqual(headers[1].ValueBytes, trailers[1].ValueBytes);
}
[Test]
public void UnaryCallPerformance()
{
helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) =>
{
return request;
});
var callDetails = helper.CreateUnaryCall();
BenchmarkUtil.RunBenchmark(100, 100,
() => { Calls.BlockingUnaryCall(callDetails, "ABC"); });
}
[Test]
public void UnknownMethodHandler()
{
var nonexistentMethod = new Method<string, string>(
MethodType.Unary,
MockServiceHelper.ServiceName,
"NonExistentMethod",
Marshallers.StringMarshaller,
Marshallers.StringMarshaller);
var callDetails = new CallInvocationDetails<string, string>(channel, nonexistentMethod, new CallOptions());
var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(callDetails, "abc"));
Assert.AreEqual(StatusCode.Unimplemented, ex.Status.StatusCode);
}
[Test]
public void UserAgentStringPresent()
{
helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) =>
{
return context.RequestHeaders.Where(entry => entry.Key == "user-agent").Single().Value;
});
string userAgent = Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc");
Assert.IsTrue(userAgent.StartsWith("grpc-csharp/"));
}
[Test]
public void PeerInfoPresent()
{
helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) =>
{
return context.Peer;
});
string peer = Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc");
Assert.IsTrue(peer.Contains(Host));
}
[Test]
public async Task Channel_WaitForStateChangedAsync()
{
helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) =>
{
return request;
});
Assert.Throws(typeof(TaskCanceledException),
async () => await channel.WaitForStateChangedAsync(channel.State, DateTime.UtcNow.AddMilliseconds(10)));
var stateChangedTask = channel.WaitForStateChangedAsync(channel.State);
await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc");
await stateChangedTask;
Assert.AreEqual(ChannelState.Ready, channel.State);
}
[Test]
public async Task Channel_ConnectAsync()
{
await channel.ConnectAsync();
Assert.AreEqual(ChannelState.Ready, channel.State);
await channel.ConnectAsync(DateTime.UtcNow.AddMilliseconds(1000));
Assert.AreEqual(ChannelState.Ready, channel.State);
}
}
}
| |
/*******************************************************************************
INTEL CORPORATION PROPRIETARY INFORMATION
This software is supplied under the terms of a license agreement or nondisclosure
agreement with Intel Corporation and may not be copied or disclosed except in
accordance with the terms of that agreement
Copyright(c) 2012-2014 Intel Corporation. All Rights Reserved.
*******************************************************************************/
using UnityEngine;
using System.Collections;
namespace RSUnityToolkit
{
/// <summary>
/// Hand tracking rule - Processes Track Triggers
/// </summary>
[AddComponentMenu("")]
[TrackTrigger.TrackTriggerAtt]
public class BlobTrackingRule : BaseRule
{
#region Public Fields
/// <summary>
/// The real world box center. In centimiters.
/// </summary>
public Vector3 RealWorldBoxCenter = new Vector3(0, 0, 50);
/// <summary>
/// The real world box dimensions. In Centimiters.
/// </summary>
public Vector3 RealWorldBoxDimensions = new Vector3(100, 100, 100);
public float MaxDistance = 50;
public BlobUtilityClass.TrackingBlobPoint BlobPointToTrack = BlobUtilityClass.TrackingBlobPoint.ClosestPoint;
public int BlobIndex = 0;
#endregion
#region Private Fields
private float[] _depthArray;
private PXCMPoint3DF32[] _pos_uvz;
private PXCMPoint3DF32[] _pos3d;
#endregion
#region C'tors
public BlobTrackingRule(): base()
{
FriendlyName = "Blob Tracking";
}
#endregion
#region Public Methods
override public string GetIconPath()
{
return @"RulesIcons/object-tracking";
}
override public string GetRuleDescription()
{
return "Track blob's position";
}
protected override bool OnRuleEnabled()
{
SenseToolkitManager.Instance.SetSenseOption(SenseOption.SenseOptionID.VideoDepthStream);
return true;
}
protected override void OnRuleDisabled()
{
SenseToolkitManager.Instance.UnsetSenseOption(SenseOption.SenseOptionID.VideoDepthStream);
}
public override bool Process(Trigger trigger)
{
trigger.ErrorDetected = false;
if (!SenseToolkitManager.Instance.IsSenseOptionSet(SenseOption.SenseOptionID.VideoDepthStream))
{
trigger.ErrorDetected = true;
Debug.LogError("Blob Analysis Module Not Set");
return false;
}
if (!(trigger is TrackTrigger))
{
trigger.ErrorDetected = true;
return false;
}
bool success = false;
// make sure we have valid values
if (RealWorldBoxDimensions.x <= 0)
{
RealWorldBoxDimensions.x = 1;
}
if (RealWorldBoxDimensions.y <= 0)
{
RealWorldBoxDimensions.y = 1;
}
if (RealWorldBoxDimensions.z <= 0)
{
RealWorldBoxDimensions.z = 1;
}
if (SenseToolkitManager.Instance != null && SenseToolkitManager.Instance.Initialized && SenseToolkitManager.Instance.BlobExtractor != null && SenseToolkitManager.Instance.ImageDepthOutput != null)
{
// Setting max distance for this rule and process the image
PXCMBlobExtractor.BlobData _blobData = new PXCMBlobExtractor.BlobData();
SenseToolkitManager.Instance.BlobExtractor.SetMaxDistance(MaxDistance * 10);
var sts = SenseToolkitManager.Instance.BlobExtractor.ProcessImage(SenseToolkitManager.Instance.ImageDepthOutput);
if (sts >= pxcmStatus.PXCM_STATUS_NO_ERROR && SenseToolkitManager.Instance.BlobExtractor.QueryNumberOfBlobs() > 0)
{
if (BlobIndex >= SenseToolkitManager.Instance.BlobExtractor.QueryNumberOfBlobs() )
{
return false;
}
PXCMImage.ImageInfo info = SenseToolkitManager.Instance.ImageDepthOutput.QueryInfo();
info.format = PXCMImage.PixelFormat.PIXEL_FORMAT_Y8;
PXCMImage new_image = SenseToolkitManager.Instance.SenseManager.session.CreateImage(info);
// Process Tracking
SenseToolkitManager.Instance.BlobExtractor.QueryBlobData(BlobIndex, new_image, out _blobData);
new_image.Dispose();
TrackTrigger specificTrigger = (TrackTrigger)trigger;
PXCMPointI32 trackedPoint = BlobUtilityClass.GetTrackedPoint(_blobData, BlobPointToTrack);
PXCMImage.ImageData data;
SenseToolkitManager.Instance.ImageDepthOutput.AcquireAccess(PXCMImage.Access.ACCESS_READ,PXCMImage.PixelFormat.PIXEL_FORMAT_DEPTH_F32, out data);
if (_depthArray == null)
{
_depthArray = new float[SenseToolkitManager.Instance.ImageDepthOutput.info.width * SenseToolkitManager.Instance.ImageDepthOutput.info.height];
}
data.ToFloatArray(0, _depthArray);
float depth = _depthArray[(int)trackedPoint.x + (int)trackedPoint.y * SenseToolkitManager.Instance.ImageDepthOutput.info.width];
if (_pos_uvz == null )
{
_pos_uvz = new PXCMPoint3DF32[1]{new PXCMPoint3DF32()};
}
_pos_uvz[0].x = trackedPoint.x;
_pos_uvz[0].y = trackedPoint.y;
_pos_uvz[0].z = depth;
if (_pos3d == null)
{
_pos3d = new PXCMPoint3DF32[1]{new PXCMPoint3DF32()};
}
SenseToolkitManager.Instance.Projection.ProjectDepthToCamera(_pos_uvz, _pos3d);
Vector3 position = new Vector3();
position.x = -_pos3d[0].x/10;
position.y = _pos3d[0].y/10 ;
position.z = _pos3d[0].z/10 ;
SenseToolkitManager.Instance.ImageDepthOutput.ReleaseAccess(data);
TrackingUtilityClass.ClampToRealWorldInputBox(ref position, RealWorldBoxCenter, RealWorldBoxDimensions);
TrackingUtilityClass.Normalize(ref position, RealWorldBoxCenter, RealWorldBoxDimensions);
if (!float.IsNaN(position.x) && !float.IsNaN(position.y) && !float.IsNaN(position.z))
{
specificTrigger.Position = position;
}
else
{
return false;
}
success = true;
}
}
else
{
return false;
}
return success;
}
#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.Text;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class LoopTests
{
private static class Unreadable<T>
{
public static T WriteOnly
{
set { }
}
}
private class IntegralException : Exception
{
public IntegralException(int number)
{
Number = number;
}
public int Number { get; }
}
[Fact]
public void NullBody()
{
AssertExtensions.Throws<ArgumentNullException>("body", () => Expression.Loop(null));
AssertExtensions.Throws<ArgumentNullException>("body", () => Expression.Loop(null, null));
AssertExtensions.Throws<ArgumentNullException>("body", () => Expression.Loop(null, null, null));
}
[Fact]
public void UnreadableBody()
{
Expression body = Expression.Property(null, typeof(Unreadable<int>), nameof(Unreadable<int>.WriteOnly));
AssertExtensions.Throws<ArgumentException>("body", () => Expression.Loop(body));
AssertExtensions.Throws<ArgumentException>("body", () => Expression.Loop(body, null));
AssertExtensions.Throws<ArgumentException>("body", () => Expression.Loop(body, null, null));
}
[Fact]
public void NonVoidContinue()
{
AssertExtensions.Throws<ArgumentException>("continue", () => Expression.Loop(Expression.Empty(), null, Expression.Label(typeof(int))));
}
[Fact]
public void TypeWithoutBreakIsVoid()
{
Assert.Equal(typeof(void), Expression.Loop(Expression.Constant(3)).Type);
Assert.Equal(typeof(void), Expression.Loop(Expression.Constant(3), null).Type);
Assert.Equal(typeof(void), Expression.Loop(Expression.Constant(3), null, null).Type);
}
[Fact]
public void TypeIsBreaksType()
{
LabelTarget voidLabelTarget = Expression.Label();
Assert.Equal(typeof(void), Expression.Loop(Expression.Constant(3), voidLabelTarget).Type);
Assert.Equal(typeof(void), Expression.Loop(Expression.Constant(3), voidLabelTarget, null).Type);
LabelTarget int32LabelTarget = Expression.Label(typeof(int));
Assert.Equal(typeof(int), Expression.Loop(Expression.Empty(), int32LabelTarget).Type);
Assert.Equal(typeof(int), Expression.Loop(Expression.Empty(), int32LabelTarget).Type);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void BreakWithinLoop(bool useInterpreter)
{
string labelName = "Not likely to appear for any other reason {E90FAF9D-1934-4FC9-93EB-BCE70B586146}";
LabelTarget @break = Expression.Label(labelName);
Expression<Action> lambda = Expression.Lambda<Action>(Expression.Loop(Expression.Label(@break), @break));
Assert.Contains(labelName, Assert.Throws<InvalidOperationException>(() => lambda.Compile(useInterpreter)).Message);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void ContinueWithinLoop(bool useInterpreter)
{
string labelName = "Not likely to appear for any other reason {F9C549FE-6E6C-44A2-A434-0147E0D49F7F}";
LabelTarget @continue = Expression.Label(labelName);
Expression<Action> lambda = Expression.Lambda<Action>(Expression.Loop(Expression.Label(@continue), null, @continue));
Assert.Throws<InvalidOperationException>(() => lambda.Compile());
Assert.Contains(labelName, Assert.Throws<InvalidOperationException>(() => lambda.Compile(useInterpreter)).Message);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void BreakOutsideLoop(bool useInterpreter)
{
string labelName = "Not likely to appear for any other reason {D3C6FCD8-EA2F-440B-938F-C81560C3BDBA}";
LabelTarget @break = Expression.Label(labelName);
Expression<Action> lambda = Expression.Lambda<Action>(
Expression.Block(
Expression.Label(@break),
Expression.Loop(Expression.Empty(), @break)
)
);
Assert.Contains(labelName, Assert.Throws<InvalidOperationException>(() => lambda.Compile(useInterpreter)).Message);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void ContinueOutsideLoop(bool useInterpreter)
{
string labelName = "Not likely to appear for any other reason {1107D64D-9FC4-4533-83E2-0F5F78B48315}";
LabelTarget @continue = Expression.Label(labelName);
Expression<Action> lambda = Expression.Lambda<Action>(
Expression.Block(
Expression.Label(@continue),
Expression.Loop(Expression.Empty(), null, @continue)
)
);
Assert.Contains(labelName, Assert.Throws<InvalidOperationException>(() => lambda.Compile(useInterpreter)).Message);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void ContinueTheSameAsBreak(bool useInterpreter)
{
string labelName = "Not likely to appear for any other reason {B9CD9CF5-6C67-41C9-98C0-F445CAAB5082}";
LabelTarget label = Expression.Label(labelName);
Expression<Action> lambda = Expression.Lambda<Action>(
Expression.Loop(Expression.Empty(), label, label)
);
Assert.Contains(labelName, Assert.Throws<InvalidOperationException>(() => lambda.Compile(useInterpreter)).Message);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void NoLabelsInfiniteLoop(bool useInterpreter)
{
// Have an error condition so the otherwise-infinite loop can complete.
ParameterExpression num = Expression.Variable(typeof(int));
Action spinThenThrow = Expression.Lambda<Action>(
Expression.Block(
new[] {num},
Expression.Assign(num, Expression.Constant(0)),
Expression.Loop(
Expression.IfThen(
Expression.GreaterThan(
Expression.PreIncrementAssign(num),
Expression.Constant(19)
),
Expression.Throw(
Expression.New(
typeof(IntegralException).GetConstructor(new[] {typeof(int)}),
num
)
)
)
)
)
).Compile(useInterpreter);
Assert.Equal(20, Assert.Throws<IntegralException>(spinThenThrow).Number);
}
public void NoBreakToLabelInfiniteLoop(bool useInterpreter)
{
// Have an error condition so the otherwise-infinite loop can complete.
ParameterExpression num = Expression.Variable(typeof(int));
Func<int> spinThenThrow = Expression.Lambda<Func<int>>(
Expression.Block(
new[] { num },
Expression.Assign(num, Expression.Constant(0)),
Expression.Loop(
Expression.IfThen(
Expression.GreaterThan(
Expression.PreIncrementAssign(num),
Expression.Constant(19)
),
Expression.Throw(
Expression.New(
typeof(IntegralException).GetConstructor(new[] { typeof(int) }),
num
)
)
),
Expression.Label(typeof(int))
)
)
).Compile(useInterpreter);
Assert.Equal(20, Assert.Throws<IntegralException>(() => spinThenThrow()).Number);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void ExplicitContinue(bool useInterpreter)
{
var builder = new StringBuilder();
ParameterExpression value = Expression.Variable(typeof(int));
LabelTarget @break = Expression.Label();
LabelTarget @continue = Expression.Label();
Reflection.MethodInfo append = typeof(StringBuilder).GetMethod(nameof(StringBuilder.Append), new[] {typeof(int)});
Action act = Expression.Lambda<Action>(
Expression.Block(
new[] {value},
Expression.Assign(value, Expression.Constant(0)),
Expression.Loop(
Expression.Block(
Expression.PostIncrementAssign(value),
Expression.IfThen(
Expression.GreaterThanOrEqual(value, Expression.Constant(10)),
Expression.Break(@break)
),
Expression.IfThen(
Expression.Equal(
Expression.Modulo(value, Expression.Constant(2)),
Expression.Constant(0)
),
Expression.Continue(@continue)
),
Expression.Call(Expression.Constant(builder), append, value)
),
@break,
@continue
)
)
).Compile(useInterpreter);
act();
Assert.Equal("13579", builder.ToString());
}
[Theory, ClassData(typeof(CompilationTypes))]
public void LoopWithBreak(bool useInterpreter)
{
ParameterExpression value = Expression.Parameter(typeof(int));
ParameterExpression result = Expression.Variable(typeof(int));
LabelTarget label = Expression.Label(typeof(int));
BlockExpression block = Expression.Block(
new[] {result},
Expression.Assign(result, Expression.Constant(1)),
Expression.Loop(
Expression.IfThenElse(
Expression.GreaterThan(value, Expression.Constant(1)),
Expression.MultiplyAssign(result,
Expression.PostDecrementAssign(value)),
Expression.Break(label, result)
),
label
)
);
Func<int, int> factorial = Expression.Lambda<Func<int, int>>(block, value).Compile(useInterpreter);
Assert.Equal(120, factorial(5));
}
[Fact]
public void CannotReduce()
{
LoopExpression loop = Expression.Loop(Expression.Empty(), Expression.Label(), Expression.Label());
Assert.False(loop.CanReduce);
Assert.Same(loop, loop.Reduce());
Assert.Throws<ArgumentException>(null, () => loop.ReduceAndCheck());
}
[Fact]
public void UpdateSameIsSame()
{
LoopExpression loop = Expression.Loop(Expression.Empty(), Expression.Label(), Expression.Label());
Assert.Same(loop, loop.Update(loop.BreakLabel, loop.ContinueLabel, loop.Body));
}
[Fact]
public void UpdateDifferentBodyIsDifferent()
{
LoopExpression loop = Expression.Loop(Expression.Empty(), Expression.Label(), Expression.Label());
Assert.NotSame(loop, loop.Update(loop.BreakLabel, loop.ContinueLabel, Expression.Empty()));
}
[Fact]
public void UpdateDifferentBreakIsDifferent()
{
LoopExpression loop = Expression.Loop(Expression.Empty(), Expression.Label(), Expression.Label());
Assert.NotSame(loop, loop.Update(Expression.Label(), loop.ContinueLabel, loop.Body));
}
[Fact]
public void UpdateDifferentContinueIsDifferent()
{
LoopExpression loop = Expression.Loop(Expression.Empty(), Expression.Label(), Expression.Label());
Assert.NotSame(loop, loop.Update(loop.BreakLabel, Expression.Label(), loop.Body));
}
[Fact]
public void ToStringTest()
{
LoopExpression e = Expression.Loop(Expression.Empty());
Assert.Equal("loop { ... }", e.ToString());
}
}
}
| |
using System;
using System.Collections;
using System.Text;
namespace NetOffice.DeveloperToolbox.Controls.Hex
{
internal class DataMap : ICollection, IEnumerable
{
readonly object _syncRoot = new object();
internal int _count;
internal DataBlock _firstBlock;
internal int _version;
public DataMap()
{
}
public DataMap(IEnumerable collection)
{
if (collection == null)
throw new ArgumentNullException("collection");
foreach (DataBlock item in collection)
AddLast(item);
}
public DataBlock FirstBlock
{
get
{
return _firstBlock;
}
}
public void AddAfter(DataBlock block, DataBlock newBlock)
{
AddAfterInternal(block, newBlock);
}
public void AddBefore(DataBlock block, DataBlock newBlock)
{
AddBeforeInternal(block, newBlock);
}
public void AddFirst(DataBlock block)
{
if (_firstBlock == null)
AddBlockToEmptyMap(block);
else
AddBeforeInternal(_firstBlock, block);
}
public void AddLast(DataBlock block)
{
if (_firstBlock == null)
AddBlockToEmptyMap(block);
else
AddAfterInternal(GetLastBlock(), block);
}
public void Remove(DataBlock block)
{
RemoveInternal(block);
}
public void RemoveFirst()
{
if (_firstBlock == null)
throw new InvalidOperationException("The collection is empty.");
RemoveInternal(_firstBlock);
}
public void RemoveLast()
{
if (_firstBlock == null)
throw new InvalidOperationException("The collection is empty.");
RemoveInternal(GetLastBlock());
}
public DataBlock Replace(DataBlock block, DataBlock newBlock)
{
AddAfterInternal(block, newBlock);
RemoveInternal(block);
return newBlock;
}
public void Clear()
{
DataBlock block = FirstBlock;
while (block != null)
{
DataBlock nextBlock = block.NextBlock;
InvalidateBlock(block);
block = nextBlock;
}
_firstBlock = null;
_count = 0;
_version++;
}
void AddAfterInternal(DataBlock block, DataBlock newBlock)
{
newBlock._previousBlock = block;
newBlock._nextBlock = block._nextBlock;
newBlock._map = this;
if (block._nextBlock != null)
block._nextBlock._previousBlock = newBlock;
block._nextBlock = newBlock;
this._version++;
this._count++;
}
void AddBeforeInternal(DataBlock block, DataBlock newBlock)
{
newBlock._nextBlock = block;
newBlock._previousBlock = block._previousBlock;
newBlock._map = this;
if (block._previousBlock != null)
block._previousBlock._nextBlock = newBlock;
block._previousBlock = newBlock;
if (_firstBlock == block)
_firstBlock = newBlock;
this._version++;
this._count++;
}
void RemoveInternal(DataBlock block)
{
DataBlock previousBlock = block._previousBlock;
DataBlock nextBlock = block._nextBlock;
if (previousBlock != null)
previousBlock._nextBlock = nextBlock;
if (nextBlock != null)
nextBlock._previousBlock = previousBlock;
if (_firstBlock == block)
_firstBlock = nextBlock;
InvalidateBlock(block);
_count--;
_version++;
}
DataBlock GetLastBlock()
{
DataBlock lastBlock = null;
for (DataBlock block = FirstBlock; block != null; block = block.NextBlock)
{
lastBlock = block;
}
return lastBlock;
}
void InvalidateBlock(DataBlock block)
{
block._map = null;
block._nextBlock = null;
block._previousBlock = null;
}
void AddBlockToEmptyMap(DataBlock block)
{
block._map = this;
block._nextBlock = null;
block._previousBlock = null;
_firstBlock = block;
_version++;
_count++;
}
#region ICollection Members
public void CopyTo(Array array, int index)
{
DataBlock[] blockArray = array as DataBlock[];
for (DataBlock block = FirstBlock; block != null; block = block.NextBlock)
{
blockArray[index++] = block;
}
}
public int Count
{
get
{
return _count;
}
}
public bool IsSynchronized
{
get
{
return false;
}
}
public object SyncRoot
{
get
{
return _syncRoot;
}
}
#endregion
#region IEnumerable Members
public IEnumerator GetEnumerator()
{
return new Enumerator(this);
}
#endregion
#region Enumerator Nested Type
internal class Enumerator : IEnumerator, IDisposable
{
DataMap _map;
DataBlock _current;
int _index;
int _version;
internal Enumerator(DataMap map)
{
_map = map;
_version = map._version;
_current = null;
_index = -1;
}
object IEnumerator.Current
{
get
{
if (_index < 0 || _index > _map.Count)
{
throw new InvalidOperationException("Enumerator is positioned before the first element or after the last element of the collection.");
}
return _current;
}
}
public bool MoveNext()
{
if (this._version != _map._version)
{
throw new InvalidOperationException("Collection was modified after the enumerator was instantiated.");
}
if (_index >= _map.Count)
{
return false;
}
if (++_index == 0)
{
_current = _map.FirstBlock;
}
else
{
_current = _current.NextBlock;
}
return (_index < _map.Count);
}
void IEnumerator.Reset()
{
if (this._version != this._map._version)
{
throw new InvalidOperationException("Collection was modified after the enumerator was instantiated.");
}
this._index = -1;
this._current = null;
}
public void Dispose()
{
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.DiaSymReader;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal sealed class EvaluationContext : EvaluationContextBase
{
private const string TypeName = "<>x";
private const string MethodName = "<>m0";
internal const bool IsLocalScopeEndInclusive = false;
internal readonly ImmutableArray<MetadataBlock> MetadataBlocks;
internal readonly MethodContextReuseConstraints? MethodContextReuseConstraints;
internal readonly CSharpCompilation Compilation;
private readonly MetadataDecoder _metadataDecoder;
private readonly MethodSymbol _currentFrame;
private readonly ImmutableArray<LocalSymbol> _locals;
private readonly InScopeHoistedLocals _inScopeHoistedLocals;
private readonly MethodDebugInfo _methodDebugInfo;
private EvaluationContext(
ImmutableArray<MetadataBlock> metadataBlocks,
MethodContextReuseConstraints? methodContextReuseConstraints,
CSharpCompilation compilation,
MetadataDecoder metadataDecoder,
MethodSymbol currentFrame,
ImmutableArray<LocalSymbol> locals,
InScopeHoistedLocals inScopeHoistedLocals,
MethodDebugInfo methodDebugInfo)
{
Debug.Assert(inScopeHoistedLocals != null);
this.MetadataBlocks = metadataBlocks;
this.MethodContextReuseConstraints = methodContextReuseConstraints;
this.Compilation = compilation;
_metadataDecoder = metadataDecoder;
_currentFrame = currentFrame;
_locals = locals;
_inScopeHoistedLocals = inScopeHoistedLocals;
_methodDebugInfo = methodDebugInfo;
}
/// <summary>
/// Create a context for evaluating expressions at a type scope.
/// </summary>
/// <param name="previous">Previous context, if any, for possible re-use.</param>
/// <param name="metadataBlocks">Module metadata</param>
/// <param name="moduleVersionId">Module containing type</param>
/// <param name="typeToken">Type metadata token</param>
/// <returns>Evaluation context</returns>
/// <remarks>
/// No locals since locals are associated with methods, not types.
/// </remarks>
internal static EvaluationContext CreateTypeContext(
CSharpMetadataContext previous,
ImmutableArray<MetadataBlock> metadataBlocks,
Guid moduleVersionId,
int typeToken)
{
Debug.Assert(MetadataTokens.Handle(typeToken).Kind == HandleKind.TypeDefinition);
// Re-use the previous compilation if possible.
var compilation = previous.Matches(metadataBlocks) ?
previous.Compilation :
metadataBlocks.ToCompilation();
MetadataDecoder metadataDecoder;
var currentType = compilation.GetType(moduleVersionId, typeToken, out metadataDecoder);
Debug.Assert((object)currentType != null);
Debug.Assert(metadataDecoder != null);
var currentFrame = new SynthesizedContextMethodSymbol(currentType);
return new EvaluationContext(
metadataBlocks,
null,
compilation,
metadataDecoder,
currentFrame,
default(ImmutableArray<LocalSymbol>),
InScopeHoistedLocals.Empty,
default(MethodDebugInfo));
}
/// <summary>
/// Create a context for evaluating expressions within a method scope.
/// </summary>
/// <param name="previous">Previous context, if any, for possible re-use.</param>
/// <param name="metadataBlocks">Module metadata</param>
/// <param name="symReader"><see cref="ISymUnmanagedReader"/> for PDB associated with <paramref name="moduleVersionId"/></param>
/// <param name="moduleVersionId">Module containing method</param>
/// <param name="methodToken">Method metadata token</param>
/// <param name="methodVersion">Method version.</param>
/// <param name="ilOffset">IL offset of instruction pointer in method</param>
/// <param name="localSignatureToken">Method local signature token</param>
/// <returns>Evaluation context</returns>
internal static EvaluationContext CreateMethodContext(
CSharpMetadataContext previous,
ImmutableArray<MetadataBlock> metadataBlocks,
object symReader,
Guid moduleVersionId,
int methodToken,
int methodVersion,
int ilOffset,
int localSignatureToken)
{
Debug.Assert(MetadataTokens.Handle(methodToken).Kind == HandleKind.MethodDefinition);
// Re-use the previous compilation if possible.
CSharpCompilation compilation;
if (previous.Matches(metadataBlocks))
{
// Re-use entire context if method scope has not changed.
var previousContext = previous.EvaluationContext;
if (previousContext != null &&
previousContext.MethodContextReuseConstraints.HasValue &&
previousContext.MethodContextReuseConstraints.GetValueOrDefault().AreSatisfied(moduleVersionId, methodToken, methodVersion, ilOffset))
{
return previousContext;
}
compilation = previous.Compilation;
}
else
{
compilation = metadataBlocks.ToCompilation();
}
var typedSymReader = (ISymUnmanagedReader)symReader;
var allScopes = ArrayBuilder<ISymUnmanagedScope>.GetInstance();
var containingScopes = ArrayBuilder<ISymUnmanagedScope>.GetInstance();
typedSymReader.GetScopes(methodToken, methodVersion, ilOffset, IsLocalScopeEndInclusive, allScopes, containingScopes);
var methodContextReuseConstraints = allScopes.GetReuseConstraints(moduleVersionId, methodToken, methodVersion, ilOffset, IsLocalScopeEndInclusive);
allScopes.Free();
var localNames = containingScopes.GetLocalNames();
var inScopeHoistedLocals = InScopeHoistedLocals.Empty;
var methodDebugInfo = default(MethodDebugInfo);
if (typedSymReader != null)
{
try
{
// TODO (https://github.com/dotnet/roslyn/issues/702): switch on the type of typedSymReader and call the appropriate helper.
methodDebugInfo = typedSymReader.GetMethodDebugInfo(methodToken, methodVersion, localNames.FirstOrDefault());
var inScopeHoistedLocalIndices = methodDebugInfo.GetInScopeHoistedLocalIndices(ilOffset, ref methodContextReuseConstraints);
inScopeHoistedLocals = new CSharpInScopeHoistedLocals(inScopeHoistedLocalIndices);
}
catch (InvalidOperationException)
{
// bad CDI, ignore
}
}
var methodHandle = (MethodDefinitionHandle)MetadataTokens.Handle(methodToken);
var currentFrame = compilation.GetMethod(moduleVersionId, methodHandle);
Debug.Assert((object)currentFrame != null);
var metadataDecoder = new MetadataDecoder((PEModuleSymbol)currentFrame.ContainingModule, currentFrame);
var localInfo = metadataDecoder.GetLocalInfo(localSignatureToken);
var localBuilder = ArrayBuilder<LocalSymbol>.GetInstance();
var sourceAssembly = compilation.SourceAssembly;
GetLocals(localBuilder, currentFrame, localNames, localInfo, methodDebugInfo.DynamicLocalMap, sourceAssembly);
GetConstants(localBuilder, currentFrame, containingScopes.GetConstantSignatures(), metadataDecoder, methodDebugInfo.DynamicLocalConstantMap, sourceAssembly);
containingScopes.Free();
var locals = localBuilder.ToImmutableAndFree();
return new EvaluationContext(
metadataBlocks,
methodContextReuseConstraints,
compilation,
metadataDecoder,
currentFrame,
locals,
inScopeHoistedLocals,
methodDebugInfo);
}
internal CompilationContext CreateCompilationContext(CSharpSyntaxNode syntax)
{
return new CompilationContext(
this.Compilation,
_metadataDecoder,
_currentFrame,
_locals,
_inScopeHoistedLocals,
_methodDebugInfo,
syntax);
}
internal override CompileResult CompileExpression(
InspectionContext inspectionContext,
string expr,
DkmEvaluationFlags compilationFlags,
DiagnosticFormatter formatter,
out ResultProperties resultProperties,
out string error,
out ImmutableArray<AssemblyIdentity> missingAssemblyIdentities,
System.Globalization.CultureInfo preferredUICulture,
Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData)
{
resultProperties = default(ResultProperties);
var diagnostics = DiagnosticBag.GetInstance();
try
{
ReadOnlyCollection<string> formatSpecifiers;
var syntax = Parse(expr, (compilationFlags & DkmEvaluationFlags.TreatAsExpression) != 0, diagnostics, out formatSpecifiers);
if (syntax == null)
{
error = GetErrorMessageAndMissingAssemblyIdentities(diagnostics, formatter, preferredUICulture, out missingAssemblyIdentities);
return default(CompileResult);
}
var context = this.CreateCompilationContext(syntax);
ResultProperties properties;
var moduleBuilder = context.CompileExpression(inspectionContext, TypeName, MethodName, testData, diagnostics, out properties);
if (moduleBuilder == null)
{
error = GetErrorMessageAndMissingAssemblyIdentities(diagnostics, formatter, preferredUICulture, out missingAssemblyIdentities);
return default(CompileResult);
}
using (var stream = new MemoryStream())
{
Cci.PeWriter.WritePeToStream(
new EmitContext((Cci.IModule)moduleBuilder, null, diagnostics),
context.MessageProvider,
() => stream,
nativePdbWriterOpt: null,
allowMissingMethodBodies: false,
deterministic: false,
cancellationToken: default(CancellationToken));
if (diagnostics.HasAnyErrors())
{
error = GetErrorMessageAndMissingAssemblyIdentities(diagnostics, formatter, preferredUICulture, out missingAssemblyIdentities);
return default(CompileResult);
}
resultProperties = properties;
error = null;
missingAssemblyIdentities = ImmutableArray<AssemblyIdentity>.Empty;
return new CompileResult(
stream.ToArray(),
typeName: TypeName,
methodName: MethodName,
formatSpecifiers: formatSpecifiers);
}
}
finally
{
diagnostics.Free();
}
}
private static CSharpSyntaxNode Parse(
string expr,
bool treatAsExpression,
DiagnosticBag diagnostics,
out ReadOnlyCollection<string> formatSpecifiers)
{
if (treatAsExpression)
{
return expr.ParseExpression(diagnostics, allowFormatSpecifiers: true, formatSpecifiers: out formatSpecifiers);
}
else
{
// Try to parse as an expression. If that fails, parse as a statement.
var exprDiagnostics = DiagnosticBag.GetInstance();
ReadOnlyCollection<string> exprFormatSpecifiers;
CSharpSyntaxNode syntax = expr.ParseExpression(exprDiagnostics, allowFormatSpecifiers: true, formatSpecifiers: out exprFormatSpecifiers);
Debug.Assert((syntax == null) || !exprDiagnostics.HasAnyErrors());
exprDiagnostics.Free();
if (syntax != null)
{
Debug.Assert(!diagnostics.HasAnyErrors());
formatSpecifiers = exprFormatSpecifiers;
return syntax;
}
formatSpecifiers = null;
syntax = expr.ParseStatement(diagnostics);
if ((syntax != null) && (syntax.Kind() != SyntaxKind.LocalDeclarationStatement))
{
diagnostics.Add(ErrorCode.ERR_ExpressionOrDeclarationExpected, Location.None);
return null;
}
return syntax;
}
}
internal override CompileResult CompileAssignment(
InspectionContext inspectionContext,
string target,
string expr,
DiagnosticFormatter formatter,
out ResultProperties resultProperties,
out string error,
out ImmutableArray<AssemblyIdentity> missingAssemblyIdentities,
System.Globalization.CultureInfo preferredUICulture,
Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData)
{
var diagnostics = DiagnosticBag.GetInstance();
try
{
var assignment = target.ParseAssignment(expr, diagnostics);
if (assignment == null)
{
error = GetErrorMessageAndMissingAssemblyIdentities(diagnostics, formatter, preferredUICulture, out missingAssemblyIdentities);
resultProperties = default(ResultProperties);
return default(CompileResult);
}
var context = this.CreateCompilationContext(assignment);
ResultProperties properties;
var moduleBuilder = context.CompileAssignment(inspectionContext, TypeName, MethodName, testData, diagnostics, out properties);
if (moduleBuilder == null)
{
error = GetErrorMessageAndMissingAssemblyIdentities(diagnostics, formatter, preferredUICulture, out missingAssemblyIdentities);
resultProperties = default(ResultProperties);
return default(CompileResult);
}
using (var stream = new MemoryStream())
{
Cci.PeWriter.WritePeToStream(
new EmitContext((Cci.IModule)moduleBuilder, null, diagnostics),
context.MessageProvider,
() => stream,
nativePdbWriterOpt: null,
allowMissingMethodBodies: false,
deterministic: false,
cancellationToken: default(CancellationToken));
if (diagnostics.HasAnyErrors())
{
error = GetErrorMessageAndMissingAssemblyIdentities(diagnostics, formatter, preferredUICulture, out missingAssemblyIdentities);
resultProperties = default(ResultProperties);
return default(CompileResult);
}
resultProperties = properties;
error = null;
missingAssemblyIdentities = ImmutableArray<AssemblyIdentity>.Empty;
return new CompileResult(
stream.ToArray(),
typeName: TypeName,
methodName: MethodName,
formatSpecifiers: null);
}
}
finally
{
diagnostics.Free();
}
}
private static readonly ReadOnlyCollection<byte> s_emptyBytes = new ReadOnlyCollection<byte>(new byte[0]);
internal override ReadOnlyCollection<byte> CompileGetLocals(
ArrayBuilder<LocalAndMethod> locals,
bool argumentsOnly,
out string typeName,
Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData = null)
{
var diagnostics = DiagnosticBag.GetInstance();
var context = this.CreateCompilationContext(null);
var moduleBuilder = context.CompileGetLocals(TypeName, locals, argumentsOnly, testData, diagnostics);
ReadOnlyCollection<byte> assembly = null;
if ((moduleBuilder != null) && (locals.Count > 0))
{
using (var stream = new MemoryStream())
{
Cci.PeWriter.WritePeToStream(
new EmitContext((Cci.IModule)moduleBuilder, null, diagnostics),
context.MessageProvider,
() => stream,
nativePdbWriterOpt: null,
allowMissingMethodBodies: false,
deterministic: false,
cancellationToken: default(CancellationToken));
if (!diagnostics.HasAnyErrors())
{
assembly = new ReadOnlyCollection<byte>(stream.ToArray());
}
}
}
diagnostics.Free();
if (assembly == null)
{
locals.Clear();
assembly = s_emptyBytes;
}
typeName = TypeName;
return assembly;
}
/// <summary>
/// Returns symbols for the locals emitted in the original method,
/// based on the local signatures from the IL and the names and
/// slots from the PDB. The actual locals are needed to ensure the
/// local slots in the generated method match the original.
/// </summary>
private static void GetLocals(
ArrayBuilder<LocalSymbol> builder,
MethodSymbol method,
ImmutableArray<string> names,
ImmutableArray<LocalInfo<TypeSymbol>> localInfo,
ImmutableDictionary<int, ImmutableArray<bool>> dynamicLocalMap,
SourceAssemblySymbol containingAssembly)
{
if (localInfo.Length == 0)
{
// When debugging a .dmp without a heap, localInfo will be empty although
// names may be non-empty if there is a PDB. Since there's no type info, the
// locals are dropped. Note this means the local signature of any generated
// method will not match the original signature, so new locals will overlap
// original locals. That is ok since there is no live process for the debugger
// to update (any modified values exist in the debugger only).
return;
}
Debug.Assert(localInfo.Length >= names.Length);
for (int i = 0; i < localInfo.Length; i++)
{
var name = (i < names.Length) ? names[i] : null;
var info = localInfo[i];
var isPinned = info.IsPinned;
LocalDeclarationKind kind;
RefKind refKind;
TypeSymbol type;
if (info.IsByRef && isPinned)
{
kind = LocalDeclarationKind.FixedVariable;
refKind = RefKind.None;
type = new PointerTypeSymbol(info.Type);
}
else
{
kind = LocalDeclarationKind.RegularVariable;
refKind = info.IsByRef ? RefKind.Ref : RefKind.None;
type = info.Type;
}
ImmutableArray<bool> dynamicFlags;
if (dynamicLocalMap != null && dynamicLocalMap.TryGetValue(i, out dynamicFlags))
{
type = DynamicTypeDecoder.TransformTypeWithoutCustomModifierFlags(
type,
containingAssembly,
refKind,
dynamicFlags);
}
// Custom modifiers can be dropped since binding ignores custom
// modifiers from locals and since we only need to preserve
// the type of the original local in the generated method.
builder.Add(new EELocalSymbol(method, EELocalSymbol.NoLocations, name, i, kind, type, refKind, isPinned, isCompilerGenerated: false, canScheduleToStack: false));
}
}
private static void GetConstants(
ArrayBuilder<LocalSymbol> builder,
MethodSymbol method,
ImmutableArray<NamedLocalConstant> constants,
MetadataDecoder metadataDecoder,
ImmutableDictionary<string, ImmutableArray<bool>> dynamicLocalConstantMap,
SourceAssemblySymbol containingAssembly)
{
foreach (var constant in constants)
{
var info = metadataDecoder.GetLocalInfo(constant.Signature);
Debug.Assert(!info.IsByRef);
Debug.Assert(!info.IsPinned);
var type = info.Type;
ImmutableArray<bool> dynamicFlags;
if (dynamicLocalConstantMap != null && dynamicLocalConstantMap.TryGetValue(constant.Name, out dynamicFlags))
{
type = DynamicTypeDecoder.TransformTypeWithoutCustomModifierFlags(
type,
containingAssembly,
RefKind.None,
dynamicFlags);
}
var constantValue = ReinterpretConstantValue(constant.Value, type.SpecialType);
builder.Add(new EELocalConstantSymbol(method, constant.Name, type, constantValue));
}
}
internal override ImmutableArray<AssemblyIdentity> GetMissingAssemblyIdentities(Diagnostic diagnostic)
{
return GetMissingAssemblyIdentitiesHelper((ErrorCode)diagnostic.Code, diagnostic.Arguments);
}
/// <remarks>
/// Internal for testing.
/// </remarks>
internal static ImmutableArray<AssemblyIdentity> GetMissingAssemblyIdentitiesHelper(ErrorCode code, IReadOnlyList<object> arguments)
{
switch (code)
{
case ErrorCode.ERR_NoTypeDef:
case ErrorCode.ERR_GlobalSingleTypeNameNotFoundFwd:
case ErrorCode.ERR_DottedTypeNameNotFoundInNSFwd:
case ErrorCode.ERR_SingleTypeNameNotFoundFwd:
case ErrorCode.ERR_NameNotInContextPossibleMissingReference: // Probably can't happen.
foreach (var argument in arguments)
{
var identity = (argument as AssemblyIdentity) ?? (argument as AssemblySymbol)?.Identity;
if (identity != null && !identity.Equals(MissingCorLibrarySymbol.Instance.Identity))
{
return ImmutableArray.Create(identity);
}
}
break;
case ErrorCode.ERR_DottedTypeNameNotFoundInNS:
if (arguments.Count == 2)
{
var namespaceName = arguments[0] as string;
var containingNamespace = arguments[1] as NamespaceSymbol;
if (namespaceName != null && (object)containingNamespace != null &&
containingNamespace.ConstituentNamespaces.Any(n => n.ContainingAssembly.Identity.IsWindowsAssemblyIdentity()))
{
// This is just a heuristic, but it has the advantage of being portable, particularly
// across different versions of (desktop) windows.
var identity = new AssemblyIdentity($"{containingNamespace.ToDisplayString()}.{namespaceName}", contentType: System.Reflection.AssemblyContentType.WindowsRuntime);
return ImmutableArray.Create(identity);
}
}
break;
case ErrorCode.ERR_DynamicAttributeMissing:
case ErrorCode.ERR_DynamicRequiredTypesMissing:
// MSDN says these might come from System.Dynamic.Runtime
case ErrorCode.ERR_QueryNoProviderStandard:
case ErrorCode.ERR_ExtensionAttrNotFound: // Probably can't happen.
return ImmutableArray.Create(SystemCoreIdentity);
case ErrorCode.ERR_BadAwaitArg_NeedSystem:
Debug.Assert(false, "Roslyn no longer produces ERR_BadAwaitArg_NeedSystem");
break;
}
return default(ImmutableArray<AssemblyIdentity>);
}
}
}
| |
//
// ColorGradientWidget.cs
//
// Author:
// Krzysztof Marecki <marecki.krzysztof@gmail.com>
//
// Copyright (c) 2010 Krzysztof Marecki
//
// 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;
using System.Linq;
using Cairo;
using Pinta.Core;
namespace Pinta.Gui.Widgets
{
[System.ComponentModel.ToolboxItem(true)]
public partial class ColorGradientWidget : Gtk.Bin
{
//gradient horizontal padding
private const double xpad = 0.15;
//gradient vertical padding
private const double ypad = 0.03;
private double[] vals;
private Rectangle GradientRectangle {
get {
Rectangle rect = Allocation.ToCairoRectangle ();
double x = rect.X + xpad * rect.Width;
double y = rect.Y + ypad * rect.Height;
double width = (1 - 2 * xpad) * rect.Width;
double height = (1 - 2 * ypad) * rect.Height;
return new Rectangle (x, y, width, height);
}
}
[Category("Custom Properties")]
public int Count {
get { return vals.Length; }
set {
if (value < 2 || value > 3) {
throw new ArgumentOutOfRangeException("value", value, "Count must be 2 or 3");
}
vals = new double[value];
double step = 256 / (value - 1);
for (int i = 0; i < value ; i++) {
vals [i] = i * step - ((i != 0) ? 1 : 0);
}
}
}
public Color MaxColor { get; set; }
public int ValueIndex { get; private set; }
public ColorGradientWidget ()
{
this.Build ();
ValueIndex = -1;
eventbox.MotionNotifyEvent += HandleMotionNotifyEvent;
eventbox.LeaveNotifyEvent += HandleLeaveNotifyEvent;
eventbox.ButtonPressEvent += HandleButtonPressEvent;
eventbox.ButtonReleaseEvent += HandleButtonReleaseEvent;
ExposeEvent += HandleExposeEvent;
}
public int GetValue (int i)
{
return (int) vals [i];
}
public void SetValue (int i, int val)
{
if ((int)vals [i] != val) {
vals [i] = val;
OnValueChanged (i);
}
}
private double GetYFromValue (double val)
{
Rectangle rect = GradientRectangle;
Rectangle all = Allocation.ToCairoRectangle ();
return all.Y + ypad * all.Height + rect.Height * (255 - val) / 255;
}
private double NormalizeY (int index, double py)
{
Rectangle rect = GradientRectangle;
var yvals = (from val in vals select GetYFromValue (val)).Concat(
new double[] {rect.Y, rect.Y + rect.Height}).OrderByDescending (
v => v).ToArray();
index++;
if (py >= yvals [index - 1]) {
py = yvals [index - 1];
} else if (py < yvals [index + 1]) {
py = yvals [index + 1];
}
return py;
}
private int GetValueFromY (double py)
{
Rectangle rect = GradientRectangle;
Rectangle all = Allocation.ToCairoRectangle ();
py -= all.Y + ypad * all.Height;
return ((int)(255 * (rect.Height - py) / rect.Height));
}
private int FindValueIndex(int y)
{
if (ValueIndex == -1) {
var yvals = (from val in vals select GetYFromValue (val)).ToArray ();
int count = Count - 1;
for (int i = 0; i < count; i++) {
double y1 = yvals [i];
double y2 = yvals [i + 1];
double h = (y1 - y2) / 2;
// pointer is below the lowest value triangle
if (i == 0 && y1 < y)
return i;
// pointer is above the highest value triangle
if (i == (count - 1) && y2 > y)
return i + 1;
// pointer is outside i and i + 1 value triangles
if (!(y1 >= y && y >= y2))
continue;
// pointer is closer to lower value triangle
if (y1 - y <= h) return i;
// pointer is closer to higher value triangle
if (y - y2 <= h) return i + 1;
}
return -1;
} else {
return ValueIndex;
}
}
private void HandleMotionNotifyEvent (object o, Gtk.MotionNotifyEventArgs args)
{
int px, py;
Gdk.ModifierType mask;
GdkWindow.GetPointer (out px, out py, out mask);
int index = FindValueIndex (py);
py = (int)NormalizeY (index, py);
if (mask == Gdk.ModifierType.Button1Mask) {
if (index != -1) {
double y = GetValueFromY (py);
vals[index] = y;
OnValueChanged (index);
}
}
//to avoid unnessesary costly redrawing
if (index != -1)
GdkWindow.Invalidate ();
}
private void HandleLeaveNotifyEvent (object o, Gtk.LeaveNotifyEventArgs args)
{
if (args.Event.State != Gdk.ModifierType.Button1Mask)
ValueIndex = -1;
GdkWindow.Invalidate ();
}
void HandleButtonPressEvent (object o, Gtk.ButtonPressEventArgs args)
{
int px, py;
Gdk.ModifierType mask;
GdkWindow.GetPointer (out px, out py, out mask);
int index = FindValueIndex ((int)py);
if (index != -1)
ValueIndex = index;
}
void HandleButtonReleaseEvent (object o, Gtk.ButtonReleaseEventArgs args)
{
ValueIndex = -1;
}
private void DrawGradient (Context g)
{
Rectangle rect = GradientRectangle;
Gradient pat = new LinearGradient(rect.X, rect.Y, rect.X,
rect.Y + rect.Height);
pat.AddColorStop (0, MaxColor);
pat.AddColorStop (1, new Cairo.Color (0, 0, 0));
g.Rectangle (rect);
g.SetSource (pat);
g.Fill();
}
private void DrawTriangles (Context g)
{
int px, py;
Gdk.ModifierType mask;
GdkWindow.GetPointer (out px, out py, out mask);
Rectangle rect = GradientRectangle;
Rectangle all = Allocation.ToCairoRectangle();
int index = FindValueIndex (py);
for (int i = 0; i < Count; i++) {
double val = vals [i];
double y = GetYFromValue (val);
bool hoover = ((index == i)) && (all.ContainsPoint (px, py) || ValueIndex != -1);
Color color = hoover ? new Color (0.1, 0.1, 0.9) : new Color (0.1, 0.1, 0.1);
//left triangle
PointD[] points = new PointD[] { new PointD (rect.X, y),
new PointD (rect.X - xpad * rect.Width, y + ypad * rect.Height),
new PointD (rect.X - xpad * rect.Width, y - ypad * rect.Height) };
g.FillPolygonal (points, color);
double x = rect.X + rect.Width;
//right triangle
PointD[] points2 = new PointD[] { new PointD (x , y),
new PointD (x + xpad * rect.Width, y + ypad * rect.Height),
new PointD (x + xpad * rect.Width, y - ypad * rect.Height) };
g.FillPolygonal (points2, color);
}
}
private void HandleExposeEvent (object o, Gtk.ExposeEventArgs args)
{
using (Context g = Gdk.CairoHelper.Create (this.GdkWindow)) {
DrawGradient (g);
DrawTriangles (g);
}
}
#region Protected Methods
protected void OnValueChanged(int index)
{
if (ValueChanged != null) {
ValueChanged(this, new IndexEventArgs (index));
}
}
#endregion
#region Public Events
public event IndexEventHandler ValueChanged;
#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.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.WindowsRuntime.Internal;
using System.Security;
using System.Threading;
using Windows.Foundation;
using Windows.Storage.Streams;
namespace System.Runtime.InteropServices.WindowsRuntime
{
/// <summary>
/// Contains an implementation of the WinRT IBuffer interface that conforms to all requirements on classes that implement that interface,
/// such as implementing additional interfaces.
/// </summary>
public sealed class WindowsRuntimeBuffer : IBuffer, IBufferByteAccess, IMarshal, IAgileObject
{
#region Constants
private const String WinTypesDLL = "WinTypes.dll";
private enum MSHCTX : int { Local = 0, NoSharedMem = 1, DifferentMachine = 2, InProc = 3, CrossCtx = 4 }
private enum MSHLFLAGS : int { Normal = 0, TableStrong = 1, TableWeak = 2, NoPing = 4 }
#endregion Constants
#region Static factory methods
[CLSCompliant(false)]
public static IBuffer Create(Int32 capacity)
{
if (capacity < 0) throw new ArgumentOutOfRangeException("capacity");
Contract.Ensures(Contract.Result<IBuffer>() != null);
Contract.Ensures(Contract.Result<IBuffer>().Length == unchecked((UInt32)0));
Contract.Ensures(Contract.Result<IBuffer>().Capacity == unchecked((UInt32)capacity));
Contract.EndContractBlock();
return new WindowsRuntimeBuffer(capacity);
}
[CLSCompliant(false)]
public static IBuffer Create(Byte[] data, Int32 offset, Int32 length, Int32 capacity)
{
if (data == null) throw new ArgumentNullException("data");
if (offset < 0) throw new ArgumentOutOfRangeException("offset");
if (length < 0) throw new ArgumentOutOfRangeException("length");
if (capacity < 0) throw new ArgumentOutOfRangeException("capacity");
if (data.Length - offset < length) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset);
if (data.Length - offset < capacity) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset);
if (capacity < length) throw new ArgumentException(SR.Argument_InsufficientBufferCapacity);
Contract.Ensures(Contract.Result<IBuffer>() != null);
Contract.Ensures(Contract.Result<IBuffer>().Length == unchecked((UInt32)length));
Contract.Ensures(Contract.Result<IBuffer>().Capacity == unchecked((UInt32)capacity));
Contract.EndContractBlock();
Byte[] underlyingData = new Byte[capacity];
Array.Copy(data, offset, underlyingData, 0, length);
return new WindowsRuntimeBuffer(underlyingData, 0, length, capacity);
}
#endregion Static factory methods
#region Static fields and helpers
// This object handles IMarshal calls for us:
[ThreadStatic]
private static IMarshal s_winRtMarshalProxy = null;
private static void EnsureHasMarshalProxy()
{
if (s_winRtMarshalProxy != null)
return;
try
{
IMarshal proxy;
Int32 hr = Interop.mincore.RoGetBufferMarshaler(out proxy);
s_winRtMarshalProxy = proxy;
if (hr != HResults.S_OK)
{
Exception ex = new Exception(String.Format("{0} ({1}!RoGetBufferMarshaler)", SR.WinRtCOM_Error, WinTypesDLL));
ex.SetErrorCode(hr);
throw ex;
}
if (proxy == null)
throw new NullReferenceException(String.Format("{0} ({1}!RoGetBufferMarshaler)", SR.WinRtCOM_Error, WinTypesDLL));
}
catch (DllNotFoundException ex)
{
throw new NotImplementedException(SR.Format(SR.NotImplemented_NativeRoutineNotFound,
String.Format("{0}!RoGetBufferMarshaler", WinTypesDLL)),
ex);
}
}
#endregion Static fields and helpers
#region Fields
private Byte[] _data = null;
private Int32 _dataStartOffs = 0;
private Int32 _usefulDataLength = 0;
private Int32 _maxDataCapacity = 0;
private GCHandle _pinHandle;
// Pointer to data[dataStartOffs] when data is pinned:
private IntPtr _dataPtr = IntPtr.Zero;
#endregion Fields
#region Constructors
internal WindowsRuntimeBuffer(Int32 capacity)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException("capacity");
Contract.EndContractBlock();
_data = new Byte[capacity];
_dataStartOffs = 0;
_usefulDataLength = 0;
_maxDataCapacity = capacity;
_dataPtr = IntPtr.Zero;
}
internal WindowsRuntimeBuffer(Byte[] data, Int32 offset, Int32 length, Int32 capacity)
{
if (data == null) throw new ArgumentNullException("data");
if (offset < 0) throw new ArgumentOutOfRangeException("offset");
if (length < 0) throw new ArgumentOutOfRangeException("length");
if (capacity < 0) throw new ArgumentOutOfRangeException("capacity");
if (data.Length - offset < length) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset);
if (data.Length - offset < capacity) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset);
if (capacity < length) throw new ArgumentException(SR.Argument_InsufficientBufferCapacity);
Contract.EndContractBlock();
_data = data;
_dataStartOffs = offset;
_usefulDataLength = length;
_maxDataCapacity = capacity;
_dataPtr = IntPtr.Zero;
}
#endregion Constructors
#region Helpers
internal void GetUnderlyingData(out Byte[] underlyingDataArray, out Int32 underlyingDataArrayStartOffset)
{
underlyingDataArray = _data;
underlyingDataArrayStartOffset = _dataStartOffs;
}
private unsafe Byte* PinUnderlyingData()
{
GCHandle gcHandle = default(GCHandle);
bool ptrWasStored = false;
IntPtr buffPtr;
try { }
finally
{
try
{
// Pin the the data array:
gcHandle = GCHandle.Alloc(_data, GCHandleType.Pinned);
buffPtr = gcHandle.AddrOfPinnedObject() + _dataStartOffs;
// Store the pin IFF it has not been assigned:
ptrWasStored = (Interlocked.CompareExchange(ref _dataPtr, buffPtr, IntPtr.Zero) == IntPtr.Zero);
}
finally
{
if (!ptrWasStored)
{
// There is a race with another thread also trying to create a pin and they were first
// in assigning to data pin. That's ok, just give it up.
// Unpin again (the pin from the other thread remains):
gcHandle.Free();
}
else
{
if (_pinHandle.IsAllocated)
_pinHandle.Free();
// Make sure we keep track of the handle
_pinHandle = gcHandle;
}
}
}
// Ok, now all is good:
return (Byte*)buffPtr;
}
~WindowsRuntimeBuffer()
{
if (_pinHandle.IsAllocated)
_pinHandle.Free();
}
#endregion Helpers
#region Implementation of Windows.Foundation.IBuffer
UInt32 IBuffer.Capacity
{
get { return unchecked((UInt32)_maxDataCapacity); }
}
UInt32 IBuffer.Length
{
get
{
return unchecked((UInt32)_usefulDataLength);
}
set
{
if (value > ((IBuffer)this).Capacity)
{
ArgumentOutOfRangeException ex = new ArgumentOutOfRangeException(SR.Argument_BufferLengthExceedsCapacity, "value");
ex.SetErrorCode(HResults.E_BOUNDS);
throw ex;
}
// Capacity is ensured to not exceed Int32.MaxValue, so Length is within this limit and this cast is safe:
Debug.Assert(((IBuffer)this).Capacity <= Int32.MaxValue);
_usefulDataLength = unchecked((Int32)value);
}
}
#endregion Implementation of Windows.Foundation.IBuffer
#region Implementation of IBufferByteAccess
unsafe IntPtr IBufferByteAccess.GetBuffer()
{
// Get pin handle:
IntPtr buffPtr = Volatile.Read(ref _dataPtr);
// If we are already pinned, return the pointer and have a nice day:
if (buffPtr != IntPtr.Zero)
return buffPtr;
// Ok, we we are not yet pinned. Let's do it.
return new IntPtr(PinUnderlyingData());
}
#endregion Implementation of IBufferByteAccess
#region Implementation of IMarshal
void IMarshal.DisconnectObject(UInt32 dwReserved)
{
EnsureHasMarshalProxy();
s_winRtMarshalProxy.DisconnectObject(dwReserved);
}
void IMarshal.GetMarshalSizeMax(ref Guid riid, IntPtr pv, UInt32 dwDestContext, IntPtr pvDestContext, UInt32 mshlflags, out UInt32 pSize)
{
EnsureHasMarshalProxy();
s_winRtMarshalProxy.GetMarshalSizeMax(ref riid, pv, dwDestContext, pvDestContext, mshlflags, out pSize);
}
void IMarshal.GetUnmarshalClass(ref Guid riid, IntPtr pv, UInt32 dwDestContext, IntPtr pvDestContext, UInt32 mshlFlags, out Guid pCid)
{
EnsureHasMarshalProxy();
s_winRtMarshalProxy.GetUnmarshalClass(ref riid, pv, dwDestContext, pvDestContext, mshlFlags, out pCid);
}
void IMarshal.MarshalInterface(IntPtr pStm, ref Guid riid, IntPtr pv, UInt32 dwDestContext, IntPtr pvDestContext, UInt32 mshlflags)
{
EnsureHasMarshalProxy();
s_winRtMarshalProxy.MarshalInterface(pStm, ref riid, pv, dwDestContext, pvDestContext, mshlflags);
}
void IMarshal.ReleaseMarshalData(IntPtr pStm)
{
EnsureHasMarshalProxy();
s_winRtMarshalProxy.ReleaseMarshalData(pStm);
}
void IMarshal.UnmarshalInterface(IntPtr pStm, ref Guid riid, out IntPtr ppv)
{
EnsureHasMarshalProxy();
s_winRtMarshalProxy.UnmarshalInterface(pStm, ref riid, out ppv);
}
#endregion Implementation of IMarshal
} // class WindowsRuntimeBuffer
} // namespace
// WindowsRuntimeBuffer.cs
| |
// 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 Fixtures.AcceptanceTestsAzureCompositeModelClient
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// BasicOperations operations.
/// </summary>
internal partial class BasicOperations : Microsoft.Rest.IServiceOperations<AzureCompositeModel>, IBasicOperations
{
/// <summary>
/// Initializes a new instance of the BasicOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal BasicOperations(AzureCompositeModel client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AzureCompositeModel
/// </summary>
public AzureCompositeModel Client { get; private set; }
/// <summary>
/// Get complex type {id: 2, name: 'abc', color: 'YELLOW'}
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<BasicInner>> GetValidWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/valid").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<BasicInner>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<BasicInner>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Please put {id: 2, name: 'abc', color: 'Magenta'}
/// </summary>
/// <param name='complexBody'>
/// Please put {id: 2, name: 'abc', color: 'Magenta'}
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PutValidWithHttpMessagesAsync(BasicInner complexBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (complexBody == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "complexBody");
}
string apiVersion = "2016-02-29";
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/valid").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(complexBody != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get a basic complex type that is invalid for the local strong type
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<BasicInner>> GetInvalidWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetInvalid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/invalid").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<BasicInner>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<BasicInner>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get a basic complex type that is empty
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<BasicInner>> GetEmptyWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetEmpty", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/empty").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<BasicInner>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<BasicInner>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get a basic complex type whose properties are null
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<BasicInner>> GetNullWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/null").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<BasicInner>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<BasicInner>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get a basic complex type while the server doesn't provide a response
/// payload
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<BasicInner>> GetNotProvidedWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetNotProvided", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/notprovided").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<BasicInner>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<BasicInner>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Authentication;
using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RedditSharp.Extensions;
namespace RedditSharp.Things
{
public class Post : VotableThing
{
private const string CommentUrl = "/api/comment";
private const string GetCommentsUrl = "/comments/{0}.json";
private const string EditUserTextUrl = "/api/editusertext";
private const string HideUrl = "/api/hide";
private const string UnhideUrl = "/api/unhide";
private const string SetFlairUrl = "/r/{0}/api/flair";
private const string MarkNSFWUrl = "/api/marknsfw";
private const string UnmarkNSFWUrl = "/api/unmarknsfw";
private const string ContestModeUrl = "/api/set_contest_mode";
private const string StickyModeUrl = "/api/set_subreddit_sticky";
private const string SpoilerUrl = "/api/spoiler";
private const string UnSpoilerUrl = "/api/unspoiler";
/// <summary>
/// Initialize
/// </summary>
/// <param name="reddit"></param>
/// <param name="post"></param>
/// <param name="webAgent"></param>
/// <returns></returns>
public async Task<Post> InitAsync(Reddit reddit, JToken post, IWebAgent webAgent)
{
await CommonInitAsync(reddit, post, webAgent);
JsonConvert.PopulateObject(post["data"].ToString(), this, reddit.JsonSerializerSettings);
return this;
}
/// <summary>
/// Initialize
/// </summary>
/// <param name="reddit"></param>
/// <param name="post"></param>
/// <param name="webAgent"></param>
/// <returns></returns>
public Post Init(Reddit reddit, JToken post, IWebAgent webAgent)
{
CommonInit(reddit, post, webAgent);
JsonConvert.PopulateObject(post["data"].ToString(), this, reddit.JsonSerializerSettings);
return this;
}
private void CommonInit(Reddit reddit, JToken post, IWebAgent webAgent)
{
base.Init(reddit, webAgent, post);
Reddit = reddit;
WebAgent = webAgent;
}
private async Task CommonInitAsync(Reddit reddit, JToken post, IWebAgent webAgent)
{
await base.InitAsync(reddit, webAgent, post);
Reddit = reddit;
WebAgent = webAgent;
}
/// <summary>
/// Author of this post.
/// </summary>
[JsonIgnore]
public RedditUser Author
{
get
{
return Reddit.GetUser(AuthorName);
}
}
/// <summary>
/// An array of comments on this post.
/// </summary>
public Comment[] Comments
{
get
{
return ListComments().ToArray();
}
}
/// <summary>
/// Returns true if post is marekd as spoiler
/// </summary>
[JsonProperty("spoiler")]
public bool IsSpoiler { get; set; }
/// <summary>
/// Domain of this post.
/// </summary>
[JsonProperty("domain")]
public string Domain { get; set; }
/// <summary>
/// Returns true if this is a self post.
/// </summary>
[JsonProperty("is_self")]
public bool IsSelfPost { get; set; }
/// <summary>
/// Css class of the link flair.
/// </summary>
[JsonProperty("link_flair_css_class")]
public string LinkFlairCssClass { get; set; }
/// <summary>
/// Text of the link flair.
/// </summary>
[JsonProperty("link_flair_text")]
public string LinkFlairText { get; set; }
/// <summary>
/// Number of comments on this post.
/// </summary>
[JsonProperty("num_comments")]
public int CommentCount { get; set; }
/// <summary>
/// Returns true if this post is marked not safe for work.
/// </summary>
[JsonProperty("over_18")]
public bool NSFW { get; set; }
/// <summary>
/// Post permalink.
/// </summary>
[JsonProperty("permalink")]
[JsonConverter(typeof(UrlParser))]
public Uri Permalink { get; set; }
/// <summary>
/// Post self text markdown.
/// </summary>
[JsonProperty("selftext")]
public string SelfText { get; set; }
/// <summary>
/// Post self text html.
/// </summary>
[JsonProperty("selftext_html")]
public string SelfTextHtml { get; set; }
/// <summary>
/// Uri to the thumbnail image of this post.
/// </summary>
[JsonProperty("thumbnail")]
[JsonConverter(typeof(UrlParser))]
public Uri Thumbnail { get; set; }
/// <summary>
/// Post title.
/// </summary>
[JsonProperty("title")]
public string Title { get; set; }
/// <summary>
/// Parent subreddit name.
/// </summary>
[JsonProperty("subreddit")]
public string SubredditName { get; set; }
/// <summary>
/// Parent subreddit.
/// </summary>
[JsonIgnore]
public Subreddit Subreddit
{
get
{
return Reddit.GetSubreddit("/r/" + SubredditName);
}
}
/// <summary>
/// Post uri.
/// </summary>
[JsonProperty("url")]
[JsonConverter(typeof(UrlParser))]
public Uri Url { get; set; }
/// <summary>
/// Comment on this post.
/// </summary>
/// <param name="message">Markdown text.</param>
/// <returns></returns>
public Comment Comment(string message)
{
if (Reddit.User == null)
throw new AuthenticationException("No user logged in.");
var request = WebAgent.CreatePost(CommentUrl);
var stream = request.GetRequestStream();
WebAgent.WritePostBody(stream, new
{
text = message,
thing_id = FullName,
uh = Reddit.User.Modhash,
api_type = "json"
});
stream.Close();
var response = request.GetResponse();
var data = WebAgent.GetResponseString(response.GetResponseStream());
var json = JObject.Parse(data);
if (json["json"]["ratelimit"] != null)
throw new RateLimitException(TimeSpan.FromSeconds(json["json"]["ratelimit"].ValueOrDefault<double>()));
return new Comment().Init(Reddit, json["json"]["data"]["things"][0], WebAgent, this);
}
/// <summary>
/// Marks post as spoiler
/// </summary>
public void Spoiler()
{
var data = SimpleAction(SpoilerUrl);
}
/// <summary>
/// Unmarks a post as being a spoiler
/// </summary>
public void UnSpoiler()
{
var data = SimpleAction(UnSpoilerUrl);
}
private string SimpleActionToggle(string endpoint, bool value, bool requiresModAction = false)
{
if (Reddit.User == null)
throw new AuthenticationException("No user logged in.");
var modNameList = this.Subreddit.Moderators.Select(b => b.Name).ToList();
if (requiresModAction && !modNameList.Contains(Reddit.User.Name))
throw new AuthenticationException(
string.Format(
@"User {0} is not a moderator of subreddit {1}.",
Reddit.User.Name,
this.Subreddit.Name));
var request = WebAgent.CreatePost(endpoint);
var stream = request.GetRequestStream();
WebAgent.WritePostBody(stream, new
{
id = FullName,
state = value,
uh = Reddit.User.Modhash
});
stream.Close();
var response = request.GetResponse();
var data = WebAgent.GetResponseString(response.GetResponseStream());
return data;
}
/// <summary>
/// Hide this post.
/// </summary>
public void Hide()
{
var data = SimpleAction(HideUrl);
}
/// <summary>
/// Unhide this post.
/// </summary>
public void Unhide()
{
var data = SimpleAction(UnhideUrl);
}
/// <summary>
/// Mark this post not safe for work.
/// </summary>
public void MarkNSFW()
{
var data = SimpleAction(MarkNSFWUrl);
}
/// <summary>
/// Unmark this post not safe for work.
/// </summary>
public void UnmarkNSFW()
{
var data = SimpleAction(UnmarkNSFWUrl);
}
/// <summary>
/// Set contest mode state. Logged in user must be a moderator of parent subreddit.
/// </summary>
/// <param name="state"></param>
public void ContestMode(bool state)
{
var data = SimpleActionToggle(ContestModeUrl, state);
}
/// <summary>
/// Set sticky state. Logged in user must be a moderator of parent subreddit.
/// </summary>
/// <param name="state"></param>
public void StickyMode(bool state)
{
var data = SimpleActionToggle(StickyModeUrl, state, true);
}
#region Obsolete Getter Methods
[Obsolete("Use Comments property instead")]
public Comment[] GetComments()
{
return Comments;
}
#endregion Obsolete Getter Methods
/// <summary>
/// Replaces the text in this post with the input text.
/// </summary>
/// <param name="newText">The text to replace the post's contents</param>
public void EditText(string newText)
{
if (Reddit.User == null)
throw new Exception("No user logged in.");
if (!IsSelfPost)
throw new Exception("Submission to edit is not a self-post.");
var request = WebAgent.CreatePost(EditUserTextUrl);
WebAgent.WritePostBody(request.GetRequestStream(), new
{
api_type = "json",
text = newText,
thing_id = FullName,
uh = Reddit.User.Modhash
});
var response = request.GetResponse();
var result = WebAgent.GetResponseString(response.GetResponseStream());
JToken json = JToken.Parse(result);
if (json["json"].ToString().Contains("\"errors\": []"))
SelfText = newText;
else
throw new Exception("Error editing text. Error: " + json["json"]["errors"][0][0].ToString());
}
/// <summary>
/// Update this post.
/// </summary>
public void Update()
{
JToken post = Reddit.GetToken(this.Url);
JsonConvert.PopulateObject(post["data"].ToString(), this, Reddit.JsonSerializerSettings);
}
/// <summary>
/// Sets your claim
/// </summary>
/// <param name="flairText">Text to set your flair</param>
/// <param name="flairClass">class of the flair</param>
public void SetFlair(string flairText, string flairClass)
{
if (Reddit.User == null)
throw new Exception("No user logged in.");
var request = WebAgent.CreatePost(string.Format(SetFlairUrl, SubredditName));
WebAgent.WritePostBody(request.GetRequestStream(), new
{
api_type = "json",
css_class = flairClass,
link = FullName,
name = Reddit.User.Name,
text = flairText,
uh = Reddit.User.Modhash
});
var response = request.GetResponse();
var result = WebAgent.GetResponseString(response.GetResponseStream());
var json = JToken.Parse(result);
LinkFlairText = flairText;
}
/// <summary>
/// Get a <see cref="Listing{T}"/> of comments.
/// </summary>
/// <param name="limit"></param>
/// <returns></returns>
public List<Comment> ListComments(int? limit = null)
{
var url = string.Format(GetCommentsUrl, Id);
if (limit.HasValue)
{
var query = HttpUtility.ParseQueryString(string.Empty);
query.Add("limit", limit.Value.ToString());
url = string.Format("{0}?{1}", url, query);
}
var request = WebAgent.CreateGet(url);
var response = request.GetResponse();
var data = WebAgent.GetResponseString(response.GetResponseStream());
var json = JArray.Parse(data);
var postJson = json.Last()["data"]["children"];
var comments = new List<Comment>();
foreach (var comment in postJson)
{
Comment newComment = new Comment().Init(Reddit, comment, WebAgent, this);
if (newComment.Kind == "more")
{
}
else
{
comments.Add(newComment);
}
}
return comments;
}
/// <summary>
/// Enumerate more comments.
/// </summary>
/// <returns></returns>
public IEnumerable<Comment> EnumerateComments()
{
var url = string.Format(GetCommentsUrl, Id);
var request = WebAgent.CreateGet(url);
var response = request.GetResponse();
var data = WebAgent.GetResponseString(response.GetResponseStream());
var json = JArray.Parse(data);
var postJson = json.Last()["data"]["children"];
More moreComments = null;
foreach (var comment in postJson)
{
Comment newComment = new Comment().Init(Reddit, comment, WebAgent, this);
if (newComment.Kind == "more")
{
moreComments = new More().Init(Reddit, comment, WebAgent);
}
else
{
yield return newComment;
}
}
if (moreComments != null)
{
IEnumerator<Thing> things = moreComments.Things().GetEnumerator();
things.MoveNext();
Thing currentThing = null;
while (currentThing != things.Current)
{
currentThing = things.Current;
if (things.Current is Comment)
{
Comment next = ((Comment)things.Current).PopulateComments(things);
yield return next;
}
if (things.Current is More)
{
More more = (More)things.Current;
if (more.ParentId != FullName) break;
things = more.Things().GetEnumerator();
things.MoveNext();
}
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.