context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace Bookshelf.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
//#define PrintDebug
//
// Copyright (C) 2005, 2007 Novell, Inc. http://www.novell.com
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Author:
//
// Jordi Mas i Hernandez, jordimash@gmail.com
//
using System.Runtime.InteropServices;
using System.Collections;
using System.Collections.Specialized;
using System.Drawing.Printing;
using System.ComponentModel;
using System.Drawing.Imaging;
using System.Text;
using System.IO;
namespace System.Drawing.Printing
{
internal class PrintingServicesUnix : PrintingServices
{
#region Private Fields
private static Hashtable doc_info = new Hashtable();
private static bool cups_installed;
//private string printer_name;
private static Hashtable installed_printers;
private static string default_printer = String.Empty;
#endregion
#region Constructor
internal PrintingServicesUnix()
{
}
static PrintingServicesUnix()
{
installed_printers = new Hashtable();
CheckCupsInstalled();
}
#endregion
#region Properties
internal static PrinterSettings.StringCollection InstalledPrinters
{
get
{
LoadPrinters();
PrinterSettings.StringCollection list = new PrinterSettings.StringCollection(new string[] { });
foreach (object key in installed_printers.Keys)
{
list.Add(key.ToString());
}
return list;
}
}
internal override string DefaultPrinter
{
get
{
if (installed_printers.Count == 0)
LoadPrinters();
return default_printer;
}
}
#endregion
#region Methods
/// <summary>
/// Do a cups call to check if it is installed
/// </summary>
private static void CheckCupsInstalled()
{
try
{
cupsGetDefault();
}
catch (DllNotFoundException)
{
#if NETCORE
System.Diagnostics.Debug.WriteLine("libcups not found. To have printing support, you need cups installed");
#else
Console.WriteLine("libcups not found. To have printing support, you need cups installed");
#endif
cups_installed = false;
return;
}
cups_installed = true;
}
/// <summary>
/// Open the printer's PPD file
/// </summary>
/// <param name="printer">Printer name, returned from cupsGetDests</param>
private IntPtr OpenPrinter(string printer)
{
try
{
IntPtr ptr = cupsGetPPD(printer);
string ppd_filename = Marshal.PtrToStringAnsi(ptr);
IntPtr ppd_handle = ppdOpenFile(ppd_filename);
return ppd_handle;
}
catch (Exception)
{
#if NETCORE
System.Diagnostics.Debug.WriteLine("There was an error opening the printer {0}. Please check your cups installation.");
#else
Console.WriteLine("There was an error opening the printer {0}. Please check your cups installation.");
#endif
}
return IntPtr.Zero;
}
/// <summary>
/// Close the printer file
/// </summary>
/// <param name="handle">PPD handle</param>
private void ClosePrinter(ref IntPtr handle)
{
try
{
if (handle != IntPtr.Zero)
ppdClose(handle);
}
finally
{
handle = IntPtr.Zero;
}
}
private static int OpenDests(ref IntPtr ptr)
{
try
{
return cupsGetDests(ref ptr);
}
catch
{
ptr = IntPtr.Zero;
}
return 0;
}
private static void CloseDests(ref IntPtr ptr, int count)
{
try
{
if (ptr != IntPtr.Zero)
cupsFreeDests(count, ptr);
}
finally
{
ptr = IntPtr.Zero;
}
}
/// <summary>
/// Checks if a printer has a valid PPD file. Caches the result unless force is true
/// </summary>
/// <param name="force">Does the check disregarding the last cached value if true</param>
internal override bool IsPrinterValid(string printer)
{
if (!cups_installed || printer == null | printer == String.Empty)
return false;
return installed_printers.Contains(printer);
/*
if (!force && this.printer_name != null && String.Intern(this.printer_name).Equals(printer))
return is_printer_valid;
IntPtr ptr = cupsGetPPD (printer);
string ppd_filename = Marshal.PtrToStringAnsi (ptr);
is_printer_valid = ppd_filename != null;
this.printer_name = printer;
return is_printer_valid;
*/
}
/// <summary>
/// Loads the printer settings and initializes the PrinterSettings and PageSettings fields
/// </summary>
/// <param name="printer">Printer name</param>
/// <param name="settings">PrinterSettings object to initialize</param>
internal override void LoadPrinterSettings(string printer, PrinterSettings settings)
{
if (cups_installed == false || (printer == null) || (printer == String.Empty))
return;
if (installed_printers.Count == 0)
LoadPrinters();
if (((SysPrn.Printer)installed_printers[printer]).Settings != null)
{
SysPrn.Printer p = (SysPrn.Printer)installed_printers[printer];
settings.can_duplex = p.Settings.can_duplex;
settings.is_plotter = p.Settings.is_plotter;
settings.landscape_angle = p.Settings.landscape_angle;
settings.maximum_copies = p.Settings.maximum_copies;
settings.paper_sizes = p.Settings.paper_sizes;
settings.paper_sources = p.Settings.paper_sources;
settings.printer_capabilities = p.Settings.printer_capabilities;
settings.printer_resolutions = p.Settings.printer_resolutions;
settings.supports_color = p.Settings.supports_color;
return;
}
settings.PrinterCapabilities.Clear();
IntPtr dests = IntPtr.Zero, ptr = IntPtr.Zero, ptr_printer, ppd_handle = IntPtr.Zero;
string name = String.Empty;
CUPS_DESTS printer_dest;
PPD_FILE ppd;
int ret = 0, cups_dests_size;
NameValueCollection options, paper_names, paper_sources;
try
{
ret = OpenDests(ref dests);
if (ret == 0)
return;
cups_dests_size = Marshal.SizeOf(typeof(CUPS_DESTS));
ptr = dests;
for (int i = 0; i < ret; i++)
{
ptr_printer = (IntPtr)Marshal.ReadIntPtr(ptr);
if (Marshal.PtrToStringAnsi(ptr_printer).Equals(printer))
{
name = printer;
break;
}
ptr = (IntPtr)((long)ptr + cups_dests_size);
}
if (!name.Equals(printer))
{
return;
}
ppd_handle = OpenPrinter(printer);
if (ppd_handle == IntPtr.Zero)
return;
printer_dest = (CUPS_DESTS)Marshal.PtrToStructure(ptr, typeof(CUPS_DESTS));
options = new NameValueCollection();
paper_names = new NameValueCollection();
paper_sources = new NameValueCollection();
string defsize;
string defsource;
LoadPrinterOptions(printer_dest.options, printer_dest.num_options, ppd_handle, options,
paper_names, out defsize,
paper_sources, out defsource);
if (settings.paper_sizes == null)
settings.paper_sizes = new PrinterSettings.PaperSizeCollection(new PaperSize[] { });
else
settings.paper_sizes.Clear();
if (settings.paper_sources == null)
settings.paper_sources = new PrinterSettings.PaperSourceCollection(new PaperSource[] { });
else
settings.paper_sources.Clear();
settings.DefaultPageSettings.PaperSource = LoadPrinterPaperSources(settings, defsource, paper_sources);
settings.DefaultPageSettings.PaperSize = LoadPrinterPaperSizes(ppd_handle, settings, defsize, paper_names);
LoadPrinterResolutionsAndDefault(printer, settings, ppd_handle);
ppd = (PPD_FILE)Marshal.PtrToStructure(ppd_handle, typeof(PPD_FILE));
settings.landscape_angle = ppd.landscape;
settings.supports_color = (ppd.color_device == 0) ? false : true;
settings.can_duplex = options["Duplex"] != null;
ClosePrinter(ref ppd_handle);
((SysPrn.Printer)installed_printers[printer]).Settings = settings;
}
finally
{
CloseDests(ref dests, ret);
}
}
/// <summary>
/// Loads the global options of a printer plus the paper types and trays supported,
/// and sets the default paper size and source tray.
/// </summary>
/// <param name="options">The options field of a printer's CUPS_DESTS structure</param>
/// <param name="numOptions">The number of options of the printer</param>
/// <param name="ppd">A ppd handle for the printer, returned by ppdOpen</param>
/// <param name="list">The list of options</param>
/// <param name="paper_names">A list of types of paper (PageSize)</param>
/// <param name="defsize">The default paper size, set by LoadOptionList</param>
/// <param name="paper_sources">A list of trays(InputSlot) </param>
/// <param name="defsource">The default source tray, set by LoadOptionList</param>
private static void LoadPrinterOptions(IntPtr options, int numOptions, IntPtr ppd,
NameValueCollection list,
NameValueCollection paper_names, out string defsize,
NameValueCollection paper_sources, out string defsource)
{
CUPS_OPTIONS cups_options;
string option_name, option_value;
int cups_size = Marshal.SizeOf(typeof(CUPS_OPTIONS));
LoadOptionList(ppd, "PageSize", paper_names, out defsize);
LoadOptionList(ppd, "InputSlot", paper_sources, out defsource);
for (int j = 0; j < numOptions; j++)
{
cups_options = (CUPS_OPTIONS)Marshal.PtrToStructure(options, typeof(CUPS_OPTIONS));
option_name = Marshal.PtrToStringAnsi(cups_options.name);
option_value = Marshal.PtrToStringAnsi(cups_options.val);
if (option_name == "PageSize")
defsize = option_value;
else if (option_name == "InputSlot")
defsource = option_value;
#if PrintDebug
Console.WriteLine("{0} = {1}", option_name, option_value);
#endif
list.Add(option_name, option_value);
options = (IntPtr)((long)options + cups_size);
}
}
/// <summary>
/// Loads the global options of a printer.
/// </summary>
/// <param name="options">The options field of a printer's CUPS_DESTS structure</param>
/// <param name="numOptions">The number of options of the printer</param>
private static NameValueCollection LoadPrinterOptions(IntPtr options, int numOptions)
{
CUPS_OPTIONS cups_options;
string option_name, option_value;
int cups_size = Marshal.SizeOf(typeof(CUPS_OPTIONS));
NameValueCollection list = new NameValueCollection();
for (int j = 0; j < numOptions; j++)
{
cups_options = (CUPS_OPTIONS)Marshal.PtrToStructure(options, typeof(CUPS_OPTIONS));
option_name = Marshal.PtrToStringAnsi(cups_options.name);
option_value = Marshal.PtrToStringAnsi(cups_options.val);
#if PrintDebug
Console.WriteLine("{0} = {1}", option_name, option_value);
#endif
list.Add(option_name, option_value);
options = (IntPtr)((long)options + cups_size);
}
return list;
}
/// <summary>
/// Loads a printer's options (selection of paper sizes, paper sources, etc)
/// and sets the default option from the selected list.
/// </summary>
/// <param name="ppd">Printer ppd file handle</param>
/// <param name="option_name">Name of the option group to load</param>
/// <param name="list">List of loaded options</param>
/// <param name="defoption">The default option from the loaded options list</param>
private static void LoadOptionList(IntPtr ppd, string option_name, NameValueCollection list, out string defoption)
{
IntPtr ptr = IntPtr.Zero;
PPD_OPTION ppd_option;
PPD_CHOICE choice;
int choice_size = Marshal.SizeOf(typeof(PPD_CHOICE));
defoption = null;
ptr = ppdFindOption(ppd, option_name);
if (ptr != IntPtr.Zero)
{
ppd_option = (PPD_OPTION)Marshal.PtrToStructure(ptr, typeof(PPD_OPTION));
#if PrintDebug
Console.WriteLine (" OPTION key:{0} def:{1} text: {2}", ppd_option.keyword, ppd_option.defchoice, ppd_option.text);
#endif
defoption = ppd_option.defchoice;
ptr = ppd_option.choices;
for (int c = 0; c < ppd_option.num_choices; c++)
{
choice = (PPD_CHOICE)Marshal.PtrToStructure(ptr, typeof(PPD_CHOICE));
list.Add(choice.choice, choice.text);
#if PrintDebug
Console.WriteLine (" choice:{0} - text: {1}", choice.choice, choice.text);
#endif
ptr = (IntPtr)((long)ptr + choice_size);
}
}
}
/// <summary>
/// Loads a printer's available resolutions
/// </summary>
/// <param name="printer">Printer name</param>
/// <param name="settings">PrinterSettings object to fill</param>
internal override void LoadPrinterResolutions(string printer, PrinterSettings settings)
{
IntPtr ppd_handle = OpenPrinter(printer);
if (ppd_handle == IntPtr.Zero)
return;
LoadPrinterResolutionsAndDefault(printer, settings, ppd_handle);
ClosePrinter(ref ppd_handle);
}
/// <summary>
/// Create a PrinterResolution from a string Resolution that is set in the PPD option.
/// An example of Resolution is "600x600dpi" or "600dpi". Returns null if malformed or "Unknown".
/// </summary>
private PrinterResolution ParseResolution(string resolution)
{
if (String.IsNullOrEmpty(resolution))
return null;
int dpiIndex = resolution.IndexOf("dpi");
if (dpiIndex == -1)
{
// Resolution is "Unknown" or unparsable
return null;
}
resolution = resolution.Substring(0, dpiIndex);
int x_resolution, y_resolution;
try
{
if (resolution.Contains("x"))
{
string[] resolutions = resolution.Split(new[] { 'x' });
x_resolution = Convert.ToInt32(resolutions[0]);
y_resolution = Convert.ToInt32(resolutions[1]);
}
else
{
x_resolution = Convert.ToInt32(resolution);
y_resolution = x_resolution;
}
}
catch (Exception)
{
return null;
}
return new PrinterResolution(PrinterResolutionKind.Custom, x_resolution, y_resolution);
}
/// <summary>
/// Loads a printer's paper sizes. Returns the default PaperSize, and fills a list of paper_names for use in dialogues
/// </summary>
/// <param name="ppd_handle">PPD printer file handle</param>
/// <param name="settings">PrinterSettings object to fill</param>
/// <param name="def_size">Default paper size, from the global options of the printer</param>
/// <param name="paper_names">List of available paper sizes that gets filled</param>
private PaperSize LoadPrinterPaperSizes(IntPtr ppd_handle, PrinterSettings settings,
string def_size, NameValueCollection paper_names)
{
IntPtr ptr;
string real_name;
PPD_FILE ppd;
PPD_SIZE size;
PaperSize ps;
PaperSize defsize = new PaperSize(GetPaperKind(827, 1169), "A4", 827, 1169);
ppd = (PPD_FILE)Marshal.PtrToStructure(ppd_handle, typeof(PPD_FILE));
ptr = ppd.sizes;
float w, h;
for (int i = 0; i < ppd.num_sizes; i++)
{
size = (PPD_SIZE)Marshal.PtrToStructure(ptr, typeof(PPD_SIZE));
real_name = paper_names[size.name];
w = size.width * 100 / 72;
h = size.length * 100 / 72;
PaperKind kind = GetPaperKind((int)w, (int)h);
ps = new PaperSize(kind, real_name, (int)w, (int)h);
ps.RawKind = (int)kind;
if (def_size == ps.Kind.ToString())
defsize = ps;
settings.paper_sizes.Add(ps);
ptr = (IntPtr)((long)ptr + Marshal.SizeOf(size));
}
return defsize;
}
/// <summary>
/// Loads a printer's paper sources (trays). Returns the default PaperSource, and fills a list of paper_sources for use in dialogues
/// </summary>
/// <param name="settings">PrinterSettings object to fill</param>
/// <param name="def_source">Default paper source, from the global options of the printer</param>
/// <param name="paper_sources">List of available paper sizes that gets filled</param>
private PaperSource LoadPrinterPaperSources(PrinterSettings settings, string def_source,
NameValueCollection paper_sources)
{
PaperSourceKind kind;
PaperSource defsource = null;
foreach (string source in paper_sources)
{
switch (source)
{
case "Auto":
kind = PaperSourceKind.AutomaticFeed;
break;
case "Standard":
kind = PaperSourceKind.AutomaticFeed;
break;
case "Tray":
kind = PaperSourceKind.AutomaticFeed;
break;
case "Envelope":
kind = PaperSourceKind.Envelope;
break;
case "Manual":
kind = PaperSourceKind.Manual;
break;
default:
kind = PaperSourceKind.Custom;
break;
}
settings.paper_sources.Add(new PaperSource(kind, paper_sources[source]));
if (def_source == source)
defsource = settings.paper_sources[settings.paper_sources.Count - 1];
}
if (defsource == null && settings.paper_sources.Count > 0)
return settings.paper_sources[0];
return defsource;
}
/// <summary>
/// Sets the available resolutions and default resolution from a
/// printer's PPD file into settings.
/// </summary>
private void LoadPrinterResolutionsAndDefault(string printer,
PrinterSettings settings, IntPtr ppd_handle)
{
if (settings.printer_resolutions == null)
settings.printer_resolutions = new PrinterSettings.PrinterResolutionCollection(new PrinterResolution[] { });
else
settings.printer_resolutions.Clear();
var printer_resolutions = new NameValueCollection();
string defresolution;
LoadOptionList(ppd_handle, "Resolution", printer_resolutions, out defresolution);
foreach (var resolution in printer_resolutions.Keys)
{
var new_resolution = ParseResolution(resolution.ToString());
settings.PrinterResolutions.Add(new_resolution);
}
var default_resolution = ParseResolution(defresolution);
if (default_resolution == null)
default_resolution = ParseResolution("300dpi");
if (printer_resolutions.Count == 0)
settings.PrinterResolutions.Add(default_resolution);
settings.DefaultPageSettings.PrinterResolution = default_resolution;
}
/// <summary>
/// </summary>
/// <param name="load"></param>
/// <param name="def_printer"></param>
private static void LoadPrinters()
{
installed_printers.Clear();
if (cups_installed == false)
return;
IntPtr dests = IntPtr.Zero, ptr_printers;
CUPS_DESTS printer;
int n_printers = 0;
int cups_dests_size = Marshal.SizeOf(typeof(CUPS_DESTS));
string name, first, type, status, comment;
first = type = status = comment = String.Empty;
int state = 0;
try
{
n_printers = OpenDests(ref dests);
ptr_printers = dests;
for (int i = 0; i < n_printers; i++)
{
printer = (CUPS_DESTS)Marshal.PtrToStructure(ptr_printers, typeof(CUPS_DESTS));
name = Marshal.PtrToStringAnsi(printer.name);
if (printer.is_default == 1)
default_printer = name;
if (first.Equals(String.Empty))
first = name;
NameValueCollection options = LoadPrinterOptions(printer.options, printer.num_options);
if (options["printer-state"] != null)
state = Int32.Parse(options["printer-state"]);
if (options["printer-comment"] != null)
comment = options["printer-state"];
switch (state)
{
case 4:
status = "Printing";
break;
case 5:
status = "Stopped";
break;
default:
status = "Ready";
break;
}
installed_printers.Add(name, new SysPrn.Printer(String.Empty, type, status, comment));
ptr_printers = (IntPtr)((long)ptr_printers + cups_dests_size);
}
}
finally
{
CloseDests(ref dests, n_printers);
}
if (default_printer.Equals(String.Empty))
default_printer = first;
}
/// <summary>
/// Gets a printer's settings for use in the print dialogue
/// </summary>
/// <param name="printer"></param>
/// <param name="port"></param>
/// <param name="type"></param>
/// <param name="status"></param>
/// <param name="comment"></param>
internal override void GetPrintDialogInfo(string printer, ref string port, ref string type, ref string status, ref string comment)
{
int count = 0, state = -1;
bool found = false;
CUPS_DESTS cups_dests;
IntPtr dests = IntPtr.Zero, ptr_printers, ptr_printer;
int cups_dests_size = Marshal.SizeOf(typeof(CUPS_DESTS));
if (cups_installed == false)
return;
try
{
count = OpenDests(ref dests);
if (count == 0)
return;
ptr_printers = dests;
for (int i = 0; i < count; i++)
{
ptr_printer = (IntPtr)Marshal.ReadIntPtr(ptr_printers);
if (Marshal.PtrToStringAnsi(ptr_printer).Equals(printer))
{
found = true;
break;
}
ptr_printers = (IntPtr)((long)ptr_printers + cups_dests_size);
}
if (!found)
return;
cups_dests = (CUPS_DESTS)Marshal.PtrToStructure(ptr_printers, typeof(CUPS_DESTS));
NameValueCollection options = LoadPrinterOptions(cups_dests.options, cups_dests.num_options);
if (options["printer-state"] != null)
state = Int32.Parse(options["printer-state"]);
if (options["printer-comment"] != null)
comment = options["printer-state"];
switch (state)
{
case 4:
status = "Printing";
break;
case 5:
status = "Stopped";
break;
default:
status = "Ready";
break;
}
}
finally
{
CloseDests(ref dests, count);
}
}
/// <summary>
/// Returns the appropriate PaperKind for the width and height
/// </summary>
/// <param name="width"></param>
/// <param name="height"></param>
private PaperKind GetPaperKind(int width, int height)
{
if (width == 827 && height == 1169)
return PaperKind.A4;
if (width == 583 && height == 827)
return PaperKind.A5;
if (width == 717 && height == 1012)
return PaperKind.B5;
if (width == 693 && height == 984)
return PaperKind.B5Envelope;
if (width == 638 && height == 902)
return PaperKind.C5Envelope;
if (width == 449 && height == 638)
return PaperKind.C6Envelope;
if (width == 1700 && height == 2200)
return PaperKind.CSheet;
if (width == 433 && height == 866)
return PaperKind.DLEnvelope;
if (width == 2200 && height == 3400)
return PaperKind.DSheet;
if (width == 3400 && height == 4400)
return PaperKind.ESheet;
if (width == 725 && height == 1050)
return PaperKind.Executive;
if (width == 850 && height == 1300)
return PaperKind.Folio;
if (width == 850 && height == 1200)
return PaperKind.GermanStandardFanfold;
if (width == 1700 && height == 1100)
return PaperKind.Ledger;
if (width == 850 && height == 1400)
return PaperKind.Legal;
if (width == 927 && height == 1500)
return PaperKind.LegalExtra;
if (width == 850 && height == 1100)
return PaperKind.Letter;
if (width == 927 && height == 1200)
return PaperKind.LetterExtra;
if (width == 850 && height == 1269)
return PaperKind.LetterPlus;
if (width == 387 && height == 750)
return PaperKind.MonarchEnvelope;
if (width == 387 && height == 887)
return PaperKind.Number9Envelope;
if (width == 413 && height == 950)
return PaperKind.Number10Envelope;
if (width == 450 && height == 1037)
return PaperKind.Number11Envelope;
if (width == 475 && height == 1100)
return PaperKind.Number12Envelope;
if (width == 500 && height == 1150)
return PaperKind.Number14Envelope;
if (width == 363 && height == 650)
return PaperKind.PersonalEnvelope;
if (width == 1000 && height == 1100)
return PaperKind.Standard10x11;
if (width == 1000 && height == 1400)
return PaperKind.Standard10x14;
if (width == 1100 && height == 1700)
return PaperKind.Standard11x17;
if (width == 1200 && height == 1100)
return PaperKind.Standard12x11;
if (width == 1500 && height == 1100)
return PaperKind.Standard15x11;
if (width == 900 && height == 1100)
return PaperKind.Standard9x11;
if (width == 550 && height == 850)
return PaperKind.Statement;
if (width == 1100 && height == 1700)
return PaperKind.Tabloid;
if (width == 1487 && height == 1100)
return PaperKind.USStandardFanfold;
return PaperKind.Custom;
}
#endregion
#region Print job methods
static string tmpfile;
/// <summary>
/// Gets a pointer to an options list parsed from the printer's current settings, to use when setting up the printing job
/// </summary>
/// <param name="printer_settings"></param>
/// <param name="page_settings"></param>
/// <param name="options"></param>
internal static int GetCupsOptions(PrinterSettings printer_settings, PageSettings page_settings, out IntPtr options)
{
options = IntPtr.Zero;
PaperSize size = page_settings.PaperSize;
int width = size.Width * 72 / 100;
int height = size.Height * 72 / 100;
StringBuilder sb = new StringBuilder();
sb.Append(
"copies=" + printer_settings.Copies + " " +
"Collate=" + printer_settings.Collate + " " +
"ColorModel=" + (page_settings.Color ? "Color" : "Black") + " " +
"PageSize=" + String.Format("Custom.{0}x{1}", width, height) + " " +
"landscape=" + page_settings.Landscape
);
if (printer_settings.CanDuplex)
{
if (printer_settings.Duplex == Duplex.Simplex)
sb.Append(" Duplex=None");
else
sb.Append(" Duplex=DuplexNoTumble");
}
return cupsParseOptions(sb.ToString(), 0, ref options);
}
internal static bool StartDoc(GraphicsPrinter gr, string doc_name, string output_file)
{
DOCINFO doc = (DOCINFO)doc_info[gr.Hdc];
doc.title = doc_name;
return true;
}
internal static bool EndDoc(GraphicsPrinter gr)
{
DOCINFO doc = (DOCINFO)doc_info[gr.Hdc];
gr.Graphics.Dispose(); // Dispose object to force surface finish
IntPtr options;
int options_count = GetCupsOptions(doc.settings, doc.default_page_settings, out options);
cupsPrintFile(doc.settings.PrinterName, doc.filename, doc.title, options_count, options);
cupsFreeOptions(options_count, options);
doc_info.Remove(gr.Hdc);
if (tmpfile != null)
{
try
{ File.Delete(tmpfile); }
catch { }
}
return true;
}
internal static bool StartPage(GraphicsPrinter gr)
{
return true;
}
internal static bool EndPage(GraphicsPrinter gr)
{
GdipGetPostScriptSavePage(gr.Hdc);
return true;
}
// Unfortunately, PrinterSettings and PageSettings couldn't be referencing each other,
// thus we need to pass them separately
internal static IntPtr CreateGraphicsContext(PrinterSettings settings, PageSettings default_page_settings)
{
IntPtr graphics = IntPtr.Zero;
string name;
if (!settings.PrintToFile)
{
StringBuilder sb = new StringBuilder(1024);
int length = sb.Capacity;
cupsTempFd(sb, length);
name = sb.ToString();
tmpfile = name;
}
else
name = settings.PrintFileName;
PaperSize psize = default_page_settings.PaperSize;
int width, height;
if (default_page_settings.Landscape)
{ // Swap in case of landscape
width = psize.Height;
height = psize.Width;
}
else
{
width = psize.Width;
height = psize.Height;
}
GdipGetPostScriptGraphicsContext(name,
width * 72 / 100,
height * 72 / 100,
default_page_settings.PrinterResolution.X,
default_page_settings.PrinterResolution.Y, ref graphics);
DOCINFO doc = new DOCINFO();
doc.filename = name;
doc.settings = settings;
doc.default_page_settings = default_page_settings;
doc_info.Add(graphics, doc);
return graphics;
}
#endregion
#region DllImports
[DllImport("libcups", CharSet = CharSet.Ansi)]
static extern int cupsGetDests(ref IntPtr dests);
// [DllImport("libcups", CharSet=CharSet.Ansi)]
// static extern void cupsGetDest (string name, string instance, int num_dests, ref IntPtr dests);
[DllImport("libcups")]
static extern void cupsFreeDests(int num_dests, IntPtr dests);
[DllImport("libcups", CharSet = CharSet.Ansi)]
static extern IntPtr cupsTempFd(StringBuilder sb, int len);
[DllImport("libcups", CharSet = CharSet.Ansi)]
static extern IntPtr cupsGetDefault();
[DllImport("libcups", CharSet = CharSet.Ansi)]
static extern int cupsPrintFile(string printer, string filename, string title, int num_options, IntPtr options);
[DllImport("libcups", CharSet = CharSet.Ansi)]
static extern IntPtr cupsGetPPD(string printer);
[DllImport("libcups", CharSet = CharSet.Ansi)]
static extern IntPtr ppdOpenFile(string filename);
[DllImport("libcups", CharSet = CharSet.Ansi)]
static extern IntPtr ppdFindOption(IntPtr ppd_file, string keyword);
[DllImport("libcups")]
static extern void ppdClose(IntPtr ppd);
[DllImport("libcups", CharSet = CharSet.Ansi)]
static extern int cupsParseOptions(string arg, int number_of_options, ref IntPtr options);
[DllImport("libcups")]
static extern void cupsFreeOptions(int number_options, IntPtr options);
[DllImport("gdiplus.dll", CharSet = CharSet.Ansi)]
static extern int GdipGetPostScriptGraphicsContext(string filename, int with, int height, double dpix, double dpiy, ref IntPtr graphics);
[DllImport("gdiplus.dll")]
static extern int GdipGetPostScriptSavePage(IntPtr graphics);
#endregion
#pragma warning disable 649
#region Struct
public struct DOCINFO
{
public PrinterSettings settings;
public PageSettings default_page_settings;
public string title;
public string filename;
}
public struct PPD_SIZE
{
public int marked;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 42)]
public string name;
public float width;
public float length;
public float left;
public float bottom;
public float right;
public float top;
}
public struct PPD_GROUP
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 40)]
public string text;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 42)]
public string name;
public int num_options;
public IntPtr options;
public int num_subgroups;
public IntPtr subgrups;
}
public struct PPD_OPTION
{
public byte conflicted;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 41)]
public string keyword;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 41)]
public string defchoice;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 81)]
public string text;
public int ui;
public int section;
public float order;
public int num_choices;
public IntPtr choices;
}
public struct PPD_CHOICE
{
public byte marked;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 41)]
public string choice;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 81)]
public string text;
public IntPtr code;
public IntPtr option;
}
public struct PPD_FILE
{
public int language_level;
public int color_device;
public int variable_sizes;
public int accurate_screens;
public int contone_only;
public int landscape;
public int model_number;
public int manual_copies;
public int throughput;
public int colorspace;
public IntPtr patches;
public int num_emulations;
public IntPtr emulations;
public IntPtr jcl_begin;
public IntPtr jcl_ps;
public IntPtr jcl_end;
public IntPtr lang_encoding;
public IntPtr lang_version;
public IntPtr modelname;
public IntPtr ttrasterizer;
public IntPtr manufacturer;
public IntPtr product;
public IntPtr nickname;
public IntPtr shortnickname;
public int num_groups;
public IntPtr groups;
public int num_sizes;
public IntPtr sizes;
/* There is more data after this that we are not using*/
}
public struct CUPS_OPTIONS
{
public IntPtr name;
public IntPtr val;
}
public struct CUPS_DESTS
{
public IntPtr name;
public IntPtr instance;
public int is_default;
public int num_options;
public IntPtr options;
}
#endregion
#pragma warning restore 649
}
class GlobalPrintingServicesUnix : GlobalPrintingServices
{
internal override PrinterSettings.StringCollection InstalledPrinters
{
get
{
return PrintingServicesUnix.InstalledPrinters;
}
}
internal override IntPtr CreateGraphicsContext(PrinterSettings settings, PageSettings default_page_settings)
{
return PrintingServicesUnix.CreateGraphicsContext(settings, default_page_settings);
}
internal override bool StartDoc(GraphicsPrinter gr, string doc_name, string output_file)
{
return PrintingServicesUnix.StartDoc(gr, doc_name, output_file);
}
internal override bool EndDoc(GraphicsPrinter gr)
{
return PrintingServicesUnix.EndDoc(gr);
}
internal override bool StartPage(GraphicsPrinter gr)
{
return PrintingServicesUnix.StartPage(gr);
}
internal override bool EndPage(GraphicsPrinter gr)
{
return PrintingServicesUnix.EndPage(gr);
}
}
}
| |
using System;
using System.Threading.Tasks;
using CorePhoto.IO;
using CorePhoto.Numerics;
using CorePhoto.Tests.Helpers;
using CorePhoto.Tiff;
using Xunit;
namespace CorePhoto.Tests.Tiff
{
public class TiffIfdReaderTests
{
public static object[][] SampleAsciiValues = new[] { new object[] { ByteOrder.LittleEndian, TiffType.Ascii, "\0", "" },
new object[] { ByteOrder.LittleEndian, TiffType.Ascii, "Test Text\0", "Test Text" },
new object[] { ByteOrder.LittleEndian, TiffType.Ascii, "First\0Second\0", "First\0Second" },
new object[] { ByteOrder.LittleEndian, TiffType.Ascii, null, null },
new object[] { ByteOrder.BigEndian, TiffType.Ascii, "\0", "" },
new object[] { ByteOrder.BigEndian, TiffType.Ascii, "Test Text\0", "Test Text" },
new object[] { ByteOrder.BigEndian, TiffType.Ascii, "First\0Second\0", "First\0Second" },
new object[] { ByteOrder.BigEndian, TiffType.Ascii, null, null }};
public static object[][] SampleIntegerValues = new[] { new object[] { ByteOrder.LittleEndian, TiffType.Undefined, (uint?)null },
new object[] { ByteOrder.LittleEndian, TiffType.Byte, (uint?)42 },
new object[] { ByteOrder.LittleEndian, TiffType.Short, (uint?)3482 },
new object[] { ByteOrder.LittleEndian, TiffType.Long, (uint?)96326 },
new object[] { ByteOrder.BigEndian, TiffType.Byte, (uint?)42 },
new object[] { ByteOrder.BigEndian, TiffType.Short, (uint?)3482 },
new object[] { ByteOrder.BigEndian, TiffType.Long, (uint?)96326 }};
public static object[][] SampleIntegerArrayValues = new[] { new object[] { ByteOrder.LittleEndian, TiffType.Undefined, null },
new object[] { ByteOrder.LittleEndian, TiffType.Byte, new uint[] { 42 } },
new object[] { ByteOrder.LittleEndian, TiffType.Byte, new uint[] { 41, 96 } },
new object[] { ByteOrder.LittleEndian, TiffType.Byte, new uint[] { 35, 91, 17 } },
new object[] { ByteOrder.LittleEndian, TiffType.Byte, new uint[] { 18, 91, 17, 24 } },
new object[] { ByteOrder.LittleEndian, TiffType.Byte, new uint[] { 28, 12, 63, 85, 13 } },
new object[] { ByteOrder.LittleEndian, TiffType.Short, new uint[] { 3482 } },
new object[] { ByteOrder.LittleEndian, TiffType.Short, new uint[] { 1452, 2852 } },
new object[] { ByteOrder.LittleEndian, TiffType.Short, new uint[] { 3452, 7934, 1853 } },
new object[] { ByteOrder.LittleEndian, TiffType.Long, new uint[] { 96326 } },
new object[] { ByteOrder.LittleEndian, TiffType.Long, new uint[] { 26894, 68395 } },
new object[] { ByteOrder.BigEndian, TiffType.Byte, new uint[] { 42 } },
new object[] { ByteOrder.BigEndian, TiffType.Byte, new uint[] { 41, 96 } },
new object[] { ByteOrder.BigEndian, TiffType.Byte, new uint[] { 35, 91, 17 } },
new object[] { ByteOrder.BigEndian, TiffType.Byte, new uint[] { 18, 91, 17, 24 } },
new object[] { ByteOrder.BigEndian, TiffType.Byte, new uint[] { 28, 12, 63, 85, 13 } },
new object[] { ByteOrder.BigEndian, TiffType.Short, new uint[] { 3482 } },
new object[] { ByteOrder.BigEndian, TiffType.Short, new uint[] { 1452, 2852 } },
new object[] { ByteOrder.BigEndian, TiffType.Short, new uint[] { 3452, 7934, 1853 } },
new object[] { ByteOrder.BigEndian, TiffType.Long, new uint[] { 96326 } },
new object[] { ByteOrder.BigEndian, TiffType.Long, new uint[] { 26894, 68395 } }};
public static object[][] SampleRationalValues = new[] { new object[] { ByteOrder.LittleEndian, TiffType.Undefined, (Rational?)null },
new object[] { ByteOrder.LittleEndian, TiffType.Rational, (Rational?)new Rational(1, 3) },
new object[] { ByteOrder.LittleEndian, TiffType.Rational, (Rational?)new Rational(10, 21) },
new object[] { ByteOrder.BigEndian, TiffType.Rational, (Rational?)new Rational(1, 3) },
new object[] { ByteOrder.BigEndian, TiffType.Rational, (Rational?)new Rational(10, 21) }};
public static object[][] SampleDateTimeValues = new[] { new object[] { ByteOrder.LittleEndian, TiffType.Ascii, "2012:05:18 11:46:08\0", new DateTimeOffset(2012, 5, 18, 11, 46, 8, TimeSpan.Zero) },
new object[] { ByteOrder.LittleEndian, TiffType.Ascii, null, null },
new object[] { ByteOrder.BigEndian, TiffType.Ascii, "2012:05:18 11:46:08\0", new DateTimeOffset(2012, 5, 18, 11, 46, 8, TimeSpan.Zero) },
new object[] { ByteOrder.BigEndian, TiffType.Ascii, null, null }};
[Theory]
[MemberData(nameof(SampleAsciiValues))]
public async Task ReadArtistAsync_ReturnsValue(ByteOrder byteOrder, TiffType type, string data, string expectedResult)
{
var ifdStreamTuple = TiffIfdBuilder.GenerateIfd(TiffTags.Artist, type, data, byteOrder);
var ifd = ifdStreamTuple.Ifd;
var stream = ifdStreamTuple.Stream;
var result = await ifd.ReadArtistAsync(stream, byteOrder);
Assert.Equal(expectedResult, result);
}
[Theory]
[MemberData(nameof(SampleIntegerArrayValues))]
public async Task ReadBitsPerSampleAsync_ReturnsValue(ByteOrder byteOrder, TiffType type, uint[] value)
{
var ifdStreamTuple = TiffIfdBuilder.GenerateIfd(TiffTags.BitsPerSample, type, value, byteOrder);
var ifd = ifdStreamTuple.Ifd;
var stream = ifdStreamTuple.Stream;
var result = await ifd.ReadBitsPerSampleAsync(stream, byteOrder);
if (value == null)
value = new uint[] { 1 }; // Default value
Assert.Equal(value, result);
}
[Theory]
[MemberData(nameof(SampleIntegerValues))]
public void GetCellLength_ReturnsValue(ByteOrder byteOrder, TiffType type, uint? value)
{
var ifd = TiffIfdBuilder.GenerateIfd(TiffTags.CellLength, type, value, byteOrder).Ifd;
var result = ifd.GetCellLength(byteOrder);
Assert.Equal(value, result);
}
[Theory]
[MemberData(nameof(SampleIntegerValues))]
public void GetCellWidth_ReturnsValue(ByteOrder byteOrder, TiffType type, uint? value)
{
var ifd = TiffIfdBuilder.GenerateIfd(TiffTags.CellWidth, type, value, byteOrder).Ifd;
var result = ifd.GetCellWidth(byteOrder);
Assert.Equal(value, result);
}
[Theory]
[MemberData(nameof(SampleIntegerArrayValues))]
public async Task ReadColorMapAsync_ReturnsValue(ByteOrder byteOrder, TiffType type, uint[] value)
{
var ifdStreamTuple = TiffIfdBuilder.GenerateIfd(TiffTags.ColorMap, type, value, byteOrder);
var ifd = ifdStreamTuple.Ifd;
var stream = ifdStreamTuple.Stream;
var result = await ifd.ReadColorMapAsync(stream, byteOrder);
Assert.Equal(value, result);
}
[Theory]
[InlineData(ByteOrder.LittleEndian, TiffType.Undefined, null, TiffCompression.None)]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, 1, TiffCompression.None)]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, 32773, TiffCompression.PackBits)]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, 99, (TiffCompression)99)]
[InlineData(ByteOrder.BigEndian, TiffType.Short, 1, TiffCompression.None)]
[InlineData(ByteOrder.BigEndian, TiffType.Short, 32773, TiffCompression.PackBits)]
[InlineData(ByteOrder.BigEndian, TiffType.Short, 99, (TiffCompression)99)]
public void GetCompression_ReturnsValue(ByteOrder byteOrder, TiffType type, int? data, TiffCompression expectedResult)
{
var ifd = TiffIfdBuilder.GenerateIfd(TiffTags.Compression, type, data, byteOrder).Ifd;
var result = ifd.GetCompression(byteOrder);
Assert.Equal(expectedResult, result);
}
[Theory]
[MemberData(nameof(SampleAsciiValues))]
public async Task ReadCopyrightAsync_ReturnsValue(ByteOrder byteOrder, TiffType type, string data, string expectedResult)
{
var ifdStreamTuple = TiffIfdBuilder.GenerateIfd(TiffTags.Copyright, type, data, byteOrder);
var ifd = ifdStreamTuple.Ifd;
var stream = ifdStreamTuple.Stream;
var result = await ifd.ReadCopyrightAsync(stream, byteOrder);
Assert.Equal(expectedResult, result);
}
[Theory]
[MemberData(nameof(SampleDateTimeValues))]
public async Task ReadDateTimeAsync_ReturnsValue(ByteOrder byteOrder, TiffType type, string data, DateTimeOffset? expectedResult)
{
var ifdStreamTuple = TiffIfdBuilder.GenerateIfd(TiffTags.DateTime, type, data, byteOrder);
var ifd = ifdStreamTuple.Ifd;
var stream = ifdStreamTuple.Stream;
var result = await ifd.ReadDateTimeAsync(stream, byteOrder);
Assert.Equal(expectedResult, result);
}
[Theory]
[InlineData(ByteOrder.LittleEndian, TiffType.Undefined, null, new TiffExtraSamples[0])]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, new uint[] { 0 }, new[] { TiffExtraSamples.Unspecified })]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, new uint[] { 1, 2 }, new[] { TiffExtraSamples.AssociatedAlpha, TiffExtraSamples.UnassociatedAlpha })]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, new uint[] { 99 }, new[] { (TiffExtraSamples)99 })]
[InlineData(ByteOrder.BigEndian, TiffType.Short, new uint[] { 0 }, new[] { TiffExtraSamples.Unspecified })]
[InlineData(ByteOrder.BigEndian, TiffType.Short, new uint[] { 1, 2 }, new[] { TiffExtraSamples.AssociatedAlpha, TiffExtraSamples.UnassociatedAlpha })]
[InlineData(ByteOrder.BigEndian, TiffType.Short, new uint[] { 99 }, new[] { (TiffExtraSamples)99 })]
public async Task ReadExtraSamplesAsync_ReturnsValue(ByteOrder byteOrder, TiffType type, uint[] data, TiffExtraSamples[] expectedResult)
{
var ifdStreamTuple = TiffIfdBuilder.GenerateIfd(TiffTags.ExtraSamples, type, data, byteOrder);
var ifd = ifdStreamTuple.Ifd;
var stream = ifdStreamTuple.Stream;
var result = await ifd.ReadExtraSamplesAsync(stream, byteOrder);
Assert.Equal(expectedResult, result);
}
[Theory]
[InlineData(ByteOrder.LittleEndian, TiffType.Undefined, null, TiffFillOrder.MostSignificantBitFirst)]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, 1, TiffFillOrder.MostSignificantBitFirst)]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, 2, TiffFillOrder.LeastSignificantBitFirst)]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, 99, (TiffFillOrder)99)]
[InlineData(ByteOrder.BigEndian, TiffType.Short, 1, TiffFillOrder.MostSignificantBitFirst)]
[InlineData(ByteOrder.BigEndian, TiffType.Short, 2, TiffFillOrder.LeastSignificantBitFirst)]
[InlineData(ByteOrder.BigEndian, TiffType.Short, 99, (TiffFillOrder)99)]
public void GetFillOrder_ReturnsValue(ByteOrder byteOrder, TiffType type, int? data, TiffFillOrder expectedResult)
{
var ifd = TiffIfdBuilder.GenerateIfd(TiffTags.FillOrder, type, data, byteOrder).Ifd;
var result = ifd.GetFillOrder(byteOrder);
Assert.Equal(expectedResult, result);
}
[Theory]
[MemberData(nameof(SampleIntegerArrayValues))]
public async Task ReadFreeByteCountsAsync_ReturnsValue(ByteOrder byteOrder, TiffType type, uint[] value)
{
var ifdStreamTuple = TiffIfdBuilder.GenerateIfd(TiffTags.FreeByteCounts, type, value, byteOrder);
var ifd = ifdStreamTuple.Ifd;
var stream = ifdStreamTuple.Stream;
var result = await ifd.ReadFreeByteCountsAsync(stream, byteOrder);
Assert.Equal(value, result);
}
[Theory]
[MemberData(nameof(SampleIntegerArrayValues))]
public async Task ReadFreeOffsetsAsync_ReturnsValue(ByteOrder byteOrder, TiffType type, uint[] value)
{
var ifdStreamTuple = TiffIfdBuilder.GenerateIfd(TiffTags.FreeOffsets, type, value, byteOrder);
var ifd = ifdStreamTuple.Ifd;
var stream = ifdStreamTuple.Stream;
var result = await ifd.ReadFreeOffsetsAsync(stream, byteOrder);
Assert.Equal(value, result);
}
[Theory]
[MemberData(nameof(SampleIntegerArrayValues))]
public async Task ReadGrayResponseCurveAsync_ReturnsValue(ByteOrder byteOrder, TiffType type, uint[] value)
{
var ifdStreamTuple = TiffIfdBuilder.GenerateIfd(TiffTags.GrayResponseCurve, type, value, byteOrder);
var ifd = ifdStreamTuple.Ifd;
var stream = ifdStreamTuple.Stream;
var result = await ifd.ReadGrayResponseCurveAsync(stream, byteOrder);
Assert.Equal(value, result);
}
[Theory]
[InlineData(ByteOrder.LittleEndian, TiffType.Undefined, null, 0.01)]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, 1, 0.1)]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, 2, 0.01)]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, 3, 0.001)]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, 4, 0.0001)]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, 5, 0.00001)]
[InlineData(ByteOrder.BigEndian, TiffType.Short, 1, 0.1)]
[InlineData(ByteOrder.BigEndian, TiffType.Short, 2, 0.01)]
[InlineData(ByteOrder.BigEndian, TiffType.Short, 3, 0.001)]
[InlineData(ByteOrder.BigEndian, TiffType.Short, 4, 0.0001)]
[InlineData(ByteOrder.BigEndian, TiffType.Short, 5, 0.00001)]
public void GetGrayResponseUnit_ReturnsValue(ByteOrder byteOrder, TiffType type, int? data, double expectedResult)
{
var ifd = TiffIfdBuilder.GenerateIfd(TiffTags.GrayResponseUnit, type, data, byteOrder).Ifd;
var result = ifd.GetGrayResponseUnit(byteOrder);
Assert.Equal(expectedResult, result);
}
[Theory]
[MemberData(nameof(SampleAsciiValues))]
public async Task ReadHostComputerAsync_ReturnsValue(ByteOrder byteOrder, TiffType type, string data, string expectedResult)
{
var ifdStreamTuple = TiffIfdBuilder.GenerateIfd(TiffTags.HostComputer, type, data, byteOrder);
var ifd = ifdStreamTuple.Ifd;
var stream = ifdStreamTuple.Stream;
var result = await ifd.ReadHostComputerAsync(stream, byteOrder);
Assert.Equal(expectedResult, result);
}
[Theory]
[MemberData(nameof(SampleAsciiValues))]
public async Task ReadImageDescriptionAsync_ReturnsValue(ByteOrder byteOrder, TiffType type, string data, string expectedResult)
{
var ifdStreamTuple = TiffIfdBuilder.GenerateIfd(TiffTags.ImageDescription, type, data, byteOrder);
var ifd = ifdStreamTuple.Ifd;
var stream = ifdStreamTuple.Stream;
var result = await ifd.ReadImageDescriptionAsync(stream, byteOrder);
Assert.Equal(expectedResult, result);
}
[Theory]
[MemberData(nameof(SampleIntegerValues))]
public void GetImageLength_ReturnsValue(ByteOrder byteOrder, TiffType type, uint? value)
{
var ifd = TiffIfdBuilder.GenerateIfd(TiffTags.ImageLength, type, value, byteOrder).Ifd;
var result = ifd.GetImageLength(byteOrder);
Assert.Equal(value, result);
}
[Theory]
[MemberData(nameof(SampleIntegerValues))]
public void GetImageWidth_ReturnsValue(ByteOrder byteOrder, TiffType type, uint? value)
{
var ifd = TiffIfdBuilder.GenerateIfd(TiffTags.ImageWidth, type, value, byteOrder).Ifd;
var result = ifd.GetImageWidth(byteOrder);
Assert.Equal(value, result);
}
[Theory]
[MemberData(nameof(SampleAsciiValues))]
public async Task ReadMakeAsync_ReturnsValue(ByteOrder byteOrder, TiffType type, string data, string expectedResult)
{
var ifdStreamTuple = TiffIfdBuilder.GenerateIfd(TiffTags.Make, type, data, byteOrder);
var ifd = ifdStreamTuple.Ifd;
var stream = ifdStreamTuple.Stream;
var result = await ifd.ReadMakeAsync(stream, byteOrder);
Assert.Equal(expectedResult, result);
}
[Theory]
[MemberData(nameof(SampleIntegerArrayValues))]
public async Task ReadMaxSampleValueAsync_ReturnsValue(ByteOrder byteOrder, TiffType type, uint[] value)
{
var ifdStreamTuple = TiffIfdBuilder.GenerateIfd(TiffTags.MaxSampleValue, type, value, byteOrder);
var ifd = ifdStreamTuple.Ifd;
var stream = ifdStreamTuple.Stream;
var result = await ifd.ReadMaxSampleValueAsync(stream, byteOrder);
Assert.Equal(value, result);
}
[Theory]
[MemberData(nameof(SampleIntegerArrayValues))]
public async Task ReadMinSampleValueAsync_ReturnsValue(ByteOrder byteOrder, TiffType type, uint[] value)
{
var ifdStreamTuple = TiffIfdBuilder.GenerateIfd(TiffTags.MinSampleValue, type, value, byteOrder);
var ifd = ifdStreamTuple.Ifd;
var stream = ifdStreamTuple.Stream;
var result = await ifd.ReadMinSampleValueAsync(stream, byteOrder);
Assert.Equal(value, result);
}
[Theory]
[MemberData(nameof(SampleAsciiValues))]
public async Task ReadModelAsync_ReturnsValue(ByteOrder byteOrder, TiffType type, string data, string expectedResult)
{
var ifdStreamTuple = TiffIfdBuilder.GenerateIfd(TiffTags.Model, type, data, byteOrder);
var ifd = ifdStreamTuple.Ifd;
var stream = ifdStreamTuple.Stream;
var result = await ifd.ReadModelAsync(stream, byteOrder);
Assert.Equal(expectedResult, result);
}
[Theory]
[InlineData(ByteOrder.LittleEndian, TiffType.Undefined, null, TiffNewSubfileType.FullImage)]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, 0, TiffNewSubfileType.FullImage)]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, 2, TiffNewSubfileType.SinglePage)]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, 3, TiffNewSubfileType.SinglePage | TiffNewSubfileType.Preview)]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, 99, (TiffNewSubfileType)99)]
[InlineData(ByteOrder.BigEndian, TiffType.Short, 0, TiffNewSubfileType.FullImage)]
[InlineData(ByteOrder.BigEndian, TiffType.Short, 2, TiffNewSubfileType.SinglePage)]
[InlineData(ByteOrder.BigEndian, TiffType.Short, 3, TiffNewSubfileType.SinglePage | TiffNewSubfileType.Preview)]
[InlineData(ByteOrder.BigEndian, TiffType.Short, 99, (TiffNewSubfileType)99)]
public void GetNewSubfileType_ReturnsValue(ByteOrder byteOrder, TiffType type, int? data, TiffNewSubfileType expectedResult)
{
var ifd = TiffIfdBuilder.GenerateIfd(TiffTags.NewSubfileType, type, data, byteOrder).Ifd;
var result = ifd.GetNewSubfileType(byteOrder);
Assert.Equal(expectedResult, result);
}
[Theory]
[InlineData(ByteOrder.LittleEndian, TiffType.Undefined, null, TiffOrientation.TopLeft)]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, 1, TiffOrientation.TopLeft)]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, 5, TiffOrientation.LeftTop)]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, 99, (TiffOrientation)99)]
[InlineData(ByteOrder.BigEndian, TiffType.Short, 1, TiffOrientation.TopLeft)]
[InlineData(ByteOrder.BigEndian, TiffType.Short, 5, TiffOrientation.LeftTop)]
[InlineData(ByteOrder.BigEndian, TiffType.Short, 99, (TiffOrientation)99)]
public void GetOrientation_ReturnsValue(ByteOrder byteOrder, TiffType type, int? data, TiffOrientation expectedResult)
{
var ifd = TiffIfdBuilder.GenerateIfd(TiffTags.Orientation, type, data, byteOrder).Ifd;
var result = ifd.GetOrientation(byteOrder);
Assert.Equal(expectedResult, result);
}
[Theory]
[InlineData(ByteOrder.LittleEndian, TiffType.Undefined, null, null)]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, 1, TiffPhotometricInterpretation.BlackIsZero)]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, 34892, TiffPhotometricInterpretation.LinearRaw)]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, 99, (TiffPhotometricInterpretation)99)]
[InlineData(ByteOrder.BigEndian, TiffType.Short, 1, TiffPhotometricInterpretation.BlackIsZero)]
[InlineData(ByteOrder.BigEndian, TiffType.Short, 34892, TiffPhotometricInterpretation.LinearRaw)]
[InlineData(ByteOrder.BigEndian, TiffType.Short, 99, (TiffPhotometricInterpretation)99)]
public void GetPhotometricInterpretation_ReturnsValue(ByteOrder byteOrder, TiffType type, int? data, TiffPhotometricInterpretation? expectedResult)
{
var ifd = TiffIfdBuilder.GenerateIfd(TiffTags.PhotometricInterpretation, type, data, byteOrder).Ifd;
var result = ifd.GetPhotometricInterpretation(byteOrder);
Assert.Equal(expectedResult, result);
}
[Theory]
[InlineData(ByteOrder.LittleEndian, TiffType.Undefined, null, TiffPlanarConfiguration.Chunky)]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, 1, TiffPlanarConfiguration.Chunky)]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, 2, TiffPlanarConfiguration.Planar)]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, 99, (TiffPlanarConfiguration)99)]
[InlineData(ByteOrder.BigEndian, TiffType.Short, 1, TiffPlanarConfiguration.Chunky)]
[InlineData(ByteOrder.BigEndian, TiffType.Short, 2, TiffPlanarConfiguration.Planar)]
[InlineData(ByteOrder.BigEndian, TiffType.Short, 99, (TiffPlanarConfiguration)99)]
public void GetPlanarConfiguraion_ReturnsValue(ByteOrder byteOrder, TiffType type, int? data, TiffPlanarConfiguration expectedResult)
{
var ifd = TiffIfdBuilder.GenerateIfd(TiffTags.PlanarConfiguration, type, data, byteOrder).Ifd;
var result = ifd.GetPlanarConfiguration(byteOrder);
Assert.Equal(expectedResult, result);
}
[Theory]
[InlineData(ByteOrder.LittleEndian, TiffType.Undefined, null, TiffResolutionUnit.Inch)]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, 1, TiffResolutionUnit.None)]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, 2, TiffResolutionUnit.Inch)]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, 99, (TiffResolutionUnit)99)]
[InlineData(ByteOrder.BigEndian, TiffType.Short, 1, TiffResolutionUnit.None)]
[InlineData(ByteOrder.BigEndian, TiffType.Short, 2, TiffResolutionUnit.Inch)]
[InlineData(ByteOrder.BigEndian, TiffType.Short, 99, (TiffResolutionUnit)99)]
public void GetResolutionUnit_ReturnsValue(ByteOrder byteOrder, TiffType type, int? data, TiffResolutionUnit expectedResult)
{
var ifd = TiffIfdBuilder.GenerateIfd(TiffTags.ResolutionUnit, type, data, byteOrder).Ifd;
var result = ifd.GetResolutionUnit(byteOrder);
Assert.Equal(expectedResult, result);
}
[Theory]
[MemberData(nameof(SampleIntegerValues))]
public void GetRowsPerStrip_ReturnsValue(ByteOrder byteOrder, TiffType type, uint? value)
{
var ifd = TiffIfdBuilder.GenerateIfd(TiffTags.RowsPerStrip, type, value, byteOrder).Ifd;
var result = ifd.GetRowsPerStrip(byteOrder);
if (value == null)
value = UInt32.MaxValue; // Default value
Assert.Equal(value, result);
}
[Theory]
[MemberData(nameof(SampleIntegerValues))]
public void GetSamplesPerPixel_ReturnsValue(ByteOrder byteOrder, TiffType type, uint? value)
{
var ifd = TiffIfdBuilder.GenerateIfd(TiffTags.SamplesPerPixel, type, value, byteOrder).Ifd;
var result = ifd.GetSamplesPerPixel(byteOrder);
if (value == null)
value = 1; // Default value
Assert.Equal(value, result);
}
[Theory]
[MemberData(nameof(SampleAsciiValues))]
public async Task ReadSoftwareAsync_ReturnsValue(ByteOrder byteOrder, TiffType type, string data, string expectedResult)
{
var ifdStreamTuple = TiffIfdBuilder.GenerateIfd(TiffTags.Software, type, data, byteOrder);
var ifd = ifdStreamTuple.Ifd;
var stream = ifdStreamTuple.Stream;
var result = await ifd.ReadSoftwareAsync(stream, byteOrder);
Assert.Equal(expectedResult, result);
}
[Theory]
[MemberData(nameof(SampleIntegerArrayValues))]
public async Task ReadStripByteCountsAsync_ReturnsValue(ByteOrder byteOrder, TiffType type, uint[] value)
{
var ifdStreamTuple = TiffIfdBuilder.GenerateIfd(TiffTags.StripByteCounts, type, value, byteOrder);
var ifd = ifdStreamTuple.Ifd;
var stream = ifdStreamTuple.Stream;
var result = await ifd.ReadStripByteCountsAsync(stream, byteOrder);
Assert.Equal(value, result);
}
[Theory]
[MemberData(nameof(SampleIntegerArrayValues))]
public async Task ReadStripOffsetsAsync_ReturnsValue(ByteOrder byteOrder, TiffType type, uint[] value)
{
var ifdStreamTuple = TiffIfdBuilder.GenerateIfd(TiffTags.StripOffsets, type, value, byteOrder);
var ifd = ifdStreamTuple.Ifd;
var stream = ifdStreamTuple.Stream;
var result = await ifd.ReadStripOffsetsAsync(stream, byteOrder);
Assert.Equal(value, result);
}
[Theory]
[InlineData(ByteOrder.LittleEndian, TiffType.Undefined, null, null)]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, 1, TiffSubfileType.FullImage)]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, 2, TiffSubfileType.Preview)]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, 99, (TiffSubfileType)99)]
[InlineData(ByteOrder.BigEndian, TiffType.Short, 1, TiffSubfileType.FullImage)]
[InlineData(ByteOrder.BigEndian, TiffType.Short, 2, TiffSubfileType.Preview)]
[InlineData(ByteOrder.BigEndian, TiffType.Short, 99, (TiffSubfileType)99)]
public void GetSubfileType_ReturnsValue(ByteOrder byteOrder, TiffType type, int? data, TiffSubfileType? expectedResult)
{
var ifd = TiffIfdBuilder.GenerateIfd(TiffTags.SubfileType, type, data, byteOrder).Ifd;
var result = ifd.GetSubfileType(byteOrder);
Assert.Equal(expectedResult, result);
}
[Theory]
[InlineData(ByteOrder.LittleEndian, TiffType.Undefined, null, TiffThreshholding.None)]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, 1, TiffThreshholding.None)]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, 2, TiffThreshholding.Ordered)]
[InlineData(ByteOrder.LittleEndian, TiffType.Short, 99, (TiffThreshholding)99)]
[InlineData(ByteOrder.BigEndian, TiffType.Short, 1, TiffThreshholding.None)]
[InlineData(ByteOrder.BigEndian, TiffType.Short, 2, TiffThreshholding.Ordered)]
[InlineData(ByteOrder.BigEndian, TiffType.Short, 99, (TiffThreshholding)99)]
public void GetThreshholding_ReturnsValue(ByteOrder byteOrder, TiffType type, int? data, TiffThreshholding expectedResult)
{
var ifd = TiffIfdBuilder.GenerateIfd(TiffTags.Threshholding, type, data, byteOrder).Ifd;
var result = ifd.GetThreshholding(byteOrder);
Assert.Equal(expectedResult, result);
}
[Theory]
[MemberData(nameof(SampleRationalValues))]
public async Task ReadXResolutionAsync_ReturnsValue(ByteOrder byteOrder, TiffType type, Rational? value)
{
var ifdStreamTuple = TiffIfdBuilder.GenerateIfd(TiffTags.XResolution, type, value, byteOrder);
var ifd = ifdStreamTuple.Ifd;
var stream = ifdStreamTuple.Stream;
var result = await ifd.ReadXResolutionAsync(stream, byteOrder);
Assert.Equal(value, result);
}
[Theory]
[MemberData(nameof(SampleRationalValues))]
public async Task ReadYResolutionAsync_ReturnsValue(ByteOrder byteOrder, TiffType type, Rational? value)
{
var ifdStreamTuple = TiffIfdBuilder.GenerateIfd(TiffTags.YResolution, type, value, byteOrder);
var ifd = ifdStreamTuple.Ifd;
var stream = ifdStreamTuple.Stream;
var result = await ifd.ReadYResolutionAsync(stream, byteOrder);
Assert.Equal(value, result);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Certify.Management;
using Certify.Models;
using Certify.Models.Providers;
namespace Certify.Core.Management
{
public class BindingDeploymentManager : IBindingDeploymentManager
{
private bool _enableCertDoubleImportBehaviour { get; set; } = true;
private static string[] unassignedIPs = new string[] {
null,
"",
"0.0.0.0",
"::",
"*"
};
private static string[] nonSpecificHostnames = new string[] {
null,
"",
"*"
};
/// <summary>
/// Creates or updates the https bindings associated with the dns names in the current
/// request config, using the requested port/ips or autobinding
/// </summary>
/// <param name="requestConfig"> </param>
/// <param name="pfxPath"> </param>
/// <param name="cleanupCertStore"> </param>
/// <returns> </returns>
public async Task<List<ActionStep>> StoreAndDeploy(IBindingDeploymentTarget deploymentTarget, ManagedCertificate managedCertificate, string pfxPath, string pfxPwd, bool isPreviewOnly)
{
var actions = new List<ActionStep>();
var requestConfig = managedCertificate.RequestConfig;
if (!isPreviewOnly)
{
if (new System.IO.FileInfo(pfxPath).Length == 0)
{
throw new ArgumentException("InstallCertForRequest: Invalid PFX File");
}
}
//store cert in default store against primary domain
var certStoreName = CertificateManager.GetStore().Name;
X509Certificate2 storedCert = null;
byte[] certHash = null;
// unless user has opted not to store cert, store it now
if (requestConfig.DeploymentSiteOption != DeploymentOption.NoDeployment)
{
if (!isPreviewOnly)
{
try
{
storedCert = await CertificateManager.StoreCertificate(requestConfig.PrimaryDomain, pfxPath, isRetry: false, enableRetryBehaviour: _enableCertDoubleImportBehaviour, pwd: pfxPwd);
if (storedCert != null)
{
certHash = storedCert.GetCertHash();
// TODO: move setting friendly name to cert request manager
managedCertificate.CertificateFriendlyName = storedCert.FriendlyName;
actions.Add(new ActionStep { HasError = false, Title = "Certificate Stored", Category = "Certificate Storage", Description = "Certificate stored OK" });
}
}
catch (Exception exp)
{
actions.Add(new ActionStep { HasError = true, Title = "Certificate Storage Failed", Category = "Certificate Storage", Description = "Error storing certificate." + exp.Message });
return actions;
}
}
else
{
//fake cert for preview only
storedCert = new X509Certificate2();
certHash = new byte[] { 0x00, 0x01, 0x02 };
}
}
if (storedCert != null)
{
//get list of domains we need to create/update https bindings for
var dnsHosts = new List<string> {
requestConfig.PrimaryDomain
};
if (requestConfig.SubjectAlternativeNames != null)
{
foreach (var san in requestConfig.SubjectAlternativeNames)
{
dnsHosts.Add(san);
}
}
dnsHosts = dnsHosts
.Distinct()
.Where(d => !string.IsNullOrEmpty(d))
.ToList();
// depending on our deployment mode we decide which sites/bindings to update:
var deployments = await DeployToAllTargetBindings(deploymentTarget, managedCertificate, requestConfig, certStoreName, certHash, dnsHosts, isPreviewOnly);
actions.AddRange(deployments);
}
else
{
if (requestConfig.DeploymentSiteOption != DeploymentOption.NoDeployment)
{
actions.Add(new ActionStep { HasError = true, Title = "Certificate Storage", Description = "Certificate could not be stored." });
}
}
// deployment tasks completed
return actions;
}
private async Task<List<ActionStep>> DeployToAllTargetBindings(IBindingDeploymentTarget deploymentTarget,
ManagedCertificate managedCertificate,
CertRequestConfig requestConfig,
string certStoreName,
byte[] certHash,
List<string> dnsHosts,
bool isPreviewOnly = false
)
{
var actions = new List<ActionStep>();
var targetSites = new List<IBindingDeploymentTargetItem>();
// ensure defaults applied for deployment mode
requestConfig.ApplyDeploymentOptionDefaults();
// if single site, add that
if (requestConfig.DeploymentSiteOption == DeploymentOption.SingleSite)
{
if (!string.IsNullOrEmpty(managedCertificate.ServerSiteId))
{
var site = await deploymentTarget.GetTargetItem(managedCertificate.ServerSiteId);
if (site != null)
{
targetSites.Add(site);
}
}
}
// or add all sites (if required)
if (requestConfig.DeploymentSiteOption == DeploymentOption.AllSites || requestConfig.DeploymentSiteOption == DeploymentOption.Auto)
{
targetSites.AddRange(await deploymentTarget.GetAllTargetItems());
}
// for each sites we want to target, identify bindings to add/update as required
foreach (var site in targetSites)
{
try
{
var existingBindings = await deploymentTarget.GetBindings(site.Id);
var existingHttps = existingBindings.Where(e => e.Protocol == "https").ToList();
//remove https bindings which already have an https equivalent (specific hostname or blank)
existingBindings.RemoveAll(b => existingHttps.Any(e => e.Host == b.Host) && b.Protocol == "http");
existingBindings = existingBindings.OrderBy(b => b.Protocol).ThenBy(b => b.Host).ToList();
// copy existing bindings so we can add/remove
var updatedBindings = existingBindings.ToList();
// for each binding create or update an https binding
foreach (var b in existingBindings)
{
var updateBinding = false;
//if binding is http and there is no https binding, create one
var hostname = b.Host;
// install the cert for this binding if the hostname matches, or we have a
// matching wildcard, or if there is no hostname specified in the binding
if (requestConfig.DeploymentBindingReplacePrevious || requestConfig.DeploymentSiteOption == DeploymentOption.Auto)
{
// if replacing previous, check if current binding cert hash matches
// previous cert hash
if (b.CertificateHash != null && (managedCertificate.CertificatePreviousThumbprintHash != null || managedCertificate.CertificateThumbprintHash != null))
{
if (string.Equals(b.CertificateHash, managedCertificate.CertificatePreviousThumbprintHash))
{
updateBinding = true;
}
else if (string.Equals(b.CertificateHash, managedCertificate.CertificateThumbprintHash))
{
updateBinding = true;
}
}
}
if (updateBinding == false)
{
// TODO: add wildcard match
if (nonSpecificHostnames.Contains(hostname) && requestConfig.DeploymentBindingBlankHostname)
{
updateBinding = true;
}
else
{
if (requestConfig.DeploymentBindingMatchHostname)
{
updateBinding = ManagedCertificate.IsDomainOrWildcardMatch(dnsHosts, hostname);
}
}
}
if (requestConfig.DeploymentBindingOption == DeploymentBindingOption.UpdateOnly)
{
// update existing bindings only, so only update if this is already an
// https binding
if (b.Protocol != "https")
{
updateBinding = false;
}
}
if (b.Protocol != "http" && b.Protocol != "https" && b.Protocol != "ftp")
{
// skip bindings for other service types
updateBinding = false;
}
if (updateBinding)
{
//SSL port defaults to 443 or the config default, unless we already have an https binding, in which case re-use same port
var sslPort = b.IsFtpSite ? 21 : 443;
var targetIPAddress = "*";
if (!string.IsNullOrWhiteSpace(requestConfig.BindingPort))
{
sslPort = int.Parse(requestConfig.BindingPort);
}
if (b.Protocol == "https")
{
if (b.Port > 0)
{
sslPort = b.Port;
}
if (!unassignedIPs.Contains(b.IP))
{
targetIPAddress = b.IP;
}
}
else
{
if (!unassignedIPs.Contains(requestConfig.BindingIPAddress))
{
targetIPAddress = requestConfig.BindingIPAddress;
}
}
//create/update binding and associate new cert
//if any binding elements configured, use those, otherwise auto bind using defaults and SNI
if (!b.IsFtpSite)
{
var stepActions = await UpdateWebBinding(
deploymentTarget,
site,
updatedBindings,
certStoreName,
certHash,
hostname,
sslPort: sslPort,
useSNI: (requestConfig.BindingUseSNI != null ? (bool)requestConfig.BindingUseSNI : true),
ipAddress: targetIPAddress,
alwaysRecreateBindings: requestConfig.AlwaysRecreateBindings,
isPreviewOnly: isPreviewOnly
);
actions.AddRange(stepActions);
}
else
{
var stepActions = await UpdateFtpBinding(
deploymentTarget,
site,
updatedBindings,
certStoreName,
managedCertificate.CertificateThumbprintHash,
sslPort,
hostname,
ipAddress: targetIPAddress,
isPreviewOnly: isPreviewOnly
);
actions.AddRange(stepActions);
}
}
}
}
catch (Exception exp)
{
actions.Add(new ActionStep { Title = site.Name, Category = "Deploy.AddOrUpdateBindings", HasError = true, Description = exp.ToString() });
}
}
return actions;
}
public static bool HasExistingBinding(List<BindingInfo> bindings, BindingInfo spec)
{
foreach (var b in bindings)
{
// same protocol
if (b.Protocol == spec.Protocol && b.Port == spec.Port)
{
// same or blank host
if (b.Host == spec.Host || (string.IsNullOrEmpty(b.Host) && string.IsNullOrEmpty(spec.Host)))
{
// same or unassigned IP
if (spec.IP == b.IP || (unassignedIPs.Contains(spec.IP) && unassignedIPs.Contains(b.IP)))
{
return true;
}
}
}
}
return false;
}
/// <summary>
/// creates or updates the https binding for the dns host name specified, assigning the given
/// certificate selected from the certificate store
/// </summary>
/// <param name="site"> </param>
/// <param name="certificate"> </param>
/// <param name="host"> </param>
/// <param name="sslPort"> </param>
/// <param name="useSNI"> </param>
/// <param name="ipAddress"> </param>
public async Task<List<ActionStep>> UpdateWebBinding(
IBindingDeploymentTarget deploymentTarget,
IBindingDeploymentTargetItem site,
List<BindingInfo> existingBindings,
string certStoreName,
byte[] certificateHash,
string host,
int sslPort = 443,
bool useSNI = true,
string ipAddress = null,
bool alwaysRecreateBindings = false,
bool isPreviewOnly = false
)
{
var steps = new List<ActionStep>();
var internationalHost = host ?? "";
if (unassignedIPs.Contains(ipAddress))
{
ipAddress = "*";
}
else
{
// specific IP address, SNI is not applicable
useSNI = false;
}
// can't use SNI is hostname is blank or wildcard
if (useSNI && nonSpecificHostnames.Contains(internationalHost))
{
useSNI = false;
}
var bindingSpecString = $"{ipAddress}:{sslPort}:{internationalHost}";
var bindingSpec = new BindingInfo
{
Host = internationalHost,
Protocol = "https",
IsHTTPS = true,
Port = sslPort,
IP = ipAddress,
SiteId = site.Id,
CertificateStore = certStoreName,
CertificateHashBytes = certificateHash,
IsSNIEnabled = useSNI
};
if (!HasExistingBinding(existingBindings, bindingSpec))
{
//there are no existing https bindings to update for this domain
//add new https binding at default port "<ip>:port:hostDnsName";
var action = new ActionStep
{
Title = "Install Certificate For Binding",
Category = "Deployment.AddBinding",
Description = $"Add {bindingSpec.Protocol} binding | {site.Name} | **{bindingSpecString} {(useSNI ? "SNI" : "Non-SNI")}**",
Key = $"[{site.Id}]:{bindingSpecString}:{useSNI}"
};
if (!isPreviewOnly)
{
var result = await deploymentTarget.AddBinding(bindingSpec);
if (result.HasError)
{
// failed to add
action.HasError = true;
action.Description += $" Failed to add binding. [{result.Description}]";
}
else
{
if (result.HasWarning)
{
action.HasWarning = true;
action.Description += $" [{result.Description}]";
}
}
// we have added a binding, add to our list of known bindings to avoid trying to add any duplicates
existingBindings.Add(bindingSpec);
}
else
{
// preview mode, validate binding spec
if (string.IsNullOrEmpty(bindingSpec.SiteId))
{
action.HasError = true;
action.Description += $" Failed to add/update binding. [IIS Site Id could not be determined]";
}
}
steps.Add(action);
}
else
{
// update one or more existing https bindings with new cert
var action = new ActionStep
{
Title = "Install Certificate For Binding",
Category = "Deployment.UpdateBinding",
Description = $"Update {bindingSpec.Protocol} binding | {site.Name} | **{bindingSpecString} {(useSNI ? "SNI" : "Non-SNI")}**"
};
if (!isPreviewOnly)
{
// Update existing https Binding
var result = await deploymentTarget.UpdateBinding(bindingSpec);
if (result.HasError)
{
// failed to update
action.HasError = true;
action.Description += $" Failed to update binding. [{result.Description}]";
}
else
{
if (result.HasWarning)
{
// has update warning
action.HasWarning = true;
action.Description += $" [{result.Description}]";
}
}
}
steps.Add(action);
}
return steps;
}
/// <summary>
/// creates or updates the https binding for the dns host name specified, assigning the given
/// certificate selected from the certificate store
/// </summary>
/// <param name="site"> </param>
/// <param name="certificate"> </param>
/// <param name="host"> </param>
/// <param name="sslPort"> </param>
/// <param name="ipAddress"> </param>
public async Task<List<ActionStep>> UpdateFtpBinding(
IBindingDeploymentTarget deploymentTarget,
IBindingDeploymentTargetItem site,
List<BindingInfo> existingBindings,
string certStoreName,
string certificateHash,
int port,
string host,
string ipAddress,
bool isPreviewOnly = false
)
{
var steps = new List<ActionStep>();
var internationalHost = host ?? "";
var bindingSpecString = $"{ipAddress}:{port}:{internationalHost}";
var bindingSpec = new BindingInfo
{
Host = internationalHost,
Protocol = "ftp",
IsHTTPS = true,
Port = port,
IP = ipAddress,
SiteId = site.Id,
CertificateStore = certStoreName,
CertificateHash = certificateHash,
IsFtpSite = true
};
if (!HasExistingBinding(existingBindings, bindingSpec))
{
//there are no existing applicable bindings to update for this domain
//add new ftp binding at default port "<ip>:port:hostDnsName";
var action = new ActionStep
{
Title = "Install Certificate For FTP Binding",
Category = "Deployment.AddBinding",
Description = $"Add {bindingSpec.Protocol} binding | {site.Name} | **{bindingSpecString} **",
Key = $"[{site.Id}]:{bindingSpecString}"
};
if (!isPreviewOnly)
{
var result = await deploymentTarget.AddBinding(bindingSpec);
if (result.HasError)
{
// failed to add
action.HasError = true;
action.Description += $" Failed to add binding. [{result.Description}]";
}
else
{
if (result.HasWarning)
{
action.HasWarning = true;
action.Description += $" [{result.Description}]";
}
}
}
steps.Add(action);
}
else
{
// update one or more existing bindings with new cert
var action = new ActionStep
{
Title = "Install Certificate For Binding",
Category = "Deployment.UpdateBinding",
Description = $"Update {bindingSpec.Protocol} binding | {site.Name} | **{bindingSpecString}**"
};
if (!isPreviewOnly)
{
// Update existing Binding
var result = await deploymentTarget.UpdateBinding(bindingSpec);
if (result.HasError)
{
// failed to update
action.HasError = true;
action.Description += $" Failed to update binding. [{result.Description}]";
}
else
{
if (result.HasWarning)
{
// has update warning
action.HasWarning = true;
action.Description += $" [{result.Description}]";
}
}
}
steps.Add(action);
}
return steps;
}
}
}
| |
/*
* Copyright (c) 2007-2009 Asger Feldthaus
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
namespace LTreeDemo
{
/// <summary>
/// Perspective camera using a position, target, and up-vector to calculate its view matrix.
/// </summary>
/// <remarks>
/// The View and Projection properties are rebuilt on a when-needed basis when one of the other properties they
/// depend on have been changed. This is very convenient, but in a multithreaded environment you should to call
/// CalculateAll() before entering a section with multiple threads accessing the camera. Otherwise, several threads
/// might try to write to the projection or view matrix, even though you thought you were only reading it.
/// </remarks>
public class Camera
{
#region Fields
private Matrix view;
private Matrix projection;
private BoundingFrustum boundingFrustum = new BoundingFrustum(Matrix.Identity);
private Vector3 target = Vector3.Zero;
private Vector3 position = new Vector3(0, 0, 10);
private Vector3 up = Vector3.Up;
private float fieldOfView = MathHelper.ToRadians(45.0f);
private float aspectRatio = 4.0f / 3.0f;
private float nearZ = 1.0f;
private float farZ = 100000.0f;
private bool obsoleteView = true;
private bool obsoleteProjection = true;
private bool obsoleteBoundingFrustum = true;
private const float DefaultDistance = 100.0f;
#endregion
#region Properties
/// <summary>
/// Gets the camera's view matrix. It will be recalculated if one of the following properties has changed:
/// Position, Target, or Up.
/// The view matrix transforms points from world space into view space. In view space, the X axis points
/// to the right of the camera, Y points upwards, and Z is backwards into the screen.
/// It is generally unwanted to use the standard properties of the Matrix class on a View matrix, because it
/// is actually the inverse transformation of the camera. If for instance the camera's forward vector is wanted,
/// using Matrix.Forward will not give the desired value. Instead, [-View.M13, -View.M23, -View.M33] will be the correct
/// forward vector.
/// </summary>
public Matrix View
{
get
{
if (obsoleteView)
UpdateViewMatrix();
return view;
}
}
/// <summary>
/// Gets the camera's projection matrix. It will be recalculated if one of the following properties has changed:
/// FieldOfView, AspectRatio, NearZ, or FarZ.
/// The projection matrix transforms points from view space into clip space (ie. screen coordinates).
/// </summary>
public Matrix Projection
{
get
{
if (obsoleteProjection)
UpdateProjectionMatrix();
return projection;
}
}
/// <summary>
/// Gets of sets the target point viewed by the camera. The camera will always orientate itself to look directly towards
/// this point.
/// </summary>
public Vector3 Target
{
get { return target; }
set { target = value; obsoleteView = true; }
}
/// <summary>
/// Gets of sets the position of the camera.
/// </summary>
public Vector3 Position
{
get { return position; }
set { position = value; obsoleteView = true; }
}
/// <summary>
/// Gets or sets the camera's up vector, which determines which direction should be considered "upwards" by the camera.
/// In most cases, you want to leave this as [0,1,0] (its default), but if you want the camera to roll around you have
/// to change it.
/// If you want the Z-axis to be the up-vector you can set this to [0,0,1].
/// </summary>
public Vector3 Up
{
get { return up; }
set { up = value; obsoleteView = true; }
}
/// <summary>
/// Gets or sets the camera's field of view, in radians. This is the angle between the leftmost visible point, and the rightmost visible
/// point. A value of PI/4 radians (~45 degrees) is the default, and is typically a good value.
/// You can decrease it to simulate a telescope-effect.
/// </summary>
public float FieldOfView
{
get { return fieldOfView; }
set { fieldOfView = value; obsoleteProjection = true; }
}
/// <summary>
/// Gets or sets the aspect ratio used by the camera's projection matrix. This should always match the aspect ratio of the viewport.
/// The aspect ratio is defined as Viewport.Width / Viewport.Height. You can get the Viewport's size using the GraphicsDevice.
/// The default value is 4.0f / 3.0f, but you probably want to set it manually to be sure it is correct.
/// </summary>
public float AspectRatio
{
get { return aspectRatio; }
set { aspectRatio = value; obsoleteProjection = true; }
}
/// <summary>
/// Distance to the closest visible point from the camera. Points closer than this will be invisible. The default
/// value is 1.0f, which usually is small enough. The value must be strictly greater than zero.
/// Do not confuse this with a clipping plane; changing this between render calls will mess up the depth buffer and
/// cause unwanted behaviour.
/// </summary>
public float NearZ
{
get { return nearZ; }
set { nearZ = value; obsoleteProjection = true; }
}
/// <summary>
/// Distance to the most distant visible point from the camera. Points further away than this will be invisible.
/// The default value is 100000.0f (one hundred thousand units) which is enough for a general-purpose camera.
/// If you experience zbuffer-fighting (seen as flickering surfaces) consider decreasing the FarZ value, as the
/// depth buffe's accuracy decreases the greater the FarZ value is.
/// </summary>
public float FarZ
{
get { return farZ; }
set { farZ = value; obsoleteProjection = true; }
}
/// <summary>
/// Returns a reference to the bounding frustum of the camera. Will be recalculated if needed.
/// The bounding frustum defines the area that is visible to the camera, and is useful for culling.
/// </summary>
/// <remarks>
/// Please note that this is a <i>reference</i> to the frustum -- you should clone it if you need to store
/// it for later use.
/// </remarks>
public BoundingFrustum BoundingFrustum
{
get
{
if (obsoleteBoundingFrustum || obsoleteProjection || obsoleteView)
UpdateBoundingFrustum();
return boundingFrustum;
}
}
/// <summary>
/// Gets a vector pointing in the direction the camera is looking.
/// </summary>
public Vector3 ForwardDir
{
get
{
if (obsoleteView)
UpdateViewMatrix();
return new Vector3(-view.M13, -view.M23, -view.M33);
}
}
/// <summary>
/// Gets a vector pointing to the left of the camera.
/// </summary>
public Vector3 LeftDir
{
get
{
if (obsoleteView)
UpdateViewMatrix();
return new Vector3(-view.M11, -view.M21, -view.M31);
}
}
/// <summary>
/// Gets a vector pointing to the right of the camera.
/// </summary>
public Vector3 RightDir
{
get
{
return -LeftDir;
}
}
#endregion
/// <summary>
/// Creates a new camera at [0,0,10] looking towards [0,0,0].
/// </summary>
public Camera()
{
}
/// <summary>
/// Creates a new camera.
/// </summary>
/// <param name="position">Position of the camera.</param>
/// <param name="target">Target of the camera.</param>
public Camera(Vector3 position, Vector3 target)
{
this.position = position;
this.target = target;
}
/// <summary>
/// Calculates the view and projection matrix, if needed.
/// </summary>
/// <remarks>
/// The matrices are automatically calculated (if needed) when View or Projection is accessed, so in single-threaded
/// program this method does not need to be called. In a multithreaded program, you should call this before entering
/// a section where multiple threads might read the camera's projection or view matrix, to prevent several threads from
/// writing to the cached values simultaneously.
/// </remarks>
public void CalculateAll()
{
if (obsoleteView)
UpdateViewMatrix();
if (obsoleteProjection)
UpdateProjectionMatrix();
}
#region Helpful methods
/// <summary>
/// Changes the camera's target and position to visualize a third person's perspective of a point, using specified
/// direction and angle-of-attack.
/// </summary>
/// <remarks>
/// Note that this function assumes that +Y is your up-vector (as by default). If you use another up-vector this will
/// probably give unexpected results.
/// </remarks>
/// <param name="target">The new camera target.</param>
/// <param name="orbitRadians">Orbital angle, in radians. 0 will place the camera to the "east" (+X) of the point.
/// PI/2 will place it to the "south" (+Z), PI will place it to the "west" (-X) and so on.</param>
/// <param name="pitchRadians">Pitch angle, in radians. 0 will give a flat horizontal perspective, while PI/2 gives a
/// complete top-down perspective of the target.</param>
/// <param name="distanceToTarget">Desired distance between the camera and the target.</param>
public void SetThirdPersonView(Vector3 target, float orbitRadians, float pitchRadians, float distanceToTarget)
{
this.target = target;
SetThirdPersonView(orbitRadians, pitchRadians, distanceToTarget);
}
/// <summary>
/// Changes the camera's position to visualize a third person's perspective of a point, using specified
/// direction and angle-of-attack. The camera will keep its existing target.
/// Note that this function assumes that +Y is your up-vector (as by default). If you use another up-vector this will
/// probably give unexpected results.
/// </summary>
/// <param name="orbitRadians">Orbital angle, in radians. 0 will place the camera to the "east" (+X) of the point.
/// PI/2 will place it to the "south" (+Z), PI will place it to the "west" (-X) and so on.</param>
/// <param name="pitchRadians">Pitch angle, in radians. 0 will give a flat horizontal perspective, while PI/2 gives a
/// complete top-down perspective of the target.</param>
/// <param name="distanceToTarget">Desired distance between the camera and the target.</param>
public void SetThirdPersonView(float orbitRadians, float pitchRadians, float distanceToTarget)
{
float co = (float)Math.Cos(orbitRadians);
float so = (float)Math.Sin(orbitRadians);
float cp = (float)Math.Cos(pitchRadians);
float sp = (float)Math.Sin(pitchRadians);
position = target + distanceToTarget * new Vector3(
co * cp,
sp,
so * cp);
obsoleteView = true;
}
/// <summary>
/// Changes the camera target to fit a first person's view.
/// </summary>
/// <param name="facingRadians">Direction of the viewer, 0 being east (+X), Pi/2 being north (-Z), and so on.</param>
/// <param name="pitchRadians">Up/down viewing angle. 0 is horizontal (flat), Pi/2 is straight upwards, and -Pi/2 is straight downwards.</param>
public void SetFirstPersonView(float facingRadians, float pitchRadians)
{
SetFirstPersonView(facingRadians, pitchRadians, DefaultDistance);
}
/// <summary>
/// Changes the camera target to fit a first person's view.
/// </summary>
/// <param name="facingRadians">Direction of the viewer, 0 being east (+X), Pi/2 being north (-Z), and so on.</param>
/// <param name="pitchRadians">Up/down viewing angle. 0 is horizontal (flat), Pi/2 is straight upwards, and -Pi/2 is straight downwards.</param>
/// <param name="distanceToTarget">Distance to the target point. This does not affect the view, but the Target property will be affected by it.</param>
public void SetFirstPersonView(float facingRadians, float pitchRadians, float distanceToTarget)
{
float cf = (float)Math.Cos(facingRadians);
float sf = (float)Math.Sin(facingRadians);
float cp = (float)Math.Cos(pitchRadians);
float sp = (float)Math.Sin(pitchRadians);
target = position + distanceToTarget * new Vector3(
cf * cp,
sp,
sf * cp);
obsoleteView = true;
}
/// <summary>
/// Moves the camera position and target to a new location, maintaining the original viewing angle.
/// </summary>
/// <param name="newPosition">New position, in world space.</param>
public void PanTo(Vector3 newPosition)
{
Vector3 delta = newPosition - position;
position = newPosition;
target += delta;
obsoleteView = true;
}
#endregion
#region Private updates
private void UpdateViewMatrix()
{
view = Matrix.CreateLookAt(position, target, up);
obsoleteView = false;
}
private void UpdateProjectionMatrix()
{
projection = Matrix.CreatePerspectiveFieldOfView(fieldOfView, aspectRatio, nearZ, farZ);
obsoleteProjection = false;
}
private void UpdateBoundingFrustum()
{
if (obsoleteView)
UpdateViewMatrix();
if (obsoleteProjection)
UpdateProjectionMatrix();
boundingFrustum.Matrix = view * projection;
obsoleteBoundingFrustum = false;
}
#endregion
}
}
| |
using HarmonyLib;
using System;
using System.Collections.Generic;
namespace HarmonyLibTests.Assets
{
public interface IAccessToolsType
{
int Property1 { get; }
string this[string key] { get; }
string Method1();
}
public interface IInner { }
#pragma warning disable CS0169, CS0414, IDE0044, IDE0051, IDE0052
public class AccessToolsClass : IAccessToolsType
{
private class Inner : IInner
{
public int x;
public override string ToString()
{
return x.ToString();
}
}
public static IInner NewInner(int x)
{
return new Inner { x = x };
}
private struct InnerStruct : IInner
{
public int x;
public override string ToString()
{
return x.ToString();
}
}
public static IInner NewInnerStruct(int x)
{
return new InnerStruct { x = x };
}
protected string field1 = "field1orig";
public readonly float field2 = 2.71828f;
public static long field3 = 271828L;
// Note: static readonly fields cannot be set by reflection since .NET Core 3+:
// https://docs.microsoft.com/en-us/dotnet/core/compatibility/corefx#fieldinfosetvalue-throws-exception-for-static-init-only-fields
// As of .NET Core 3.1, the FieldRef delegates can change static readonly fields, so all resetting happens in the unit tests themselves.
private static readonly string field4 = "field4orig";
private Inner field5 = new Inner { x = 999 };
private Inner[] field6 = new Inner[] { new Inner { x = 11 }, new Inner { x = 22 } };
private InnerStruct field7 = new InnerStruct { x = 999 };
private List<InnerStruct> field8 = new List<InnerStruct> { new InnerStruct { x = 11 }, new InnerStruct { x = 22 } };
internal DayOfWeek field9 = DayOfWeek.Saturday;
private int _property = 314159;
public int Property1
{
get => _property;
set => _property = value;
}
private int Property1b
{
get => _property;
set => _property = value;
}
protected string Property2 { get; } = "3.14159";
public static string Property3 { get; set; } = "2.71828";
private static double Property4 { get; } = 2.71828;
public string this[string key]
{
get => key;
set { }
}
public string Method1()
{
return field1;
}
public double Method2()
{
return field2;
}
public void SetField(string val)
{
field1 = val;
}
public static long Method3()
{
return field3;
}
public static string Method4()
{
return field4;
}
}
public class AccessToolsSubClass : AccessToolsClass
{
private string subclassField1 = "subclassField1orig";
internal static int subclassField2 = -321;
}
public struct AccessToolsStruct : IAccessToolsType
{
private enum InnerEnum : byte
{
A = 1,
B = 2,
C = 4,
}
public static Enum NewInnerEnum(byte b)
{
return (InnerEnum)b;
}
public string structField1;
private readonly int structField2;
private static int structField3 = -123;
public static readonly string structField4 = "structField4orig";
private InnerEnum structField5;
public int Property1 { get; set; }
private string Property2 { get; }
public static int Property3 { get; set; } = 299792458;
private static string Property4 { get; } = "299,792,458";
public string this[string key] => key;
// Structs don't allow default constructor (and even a constructor with all default parameters won't be called with 'new AccessToolsStruct()'),
// but we need to assign some values to instance fields that aren't simply the default value for their types
// (so that ref value can be checked against orig value).
public AccessToolsStruct(object _)
{
structField1 = "structField1orig";
structField2 = -666;
structField5 = InnerEnum.B;
Property1 = 161803;
Property2 = "1.61803";
}
public string Method1()
{
return structField1;
}
}
#pragma warning restore CS0169, CS0414, IDE0044, IDE0051, IDE0052
public static class AccessToolsCreateInstance
{
// Has default public parameterless constructor.
public class NoConstructor
{
public bool constructorCalled = true;
}
// Does NOT have a default public parameterless constructor (or any parameterless constructor for that matter).
public class OnlyNonParameterlessConstructor
{
public bool constructorCalled = true;
public OnlyNonParameterlessConstructor(int _)
{
}
}
public class PublicParameterlessConstructor
{
public bool constructorCalled = true;
public PublicParameterlessConstructor()
{
}
}
public class InternalParameterlessConstructor
{
public bool constructorCalled = true;
internal InternalParameterlessConstructor()
{
}
}
}
public static class AccessToolsMethodDelegate
{
public interface IInterface
{
string Test(int n, ref float f);
}
public class Base : IInterface
{
public int x;
public virtual string Test(int n, ref float f)
{
return $"base test {n} {++f} {++x}";
}
}
public class Derived : Base
{
public override string Test(int n, ref float f)
{
return $"derived test {n} {++f} {++x}";
}
}
public struct Struct : IInterface
{
public int x;
public string Test(int n, ref float f)
{
return $"struct result {n} {++f} {++x}";
}
}
public static int x;
public static string Test(int n, ref float f)
{
return $"static test {n} {++f} {++x}";
}
}
public static class AccessToolsHarmonyDelegate
{
public class Foo
{
private string SomeMethod(string s)
{
return $"[{s}]";
}
}
[HarmonyDelegate(typeof(Foo), "SomeMethod")]
public delegate string FooSomeMethod(Foo foo, string s);
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
namespace ExecParse.Test
{
[TestFixture]
public class ExecParseTest
{
[Test]
public void TestParseTwoErrors()
{
BuildEngineStub buildEngine = new BuildEngineStub();
ExecParse task = new ExecParse();
task.BuildEngine = buildEngine;
task.Configuration = @"
<Error>
<Search>(\b\w*?)\s+?\b\w*?\s+?fail:(.*?):line (\d*)[^\d]((.*) endline (\d+) column1 (\d+) column2 (.+) code (\d+) keyword (.+?)\s)?</Search>
<Message>$5</Message>
<Code>$9</Code>
<File>$2</File>
<HelpKeyword>$10</HelpKeyword>
<Subcategory>$1</Subcategory>
<LineNumber>$3</LineNumber>
<EndLineNumber>$6</EndLineNumber>
<ColumnNumber>$7</ColumnNumber>
<EndColumnNumber>$8</EndColumnNumber>
</Error>";
string output =
@"First line;
Second line fail:ExecParse.cs:line 23
Third line.
Fourth line fail:ExecParse.cs:line 1 my message endline 2 column1 3 column2 x code 5 keyword banana
Fifth line.";
task.ParseOutput(output);
Assert.AreEqual(2, buildEngine._errors.Count);
Assert.AreEqual(0, buildEngine._warnings.Count);
Assert.AreEqual(0, buildEngine._messages.Count);
Assert.AreEqual("Message='', Code='', File='ExecParse.cs', HelpKeyword='', Subcategory='Second', LineNumber=23, EndLineNumber=0, ColumnNumber=1, EndColumnNumber=0", buildEngine._errors[0]);
Assert.AreEqual("Message='my message', Code='5', File='ExecParse.cs', HelpKeyword='banana', Subcategory='Fourth', LineNumber=1, EndLineNumber=2, ColumnNumber=3, EndColumnNumber=0", buildEngine._errors[1]);
}
[Test]
public void TestDefaultColumnIsOne()
{
BuildEngineStub buildEngine = new BuildEngineStub();
ExecParse task = new ExecParse();
task.BuildEngine = buildEngine;
task.Configuration = @"
<Error>
<Search>(\b\w*?)\s+?\b\w*?\s+?fail:(.*?):line (\d*)[^\d]((.*) endline (\d+) column1 (\d+) column2 (.+) code (\d+) keyword (.+?)\s)?</Search>
<File>$2</File>
<LineNumber>$3</LineNumber>
</Error>";
string output =
@"First line;
Second line fail:ExecParse.cs:line 23
Third Line";
task.ParseOutput(output);
Assert.AreEqual(1, buildEngine._errors.Count);
Assert.AreEqual(0, buildEngine._warnings.Count);
Assert.AreEqual(0, buildEngine._messages.Count);
Assert.AreEqual("Message='', Code='', File='ExecParse.cs', HelpKeyword='', Subcategory='', LineNumber=23, EndLineNumber=0, ColumnNumber=1, EndColumnNumber=0", buildEngine._errors[0]);
}
[Test]
public void TestErrorMultipleLine()
{
BuildEngineStub buildEngine = new BuildEngineStub();
ExecParse task = new ExecParse();
task.BuildEngine = buildEngine;
task.Configuration = @"
<Error>
<Search>fail:[\s\S]*?(\w*) line:</Search>
<Message>$1</Message>
</Error>";
string output =
@"First line;
Second line fail:ExecParse.cs:line 23
Third line:
Fourth line fail:ExecParse.cs:line 1 my message endline 2 column1 3 column2 x code 5 keyword banana
Fifth line.";
task.ParseOutput(output);
Assert.AreEqual(1, buildEngine._errors.Count);
Assert.AreEqual(0, buildEngine._warnings.Count);
Assert.AreEqual(0, buildEngine._messages.Count);
Assert.AreEqual("Message='Third', Code='', File='', HelpKeyword='', Subcategory='', LineNumber=0, EndLineNumber=0, ColumnNumber=0, EndColumnNumber=0", buildEngine._errors[0]);
}
[Test]
public void TestMultipleErrorSearch()
{
BuildEngineStub buildEngine = new BuildEngineStub();
ExecParse task = new ExecParse();
task.BuildEngine = buildEngine;
task.Configuration = @"
<Error>
<Search>line (\d):</Search>
<Message>message search 1 = $1</Message>
</Error>
<Error>
<Search>(\d) line:</Search>
<Message>message search 2 = $1</Message>
</Error>";
string output =
@"line 1:
2 line:
Third line.";
task.ParseOutput(output);
Assert.AreEqual(2, buildEngine._errors.Count);
Assert.AreEqual(0, buildEngine._warnings.Count);
Assert.AreEqual(0, buildEngine._messages.Count);
Assert.AreEqual("Message='message search 1 = 1', Code='', File='', HelpKeyword='', Subcategory='', LineNumber=0, EndLineNumber=0, ColumnNumber=0, EndColumnNumber=0", buildEngine._errors[0]);
Assert.AreEqual("Message='message search 2 = 2', Code='', File='', HelpKeyword='', Subcategory='', LineNumber=0, EndLineNumber=0, ColumnNumber=0, EndColumnNumber=0", buildEngine._errors[1]);
}
[Test]
public void TestWarning()
{
BuildEngineStub buildEngine = new BuildEngineStub();
ExecParse task = new ExecParse();
task.BuildEngine = buildEngine;
task.Configuration = @"
<Warning>
<Search>fail:([\s\S]*?):</Search>
<Message>$1</Message>
</Warning>";
string output =
@"First line;
Second line fail:ExecParse.cs:line 23
Third line.";
task.ParseOutput(output);
Assert.AreEqual(0, buildEngine._errors.Count);
Assert.AreEqual(1, buildEngine._warnings.Count);
Assert.AreEqual(0, buildEngine._messages.Count);
Assert.AreEqual("Message='ExecParse.cs', Code='', File='BuildEngineStub', HelpKeyword='', Subcategory='', LineNumber=0, EndLineNumber=0, ColumnNumber=0, EndColumnNumber=0", buildEngine._warnings[0]);
}
[Test]
public void TestMessage()
{
BuildEngineStub buildEngine = new BuildEngineStub();
ExecParse task = new ExecParse();
task.BuildEngine = buildEngine;
task.Configuration = @"
<Message>
<Search>fail:([\s\S]*?):</Search>
<Message>$1</Message>
<Importance>high</Importance>
</Message>";
string output =
@"First line;
Second line fail:ExecParse.cs:line 23
Third line.";
task.ParseOutput(output);
Assert.AreEqual(0, buildEngine._errors.Count);
Assert.AreEqual(0, buildEngine._warnings.Count);
Assert.AreEqual(1, buildEngine._messages.Count);
Assert.AreEqual("Message='ExecParse.cs', Importance='High'", buildEngine._messages[0]);
}
[Test]
public void TestMultipleMessageSearch()
{
BuildEngineStub buildEngine = new BuildEngineStub();
ExecParse task = new ExecParse();
task.BuildEngine = buildEngine;
task.Configuration = @"
<Message>
<Search>line (\d):</Search>
<Message>message search 1 = $1</Message>
</Message>
<Message>
<Search>(\d) line:</Search>
<Message>message search 2 = $1</Message>
</Message>";
string output =
@"line 1:
2 line:
Third line.";
task.ParseOutput(output);
Assert.AreEqual(0, buildEngine._errors.Count);
Assert.AreEqual(0, buildEngine._warnings.Count);
Assert.AreEqual(2, buildEngine._messages.Count);
Assert.AreEqual("Message='message search 1 = 1', Importance='Low'", buildEngine._messages[0]);
Assert.AreEqual("Message='message search 2 = 2', Importance='Low'", buildEngine._messages[1]);
}
[Test]
public void TestConfigurationWithNamespace()
{
BuildEngineStub buildEngine = new BuildEngineStub();
ExecParse task = new ExecParse();
task.BuildEngine = buildEngine;
task.Configuration = @"
<Message xmlns='http://my.namespace.com/test' xmlns:tst=""http://my.namespace.com/test"">
<Search>fail:([\s\S]*?):</Search>
<Message>$1</Message>
</Message>";
string output =
@"First line;
Second line fail:ExecParse.cs:line 23
Third line.";
task.ParseOutput(output);
Assert.AreEqual(0, buildEngine._errors.Count);
Assert.AreEqual(0, buildEngine._warnings.Count);
Assert.AreEqual(1, buildEngine._messages.Count);
Assert.AreEqual("Message='ExecParse.cs', Importance='Low'", buildEngine._messages[0]);
}
[Test]
public void TestBlankConfiguration()
{
BuildEngineStub buildEngine = new BuildEngineStub();
ExecParse task = new ExecParse();
task.BuildEngine = buildEngine;
task.ParseOutput("");
Assert.AreEqual(0, buildEngine._errors.Count);
Assert.AreEqual(0, buildEngine._warnings.Count);
Assert.AreEqual(0, buildEngine._messages.Count);
}
[Test]
public void TestReplaceSearch()
{
BuildEngineStub buildEngine = new BuildEngineStub();
ExecParse task = new ExecParse();
task.BuildEngine = buildEngine;
task.Configuration = @"
<Message>
<Search>(aa)(?=bb)</Search>
<ReplaceSearch>(aa)</ReplaceSearch>
<Message>test $1</Message>
</Message>";
string output = "aabb";
task.ParseOutput(output);
Assert.AreEqual(0, buildEngine._errors.Count);
Assert.AreEqual(0, buildEngine._warnings.Count);
Assert.AreEqual(1, buildEngine._messages.Count);
Assert.AreEqual("Message='test aa', Importance='Low'", buildEngine._messages[0]);
}
[Test]
public void TestPassFail_NoErrorsOrWarningsLogged()
{
BuildEngineStub buildEngine = new BuildEngineStub();
ExecParse task = new ExecParse();
task.BuildEngine = buildEngine;
Assert.AreEqual(0, buildEngine._errors.Count);
Assert.AreEqual(0, buildEngine._warnings.Count);
task.ErrorCausesFail = false;
Assert.AreEqual(true, task.ModifiedPass(true));
Assert.AreEqual(false, task.ModifiedPass(false));
task.ErrorCausesFail = true;
Assert.AreEqual(true, task.ModifiedPass(true));
Assert.AreEqual(false, task.ModifiedPass(false));
}
[Test]
public void TestPassFail_SingleErrorNoWarningsLogged()
{
BuildEngineStub buildEngine = new BuildEngineStub();
ExecParse task = new ExecParse();
task.BuildEngine = buildEngine;
task.Configuration = @"
<Error>
<Search>b</Search>
</Error>";
string output = "abc";
task.ParseOutput(output);
Assert.AreEqual(1, buildEngine._errors.Count);
Assert.AreEqual(0, buildEngine._warnings.Count);
task.ErrorCausesFail = false;
Assert.AreEqual(true, task.ModifiedPass(true));
Assert.AreEqual(false, task.ModifiedPass(false));
task.ErrorCausesFail = true;
Assert.AreEqual(false, task.ModifiedPass(true));
Assert.AreEqual(false, task.ModifiedPass(false));
}
}
}
| |
#if !DISABLE_PLAYFABENTITY_API
using PlayFab.InsightsModels;
using PlayFab.Internal;
#pragma warning disable 0649
using System;
// This is required for the Obsolete Attribute flag
// which is not always present in all API's
#pragma warning restore 0649
using System.Collections.Generic;
using System.Threading.Tasks;
namespace PlayFab
{
/// <summary>
/// Manage the Insights performance level and data storage retention settings.
/// </summary>
public class PlayFabInsightsInstanceAPI
{
public readonly PlayFabApiSettings apiSettings = null;
public readonly PlayFabAuthenticationContext authenticationContext = null;
public PlayFabInsightsInstanceAPI(PlayFabAuthenticationContext context)
{
if (context == null)
throw new PlayFabException(PlayFabExceptionCode.AuthContextRequired, "Context cannot be null, create a PlayFabAuthenticationContext for each player in advance, or get <PlayFabClientInstanceAPI>.authenticationContext");
authenticationContext = context;
}
public PlayFabInsightsInstanceAPI(PlayFabApiSettings settings, PlayFabAuthenticationContext context)
{
if (context == null)
throw new PlayFabException(PlayFabExceptionCode.AuthContextRequired, "Context cannot be null, create a PlayFabAuthenticationContext for each player in advance, or get <PlayFabClientInstanceAPI>.authenticationContext");
apiSettings = settings;
authenticationContext = context;
}
/// <summary>
/// Verify entity login.
/// </summary>
public bool IsEntityLoggedIn()
{
return authenticationContext == null ? false : authenticationContext.IsEntityLoggedIn();
}
/// <summary>
/// Clear the Client SessionToken which allows this Client to call API calls requiring login.
/// A new/fresh login will be required after calling this.
/// </summary>
public void ForgetAllCredentials()
{
authenticationContext?.ForgetAllCredentials();
}
/// <summary>
/// Gets the current values for the Insights performance and data storage retention, list of pending operations, and the
/// performance and data storage retention limits.
/// </summary>
public async Task<PlayFabResult<InsightsGetDetailsResponse>> GetDetailsAsync(InsightsEmptyRequest request, object customData = null, Dictionary<string, string> extraHeaders = null)
{
await new PlayFabUtil.SynchronizationContextRemover();
var requestContext = request?.AuthenticationContext ?? authenticationContext;
var requestSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method");
var httpResult = await PlayFabHttp.DoPost("/Insights/GetDetails", request, "X-EntityToken", requestContext.EntityToken, extraHeaders, requestSettings);
if (httpResult is PlayFabError)
{
var error = (PlayFabError)httpResult;
PlayFabSettings.GlobalErrorHandler?.Invoke(error);
return new PlayFabResult<InsightsGetDetailsResponse> { Error = error, CustomData = customData };
}
var resultRawJson = (string)httpResult;
var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<InsightsGetDetailsResponse>>(resultRawJson);
var result = resultData.data;
return new PlayFabResult<InsightsGetDetailsResponse> { Result = result, CustomData = customData };
}
/// <summary>
/// Retrieves the range of allowed values for performance and data storage retention values as well as the submeter details
/// for each performance level.
/// </summary>
public async Task<PlayFabResult<InsightsGetLimitsResponse>> GetLimitsAsync(InsightsEmptyRequest request, object customData = null, Dictionary<string, string> extraHeaders = null)
{
await new PlayFabUtil.SynchronizationContextRemover();
var requestContext = request?.AuthenticationContext ?? authenticationContext;
var requestSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method");
var httpResult = await PlayFabHttp.DoPost("/Insights/GetLimits", request, "X-EntityToken", requestContext.EntityToken, extraHeaders, requestSettings);
if (httpResult is PlayFabError)
{
var error = (PlayFabError)httpResult;
PlayFabSettings.GlobalErrorHandler?.Invoke(error);
return new PlayFabResult<InsightsGetLimitsResponse> { Error = error, CustomData = customData };
}
var resultRawJson = (string)httpResult;
var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<InsightsGetLimitsResponse>>(resultRawJson);
var result = resultData.data;
return new PlayFabResult<InsightsGetLimitsResponse> { Result = result, CustomData = customData };
}
/// <summary>
/// Gets the status of a SetPerformance or SetStorageRetention operation.
/// </summary>
public async Task<PlayFabResult<InsightsGetOperationStatusResponse>> GetOperationStatusAsync(InsightsGetOperationStatusRequest request, object customData = null, Dictionary<string, string> extraHeaders = null)
{
await new PlayFabUtil.SynchronizationContextRemover();
var requestContext = request?.AuthenticationContext ?? authenticationContext;
var requestSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method");
var httpResult = await PlayFabHttp.DoPost("/Insights/GetOperationStatus", request, "X-EntityToken", requestContext.EntityToken, extraHeaders, requestSettings);
if (httpResult is PlayFabError)
{
var error = (PlayFabError)httpResult;
PlayFabSettings.GlobalErrorHandler?.Invoke(error);
return new PlayFabResult<InsightsGetOperationStatusResponse> { Error = error, CustomData = customData };
}
var resultRawJson = (string)httpResult;
var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<InsightsGetOperationStatusResponse>>(resultRawJson);
var result = resultData.data;
return new PlayFabResult<InsightsGetOperationStatusResponse> { Result = result, CustomData = customData };
}
/// <summary>
/// Gets a list of pending SetPerformance and/or SetStorageRetention operations for the title.
/// </summary>
public async Task<PlayFabResult<InsightsGetPendingOperationsResponse>> GetPendingOperationsAsync(InsightsGetPendingOperationsRequest request, object customData = null, Dictionary<string, string> extraHeaders = null)
{
await new PlayFabUtil.SynchronizationContextRemover();
var requestContext = request?.AuthenticationContext ?? authenticationContext;
var requestSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method");
var httpResult = await PlayFabHttp.DoPost("/Insights/GetPendingOperations", request, "X-EntityToken", requestContext.EntityToken, extraHeaders, requestSettings);
if (httpResult is PlayFabError)
{
var error = (PlayFabError)httpResult;
PlayFabSettings.GlobalErrorHandler?.Invoke(error);
return new PlayFabResult<InsightsGetPendingOperationsResponse> { Error = error, CustomData = customData };
}
var resultRawJson = (string)httpResult;
var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<InsightsGetPendingOperationsResponse>>(resultRawJson);
var result = resultData.data;
return new PlayFabResult<InsightsGetPendingOperationsResponse> { Result = result, CustomData = customData };
}
/// <summary>
/// Sets the Insights performance level value for the title.
/// </summary>
public async Task<PlayFabResult<InsightsOperationResponse>> SetPerformanceAsync(InsightsSetPerformanceRequest request, object customData = null, Dictionary<string, string> extraHeaders = null)
{
await new PlayFabUtil.SynchronizationContextRemover();
var requestContext = request?.AuthenticationContext ?? authenticationContext;
var requestSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method");
var httpResult = await PlayFabHttp.DoPost("/Insights/SetPerformance", request, "X-EntityToken", requestContext.EntityToken, extraHeaders, requestSettings);
if (httpResult is PlayFabError)
{
var error = (PlayFabError)httpResult;
PlayFabSettings.GlobalErrorHandler?.Invoke(error);
return new PlayFabResult<InsightsOperationResponse> { Error = error, CustomData = customData };
}
var resultRawJson = (string)httpResult;
var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<InsightsOperationResponse>>(resultRawJson);
var result = resultData.data;
return new PlayFabResult<InsightsOperationResponse> { Result = result, CustomData = customData };
}
/// <summary>
/// Sets the Insights data storage retention days value for the title.
/// </summary>
public async Task<PlayFabResult<InsightsOperationResponse>> SetStorageRetentionAsync(InsightsSetStorageRetentionRequest request, object customData = null, Dictionary<string, string> extraHeaders = null)
{
await new PlayFabUtil.SynchronizationContextRemover();
var requestContext = request?.AuthenticationContext ?? authenticationContext;
var requestSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method");
var httpResult = await PlayFabHttp.DoPost("/Insights/SetStorageRetention", request, "X-EntityToken", requestContext.EntityToken, extraHeaders, requestSettings);
if (httpResult is PlayFabError)
{
var error = (PlayFabError)httpResult;
PlayFabSettings.GlobalErrorHandler?.Invoke(error);
return new PlayFabResult<InsightsOperationResponse> { Error = error, CustomData = customData };
}
var resultRawJson = (string)httpResult;
var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<InsightsOperationResponse>>(resultRawJson);
var result = resultData.data;
return new PlayFabResult<InsightsOperationResponse> { Result = result, CustomData = customData };
}
}
}
#endif
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.SS.Formula.Function
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using NPOI.SS.Formula.PTG;
using System.Globalization;
using System.Text;
/**
* Converts the text meta-data file into a <c>FunctionMetadataRegistry</c>
*
* @author Josh Micich
*/
class FunctionMetadataReader
{
#if NETSTANDARD2_1 || NETSTANDARD2_0
private const String METADATA_FILE_NAME = "NPOI.Resources.functionMetadata.txt";
#else
private const String METADATA_FILE_NAME = "functionMetadata.txt";
#endif
/** plain ASCII text metadata file uses three dots for ellipsis */
private const string ELLIPSIS = "...";
private const string TAB_DELIM_PATTERN = @"\t";
private const string SPACE_DELIM_PATTERN = @"\s";
private static readonly byte[] EMPTY_BYTE_ARRAY = { };
private static readonly string[] DIGIT_ENDING_FUNCTION_NAMES = {
// Digits at the end of a function might be due to a left-over footnote marker.
// except in these cases
"LOG10", "ATAN2", "DAYS360", "SUMXMY2", "SUMX2MY2", "SUMX2PY2",
};
private static List<string> DIGIT_ENDING_FUNCTION_NAMES_Set = new List<string> (DIGIT_ENDING_FUNCTION_NAMES);
public static FunctionMetadataRegistry CreateRegistry()
{
using (StreamReader br = new StreamReader (typeof (FunctionMetadataReader).Assembly.GetManifestResourceStream (METADATA_FILE_NAME)))
{
FunctionDataBuilder fdb = new FunctionDataBuilder(400);
try
{
while (true)
{
String line = br.ReadLine();
if (line == null)
{
break;
}
if (line.Length < 1 || line[0] == '#')
{
continue;
}
String TrimLine = line.Trim();
if (TrimLine.Length < 1)
{
continue;
}
ProcessLine(fdb, line);
}
}
catch (IOException)
{
throw;
}
return fdb.Build();
}
}
private static void ProcessLine(FunctionDataBuilder fdb, String line)
{
Regex regex = new Regex(TAB_DELIM_PATTERN);
String[] parts = regex.Split(line);
if (parts.Length != 8)
{
throw new Exception("Bad line format '" + line + "' - expected 8 data fields");
}
int functionIndex = ParseInt(parts[0]);
String functionName = parts[1];
int minParams = ParseInt(parts[2]);
int maxParams = ParseInt(parts[3]);
byte returnClassCode = ParseReturnTypeCode(parts[4]);
byte[] parameterClassCodes = ParseOperandTypeCodes(parts[5]);
// 6 IsVolatile
bool hasNote = parts[7].Length > 0;
ValidateFunctionName(functionName);
// TODO - make POI use IsVolatile
fdb.Add(functionIndex, functionName, minParams, maxParams,
returnClassCode, parameterClassCodes, hasNote);
}
private static byte ParseReturnTypeCode(String code)
{
if (code.Length == 0)
{
return Ptg.CLASS_REF; // happens for GetPIVOTDATA
}
return ParseOperandTypeCode(code);
}
private static byte[] ParseOperandTypeCodes(String codes)
{
if (codes.Length < 1)
{
return EMPTY_BYTE_ARRAY; // happens for GetPIVOTDATA
}
if (IsDash(codes))
{
// '-' means empty:
return EMPTY_BYTE_ARRAY;
}
Regex regex = new Regex(SPACE_DELIM_PATTERN);
String[] array = regex.Split(codes);
int nItems = array.Length;
if (ELLIPSIS.Equals(array[nItems - 1]))
{
// ellipsis is optional, and ignored
// (all Unspecified params are assumed to be the same as the last)
nItems--;
}
byte[] result = new byte[nItems];
for (int i = 0; i < nItems; i++)
{
result[i] = ParseOperandTypeCode(array[i]);
}
return result;
}
private static bool IsDash(String codes)
{
if (codes.Length == 1)
{
switch (codes[0])
{
case '-':
return true;
}
}
return false;
}
private static byte ParseOperandTypeCode(String code)
{
if (code.Length != 1)
{
throw new Exception("Bad operand type code format '" + code + "' expected single char");
}
switch (code[0])
{
case 'V': return Ptg.CLASS_VALUE;
case 'R': return Ptg.CLASS_REF;
case 'A': return Ptg.CLASS_ARRAY;
}
throw new ArgumentException("Unexpected operand type code '" + code + "' (" + (int)code[0] + ")");
}
/**
* Makes sure that footnote digits from the original OOO document have not been accidentally
* left behind
*/
private static void ValidateFunctionName(String functionName)
{
int len = functionName.Length;
int ix = len - 1;
if (!Char.IsDigit(functionName[ix]))
{
return;
}
while (ix >= 0)
{
if (!Char.IsDigit(functionName[ix]))
{
break;
}
ix--;
}
if (DIGIT_ENDING_FUNCTION_NAMES_Set.Contains(functionName))
{
return;
}
throw new Exception("Invalid function name '" + functionName
+ "' (is footnote number incorrectly Appended)");
}
private static int ParseInt(String valStr)
{
return int.Parse(valStr, CultureInfo.InvariantCulture);
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using Google.ProtocolBuffers;
using log4net;
using Rhino.DistributedHashTable.Commands;
using Rhino.DistributedHashTable.Internal;
using Rhino.DistributedHashTable.Protocol;
using Rhino.DistributedHashTable.Remote;
using Rhino.DistributedHashTable.Util;
using Rhino.PersistentHashTable;
using NodeEndpoint = Rhino.DistributedHashTable.Internal.NodeEndpoint;
using ReplicationType=Rhino.DistributedHashTable.Protocol.ReplicationType;
namespace Rhino.DistributedHashTable.Hosting
{
public class DistributedHashTableMasterHost : IDisposable
{
private readonly IExecuter executer;
private readonly ILog log = LogManager.GetLogger(typeof(DistributedHashTableMasterHost));
private readonly TcpListener listener;
private readonly DistributedHashTableMaster master;
private readonly PersistentHashTable.PersistentHashTable hashTable;
public DistributedHashTableMasterHost()
: this("master.esent", new ThreadPoolExecuter(), 2200)
{
}
public DistributedHashTableMasterHost(string name, IExecuter executer, int port)
{
this.executer = executer;
master = new DistributedHashTableMaster();
master.TopologyChanged += OnTopologyChanged;
listener = new TcpListener(IPAddress.Any, port);
hashTable = new PersistentHashTable.PersistentHashTable(name);
}
private void OnTopologyChanged()
{
log.DebugFormat("Topology updated to {0}", master.Topology.Version);
executer.RegisterForExecution(new NotifyEndpointsAboutTopologyChange(
master.Endpoints.ToArray(),
new NonPooledDistributedHashTableNodeFactory()
));
PersistTopology();
}
private void PersistTopology()
{
byte[] buffer;
var topology = master.Topology.GetTopology();
using (var stream = new MemoryStream())
{
var writer = new MessageStreamWriter<TopologyResultMessage>(stream);
writer.Write(topology);
writer.Flush();
buffer = stream.ToArray();
}
hashTable.Batch(actions =>
{
var values = actions.Get(new GetRequest
{
Key = Constants.Topology
});
actions.Put(new PutRequest
{
Key = Constants.Topology,
ParentVersions = values.Select(x => x.Version).ToArray(),
Bytes = buffer,
IsReadOnly = true
});
actions.Commit();
});
}
public void Dispose()
{
listener.Stop();
executer.Dispose();
master.Dispose();
hashTable.Dispose();
}
public void Start()
{
hashTable.Initialize();
hashTable.Batch(actions =>
{
var value = actions.Get(new GetRequest {Key = Constants.Topology}).LastOrDefault();
if (value != null)
{
var topology = MessageStreamIterator<TopologyResultMessage>
.FromStreamProvider(() => new MemoryStream(value.Data))
.First();
master.Topology = topology.GetTopology();
master.RefreshEndpoints();
}
actions.Commit();
});
listener.Start();
listener.BeginAcceptTcpClient(OnAcceptTcpClient, null);
OnTopologyChanged();
}
private void OnAcceptTcpClient(IAsyncResult result)
{
TcpClient client;
try
{
client = listener.EndAcceptTcpClient(result);
}
catch (ObjectDisposedException)
{
return;
}
//this is done intentionally in a single threaded fashion
//the master is not a hot spot and it drastically simplify our life
//to avoid having to do multi threaded stuff here
//all calls to the master are also very short
try
{
using (client)
using (var stream = client.GetStream())
{
var writer = new MessageStreamWriter<MasterMessageUnion>(stream);
foreach (var wrapper in MessageStreamIterator<MasterMessageUnion>.FromStreamProvider(() => stream))
{
try
{
log.DebugFormat("Accepting message from {0} - {1}",
client.Client.RemoteEndPoint,
wrapper.Type);
switch (wrapper.Type)
{
case MasterMessageType.GetTopologyRequest:
HandleGetToplogy(writer);
break;
case MasterMessageType.JoinRequest:
HandleJoin(wrapper, writer);
break;
case MasterMessageType.CaughtUpRequest:
HandleCatchUp(wrapper, writer);
break;
case MasterMessageType.GaveUpRequest:
HandleGaveUp(wrapper, writer);
break;
default:
throw new ArgumentOutOfRangeException();
}
writer.Flush();
stream.Flush();
}
catch (Exception e)
{
log.Warn("Error performing request", e);
writer.Write(new MasterMessageUnion.Builder
{
Type = MasterMessageType.MasterErrorResult,
Exception = new ErrorMessage.Builder
{
Message = e.ToString()
}.Build()
}.Build());
writer.Flush();
stream.Flush();
}
}
}
}
catch (Exception e)
{
log.Warn("Error when dealing with a request (or could not send error details)", e);
}
finally
{
try
{
listener.BeginAcceptTcpClient(OnAcceptTcpClient, null);
}
catch (InvalidOperationException)
{
//the listener was closed
}
}
}
private void HandleCatchUp(MasterMessageUnion wrapper,
MessageStreamWriter<MasterMessageUnion> writer)
{
master.CaughtUp(new NodeEndpoint
{
Async = new Uri(wrapper.CaughtUp.Endpoint.Async),
Sync = new Uri(wrapper.CaughtUp.Endpoint.Sync)
},
wrapper.CaughtUp.Type == ReplicationType.Backup ? Internal.ReplicationType.Backup : Internal.ReplicationType.Ownership,
wrapper.CaughtUp.CaughtUpSegmentsList.ToArray());
writer.Write(new MasterMessageUnion.Builder
{
Type = MasterMessageType.CaughtUpResponse
}.Build());
}
private void HandleGaveUp(MasterMessageUnion wrapper,
MessageStreamWriter<MasterMessageUnion> writer)
{
master.GaveUp(new NodeEndpoint
{
Async = new Uri(wrapper.GaveUp.Endpoint.Async),
Sync = new Uri(wrapper.GaveUp.Endpoint.Sync)
},
wrapper.GaveUp.Type == ReplicationType.Backup ? Internal.ReplicationType.Backup : Internal.ReplicationType.Ownership,
wrapper.GaveUp.GaveUpSegmentsList.ToArray());
writer.Write(new MasterMessageUnion.Builder
{
Type = MasterMessageType.GaveUpResponse
}.Build());
}
private void HandleJoin(MasterMessageUnion wrapper,
MessageStreamWriter<MasterMessageUnion> writer)
{
var endpoint = wrapper.JoinRequest.EndpointJoining;
var segments = master.Join(new NodeEndpoint
{
Async = new Uri(endpoint.Async),
Sync = new Uri(endpoint.Sync)
});
var joinResponse = new JoinResponseMessage.Builder
{
SegmentsList = { segments.Select(x => x.GetSegment()) }
};
writer.Write(new MasterMessageUnion.Builder
{
Type = MasterMessageType.JoinResult,
JoinResponse = joinResponse.Build()
}.Build());
}
private void HandleGetToplogy(MessageStreamWriter<MasterMessageUnion> writer)
{
var topology = master.GetTopology();
writer.Write(new MasterMessageUnion.Builder
{
Type = MasterMessageType.GetTopologyResult,
Topology = topology.GetTopology()
}.Build());
}
}
}
| |
// 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,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using Microsoft.PythonTools;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Intellisense;
using Microsoft.PythonTools.Parsing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Tagging;
using TestUtilities;
using TestUtilities.Python;
namespace PythonToolsTests {
[TestClass]
public class EditorTests {
[ClassInitialize]
public static void DoDeployment(TestContext context) {
AssertListener.Initialize();
PythonTestData.Deploy();
}
#region Test Cases
#region Outlining Regions
[TestMethod, Priority(0)]
public void OutlineRegions() {
string content = @"print('Hello World')
#region
if param:
print('hello')
#endregion
elif not param:
print('world')
else:
print('!')
# region someClass
class someClass:
def this( self ):
return self._hidden_variable * 2
# endregion someClass";
SnapshotRegionTest(content,
new ExpectedTag(29, 77, "\r\nif param: \r\n print('hello')\r\n #endregion"),
new ExpectedTag(160, 269, "\r\nclass someClass:\r\n def this( self ):\r\n return self._hidden_variable * 2\r\n# endregion someClass"));
}
[TestMethod, Priority(0)]
public void OutlineUnbalancedRegions() {
string content = @"#region
#endregion
#endregion
#region
#region";
SnapshotRegionTest(content,
new ExpectedTag(7, 19, "\r\n#endregion"));
}
#endregion Outlining Regions
#region Outlining Cells
[TestMethod, Priority(0)]
public void OutlineCells() {
string content = @"pass
#%% cell 1
pass
#%% empty cell
#%%cell2
pass
# Preceding comment
# In[7]: IPython tag
pass
";
SnapshotCellTest(content,
new ExpectedTag(16, 22, "\r\npass"),
new ExpectedTag(50, 58, "\r\n\r\npass"),
new ExpectedTag(81, 109, "\r\n# In[7]: IPython tag\r\npass")
);
}
#endregion
#region Outline Compound Statements
[TestMethod, Priority(0)]
public void OutlineIf() {
string content = @"if param:
print('hello')
print('world')
print('!')
elif not param:
print('hello')
print('world')
print('!')
else:
print('hello')
print('world')
print('!')
if param and \
param:
print('hello')
print('world')
print('!')";
SnapshotOutlineTest(content,
new ExpectedTag(149, 205, "\r\n print('hello')\r\n print('world')\r\n print('!')"),
new ExpectedTag(9, 65, "\r\n print('hello')\r\n print('world')\r\n print('!')"),
new ExpectedTag(84, 140, "\r\n print('hello')\r\n print('world')\r\n print('!')"),
new ExpectedTag(223, 291, "\r\n param:\r\n print('hello')\r\n print('world')\r\n print('!')"));
}
[TestMethod, Priority(0)]
public void OutlineWhile() {
string content = @"while b and c and d \
and e \
and f:
print('hello')";
SnapshotOutlineTest(content,
new ExpectedTag(21, 66, "\r\n and e \\\r\n and f:\r\n print('hello')"));
}
[TestMethod, Priority(0)]
public void OutlineFor() {
string content = @"for x in [
1,
2,
3,
4
]:
print('for')
else:
print('final')
print('final')
print('final')
for x in [1,2,3,4]:
print('for2')
print('for2')
print('for2')";
SnapshotOutlineTest(content,
new ExpectedTag(11, 64, "\r\n 1,\r\n 2,\r\n 3,\r\n 4\r\n]:\r\n print('for')"),
new ExpectedTag(73, 133, "\r\n print('final')\r\n print('final')\r\n print('final')"),
new ExpectedTag(158, 215, "\r\n print('for2')\r\n print('for2')\r\n print('for2')"));
}
[TestMethod, Priority(0)]
public void OutlineTry() {
string content = @"
try:
print('try')
print('try')
except TypeError:
print('TypeError')
print('TypeError')
except NameError:
print('NameError')
print('NameError')
else:
print('else')
print('else')
finally:
print('finally')
print('finally')
try:
print('try2')
print('try2')
finally:
print('finally2')
print('finally2')";
SnapshotOutlineTest(content,
new ExpectedTag(6, 43, " \r\n print('try')\r\n print('try')"),
new ExpectedTag(62, 110, "\r\n print('TypeError')\r\n print('TypeError')"),
new ExpectedTag(129, 177, "\r\n print('NameError')\r\n print('NameError')"),
new ExpectedTag(232, 276, "\r\n print('finally')\r\n print('finally')"),
new ExpectedTag(184, 222, "\r\n print('else')\r\n print('else')"),
new ExpectedTag(284, 323, " \r\n print('try2')\r\n print('try2')"),
new ExpectedTag(333, 379, "\r\n print('finally2')\r\n print('finally2')"));
}
[TestMethod, Priority(0)]
public void OutlineWith() {
string content = @"with open('file.txt') as f:
line = f.readline()
print(line)";
SnapshotOutlineTest(content,
new ExpectedTag(27, 69, "\r\n line = f.readline()\r\n print(line)"));
}
[TestMethod, Priority(0)]
public void OutlineFuncDef() {
string content = @"@decorator_stmt_made_up
def f():
print('f')
def g(a,
b,
c):
print('g')
print('g')";
SnapshotOutlineTest(content,
new ExpectedTag(33, 134, "\r\n print('f')\r\n def g(a, \r\n b, \r\n c):\r\n print('g')\r\n print('g')"),
new ExpectedTag(94, 134, "\r\n print('g')\r\n print('g')"));
}
[TestMethod, Priority(0)]
public void OutlineClassDef() {
string content = @"class SomeClass:
def this( self ):
return self";
SnapshotOutlineTest(content,
new ExpectedTag(16, 60, "\r\n def this( self ):\r\n return self"));
}
[TestMethod, Priority(0)]
public void OutlineDecorated() {
string content = @"
@decorator_stmt(a,
b,
c)";
SnapshotOutlineTest(content,
new ExpectedTag(20, 58, "\r\n b,\r\n c)"));
}
#endregion Outline Compound Statements
#region Outlining Statements
[TestMethod, Priority(0)]
public void OutlineLists() {
string content = @"a = [1,
2,
3]
[1,
[2,
3,
5, 6, 7,
9,
10],
4
]
";
SnapshotOutlineTest(content,
new ExpectedTag(7, 25, "\r\n 2,\r\n 3]"),
new ExpectedTag(32, 123, "\r\n [2,\r\n 3,\r\n 5, 6, 7,\r\n 9,\r\n 10],\r\n 4\r\n ]"),
new ExpectedTag(45, 104, "\r\n 3,\r\n 5, 6, 7,\r\n 9,\r\n 10]"));
}
[TestMethod, Priority(0)]
public void OutlineTuple() {
string content = @"( 'value1',
'value2',
'value3')";
SnapshotOutlineTest(content,
new ExpectedTag(12, 38, "\r\n 'value2',\r\n 'value3')"));
}
[TestMethod, Priority(0)]
public void OutlineDictionary() {
string content = @"dict = {""hello"":""world"",
""hello"":""world"",""hello"":[1,
2,3,4,
5],
""hello"":""world"",
""check"": (""tuple1"",
""tuple2"",
""tuple3"",
""tuple4"")}";
SnapshotOutlineTest(content,
new ExpectedTag(24, 283,
"\r\n \"hello\":\"world\",\"hello\":[1,\r\n" +
" 2,3,4,\r\n" +
" 5],\r\n" +
" \"hello\":\"world\",\r\n" +
" \"check\": (\"tuple1\",\r\n" +
" \"tuple2\"," +
"\r\n \"tuple3\"," +
"\r\n \"tuple4\")}"),
new ExpectedTag(61, 139, "\r\n 2,3,4,\r\n 5]"),
new ExpectedTag(195, 282, "\r\n \"tuple2\",\r\n \"tuple3\",\r\n \"tuple4\")"));
}
[TestMethod, Priority(0)]
public void OutlineParenthesesExpression() {
string content = @"
( 'abc'
'def'
'qrt'
'quox'
)";
SnapshotOutlineTest(content,
new ExpectedTag(11, 48, "\r\n 'def'\r\n 'qrt'\r\n 'quox'\r\n)"));
}
[TestMethod, Priority(0)]
public void OutlineCallExpression() {
string content = @"function_call(arg1,
arg2,
arg3)";
SnapshotOutlineTest(content,
new ExpectedTag(19, 61, "\r\n arg2,\r\n arg3)"));
}
[TestMethod, Priority(0)]
public void OutlineFromImportStatement() {
string content = @"from sys \
import argv \
as c";
SnapshotOutlineTest(content,
new ExpectedTag(10, 31, "\r\nimport argv \\\r\nas c"));
}
[TestMethod, Priority(0)]
public void OutlineSetExpression() {
string content = @"{1,
2,
3}";
SnapshotOutlineTest(content,
new ExpectedTag(3, 13, "\r\n 2,\r\n 3}"));
}
[TestMethod, Priority(0)]
public void OutlineConstantExpression() {
string content = @"'''this
is
a
multiline
string'''";
SnapshotOutlineTest(content,
new ExpectedTag(7, 36, "\r\nis\r\na\r\nmultiline\r\nstring'''"));
}
private void SnapshotOutlineTest(string fileContents, params ExpectedTag[] expected) {
var snapshot = new TestUtilities.Mocks.MockTextSnapshot(new TestUtilities.Mocks.MockTextBuffer(fileContents), fileContents);
var ast = Parser.CreateParser(new TextSnapshotToTextReader(snapshot), PythonLanguageVersion.V34).ParseFile();
var walker = new OutliningWalker(ast);
ast.Walk(walker);
var protoTags = walker.GetTags();
var tags = protoTags.Select(x =>
OutliningTaggerProvider.OutliningTagger.GetTagSpan(
snapshot,
x.startIndex,
x.endIndex,
x.headerIndex
)
);
VerifyTags(snapshot, tags, expected);
}
private void SnapshotRegionTest(string fileContents, params ExpectedTag[] expected) {
var snapshot = new TestUtilities.Mocks.MockTextSnapshot(new TestUtilities.Mocks.MockTextBuffer(fileContents), fileContents);
var ast = Parser.CreateParser(new TextSnapshotToTextReader(snapshot), PythonLanguageVersion.V34).ParseFile();
var tags = Microsoft.PythonTools.OutliningTaggerProvider.OutliningTagger.ProcessRegionTags(snapshot, default(CancellationToken));
VerifyTags(snapshot, tags, expected);
}
private void SnapshotCellTest(string fileContents, params ExpectedTag[] expected) {
var snapshot = new TestUtilities.Mocks.MockTextSnapshot(new TestUtilities.Mocks.MockTextBuffer(fileContents), fileContents);
var ast = Parser.CreateParser(new TextSnapshotToTextReader(snapshot), PythonLanguageVersion.V34).ParseFile();
var tags = Microsoft.PythonTools.OutliningTaggerProvider.OutliningTagger.ProcessCellTags(snapshot, default(CancellationToken));
VerifyTags(snapshot, tags, expected);
}
#endregion Outlining Statements
private static StringLiteralCompletionList.EntryInfo MakeEntryInfo(string rootpath, string filename, string insertionText = null, string fullpath = null, bool? isFile = null) {
var realIsFile = isFile ?? !string.IsNullOrEmpty(Path.GetExtension(filename));
return new StringLiteralCompletionList.EntryInfo {
Tooltip = fullpath ?? Path.Combine(rootpath, filename),
InsertionText = insertionText ?? (Path.Combine(rootpath, filename) + (realIsFile ? "" : "\\")),
Caption = filename,
IsFile = realIsFile
};
}
[TestMethod, Priority(0)]
public void StringCompletionFileEntries() {
var cwd = TestData.GetPath("TestData");
var user = TestData.GetPath("TestData\\Databases");
AssertUtil.ContainsAtLeast(
StringLiteralCompletionList.GetEntryInfo(cwd + "\\AbsolutePaths", cwd, user),
MakeEntryInfo(cwd, "AbsolutePath"),
MakeEntryInfo(cwd, "AbsolutePath.sln"),
MakeEntryInfo(cwd, "HelloWorld"),
MakeEntryInfo(cwd, "HelloWorld.sln")
);
AssertUtil.ContainsAtLeast(
StringLiteralCompletionList.GetEntryInfo(cwd + "\\AbsolutePath\\", cwd, user),
MakeEntryInfo(cwd + "\\AbsolutePath", "AbsolutePath.pyproj")
);
AssertUtil.ContainsAtLeast(
StringLiteralCompletionList.GetEntryInfo("./AbsolutePaths", cwd, user),
MakeEntryInfo(cwd, "AbsolutePath", ".\\AbsolutePath\\"),
MakeEntryInfo(cwd, "AbsolutePath.sln", ".\\AbsolutePath.sln"),
MakeEntryInfo(cwd, "HelloWorld", ".\\HelloWorld\\"),
MakeEntryInfo(cwd, "HelloWorld.sln", ".\\HelloWorld.sln")
);
AssertUtil.ContainsAtLeast(
StringLiteralCompletionList.GetEntryInfo(".\\Ab", cwd, user),
MakeEntryInfo(cwd, "AbsolutePath", ".\\AbsolutePath\\"),
MakeEntryInfo(cwd, "AbsolutePath.sln", ".\\AbsolutePath.sln"),
MakeEntryInfo(cwd, "HelloWorld", ".\\HelloWorld\\"),
MakeEntryInfo(cwd, "HelloWorld.sln", ".\\HelloWorld.sln")
);
AssertUtil.ContainsAtLeast(
StringLiteralCompletionList.GetEntryInfo("~/Ab", cwd, user),
MakeEntryInfo(user, "V27", "~\\V27\\"),
MakeEntryInfo(user, "Readme.txt", "~\\Readme.txt")
);
AssertUtil.ContainsAtLeast(
StringLiteralCompletionList.GetEntryInfo("~\\Ab", cwd, user),
MakeEntryInfo(user, "V27", "~\\V27\\"),
MakeEntryInfo(user, "Readme.txt", "~\\Readme.txt")
);
AssertUtil.ContainsAtLeast(
StringLiteralCompletionList.GetEntryInfo("~\\V27\\", cwd, user),
MakeEntryInfo(user + "\\V27", "ntpath.idb", "~\\V27\\ntpath.idb"),
MakeEntryInfo(user + "\\V27", "os.idb", "~\\V27\\os.idb")
);
AssertUtil.ContainsAtLeast(
StringLiteralCompletionList.GetEntryInfo("Ab", cwd, user)
);
}
#endregion Test Cases
#region Helpers
private void VerifyTags(ITextSnapshot snapshot, IEnumerable<ITagSpan<IOutliningRegionTag>> tags, params ExpectedTag[] expected) {
var ltags = new List<ITagSpan<IOutliningRegionTag>>(tags);
// Print this out so we can easily update the tests if things change.
foreach (var tag in ltags) {
int start = tag.Span.Start.Position;
int end = tag.Span.End.Position;
Console.WriteLine("new ExpectedTag({0}, {1}, \"{2}\"),",
start,
end,
Classification.FormatString(snapshot.GetText(Span.FromBounds(start, end)))
);
}
Assert.AreEqual(expected.Length, ltags.Count);
for (int i = 0; i < ltags.Count; i++) {
int start = ltags[i].Span.Start.Position;
int end = ltags[i].Span.End.Position;
Assert.AreEqual(expected[i].Start, start);
Assert.AreEqual(expected[i].End, end);
Assert.AreEqual(expected[i].Text, snapshot.GetText(Span.FromBounds(start, end)));
Assert.AreEqual(ltags[i].Tag.IsImplementation, true);
}
}
private class ExpectedTag {
public readonly int Start, End;
public readonly string Text;
public ExpectedTag(int start, int end, string text) {
Start = start;
End = end;
Text = text;
}
}
#endregion
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Symbology.Forms.dll
// Description: The Windows Forms user interface layer for the DotSpatial.Symbology library.
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 11/20/2008 10:54:05 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace DotSpatial.Symbology.Forms
{
/// <summary>
/// ColorBox
/// </summary>
[DefaultEvent("SelectedItemChanged")]
[DefaultProperty("Value")]
public class ColorBox : UserControl
{
#region Events
/// <summary>
/// Occurs when the selected color has been changed in the drop-down
/// </summary>
public event EventHandler SelectedItemChanged;
#endregion
private ColorDropDown cddColor;
private Button cmdShowDialog;
private Label lblColor;
#region Private Variables
/// <summary>
/// Required designer variable.
/// </summary>
private IContainer components = null;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of ColorBox
/// </summary>
public ColorBox()
{
InitializeComponent();
cddColor.SelectedIndexChanged += cddColor_SelectedIndexChanged;
}
private void cddColor_SelectedIndexChanged(object sender, EventArgs e)
{
if (SelectedItemChanged != null) SelectedItemChanged(this, EventArgs.Empty);
}
#endregion
#region Methods
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
ComponentResourceManager resources = new ComponentResourceManager(typeof(ColorBox));
this.lblColor = new Label();
this.cddColor = new ColorDropDown();
this.cmdShowDialog = new Button();
this.SuspendLayout();
//
// lblColor
//
resources.ApplyResources(this.lblColor, "lblColor");
this.lblColor.Name = "lblColor";
//
// cddColor
//
resources.ApplyResources(this.cddColor, "cddColor");
this.cddColor.DrawMode = DrawMode.OwnerDrawFixed;
this.cddColor.DropDownStyle = ComboBoxStyle.DropDownList;
this.cddColor.FormattingEnabled = true;
this.cddColor.Items.AddRange(new[] {
((resources.GetObject("cddColor.Items"))),
((resources.GetObject("cddColor.Items1"))),
((resources.GetObject("cddColor.Items2"))),
((resources.GetObject("cddColor.Items3"))),
((resources.GetObject("cddColor.Items4"))),
((resources.GetObject("cddColor.Items5"))),
((resources.GetObject("cddColor.Items6"))),
((resources.GetObject("cddColor.Items7"))),
((resources.GetObject("cddColor.Items8"))),
((resources.GetObject("cddColor.Items9"))),
((resources.GetObject("cddColor.Items10"))),
((resources.GetObject("cddColor.Items11"))),
((resources.GetObject("cddColor.Items12"))),
((resources.GetObject("cddColor.Items13"))),
((resources.GetObject("cddColor.Items14"))),
((resources.GetObject("cddColor.Items15"))),
((resources.GetObject("cddColor.Items16"))),
((resources.GetObject("cddColor.Items17"))),
((resources.GetObject("cddColor.Items18"))),
((resources.GetObject("cddColor.Items19"))),
((resources.GetObject("cddColor.Items20"))),
((resources.GetObject("cddColor.Items21"))),
((resources.GetObject("cddColor.Items22"))),
((resources.GetObject("cddColor.Items23"))),
((resources.GetObject("cddColor.Items24"))),
((resources.GetObject("cddColor.Items25"))),
((resources.GetObject("cddColor.Items26"))),
((resources.GetObject("cddColor.Items27"))),
((resources.GetObject("cddColor.Items28"))),
((resources.GetObject("cddColor.Items29"))),
((resources.GetObject("cddColor.Items30"))),
((resources.GetObject("cddColor.Items31"))),
((resources.GetObject("cddColor.Items32"))),
((resources.GetObject("cddColor.Items33"))),
((resources.GetObject("cddColor.Items34"))),
((resources.GetObject("cddColor.Items35"))),
((resources.GetObject("cddColor.Items36"))),
((resources.GetObject("cddColor.Items37"))),
((resources.GetObject("cddColor.Items38"))),
((resources.GetObject("cddColor.Items39"))),
((resources.GetObject("cddColor.Items40"))),
((resources.GetObject("cddColor.Items41"))),
((resources.GetObject("cddColor.Items42"))),
((resources.GetObject("cddColor.Items43"))),
((resources.GetObject("cddColor.Items44"))),
((resources.GetObject("cddColor.Items45"))),
((resources.GetObject("cddColor.Items46"))),
((resources.GetObject("cddColor.Items47"))),
((resources.GetObject("cddColor.Items48"))),
((resources.GetObject("cddColor.Items49"))),
((resources.GetObject("cddColor.Items50"))),
((resources.GetObject("cddColor.Items51"))),
((resources.GetObject("cddColor.Items52"))),
((resources.GetObject("cddColor.Items53"))),
((resources.GetObject("cddColor.Items54"))),
((resources.GetObject("cddColor.Items55"))),
((resources.GetObject("cddColor.Items56"))),
((resources.GetObject("cddColor.Items57"))),
((resources.GetObject("cddColor.Items58"))),
((resources.GetObject("cddColor.Items59"))),
((resources.GetObject("cddColor.Items60"))),
((resources.GetObject("cddColor.Items61"))),
((resources.GetObject("cddColor.Items62"))),
((resources.GetObject("cddColor.Items63"))),
((resources.GetObject("cddColor.Items64"))),
((resources.GetObject("cddColor.Items65"))),
((resources.GetObject("cddColor.Items66"))),
((resources.GetObject("cddColor.Items67"))),
((resources.GetObject("cddColor.Items68"))),
((resources.GetObject("cddColor.Items69"))),
((resources.GetObject("cddColor.Items70"))),
((resources.GetObject("cddColor.Items71"))),
((resources.GetObject("cddColor.Items72"))),
((resources.GetObject("cddColor.Items73"))),
((resources.GetObject("cddColor.Items74"))),
((resources.GetObject("cddColor.Items75"))),
((resources.GetObject("cddColor.Items76"))),
((resources.GetObject("cddColor.Items77"))),
((resources.GetObject("cddColor.Items78"))),
((resources.GetObject("cddColor.Items79"))),
((resources.GetObject("cddColor.Items80"))),
((resources.GetObject("cddColor.Items81"))),
((resources.GetObject("cddColor.Items82"))),
((resources.GetObject("cddColor.Items83"))),
((resources.GetObject("cddColor.Items84"))),
((resources.GetObject("cddColor.Items85"))),
((resources.GetObject("cddColor.Items86"))),
((resources.GetObject("cddColor.Items87"))),
((resources.GetObject("cddColor.Items88"))),
((resources.GetObject("cddColor.Items89"))),
((resources.GetObject("cddColor.Items90"))),
((resources.GetObject("cddColor.Items91"))),
((resources.GetObject("cddColor.Items92"))),
((resources.GetObject("cddColor.Items93"))),
((resources.GetObject("cddColor.Items94"))),
((resources.GetObject("cddColor.Items95"))),
((resources.GetObject("cddColor.Items96"))),
((resources.GetObject("cddColor.Items97"))),
((resources.GetObject("cddColor.Items98"))),
((resources.GetObject("cddColor.Items99"))),
((resources.GetObject("cddColor.Items100"))),
((resources.GetObject("cddColor.Items101"))),
((resources.GetObject("cddColor.Items102"))),
((resources.GetObject("cddColor.Items103"))),
((resources.GetObject("cddColor.Items104"))),
((resources.GetObject("cddColor.Items105"))),
((resources.GetObject("cddColor.Items106"))),
((resources.GetObject("cddColor.Items107"))),
((resources.GetObject("cddColor.Items108"))),
((resources.GetObject("cddColor.Items109"))),
((resources.GetObject("cddColor.Items110"))),
((resources.GetObject("cddColor.Items111"))),
((resources.GetObject("cddColor.Items112"))),
((resources.GetObject("cddColor.Items113"))),
((resources.GetObject("cddColor.Items114"))),
((resources.GetObject("cddColor.Items115"))),
((resources.GetObject("cddColor.Items116"))),
((resources.GetObject("cddColor.Items117"))),
((resources.GetObject("cddColor.Items118"))),
((resources.GetObject("cddColor.Items119"))),
((resources.GetObject("cddColor.Items120"))),
((resources.GetObject("cddColor.Items121"))),
((resources.GetObject("cddColor.Items122"))),
((resources.GetObject("cddColor.Items123"))),
((resources.GetObject("cddColor.Items124"))),
((resources.GetObject("cddColor.Items125"))),
((resources.GetObject("cddColor.Items126"))),
((resources.GetObject("cddColor.Items127"))),
((resources.GetObject("cddColor.Items128"))),
((resources.GetObject("cddColor.Items129"))),
((resources.GetObject("cddColor.Items130"))),
((resources.GetObject("cddColor.Items131"))),
((resources.GetObject("cddColor.Items132"))),
((resources.GetObject("cddColor.Items133"))),
((resources.GetObject("cddColor.Items134"))),
((resources.GetObject("cddColor.Items135"))),
((resources.GetObject("cddColor.Items136"))),
((resources.GetObject("cddColor.Items137"))),
((resources.GetObject("cddColor.Items138"))),
((resources.GetObject("cddColor.Items139"))),
((resources.GetObject("cddColor.Items140"))),
((resources.GetObject("cddColor.Items141"))),
((resources.GetObject("cddColor.Items142"))),
((resources.GetObject("cddColor.Items143"))),
((resources.GetObject("cddColor.Items144"))),
((resources.GetObject("cddColor.Items145"))),
((resources.GetObject("cddColor.Items146"))),
((resources.GetObject("cddColor.Items147"))),
((resources.GetObject("cddColor.Items148"))),
((resources.GetObject("cddColor.Items149"))),
((resources.GetObject("cddColor.Items150"))),
((resources.GetObject("cddColor.Items151"))),
((resources.GetObject("cddColor.Items152"))),
((resources.GetObject("cddColor.Items153"))),
((resources.GetObject("cddColor.Items154"))),
((resources.GetObject("cddColor.Items155"))),
((resources.GetObject("cddColor.Items156"))),
((resources.GetObject("cddColor.Items157"))),
((resources.GetObject("cddColor.Items158"))),
((resources.GetObject("cddColor.Items159"))),
((resources.GetObject("cddColor.Items160"))),
((resources.GetObject("cddColor.Items161"))),
((resources.GetObject("cddColor.Items162"))),
((resources.GetObject("cddColor.Items163"))),
((resources.GetObject("cddColor.Items164"))),
((resources.GetObject("cddColor.Items165"))),
((resources.GetObject("cddColor.Items166"))),
((resources.GetObject("cddColor.Items167"))),
((resources.GetObject("cddColor.Items168"))),
((resources.GetObject("cddColor.Items169"))),
((resources.GetObject("cddColor.Items170"))),
((resources.GetObject("cddColor.Items171"))),
((resources.GetObject("cddColor.Items172"))),
((resources.GetObject("cddColor.Items173"))),
((resources.GetObject("cddColor.Items174"))),
((resources.GetObject("cddColor.Items175"))),
((resources.GetObject("cddColor.Items176"))),
((resources.GetObject("cddColor.Items177"))),
((resources.GetObject("cddColor.Items178"))),
((resources.GetObject("cddColor.Items179"))),
((resources.GetObject("cddColor.Items180"))),
((resources.GetObject("cddColor.Items181"))),
((resources.GetObject("cddColor.Items182"))),
((resources.GetObject("cddColor.Items183"))),
((resources.GetObject("cddColor.Items184"))),
((resources.GetObject("cddColor.Items185"))),
((resources.GetObject("cddColor.Items186"))),
((resources.GetObject("cddColor.Items187"))),
((resources.GetObject("cddColor.Items188"))),
((resources.GetObject("cddColor.Items189"))),
((resources.GetObject("cddColor.Items190"))),
((resources.GetObject("cddColor.Items191"))),
((resources.GetObject("cddColor.Items192"))),
((resources.GetObject("cddColor.Items193"))),
((resources.GetObject("cddColor.Items194"))),
((resources.GetObject("cddColor.Items195"))),
((resources.GetObject("cddColor.Items196"))),
((resources.GetObject("cddColor.Items197"))),
((resources.GetObject("cddColor.Items198"))),
((resources.GetObject("cddColor.Items199"))),
((resources.GetObject("cddColor.Items200"))),
((resources.GetObject("cddColor.Items201"))),
((resources.GetObject("cddColor.Items202"))),
((resources.GetObject("cddColor.Items203"))),
((resources.GetObject("cddColor.Items204"))),
((resources.GetObject("cddColor.Items205"))),
((resources.GetObject("cddColor.Items206"))),
((resources.GetObject("cddColor.Items207"))),
((resources.GetObject("cddColor.Items208"))),
((resources.GetObject("cddColor.Items209"))),
((resources.GetObject("cddColor.Items210"))),
((resources.GetObject("cddColor.Items211"))),
((resources.GetObject("cddColor.Items212"))),
((resources.GetObject("cddColor.Items213"))),
((resources.GetObject("cddColor.Items214"))),
((resources.GetObject("cddColor.Items215"))),
((resources.GetObject("cddColor.Items216"))),
((resources.GetObject("cddColor.Items217"))),
((resources.GetObject("cddColor.Items218"))),
((resources.GetObject("cddColor.Items219"))),
((resources.GetObject("cddColor.Items220"))),
((resources.GetObject("cddColor.Items221"))),
((resources.GetObject("cddColor.Items222"))),
((resources.GetObject("cddColor.Items223"))),
((resources.GetObject("cddColor.Items224"))),
((resources.GetObject("cddColor.Items225"))),
((resources.GetObject("cddColor.Items226"))),
((resources.GetObject("cddColor.Items227"))),
((resources.GetObject("cddColor.Items228"))),
((resources.GetObject("cddColor.Items229"))),
((resources.GetObject("cddColor.Items230"))),
((resources.GetObject("cddColor.Items231"))),
((resources.GetObject("cddColor.Items232"))),
((resources.GetObject("cddColor.Items233"))),
((resources.GetObject("cddColor.Items234"))),
((resources.GetObject("cddColor.Items235"))),
((resources.GetObject("cddColor.Items236"))),
((resources.GetObject("cddColor.Items237"))),
((resources.GetObject("cddColor.Items238"))),
((resources.GetObject("cddColor.Items239"))),
((resources.GetObject("cddColor.Items240"))),
((resources.GetObject("cddColor.Items241"))),
((resources.GetObject("cddColor.Items242"))),
((resources.GetObject("cddColor.Items243"))),
((resources.GetObject("cddColor.Items244"))),
((resources.GetObject("cddColor.Items245"))),
((resources.GetObject("cddColor.Items246"))),
((resources.GetObject("cddColor.Items247"))),
((resources.GetObject("cddColor.Items248"))),
((resources.GetObject("cddColor.Items249"))),
((resources.GetObject("cddColor.Items250"))),
((resources.GetObject("cddColor.Items251"))),
((resources.GetObject("cddColor.Items252"))),
((resources.GetObject("cddColor.Items253"))),
((resources.GetObject("cddColor.Items254"))),
((resources.GetObject("cddColor.Items255"))),
((resources.GetObject("cddColor.Items256"))),
((resources.GetObject("cddColor.Items257"))),
((resources.GetObject("cddColor.Items258"))),
((resources.GetObject("cddColor.Items259"))),
((resources.GetObject("cddColor.Items260"))),
((resources.GetObject("cddColor.Items261"))),
((resources.GetObject("cddColor.Items262"))),
((resources.GetObject("cddColor.Items263"))),
((resources.GetObject("cddColor.Items264"))),
((resources.GetObject("cddColor.Items265"))),
((resources.GetObject("cddColor.Items266"))),
((resources.GetObject("cddColor.Items267"))),
((resources.GetObject("cddColor.Items268"))),
((resources.GetObject("cddColor.Items269"))),
((resources.GetObject("cddColor.Items270"))),
((resources.GetObject("cddColor.Items271"))),
((resources.GetObject("cddColor.Items272"))),
((resources.GetObject("cddColor.Items273"))),
((resources.GetObject("cddColor.Items274"))),
((resources.GetObject("cddColor.Items275"))),
((resources.GetObject("cddColor.Items276"))),
((resources.GetObject("cddColor.Items277"))),
((resources.GetObject("cddColor.Items278"))),
((resources.GetObject("cddColor.Items279"))),
((resources.GetObject("cddColor.Items280"))),
((resources.GetObject("cddColor.Items281"))),
((resources.GetObject("cddColor.Items282"))),
((resources.GetObject("cddColor.Items283"))),
((resources.GetObject("cddColor.Items284"))),
((resources.GetObject("cddColor.Items285"))),
((resources.GetObject("cddColor.Items286"))),
((resources.GetObject("cddColor.Items287"))),
((resources.GetObject("cddColor.Items288"))),
((resources.GetObject("cddColor.Items289"))),
((resources.GetObject("cddColor.Items290"))),
((resources.GetObject("cddColor.Items291"))),
((resources.GetObject("cddColor.Items292"))),
((resources.GetObject("cddColor.Items293"))),
((resources.GetObject("cddColor.Items294"))),
((resources.GetObject("cddColor.Items295"))),
((resources.GetObject("cddColor.Items296"))),
((resources.GetObject("cddColor.Items297"))),
((resources.GetObject("cddColor.Items298"))),
((resources.GetObject("cddColor.Items299"))),
((resources.GetObject("cddColor.Items300"))),
((resources.GetObject("cddColor.Items301"))),
((resources.GetObject("cddColor.Items302"))),
((resources.GetObject("cddColor.Items303"))),
((resources.GetObject("cddColor.Items304"))),
((resources.GetObject("cddColor.Items305"))),
((resources.GetObject("cddColor.Items306"))),
((resources.GetObject("cddColor.Items307"))),
((resources.GetObject("cddColor.Items308"))),
((resources.GetObject("cddColor.Items309"))),
((resources.GetObject("cddColor.Items310"))),
((resources.GetObject("cddColor.Items311"))),
((resources.GetObject("cddColor.Items312"))),
((resources.GetObject("cddColor.Items313"))),
((resources.GetObject("cddColor.Items314"))),
((resources.GetObject("cddColor.Items315"))),
((resources.GetObject("cddColor.Items316"))),
((resources.GetObject("cddColor.Items317"))),
((resources.GetObject("cddColor.Items318"))),
((resources.GetObject("cddColor.Items319"))),
((resources.GetObject("cddColor.Items320"))),
((resources.GetObject("cddColor.Items321"))),
((resources.GetObject("cddColor.Items322"))),
((resources.GetObject("cddColor.Items323"))),
((resources.GetObject("cddColor.Items324"))),
((resources.GetObject("cddColor.Items325"))),
((resources.GetObject("cddColor.Items326"))),
((resources.GetObject("cddColor.Items327"))),
((resources.GetObject("cddColor.Items328"))),
((resources.GetObject("cddColor.Items329"))),
((resources.GetObject("cddColor.Items330"))),
((resources.GetObject("cddColor.Items331"))),
((resources.GetObject("cddColor.Items332"))),
((resources.GetObject("cddColor.Items333"))),
((resources.GetObject("cddColor.Items334"))),
((resources.GetObject("cddColor.Items335"))),
((resources.GetObject("cddColor.Items336"))),
((resources.GetObject("cddColor.Items337"))),
((resources.GetObject("cddColor.Items338"))),
((resources.GetObject("cddColor.Items339"))),
((resources.GetObject("cddColor.Items340"))),
((resources.GetObject("cddColor.Items341"))),
((resources.GetObject("cddColor.Items342"))),
((resources.GetObject("cddColor.Items343"))),
((resources.GetObject("cddColor.Items344"))),
((resources.GetObject("cddColor.Items345"))),
((resources.GetObject("cddColor.Items346"))),
((resources.GetObject("cddColor.Items347"))),
((resources.GetObject("cddColor.Items348"))),
((resources.GetObject("cddColor.Items349"))),
((resources.GetObject("cddColor.Items350"))),
((resources.GetObject("cddColor.Items351"))),
((resources.GetObject("cddColor.Items352"))),
((resources.GetObject("cddColor.Items353"))),
((resources.GetObject("cddColor.Items354"))),
((resources.GetObject("cddColor.Items355"))),
((resources.GetObject("cddColor.Items356"))),
((resources.GetObject("cddColor.Items357"))),
((resources.GetObject("cddColor.Items358"))),
((resources.GetObject("cddColor.Items359"))),
((resources.GetObject("cddColor.Items360"))),
((resources.GetObject("cddColor.Items361"))),
((resources.GetObject("cddColor.Items362"))),
((resources.GetObject("cddColor.Items363"))),
((resources.GetObject("cddColor.Items364"))),
((resources.GetObject("cddColor.Items365"))),
((resources.GetObject("cddColor.Items366"))),
((resources.GetObject("cddColor.Items367"))),
((resources.GetObject("cddColor.Items368"))),
((resources.GetObject("cddColor.Items369"))),
((resources.GetObject("cddColor.Items370"))),
((resources.GetObject("cddColor.Items371"))),
((resources.GetObject("cddColor.Items372"))),
((resources.GetObject("cddColor.Items373"))),
((resources.GetObject("cddColor.Items374"))),
((resources.GetObject("cddColor.Items375"))),
((resources.GetObject("cddColor.Items376"))),
((resources.GetObject("cddColor.Items377"))),
((resources.GetObject("cddColor.Items378"))),
((resources.GetObject("cddColor.Items379"))),
((resources.GetObject("cddColor.Items380"))),
((resources.GetObject("cddColor.Items381"))),
((resources.GetObject("cddColor.Items382"))),
((resources.GetObject("cddColor.Items383"))),
((resources.GetObject("cddColor.Items384"))),
((resources.GetObject("cddColor.Items385"))),
((resources.GetObject("cddColor.Items386"))),
((resources.GetObject("cddColor.Items387"))),
((resources.GetObject("cddColor.Items388"))),
((resources.GetObject("cddColor.Items389"))),
((resources.GetObject("cddColor.Items390"))),
((resources.GetObject("cddColor.Items391"))),
((resources.GetObject("cddColor.Items392"))),
((resources.GetObject("cddColor.Items393"))),
((resources.GetObject("cddColor.Items394"))),
((resources.GetObject("cddColor.Items395"))),
((resources.GetObject("cddColor.Items396"))),
((resources.GetObject("cddColor.Items397"))),
((resources.GetObject("cddColor.Items398"))),
((resources.GetObject("cddColor.Items399"))),
((resources.GetObject("cddColor.Items400"))),
((resources.GetObject("cddColor.Items401"))),
((resources.GetObject("cddColor.Items402"))),
((resources.GetObject("cddColor.Items403"))),
((resources.GetObject("cddColor.Items404"))),
((resources.GetObject("cddColor.Items405"))),
((resources.GetObject("cddColor.Items406"))),
((resources.GetObject("cddColor.Items407"))),
((resources.GetObject("cddColor.Items408"))),
((resources.GetObject("cddColor.Items409"))),
((resources.GetObject("cddColor.Items410"))),
((resources.GetObject("cddColor.Items411"))),
((resources.GetObject("cddColor.Items412"))),
((resources.GetObject("cddColor.Items413"))),
((resources.GetObject("cddColor.Items414"))),
((resources.GetObject("cddColor.Items415"))),
((resources.GetObject("cddColor.Items416"))),
((resources.GetObject("cddColor.Items417"))),
((resources.GetObject("cddColor.Items418"))),
((resources.GetObject("cddColor.Items419"))),
((resources.GetObject("cddColor.Items420"))),
((resources.GetObject("cddColor.Items421"))),
((resources.GetObject("cddColor.Items422"))),
((resources.GetObject("cddColor.Items423"))),
((resources.GetObject("cddColor.Items424"))),
((resources.GetObject("cddColor.Items425"))),
((resources.GetObject("cddColor.Items426"))),
((resources.GetObject("cddColor.Items427"))),
((resources.GetObject("cddColor.Items428"))),
((resources.GetObject("cddColor.Items429"))),
((resources.GetObject("cddColor.Items430"))),
((resources.GetObject("cddColor.Items431"))),
((resources.GetObject("cddColor.Items432"))),
((resources.GetObject("cddColor.Items433"))),
((resources.GetObject("cddColor.Items434"))),
((resources.GetObject("cddColor.Items435"))),
((resources.GetObject("cddColor.Items436"))),
((resources.GetObject("cddColor.Items437"))),
((resources.GetObject("cddColor.Items438"))),
((resources.GetObject("cddColor.Items439"))),
((resources.GetObject("cddColor.Items440"))),
((resources.GetObject("cddColor.Items441"))),
((resources.GetObject("cddColor.Items442"))),
((resources.GetObject("cddColor.Items443"))),
((resources.GetObject("cddColor.Items444"))),
((resources.GetObject("cddColor.Items445"))),
((resources.GetObject("cddColor.Items446"))),
((resources.GetObject("cddColor.Items447"))),
((resources.GetObject("cddColor.Items448"))),
((resources.GetObject("cddColor.Items449"))),
((resources.GetObject("cddColor.Items450"))),
((resources.GetObject("cddColor.Items451"))),
((resources.GetObject("cddColor.Items452"))),
((resources.GetObject("cddColor.Items453"))),
((resources.GetObject("cddColor.Items454"))),
((resources.GetObject("cddColor.Items455"))),
((resources.GetObject("cddColor.Items456"))),
((resources.GetObject("cddColor.Items457"))),
((resources.GetObject("cddColor.Items458"))),
((resources.GetObject("cddColor.Items459"))),
((resources.GetObject("cddColor.Items460"))),
((resources.GetObject("cddColor.Items461"))),
((resources.GetObject("cddColor.Items462"))),
((resources.GetObject("cddColor.Items463"))),
((resources.GetObject("cddColor.Items464"))),
((resources.GetObject("cddColor.Items465"))),
((resources.GetObject("cddColor.Items466"))),
((resources.GetObject("cddColor.Items467"))),
((resources.GetObject("cddColor.Items468"))),
((resources.GetObject("cddColor.Items469"))),
((resources.GetObject("cddColor.Items470"))),
((resources.GetObject("cddColor.Items471"))),
((resources.GetObject("cddColor.Items472"))),
((resources.GetObject("cddColor.Items473"))),
((resources.GetObject("cddColor.Items474"))),
((resources.GetObject("cddColor.Items475"))),
((resources.GetObject("cddColor.Items476"))),
((resources.GetObject("cddColor.Items477"))),
((resources.GetObject("cddColor.Items478"))),
((resources.GetObject("cddColor.Items479"))),
((resources.GetObject("cddColor.Items480"))),
((resources.GetObject("cddColor.Items481"))),
((resources.GetObject("cddColor.Items482"))),
((resources.GetObject("cddColor.Items483"))),
((resources.GetObject("cddColor.Items484"))),
((resources.GetObject("cddColor.Items485"))),
((resources.GetObject("cddColor.Items486"))),
((resources.GetObject("cddColor.Items487"))),
((resources.GetObject("cddColor.Items488"))),
((resources.GetObject("cddColor.Items489"))),
((resources.GetObject("cddColor.Items490"))),
((resources.GetObject("cddColor.Items491"))),
((resources.GetObject("cddColor.Items492"))),
((resources.GetObject("cddColor.Items493"))),
((resources.GetObject("cddColor.Items494"))),
((resources.GetObject("cddColor.Items495"))),
((resources.GetObject("cddColor.Items496"))),
((resources.GetObject("cddColor.Items497"))),
((resources.GetObject("cddColor.Items498"))),
((resources.GetObject("cddColor.Items499"))),
((resources.GetObject("cddColor.Items500"))),
((resources.GetObject("cddColor.Items501"))),
((resources.GetObject("cddColor.Items502"))),
((resources.GetObject("cddColor.Items503"))),
((resources.GetObject("cddColor.Items504"))),
((resources.GetObject("cddColor.Items505"))),
((resources.GetObject("cddColor.Items506"))),
((resources.GetObject("cddColor.Items507"))),
((resources.GetObject("cddColor.Items508"))),
((resources.GetObject("cddColor.Items509"))),
((resources.GetObject("cddColor.Items510"))),
((resources.GetObject("cddColor.Items511"))),
((resources.GetObject("cddColor.Items512"))),
((resources.GetObject("cddColor.Items513"))),
((resources.GetObject("cddColor.Items514"))),
((resources.GetObject("cddColor.Items515"))),
((resources.GetObject("cddColor.Items516"))),
((resources.GetObject("cddColor.Items517"))),
((resources.GetObject("cddColor.Items518"))),
((resources.GetObject("cddColor.Items519"))),
((resources.GetObject("cddColor.Items520"))),
((resources.GetObject("cddColor.Items521"))),
((resources.GetObject("cddColor.Items522"))),
((resources.GetObject("cddColor.Items523"))),
((resources.GetObject("cddColor.Items524"))),
((resources.GetObject("cddColor.Items525"))),
((resources.GetObject("cddColor.Items526"))),
((resources.GetObject("cddColor.Items527"))),
((resources.GetObject("cddColor.Items528"))),
((resources.GetObject("cddColor.Items529"))),
((resources.GetObject("cddColor.Items530"))),
((resources.GetObject("cddColor.Items531"))),
((resources.GetObject("cddColor.Items532"))),
((resources.GetObject("cddColor.Items533"))),
((resources.GetObject("cddColor.Items534"))),
((resources.GetObject("cddColor.Items535"))),
((resources.GetObject("cddColor.Items536"))),
((resources.GetObject("cddColor.Items537"))),
((resources.GetObject("cddColor.Items538"))),
((resources.GetObject("cddColor.Items539"))),
((resources.GetObject("cddColor.Items540"))),
((resources.GetObject("cddColor.Items541"))),
((resources.GetObject("cddColor.Items542"))),
((resources.GetObject("cddColor.Items543"))),
((resources.GetObject("cddColor.Items544"))),
((resources.GetObject("cddColor.Items545"))),
((resources.GetObject("cddColor.Items546"))),
((resources.GetObject("cddColor.Items547"))),
((resources.GetObject("cddColor.Items548"))),
((resources.GetObject("cddColor.Items549"))),
((resources.GetObject("cddColor.Items550"))),
((resources.GetObject("cddColor.Items551"))),
((resources.GetObject("cddColor.Items552"))),
((resources.GetObject("cddColor.Items553"))),
((resources.GetObject("cddColor.Items554"))),
((resources.GetObject("cddColor.Items555"))),
((resources.GetObject("cddColor.Items556"))),
((resources.GetObject("cddColor.Items557"))),
((resources.GetObject("cddColor.Items558"))),
((resources.GetObject("cddColor.Items559"))),
((resources.GetObject("cddColor.Items560"))),
((resources.GetObject("cddColor.Items561"))),
((resources.GetObject("cddColor.Items562"))),
((resources.GetObject("cddColor.Items563"))),
((resources.GetObject("cddColor.Items564"))),
((resources.GetObject("cddColor.Items565"))),
((resources.GetObject("cddColor.Items566"))),
((resources.GetObject("cddColor.Items567"))),
((resources.GetObject("cddColor.Items568"))),
((resources.GetObject("cddColor.Items569"))),
((resources.GetObject("cddColor.Items570"))),
((resources.GetObject("cddColor.Items571"))),
((resources.GetObject("cddColor.Items572"))),
((resources.GetObject("cddColor.Items573"))),
((resources.GetObject("cddColor.Items574"))),
((resources.GetObject("cddColor.Items575"))),
((resources.GetObject("cddColor.Items576"))),
((resources.GetObject("cddColor.Items577"))),
((resources.GetObject("cddColor.Items578"))),
((resources.GetObject("cddColor.Items579"))),
((resources.GetObject("cddColor.Items580"))),
((resources.GetObject("cddColor.Items581"))),
((resources.GetObject("cddColor.Items582"))),
((resources.GetObject("cddColor.Items583"))),
((resources.GetObject("cddColor.Items584"))),
((resources.GetObject("cddColor.Items585"))),
((resources.GetObject("cddColor.Items586"))),
((resources.GetObject("cddColor.Items587"))),
((resources.GetObject("cddColor.Items588"))),
((resources.GetObject("cddColor.Items589"))),
((resources.GetObject("cddColor.Items590"))),
((resources.GetObject("cddColor.Items591"))),
((resources.GetObject("cddColor.Items592"))),
((resources.GetObject("cddColor.Items593"))),
((resources.GetObject("cddColor.Items594"))),
((resources.GetObject("cddColor.Items595"))),
((resources.GetObject("cddColor.Items596"))),
((resources.GetObject("cddColor.Items597"))),
((resources.GetObject("cddColor.Items598"))),
((resources.GetObject("cddColor.Items599"))),
((resources.GetObject("cddColor.Items600"))),
((resources.GetObject("cddColor.Items601"))),
((resources.GetObject("cddColor.Items602"))),
((resources.GetObject("cddColor.Items603"))),
((resources.GetObject("cddColor.Items604"))),
((resources.GetObject("cddColor.Items605"))),
((resources.GetObject("cddColor.Items606"))),
((resources.GetObject("cddColor.Items607"))),
((resources.GetObject("cddColor.Items608"))),
((resources.GetObject("cddColor.Items609"))),
((resources.GetObject("cddColor.Items610"))),
((resources.GetObject("cddColor.Items611"))),
((resources.GetObject("cddColor.Items612"))),
((resources.GetObject("cddColor.Items613"))),
((resources.GetObject("cddColor.Items614"))),
((resources.GetObject("cddColor.Items615"))),
((resources.GetObject("cddColor.Items616"))),
((resources.GetObject("cddColor.Items617"))),
((resources.GetObject("cddColor.Items618"))),
((resources.GetObject("cddColor.Items619"))),
((resources.GetObject("cddColor.Items620"))),
((resources.GetObject("cddColor.Items621"))),
((resources.GetObject("cddColor.Items622"))),
((resources.GetObject("cddColor.Items623"))),
((resources.GetObject("cddColor.Items624"))),
((resources.GetObject("cddColor.Items625"))),
((resources.GetObject("cddColor.Items626"))),
((resources.GetObject("cddColor.Items627"))),
((resources.GetObject("cddColor.Items628"))),
((resources.GetObject("cddColor.Items629"))),
((resources.GetObject("cddColor.Items630"))),
((resources.GetObject("cddColor.Items631"))),
((resources.GetObject("cddColor.Items632"))),
((resources.GetObject("cddColor.Items633"))),
((resources.GetObject("cddColor.Items634"))),
((resources.GetObject("cddColor.Items635"))),
((resources.GetObject("cddColor.Items636"))),
((resources.GetObject("cddColor.Items637"))),
((resources.GetObject("cddColor.Items638"))),
((resources.GetObject("cddColor.Items639"))),
((resources.GetObject("cddColor.Items640"))),
((resources.GetObject("cddColor.Items641"))),
((resources.GetObject("cddColor.Items642"))),
((resources.GetObject("cddColor.Items643"))),
((resources.GetObject("cddColor.Items644"))),
((resources.GetObject("cddColor.Items645"))),
((resources.GetObject("cddColor.Items646"))),
((resources.GetObject("cddColor.Items647"))),
((resources.GetObject("cddColor.Items648"))),
((resources.GetObject("cddColor.Items649"))),
((resources.GetObject("cddColor.Items650"))),
((resources.GetObject("cddColor.Items651"))),
((resources.GetObject("cddColor.Items652"))),
((resources.GetObject("cddColor.Items653"))),
((resources.GetObject("cddColor.Items654"))),
((resources.GetObject("cddColor.Items655"))),
((resources.GetObject("cddColor.Items656"))),
((resources.GetObject("cddColor.Items657"))),
((resources.GetObject("cddColor.Items658"))),
((resources.GetObject("cddColor.Items659"))),
((resources.GetObject("cddColor.Items660"))),
((resources.GetObject("cddColor.Items661"))),
((resources.GetObject("cddColor.Items662"))),
((resources.GetObject("cddColor.Items663"))),
((resources.GetObject("cddColor.Items664"))),
((resources.GetObject("cddColor.Items665"))),
((resources.GetObject("cddColor.Items666"))),
((resources.GetObject("cddColor.Items667"))),
((resources.GetObject("cddColor.Items668"))),
((resources.GetObject("cddColor.Items669"))),
((resources.GetObject("cddColor.Items670"))),
((resources.GetObject("cddColor.Items671"))),
((resources.GetObject("cddColor.Items672"))),
((resources.GetObject("cddColor.Items673"))),
((resources.GetObject("cddColor.Items674"))),
((resources.GetObject("cddColor.Items675"))),
((resources.GetObject("cddColor.Items676"))),
((resources.GetObject("cddColor.Items677"))),
((resources.GetObject("cddColor.Items678"))),
((resources.GetObject("cddColor.Items679"))),
((resources.GetObject("cddColor.Items680"))),
((resources.GetObject("cddColor.Items681"))),
((resources.GetObject("cddColor.Items682"))),
((resources.GetObject("cddColor.Items683"))),
((resources.GetObject("cddColor.Items684"))),
((resources.GetObject("cddColor.Items685"))),
((resources.GetObject("cddColor.Items686"))),
((resources.GetObject("cddColor.Items687"))),
((resources.GetObject("cddColor.Items688"))),
((resources.GetObject("cddColor.Items689"))),
((resources.GetObject("cddColor.Items690"))),
((resources.GetObject("cddColor.Items691"))),
((resources.GetObject("cddColor.Items692"))),
((resources.GetObject("cddColor.Items693"))),
((resources.GetObject("cddColor.Items694"))),
((resources.GetObject("cddColor.Items695"))),
((resources.GetObject("cddColor.Items696")))});
this.cddColor.Name = "cddColor";
this.cddColor.Value = Color.Empty;
//
// cmdShowDialog
//
resources.ApplyResources(this.cmdShowDialog, "cmdShowDialog");
this.cmdShowDialog.Name = "cmdShowDialog";
this.cmdShowDialog.UseVisualStyleBackColor = true;
this.cmdShowDialog.Click += this.cmdShowDialog_Click;
//
// ColorBox
//
resources.ApplyResources(this, "$this");
this.Controls.Add(this.cmdShowDialog);
this.Controls.Add(this.cddColor);
this.Controls.Add(this.lblColor);
this.Name = "ColorBox";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the selected color
/// </summary>
[Category("Appearance"), Description("Gets or sets the selected color")]
public Color Value
{
get { return cddColor.Value; }
set { cddColor.Value = value; }
}
/// <summary>
/// Gets or sets the text for the label portion
/// </summary>
[Category("Appearance"), Description("Gets or sets the text for the label portion")]
public string LabelText
{
get { return lblColor.Text; }
set
{
lblColor.Text = value;
Reset();
}
}
/// <summary>
/// Gets or set the font for the label portion of the component.
/// </summary>
[Category("Appearance"), Description("Gets or set the font for the label portion of the component.")]
public new Font Font
{
get { return lblColor.Font; }
set
{
lblColor.Font = value;
Reset();
}
}
#endregion
#region Protected Methods
/// <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);
}
#endregion
private void cmdShowDialog_Click(object sender, EventArgs e)
{
ColorDialog cdlg = new ColorDialog();
if (cdlg.ShowDialog(ParentForm) != DialogResult.OK) return;
foreach (object item in cddColor.Items)
{
if (item is KnownColor)
{
KnownColor kn = (KnownColor)item;
if (Color.FromKnownColor(kn) == cdlg.Color)
{
cddColor.SelectedItem = kn;
return;
}
}
}
if (cddColor.Items.Contains(cdlg.Color))
{
cddColor.SelectedItem = cdlg.Color;
return;
}
else
{
cddColor.Items.Add(cdlg.Color);
cddColor.SelectedIndex = cddColor.Items.Count - 1;
}
}
/// <summary>
/// Changes the starting location of the color drop down based on the current text.
/// </summary>
private void Reset()
{
cddColor.Left = lblColor.Width + 5;
cddColor.Width = cmdShowDialog.Left - cddColor.Left - 10;
}
}
}
| |
//
// System.Data.SybaseTypes.SybaseSingle
//
// Author:
// Tim Coleman <tim@timcoleman.com>
//
// (C) Copyright 2002 Tim Coleman
//
//
// 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 Mono.Data.SybaseClient;
using System;
using System.Data.SqlTypes;
using System.Globalization;
namespace Mono.Data.SybaseTypes {
public struct SybaseSingle : INullable, IComparable
{
#region Fields
float value;
private bool notNull;
public static readonly SybaseSingle MaxValue = new SybaseSingle (3.40282346638528859e38);
public static readonly SybaseSingle MinValue = new SybaseSingle (-3.40282346638528859e38);
public static readonly SybaseSingle Null;
public static readonly SybaseSingle Zero = new SybaseSingle (0);
#endregion
#region Constructors
public SybaseSingle (double value)
{
this.value = (float)value;
notNull = true;
}
public SybaseSingle (float value)
{
this.value = value;
notNull = true;
}
#endregion
#region Properties
public bool IsNull {
get { return !notNull; }
}
public float Value {
get {
if (this.IsNull)
throw new SybaseNullValueException ();
else
return value;
}
}
#endregion
#region Methods
public static SybaseSingle Add (SybaseSingle x, SybaseSingle y)
{
return (x + y);
}
public int CompareTo (object value)
{
if (value == null)
return 1;
else if (!(value is SybaseSingle))
throw new ArgumentException (Locale.GetText ("Value is not a System.Data.SybaseTypes.SybaseSingle"));
else if (((SybaseSingle)value).IsNull)
return 1;
else
return this.value.CompareTo (((SybaseSingle)value).Value);
}
public static SybaseSingle Divide (SybaseSingle x, SybaseSingle y)
{
return (x / y);
}
public override bool Equals (object value)
{
if (!(value is SybaseSingle))
return false;
else
return (bool) (this == (SybaseSingle)value);
}
public static SybaseBoolean Equals (SybaseSingle x, SybaseSingle y)
{
return (x == y);
}
public override int GetHashCode ()
{
long LongValue = (long) value;
return (int)(LongValue ^ (LongValue >> 32));
}
public static SybaseBoolean GreaterThan (SybaseSingle x, SybaseSingle y)
{
return (x > y);
}
public static SybaseBoolean GreaterThanOrEqual (SybaseSingle x, SybaseSingle y)
{
return (x >= y);
}
public static SybaseBoolean LessThan (SybaseSingle x, SybaseSingle y)
{
return (x < y);
}
public static SybaseBoolean LessThanOrEqual (SybaseSingle x, SybaseSingle y)
{
return (x <= y);
}
public static SybaseSingle Multiply (SybaseSingle x, SybaseSingle y)
{
return (x * y);
}
public static SybaseBoolean NotEquals (SybaseSingle x, SybaseSingle y)
{
return (x != y);
}
public static SybaseSingle Parse (string s)
{
return new SybaseSingle (Single.Parse (s));
}
public static SybaseSingle Subtract (SybaseSingle x, SybaseSingle y)
{
return (x - y);
}
public SybaseBoolean ToSybaseBoolean ()
{
return ((SybaseBoolean)this);
}
public SybaseByte ToSybaseByte ()
{
return ((SybaseByte)this);
}
public SybaseDecimal ToSybaseDecimal ()
{
return ((SybaseDecimal)this);
}
public SybaseDouble ToSybaseDouble ()
{
return ((SybaseDouble)this);
}
public SybaseInt16 ToSybaseInt16 ()
{
return ((SybaseInt16)this);
}
public SybaseInt32 ToSybaseInt32 ()
{
return ((SybaseInt32)this);
}
public SybaseInt64 ToSybaseInt64 ()
{
return ((SybaseInt64)this);
}
public SybaseMoney ToSybaseMoney ()
{
return ((SybaseMoney)this);
}
public SybaseString ToSybaseString ()
{
return ((SybaseString)this);
}
public override string ToString ()
{
return value.ToString ();
}
public static SybaseSingle operator + (SybaseSingle x, SybaseSingle y)
{
return new SybaseSingle (x.Value + y.Value);
}
public static SybaseSingle operator / (SybaseSingle x, SybaseSingle y)
{
return new SybaseSingle (x.Value / y.Value);
}
public static SybaseBoolean operator == (SybaseSingle x, SybaseSingle y)
{
if (x.IsNull || y .IsNull) return SybaseBoolean.Null;
return new SybaseBoolean (x.Value == y.Value);
}
public static SybaseBoolean operator > (SybaseSingle x, SybaseSingle y)
{
if (x.IsNull || y .IsNull) return SybaseBoolean.Null;
return new SybaseBoolean (x.Value > y.Value);
}
public static SybaseBoolean operator >= (SybaseSingle x, SybaseSingle y)
{
if (x.IsNull || y .IsNull) return SybaseBoolean.Null;
return new SybaseBoolean (x.Value >= y.Value);
}
public static SybaseBoolean operator != (SybaseSingle x, SybaseSingle y)
{
if (x.IsNull || y .IsNull) return SybaseBoolean.Null;
return new SybaseBoolean (!(x.Value == y.Value));
}
public static SybaseBoolean operator < (SybaseSingle x, SybaseSingle y)
{
if (x.IsNull || y .IsNull) return SybaseBoolean.Null;
return new SybaseBoolean (x.Value < y.Value);
}
public static SybaseBoolean operator <= (SybaseSingle x, SybaseSingle y)
{
if (x.IsNull || y .IsNull) return SybaseBoolean.Null;
return new SybaseBoolean (x.Value <= y.Value);
}
public static SybaseSingle operator * (SybaseSingle x, SybaseSingle y)
{
return new SybaseSingle (x.Value * y.Value);
}
public static SybaseSingle operator - (SybaseSingle x, SybaseSingle y)
{
return new SybaseSingle (x.Value - y.Value);
}
public static SybaseSingle operator - (SybaseSingle n)
{
return new SybaseSingle (-(n.Value));
}
public static explicit operator SybaseSingle (SybaseBoolean x)
{
return new SybaseSingle((float)x.ByteValue);
}
public static explicit operator SybaseSingle (SybaseDouble x)
{
return new SybaseSingle((float)x.Value);
}
public static explicit operator float (SybaseSingle x)
{
return x.Value;
}
public static explicit operator SybaseSingle (SybaseString x)
{
return SybaseSingle.Parse (x.Value);
}
public static implicit operator SybaseSingle (float x)
{
return new SybaseSingle (x);
}
public static implicit operator SybaseSingle (SybaseByte x)
{
if (x.IsNull)
return Null;
else
return new SybaseSingle((float)x.Value);
}
public static implicit operator SybaseSingle (SybaseDecimal x)
{
if (x.IsNull)
return Null;
else
return new SybaseSingle((float)x.Value);
}
public static implicit operator SybaseSingle (SybaseInt16 x)
{
if (x.IsNull)
return Null;
else
return new SybaseSingle((float)x.Value);
}
public static implicit operator SybaseSingle (SybaseInt32 x)
{
if (x.IsNull)
return Null;
else
return new SybaseSingle((float)x.Value);
}
public static implicit operator SybaseSingle (SybaseInt64 x)
{
if (x.IsNull)
return Null;
else
return new SybaseSingle((float)x.Value);
}
public static implicit operator SybaseSingle (SybaseMoney x)
{
if (x.IsNull)
return Null;
else
return new SybaseSingle((float)x.Value);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using Xamarin.Forms.Internals;
namespace Xamarin.Forms
{
[ContentProperty("Children")]
public abstract class Layout<T> : Layout, IViewContainer<T> where T : View
{
readonly ElementCollection<T> _children;
protected Layout()
{
_children = new ElementCollection<T>(InternalChildren);
}
public IList<T> Children
{
get { return _children; }
}
protected virtual void OnAdded(T view)
{
}
protected override void OnChildAdded(Element child)
{
base.OnChildAdded(child);
var typedChild = child as T;
if (typedChild != null)
OnAdded(typedChild);
}
protected override void OnChildRemoved(Element child)
{
base.OnChildRemoved(child);
var typedChild = child as T;
if (typedChild != null)
OnRemoved(typedChild);
}
protected virtual void OnRemoved(T view)
{
}
}
public abstract class Layout : View, ILayout, ILayoutController
{
public static readonly BindableProperty IsClippedToBoundsProperty = BindableProperty.Create("IsClippedToBounds", typeof(bool), typeof(Layout), false);
public static readonly BindableProperty PaddingProperty = BindableProperty.Create("Padding", typeof(Thickness), typeof(Layout), default(Thickness), propertyChanged: (bindable, old, newValue) =>
{
var layout = (Layout)bindable;
layout.UpdateChildrenLayout();
});
static IList<KeyValuePair<Layout, int>> s_resolutionList = new List<KeyValuePair<Layout, int>>();
static bool s_relayoutInProgress;
bool _allocatedFlag;
bool _hasDoneLayout;
Size _lastLayoutSize = new Size(-1, -1);
ReadOnlyCollection<Element> _logicalChildren;
protected Layout()
{
InternalChildren.CollectionChanged += InternalChildrenOnCollectionChanged;
}
public bool IsClippedToBounds
{
get { return (bool)GetValue(IsClippedToBoundsProperty); }
set { SetValue(IsClippedToBoundsProperty, value); }
}
public Thickness Padding
{
get { return (Thickness)GetValue(PaddingProperty); }
set { SetValue(PaddingProperty, value); }
}
internal ObservableCollection<Element> InternalChildren { get; } = new ObservableCollection<Element>();
internal override ReadOnlyCollection<Element> LogicalChildren
{
get { return _logicalChildren ?? (_logicalChildren = new ReadOnlyCollection<Element>(InternalChildren)); }
}
public event EventHandler LayoutChanged;
IReadOnlyList<Element> ILayoutController.Children
{
get { return InternalChildren; }
}
public void ForceLayout()
{
SizeAllocated(Width, Height);
}
[Obsolete("Use Measure")]
public sealed override SizeRequest GetSizeRequest(double widthConstraint, double heightConstraint)
{
SizeRequest size = base.GetSizeRequest(widthConstraint - Padding.HorizontalThickness, heightConstraint - Padding.VerticalThickness);
return new SizeRequest(new Size(size.Request.Width + Padding.HorizontalThickness, size.Request.Height + Padding.VerticalThickness),
new Size(size.Minimum.Width + Padding.HorizontalThickness, size.Minimum.Height + Padding.VerticalThickness));
}
public static void LayoutChildIntoBoundingRegion(VisualElement child, Rectangle region)
{
var view = child as View;
if (view == null)
{
child.Layout(region);
return;
}
LayoutOptions horizontalOptions = view.HorizontalOptions;
if (horizontalOptions.Alignment != LayoutAlignment.Fill)
{
SizeRequest request = child.Measure(region.Width, region.Height, MeasureFlags.IncludeMargins);
double diff = Math.Max(0, region.Width - request.Request.Width);
region.X += (int)(diff * horizontalOptions.Alignment.ToDouble());
region.Width -= diff;
}
LayoutOptions verticalOptions = view.VerticalOptions;
if (verticalOptions.Alignment != LayoutAlignment.Fill)
{
SizeRequest request = child.Measure(region.Width, region.Height, MeasureFlags.IncludeMargins);
double diff = Math.Max(0, region.Height - request.Request.Height);
region.Y += (int)(diff * verticalOptions.Alignment.ToDouble());
region.Height -= diff;
}
Thickness margin = view.Margin;
region.X += margin.Left;
region.Width -= margin.HorizontalThickness;
region.Y += margin.Top;
region.Height -= margin.VerticalThickness;
child.Layout(region);
}
public void LowerChild(View view)
{
if (!InternalChildren.Contains(view) || InternalChildren.First() == view)
return;
InternalChildren.Move(InternalChildren.IndexOf(view), 0);
OnChildrenReordered();
}
public void RaiseChild(View view)
{
if (!InternalChildren.Contains(view) || InternalChildren.Last() == view)
return;
InternalChildren.Move(InternalChildren.IndexOf(view), InternalChildren.Count - 1);
OnChildrenReordered();
}
protected virtual void InvalidateLayout()
{
_hasDoneLayout = false;
InvalidateMeasureInternal(InvalidationTrigger.MeasureChanged);
if (!_hasDoneLayout)
ForceLayout();
}
protected abstract void LayoutChildren(double x, double y, double width, double height);
protected void OnChildMeasureInvalidated(object sender, EventArgs e)
{
InvalidationTrigger trigger = (e as InvalidationEventArgs)?.Trigger ?? InvalidationTrigger.Undefined;
OnChildMeasureInvalidated((VisualElement)sender, trigger);
OnChildMeasureInvalidated();
}
protected virtual void OnChildMeasureInvalidated()
{
}
protected override void OnSizeAllocated(double width, double height)
{
_allocatedFlag = true;
base.OnSizeAllocated(width, height);
UpdateChildrenLayout();
}
protected virtual bool ShouldInvalidateOnChildAdded(View child)
{
return true;
}
protected virtual bool ShouldInvalidateOnChildRemoved(View child)
{
return true;
}
protected void UpdateChildrenLayout()
{
_hasDoneLayout = true;
if (!ShouldLayoutChildren())
return;
var oldBounds = new Rectangle[LogicalChildren.Count];
for (var index = 0; index < oldBounds.Length; index++)
{
var c = (VisualElement)LogicalChildren[index];
oldBounds[index] = c.Bounds;
}
double width = Width;
double height = Height;
double x = Padding.Left;
double y = Padding.Top;
double w = Math.Max(0, width - Padding.HorizontalThickness);
double h = Math.Max(0, height - Padding.VerticalThickness);
LayoutChildren(x, y, w, h);
for (var i = 0; i < oldBounds.Length; i++)
{
Rectangle oldBound = oldBounds[i];
Rectangle newBound = ((VisualElement)LogicalChildren[i]).Bounds;
if (oldBound != newBound)
{
EventHandler handler = LayoutChanged;
if (handler != null)
handler(this, EventArgs.Empty);
return;
}
}
_lastLayoutSize = new Size(width, height);
}
internal static void LayoutChildIntoBoundingRegion(View child, Rectangle region, SizeRequest childSizeRequest)
{
if (region.Size != childSizeRequest.Request)
{
bool canUseAlreadyDoneRequest = region.Width >= childSizeRequest.Request.Width && region.Height >= childSizeRequest.Request.Height;
if (child.HorizontalOptions.Alignment != LayoutAlignment.Fill)
{
SizeRequest request = canUseAlreadyDoneRequest ? childSizeRequest : child.Measure(region.Width, region.Height, MeasureFlags.IncludeMargins);
double diff = Math.Max(0, region.Width - request.Request.Width);
region.X += (int)(diff * child.HorizontalOptions.Alignment.ToDouble());
region.Width -= diff;
}
if (child.VerticalOptions.Alignment != LayoutAlignment.Fill)
{
SizeRequest request = canUseAlreadyDoneRequest ? childSizeRequest : child.Measure(region.Width, region.Height, MeasureFlags.IncludeMargins);
double diff = Math.Max(0, region.Height - request.Request.Height);
region.Y += (int)(diff * child.VerticalOptions.Alignment.ToDouble());
region.Height -= diff;
}
}
Thickness margin = child.Margin;
region.X += margin.Left;
region.Width -= margin.HorizontalThickness;
region.Y += margin.Top;
region.Height -= margin.VerticalThickness;
child.Layout(region);
}
internal virtual void OnChildMeasureInvalidated(VisualElement child, InvalidationTrigger trigger)
{
ReadOnlyCollection<Element> children = LogicalChildren;
int count = children.Count;
for (var index = 0; index < count; index++)
{
var v = LogicalChildren[index] as VisualElement;
if (v != null && v.IsVisible && (!v.IsPlatformEnabled || !v.IsNativeStateConsistent))
return;
}
var view = child as View;
if (view != null)
{
// we can ignore the request if we are either fully constrained or when the size request changes and we were already fully constrainted
if ((trigger == InvalidationTrigger.MeasureChanged && view.Constraint == LayoutConstraint.Fixed) ||
(trigger == InvalidationTrigger.SizeRequestChanged && view.ComputedConstraint == LayoutConstraint.Fixed))
{
return;
}
if (trigger == InvalidationTrigger.HorizontalOptionsChanged || trigger == InvalidationTrigger.VerticalOptionsChanged)
{
ComputeConstraintForView(view);
}
}
_allocatedFlag = false;
if (trigger == InvalidationTrigger.RendererReady)
{
InvalidateMeasureInternal(InvalidationTrigger.RendererReady);
}
else
{
InvalidateMeasureInternal(InvalidationTrigger.MeasureChanged);
}
s_resolutionList.Add(new KeyValuePair<Layout, int>(this, GetElementDepth(this)));
if (!s_relayoutInProgress)
{
s_relayoutInProgress = true;
Device.BeginInvokeOnMainThread(() =>
{
// if thread safety mattered we would need to lock this and compareexchange above
IList<KeyValuePair<Layout, int>> copy = s_resolutionList;
s_resolutionList = new List<KeyValuePair<Layout, int>>();
s_relayoutInProgress = false;
foreach (KeyValuePair<Layout, int> kvp in copy.OrderBy(kvp => kvp.Value))
{
Layout layout = kvp.Key;
double width = layout.Width, height = layout.Height;
if (!layout._allocatedFlag && width >= 0 && height >= 0)
{
layout.SizeAllocated(width, height);
}
}
});
}
}
internal override void OnIsVisibleChanged(bool oldValue, bool newValue)
{
base.OnIsVisibleChanged(oldValue, newValue);
if (newValue)
{
if (_lastLayoutSize != new Size(Width, Height))
{
UpdateChildrenLayout();
}
}
}
static int GetElementDepth(Element view)
{
var result = 0;
while (view.Parent != null)
{
result++;
view = view.Parent;
}
return result;
}
void InternalChildrenOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Move)
{
return;
}
if (e.OldItems != null)
{
foreach (object item in e.OldItems)
{
var v = item as View;
if (v == null)
continue;
OnInternalRemoved(v);
}
}
if (e.NewItems != null)
{
foreach (object item in e.NewItems)
{
var v = item as View;
if (v == null)
continue;
if (item == this)
throw new InvalidOperationException("Can not add self to own child collection.");
OnInternalAdded(v);
}
}
}
void OnInternalAdded(View view)
{
var parent = view.Parent as Layout;
parent?.InternalChildren.Remove(view);
OnChildAdded(view);
if (ShouldInvalidateOnChildAdded(view))
InvalidateLayout();
view.MeasureInvalidated += OnChildMeasureInvalidated;
}
void OnInternalRemoved(View view)
{
view.MeasureInvalidated -= OnChildMeasureInvalidated;
OnChildRemoved(view);
if (ShouldInvalidateOnChildRemoved(view))
InvalidateLayout();
}
bool ShouldLayoutChildren()
{
if (!LogicalChildren.Any() || Width <= 0 || Height <= 0 || !IsVisible || !IsNativeStateConsistent || DisableLayout)
return false;
foreach (Element element in VisibleDescendants())
{
var visual = element as VisualElement;
if (visual == null || !visual.IsVisible)
continue;
if (!visual.IsPlatformEnabled || !visual.IsNativeStateConsistent)
{
return false;
}
}
return true;
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="ActorMaterializer.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Runtime.Serialization;
using Akka.Actor;
using Akka.Configuration;
using Akka.Dispatch;
using Akka.Event;
using Akka.Pattern;
using Akka.Streams.Dsl;
using Akka.Streams.Dsl.Internal;
using Akka.Streams.Implementation;
using Akka.Streams.Stage;
using Akka.Streams.Supervision;
using Akka.Util;
using Reactive.Streams;
using Decider = Akka.Streams.Supervision.Decider;
namespace Akka.Streams
{
/// <summary>
/// A ActorMaterializer takes the list of transformations comprising a
/// <see cref="IFlow{TOut,TMat}"/> and materializes them in the form of
/// <see cref="IProcessor{T1,T2}"/> instances. How transformation
/// steps are split up into asynchronous regions is implementation
/// dependent.
/// </summary>
public abstract class ActorMaterializer : IMaterializer, IMaterializerLoggingProvider, IDisposable
{
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public static Config DefaultConfig()
=> ConfigurationFactory.FromResource<ActorMaterializer>("Akka.Streams.reference.conf");
#region static
/// <summary>
/// <para>
/// Creates a ActorMaterializer which will execute every step of a transformation
/// pipeline within its own <see cref="ActorBase"/>. The required <see cref="IActorRefFactory"/>
/// (which can be either an <see cref="ActorSystem"/> or an <see cref="IActorContext"/>)
/// will be used to create one actor that in turn creates actors for the transformation steps.
/// </para>
/// <para>
/// The materializer's <see cref="ActorMaterializerSettings"/> will be obtained from the
/// configuration of the <paramref name="context"/>'s underlying <see cref="ActorSystem"/>.
/// </para>
/// <para>
/// The <paramref name="namePrefix"/> is used as the first part of the names of the actors running
/// the processing steps. The default <paramref name="namePrefix"/> is "flow". The actor names are built up of
/// `namePrefix-flowNumber-flowStepNumber-stepName`.
/// </para>
/// </summary>
/// <param name="context">TBD</param>
/// <param name="settings">TBD</param>
/// <param name="namePrefix">TBD</param>
/// <exception cref="ArgumentException">
/// This exception is thrown when the specified <paramref name="context"/> is not of type <see cref="ActorSystem"/> or <see cref="IActorContext"/>.
/// </exception>
/// <exception cref="ArgumentNullException">
/// This exception is thrown when the specified <paramref name="context"/> is undefined.
/// </exception>
/// <returns>TBD</returns>
public static ActorMaterializer Create(IActorRefFactory context, ActorMaterializerSettings settings = null, string namePrefix = null)
{
var haveShutDown = new AtomicBoolean();
var system = ActorSystemOf(context);
system.Settings.InjectTopLevelFallback(DefaultConfig());
settings = settings ?? ActorMaterializerSettings.Create(system);
return new ActorMaterializerImpl(
system: system,
settings: settings,
dispatchers: system.Dispatchers,
supervisor: context.ActorOf(StreamSupervisor.Props(settings, haveShutDown).WithDispatcher(settings.Dispatcher), StreamSupervisor.NextName()),
haveShutDown: haveShutDown,
flowNames: EnumerableActorName.Create(namePrefix ?? "Flow"));
}
private static ActorSystem ActorSystemOf(IActorRefFactory context)
{
if (context is ExtendedActorSystem)
return (ActorSystem)context;
if (context is IActorContext)
return ((IActorContext)context).System;
if (context == null)
throw new ArgumentNullException(nameof(context), "IActorRefFactory must be defined");
throw new ArgumentException($"ActorRefFactory context must be a ActorSystem or ActorContext, got [{context.GetType()}]");
}
#endregion
/// <summary>
/// TBD
/// </summary>
public abstract ActorMaterializerSettings Settings { get; }
/// <summary>
/// Indicates if the materializer has been shut down.
/// </summary>
public abstract bool IsShutdown { get; }
/// <summary>
/// TBD
/// </summary>
public abstract MessageDispatcher ExecutionContext { get; }
/// <summary>
/// TBD
/// </summary>
public abstract ActorSystem System { get; }
/// <summary>
/// TBD
/// </summary>
public abstract ILoggingAdapter Logger { get; }
/// <summary>
/// TBD
/// </summary>
public abstract IActorRef Supervisor { get; }
/// <summary>
/// TBD
/// </summary>
/// <param name="namePrefix">TBD</param>
/// <returns>TBD</returns>
public abstract IMaterializer WithNamePrefix(string namePrefix);
/// <inheritdoc />
public abstract TMat Materialize<TMat>(IGraph<ClosedShape, TMat> runnable);
/// <inheritdoc />
public abstract TMat Materialize<TMat>(IGraph<ClosedShape, TMat> runnable, Attributes initialAttributes);
/// <summary>
/// TBD
/// </summary>
/// <param name="delay">TBD</param>
/// <param name="action">TBD</param>
/// <returns>TBD</returns>
public abstract ICancelable ScheduleOnce(TimeSpan delay, Action action);
/// <summary>
/// TBD
/// </summary>
/// <param name="initialDelay">TBD</param>
/// <param name="interval">TBD</param>
/// <param name="action">TBD</param>
/// <returns>TBD</returns>
public abstract ICancelable ScheduleRepeatedly(TimeSpan initialDelay, TimeSpan interval, Action action);
/// <summary>
/// TBD
/// </summary>
/// <param name="attributes">TBD</param>
/// <returns>TBD</returns>
public abstract ActorMaterializerSettings EffectiveSettings(Attributes attributes);
/// <summary>
/// Shuts down this materializer and all the stages that have been materialized through this materializer. After
/// having shut down, this materializer cannot be used again. Any attempt to materialize stages after having
/// shut down will result in an <see cref="IllegalStateException"/> being thrown at materialization time.
/// </summary>
public abstract void Shutdown();
/// <summary>
/// TBD
/// </summary>
/// <param name="context">TBD</param>
/// <param name="props">TBD</param>
/// <returns>TBD</returns>
public abstract IActorRef ActorOf(MaterializationContext context, Props props);
/// <summary>
/// Creates a new logging adapter.
/// </summary>
/// <param name="logSource">The source that produces the log events.</param>
/// <returns>The newly created logging adapter.</returns>
public abstract ILoggingAdapter MakeLogger(object logSource);
/// <inheritdoc/>
public void Dispose() => Shutdown();
}
/// <summary>
/// INTERNAL API
/// </summary>
internal static class ActorMaterializerHelper
{
/// <summary>
/// TBD
/// </summary>
/// <param name="materializer">TBD</param>
/// <exception cref="ArgumentException">
/// This exception is thrown when the specified <paramref name="materializer"/> is not of type <see cref="ActorMaterializer"/>.
/// </exception>
/// <returns>TBD</returns>
internal static ActorMaterializer Downcast(IMaterializer materializer)
{
//FIXME this method is going to cause trouble for other Materializer implementations
var downcast = materializer as ActorMaterializer;
if (downcast != null)
return downcast;
throw new ArgumentException($"Expected {typeof(ActorMaterializer)} but got {materializer.GetType()}");
}
}
/// <summary>
/// This exception signals that an actor implementing a Reactive Streams Subscriber, Publisher or Processor
/// has been terminated without being notified by an onError, onComplete or cancel signal. This usually happens
/// when an ActorSystem is shut down while stream processing actors are still running.
/// </summary>
[Serializable]
public class AbruptTerminationException : Exception
{
/// <summary>
/// The actor that was terminated without notification.
/// </summary>
public readonly IActorRef Actor;
/// <summary>
/// Initializes a new instance of the <see cref="AbruptTerminationException" /> class.
/// </summary>
/// <param name="actor">The actor that was terminated.</param>
public AbruptTerminationException(IActorRef actor)
: base($"Processor actor [{actor}] terminated abruptly")
{
Actor = actor;
}
#if SERIALIZATION
/// <summary>
/// Initializes a new instance of the <see cref="AbruptTerminationException" /> class.
/// </summary>
/// <param name="info">The <see cref="SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="StreamingContext"/> that contains contextual information about the source or destination.</param>
protected AbruptTerminationException(SerializationInfo info, StreamingContext context) : base(info, context)
{
Actor = (IActorRef)info.GetValue("Actor", typeof(IActorRef));
}
#endif
}
/// <summary>
/// This exception or subtypes thereof should be used to signal materialization failures.
/// </summary>
public class MaterializationException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="MaterializationException"/> class.
/// </summary>
/// <param name="message">The message that describes the error.</param>
/// <param name="innerException">The exception that is the cause of the current exception.</param>
public MaterializationException(string message, Exception innerException) : base(message, innerException) { }
#if SERIALIZATION
/// <summary>
/// Initializes a new instance of the <see cref="MaterializationException"/> class.
/// </summary>
/// <param name="info">The <see cref="SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="StreamingContext" /> that contains contextual information about the source or destination.</param>
protected MaterializationException(SerializationInfo info, StreamingContext context) : base(info, context) { }
#endif
}
/// <summary>
/// Signal that the stage was abruptly terminated, usually seen as a call to <see cref="GraphStageLogic.PostStop"/> without
/// any of the handler callbacks seeing completion or failure from upstream or cancellation from downstream. This can happen when
/// the actor running the graph is killed, which happens when the materializer or actor system is terminated.
/// </summary>
public sealed class AbruptStageTerminationException : Exception
{
public AbruptStageTerminationException(GraphStageLogic logic)
: base($"GraphStage {logic} terminated abruptly, caused by for example materializer or actor system termination.")
{
}
}
/// <summary>
/// This class describes the configurable properties of the <see cref="ActorMaterializer"/>.
/// Please refer to the withX methods for descriptions of the individual settings.
/// </summary>
public sealed class ActorMaterializerSettings
{
/// <summary>
/// TBD
/// </summary>
/// <param name="system">TBD</param>
/// <returns>TBD</returns>
public static ActorMaterializerSettings Create(ActorSystem system)
{
var config = system.Settings.Config.GetConfig("akka.stream.materializer");
return Create(config ?? Config.Empty);
}
private static ActorMaterializerSettings Create(Config config)
{
return new ActorMaterializerSettings(
initialInputBufferSize: config.GetInt("initial-input-buffer-size", 4),
maxInputBufferSize: config.GetInt("max-input-buffer-size", 16),
dispatcher: config.GetString("dispatcher", string.Empty),
supervisionDecider: Deciders.StoppingDecider,
subscriptionTimeoutSettings: StreamSubscriptionTimeoutSettings.Create(config),
isDebugLogging: config.GetBoolean("debug-logging"),
outputBurstLimit: config.GetInt("output-burst-limit", 1000),
isFuzzingMode: config.GetBoolean("debug.fuzzing-mode"),
isAutoFusing: config.GetBoolean("auto-fusing", true),
maxFixedBufferSize: config.GetInt("max-fixed-buffer-size", 1000000000),
syncProcessingLimit: config.GetInt("sync-processing-limit", 1000));
}
private const int DefaultlMaxFixedbufferSize = 1000;
/// <summary>
/// TBD
/// </summary>
public readonly int InitialInputBufferSize;
/// <summary>
/// TBD
/// </summary>
public readonly int MaxInputBufferSize;
/// <summary>
/// TBD
/// </summary>
public readonly string Dispatcher;
/// <summary>
/// TBD
/// </summary>
public readonly Decider SupervisionDecider;
/// <summary>
/// TBD
/// </summary>
public readonly StreamSubscriptionTimeoutSettings SubscriptionTimeoutSettings;
/// <summary>
/// TBD
/// </summary>
public readonly bool IsDebugLogging;
/// <summary>
/// TBD
/// </summary>
public readonly int OutputBurstLimit;
/// <summary>
/// TBD
/// </summary>
public readonly bool IsFuzzingMode;
/// <summary>
/// TBD
/// </summary>
public readonly bool IsAutoFusing;
/// <summary>
/// TBD
/// </summary>
public readonly int MaxFixedBufferSize;
/// <summary>
/// TBD
/// </summary>
public readonly int SyncProcessingLimit;
/// <summary>
/// TBD
/// </summary>
/// <param name="initialInputBufferSize">TBD</param>
/// <param name="maxInputBufferSize">TBD</param>
/// <param name="dispatcher">TBD</param>
/// <param name="supervisionDecider">TBD</param>
/// <param name="subscriptionTimeoutSettings">TBD</param>
/// <param name="isDebugLogging">TBD</param>
/// <param name="outputBurstLimit">TBD</param>
/// <param name="isFuzzingMode">TBD</param>
/// <param name="isAutoFusing">TBD</param>
/// <param name="maxFixedBufferSize">TBD</param>
/// <param name="syncProcessingLimit">TBD</param>
public ActorMaterializerSettings(int initialInputBufferSize, int maxInputBufferSize, string dispatcher, Decider supervisionDecider, StreamSubscriptionTimeoutSettings subscriptionTimeoutSettings, bool isDebugLogging, int outputBurstLimit, bool isFuzzingMode, bool isAutoFusing, int maxFixedBufferSize, int syncProcessingLimit = DefaultlMaxFixedbufferSize)
{
InitialInputBufferSize = initialInputBufferSize;
MaxInputBufferSize = maxInputBufferSize;
Dispatcher = dispatcher;
SupervisionDecider = supervisionDecider;
SubscriptionTimeoutSettings = subscriptionTimeoutSettings;
IsDebugLogging = isDebugLogging;
OutputBurstLimit = outputBurstLimit;
IsFuzzingMode = isFuzzingMode;
IsAutoFusing = isAutoFusing;
MaxFixedBufferSize = maxFixedBufferSize;
SyncProcessingLimit = syncProcessingLimit;
}
/// <summary>
/// TBD
/// </summary>
/// <param name="initialSize">TBD</param>
/// <param name="maxSize">TBD</param>
/// <returns>TBD</returns>
public ActorMaterializerSettings WithInputBuffer(int initialSize, int maxSize)
{
return new ActorMaterializerSettings(initialSize, maxSize, Dispatcher, SupervisionDecider, SubscriptionTimeoutSettings, IsDebugLogging, OutputBurstLimit, IsFuzzingMode, IsAutoFusing, MaxFixedBufferSize, SyncProcessingLimit);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="dispatcher">TBD</param>
/// <returns>TBD</returns>
public ActorMaterializerSettings WithDispatcher(string dispatcher)
{
return new ActorMaterializerSettings(InitialInputBufferSize, MaxInputBufferSize, dispatcher, SupervisionDecider, SubscriptionTimeoutSettings, IsDebugLogging, OutputBurstLimit, IsFuzzingMode, IsAutoFusing, MaxFixedBufferSize, SyncProcessingLimit);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="decider">TBD</param>
/// <returns>TBD</returns>
public ActorMaterializerSettings WithSupervisionStrategy(Decider decider)
{
return new ActorMaterializerSettings(InitialInputBufferSize, MaxInputBufferSize, Dispatcher, decider, SubscriptionTimeoutSettings, IsDebugLogging, OutputBurstLimit, IsFuzzingMode, IsAutoFusing, MaxFixedBufferSize, SyncProcessingLimit);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="isEnabled">TBD</param>
/// <returns>TBD</returns>
public ActorMaterializerSettings WithDebugLogging(bool isEnabled)
{
return new ActorMaterializerSettings(InitialInputBufferSize, MaxInputBufferSize, Dispatcher, SupervisionDecider, SubscriptionTimeoutSettings, isEnabled, OutputBurstLimit, IsFuzzingMode, IsAutoFusing, MaxFixedBufferSize, SyncProcessingLimit);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="isFuzzingMode">TBD</param>
/// <returns>TBD</returns>
public ActorMaterializerSettings WithFuzzingMode(bool isFuzzingMode)
{
return new ActorMaterializerSettings(InitialInputBufferSize, MaxInputBufferSize, Dispatcher, SupervisionDecider, SubscriptionTimeoutSettings, IsDebugLogging, OutputBurstLimit, isFuzzingMode, IsAutoFusing, MaxFixedBufferSize, SyncProcessingLimit);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="isAutoFusing">TBD</param>
/// <returns>TBD</returns>
public ActorMaterializerSettings WithAutoFusing(bool isAutoFusing)
{
return new ActorMaterializerSettings(InitialInputBufferSize, MaxInputBufferSize, Dispatcher, SupervisionDecider, SubscriptionTimeoutSettings, IsDebugLogging, OutputBurstLimit, IsFuzzingMode, isAutoFusing, MaxFixedBufferSize, SyncProcessingLimit);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="maxFixedBufferSize">TBD</param>
/// <returns>TBD</returns>
public ActorMaterializerSettings WithMaxFixedBufferSize(int maxFixedBufferSize)
{
return new ActorMaterializerSettings(InitialInputBufferSize, MaxInputBufferSize, Dispatcher, SupervisionDecider, SubscriptionTimeoutSettings, IsDebugLogging, OutputBurstLimit, IsFuzzingMode, IsAutoFusing, maxFixedBufferSize, SyncProcessingLimit);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="limit">TBD</param>
/// <returns>TBD</returns>
public ActorMaterializerSettings WithSyncProcessingLimit(int limit)
{
return new ActorMaterializerSettings(InitialInputBufferSize, MaxInputBufferSize, Dispatcher, SupervisionDecider, SubscriptionTimeoutSettings, IsDebugLogging, OutputBurstLimit, IsFuzzingMode, IsAutoFusing, MaxFixedBufferSize, limit);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="settings">TBD</param>
/// <returns>TBD</returns>
public ActorMaterializerSettings WithSubscriptionTimeoutSettings(StreamSubscriptionTimeoutSettings settings)
{
if (Equals(settings, SubscriptionTimeoutSettings))
return this;
return new ActorMaterializerSettings(InitialInputBufferSize, MaxInputBufferSize, Dispatcher, SupervisionDecider, settings, IsDebugLogging, OutputBurstLimit, IsFuzzingMode, IsAutoFusing, MaxFixedBufferSize, SyncProcessingLimit);
}
}
/// <summary>
/// Leaked publishers and subscribers are cleaned up when they are not used within a given deadline, configured by <see cref="StreamSubscriptionTimeoutSettings"/>.
/// </summary>
public sealed class StreamSubscriptionTimeoutSettings : IEquatable<StreamSubscriptionTimeoutSettings>
{
/// <summary>
/// TBD
/// </summary>
/// <param name="config">TBD</param>
/// <exception cref="ArgumentException">TBD</exception>
/// <returns>TBD</returns>
public static StreamSubscriptionTimeoutSettings Create(Config config)
{
var c = config.GetConfig("subscription-timeout") ?? Config.Empty;
var configMode = c.GetString("mode", "cancel").ToLowerInvariant();
StreamSubscriptionTimeoutTerminationMode mode;
switch (configMode)
{
case "no": case "off": case "false": case "noop": mode = StreamSubscriptionTimeoutTerminationMode.NoopTermination; break;
case "warn": mode = StreamSubscriptionTimeoutTerminationMode.WarnTermination; break;
case "cancel": mode = StreamSubscriptionTimeoutTerminationMode.CancelTermination; break;
default: throw new ArgumentException("akka.stream.materializer.subscribtion-timeout.mode was not defined or has invalid value. Valid values are: no, off, false, noop, warn, cancel");
}
return new StreamSubscriptionTimeoutSettings(
mode: mode,
timeout: c.GetTimeSpan("timeout", TimeSpan.FromSeconds(5)));
}
/// <summary>
/// TBD
/// </summary>
public readonly StreamSubscriptionTimeoutTerminationMode Mode;
/// <summary>
/// TBD
/// </summary>
public readonly TimeSpan Timeout;
/// <summary>
/// TBD
/// </summary>
/// <param name="mode">TBD</param>
/// <param name="timeout">TBD</param>
public StreamSubscriptionTimeoutSettings(StreamSubscriptionTimeoutTerminationMode mode, TimeSpan timeout)
{
Mode = mode;
Timeout = timeout;
}
/// <inheritdoc/>
public override bool Equals(object obj)
{
if (ReferenceEquals(obj, null))
return false;
if (ReferenceEquals(obj, this))
return true;
if (obj is StreamSubscriptionTimeoutSettings)
return Equals((StreamSubscriptionTimeoutSettings) obj);
return false;
}
/// <inheritdoc/>
public bool Equals(StreamSubscriptionTimeoutSettings other)
=> Mode == other.Mode && Timeout.Equals(other.Timeout);
/// <inheritdoc/>
public override int GetHashCode()
{
unchecked
{
return ((int)Mode * 397) ^ Timeout.GetHashCode();
}
}
/// <inheritdoc/>
public override string ToString() => $"StreamSubscriptionTimeoutSettings<{Mode}, {Timeout}>";
}
/// <summary>
/// This mode describes what shall happen when the subscription timeout expires
/// for substream Publishers created by operations like <see cref="InternalFlowOperations.PrefixAndTail{T,TMat}"/>.
/// </summary>
public enum StreamSubscriptionTimeoutTerminationMode
{
/// <summary>
/// Do not do anything when timeout expires.
/// </summary>
NoopTermination,
/// <summary>
/// Log a warning when the timeout expires.
/// </summary>
WarnTermination,
/// <summary>
/// When the timeout expires attach a Subscriber that will immediately cancel its subscription.
/// </summary>
CancelTermination
}
/// <summary>
/// TBD
/// </summary>
public static class ActorMaterializerExtensions
{
/// <summary>
/// <para>
/// Creates a ActorMaterializer which will execute every step of a transformation
/// pipeline within its own <see cref="ActorBase"/>. The required <see cref="IActorRefFactory"/>
/// (which can be either an <see cref="ActorSystem"/> or an <see cref="IActorContext"/>)
/// will be used to create one actor that in turn creates actors for the transformation steps.
/// </para>
/// <para>
/// The materializer's <see cref="ActorMaterializerSettings"/> will be obtained from the
/// configuration of the <paramref name="context"/>'s underlying <see cref="ActorSystem"/>.
/// </para>
/// <para>
/// The <paramref name="namePrefix"/> is used as the first part of the names of the actors running
/// the processing steps. The default <paramref name="namePrefix"/> is "flow". The actor names are built up of
/// namePrefix-flowNumber-flowStepNumber-stepName.
/// </para>
/// </summary>
/// <param name="context">TBD</param>
/// <param name="settings">TBD</param>
/// <param name="namePrefix">TBD</param>
/// <returns>TBD</returns>
public static ActorMaterializer Materializer(this IActorRefFactory context, ActorMaterializerSettings settings = null, string namePrefix = null)
=> ActorMaterializer.Create(context, settings, namePrefix);
}
}
| |
using System.Text;
namespace KeyStates
{
public enum VirtualKeyCode : byte //: UInt16
{
// ReSharper disable InconsistentNaming
/// <summary>
/// Left mouse button
/// </summary>
LBUTTON = 0x01,
/// <summary>
/// Right mouse button
/// </summary>
RBUTTON = 0x02,
/// <summary>
/// Control-break processing
/// </summary>
CANCEL = 0x03,
/// <summary>
/// Middle mouse button (three-button mouse) - NOT contiguous with LBUTTON and RBUTTON
/// </summary>
MBUTTON = 0x04,
/// <summary>
/// Windows 2000/XP: X1 mouse button - NOT contiguous with LBUTTON and RBUTTON
/// </summary>
XBUTTON1 = 0x05,
/// <summary>
/// Windows 2000/XP: X2 mouse button - NOT contiguous with LBUTTON and RBUTTON
/// </summary>
XBUTTON2 = 0x06,
// 0x07 : Undefined
/// <summary>
/// BACKSPACE key
/// </summary>
BACK = 0x08,
/// <summary>
/// TAB key
/// </summary>
TAB = 0x09,
// 0x0A - 0x0B : Reserved
/// <summary>
/// CLEAR key
/// </summary>
CLEAR = 0x0C,
/// <summary>
/// ENTER key
/// </summary>
RETURN = 0x0D,
// 0x0E - 0x0F : Undefined
/// <summary>
/// SHIFT key
/// </summary>
SHIFT = 0x10,
/// <summary>
/// CTRL key
/// </summary>
CONTROL = 0x11,
/// <summary>
/// ALT key
/// </summary>
MENU = 0x12,
/// <summary>
/// PAUSE key
/// </summary>
PAUSE = 0x13,
/// <summary>
/// CAPS LOCK key
/// </summary>
CAPITAL = 0x14,
/// <summary>
/// Input Method Editor (IME) Kana mode
/// </summary>
KANA = 0x15,
/// <summary>
/// IME Hanguel mode (maintained for compatibility; use HANGUL)
/// </summary>
HANGEUL = 0x15,
/// <summary>
/// IME Hangul mode
/// </summary>
HANGUL = 0x15,
// 0x16 : Undefined
/// <summary>
/// IME Junja mode
/// </summary>
JUNJA = 0x17,
/// <summary>
/// IME final mode
/// </summary>
FINAL = 0x18,
/// <summary>
/// IME Hanja mode
/// </summary>
HANJA = 0x19,
/// <summary>
/// IME Kanji mode
/// </summary>
KANJI = 0x19,
// 0x1A : Undefined
/// <summary>
/// ESC key
/// </summary>
ESCAPE = 0x1B,
/// <summary>
/// IME convert
/// </summary>
CONVERT = 0x1C,
/// <summary>
/// IME nonconvert
/// </summary>
NONCONVERT = 0x1D,
/// <summary>
/// IME accept
/// </summary>
ACCEPT = 0x1E,
/// <summary>
/// IME mode change request
/// </summary>
MODECHANGE = 0x1F,
/// <summary>
/// SPACEBAR
/// </summary>
SPACE = 0x20,
/// <summary>
/// PAGE UP key
/// </summary>
PRIOR = 0x21,
/// <summary>
/// PAGE DOWN key
/// </summary>
NEXT = 0x22,
/// <summary>
/// END key
/// </summary>
END = 0x23,
/// <summary>
/// HOME key
/// </summary>
HOME = 0x24,
/// <summary>
/// LEFT ARROW key
/// </summary>
LEFT = 0x25,
/// <summary>
/// UP ARROW key
/// </summary>
UP = 0x26,
/// <summary>
/// RIGHT ARROW key
/// </summary>
RIGHT = 0x27,
/// <summary>
/// DOWN ARROW key
/// </summary>
DOWN = 0x28,
/// <summary>
/// SELECT key
/// </summary>
SELECT = 0x29,
/// <summary>
/// PRINT key
/// </summary>
PRINT = 0x2A,
/// <summary>
/// EXECUTE key
/// </summary>
EXECUTE = 0x2B,
/// <summary>
/// PRINT SCREEN key
/// </summary>
SNAPSHOT = 0x2C,
/// <summary>
/// INS key
/// </summary>
INSERT = 0x2D,
/// <summary>
/// DEL key
/// </summary>
DELETE = 0x2E,
/// <summary>
/// HELP key
/// </summary>
HELP = 0x2F,
#region Numbers
/// <summary>
/// 0 key
/// </summary>
VK_0 = 0x30,
/// <summary>
/// 1 key
/// </summary>
VK_1 = 0x31,
/// <summary>
/// 2 key
/// </summary>
VK_2 = 0x32,
/// <summary>
/// 3 key
/// </summary>
VK_3 = 0x33,
/// <summary>
/// 4 key
/// </summary>
VK_4 = 0x34,
/// <summary>
/// 5 key
/// </summary>
VK_5 = 0x35,
/// <summary>
/// 6 key
/// </summary>
VK_6 = 0x36,
/// <summary>
/// 7 key
/// </summary>
VK_7 = 0x37,
/// <summary>
/// 8 key
/// </summary>
VK_8 = 0x38,
/// <summary>
/// 9 key
/// </summary>
VK_9 = 0x39,
#endregion
//
// 0x3A - 0x40 : Udefined
//
#region Letters
/// <summary>
/// A key
/// </summary>
VK_A = 0x41,
/// <summary>
/// B key
/// </summary>
VK_B = 0x42,
/// <summary>
/// C key
/// </summary>
VK_C = 0x43,
/// <summary>
/// D key
/// </summary>
VK_D = 0x44,
/// <summary>
/// E key
/// </summary>
VK_E = 0x45,
/// <summary>
/// F key
/// </summary>
VK_F = 0x46,
/// <summary>
/// G key
/// </summary>
VK_G = 0x47,
/// <summary>
/// H key
/// </summary>
VK_H = 0x48,
/// <summary>
/// I key
/// </summary>
VK_I = 0x49,
/// <summary>
/// J key
/// </summary>
VK_J = 0x4A,
/// <summary>
/// K key
/// </summary>
VK_K = 0x4B,
/// <summary>
/// L key
/// </summary>
VK_L = 0x4C,
/// <summary>
/// M key
/// </summary>
VK_M = 0x4D,
/// <summary>
/// N key
/// </summary>
VK_N = 0x4E,
/// <summary>
/// O key
/// </summary>
VK_O = 0x4F,
/// <summary>
/// P key
/// </summary>
VK_P = 0x50,
/// <summary>
/// Q key
/// </summary>
VK_Q = 0x51,
/// <summary>
/// R key
/// </summary>
VK_R = 0x52,
/// <summary>
/// S key
/// </summary>
VK_S = 0x53,
/// <summary>
/// T key
/// </summary>
VK_T = 0x54,
/// <summary>
/// U key
/// </summary>
VK_U = 0x55,
/// <summary>
/// V key
/// </summary>
VK_V = 0x56,
/// <summary>
/// W key
/// </summary>
VK_W = 0x57,
/// <summary>
/// X key
/// </summary>
VK_X = 0x58,
/// <summary>
/// Y key
/// </summary>
VK_Y = 0x59,
/// <summary>
/// Z key
/// </summary>
VK_Z = 0x5A,
#endregion
/// <summary>
/// Left Windows key (Microsoft Natural keyboard)
/// </summary>
LWIN = 0x5B,
/// <summary>
/// Right Windows key (Natural keyboard)
/// </summary>
RWIN = 0x5C,
/// <summary>
/// Applications key (Natural keyboard)
/// </summary>
APPS = 0x5D,
// 0x5E : reserved
/// <summary>
/// Computer Sleep key
/// </summary>
SLEEP = 0x5F,
#region Keypad Numbers
/// <summary>
/// Numeric keypad 0 key
/// </summary>
NUMPAD0 = 0x60,
/// <summary>
/// Numeric keypad 1 key
/// </summary>
NUMPAD1 = 0x61,
/// <summary>
/// Numeric keypad 2 key
/// </summary>
NUMPAD2 = 0x62,
/// <summary>
/// Numeric keypad 3 key
/// </summary>
NUMPAD3 = 0x63,
/// <summary>
/// Numeric keypad 4 key
/// </summary>
NUMPAD4 = 0x64,
/// <summary>
/// Numeric keypad 5 key
/// </summary>
NUMPAD5 = 0x65,
/// <summary>
/// Numeric keypad 6 key
/// </summary>
NUMPAD6 = 0x66,
/// <summary>
/// Numeric keypad 7 key
/// </summary>
NUMPAD7 = 0x67,
/// <summary>
/// Numeric keypad 8 key
/// </summary>
NUMPAD8 = 0x68,
/// <summary>
/// Numeric keypad 9 key
/// </summary>
NUMPAD9 = 0x69,
#endregion
#region Keypad Operators
/// <summary>
/// Multiply key
/// </summary>
MULTIPLY = 0x6A,
/// <summary>
/// Add key
/// </summary>
ADD = 0x6B,
/// <summary>
/// Separator key
/// </summary>
SEPARATOR = 0x6C,
/// <summary>
/// Subtract key
/// </summary>
SUBTRACT = 0x6D,
/// <summary>
/// Decimal key
/// </summary>
DECIMAL = 0x6E,
/// <summary>
/// Divide key
/// </summary>
DIVIDE = 0x6F,
#endregion
#region Function Keys
/// <summary>
/// F1 key
/// </summary>
F1 = 0x70,
/// <summary>
/// F2 key
/// </summary>
F2 = 0x71,
/// <summary>
/// F3 key
/// </summary>
F3 = 0x72,
/// <summary>
/// F4 key
/// </summary>
F4 = 0x73,
/// <summary>
/// F5 key
/// </summary>
F5 = 0x74,
/// <summary>
/// F6 key
/// </summary>
F6 = 0x75,
/// <summary>
/// F7 key
/// </summary>
F7 = 0x76,
/// <summary>
/// F8 key
/// </summary>
F8 = 0x77,
/// <summary>
/// F9 key
/// </summary>
F9 = 0x78,
/// <summary>
/// F10 key
/// </summary>
F10 = 0x79,
/// <summary>
/// F11 key
/// </summary>
F11 = 0x7A,
/// <summary>
/// F12 key
/// </summary>
F12 = 0x7B,
/// <summary>
/// F13 key
/// </summary>
F13 = 0x7C,
/// <summary>
/// F14 key
/// </summary>
F14 = 0x7D,
/// <summary>
/// F15 key
/// </summary>
F15 = 0x7E,
/// <summary>
/// F16 key
/// </summary>
F16 = 0x7F,
/// <summary>
/// F17 key
/// </summary>
F17 = 0x80,
/// <summary>
/// F18 key
/// </summary>
F18 = 0x81,
/// <summary>
/// F19 key
/// </summary>
F19 = 0x82,
/// <summary>
/// F20 key
/// </summary>
F20 = 0x83,
/// <summary>
/// F21 key
/// </summary>
F21 = 0x84,
/// <summary>
/// F22 key
/// </summary>
F22 = 0x85,
/// <summary>
/// F23 key
/// </summary>
F23 = 0x86,
/// <summary>
/// F24 key
/// </summary>
F24 = 0x87,
#endregion
//
// 0x88 - 0x8F : Unassigned
//
/// <summary>
/// NUM LOCK key
/// </summary>
NUMLOCK = 0x90,
/// <summary>
/// SCROLL LOCK key
/// </summary>
SCROLL = 0x91,
// 0x92 - 0x96 : OEM Specific
// 0x97 - 0x9F : Unassigned
//
// L* & R* - left and right Alt, Ctrl and Shift virtual keys.
// Used only as parameters to GetAsyncKeyState() and GetKeyState().
// No other API or message will distinguish left and right keys in this way.
//
/// <summary>
/// Left SHIFT key - Used only as parameters to GetAsyncKeyState() and GetKeyState()
/// </summary>
LSHIFT = 0xA0,
/// <summary>
/// Right SHIFT key - Used only as parameters to GetAsyncKeyState() and GetKeyState()
/// </summary>
RSHIFT = 0xA1,
/// <summary>
/// Left CONTROL key - Used only as parameters to GetAsyncKeyState() and GetKeyState()
/// </summary>
LCONTROL = 0xA2,
/// <summary>
/// Right CONTROL key - Used only as parameters to GetAsyncKeyState() and GetKeyState()
/// </summary>
RCONTROL = 0xA3,
/// <summary>
/// Left MENU key - Used only as parameters to GetAsyncKeyState() and GetKeyState()
/// </summary>
LMENU = 0xA4,
/// <summary>
/// Right MENU key - Used only as parameters to GetAsyncKeyState() and GetKeyState()
/// </summary>
RMENU = 0xA5,
/// <summary>
/// Windows 2000/XP: Browser Back key
/// </summary>
BROWSER_BACK = 0xA6,
/// <summary>
/// Windows 2000/XP: Browser Forward key
/// </summary>
BROWSER_FORWARD = 0xA7,
/// <summary>
/// Windows 2000/XP: Browser Refresh key
/// </summary>
BROWSER_REFRESH = 0xA8,
/// <summary>
/// Windows 2000/XP: Browser Stop key
/// </summary>
BROWSER_STOP = 0xA9,
/// <summary>
/// Windows 2000/XP: Browser Search key
/// </summary>
BROWSER_SEARCH = 0xAA,
/// <summary>
/// Windows 2000/XP: Browser Favorites key
/// </summary>
BROWSER_FAVORITES = 0xAB,
/// <summary>
/// Windows 2000/XP: Browser Start and Home key
/// </summary>
BROWSER_HOME = 0xAC,
/// <summary>
/// Windows 2000/XP: Volume Mute key
/// </summary>
VOLUME_MUTE = 0xAD,
/// <summary>
/// Windows 2000/XP: Volume Down key
/// </summary>
VOLUME_DOWN = 0xAE,
/// <summary>
/// Windows 2000/XP: Volume Up key
/// </summary>
VOLUME_UP = 0xAF,
/// <summary>
/// Windows 2000/XP: Next Track key
/// </summary>
MEDIA_NEXT_TRACK = 0xB0,
/// <summary>
/// Windows 2000/XP: Previous Track key
/// </summary>
MEDIA_PREV_TRACK = 0xB1,
/// <summary>
/// Windows 2000/XP: Stop Media key
/// </summary>
MEDIA_STOP = 0xB2,
/// <summary>
/// Windows 2000/XP: Play/Pause Media key
/// </summary>
MEDIA_PLAY_PAUSE = 0xB3,
/// <summary>
/// Windows 2000/XP: Start Mail key
/// </summary>
LAUNCH_MAIL = 0xB4,
/// <summary>
/// Windows 2000/XP: Select Media key
/// </summary>
LAUNCH_MEDIA_SELECT = 0xB5,
/// <summary>
/// Windows 2000/XP: Start Application 1 key
/// </summary>
LAUNCH_APP1 = 0xB6,
/// <summary>
/// Windows 2000/XP: Start Application 2 key
/// </summary>
LAUNCH_APP2 = 0xB7,
//
// 0xB8 - 0xB9 : Reserved
//
/// <summary>
/// Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the ';:' key
/// </summary>
OEM_1 = 0xBA,
#region Various Symbols
/// <summary>
/// Windows 2000/XP: For any country/region, the '+' key
/// </summary>
OEM_PLUS = 0xBB,
/// <summary>
/// Windows 2000/XP: For any country/region, the ',' key
/// </summary>
OEM_COMMA = 0xBC,
/// <summary>
/// Windows 2000/XP: For any country/region, the '-' key
/// </summary>
OEM_MINUS = 0xBD,
/// <summary>
/// Windows 2000/XP: For any country/region, the '.' key
/// </summary>
OEM_PERIOD = 0xBE,
/// <summary>
/// Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '/?' key
/// </summary>
OEM_2 = 0xBF,
/// <summary>
/// Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '`~' key
/// </summary>
OEM_3 = 0xC0,
#endregion
//
// 0xC1 - 0xD7 : Reserved
//
//
// 0xD8 - 0xDA : Unassigned
//
#region More Symbols
/// <summary>
/// Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '[{' key
/// </summary>
OEM_4 = 0xDB,
/// <summary>
/// Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '\|' key
/// </summary>
OEM_5 = 0xDC,
/// <summary>
/// Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the ']}' key
/// </summary>
OEM_6 = 0xDD,
/// <summary>
/// Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the 'single-quote/double-quote' key
/// </summary>
OEM_7 = 0xDE,
#endregion
/// <summary>
/// Used for miscellaneous characters; it can vary by keyboard.
/// </summary>
OEM_8 = 0xDF,
//
// 0xE0 : Reserved
//
//
// 0xE1 : OEM Specific
//
/// <summary>
/// Windows 2000/XP: Either the angle bracket key or the backslash key on the RT 102-key keyboard
/// </summary>
OEM_102 = 0xE2,
//
// (0xE3-E4) : OEM specific
//
/// <summary>
/// Windows 95/98/Me, Windows NT 4.0, Windows 2000/XP: IME PROCESS key
/// </summary>
PROCESSKEY = 0xE5,
//
// 0xE6 : OEM specific
//
/// <summary>
/// Windows 2000/XP: Used to pass Unicode characters as if they were keystrokes. The PACKET key is the low word of a 32-bit Virtual Key value used for non-keyboard input methods. For more information, see Remark in KEYBDINPUT, SendInput, WM_KEYDOWN, and WM_KEYUP
/// </summary>
PACKET = 0xE7,
//
// 0xE8 : Unassigned
//
//
// 0xE9-F5 : OEM specific
//
/// <summary>
/// Attn key
/// </summary>
ATTN = 0xF6,
/// <summary>
/// CrSel key
/// </summary>
CRSEL = 0xF7,
/// <summary>
/// ExSel key
/// </summary>
EXSEL = 0xF8,
/// <summary>
/// Erase EOF key
/// </summary>
EREOF = 0xF9,
/// <summary>
/// Play key
/// </summary>
PLAY = 0xFA,
/// <summary>
/// Zoom key
/// </summary>
ZOOM = 0xFB,
/// <summary>
/// Reserved
/// </summary>
NONAME = 0xFC,
/// <summary>
/// PA1 key
/// </summary>
PA1 = 0xFD,
/// <summary>
/// Clear key
/// </summary>
OEM_CLEAR = 0xFE,
// ReSharper restore InconsistentNaming
}
public static class VirtualKeyCodeExtension
{
public static char ToChar(this VirtualKeyCode key, bool shift, bool altGr)
{
var buf = new StringBuilder(256);
var keyboardState = new byte[256];
if (shift)
keyboardState[(int)VirtualKeyCode.SHIFT] = 0xff;
if (altGr)
{
keyboardState[(int)VirtualKeyCode.CONTROL] = 0xff;
keyboardState[(int)VirtualKeyCode.MENU] = 0xff;
}
var result = NativeMethods.ToUnicode(key, 0, keyboardState, buf, 256, 0);
switch (result)
{
case 1:
return buf.ToString()[0];
//case -1:
// Dead key
//case 0:
// No Unicode Value
default:
// Unexpected return value
return '\0';
}
}
public static bool IsTextKey(this VirtualKeyCode key)
{
return key.ToChar(false, false) != '\0';
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System
{
[global::System.CLSCompliantAttribute(false)]
[global::System.Security.SecurityCriticalAttribute]
public static partial class WindowsRuntimeSystemExtensions
{
public static global::Windows.Foundation.IAsyncAction AsAsyncAction(this global::System.Threading.Tasks.Task source) { return default(global::Windows.Foundation.IAsyncAction); }
public static global::Windows.Foundation.IAsyncOperation<TResult> AsAsyncOperation<TResult>(this global::System.Threading.Tasks.Task<TResult> source) { return default(global::Windows.Foundation.IAsyncOperation<TResult>); }
public static global::System.Threading.Tasks.Task AsTask(this global::Windows.Foundation.IAsyncAction source) { return default(global::System.Threading.Tasks.Task); }
public static global::System.Threading.Tasks.Task AsTask(this global::Windows.Foundation.IAsyncAction source, global::System.Threading.CancellationToken cancellationToken) { return default(global::System.Threading.Tasks.Task); }
public static global::System.Threading.Tasks.Task AsTask<TProgress>(this global::Windows.Foundation.IAsyncActionWithProgress<TProgress> source) { return default(global::System.Threading.Tasks.Task); }
public static global::System.Threading.Tasks.Task AsTask<TProgress>(this global::Windows.Foundation.IAsyncActionWithProgress<TProgress> source, global::System.IProgress<TProgress> progress) { return default(global::System.Threading.Tasks.Task); }
public static global::System.Threading.Tasks.Task AsTask<TProgress>(this global::Windows.Foundation.IAsyncActionWithProgress<TProgress> source, global::System.Threading.CancellationToken cancellationToken) { return default(global::System.Threading.Tasks.Task); }
public static global::System.Threading.Tasks.Task AsTask<TProgress>(this global::Windows.Foundation.IAsyncActionWithProgress<TProgress> source, global::System.Threading.CancellationToken cancellationToken, global::System.IProgress<TProgress> progress) { return default(global::System.Threading.Tasks.Task); }
public static global::System.Threading.Tasks.Task<TResult> AsTask<TResult>(this global::Windows.Foundation.IAsyncOperation<TResult> source) { return default(global::System.Threading.Tasks.Task<TResult>); }
public static global::System.Threading.Tasks.Task<TResult> AsTask<TResult>(this global::Windows.Foundation.IAsyncOperation<TResult> source, global::System.Threading.CancellationToken cancellationToken) { return default(global::System.Threading.Tasks.Task<TResult>); }
public static global::System.Threading.Tasks.Task<TResult> AsTask<TResult, TProgress>(this global::Windows.Foundation.IAsyncOperationWithProgress<TResult, TProgress> source) { return default(global::System.Threading.Tasks.Task<TResult>); }
public static global::System.Threading.Tasks.Task<TResult> AsTask<TResult, TProgress>(this global::Windows.Foundation.IAsyncOperationWithProgress<TResult, TProgress> source, global::System.IProgress<TProgress> progress) { return default(global::System.Threading.Tasks.Task<TResult>); }
public static global::System.Threading.Tasks.Task<TResult> AsTask<TResult, TProgress>(this global::Windows.Foundation.IAsyncOperationWithProgress<TResult, TProgress> source, global::System.Threading.CancellationToken cancellationToken) { return default(global::System.Threading.Tasks.Task<TResult>); }
public static global::System.Threading.Tasks.Task<TResult> AsTask<TResult, TProgress>(this global::Windows.Foundation.IAsyncOperationWithProgress<TResult, TProgress> source, global::System.Threading.CancellationToken cancellationToken, global::System.IProgress<TProgress> progress) { return default(global::System.Threading.Tasks.Task<TResult>); }
[global::System.ComponentModel.EditorBrowsableAttribute((global::System.ComponentModel.EditorBrowsableState)(1))]
public static global::System.Runtime.CompilerServices.TaskAwaiter GetAwaiter(this global::Windows.Foundation.IAsyncAction source) { return default(global::System.Runtime.CompilerServices.TaskAwaiter); }
[global::System.ComponentModel.EditorBrowsableAttribute((global::System.ComponentModel.EditorBrowsableState)(1))]
public static global::System.Runtime.CompilerServices.TaskAwaiter GetAwaiter<TProgress>(this global::Windows.Foundation.IAsyncActionWithProgress<TProgress> source) { return default(global::System.Runtime.CompilerServices.TaskAwaiter); }
[global::System.ComponentModel.EditorBrowsableAttribute((global::System.ComponentModel.EditorBrowsableState)(1))]
public static global::System.Runtime.CompilerServices.TaskAwaiter<TResult> GetAwaiter<TResult>(this global::Windows.Foundation.IAsyncOperation<TResult> source) { return default(global::System.Runtime.CompilerServices.TaskAwaiter<TResult>); }
[global::System.ComponentModel.EditorBrowsableAttribute((global::System.ComponentModel.EditorBrowsableState)(1))]
public static global::System.Runtime.CompilerServices.TaskAwaiter<TResult> GetAwaiter<TResult, TProgress>(this global::Windows.Foundation.IAsyncOperationWithProgress<TResult, TProgress> source) { return default(global::System.Runtime.CompilerServices.TaskAwaiter<TResult>); }
}
}
namespace System.IO
{
[global::System.Security.SecurityCriticalAttribute]
public static partial class WindowsRuntimeStorageExtensions
{
[global::System.CLSCompliantAttribute(false)]
public static global::System.Threading.Tasks.Task<global::System.IO.Stream> OpenStreamForReadAsync(this global::Windows.Storage.IStorageFile windowsRuntimeFile) { return default(global::System.Threading.Tasks.Task<global::System.IO.Stream>); }
[global::System.CLSCompliantAttribute(false)]
public static global::System.Threading.Tasks.Task<global::System.IO.Stream> OpenStreamForReadAsync(this global::Windows.Storage.IStorageFolder rootDirectory, string relativePath) { return default(global::System.Threading.Tasks.Task<global::System.IO.Stream>); }
[global::System.CLSCompliantAttribute(false)]
public static global::System.Threading.Tasks.Task<global::System.IO.Stream> OpenStreamForWriteAsync(this global::Windows.Storage.IStorageFile windowsRuntimeFile) { return default(global::System.Threading.Tasks.Task<global::System.IO.Stream>); }
[global::System.CLSCompliantAttribute(false)]
public static global::System.Threading.Tasks.Task<global::System.IO.Stream> OpenStreamForWriteAsync(this global::Windows.Storage.IStorageFolder rootDirectory, string relativePath, global::Windows.Storage.CreationCollisionOption creationCollisionOption) { return default(global::System.Threading.Tasks.Task<global::System.IO.Stream>); }
}
[global::System.Security.SecurityCriticalAttribute]
public static partial class WindowsRuntimeStreamExtensions
{
[global::System.CLSCompliantAttribute(false)]
public static global::Windows.Storage.Streams.IInputStream AsInputStream(this global::System.IO.Stream stream) { return default(global::Windows.Storage.Streams.IInputStream); }
[global::System.CLSCompliantAttribute(false)]
public static global::Windows.Storage.Streams.IOutputStream AsOutputStream(this global::System.IO.Stream stream) { return default(global::Windows.Storage.Streams.IOutputStream); }
[global::System.CLSCompliantAttribute(false)]
public static global::Windows.Storage.Streams.IRandomAccessStream AsRandomAccessStream(this global::System.IO.Stream stream) { return default(global::Windows.Storage.Streams.IRandomAccessStream); }
[global::System.CLSCompliantAttribute(false)]
public static global::System.IO.Stream AsStream(this global::Windows.Storage.Streams.IRandomAccessStream windowsRuntimeStream) { return default(global::System.IO.Stream); }
[global::System.CLSCompliantAttribute(false)]
public static global::System.IO.Stream AsStream(this global::Windows.Storage.Streams.IRandomAccessStream windowsRuntimeStream, int bufferSize) { return default(global::System.IO.Stream); }
[global::System.CLSCompliantAttribute(false)]
public static global::System.IO.Stream AsStreamForRead(this global::Windows.Storage.Streams.IInputStream windowsRuntimeStream) { return default(global::System.IO.Stream); }
[global::System.CLSCompliantAttribute(false)]
public static global::System.IO.Stream AsStreamForRead(this global::Windows.Storage.Streams.IInputStream windowsRuntimeStream, int bufferSize) { return default(global::System.IO.Stream); }
[global::System.CLSCompliantAttribute(false)]
public static global::System.IO.Stream AsStreamForWrite(this global::Windows.Storage.Streams.IOutputStream windowsRuntimeStream) { return default(global::System.IO.Stream); }
[global::System.CLSCompliantAttribute(false)]
public static global::System.IO.Stream AsStreamForWrite(this global::Windows.Storage.Streams.IOutputStream windowsRuntimeStream, int bufferSize) { return default(global::System.IO.Stream); }
}
}
namespace System.Runtime.InteropServices.WindowsRuntime
{
[global::System.CLSCompliantAttribute(false)]
[global::System.Security.SecurityCriticalAttribute]
public static partial class AsyncInfo
{
public static global::Windows.Foundation.IAsyncAction Run(global::System.Func<global::System.Threading.CancellationToken, global::System.Threading.Tasks.Task> taskProvider) { return default(global::Windows.Foundation.IAsyncAction); }
public static global::Windows.Foundation.IAsyncActionWithProgress<TProgress> Run<TProgress>(global::System.Func<global::System.Threading.CancellationToken, global::System.IProgress<TProgress>, global::System.Threading.Tasks.Task> taskProvider) { return default(global::Windows.Foundation.IAsyncActionWithProgress<TProgress>); }
public static global::Windows.Foundation.IAsyncOperation<TResult> Run<TResult>(global::System.Func<global::System.Threading.CancellationToken, global::System.Threading.Tasks.Task<TResult>> taskProvider) { return default(global::Windows.Foundation.IAsyncOperation<TResult>); }
public static global::Windows.Foundation.IAsyncOperationWithProgress<TResult, TProgress> Run<TResult, TProgress>(global::System.Func<global::System.Threading.CancellationToken, global::System.IProgress<TProgress>, global::System.Threading.Tasks.Task<TResult>> taskProvider) { return default(global::Windows.Foundation.IAsyncOperationWithProgress<TResult, TProgress>); }
}
[global::System.Security.SecurityCriticalAttribute]
public sealed partial class WindowsRuntimeBuffer
{
internal WindowsRuntimeBuffer() { }
[global::System.CLSCompliantAttribute(false)]
public static global::Windows.Storage.Streams.IBuffer Create(byte[] data, int offset, int length, int capacity) { return default(global::Windows.Storage.Streams.IBuffer); }
[global::System.CLSCompliantAttribute(false)]
public static global::Windows.Storage.Streams.IBuffer Create(int capacity) { return default(global::Windows.Storage.Streams.IBuffer); }
}
[global::System.Security.SecurityCriticalAttribute]
public static partial class WindowsRuntimeBufferExtensions
{
[global::System.CLSCompliantAttribute(false)]
public static global::Windows.Storage.Streams.IBuffer AsBuffer(this byte[] source) { return default(global::Windows.Storage.Streams.IBuffer); }
[global::System.CLSCompliantAttribute(false)]
public static global::Windows.Storage.Streams.IBuffer AsBuffer(this byte[] source, int offset, int length) { return default(global::Windows.Storage.Streams.IBuffer); }
[global::System.CLSCompliantAttribute(false)]
public static global::Windows.Storage.Streams.IBuffer AsBuffer(this byte[] source, int offset, int length, int capacity) { return default(global::Windows.Storage.Streams.IBuffer); }
[global::System.CLSCompliantAttribute(false)]
public static global::System.IO.Stream AsStream(this global::Windows.Storage.Streams.IBuffer source) { return default(global::System.IO.Stream); }
[global::System.CLSCompliantAttribute(false)]
public static void CopyTo(this byte[] source, int sourceIndex, global::Windows.Storage.Streams.IBuffer destination, uint destinationIndex, int count) { }
[global::System.CLSCompliantAttribute(false)]
public static void CopyTo(this byte[] source, global::Windows.Storage.Streams.IBuffer destination) { }
[global::System.CLSCompliantAttribute(false)]
public static void CopyTo(this global::Windows.Storage.Streams.IBuffer source, byte[] destination) { }
[global::System.CLSCompliantAttribute(false)]
public static void CopyTo(this global::Windows.Storage.Streams.IBuffer source, uint sourceIndex, byte[] destination, int destinationIndex, int count) { }
[global::System.CLSCompliantAttribute(false)]
public static void CopyTo(this global::Windows.Storage.Streams.IBuffer source, uint sourceIndex, global::Windows.Storage.Streams.IBuffer destination, uint destinationIndex, uint count) { }
[global::System.CLSCompliantAttribute(false)]
public static void CopyTo(this global::Windows.Storage.Streams.IBuffer source, global::Windows.Storage.Streams.IBuffer destination) { }
[global::System.CLSCompliantAttribute(false)]
public static byte GetByte(this global::Windows.Storage.Streams.IBuffer source, uint byteOffset) { return default(byte); }
[global::System.CLSCompliantAttribute(false)]
public static global::Windows.Storage.Streams.IBuffer GetWindowsRuntimeBuffer(this global::System.IO.MemoryStream underlyingStream) { return default(global::Windows.Storage.Streams.IBuffer); }
[global::System.CLSCompliantAttribute(false)]
public static global::Windows.Storage.Streams.IBuffer GetWindowsRuntimeBuffer(this global::System.IO.MemoryStream underlyingStream, int positionInStream, int length) { return default(global::Windows.Storage.Streams.IBuffer); }
[global::System.CLSCompliantAttribute(false)]
public static bool IsSameData(this global::Windows.Storage.Streams.IBuffer buffer, global::Windows.Storage.Streams.IBuffer otherBuffer) { return default(bool); }
[global::System.CLSCompliantAttribute(false)]
public static byte[] ToArray(this global::Windows.Storage.Streams.IBuffer source) { return default(byte[]); }
[global::System.CLSCompliantAttribute(false)]
public static byte[] ToArray(this global::Windows.Storage.Streams.IBuffer source, uint sourceIndex, int count) { return default(byte[]); }
}
}
namespace Windows.Foundation
{
[global::System.Security.SecurityCriticalAttribute]
[global::System.Runtime.InteropServices.StructLayoutAttribute(global::System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct Point
{
public Point(double x, double y) { throw new global::System.NotImplementedException(); }
public double X { get { return default(double); } set { } }
public double Y { get { return default(double); } set { } }
[global::System.Security.SecuritySafeCriticalAttribute]
public override bool Equals(object o) { return default(bool); }
public bool Equals(global::Windows.Foundation.Point value) { return default(bool); }
[global::System.Security.SecuritySafeCriticalAttribute]
public override int GetHashCode() { return default(int); }
public static bool operator ==(global::Windows.Foundation.Point point1, global::Windows.Foundation.Point point2) { return default(bool); }
public static bool operator !=(global::Windows.Foundation.Point point1, global::Windows.Foundation.Point point2) { return default(bool); }
[global::System.Security.SecuritySafeCriticalAttribute]
public override string ToString() { return default(string); }
public string ToString(global::System.IFormatProvider provider) { return default(string); }
}
[global::System.Security.SecurityCriticalAttribute]
[global::System.Runtime.InteropServices.StructLayoutAttribute(global::System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct Rect
{
public Rect(double x, double y, double width, double height) { throw new global::System.NotImplementedException(); }
public Rect(global::Windows.Foundation.Point point1, global::Windows.Foundation.Point point2) { throw new global::System.NotImplementedException(); }
public Rect(global::Windows.Foundation.Point location, global::Windows.Foundation.Size size) { throw new global::System.NotImplementedException(); }
public double Bottom { get { return default(double); } }
public static global::Windows.Foundation.Rect Empty { get { return default(global::Windows.Foundation.Rect); } }
public double Height { get { return default(double); } set { } }
public bool IsEmpty { get { return default(bool); } }
public double Left { get { return default(double); } }
public double Right { get { return default(double); } }
public double Top { get { return default(double); } }
public double Width { get { return default(double); } set { } }
public double X { get { return default(double); } set { } }
public double Y { get { return default(double); } set { } }
public bool Contains(global::Windows.Foundation.Point point) { return default(bool); }
[global::System.Security.SecuritySafeCriticalAttribute]
public override bool Equals(object o) { return default(bool); }
public bool Equals(global::Windows.Foundation.Rect value) { return default(bool); }
[global::System.Security.SecuritySafeCriticalAttribute]
public override int GetHashCode() { return default(int); }
public void Intersect(global::Windows.Foundation.Rect rect) { }
public static bool operator ==(global::Windows.Foundation.Rect rect1, global::Windows.Foundation.Rect rect2) { return default(bool); }
public static bool operator !=(global::Windows.Foundation.Rect rect1, global::Windows.Foundation.Rect rect2) { return default(bool); }
[global::System.Security.SecuritySafeCriticalAttribute]
public override string ToString() { return default(string); }
public string ToString(global::System.IFormatProvider provider) { return default(string); }
public void Union(global::Windows.Foundation.Point point) { }
public void Union(global::Windows.Foundation.Rect rect) { }
}
[global::System.Security.SecurityCriticalAttribute]
[global::System.Runtime.InteropServices.StructLayoutAttribute(global::System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct Size
{
public Size(double width, double height) { throw new global::System.NotImplementedException(); }
public static global::Windows.Foundation.Size Empty { get { return default(global::Windows.Foundation.Size); } }
public double Height { get { return default(double); } set { } }
public bool IsEmpty { get { return default(bool); } }
public double Width { get { return default(double); } set { } }
[global::System.Security.SecuritySafeCriticalAttribute]
public override bool Equals(object o) { return default(bool); }
public bool Equals(global::Windows.Foundation.Size value) { return default(bool); }
[global::System.Security.SecuritySafeCriticalAttribute]
public override int GetHashCode() { return default(int); }
public static bool operator ==(global::Windows.Foundation.Size size1, global::Windows.Foundation.Size size2) { return default(bool); }
public static bool operator !=(global::Windows.Foundation.Size size1, global::Windows.Foundation.Size size2) { return default(bool); }
[global::System.Security.SecuritySafeCriticalAttribute]
public override string ToString() { return default(string); }
}
}
namespace Windows.UI
{
[global::System.Security.SecurityCriticalAttribute]
[global::System.Runtime.InteropServices.StructLayoutAttribute(global::System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct Color
{
public byte A { get { return default(byte); } set { } }
public byte B { get { return default(byte); } set { } }
public byte G { get { return default(byte); } set { } }
public byte R { get { return default(byte); } set { } }
[global::System.Security.SecuritySafeCriticalAttribute]
public override bool Equals(object o) { return default(bool); }
public bool Equals(global::Windows.UI.Color color) { return default(bool); }
public static global::Windows.UI.Color FromArgb(byte a, byte r, byte g, byte b) { return default(global::Windows.UI.Color); }
[global::System.Security.SecuritySafeCriticalAttribute]
public override int GetHashCode() { return default(int); }
public static bool operator ==(global::Windows.UI.Color color1, global::Windows.UI.Color color2) { return default(bool); }
public static bool operator !=(global::Windows.UI.Color color1, global::Windows.UI.Color color2) { return default(bool); }
[global::System.Security.SecuritySafeCriticalAttribute]
public override string ToString() { return default(string); }
public string ToString(global::System.IFormatProvider provider) { return default(string); }
}
}
| |
// 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.
/*============================================================
**
** Class: ResourceWriter
**
**
**
** Purpose: Default way to write strings to a CLR resource
** file.
**
**
===========================================================*/
using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.Versioning;
using System.Runtime.Serialization;
using System.Diagnostics;
namespace System.Resources
{
// Generates a binary .resources file in the system default format
// from name and value pairs. Create one with a unique file name,
// call AddResource() at least once, then call Generate() to write
// the .resources file to disk, then call Dispose() to close the file.
//
// The resources generally aren't written out in the same order
// they were added.
//
// See the RuntimeResourceSet overview for details on the system
// default file format.
//
public sealed class ResourceWriter : IResourceWriter
{
// An initial size for our internal sorted list, to avoid extra resizes.
private const int AverageNameSize = 20 * 2; // chars in little endian Unicode
private const int AverageValueSize = 40;
private const string ResourceReaderFullyQualifiedName = "System.Resources.ResourceReader, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
private const string ResSetTypeName = "System.Resources.RuntimeResourceSet";
private const int ResSetVersion = 2;
private SortedDictionary<string, object> _resourceList;
private Stream _output;
private Dictionary<string, object> _caseInsensitiveDups;
private Dictionary<string, PrecannedResource> _preserializedData;
// Set this delegate to allow multi-targeting for .resources files.
public Func<Type, string> TypeNameConverter { get; set; }
public ResourceWriter(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
_output = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None);
_resourceList = new SortedDictionary<string, object>(FastResourceComparer.Default);
_caseInsensitiveDups = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
}
public ResourceWriter(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (!stream.CanWrite)
throw new ArgumentException(SR.Argument_StreamNotWritable);
_output = stream;
_resourceList = new SortedDictionary<string, object>(FastResourceComparer.Default);
_caseInsensitiveDups = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
}
// Adds a string resource to the list of resources to be written to a file.
// They aren't written until Generate() is called.
//
public void AddResource(string name, string value)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (_resourceList == null)
throw new InvalidOperationException(SR.InvalidOperation_ResourceWriterSaved);
// Check for duplicate resources whose names vary only by case.
_caseInsensitiveDups.Add(name, null);
_resourceList.Add(name, value);
}
// Adds a resource of type Object to the list of resources to be
// written to a file. They aren't written until Generate() is called.
//
public void AddResource(string name, object value)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (_resourceList == null)
throw new InvalidOperationException(SR.InvalidOperation_ResourceWriterSaved);
// needed for binary compat
if (value != null && value is Stream)
{
AddResourceInternal(name, (Stream)value, false);
}
else
{
// Check for duplicate resources whose names vary only by case.
_caseInsensitiveDups.Add(name, null);
_resourceList.Add(name, value);
}
}
// Adds a resource of type Stream to the list of resources to be
// written to a file. They aren't written until Generate() is called.
// Doesn't close the Stream when done.
//
public void AddResource(string name, Stream value)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (_resourceList == null)
throw new InvalidOperationException(SR.InvalidOperation_ResourceWriterSaved);
AddResourceInternal(name, value, false);
}
// Adds a resource of type Stream to the list of resources to be
// written to a file. They aren't written until Generate() is called.
// closeAfterWrite parameter indicates whether to close the stream when done.
//
public void AddResource(string name, Stream value, bool closeAfterWrite)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (_resourceList == null)
throw new InvalidOperationException(SR.InvalidOperation_ResourceWriterSaved);
AddResourceInternal(name, value, closeAfterWrite);
}
private void AddResourceInternal(string name, Stream value, bool closeAfterWrite)
{
if (value == null)
{
// Check for duplicate resources whose names vary only by case.
_caseInsensitiveDups.Add(name, null);
_resourceList.Add(name, value);
}
else
{
// make sure the Stream is seekable
if (!value.CanSeek)
throw new ArgumentException(SR.NotSupported_UnseekableStream);
// Check for duplicate resources whose names vary only by case.
_caseInsensitiveDups.Add(name, null);
_resourceList.Add(name, new StreamWrapper(value, closeAfterWrite));
}
}
// Adds a named byte array as a resource to the list of resources to
// be written to a file. They aren't written until Generate() is called.
//
public void AddResource(string name, byte[] value)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (_resourceList == null)
throw new InvalidOperationException(SR.InvalidOperation_ResourceWriterSaved);
// Check for duplicate resources whose names vary only by case.
_caseInsensitiveDups.Add(name, null);
_resourceList.Add(name, value);
}
public void AddResourceData(string name, string typeName, byte[] serializedData)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (typeName == null)
throw new ArgumentNullException(nameof(typeName));
if (serializedData == null)
throw new ArgumentNullException(nameof(serializedData));
if (_resourceList == null)
throw new InvalidOperationException(SR.InvalidOperation_ResourceWriterSaved);
// Check for duplicate resources whose names vary only by case.
_caseInsensitiveDups.Add(name, null);
if (_preserializedData == null)
_preserializedData = new Dictionary<string, PrecannedResource>(FastResourceComparer.Default);
_preserializedData.Add(name, new PrecannedResource(typeName, serializedData));
}
// For cases where users can't create an instance of the deserialized
// type in memory, and need to pass us serialized blobs instead.
// LocStudio's managed code parser will do this in some cases.
private class PrecannedResource
{
internal readonly string TypeName;
internal readonly byte[] Data;
internal PrecannedResource(string typeName, byte[] data)
{
TypeName = typeName;
Data = data;
}
}
private class StreamWrapper
{
internal readonly Stream Stream;
internal readonly bool CloseAfterWrite;
internal StreamWrapper(Stream s, bool closeAfterWrite)
{
Stream = s;
CloseAfterWrite = closeAfterWrite;
}
}
public void Close()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if (disposing)
{
if (_resourceList != null)
{
Generate();
}
if (_output != null)
{
_output.Dispose();
}
}
_output = null;
_caseInsensitiveDups = null;
}
public void Dispose()
{
Dispose(true);
}
// After calling AddResource, Generate() writes out all resources to the
// output stream in the system default format.
// If an exception occurs during object serialization or during IO,
// the .resources file is closed and deleted, since it is most likely
// invalid.
public void Generate()
{
if (_resourceList == null)
throw new InvalidOperationException(SR.InvalidOperation_ResourceWriterSaved);
BinaryWriter bw = new BinaryWriter(_output, Encoding.UTF8);
List<string> typeNames = new List<string>();
// Write out the ResourceManager header
// Write out magic number
bw.Write(ResourceManager.MagicNumber);
// Write out ResourceManager header version number
bw.Write(ResourceManager.HeaderVersionNumber);
MemoryStream resMgrHeaderBlob = new MemoryStream(240);
BinaryWriter resMgrHeaderPart = new BinaryWriter(resMgrHeaderBlob);
// Write out class name of IResourceReader capable of handling
// this file.
resMgrHeaderPart.Write(ResourceReaderFullyQualifiedName);
// Write out class name of the ResourceSet class best suited to
// handling this file.
// This needs to be the same even with multi-targeting. It's the
// full name -- not the assembly qualified name.
resMgrHeaderPart.Write(ResSetTypeName);
resMgrHeaderPart.Flush();
// Write number of bytes to skip over to get past ResMgr header
bw.Write((int)resMgrHeaderBlob.Length);
// Write the rest of the ResMgr header
Debug.Assert(resMgrHeaderBlob.Length > 0, "ResourceWriter: Expected non empty header");
resMgrHeaderBlob.Seek(0, SeekOrigin.Begin);
resMgrHeaderBlob.CopyTo(bw.BaseStream, (int)resMgrHeaderBlob.Length);
// End ResourceManager header
// Write out the RuntimeResourceSet header
// Version number
bw.Write(ResSetVersion);
// number of resources
int numResources = _resourceList.Count;
if (_preserializedData != null)
numResources += _preserializedData.Count;
bw.Write(numResources);
// Store values in temporary streams to write at end of file.
int[] nameHashes = new int[numResources];
int[] namePositions = new int[numResources];
int curNameNumber = 0;
MemoryStream nameSection = new MemoryStream(numResources * AverageNameSize);
BinaryWriter names = new BinaryWriter(nameSection, Encoding.Unicode);
Stream dataSection = new MemoryStream(); // Either a FileStream or a MemoryStream
using (dataSection)
{
BinaryWriter data = new BinaryWriter(dataSection, Encoding.UTF8);
if (_preserializedData != null)
{
foreach (KeyValuePair<string, PrecannedResource> entry in _preserializedData)
{
_resourceList.Add(entry.Key, entry.Value);
}
}
// Write resource name and position to the file, and the value
// to our temporary buffer. Save Type as well.
foreach (var item in _resourceList)
{
nameHashes[curNameNumber] = FastResourceComparer.HashFunction(item.Key);
namePositions[curNameNumber++] = (int)names.Seek(0, SeekOrigin.Current);
names.Write(item.Key); // key
names.Write((int)data.Seek(0, SeekOrigin.Current)); // virtual offset of value.
object value = item.Value;
ResourceTypeCode typeCode = FindTypeCode(value, typeNames);
// Write out type code
Write7BitEncodedInt(data, (int)typeCode);
var userProvidedResource = value as PrecannedResource;
if (userProvidedResource != null)
{
data.Write(userProvidedResource.Data);
}
else
{
WriteValue(typeCode, value, data);
}
}
// At this point, the ResourceManager header has been written.
// Finish RuntimeResourceSet header
// The reader expects a list of user defined type names
// following the size of the list, write 0 for this
// writer implementation
bw.Write(typeNames.Count);
foreach (var typeName in typeNames)
{
bw.Write(typeName);
}
// Write out the name-related items for lookup.
// Note that the hash array and the namePositions array must
// be sorted in parallel.
Array.Sort(nameHashes, namePositions);
// Prepare to write sorted name hashes (alignment fixup)
// Note: For 64-bit machines, these MUST be aligned on 8 byte
// boundaries! Pointers on IA64 must be aligned! And we'll
// run faster on X86 machines too.
bw.Flush();
int alignBytes = ((int)bw.BaseStream.Position) & 7;
if (alignBytes > 0)
{
for (int i = 0; i < 8 - alignBytes; i++)
bw.Write("PAD"[i % 3]);
}
// Write out sorted name hashes.
// Align to 8 bytes.
Debug.Assert((bw.BaseStream.Position & 7) == 0, "ResourceWriter: Name hashes array won't be 8 byte aligned! Ack!");
foreach (int hash in nameHashes)
{
bw.Write(hash);
}
// Write relative positions of all the names in the file.
// Note: this data is 4 byte aligned, occurring immediately
// after the 8 byte aligned name hashes (whose length may
// potentially be odd).
Debug.Assert((bw.BaseStream.Position & 3) == 0, "ResourceWriter: Name positions array won't be 4 byte aligned! Ack!");
foreach (int pos in namePositions)
{
bw.Write(pos);
}
// Flush all BinaryWriters to their underlying streams.
bw.Flush();
names.Flush();
data.Flush();
// Write offset to data section
int startOfDataSection = (int)(bw.Seek(0, SeekOrigin.Current) + nameSection.Length);
startOfDataSection += 4; // We're writing an int to store this data, adding more bytes to the header
bw.Write(startOfDataSection);
// Write name section.
if (nameSection.Length > 0)
{
nameSection.Seek(0, SeekOrigin.Begin);
nameSection.CopyTo(bw.BaseStream, (int)nameSection.Length);
}
names.Dispose();
// Write data section.
Debug.Assert(startOfDataSection == bw.Seek(0, SeekOrigin.Current), "ResourceWriter::Generate - start of data section is wrong!");
dataSection.Position = 0;
dataSection.CopyTo(bw.BaseStream);
data.Dispose();
} // using(dataSection) <--- Closes dataSection, which was opened w/ FileOptions.DeleteOnClose
bw.Flush();
// Indicate we've called Generate
_resourceList = null;
}
private static void Write7BitEncodedInt(BinaryWriter store, int value)
{
Debug.Assert(store != null);
// Write out an int 7 bits at a time. The high bit of the byte,
// when on, tells reader to continue reading more bytes.
uint v = (uint)value; // support negative numbers
while (v >= 0x80)
{
store.Write((byte)(v | 0x80));
v >>= 7;
}
store.Write((byte)v);
}
// Finds the ResourceTypeCode for a type, or adds this type to the
// types list.
private ResourceTypeCode FindTypeCode(object value, List<string> types)
{
if (value == null)
return ResourceTypeCode.Null;
Type type = value.GetType();
if (type == typeof(string))
return ResourceTypeCode.String;
else if (type == typeof(int))
return ResourceTypeCode.Int32;
else if (type == typeof(bool))
return ResourceTypeCode.Boolean;
else if (type == typeof(char))
return ResourceTypeCode.Char;
else if (type == typeof(byte))
return ResourceTypeCode.Byte;
else if (type == typeof(sbyte))
return ResourceTypeCode.SByte;
else if (type == typeof(short))
return ResourceTypeCode.Int16;
else if (type == typeof(long))
return ResourceTypeCode.Int64;
else if (type == typeof(ushort))
return ResourceTypeCode.UInt16;
else if (type == typeof(uint))
return ResourceTypeCode.UInt32;
else if (type == typeof(ulong))
return ResourceTypeCode.UInt64;
else if (type == typeof(float))
return ResourceTypeCode.Single;
else if (type == typeof(double))
return ResourceTypeCode.Double;
else if (type == typeof(decimal))
return ResourceTypeCode.Decimal;
else if (type == typeof(DateTime))
return ResourceTypeCode.DateTime;
else if (type == typeof(TimeSpan))
return ResourceTypeCode.TimeSpan;
else if (type == typeof(byte[]))
return ResourceTypeCode.ByteArray;
else if (type == typeof(StreamWrapper))
return ResourceTypeCode.Stream;
// This is a user type, or a precanned resource. Find type
// table index. If not there, add new element.
string typeName;
if (type == typeof(PrecannedResource)) {
typeName = ((PrecannedResource)value).TypeName;
if (typeName.StartsWith("ResourceTypeCode.", StringComparison.Ordinal)) {
typeName = typeName.Substring(17); // Remove through '.'
ResourceTypeCode typeCode = (ResourceTypeCode)Enum.Parse(typeof(ResourceTypeCode), typeName);
return typeCode;
}
}
else
{
typeName = MultitargetingHelpers.GetAssemblyQualifiedName(type, TypeNameConverter);
}
int typeIndex = types.IndexOf(typeName);
if (typeIndex == -1) {
typeIndex = types.Count;
types.Add(typeName);
}
return (ResourceTypeCode)(typeIndex + ResourceTypeCode.StartOfUserTypes);
}
private void WriteValue(ResourceTypeCode typeCode, object value, BinaryWriter writer)
{
Debug.Assert(writer != null);
switch (typeCode)
{
case ResourceTypeCode.Null:
break;
case ResourceTypeCode.String:
writer.Write((string)value);
break;
case ResourceTypeCode.Boolean:
writer.Write((bool)value);
break;
case ResourceTypeCode.Char:
writer.Write((ushort)(char)value);
break;
case ResourceTypeCode.Byte:
writer.Write((byte)value);
break;
case ResourceTypeCode.SByte:
writer.Write((sbyte)value);
break;
case ResourceTypeCode.Int16:
writer.Write((short)value);
break;
case ResourceTypeCode.UInt16:
writer.Write((ushort)value);
break;
case ResourceTypeCode.Int32:
writer.Write((int)value);
break;
case ResourceTypeCode.UInt32:
writer.Write((uint)value);
break;
case ResourceTypeCode.Int64:
writer.Write((long)value);
break;
case ResourceTypeCode.UInt64:
writer.Write((ulong)value);
break;
case ResourceTypeCode.Single:
writer.Write((float)value);
break;
case ResourceTypeCode.Double:
writer.Write((double)value);
break;
case ResourceTypeCode.Decimal:
writer.Write((decimal)value);
break;
case ResourceTypeCode.DateTime:
// Use DateTime's ToBinary & FromBinary.
long data = ((DateTime)value).ToBinary();
writer.Write(data);
break;
case ResourceTypeCode.TimeSpan:
writer.Write(((TimeSpan)value).Ticks);
break;
// Special Types
case ResourceTypeCode.ByteArray:
{
byte[] bytes = (byte[])value;
writer.Write(bytes.Length);
writer.Write(bytes, 0, bytes.Length);
break;
}
case ResourceTypeCode.Stream:
{
StreamWrapper sw = (StreamWrapper)value;
if (sw.Stream.GetType() == typeof(MemoryStream))
{
MemoryStream ms = (MemoryStream)sw.Stream;
if (ms.Length > int.MaxValue)
throw new ArgumentException(SR.ArgumentOutOfRange_StreamLength);
byte[] arr = ms.ToArray();
writer.Write(arr.Length);
writer.Write(arr, 0, arr.Length);
}
else
{
Stream s = sw.Stream;
// we've already verified that the Stream is seekable
if (s.Length > int.MaxValue)
throw new ArgumentException(SR.ArgumentOutOfRange_StreamLength);
s.Position = 0;
writer.Write((int)s.Length);
byte[] buffer = new byte[4096];
int read = 0;
while ((read = s.Read(buffer, 0, buffer.Length)) != 0)
{
writer.Write(buffer, 0, read);
}
if (sw.CloseAfterWrite)
{
s.Close();
}
}
break;
}
default:
Debug.Assert(typeCode >= ResourceTypeCode.StartOfUserTypes, string.Format(CultureInfo.InvariantCulture, "ResourceReader: Unsupported ResourceTypeCode in .resources file! {0}", typeCode));
throw new PlatformNotSupportedException(SR.NotSupported_BinarySerializedResources);
}
}
}
internal enum ResourceTypeCode {
// Primitives
Null = 0,
String = 1,
Boolean = 2,
Char = 3,
Byte = 4,
SByte = 5,
Int16 = 6,
UInt16 = 7,
Int32 = 8,
UInt32 = 9,
Int64 = 0xa,
UInt64 = 0xb,
Single = 0xc,
Double = 0xd,
Decimal = 0xe,
DateTime = 0xf,
TimeSpan = 0x10,
// A meta-value - change this if you add new primitives
LastPrimitive = TimeSpan,
// Types with a special representation, like byte[] and Stream
ByteArray = 0x20,
Stream = 0x21,
// User types - serialized using the binary formatter.
StartOfUserTypes = 0x40
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Text.Internal;
using System.Text.Unicode;
#if NETCOREAPP
using System.Numerics;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
#endif
namespace System.Text.Encodings.Web
{
internal sealed class UnsafeRelaxedJavaScriptEncoder : JavaScriptEncoder
{
private readonly AllowedCharactersBitmap _allowedCharacters;
internal static readonly UnsafeRelaxedJavaScriptEncoder s_singleton = new UnsafeRelaxedJavaScriptEncoder();
private UnsafeRelaxedJavaScriptEncoder()
{
var filter = new TextEncoderSettings(UnicodeRanges.All);
_allowedCharacters = filter.GetAllowedCharacters();
// Forbid codepoints which aren't mapped to characters or which are otherwise always disallowed
// (includes categories Cc, Cs, Co, Cn, Zs [except U+0020 SPACE], Zl, Zp)
_allowedCharacters.ForbidUndefinedCharacters();
// '"' (U+0022 QUOTATION MARK) must always be escaped in Javascript / ECMAScript / JSON.
_allowedCharacters.ForbidCharacter('\"'); // can be used to escape attributes
// '\' (U+005C REVERSE SOLIDUS) must always be escaped in Javascript / ECMAScript / JSON.
// '/' (U+002F SOLIDUS) is not Javascript / ECMAScript / JSON-sensitive so doesn't need to be escaped.
_allowedCharacters.ForbidCharacter('\\');
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override bool WillEncode(int unicodeScalar)
{
if (UnicodeHelpers.IsSupplementaryCodePoint(unicodeScalar))
{
return true;
}
Debug.Assert(unicodeScalar >= char.MinValue && unicodeScalar <= char.MaxValue);
return !_allowedCharacters.IsUnicodeScalarAllowed(unicodeScalar);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override unsafe int FindFirstCharacterToEncode(char* text, int textLength)
{
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
int idx = 0;
#if NETCOREAPP
if (Sse2.IsSupported)
{
short* startingAddress = (short*)text;
while (textLength - 8 >= idx)
{
Debug.Assert(startingAddress >= text && startingAddress <= (text + textLength - 8));
// Load the next 8 characters.
Vector128<short> sourceValue = Sse2.LoadVector128(startingAddress);
Vector128<short> mask = Sse2Helper.CreateAsciiMask(sourceValue);
int index = Sse2.MoveMask(mask.AsByte());
if (index != 0)
{
// At least one of the following 8 characters is non-ASCII.
int processNextEight = idx + 8;
Debug.Assert(processNextEight <= textLength);
for (; idx < processNextEight; idx++)
{
Debug.Assert((text + idx) <= (text + textLength));
if (!_allowedCharacters.IsCharacterAllowed(*(text + idx)))
{
goto Return;
}
}
startingAddress += 8;
}
else
{
// Check if any of the 8 characters need to be escaped.
mask = Sse2Helper.CreateEscapingMask_UnsafeRelaxedJavaScriptEncoder(sourceValue);
index = Sse2.MoveMask(mask.AsByte());
// If index == 0, that means none of the 8 characters needed to be escaped.
// TrailingZeroCount is relatively expensive, avoid it if possible.
if (index != 0)
{
// Found at least one character that needs to be escaped, figure out the index of
// the first one found that needed to be escaped within the 8 characters.
Debug.Assert(index > 0 && index <= 65_535);
int tzc = BitOperations.TrailingZeroCount(index);
Debug.Assert(tzc % 2 == 0 && tzc >= 0 && tzc <= 16);
idx += tzc >> 1;
goto Return;
}
idx += 8;
startingAddress += 8;
}
}
// Process the remaining characters.
Debug.Assert(textLength - idx < 8);
}
#endif
for (; idx < textLength; idx++)
{
Debug.Assert((text + idx) <= (text + textLength));
if (!_allowedCharacters.IsCharacterAllowed(*(text + idx)))
{
goto Return;
}
}
idx = -1; // All characters are allowed.
Return:
return idx;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override unsafe int FindFirstCharacterToEncodeUtf8(ReadOnlySpan<byte> utf8Text)
{
fixed (byte* ptr = utf8Text)
{
int idx = 0;
#if NETCOREAPP
if (Sse2.IsSupported)
{
sbyte* startingAddress = (sbyte*)ptr;
while (utf8Text.Length - 16 >= idx)
{
Debug.Assert(startingAddress >= ptr && startingAddress <= (ptr + utf8Text.Length - 16));
// Load the next 16 bytes.
Vector128<sbyte> sourceValue = Sse2.LoadVector128(startingAddress);
Vector128<sbyte> mask = Sse2Helper.CreateAsciiMask(sourceValue);
int index = Sse2.MoveMask(mask);
if (index != 0)
{
// At least one of the following 16 bytes is non-ASCII.
int processNextSixteen = idx + 16;
Debug.Assert(processNextSixteen <= utf8Text.Length);
while (idx < processNextSixteen)
{
Debug.Assert((ptr + idx) <= (ptr + utf8Text.Length));
if (UnicodeUtility.IsAsciiCodePoint(ptr[idx]))
{
if (!_allowedCharacters.IsUnicodeScalarAllowed(ptr[idx]))
{
goto Return;
}
idx++;
}
else
{
OperationStatus opStatus = UnicodeHelpers.DecodeScalarValueFromUtf8(utf8Text.Slice(idx), out uint nextScalarValue, out int utf8BytesConsumedForScalar);
Debug.Assert(nextScalarValue <= int.MaxValue);
if (opStatus != OperationStatus.Done || WillEncode((int)nextScalarValue))
{
goto Return;
}
Debug.Assert(opStatus == OperationStatus.Done);
idx += utf8BytesConsumedForScalar;
}
}
startingAddress = (sbyte*)ptr + idx;
}
else
{
// Check if any of the 16 bytes need to be escaped.
mask = Sse2Helper.CreateEscapingMask_UnsafeRelaxedJavaScriptEncoder(sourceValue);
index = Sse2.MoveMask(mask);
// If index == 0, that means none of the 16 bytes needed to be escaped.
// TrailingZeroCount is relatively expensive, avoid it if possible.
if (index != 0)
{
// Found at least one byte that needs to be escaped, figure out the index of
// the first one found that needed to be escaped within the 16 bytes.
Debug.Assert(index > 0 && index <= 65_535);
int tzc = BitOperations.TrailingZeroCount(index);
Debug.Assert(tzc >= 0 && tzc <= 16);
idx += tzc;
goto Return;
}
idx += 16;
startingAddress += 16;
}
}
// Process the remaining bytes.
Debug.Assert(utf8Text.Length - idx < 16);
}
#endif
while (idx < utf8Text.Length)
{
Debug.Assert((ptr + idx) <= (ptr + utf8Text.Length));
if (UnicodeUtility.IsAsciiCodePoint(ptr[idx]))
{
if (!_allowedCharacters.IsUnicodeScalarAllowed(ptr[idx]))
{
goto Return;
}
idx++;
}
else
{
OperationStatus opStatus = UnicodeHelpers.DecodeScalarValueFromUtf8(utf8Text.Slice(idx), out uint nextScalarValue, out int utf8BytesConsumedForScalar);
Debug.Assert(nextScalarValue <= int.MaxValue);
if (opStatus != OperationStatus.Done || WillEncode((int)nextScalarValue))
{
goto Return;
}
Debug.Assert(opStatus == OperationStatus.Done);
idx += utf8BytesConsumedForScalar;
}
}
idx = -1; // All bytes are allowed.
Return:
return idx;
}
}
// The worst case encoding is 6 output chars per input char: [input] U+FFFF -> [output] "\uFFFF"
// We don't need to worry about astral code points since they're represented as encoded
// surrogate pairs in the output.
public override int MaxOutputCharactersPerInputCharacter => 12; // "\uFFFF\uFFFF" is the longest encoded form
private static readonly char[] s_b = new char[] { '\\', 'b' };
private static readonly char[] s_t = new char[] { '\\', 't' };
private static readonly char[] s_n = new char[] { '\\', 'n' };
private static readonly char[] s_f = new char[] { '\\', 'f' };
private static readonly char[] s_r = new char[] { '\\', 'r' };
private static readonly char[] s_back = new char[] { '\\', '\\' };
private static readonly char[] s_doubleQuote = new char[] { '\\', '"' };
// Writes a scalar value as a JavaScript-escaped character (or sequence of characters).
// See ECMA-262, Sec. 7.8.4, and ECMA-404, Sec. 9
// http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4
// http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf
public override unsafe bool TryEncodeUnicodeScalar(int unicodeScalar, char* buffer, int bufferLength, out int numberOfCharactersWritten)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
// ECMA-262 allows encoding U+000B as "\v", but ECMA-404 does not.
// Both ECMA-262 and ECMA-404 allow encoding U+002F SOLIDUS as "\/"
// (in ECMA-262 this character is a NonEscape character); however, we
// don't encode SOLIDUS by default unless the caller has provided an
// explicit bitmap which does not contain it. In this case we'll assume
// that the caller didn't want a SOLIDUS written to the output at all,
// so it should be written using "\u002F" encoding.
// HTML-specific characters (including apostrophe and quotes) will
// be written out as numeric entities for defense-in-depth.
// See UnicodeEncoderBase ctor comments for more info.
if (!WillEncode(unicodeScalar))
{
return TryWriteScalarAsChar(unicodeScalar, buffer, bufferLength, out numberOfCharactersWritten);
}
char[] toCopy;
switch (unicodeScalar)
{
case '\"':
toCopy = s_doubleQuote;
break;
case '\b':
toCopy = s_b;
break;
case '\t':
toCopy = s_t;
break;
case '\n':
toCopy = s_n;
break;
case '\f':
toCopy = s_f;
break;
case '\r':
toCopy = s_r;
break;
case '\\':
toCopy = s_back;
break;
default:
return JavaScriptEncoderHelper.TryWriteEncodedScalarAsNumericEntity(unicodeScalar, buffer, bufferLength, out numberOfCharactersWritten);
}
return TryCopyCharacters(toCopy, buffer, bufferLength, out numberOfCharactersWritten);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="RangeBasedWriter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
//------------------------------------------------------------------------------
namespace Microsoft.Azure.Storage.DataMovement.TransferControllers
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
abstract class RangeBasedWriter : TransferReaderWriterBase
{
/// <summary>
/// Keeps track of the internal state-machine state.
/// </summary>
private volatile State state;
/// <summary>
/// Countdown event to track number of chunks that still need to be
/// uploaded/are in progress of being uploaded. Used to detect when
/// all blocks have finished uploading and change state to Commit
/// state.
/// </summary>
private CountdownEvent toUploadChunksCountdownEvent;
private volatile bool hasWork;
protected RangeBasedWriter(
TransferScheduler scheduler,
SyncTransferController controller,
CancellationToken cancellationToken)
: base(scheduler, controller, cancellationToken)
{
this.hasWork = true;
}
private enum State
{
FetchAttributes,
Create,
Upload,
Commit,
Error,
Finished
};
public override bool IsFinished
{
get
{
return State.Error == this.state || State.Finished == this.state;
}
}
public override bool HasWork
{
get
{
return this.hasWork &&
(!this.PreProcessed
|| ((State.Upload == this.state) && this.SharedTransferData.AvailableData.Any())
|| ((State.Commit == this.state) && (null != this.SharedTransferData.Attributes)));
}
}
protected TransferJob TransferJob
{
get
{
return this.SharedTransferData.TransferJob;
}
}
protected abstract Uri DestUri
{
get;
}
public override async Task DoWorkInternalAsync()
{
switch (this.state)
{
case State.FetchAttributes:
await this.FetchAttributesAsync();
break;
case State.Create:
await this.CreateAsync();
break;
case State.Upload:
await this.UploadAsync();
break;
case State.Commit:
await this.CommitAsync();
break;
case State.Error:
case State.Finished:
break;
}
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
if (null != this.toUploadChunksCountdownEvent)
{
this.toUploadChunksCountdownEvent.Dispose();
this.toUploadChunksCountdownEvent = null;
}
}
}
private async Task FetchAttributesAsync()
{
Debug.Assert(
this.state == State.FetchAttributes,
"FetchAttributesAsync called, but state isn't FetchAttributes",
"Current state is {0}",
this.state);
this.hasWork = false;
this.CheckInputStreamLength(this.SharedTransferData.TotalLength);
bool exist = !this.Controller.IsForceOverwrite;
if (!this.Controller.IsForceOverwrite)
{
try
{
await Utils.ExecuteXsclApiCallAsync(
async () => await this.DoFetchAttributesAsync(),
this.CancellationToken);
}
#if EXPECT_INTERNAL_WRAPPEDSTORAGEEXCEPTION
catch (Exception e) when (e is StorageException || (e is AggregateException && e.InnerException is StorageException))
{
var se = e as StorageException ?? e.InnerException as StorageException;
#else
catch (StorageException se)
{
#endif
// Getting a storage exception is expected if the file doesn't
// exist. In this case we won't error out, but set the
// exist flag to false to indicate we're uploading
// a new file instead of overwriting an existing one.
if (null != se.RequestInformation &&
se.RequestInformation.HttpStatusCode == (int)HttpStatusCode.NotFound)
{
exist = false;
}
else
{
this.HandleFetchAttributesResult(se);
throw;
}
}
catch (Exception e)
{
this.HandleFetchAttributesResult(e);
throw;
}
await this.Controller.CheckOverwriteAsync(
exist,
this.TransferJob.Source.Instance,
this.TransferJob.Destination.Instance);
}
if (this.TransferJob.Destination.Type == TransferLocationType.AzureBlob)
{
(this.TransferJob.Destination as AzureBlobLocation).CheckedAccessCondition = true;
}
else
{
(this.TransferJob.Destination as AzureFileLocation).CheckedAccessCondition = true;
}
this.Controller.UpdateProgressAddBytesTransferred(0);
SingleObjectCheckpoint checkpoint = this.TransferJob.CheckPoint;
// We should create the destination if there's no previous transfer progress in the checkpoint.
// Create will clear all data if the destination already exists.
bool shouldCreate = (checkpoint.EntryTransferOffset == 0) && (!checkpoint.TransferWindow.Any());
if (!shouldCreate)
{
this.InitUpload();
}
else
{
this.state = State.Create;
}
this.hasWork = true;
}
private async Task CreateAsync()
{
Debug.Assert(
this.state == State.Create,
"CreateAsync called, but state isn't Create",
"Current state is {0}",
this.state);
this.hasWork = false;
await Utils.ExecuteXsclApiCallAsync(
async () => await this.DoCreateAsync(this.SharedTransferData.TotalLength),
this.CancellationToken);
this.InitUpload();
}
private void InitUpload()
{
Debug.Assert(
null == this.toUploadChunksCountdownEvent,
"toUploadChunksCountdownEvent expected to be null");
if ((this.TransferJob.CheckPoint.EntryTransferOffset != this.SharedTransferData.TotalLength)
&& (0 != this.TransferJob.CheckPoint.EntryTransferOffset % this.SharedTransferData.BlockSize))
{
throw new FormatException(Resources.RestartableInfoCorruptedException);
}
// Calculate number of chunks.
int numChunks = (int)Math.Ceiling(
(this.SharedTransferData.TotalLength - this.TransferJob.CheckPoint.EntryTransferOffset) / (double)this.SharedTransferData.BlockSize)
+ this.TransferJob.CheckPoint.TransferWindow.Count;
if (0 == numChunks)
{
this.PreProcessed = true;
this.SetCommit();
}
else
{
this.toUploadChunksCountdownEvent = new CountdownEvent(numChunks);
this.state = State.Upload;
this.PreProcessed = true;
this.hasWork = true;
}
}
private async Task UploadAsync()
{
Debug.Assert(
State.Upload == this.state || State.Error == this.state,
"UploadAsync called, but state isn't Upload",
"Current state is {0}",
this.state);
this.hasWork = false;
Debug.Assert(
null != this.toUploadChunksCountdownEvent,
"toUploadChunksCountdownEvent not expected to be null");
if (State.Error == this.state)
{
// Some thread has set the error message, just return here.
return;
}
TransferData transferData = this.GetFirstAvailable();
this.hasWork = true;
await Task.Yield();
if (null != transferData)
{
using (transferData)
{
await this.UploadChunkAsync(transferData).ConfigureAwait(false);
}
}
}
private async Task UploadChunkAsync(TransferData transferData)
{
Debug.Assert(null != transferData, "transferData object expected");
Debug.Assert(
this.state == State.Upload || this.state == State.Error,
"UploadChunkAsync called, but state isn't Upload or Error",
"Current state is {0}",
this.state);
// If a parallel operation caused the controller to be placed in
// error state exit early to avoid unnecessary I/O.
if (this.state == State.Error)
{
return;
}
bool allZero = true;
for (int i = 0; i < transferData.MemoryBuffer.Length; ++i)
{
var memoryChunk = transferData.MemoryBuffer[i];
for (int j = 0; j < memoryChunk.Length; ++j)
{
if (0 != memoryChunk[j])
{
allZero = false;
break;
}
}
if (!allZero)
{
break;
}
}
this.Controller.CheckCancellation();
if (!allZero)
{
if (transferData.MemoryBuffer.Length == 1)
{
transferData.Stream = new MemoryStream(transferData.MemoryBuffer[0], 0, transferData.Length);
}
else
{
transferData.Stream = new ChunkedMemoryStream(transferData.MemoryBuffer, 0, transferData.Length);
}
await this.WriteRangeAsync(transferData).ConfigureAwait(false);
}
this.FinishChunk(transferData);
}
private void FinishChunk(TransferData transferData)
{
Debug.Assert(null != transferData, "transferData object expected");
Debug.Assert(
this.state == State.Upload || this.state == State.Error,
"FinishChunk called, but state isn't Upload or Error",
"Current state is {0}",
this.state);
// If a parallel operation caused the controller to be placed in
// error state exit, make sure not to accidentally change it to
// the Commit state.
if (this.state == State.Error)
{
return;
}
this.Controller.UpdateProgress(() =>
{
lock (this.TransferJob.CheckPoint.TransferWindowLock)
{
this.TransferJob.CheckPoint.TransferWindow.Remove(transferData.StartOffset);
}
this.SharedTransferData.TransferJob.Transfer.UpdateJournal();
this.Controller.UpdateProgressAddBytesTransferred(transferData.Length);
});
if (this.toUploadChunksCountdownEvent.Signal())
{
this.SetCommit();
}
}
private void SetCommit()
{
this.state = State.Commit;
this.hasWork = true;
}
private async Task CommitAsync()
{
Debug.Assert(
this.state == State.Commit,
"CommitAsync called, but state isn't Commit",
"Current state is {0}",
this.state);
this.hasWork = false;
await Utils.ExecuteXsclApiCallAsync(
async () => await this.DoCommitAsync(),
this.CancellationToken);
this.SetFinished();
}
private void SetFinished()
{
this.state = State.Finished;
this.hasWork = false;
this.NotifyFinished(null);
}
protected abstract void CheckInputStreamLength(long streamLength);
protected abstract Task DoFetchAttributesAsync();
protected abstract void HandleFetchAttributesResult(Exception e);
protected abstract Task DoCreateAsync(long size);
protected abstract Task WriteRangeAsync(TransferData transferData);
protected abstract Task DoCommitAsync();
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class ReferenceEqual : ReferenceEqualityTests
{
[Theory]
[PerCompilationType(nameof(ReferenceObjectsData))]
public void TrueOnSame(object item, bool useInterpreter)
{
Expression exp = Expression.ReferenceEqual(
Expression.Constant(item, item.GetType()),
Expression.Constant(item, item.GetType())
);
Assert.True(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(ReferenceTypesData))]
public void TrueOnBothNull(Type type, bool useInterpreter)
{
Expression exp = Expression.ReferenceEqual(
Expression.Constant(null, type),
Expression.Constant(null, type)
);
Assert.True(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(ReferenceObjectsData))]
public void FalseIfLeftNull(object item, bool useInterpreter)
{
Expression exp = Expression.ReferenceEqual(
Expression.Constant(null, item.GetType()),
Expression.Constant(item, item.GetType())
);
Assert.False(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(ReferenceObjectsData))]
public void FalseIfRightNull(object item, bool useInterpreter)
{
Expression exp = Expression.ReferenceEqual(
Expression.Constant(item, item.GetType()),
Expression.Constant(null, item.GetType())
);
Assert.False(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(DifferentObjects))]
public void FalseIfDifferentObjectsAsObject(object x, object y, bool useInterpreter)
{
Expression exp = Expression.ReferenceEqual(
Expression.Constant(x, typeof(object)),
Expression.Constant(y, typeof(object))
);
Assert.False(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(DifferentObjects))]
public void FalseIfDifferentObjectsOwnType(object x, object y, bool useInterpreter)
{
Expression exp = Expression.ReferenceEqual(
Expression.Constant(x),
Expression.Constant(y)
);
Assert.False(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)());
}
[Theory]
[MemberData(nameof(LeftValueType))]
[MemberData(nameof(RightValueType))]
[MemberData(nameof(BothValueType))]
public void ThrowsOnValueTypeArguments(object x, object y)
{
Expression xExp = Expression.Constant(x);
Expression yExp = Expression.Constant(y);
Assert.Throws<InvalidOperationException>(() => Expression.ReferenceEqual(xExp, yExp));
}
[Theory]
[MemberData(nameof(UnassignablePairs))]
public void ThrowsOnUnassignablePairs(object x, object y)
{
Expression xExp = Expression.Constant(x);
Expression yExp = Expression.Constant(y);
Assert.Throws<InvalidOperationException>(() => Expression.ReferenceEqual(xExp, yExp));
}
[Theory]
[PerCompilationType(nameof(ComparableValuesData))]
public void TrueOnSameViaInterface(object item, bool useInterpreter)
{
Expression exp = Expression.ReferenceEqual(
Expression.Constant(item, typeof(IComparable)),
Expression.Constant(item, typeof(IComparable))
);
Assert.True(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(DifferentComparableValues))]
public void FalseOnDifferentViaInterface(object x, object y, bool useInterpreter)
{
Expression exp = Expression.ReferenceEqual(
Expression.Constant(x, typeof(IComparable)),
Expression.Constant(y, typeof(IComparable))
);
Assert.False(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(ComparableReferenceTypesData))]
public void TrueOnSameLeftViaInterface(object item, bool useInterpreter)
{
Expression exp = Expression.ReferenceEqual(
Expression.Constant(item, typeof(IComparable)),
Expression.Constant(item)
);
Assert.True(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(ComparableReferenceTypesData))]
public void TrueOnSameRightViaInterface(object item, bool useInterpreter)
{
Expression exp = Expression.ReferenceEqual(
Expression.Constant(item),
Expression.Constant(item, typeof(IComparable))
);
Assert.True(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)());
}
[Fact]
public void CannotReduce()
{
Expression exp = Expression.ReferenceEqual(Expression.Constant(""), Expression.Constant(""));
Assert.False(exp.CanReduce);
Assert.Same(exp, exp.Reduce());
Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public void ThrowsOnLeftNull()
{
AssertExtensions.Throws<ArgumentNullException>("left", () => Expression.ReferenceEqual(null, Expression.Constant("")));
}
[Fact]
public void ThrowsOnRightNull()
{
AssertExtensions.Throws<ArgumentNullException>("right", () => Expression.ReferenceEqual(Expression.Constant(""), null));
}
[Fact]
public static void ThrowsOnLeftUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<string>), "WriteOnly");
AssertExtensions.Throws<ArgumentException>("left", () => Expression.ReferenceEqual(value, Expression.Constant("")));
}
[Fact]
public static void ThrowsOnRightUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<string>), "WriteOnly");
AssertExtensions.Throws<ArgumentException>("right", () => Expression.ReferenceEqual(Expression.Constant(""), value));
}
[Fact]
public void Update()
{
Expression e1 = Expression.Constant("bar");
Expression e2 = Expression.Constant("foo");
Expression e3 = Expression.Constant("qux");
BinaryExpression eq = Expression.ReferenceEqual(e1, e2);
Assert.Same(eq, eq.Update(e1, null, e2));
BinaryExpression eq1 = eq.Update(e1, null, e3);
Assert.Equal(ExpressionType.Equal, eq1.NodeType);
Assert.Same(e1, eq1.Left);
Assert.Same(e3, eq1.Right);
Assert.Null(eq1.Conversion);
Assert.Null(eq1.Method);
BinaryExpression eq2 = eq.Update(e3, null, e2);
Assert.Equal(ExpressionType.Equal, eq2.NodeType);
Assert.Same(e3, eq2.Left);
Assert.Same(e2, eq2.Right);
Assert.Null(eq2.Conversion);
Assert.Null(eq2.Method);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace BankingSite.Web.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using System.Threading.Tests;
using Xunit;
namespace System.Threading.ThreadPools.Tests
{
public partial class ThreadPoolTests
{
private const int UnexpectedTimeoutMilliseconds = ThreadTestHelpers.UnexpectedTimeoutMilliseconds;
private const int ExpectedTimeoutMilliseconds = ThreadTestHelpers.ExpectedTimeoutMilliseconds;
private const int MaxPossibleThreadCount = 0x7fff;
static ThreadPoolTests()
{
// Run the following tests before any others
if (!PlatformDetection.IsNetNative)
{
ConcurrentInitializeTest();
}
}
// Tests concurrent calls to ThreadPool.SetMinThreads
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "ThreadPool.SetMinThreads is not supported on UapAot.")]
public static void ConcurrentInitializeTest()
{
int processorCount = Environment.ProcessorCount;
var countdownEvent = new CountdownEvent(processorCount);
Action threadMain =
() =>
{
countdownEvent.Signal();
countdownEvent.Wait(ThreadTestHelpers.UnexpectedTimeoutMilliseconds);
Assert.True(ThreadPool.SetMinThreads(processorCount, processorCount));
};
var waitForThreadArray = new Action[processorCount];
for (int i = 0; i < processorCount; ++i)
{
var t = ThreadTestHelpers.CreateGuardedThread(out waitForThreadArray[i], threadMain);
t.IsBackground = true;
t.Start();
}
foreach (Action waitForThread in waitForThreadArray)
{
waitForThread();
}
}
[Fact]
public static void GetMinMaxThreadsTest()
{
int minw, minc;
ThreadPool.GetMinThreads(out minw, out minc);
Assert.True(minw >= 0);
Assert.True(minc >= 0);
int maxw, maxc;
ThreadPool.GetMaxThreads(out maxw, out maxc);
Assert.True(minw <= maxw);
Assert.True(minc <= maxc);
}
[Fact]
public static void GetAvailableThreadsTest()
{
int w, c;
ThreadPool.GetAvailableThreads(out w, out c);
Assert.True(w >= 0);
Assert.True(c >= 0);
int maxw, maxc;
ThreadPool.GetMaxThreads(out maxw, out maxc);
Assert.True(w <= maxw);
Assert.True(c <= maxc);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "ThreadPool.SetMinThreads and SetMaxThreads are not supported on UapAot.")]
public static void SetMinMaxThreadsTest()
{
int minw, minc, maxw, maxc;
ThreadPool.GetMinThreads(out minw, out minc);
ThreadPool.GetMaxThreads(out maxw, out maxc);
Action resetThreadCounts =
() =>
{
Assert.True(ThreadPool.SetMaxThreads(maxw, maxc));
VerifyMaxThreads(maxw, maxc);
Assert.True(ThreadPool.SetMinThreads(minw, minc));
VerifyMinThreads(minw, minc);
};
try
{
int mint = Environment.ProcessorCount * 2;
int maxt = mint + 1;
ThreadPool.SetMinThreads(mint, mint);
ThreadPool.SetMaxThreads(maxt, maxt);
Assert.False(ThreadPool.SetMinThreads(maxt + 1, mint));
Assert.False(ThreadPool.SetMinThreads(mint, maxt + 1));
Assert.False(ThreadPool.SetMinThreads(MaxPossibleThreadCount, mint));
Assert.False(ThreadPool.SetMinThreads(mint, MaxPossibleThreadCount));
Assert.False(ThreadPool.SetMinThreads(MaxPossibleThreadCount + 1, mint));
Assert.False(ThreadPool.SetMinThreads(mint, MaxPossibleThreadCount + 1));
Assert.False(ThreadPool.SetMinThreads(-1, mint));
Assert.False(ThreadPool.SetMinThreads(mint, -1));
Assert.False(ThreadPool.SetMaxThreads(mint - 1, maxt));
Assert.False(ThreadPool.SetMaxThreads(maxt, mint - 1));
VerifyMinThreads(mint, mint);
VerifyMaxThreads(maxt, maxt);
Assert.True(ThreadPool.SetMaxThreads(MaxPossibleThreadCount, MaxPossibleThreadCount));
VerifyMaxThreads(MaxPossibleThreadCount, MaxPossibleThreadCount);
Assert.True(ThreadPool.SetMaxThreads(MaxPossibleThreadCount + 1, MaxPossibleThreadCount + 1));
VerifyMaxThreads(MaxPossibleThreadCount, MaxPossibleThreadCount);
Assert.True(ThreadPool.SetMaxThreads(-1, -1));
VerifyMaxThreads(MaxPossibleThreadCount, MaxPossibleThreadCount);
Assert.True(ThreadPool.SetMinThreads(MaxPossibleThreadCount, MaxPossibleThreadCount));
VerifyMinThreads(MaxPossibleThreadCount, MaxPossibleThreadCount);
Assert.False(ThreadPool.SetMinThreads(MaxPossibleThreadCount + 1, MaxPossibleThreadCount));
Assert.False(ThreadPool.SetMinThreads(MaxPossibleThreadCount, MaxPossibleThreadCount + 1));
Assert.False(ThreadPool.SetMinThreads(-1, MaxPossibleThreadCount));
Assert.False(ThreadPool.SetMinThreads(MaxPossibleThreadCount, -1));
VerifyMinThreads(MaxPossibleThreadCount, MaxPossibleThreadCount);
Assert.True(ThreadPool.SetMinThreads(0, 0));
Assert.True(ThreadPool.SetMaxThreads(1, 1));
VerifyMaxThreads(1, 1);
Assert.True(ThreadPool.SetMinThreads(1, 1));
VerifyMinThreads(1, 1);
}
finally
{
resetThreadCounts();
}
}
[Fact]
// Desktop framework doesn't check for this and instead, hits an assertion failure
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
[SkipOnTargetFramework(TargetFrameworkMonikers.Mono)]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "ThreadPool.SetMinThreads and SetMaxThreads are not supported on UapAot.")]
public static void SetMinMaxThreadsTest_ChangedInDotNetCore()
{
int minw, minc, maxw, maxc;
ThreadPool.GetMinThreads(out minw, out minc);
ThreadPool.GetMaxThreads(out maxw, out maxc);
Action resetThreadCounts =
() =>
{
Assert.True(ThreadPool.SetMaxThreads(maxw, maxc));
VerifyMaxThreads(maxw, maxc);
Assert.True(ThreadPool.SetMinThreads(minw, minc));
VerifyMinThreads(minw, minc);
};
try
{
Assert.True(ThreadPool.SetMinThreads(0, 0));
Assert.False(ThreadPool.SetMaxThreads(0, 1));
Assert.False(ThreadPool.SetMaxThreads(1, 0));
VerifyMaxThreads(maxw, maxc);
}
finally
{
resetThreadCounts();
}
}
private static void VerifyMinThreads(int expectedMinw, int expectedMinc)
{
int minw, minc;
ThreadPool.GetMinThreads(out minw, out minc);
Assert.Equal(expectedMinw, minw);
Assert.Equal(expectedMinc, minc);
}
private static void VerifyMaxThreads(int expectedMaxw, int expectedMaxc)
{
int maxw, maxc;
ThreadPool.GetMaxThreads(out maxw, out maxc);
Assert.Equal(expectedMaxw, maxw);
Assert.Equal(expectedMaxc, maxc);
}
[Fact]
public static void QueueRegisterPositiveAndFlowTest()
{
var asyncLocal = new AsyncLocal<int>();
asyncLocal.Value = 1;
var obj = new object();
var registerWaitEvent = new AutoResetEvent(false);
var threadDone = new AutoResetEvent(false);
RegisteredWaitHandle registeredWaitHandle = null;
Exception backgroundEx = null;
int backgroundAsyncLocalValue = 0;
Action<bool, Action> commonBackgroundTest =
(isRegisteredWaitCallback, test) =>
{
try
{
if (isRegisteredWaitCallback)
{
RegisteredWaitHandle toUnregister = registeredWaitHandle;
registeredWaitHandle = null;
Assert.True(toUnregister.Unregister(threadDone));
}
test();
backgroundAsyncLocalValue = asyncLocal.Value;
}
catch (Exception ex)
{
backgroundEx = ex;
}
finally
{
if (!isRegisteredWaitCallback)
{
threadDone.Set();
}
}
};
Action<bool> waitForBackgroundWork =
isWaitForRegisteredWaitCallback =>
{
if (isWaitForRegisteredWaitCallback)
{
registerWaitEvent.Set();
}
threadDone.CheckedWait();
if (backgroundEx != null)
{
throw new AggregateException(backgroundEx);
}
};
ThreadPool.QueueUserWorkItem(
state =>
{
commonBackgroundTest(false, () =>
{
Assert.Same(obj, state);
});
},
obj);
waitForBackgroundWork(false);
Assert.Equal(1, backgroundAsyncLocalValue);
ThreadPool.UnsafeQueueUserWorkItem(
state =>
{
commonBackgroundTest(false, () =>
{
Assert.Same(obj, state);
});
},
obj);
waitForBackgroundWork(false);
Assert.Equal(0, backgroundAsyncLocalValue);
registeredWaitHandle =
ThreadPool.RegisterWaitForSingleObject(
registerWaitEvent,
(state, timedOut) =>
{
commonBackgroundTest(true, () =>
{
Assert.Same(obj, state);
Assert.False(timedOut);
});
},
obj,
UnexpectedTimeoutMilliseconds,
false);
waitForBackgroundWork(true);
Assert.Equal(1, backgroundAsyncLocalValue);
registeredWaitHandle =
ThreadPool.UnsafeRegisterWaitForSingleObject(
registerWaitEvent,
(state, timedOut) =>
{
commonBackgroundTest(true, () =>
{
Assert.Same(obj, state);
Assert.False(timedOut);
});
},
obj,
UnexpectedTimeoutMilliseconds,
false);
waitForBackgroundWork(true);
Assert.Equal(0, backgroundAsyncLocalValue);
}
[Fact]
public static void QueueRegisterNegativeTest()
{
Assert.Throws<ArgumentNullException>(() => ThreadPool.QueueUserWorkItem(null));
Assert.Throws<ArgumentNullException>(() => ThreadPool.UnsafeQueueUserWorkItem(null, null));
WaitHandle waitHandle = new ManualResetEvent(true);
WaitOrTimerCallback callback = (state, timedOut) => { };
Assert.Throws<ArgumentNullException>(() => ThreadPool.RegisterWaitForSingleObject(null, callback, null, 0, true));
Assert.Throws<ArgumentNullException>(() => ThreadPool.RegisterWaitForSingleObject(waitHandle, null, null, 0, true));
Assert.Throws<ArgumentOutOfRangeException>(() =>
ThreadPool.RegisterWaitForSingleObject(waitHandle, callback, null, -2, true));
Assert.Throws<ArgumentOutOfRangeException>(() =>
ThreadPool.RegisterWaitForSingleObject(waitHandle, callback, null, (long)-2, true));
Assert.Throws<ArgumentOutOfRangeException>(() =>
ThreadPool.RegisterWaitForSingleObject(waitHandle, callback, null, TimeSpan.FromMilliseconds(-2), true));
Assert.Throws<ArgumentOutOfRangeException>(() =>
ThreadPool.RegisterWaitForSingleObject(
waitHandle,
callback,
null,
TimeSpan.FromMilliseconds((double)int.MaxValue + 1),
true));
}
}
}
| |
/*
* Regex.cs - Implementation of the "System.Private.Regex" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Private
{
using System;
using System.Text;
using Platform;
internal sealed class Regex : IDisposable
{
// Internal state.
private IntPtr handle;
private RegexSyntax syntax;
// Constructors.
public Regex(String pattern) : this(pattern, RegexSyntax.PosixBasic) {}
public Regex(String pattern, RegexSyntax syntax)
{
if(pattern == null)
{
throw new ArgumentNullException("pattern");
}
this.syntax = syntax;
if((syntax & RegexSyntax.IgnoreCase) != 0)
{
pattern = pattern.ToLower();
}
if((syntax & RegexSyntax.Wildcard) != 0)
{
pattern = FileSystemToPosix(pattern);
syntax = RegexSyntax.PosixExtended;
}
syntax &= (RegexSyntax.All &
~(RegexSyntax.Debug | RegexSyntax.IgnoreCase));
lock(typeof(Regex))
{
// We lock down "Regex" while we do this because the
// syntax setting in the GNU regex routines is not
// thread-safe without it.
handle = RegexpMethods.CompileWithSyntaxInternal
(pattern, (int)syntax);
}
if(handle == IntPtr.Zero)
{
throw new ArgumentException(_("Arg_InvalidRegex"));
}
}
// Destructor.
~Regex()
{
Dispose();
}
// Implement the IDisposable interface.
public void Dispose()
{
lock(this)
{
if(handle != IntPtr.Zero)
{
RegexpMethods.FreeInternal(handle);
handle = IntPtr.Zero;
}
}
}
// Determine if a string matches this regular expression.
public bool Match(String str)
{
if(str == null)
{
throw new ArgumentNullException("str");
}
if((syntax & RegexSyntax.IgnoreCase) != 0)
{
str = str.ToLower();
}
lock(this)
{
if(handle != IntPtr.Zero)
{
return (RegexpMethods.ExecInternal
(handle, str, 0) == 0);
}
else
{
throw new ObjectDisposedException
(_("Exception_Disposed"));
}
}
}
public bool Match(String str, RegexMatchOptions options)
{
if(str == null)
{
throw new ArgumentNullException("str");
}
if((syntax & RegexSyntax.IgnoreCase) != 0)
{
str = str.ToLower();
}
lock(this)
{
if(handle != IntPtr.Zero)
{
options &= RegexMatchOptions.All;
return (RegexpMethods.ExecInternal
(handle, str, (int)options) == 0);
}
else
{
throw new ObjectDisposedException
(_("Exception_Disposed"));
}
}
}
// Determine if a string matches this regular expression and return
// all of the matches in an array. Returns null if no match.
public RegexMatch[] Match(String str, RegexMatchOptions options,
int maxMatches)
{
if(str == null)
{
throw new ArgumentNullException("str");
}
else if(maxMatches < 0)
{
throw new ArgumentOutOfRangeException
("maxMatches", "Must be non-negative");
}
if((syntax & RegexSyntax.IgnoreCase) != 0)
{
str = str.ToLower();
}
lock(this)
{
if(handle != IntPtr.Zero)
{
options &= RegexMatchOptions.All;
return (RegexMatch[])RegexpMethods.MatchInternal
(handle, str, maxMatches, (int)options,
typeof(RegexMatch));
}
else
{
throw new ObjectDisposedException
(_("Exception_Disposed"));
}
}
}
// Get the syntax options used by this regex object.
public RegexSyntax Syntax
{
get
{
return syntax;
}
}
// Determine if this regex object has been disposed.
public bool IsDisposed
{
get
{
lock(this)
{
return (handle == IntPtr.Zero);
}
}
}
// Convert a filesystem wildcard into a Posix regex pattern.
private static String FileSystemToPosix(String wildcard)
{
// Special case: match the empty string.
if(wildcard == String.Empty)
{
return "^()$";
}
// Build the new regular expression.
StringBuilder builder = new StringBuilder(wildcard.Length * 2);
char ch;
int posn = 0;
int index, index2;
builder.Append('^');
while(posn < wildcard.Length)
{
ch = wildcard[posn++];
switch(ch)
{
case '*':
{
if((posn + 1) < wildcard.Length &&
wildcard[posn] == '*' &&
(wildcard[posn + 1] == '/' ||
wildcard[posn + 1] == '\\'))
{
// "**/": match arbitrary directory prefixes.
builder.Append("(.*[/\\]|())");
posn += 2;
}
else
{
// Match a sequence of arbitrary characters.
builder.Append('.');
builder.Append('*');
}
}
break;
case '?':
{
// Match an arbitrary character.
builder.Append('.');
}
break;
case '[':
{
// Match a set of characters.
index = wildcard.IndexOf(']', posn);
index2 = wildcard.IndexOf('[', posn);
if(index != -1 &&
(index2 == -1 || index2 > index))
{
// Output the set to the regex.
builder.Append
(wildcard.Substring
(posn - 1, index - (posn - 1) + 1));
posn = index + 1;
}
else
{
// Unmatched '[': treat as a literal character.
builder.Append('\\');
builder.Append(ch);
}
}
break;
case '|': case ';':
{
// Separate multiple patterns in a dialog regex.
builder.Append("$|^");
}
break;
case '.': case '^': case '$': case ']':
case '(': case ')':
{
// Escape a special regex character.
builder.Append('\\');
builder.Append(ch);
}
break;
case '/': case '\\':
{
// Match a directory separator, irrespective
// of the type of operating system we are using.
builder.Append('[');
builder.Append('/');
builder.Append('\\');
builder.Append(']');
}
break;
default:
{
builder.Append(ch);
}
break;
}
}
builder.Append('$');
return builder.ToString();
}
}; // class Regex
}; // namespace System.Private
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#define TEST_EXCEPTIONS
using System;
using System.IO;
namespace Microsoft.Zelig.Test
{
public class WriteByte : TestBase, ITestInterface
{
[SetUp]
public InitializeResult Initialize()
{
Log.Comment("Adding set up for the tests.");
// TODO: Add your set up steps here.
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
Log.Comment("Cleaning up after the tests.");
// TODO: Add your clean up steps here.
}
public override TestResult Run( string[] args )
{
TestResult result = TestResult.Pass;
result |= Assert.CheckFailed( ExtendBuffer( ) );
result |= Assert.CheckFailed( InvalidRange( ) );
result |= Assert.CheckFailed( VanillaWrite( ) );
result |= Assert.CheckFailed( BoundaryCheck( ) );
return result;
}
#region Helper methods
private bool TestWrite(MemoryStream ms, int BytesToWrite)
{
return TestWrite(ms, BytesToWrite, ms.Position + BytesToWrite);
}
private bool TestWrite(MemoryStream ms, int BytesToWrite, long ExpectedLength)
{
bool result = true;
long startLength = ms.Position;
long nextbyte = startLength % 256;
for (int i = 0; i < BytesToWrite; i++)
{
ms.WriteByte((byte)nextbyte);
// Reset if wraps past 255
if (++nextbyte > 255)
nextbyte = 0;
}
ms.Flush();
if (ExpectedLength < ms.Length)
{
result = false;
Log.Exception("Expeceted final length of " + ExpectedLength + " bytes, but got " + ms.Length + " bytes");
}
return result;
}
#endregion Helper methods
#region Test Cases
[TestMethod]
public TestResult ExtendBuffer()
{
TestResult result = TestResult.Pass;
try
{
using (MemoryStream ms = new MemoryStream())
{
Log.Comment("Set Position past end of stream");
// Internal buffer is initialized to 256, if this changes, this test is no longer valid.
// Exposing capcity would have made this test easier/dynamic.
ms.Position = 300;
ms.WriteByte(123);
if (ms.Length != 301)
{
result = TestResult.Fail;
Log.Exception("Expected length 301, got length " + ms.Length);
}
ms.Position = 300;
int read = ms.ReadByte();
if (read != 123)
{
result = TestResult.Fail;
Log.Exception("Expected value 123, but got value " + result);
}
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception", ex);
result = TestResult.Fail;
}
return result;
}
[TestMethod]
public TestResult InvalidRange()
{
TestResult result = TestResult.Pass;
try
{
byte[] buffer = new byte[100];
using (MemoryStream ms = new MemoryStream(buffer))
{
Log.Comment("Set Position past end of static stream");
ms.Position = buffer.Length + 1;
try
{
ms.WriteByte(1);
result = TestResult.Fail;
Log.Exception("Expected NotSupportedException");
}
catch (NotSupportedException) { /* pass case */ }
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception", ex);
result = TestResult.Fail;
}
return result;
}
[TestMethod]
public TestResult VanillaWrite()
{
TestResult result = TestResult.Pass;
try
{
Log.Comment("Static Buffer");
byte[] buffer = new byte[100];
using (MemoryStream ms = new MemoryStream(buffer))
{
Log.Comment("Write 50 bytes of data");
if (!TestWrite(ms, 50, 100))
result = TestResult.Fail;
Log.Comment("Write final 50 bytes of data");
if (!TestWrite(ms, 50, 100))
result = TestResult.Fail;
#if TEST_EXCEPTIONS
Log.Comment("Any more bytes written should throw");
try
{
ms.WriteByte(50);
result = TestResult.Fail;
Log.Exception("Expected NotSupportedException");
}
catch (NotSupportedException) { /* pass case */ }
#endif
Log.Comment("Rewind and verify all bytes written");
ms.Seek(0, SeekOrigin.Begin);
if (!MemoryStreamHelper.VerifyRead(ms))
result = TestResult.Fail;
}
Log.Comment("Dynamic Buffer");
using (MemoryStream ms = new MemoryStream())
{
Log.Comment("Write 100 bytes of data");
if (!TestWrite(ms, 100))
result = TestResult.Fail;
Log.Comment("Extend internal buffer, write 160");
if (!TestWrite(ms, 160))
result = TestResult.Fail;
Log.Comment("Double extend internal buffer, write 644");
if (!TestWrite(ms, 644))
result = TestResult.Fail;
Log.Comment("write another 1100");
if (!TestWrite(ms, 1100))
result = TestResult.Fail;
Log.Comment("Rewind and verify all bytes written");
ms.Seek(0, SeekOrigin.Begin);
if (!MemoryStreamHelper.VerifyRead(ms))
result = TestResult.Fail;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception", ex);
result = TestResult.Fail;
}
return result;
}
[TestMethod]
public TestResult BoundaryCheck()
{
TestResult result = TestResult.Pass;
try
{
for (int i = 250; i < 260; i++)
{
using (MemoryStream ms = new MemoryStream())
{
MemoryStreamHelper.Write(ms, i);
ms.Position = 0;
if (!MemoryStreamHelper.VerifyRead(ms))
result = TestResult.Fail;
Log.Comment("Position: " + ms.Position);
Log.Comment("Length: " + ms.Length);
if (i != ms.Position | i != ms.Length)
{
result = TestResult.Fail;
Log.Exception("Expected Position and Length to be " + i);
}
}
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
result = TestResult.Fail;
}
return result;
}
#endregion Test Cases
}
}
| |
#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.IO;
using System.Globalization;
using Newtonsoft.Json.Utilities;
using System.Xml;
using Newtonsoft.Json.Converters;
using System.Text;
#if !NET20 && (!SILVERLIGHT || WINDOWS_PHONE)
using System.Xml.Linq;
#endif
namespace Newtonsoft.Json
{
/// <summary>
/// Provides methods for converting between common language runtime types and JSON types.
/// </summary>
public static class JsonConvert
{
/// <summary>
/// Represents JavaScript's boolean value true as a string. This field is read-only.
/// </summary>
public static readonly string True = "true";
/// <summary>
/// Represents JavaScript's boolean value false as a string. This field is read-only.
/// </summary>
public static readonly string False = "false";
/// <summary>
/// Represents JavaScript's null as a string. This field is read-only.
/// </summary>
public static readonly string Null = "null";
/// <summary>
/// Represents JavaScript's undefined as a string. This field is read-only.
/// </summary>
public static readonly string Undefined = "undefined";
/// <summary>
/// Represents JavaScript's positive infinity as a string. This field is read-only.
/// </summary>
public static readonly string PositiveInfinity = "Infinity";
/// <summary>
/// Represents JavaScript's negative infinity as a string. This field is read-only.
/// </summary>
public static readonly string NegativeInfinity = "-Infinity";
/// <summary>
/// Represents JavaScript's NaN as a string. This field is read-only.
/// </summary>
public static readonly string NaN = "NaN";
internal static readonly long InitialJavaScriptDateTicks = 621355968000000000;
/// <summary>
/// Converts the <see cref="DateTime"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="DateTime"/>.</returns>
public static string ToString(DateTime value)
{
using (StringWriter writer = StringUtils.CreateStringWriter(64))
{
WriteDateTimeString(writer, value, value.GetUtcOffset(), value.Kind);
return writer.ToString();
}
}
#if !PocketPC && !NET20
/// <summary>
/// Converts the <see cref="DateTimeOffset"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="DateTimeOffset"/>.</returns>
public static string ToString(DateTimeOffset value)
{
using (StringWriter writer = StringUtils.CreateStringWriter(64))
{
WriteDateTimeString(writer, value.UtcDateTime, value.Offset, DateTimeKind.Local);
return writer.ToString();
}
}
#endif
internal static void WriteDateTimeString(TextWriter writer, DateTime value)
{
WriteDateTimeString(writer, value, value.GetUtcOffset(), value.Kind);
}
internal static void WriteDateTimeString(TextWriter writer, DateTime value, TimeSpan offset, DateTimeKind kind)
{
long javaScriptTicks = ConvertDateTimeToJavaScriptTicks(value, offset);
writer.Write(@"""\/Date(");
writer.Write(javaScriptTicks);
switch (kind)
{
case DateTimeKind.Local:
case DateTimeKind.Unspecified:
writer.Write((offset.Ticks >= 0L) ? "+" : "-");
int absHours = Math.Abs(offset.Hours);
if (absHours < 10)
writer.Write(0);
writer.Write(absHours);
int absMinutes = Math.Abs(offset.Minutes);
if (absMinutes < 10)
writer.Write(0);
writer.Write(absMinutes);
break;
}
writer.Write(@")\/""");
}
private static long ToUniversalTicks(DateTime dateTime)
{
if (dateTime.Kind == DateTimeKind.Utc)
return dateTime.Ticks;
return ToUniversalTicks(dateTime, dateTime.GetUtcOffset());
}
private static long ToUniversalTicks(DateTime dateTime, TimeSpan offset)
{
if (dateTime.Kind == DateTimeKind.Utc)
return dateTime.Ticks;
long ticks = dateTime.Ticks - offset.Ticks;
if (ticks > 3155378975999999999L)
return 3155378975999999999L;
if (ticks < 0L)
return 0L;
return ticks;
}
internal static long ConvertDateTimeToJavaScriptTicks(DateTime dateTime, TimeSpan offset)
{
long universialTicks = ToUniversalTicks(dateTime, offset);
return UniversialTicksToJavaScriptTicks(universialTicks);
}
internal static long ConvertDateTimeToJavaScriptTicks(DateTime dateTime)
{
return ConvertDateTimeToJavaScriptTicks(dateTime, true);
}
internal static long ConvertDateTimeToJavaScriptTicks(DateTime dateTime, bool convertToUtc)
{
long ticks = (convertToUtc) ? ToUniversalTicks(dateTime) : dateTime.Ticks;
return UniversialTicksToJavaScriptTicks(ticks);
}
private static long UniversialTicksToJavaScriptTicks(long universialTicks)
{
long javaScriptTicks = (universialTicks - InitialJavaScriptDateTicks) / 10000;
return javaScriptTicks;
}
internal static DateTime ConvertJavaScriptTicksToDateTime(long javaScriptTicks)
{
DateTime dateTime = new DateTime((javaScriptTicks * 10000) + InitialJavaScriptDateTicks, DateTimeKind.Utc);
return dateTime;
}
/// <summary>
/// Converts the <see cref="Boolean"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Boolean"/>.</returns>
public static string ToString(bool value)
{
return (value) ? True : False;
}
/// <summary>
/// Converts the <see cref="Char"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Char"/>.</returns>
public static string ToString(char value)
{
return ToString(char.ToString(value));
}
/// <summary>
/// Converts the <see cref="Enum"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Enum"/>.</returns>
public static string ToString(Enum value)
{
return value.ToString("D");
}
/// <summary>
/// Converts the <see cref="Int32"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Int32"/>.</returns>
public static string ToString(int value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Int16"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Int16"/>.</returns>
public static string ToString(short value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="UInt16"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="UInt16"/>.</returns>
[CLSCompliant(false)]
public static string ToString(ushort value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="UInt32"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="UInt32"/>.</returns>
[CLSCompliant(false)]
public static string ToString(uint value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Int64"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Int64"/>.</returns>
public static string ToString(long value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="UInt64"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="UInt64"/>.</returns>
[CLSCompliant(false)]
public static string ToString(ulong value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Single"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Single"/>.</returns>
public static string ToString(float value)
{
return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
}
/// <summary>
/// Converts the <see cref="Double"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Double"/>.</returns>
public static string ToString(double value)
{
return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
}
private static string EnsureDecimalPlace(double value, string text)
{
if (double.IsNaN(value) || double.IsInfinity(value) || text.IndexOf('.') != -1 || text.IndexOf('E') != -1)
return text;
return text + ".0";
}
private static string EnsureDecimalPlace(string text)
{
if (text.IndexOf('.') != -1)
return text;
return text + ".0";
}
/// <summary>
/// Converts the <see cref="Byte"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Byte"/>.</returns>
public static string ToString(byte value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="SByte"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="SByte"/>.</returns>
[CLSCompliant(false)]
public static string ToString(sbyte value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Decimal"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="SByte"/>.</returns>
public static string ToString(decimal value)
{
return EnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture));
}
/// <summary>
/// Converts the <see cref="Guid"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Guid"/>.</returns>
public static string ToString(Guid value)
{
return '"' + value.ToString("D", CultureInfo.InvariantCulture) + '"';
}
/// <summary>
/// Converts the <see cref="TimeSpan"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="TimeSpan"/>.</returns>
public static string ToString(TimeSpan value)
{
return '"' + value.ToString() + '"';
}
/// <summary>
/// Converts the <see cref="Uri"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Uri"/>.</returns>
public static string ToString(Uri value)
{
if (value == null)
return Null;
return ToString(value.ToString());
}
/// <summary>
/// Converts the <see cref="String"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="String"/>.</returns>
public static string ToString(string value)
{
return ToString(value, '"');
}
/// <summary>
/// Converts the <see cref="String"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="delimter">The string delimiter character.</param>
/// <returns>A JSON string representation of the <see cref="String"/>.</returns>
public static string ToString(string value, char delimter)
{
return JavaScriptUtils.ToEscapedJavaScriptString(value, delimter, true);
}
/// <summary>
/// Converts the <see cref="Object"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Object"/>.</returns>
public static string ToString(object value)
{
if (value == null)
return Null;
IConvertible convertible = value as IConvertible;
if (convertible != null)
{
switch (convertible.GetTypeCode())
{
case TypeCode.String:
return ToString(convertible.ToString(CultureInfo.InvariantCulture));
case TypeCode.Char:
return ToString(convertible.ToChar(CultureInfo.InvariantCulture));
case TypeCode.Boolean:
return ToString(convertible.ToBoolean(CultureInfo.InvariantCulture));
case TypeCode.SByte:
return ToString(convertible.ToSByte(CultureInfo.InvariantCulture));
case TypeCode.Int16:
return ToString(convertible.ToInt16(CultureInfo.InvariantCulture));
case TypeCode.UInt16:
return ToString(convertible.ToUInt16(CultureInfo.InvariantCulture));
case TypeCode.Int32:
return ToString(convertible.ToInt32(CultureInfo.InvariantCulture));
case TypeCode.Byte:
return ToString(convertible.ToByte(CultureInfo.InvariantCulture));
case TypeCode.UInt32:
return ToString(convertible.ToUInt32(CultureInfo.InvariantCulture));
case TypeCode.Int64:
return ToString(convertible.ToInt64(CultureInfo.InvariantCulture));
case TypeCode.UInt64:
return ToString(convertible.ToUInt64(CultureInfo.InvariantCulture));
case TypeCode.Single:
return ToString(convertible.ToSingle(CultureInfo.InvariantCulture));
case TypeCode.Double:
return ToString(convertible.ToDouble(CultureInfo.InvariantCulture));
case TypeCode.DateTime:
return ToString(convertible.ToDateTime(CultureInfo.InvariantCulture));
case TypeCode.Decimal:
return ToString(convertible.ToDecimal(CultureInfo.InvariantCulture));
case TypeCode.DBNull:
return Null;
}
}
#if !PocketPC && !NET20
else if (value is DateTimeOffset)
{
return ToString((DateTimeOffset)value);
}
#endif
else if (value is Guid)
{
return ToString((Guid) value);
}
else if (value is Uri)
{
return ToString((Uri) value);
}
else if (value is TimeSpan)
{
return ToString((TimeSpan) value);
}
throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
}
private static bool IsJsonPrimitiveTypeCode(TypeCode typeCode)
{
switch (typeCode)
{
case TypeCode.String:
case TypeCode.Char:
case TypeCode.Boolean:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.Byte:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.DateTime:
case TypeCode.Decimal:
case TypeCode.DBNull:
return true;
default:
return false;
}
}
internal static bool IsJsonPrimitiveType(Type type)
{
if (ReflectionUtils.IsNullableType(type))
type = Nullable.GetUnderlyingType(type);
#if !PocketPC && !NET20
if (type == typeof(DateTimeOffset))
return true;
#endif
if (type == typeof(byte[]))
return true;
if (type == typeof(Uri))
return true;
if (type == typeof(TimeSpan))
return true;
if (type == typeof(Guid))
return true;
return IsJsonPrimitiveTypeCode(Type.GetTypeCode(type));
}
internal static bool IsJsonPrimitive(object value)
{
if (value == null)
return true;
IConvertible convertible = value as IConvertible;
if (convertible != null)
return IsJsonPrimitiveTypeCode(convertible.GetTypeCode());
#if !PocketPC && !NET20
if (value is DateTimeOffset)
return true;
#endif
if (value is byte[])
return true;
if (value is Uri)
return true;
if (value is TimeSpan)
return true;
if (value is Guid)
return true;
return false;
}
/// <summary>
/// Serializes the specified object to a JSON string.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <returns>A JSON string representation of the object.</returns>
public static string SerializeObject(object value)
{
return SerializeObject(value, Formatting.None, (JsonSerializerSettings)null);
}
/// <summary>
/// Serializes the specified object to a JSON string.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
public static string SerializeObject(object value, Formatting formatting)
{
return SerializeObject(value, formatting, (JsonSerializerSettings)null);
}
/// <summary>
/// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="converters">A collection converters used while serializing.</param>
/// <returns>A JSON string representation of the object.</returns>
public static string SerializeObject(object value, params JsonConverter[] converters)
{
return SerializeObject(value, Formatting.None, converters);
}
/// <summary>
/// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="converters">A collection converters used while serializing.</param>
/// <returns>A JSON string representation of the object.</returns>
public static string SerializeObject(object value, Formatting formatting, params JsonConverter[] converters)
{
JsonSerializerSettings settings = (converters != null && converters.Length > 0)
? new JsonSerializerSettings { Converters = converters }
: null;
return SerializeObject(value, formatting, settings);
}
/// <summary>
/// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is null, default serialization settings will be is used.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
public static string SerializeObject(object value, Formatting formatting, JsonSerializerSettings settings)
{
JsonSerializer jsonSerializer = JsonSerializer.Create(settings);
StringBuilder sb = new StringBuilder(128);
StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = formatting;
jsonSerializer.Serialize(jsonWriter, value);
}
return sw.ToString();
}
/// <summary>
/// Deserializes the JSON to a .NET object.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <returns>The deserialized object from the Json string.</returns>
public static object DeserializeObject(string value)
{
return DeserializeObject(value, null, (JsonSerializerSettings)null);
}
/// <summary>
/// Deserializes the JSON to a .NET object.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
public static object DeserializeObject(string value, JsonSerializerSettings settings)
{
return DeserializeObject(value, null, settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The <see cref="Type"/> of object being deserialized.</param>
/// <returns>The deserialized object from the Json string.</returns>
public static object DeserializeObject(string value, Type type)
{
return DeserializeObject(value, type, (JsonSerializerSettings)null);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <returns>The deserialized object from the Json string.</returns>
public static T DeserializeObject<T>(string value)
{
return DeserializeObject<T>(value, (JsonSerializerSettings)null);
}
/// <summary>
/// Deserializes the JSON to the given anonymous type.
/// </summary>
/// <typeparam name="T">
/// The anonymous type to deserialize to. This can't be specified
/// traditionally and must be infered from the anonymous type passed
/// as a parameter.
/// </typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="anonymousTypeObject">The anonymous type object.</param>
/// <returns>The deserialized anonymous type from the JSON string.</returns>
public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject)
{
return DeserializeObject<T>(value);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="converters">Converters to use while deserializing.</param>
/// <returns>The deserialized object from the JSON string.</returns>
public static T DeserializeObject<T>(string value, params JsonConverter[] converters)
{
return (T)DeserializeObject(value, typeof(T), converters);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The object to deserialize.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
public static T DeserializeObject<T>(string value, JsonSerializerSettings settings)
{
return (T)DeserializeObject(value, typeof(T), settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The type of the object to deserialize.</param>
/// <param name="converters">Converters to use while deserializing.</param>
/// <returns>The deserialized object from the JSON string.</returns>
public static object DeserializeObject(string value, Type type, params JsonConverter[] converters)
{
JsonSerializerSettings settings = (converters != null && converters.Length > 0)
? new JsonSerializerSettings { Converters = converters }
: null;
return DeserializeObject(value, type, settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The type of the object to deserialize to.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
public static object DeserializeObject(string value, Type type, JsonSerializerSettings settings)
{
StringReader sr = new StringReader(value);
JsonSerializer jsonSerializer = JsonSerializer.Create(settings);
object deserializedValue;
using (JsonReader jsonReader = new JsonTextReader(sr))
{
deserializedValue = jsonSerializer.Deserialize(jsonReader, type);
if (jsonReader.Read() && jsonReader.TokenType != JsonToken.Comment)
throw new JsonSerializationException("Additional text found in JSON string after finishing deserializing object.");
}
return deserializedValue;
}
/// <summary>
/// Populates the object with values from the JSON string.
/// </summary>
/// <param name="value">The JSON to populate values from.</param>
/// <param name="target">The target object to populate values onto.</param>
public static void PopulateObject(string value, object target)
{
PopulateObject(value, target, null);
}
/// <summary>
/// Populates the object with values from the JSON string.
/// </summary>
/// <param name="value">The JSON to populate values from.</param>
/// <param name="target">The target object to populate values onto.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
public static void PopulateObject(string value, object target, JsonSerializerSettings settings)
{
StringReader sr = new StringReader(value);
JsonSerializer jsonSerializer = JsonSerializer.Create(settings);
using (JsonReader jsonReader = new JsonTextReader(sr))
{
jsonSerializer.Populate(jsonReader, target);
if (jsonReader.Read() && jsonReader.TokenType != JsonToken.Comment)
throw new JsonSerializationException("Additional text found in JSON string after finishing deserializing object.");
}
}
#if !SILVERLIGHT
/// <summary>
/// Serializes the XML node to a JSON string.
/// </summary>
/// <param name="node">The node to serialize.</param>
/// <returns>A JSON string of the XmlNode.</returns>
public static string SerializeXmlNode(XmlNode node)
{
return SerializeXmlNode(node, Formatting.None);
}
/// <summary>
/// Serializes the XML node to a JSON string.
/// </summary>
/// <param name="node">The node to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <returns>A JSON string of the XmlNode.</returns>
public static string SerializeXmlNode(XmlNode node, Formatting formatting)
{
XmlNodeConverter converter = new XmlNodeConverter();
return SerializeObject(node, formatting, converter);
}
/// <summary>
/// Serializes the XML node to a JSON string.
/// </summary>
/// <param name="node">The node to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="omitRootObject">Omits writing the root object.</param>
/// <returns>A JSON string of the XmlNode.</returns>
public static string SerializeXmlNode(XmlNode node, Formatting formatting, bool omitRootObject)
{
XmlNodeConverter converter = new XmlNodeConverter { OmitRootObject = omitRootObject };
return SerializeObject(node, formatting, converter);
}
/// <summary>
/// Deserializes the XmlNode from a JSON string.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <returns>The deserialized XmlNode</returns>
public static XmlDocument DeserializeXmlNode(string value)
{
return DeserializeXmlNode(value, null);
}
/// <summary>
/// Deserializes the XmlNode from a JSON string nested in a root elment.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <returns>The deserialized XmlNode</returns>
public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName)
{
return DeserializeXmlNode(value, deserializeRootElementName, false);
}
/// <summary>
/// Deserializes the XmlNode from a JSON string nested in a root elment.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <param name="writeArrayAttribute">
/// A flag to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </param>
/// <returns>The deserialized XmlNode</returns>
public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName, bool writeArrayAttribute)
{
XmlNodeConverter converter = new XmlNodeConverter();
converter.DeserializeRootElementName = deserializeRootElementName;
converter.WriteArrayAttribute = writeArrayAttribute;
return (XmlDocument)DeserializeObject(value, typeof(XmlDocument), converter);
}
#endif
#if !NET20 && (!SILVERLIGHT || WINDOWS_PHONE)
/// <summary>
/// Serializes the <see cref="XNode"/> to a JSON string.
/// </summary>
/// <param name="node">The node to convert to JSON.</param>
/// <returns>A JSON string of the XNode.</returns>
public static string SerializeXNode(XObject node)
{
return SerializeXNode(node, Formatting.None);
}
/// <summary>
/// Serializes the <see cref="XNode"/> to a JSON string.
/// </summary>
/// <param name="node">The node to convert to JSON.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <returns>A JSON string of the XNode.</returns>
public static string SerializeXNode(XObject node, Formatting formatting)
{
return SerializeXNode(node, formatting, false);
}
/// <summary>
/// Serializes the <see cref="XNode"/> to a JSON string.
/// </summary>
/// <param name="node">The node to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="omitRootObject">Omits writing the root object.</param>
/// <returns>A JSON string of the XNode.</returns>
public static string SerializeXNode(XObject node, Formatting formatting, bool omitRootObject)
{
XmlNodeConverter converter = new XmlNodeConverter { OmitRootObject = omitRootObject };
return SerializeObject(node, formatting, converter);
}
/// <summary>
/// Deserializes the <see cref="XNode"/> from a JSON string.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <returns>The deserialized XNode</returns>
public static XDocument DeserializeXNode(string value)
{
return DeserializeXNode(value, null);
}
/// <summary>
/// Deserializes the <see cref="XNode"/> from a JSON string nested in a root elment.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <returns>The deserialized XNode</returns>
public static XDocument DeserializeXNode(string value, string deserializeRootElementName)
{
return DeserializeXNode(value, deserializeRootElementName, false);
}
/// <summary>
/// Deserializes the <see cref="XNode"/> from a JSON string nested in a root elment.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <param name="writeArrayAttribute">
/// A flag to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </param>
/// <returns>The deserialized XNode</returns>
public static XDocument DeserializeXNode(string value, string deserializeRootElementName, bool writeArrayAttribute)
{
XmlNodeConverter converter = new XmlNodeConverter();
converter.DeserializeRootElementName = deserializeRootElementName;
converter.WriteArrayAttribute = writeArrayAttribute;
return (XDocument)DeserializeObject(value, typeof(XDocument), converter);
}
#endif
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using FortuneCookies;
using Orleans.Runtime;
using Orleans.Samples.Chirper.GrainInterfaces;
using Orleans.Samples.Chirper.Network.Loader;
namespace Orleans.Samples.Chirper.Network.Driver
{
class ChirperNetworkDriver : IDisposable
{
private AsyncPipeline pipeline;
private readonly List<SimulatedUser> activeUsers;
public FileInfo GraphDataFile { get; internal set; }
public double LoggedInUserRate { get; set; }
public double ShouldRechirpRate { get; set; }
public int ChirpPublishTimebase { get; set; }
public bool ChirpPublishTimeRandom { get; set; }
public bool Verbose { get; set; }
public int LinksPerUser { get; set; }
public int PipelineLength { get; set; }
private ChirperNetworkLoader loader;
private readonly Fortune fortune;
private ChirperPerformanceCounters perfCounters;
public ChirperNetworkDriver()
{
this.LinksPerUser = 27;
this.LoggedInUserRate = 0.001;
this.ShouldRechirpRate = 0.0;
this.ChirpPublishTimebase = 0;
this.ChirpPublishTimeRandom = true;
this.activeUsers = new List<SimulatedUser>();
this.PipelineLength = 500;
this.fortune = new Fortune("fortune.txt");
if (!Orleans.GrainClient.IsInitialized)
{
Orleans.GrainClient.Initialize();
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification="This method creates SimulatedUser objects which will not be disposed until the Stop method")]
public int Run()
{
this.perfCounters = new ChirperPerformanceCounters(this.GraphDataFile.FullName);
perfCounters.ChirpsPerSecond.RawValue = 0;
pipeline = new AsyncPipeline(PipelineLength);
loader = new ChirperNetworkLoader(pipeline);
//if (this.Verbose) loader.SetVerbose();
Console.WriteLine("Loading Chirper network data file " + this.GraphDataFile.FullName);
loader.FileToLoad = this.GraphDataFile;
loader.LoadData();
loader.CreateUserNodes(); // Connect/create users
Console.WriteLine(
"Starting Chirper network traffic simulation for {0} users.\n"
+ "Chirp publication time base = {1}\n"
+ "Random time distribution = {2}\n"
+ "Rechirp rate = {3}",
loader.Users.Count, this.ChirpPublishTimebase, this.ChirpPublishTimeRandom, this.ShouldRechirpRate);
ForEachUser(user =>
{
SimulatedUser u = new SimulatedUser(user);
u.ShouldRechirpRate = this.ShouldRechirpRate;
u.ChirpPublishTimebase = this.ChirpPublishTimebase;
u.ChirpPublishTimeRandom = this.ChirpPublishTimeRandom;
u.Verbose = this.Verbose;
lock (activeUsers)
{
activeUsers.Add(u);
}
u.Start();
});
Console.WriteLine("Starting sending chirps...");
Random rand = new Random();
int count = 0;
Stopwatch stopwatch = Stopwatch.StartNew();
do
{
int i = rand.Next(activeUsers.Count);
SimulatedUser u = activeUsers[i];
if (u == null)
{
Console.WriteLine("User {0} not found.", i);
return -1;
}
string msg = fortune.GetFortune();
pipeline.Add(u.PublishMessage(msg));
count++;
if (count % 10000 == 0)
{
Console.WriteLine("{0:0.#}/sec: {1} in {2}ms. Pipeline contains {3} items.",
((float)10000 / stopwatch.ElapsedMilliseconds) * 1000, count, stopwatch.ElapsedMilliseconds, pipeline.Count);
perfCounters.ChirpsPerSecond.RawValue = (int) (((float) 10000 / stopwatch.ElapsedMilliseconds) * 1000);
stopwatch.Restart();
}
if (ChirpPublishTimebase > 0)
{
Thread.Sleep(ChirpPublishTimebase * 1000);
}
} while (true);
}
public void Stop()
{
activeUsers.ForEach(u => u.Dispose());
activeUsers.Clear();
}
public bool ParseArguments(string[] args)
{
bool ok = true;
int argPos = 1;
for (int i = 0; i < args.Length; i++)
{
string a = args[i];
if (a.StartsWith("-") || a.StartsWith("/"))
{
a = a.ToLowerInvariant().Substring(1);
switch (a)
{
case "verbose":
case "v":
this.Verbose = true;
break;
case "norandom":
this.ChirpPublishTimeRandom = false;
break;
case "time":
this.ChirpPublishTimebase = Int32.Parse(args[++i]);
break;
case "rechirp":
this.ShouldRechirpRate = Double.Parse(args[++i]);
break;
case "links":
this.LinksPerUser = Int32.Parse(args[++i]);
break;
case "pipeline":
this.PipelineLength = Int32.Parse(args[++i]);
break;
case "?":
case "help":
default:
ok = false;
break;
}
}
// unqualified arguments below
else if (argPos == 1)
{
this.GraphDataFile = new FileInfo(a);
argPos++;
if (!GraphDataFile.Exists)
{
Console.WriteLine("Cannot find data file: " + this.GraphDataFile.FullName);
ok = false;
}
}
else
{
// Too many command line arguments
Console.WriteLine("Too many command line arguments supplied: " + a);
return false;
}
}
if (GraphDataFile == null)
{
Console.WriteLine("No graph data file supplied -- driver cannot run.");
return false;
}
return ok;
}
public void PrintUsage()
{
using (StringWriter usageStr = new StringWriter())
{
usageStr.WriteLine(Assembly.GetExecutingAssembly().GetName().Name + ".exe [options] {file}");
usageStr.WriteLine("Where:");
usageStr.WriteLine(" {file} = GraphML file for network to simulate");
usageStr.WriteLine(" /create = Create the network graph in Orleans before running simulation");
usageStr.WriteLine(" /time {t} = Base chirp publication time (integer)");
usageStr.WriteLine(" /rechirp {r} = Rechirp rate (decimal 0.0 - 1.0)");
usageStr.WriteLine(" /norandom = Use constant chirp publication time intervals, rather than random");
usageStr.WriteLine(" /create = Create the network graph in Orleans before running simulation");
usageStr.WriteLine(" /v = Verbose output");
Console.WriteLine(usageStr.ToString());
}
}
private void ForEachUser(Action<IChirperAccount> action)
{
List<Task> promises = new List<Task>();
foreach (long userId in loader.Users.Keys)
{
IChirperAccount user = loader.Users[userId];
Task p = Task.Factory.StartNew(() => action(user));
pipeline.Add(p);
promises.Add(p);
}
pipeline.Wait();
Task.WhenAll(promises).Wait();
}
#region IDisposable Members
public void Dispose()
{
//loader.Dispose();
}
#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.
/*=============================================================================
**
**
**
** Purpose: The base class for all exceptional conditions.
**
**
=============================================================================*/
namespace System
{
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Diagnostics;
using System.Security;
using System.IO;
using System.Text;
using System.Reflection;
using System.Collections;
using System.Globalization;
using System.Diagnostics.Contracts;
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class Exception : ISerializable
{
private void Init()
{
_message = null;
_stackTrace = null;
_dynamicMethods = null;
HResult = HResults.COR_E_EXCEPTION;
_xcode = _COMPlusExceptionCode;
_xptrs = (IntPtr)0;
// Initialize the WatsonBuckets to be null
_watsonBuckets = null;
// Initialize the watson bucketing IP
_ipForWatsonBuckets = UIntPtr.Zero;
}
public Exception()
{
Init();
}
public Exception(String message)
{
Init();
_message = message;
}
// Creates a new Exception. All derived classes should
// provide this constructor.
// Note: the stack trace is not started until the exception
// is thrown
//
public Exception(String message, Exception innerException)
{
Init();
_message = message;
_innerException = innerException;
}
protected Exception(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
_className = info.GetString("ClassName"); // Do not rename (binary serialization)
_message = info.GetString("Message"); // Do not rename (binary serialization)
_data = (IDictionary)(info.GetValueNoThrow("Data", typeof(IDictionary))); // Do not rename (binary serialization)
_innerException = (Exception)(info.GetValue("InnerException", typeof(Exception))); // Do not rename (binary serialization)
_helpURL = info.GetString("HelpURL"); // Do not rename (binary serialization)
_stackTraceString = info.GetString("StackTraceString"); // Do not rename (binary serialization)
_remoteStackTraceString = info.GetString("RemoteStackTraceString"); // Do not rename (binary serialization)
_remoteStackIndex = info.GetInt32("RemoteStackIndex"); // Do not rename (binary serialization)
HResult = info.GetInt32("HResult"); // Do not rename (binary serialization)
_source = info.GetString("Source"); // Do not rename (binary serialization)
// Get the WatsonBuckets that were serialized - this is particularly
// done to support exceptions going across AD transitions.
//
// We use the no throw version since we could be deserializing a pre-V4
// exception object that may not have this entry. In such a case, we would
// get null.
_watsonBuckets = (Object)info.GetValueNoThrow("WatsonBuckets", typeof(byte[])); // Do not rename (binary serialization)
if (_className == null || HResult == 0)
throw new SerializationException(SR.Serialization_InsufficientState);
// If we are constructing a new exception after a cross-appdomain call...
if (context.State == StreamingContextStates.CrossAppDomain)
{
// ...this new exception may get thrown. It is logically a re-throw, but
// physically a brand-new exception. Since the stack trace is cleared
// on a new exception, the "_remoteStackTraceString" is provided to
// effectively import a stack trace from a "remote" exception. So,
// move the _stackTraceString into the _remoteStackTraceString. Note
// that if there is an existing _remoteStackTraceString, it will be
// preserved at the head of the new string, so everything works as
// expected.
// Even if this exception is NOT thrown, things will still work as expected
// because the StackTrace property returns the concatenation of the
// _remoteStackTraceString and the _stackTraceString.
_remoteStackTraceString = _remoteStackTraceString + _stackTraceString;
_stackTraceString = null;
}
}
public virtual String Message
{
get
{
if (_message == null)
{
if (_className == null)
{
_className = GetClassName();
}
return SR.Format(SR.Exception_WasThrown, _className);
}
else
{
return _message;
}
}
}
public virtual IDictionary Data
{
get
{
if (_data == null)
if (IsImmutableAgileException(this))
_data = new EmptyReadOnlyDictionaryInternal();
else
_data = new ListDictionaryInternal();
return _data;
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool IsImmutableAgileException(Exception e);
#if FEATURE_COMINTEROP
//
// Exception requires anything to be added into Data dictionary is serializable
// This wrapper is made serializable to satisfy this requirement but does NOT serialize
// the object and simply ignores it during serialization, because we only need
// the exception instance in the app to hold the error object alive.
// Once the exception is serialized to debugger, debugger only needs the error reference string
//
[Serializable]
internal class __RestrictedErrorObject
{
// Hold the error object instance but don't serialize/deserialize it
[NonSerialized]
private object _realErrorObject;
internal __RestrictedErrorObject(object errorObject)
{
_realErrorObject = errorObject;
}
public object RealErrorObject
{
get
{
return _realErrorObject;
}
}
}
[FriendAccessAllowed]
internal void AddExceptionDataForRestrictedErrorInfo(
string restrictedError,
string restrictedErrorReference,
string restrictedCapabilitySid,
object restrictedErrorObject,
bool hasrestrictedLanguageErrorObject = false)
{
IDictionary dict = Data;
if (dict != null)
{
dict.Add("RestrictedDescription", restrictedError);
dict.Add("RestrictedErrorReference", restrictedErrorReference);
dict.Add("RestrictedCapabilitySid", restrictedCapabilitySid);
// Keep the error object alive so that user could retrieve error information
// using Data["RestrictedErrorReference"]
dict.Add("__RestrictedErrorObject", (restrictedErrorObject == null ? null : new __RestrictedErrorObject(restrictedErrorObject)));
dict.Add("__HasRestrictedLanguageErrorObject", hasrestrictedLanguageErrorObject);
}
}
internal bool TryGetRestrictedLanguageErrorObject(out object restrictedErrorObject)
{
restrictedErrorObject = null;
if (Data != null && Data.Contains("__HasRestrictedLanguageErrorObject"))
{
if (Data.Contains("__RestrictedErrorObject"))
{
__RestrictedErrorObject restrictedObject = Data["__RestrictedErrorObject"] as __RestrictedErrorObject;
if (restrictedObject != null)
restrictedErrorObject = restrictedObject.RealErrorObject;
}
return (bool)Data["__HasRestrictedLanguageErrorObject"];
}
return false;
}
#endif // FEATURE_COMINTEROP
private string GetClassName()
{
// Will include namespace but not full instantiation and assembly name.
if (_className == null)
_className = GetType().ToString();
return _className;
}
// Retrieves the lowest exception (inner most) for the given Exception.
// This will traverse exceptions using the innerException property.
//
public virtual Exception GetBaseException()
{
Exception inner = InnerException;
Exception back = this;
while (inner != null)
{
back = inner;
inner = inner.InnerException;
}
return back;
}
// Returns the inner exception contained in this exception
//
public Exception InnerException
{
get { return _innerException; }
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static extern private IRuntimeMethodInfo GetMethodFromStackTrace(Object stackTrace);
private MethodBase GetExceptionMethodFromStackTrace()
{
IRuntimeMethodInfo method = GetMethodFromStackTrace(_stackTrace);
// Under certain race conditions when exceptions are re-used, this can be null
if (method == null)
return null;
return RuntimeType.GetMethodBase(method);
}
public MethodBase TargetSite
{
get
{
return GetTargetSiteInternal();
}
}
// this function is provided as a private helper to avoid the security demand
private MethodBase GetTargetSiteInternal()
{
if (_exceptionMethod != null)
{
return _exceptionMethod;
}
if (_stackTrace == null)
{
return null;
}
_exceptionMethod = GetExceptionMethodFromStackTrace();
return _exceptionMethod;
}
// Returns the stack trace as a string. If no stack trace is
// available, null is returned.
public virtual String StackTrace
{
get
{
// By default attempt to include file and line number info
return GetStackTrace(true);
}
}
// Computes and returns the stack trace as a string
// Attempts to get source file and line number information if needFileInfo
// is true. Note that this requires FileIOPermission(PathDiscovery), and so
// will usually fail in CoreCLR. To avoid the demand and resulting
// SecurityException we can explicitly not even try to get fileinfo.
private string GetStackTrace(bool needFileInfo)
{
string stackTraceString = _stackTraceString;
string remoteStackTraceString = _remoteStackTraceString;
// if no stack trace, try to get one
if (stackTraceString != null)
{
return remoteStackTraceString + stackTraceString;
}
if (_stackTrace == null)
{
return remoteStackTraceString;
}
// Obtain the stack trace string. Note that since Environment.GetStackTrace
// will add the path to the source file if the PDB is present and a demand
// for FileIOPermission(PathDiscovery) succeeds, we need to make sure we
// don't store the stack trace string in the _stackTraceString member variable.
String tempStackTraceString = Environment.GetStackTrace(this, needFileInfo);
return remoteStackTraceString + tempStackTraceString;
}
[FriendAccessAllowed]
internal void SetErrorCode(int hr)
{
HResult = hr;
}
// Sets the help link for this exception.
// This should be in a URL/URN form, such as:
// "file:///C:/Applications/Bazzal/help.html#ErrorNum42"
// Changed to be a read-write String and not return an exception
public virtual String HelpLink
{
get
{
return _helpURL;
}
set
{
_helpURL = value;
}
}
public virtual String Source
{
get
{
if (_source == null)
{
StackTrace st = new StackTrace(this, true);
if (st.FrameCount > 0)
{
StackFrame sf = st.GetFrame(0);
MethodBase method = sf.GetMethod();
Module module = method.Module;
RuntimeModule rtModule = module as RuntimeModule;
if (rtModule == null)
{
System.Reflection.Emit.ModuleBuilder moduleBuilder = module as System.Reflection.Emit.ModuleBuilder;
if (moduleBuilder != null)
rtModule = moduleBuilder.InternalModule;
else
throw new ArgumentException(SR.Argument_MustBeRuntimeReflectionObject);
}
_source = rtModule.GetRuntimeAssembly().GetSimpleName();
}
}
return _source;
}
set { _source = value; }
}
public override String ToString()
{
return ToString(true, true);
}
private String ToString(bool needFileLineInfo, bool needMessage)
{
String message = (needMessage ? Message : null);
String s;
if (message == null || message.Length <= 0)
{
s = GetClassName();
}
else
{
s = GetClassName() + ": " + message;
}
if (_innerException != null)
{
s = s + " ---> " + _innerException.ToString(needFileLineInfo, needMessage) + Environment.NewLine +
" " + SR.Exception_EndOfInnerExceptionStack;
}
string stackTrace = GetStackTrace(needFileLineInfo);
if (stackTrace != null)
{
s += Environment.NewLine + stackTrace;
}
return s;
}
protected event EventHandler<SafeSerializationEventArgs> SerializeObjectState
{
add { throw new PlatformNotSupportedException(SR.PlatformNotSupported_SecureBinarySerialization); }
remove { throw new PlatformNotSupportedException(SR.PlatformNotSupported_SecureBinarySerialization); }
}
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
String tempStackTraceString = _stackTraceString;
if (_stackTrace != null)
{
if (tempStackTraceString == null)
{
tempStackTraceString = Environment.GetStackTrace(this, true);
}
if (_exceptionMethod == null)
{
_exceptionMethod = GetExceptionMethodFromStackTrace();
}
}
if (_source == null)
{
_source = Source; // Set the Source information correctly before serialization
}
info.AddValue("ClassName", GetClassName(), typeof(String)); // Do not rename (binary serialization)
info.AddValue("Message", _message, typeof(String)); // Do not rename (binary serialization)
info.AddValue("Data", _data, typeof(IDictionary)); // Do not rename (binary serialization)
info.AddValue("InnerException", _innerException, typeof(Exception)); // Do not rename (binary serialization)
info.AddValue("HelpURL", _helpURL, typeof(String)); // Do not rename (binary serialization)
info.AddValue("StackTraceString", tempStackTraceString, typeof(String)); // Do not rename (binary serialization)
info.AddValue("RemoteStackTraceString", _remoteStackTraceString, typeof(String)); // Do not rename (binary serialization)
info.AddValue("RemoteStackIndex", _remoteStackIndex, typeof(Int32)); // Do not rename (binary serialization)
info.AddValue("ExceptionMethod", null, typeof(String)); // Do not rename (binary serialization)
info.AddValue("HResult", HResult); // Do not rename (binary serialization)
info.AddValue("Source", _source, typeof(String)); // Do not rename (binary serialization)
// Serialize the Watson bucket details as well
info.AddValue("WatsonBuckets", _watsonBuckets, typeof(byte[])); // Do not rename (binary serialization)
}
// This method will clear the _stackTrace of the exception object upon deserialization
// to ensure that references from another AD/Process dont get accidentally used.
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
_stackTrace = null;
// We wont serialize or deserialize the IP for Watson bucketing since
// we dont know where the deserialized object will be used in.
// Using it across process or an AppDomain could be invalid and result
// in AV in the runtime.
//
// Hence, we set it to zero when deserialization takes place.
_ipForWatsonBuckets = UIntPtr.Zero;
}
// This is used by the runtime when re-throwing a managed exception. It will
// copy the stack trace to _remoteStackTraceString.
internal void InternalPreserveStackTrace()
{
string tmpStackTraceString;
#if FEATURE_APPX
if (AppDomain.IsAppXModel())
{
// Call our internal GetStackTrace in AppX so we can parse the result should
// we need to strip file/line info from it to make it PII-free. Calling the
// public and overridable StackTrace getter here was probably not intended.
tmpStackTraceString = GetStackTrace(true);
// Make sure that the _source field is initialized if Source is not overriden.
// We want it to contain the original faulting point.
string source = Source;
}
else
#else // FEATURE_APPX
// Preinitialize _source on CoreSystem as well. The legacy behavior is not ideal and
// we keep it for back compat but we can afford to make the change on the Phone.
string source = Source;
#endif // FEATURE_APPX
{
// Call the StackTrace getter in classic for compat.
tmpStackTraceString = StackTrace;
}
if (tmpStackTraceString != null && tmpStackTraceString.Length > 0)
{
_remoteStackTraceString = tmpStackTraceString + Environment.NewLine;
}
_stackTrace = null;
_stackTraceString = null;
}
// This is the object against which a lock will be taken
// when attempt to restore the EDI. Since its static, its possible
// that unrelated exception object restorations could get blocked
// for a small duration but that sounds reasonable considering
// such scenarios are going to be extremely rare, where timing
// matches precisely.
[OptionalField]
private static object s_EDILock = new object();
internal UIntPtr IPForWatsonBuckets
{
get
{
return _ipForWatsonBuckets;
}
}
internal object WatsonBuckets
{
get
{
return _watsonBuckets;
}
}
internal string RemoteStackTrace
{
get
{
return _remoteStackTraceString;
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void PrepareForForeignExceptionRaise();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void GetStackTracesDeepCopy(Exception exception, out object currentStackTrace, out object dynamicMethodArray);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void SaveStackTracesFromDeepCopy(Exception exception, object currentStackTrace, object dynamicMethodArray);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern object CopyStackTrace(object currentStackTrace);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern object CopyDynamicMethods(object currentDynamicMethods);
internal object DeepCopyStackTrace(object currentStackTrace)
{
if (currentStackTrace != null)
{
return CopyStackTrace(currentStackTrace);
}
else
{
return null;
}
}
internal object DeepCopyDynamicMethods(object currentDynamicMethods)
{
if (currentDynamicMethods != null)
{
return CopyDynamicMethods(currentDynamicMethods);
}
else
{
return null;
}
}
internal void GetStackTracesDeepCopy(out object currentStackTrace, out object dynamicMethodArray)
{
GetStackTracesDeepCopy(this, out currentStackTrace, out dynamicMethodArray);
}
// This is invoked by ExceptionDispatchInfo.Throw to restore the exception stack trace, corresponding to the original throw of the
// exception, just before the exception is "rethrown".
internal void RestoreExceptionDispatchInfo(System.Runtime.ExceptionServices.ExceptionDispatchInfo exceptionDispatchInfo)
{
bool fCanProcessException = !(IsImmutableAgileException(this));
// Restore only for non-preallocated exceptions
if (fCanProcessException)
{
// Take a lock to ensure only one thread can restore the details
// at a time against this exception object that could have
// multiple ExceptionDispatchInfo instances associated with it.
//
// We do this inside a finally clause to ensure ThreadAbort cannot
// be injected while we have taken the lock. This is to prevent
// unrelated exception restorations from getting blocked due to TAE.
try { }
finally
{
// When restoring back the fields, we again create a copy and set reference to them
// in the exception object. This will ensure that when this exception is thrown and these
// fields are modified, then EDI's references remain intact.
//
// Since deep copying can throw on OOM, try to get the copies
// outside the lock.
object _stackTraceCopy = (exceptionDispatchInfo.BinaryStackTraceArray == null) ? null : DeepCopyStackTrace(exceptionDispatchInfo.BinaryStackTraceArray);
object _dynamicMethodsCopy = (exceptionDispatchInfo.DynamicMethodArray == null) ? null : DeepCopyDynamicMethods(exceptionDispatchInfo.DynamicMethodArray);
// Finally, restore the information.
//
// Since EDI can be created at various points during exception dispatch (e.g. at various frames on the stack) for the same exception instance,
// they can have different data to be restored. Thus, to ensure atomicity of restoration from each EDI, perform the restore under a lock.
lock (Exception.s_EDILock)
{
_watsonBuckets = exceptionDispatchInfo.WatsonBuckets;
_ipForWatsonBuckets = exceptionDispatchInfo.IPForWatsonBuckets;
_remoteStackTraceString = exceptionDispatchInfo.RemoteStackTrace;
SaveStackTracesFromDeepCopy(this, _stackTraceCopy, _dynamicMethodsCopy);
}
_stackTraceString = null;
// Marks the TES state to indicate we have restored foreign exception
// dispatch information.
Exception.PrepareForForeignExceptionRaise();
}
}
}
private String _className; //Needed for serialization.
private MethodBase _exceptionMethod; //Needed for serialization.
private String _exceptionMethodString; //Needed for serialization.
internal String _message;
private IDictionary _data;
private Exception _innerException;
private String _helpURL;
private Object _stackTrace;
[OptionalField] // This isnt present in pre-V4 exception objects that would be serialized.
private Object _watsonBuckets;
private String _stackTraceString; //Needed for serialization.
private String _remoteStackTraceString;
private int _remoteStackIndex;
#pragma warning disable 414 // Field is not used from managed.
// _dynamicMethods is an array of System.Resolver objects, used to keep
// DynamicMethodDescs alive for the lifetime of the exception. We do this because
// the _stackTrace field holds MethodDescs, and a DynamicMethodDesc can be destroyed
// unless a System.Resolver object roots it.
private Object _dynamicMethods;
#pragma warning restore 414
// @MANAGED: HResult is used from within the EE! Rename with care - check VM directory
internal int _HResult; // HResult
public int HResult
{
get
{
return _HResult;
}
protected set
{
_HResult = value;
}
}
private String _source; // Mainly used by VB.
// WARNING: Don't delete/rename _xptrs and _xcode - used by functions
// on Marshal class. Native functions are in COMUtilNative.cpp & AppDomain
private IntPtr _xptrs; // Internal EE stuff
#pragma warning disable 414 // Field is not used from managed.
private int _xcode; // Internal EE stuff
#pragma warning restore 414
[OptionalField]
private UIntPtr _ipForWatsonBuckets; // Used to persist the IP for Watson Bucketing
// See src\inc\corexcep.h's EXCEPTION_COMPLUS definition:
private const int _COMPlusExceptionCode = unchecked((int)0xe0434352); // Win32 exception code for COM+ exceptions
// InternalToString is called by the runtime to get the exception text
// and create a corresponding CrossAppDomainMarshaledException
internal virtual String InternalToString()
{
// Get the current stack trace string.
return ToString(true, true);
}
// this method is required so Object.GetType is not made virtual by the compiler
// _Exception.GetType()
public new Type GetType()
{
return base.GetType();
}
internal bool IsTransient
{
get
{
return nIsTransient(_HResult);
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static bool nIsTransient(int hr);
// This piece of infrastructure exists to help avoid deadlocks
// between parts of mscorlib that might throw an exception while
// holding a lock that are also used by mscorlib's ResourceManager
// instance. As a special case of code that may throw while holding
// a lock, we also need to fix our asynchronous exceptions to use
// Win32 resources as well (assuming we ever call a managed
// constructor on instances of them). We should grow this set of
// exception messages as we discover problems, then move the resources
// involved to native code.
internal enum ExceptionMessageKind
{
ThreadAbort = 1,
ThreadInterrupted = 2,
OutOfMemory = 3
}
// See comment on ExceptionMessageKind
internal static String GetMessageFromNativeResources(ExceptionMessageKind kind)
{
string retMesg = null;
GetMessageFromNativeResources(kind, JitHelpers.GetStringHandleOnStack(ref retMesg));
return retMesg;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetMessageFromNativeResources(ExceptionMessageKind kind, StringHandleOnStack retMesg);
}
//--------------------------------------------------------------------------
// Telesto: Telesto doesn't support appdomain marshaling of objects so
// managed exceptions that leak across appdomain boundaries are flatted to
// its ToString() output and rethrown as an CrossAppDomainMarshaledException.
// The Message field is set to the ToString() output of the original exception.
//--------------------------------------------------------------------------
internal sealed class CrossAppDomainMarshaledException : SystemException
{
public CrossAppDomainMarshaledException(String message, int errorCode)
: base(message)
{
HResult = errorCode;
}
// Normally, only Telesto's UEF will see these exceptions.
// This override prints out the original Exception's ToString()
// output and hides the fact that it is wrapped inside another excepton.
internal override String InternalToString()
{
return Message;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Xml;
namespace OpenSim.Server.Handlers.Authentication
{
public class AuthenticationServerPostHandler : BaseStreamHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool m_AllowGetAuthInfo = false;
private bool m_AllowSetAuthInfo = false;
private bool m_AllowSetPassword = false;
private IAuthenticationService m_AuthenticationService;
public AuthenticationServerPostHandler(IAuthenticationService service) :
this(service, null) { }
public AuthenticationServerPostHandler(IAuthenticationService service, IConfig config) :
base("POST", "/auth")
{
m_AuthenticationService = service;
if (config != null)
{
m_AllowGetAuthInfo = config.GetBoolean("AllowGetAuthInfo", m_AllowGetAuthInfo);
m_AllowSetAuthInfo = config.GetBoolean("AllowSetAuthInfo", m_AllowSetAuthInfo);
m_AllowSetPassword = config.GetBoolean("AllowSetPassword", m_AllowSetPassword);
}
}
protected override byte[] ProcessRequest(string path, Stream request,
IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
string[] p = SplitParams(path);
if (p.Length > 0)
{
switch (p[0])
{
case "plain":
StreamReader sr = new StreamReader(request);
string body = sr.ReadToEnd();
sr.Close();
return DoPlainMethods(body);
case "crypt":
byte[] buffer = new byte[request.Length];
long length = request.Length;
if (length > 16384)
length = 16384;
request.Read(buffer, 0, (int)length);
return DoEncryptedMethods(buffer);
}
}
return new byte[0];
}
private byte[] DocToBytes(XmlDocument doc)
{
MemoryStream ms = new MemoryStream();
XmlTextWriter xw = new XmlTextWriter(ms, null);
xw.Formatting = Formatting.Indented;
doc.WriteTo(xw);
xw.Flush();
return ms.GetBuffer();
}
private byte[] DoEncryptedMethods(byte[] ciphertext)
{
return new byte[0];
}
private byte[] DoPlainMethods(string body)
{
Dictionary<string, object> request =
ServerUtils.ParseQueryString(body);
int lifetime = 30;
if (request.ContainsKey("LIFETIME"))
{
lifetime = Convert.ToInt32(request["LIFETIME"].ToString());
if (lifetime > 30)
lifetime = 30;
}
if (!request.ContainsKey("METHOD"))
return FailureResult();
if (!request.ContainsKey("PRINCIPAL"))
return FailureResult();
string method = request["METHOD"].ToString();
UUID principalID;
string token;
if (!UUID.TryParse(request["PRINCIPAL"].ToString(), out principalID))
return FailureResult();
switch (method)
{
case "authenticate":
if (!request.ContainsKey("PASSWORD"))
return FailureResult();
token = m_AuthenticationService.Authenticate(principalID, request["PASSWORD"].ToString(), lifetime);
if (token != String.Empty)
return SuccessResult(token);
return FailureResult();
case "setpassword":
if (!m_AllowSetPassword)
return FailureResult();
if (!request.ContainsKey("PASSWORD"))
return FailureResult();
if (m_AuthenticationService.SetPassword(principalID, request["PASSWORD"].ToString()))
return SuccessResult();
else
return FailureResult();
case "verify":
if (!request.ContainsKey("TOKEN"))
return FailureResult();
if (m_AuthenticationService.Verify(principalID, request["TOKEN"].ToString(), lifetime))
return SuccessResult();
return FailureResult();
case "release":
if (!request.ContainsKey("TOKEN"))
return FailureResult();
if (m_AuthenticationService.Release(principalID, request["TOKEN"].ToString()))
return SuccessResult();
return FailureResult();
case "getauthinfo":
if (m_AllowGetAuthInfo)
return GetAuthInfo(principalID);
break;
case "setauthinfo":
if (m_AllowSetAuthInfo)
return SetAuthInfo(principalID, request);
break;
}
return FailureResult();
}
private byte[] FailureResult()
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "Result", "");
result.AppendChild(doc.CreateTextNode("Failure"));
rootElement.AppendChild(result);
return DocToBytes(doc);
}
private byte[] GetAuthInfo(UUID principalID)
{
AuthInfo info = m_AuthenticationService.GetAuthInfo(principalID);
if (info != null)
{
Dictionary<string, object> result = new Dictionary<string, object>();
result["result"] = info.ToKeyValuePairs();
return ResultToBytes(result);
}
else
{
return FailureResult();
}
}
private byte[] ResultToBytes(Dictionary<string, object> result)
{
string xmlString = ServerUtils.BuildXmlResponse(result);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
private byte[] SetAuthInfo(UUID principalID, Dictionary<string, object> request)
{
AuthInfo existingInfo = m_AuthenticationService.GetAuthInfo(principalID);
if (existingInfo == null)
return FailureResult();
if (request.ContainsKey("AccountType"))
existingInfo.AccountType = request["AccountType"].ToString();
if (request.ContainsKey("PasswordHash"))
existingInfo.PasswordHash = request["PasswordHash"].ToString();
if (request.ContainsKey("PasswordSalt"))
existingInfo.PasswordSalt = request["PasswordSalt"].ToString();
if (request.ContainsKey("WebLoginKey"))
existingInfo.WebLoginKey = request["WebLoginKey"].ToString();
if (!m_AuthenticationService.SetAuthInfo(existingInfo))
{
m_log.ErrorFormat(
"[AUTHENTICATION SERVER POST HANDLER]: Authentication info store failed for account {0} {1} {2}",
existingInfo.PrincipalID);
return FailureResult();
}
return SuccessResult();
}
private byte[] SuccessResult()
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "Result", "");
result.AppendChild(doc.CreateTextNode("Success"));
rootElement.AppendChild(result);
return DocToBytes(doc);
}
private byte[] SuccessResult(string token)
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "Result", "");
result.AppendChild(doc.CreateTextNode("Success"));
rootElement.AppendChild(result);
XmlElement t = doc.CreateElement("", "Token", "");
t.AppendChild(doc.CreateTextNode(token));
rootElement.AppendChild(t);
return DocToBytes(doc);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using Microsoft.Web.Administration;
namespace ConDep.PowerShell.ArrLoadBalancer.Infrastructure
{
public class WebFarmManager
{
private readonly string _farm;
private readonly string _server;
private readonly bool _useDnsLookup;
private IEnumerable<Farm> _farms;
private readonly bool _noParams;
private IEnumerable<FarmServer> _farmServers;
private delegate bool WaitCondition(Counters counters);
public WebFarmManager()
{
_noParams = true;
}
public WebFarmManager(string farm, string server, bool useDnsLookup)
{
ValidateParams(server, useDnsLookup);
_farm = farm;
_server = server;
_useDnsLookup = useDnsLookup;
}
private static void ValidateParams(string server, bool useDnsLookup)
{
if (!useDnsLookup) return;
if (string.IsNullOrEmpty(server))
{
throw new Exception("When using DNS lookup, Web Farm Server (Name) must be provided.");
}
if (WildcardPattern.ContainsWildcard(server))
{
throw new Exception("You can not use DNS lookup together with wildcards (*) in server name.");
}
}
public IEnumerable<Farm> Farms
{
get { return _farms ?? GetWebFarms(_farm, _server, _useDnsLookup); }
}
public IEnumerable<FarmServer> FarmServers
{
get
{
if(_farmServers == null)
{
_farmServers = new List<FarmServer>();
foreach (var farm in Farms)
{
((List<FarmServer>)_farmServers).AddRange(farm.Servers);
}
}
return _farmServers;
}
}
public IEnumerable<FarmServerStats> SetAvailable(Action<object> writeObject)
{
return ChangeState(x => x.MakeServerAvailable(), writeObject);
}
public IEnumerable<FarmServerStats> SetUnavailable(bool force, Action<object> writeObject)
{
return force ? ChangeState(x => x.MakeServerUnavailable(), writeObject) : ChangeState(x => x.MakeServerUnavailableGracefully(), writeObject);
}
public IEnumerable<FarmServerStats> DisallowNewConnections(Action<object> writeObject)
{
return ChangeState(x => x.DisallowNewConnections(), writeObject);
}
public IEnumerable<FarmServerStats> SetHealthy(Action<object> writeObject)
{
return ChangeState(x => x.MakeServerHealthy(), writeObject);
}
public IEnumerable<FarmServerStats> SetUnhealthy(Action<object> writeObject)
{
return ChangeState(x => x.MakeServerUnhealthy(), writeObject);
}
public IEnumerable<FarmServerStats> TakeOffline(bool force, Action<object> writeObject)
{
if(!force)
{
ChangeState(x => x.MakeServerUnavailableGracefully(), null, y => y.CurrentRequests > 0);
}
return ChangeState(x => x.TakeServerOffline(), writeObject);
}
public IEnumerable<FarmServerStats> TakeOnline(Action<object> writeObject)
{
ChangeState(x => x.BringServerOnline());
return ChangeState(x => x.MakeServerAvailable(), writeObject, y => y.State != FarmServerState.Available);
}
private IEnumerable<FarmServerStats> ChangeState(Action<StateExecutor> changeState, Action<object> writeObject = null, WaitCondition waitCondition = null)
{
var stats = new List<FarmServerStats>();
foreach (var farm in Farms)
{
foreach (var server in farm.Servers)
{
using (var arr = new ArrServerManager(server.WebFarm, server.Name))
{
changeState(arr.StateExecutor);
arr.Commit();
if(waitCondition != null)
{
while(waitCondition(arr.Counters))
{
Thread.Sleep(100);
}
}
if(writeObject != null)
{
writeObject(arr.Counters.GetServerStats());
}
}
}
}
return stats;
}
private IEnumerable<Farm> GetWebFarms(string farm, string server, bool useDnsLookup)
{
if (_noParams)
{
return FindAllWebFarms();
}
if (!string.IsNullOrEmpty(farm))
{
if (!string.IsNullOrEmpty(server))
{
var f = new Farm { Name = farm };
f.Servers.Add(new FarmServer { Name = server, WebFarm = farm });
return new[] { f };
}
return GetWebFarm(farm);
}
return !string.IsNullOrEmpty(server) ? GetWebFarmsByServer(server, useDnsLookup) : FindAllWebFarms();
}
private static IEnumerable<Farm> GetWebFarm(string farmName)
{
using (var serverManager = new ServerManager())
{
var config = serverManager.GetApplicationHostConfiguration();
var webFarmsSection = config.GetSection("webFarms");
var foundFarmServers = new List<Farm>();
foreach (var webFarm in webFarmsSection.GetCollection())
{
if (farmName.ToLower() != webFarm["name"].ToString().ToLower()) continue;
var farm = new Farm { Name = webFarm["name"].ToString() };
foreach (var server in webFarm.GetCollection())
{
farm.Servers.Add(new FarmServer { WebFarm = farm.Name, Name = server["address"].ToString() });
}
foundFarmServers.Add(farm);
}
return foundFarmServers;
}
}
private static IEnumerable<Farm> FindAllWebFarms()
{
using (var serverManager = new ServerManager())
{
var config = serverManager.GetApplicationHostConfiguration();
var webFarmsSection = config.GetSection("webFarms");
var foundFarmServers = new List<Farm>();
foreach (var webFarm in webFarmsSection.GetCollection())
{
var farm = new Farm
{
Name = webFarm["name"].ToString()
};
foreach (var server in webFarm.GetCollection())
{
farm.Servers.Add(new FarmServer {WebFarm = farm.Name, Name = server["address"].ToString()});
}
foundFarmServers.Add(farm);
}
return foundFarmServers;
}
}
//Todo: Needs refactoring together with FindAllWebFarms, GetWebFarm and GetWebFarms
private static IEnumerable<Farm> GetWebFarmsByServer(string serverName, bool useDnsLookup)
{
using (var serverManager = new ServerManager())
{
var config = serverManager.GetApplicationHostConfiguration();
var webFarmsSection = config.GetSection("webFarms");
var foundFarms = new List<Farm>();
var servers = new List<string>();
if(useDnsLookup)
{
var ips = Dns.GetHostAddresses(serverName);
foreach(var ip in ips)
{
servers.Add(ip.ToString());
}
}
else
{
servers.Add(serverName.ToLower());
}
foreach (var webFarm in webFarmsSection.GetCollection())
{
foreach (var server in webFarm.GetCollection())
{
var webFarmServerAddress = server["address"].ToString();
if (WildcardPattern.ContainsWildcard(serverName))
{
var serverAddress = server["address"].ToString();
var wildcardPattern = new WildcardPattern(serverName);
if(wildcardPattern.IsMatch(serverAddress))
{
var farm = new Farm { Name = webFarm["name"].ToString() };
farm.Servers.Add(new FarmServer
{
Name = server["address"].ToString(),
WebFarm = webFarm["name"].ToString()
});
foundFarms.Add(farm);
}
}
else if (servers.Contains(webFarmServerAddress.ToLower()))
{
var farm = new Farm {Name = webFarm["name"].ToString()};
farm.Servers.Add(new FarmServer
{
Name = server["address"].ToString(),
WebFarm = webFarm["name"].ToString()
});
foundFarms.Add(farm);
if(servers.Count == 1)
{
break;
}
}
}
}
return foundFarms;
}
}
}
}
| |
// 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.Reflection;
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 MaskStoreSingle()
{
var test = new StoreBinaryOpTest__MaskStoreSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class StoreBinaryOpTest__MaskStoreSingle
{
private struct TestStruct
{
public Vector128<Single> _fld1;
public Vector128<Single> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
return testStruct;
}
public void RunStructFldScenario(StoreBinaryOpTest__MaskStoreSingle testClass)
{
Avx.MaskStore((Single*)testClass._dataTable.outArrayPtr, _fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private SimpleBinaryOpTest__DataTable<Single, Single, Single> _dataTable;
static StoreBinaryOpTest__MaskStoreSingle()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
}
public StoreBinaryOpTest__MaskStoreSingle()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new SimpleBinaryOpTest__DataTable<Single, Single, Single>(_data1, _data2, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
Avx.MaskStore(
(Single*)_dataTable.outArrayPtr,
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
Avx.MaskStore(
(Single*)_dataTable.outArrayPtr,
Avx.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadVector128((Single*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
Avx.MaskStore(
(Single*)_dataTable.outArrayPtr,
Avx.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
typeof(Avx).GetMethod(nameof(Avx.MaskStore), new Type[] { typeof(Single*), typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Pointer.Box(_dataTable.outArrayPtr, typeof(Single*)),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
typeof(Avx).GetMethod(nameof(Avx.MaskStore), new Type[] { typeof(Single*), typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Pointer.Box(_dataTable.outArrayPtr, typeof(Single*)),
Avx.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadVector128((Single*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
typeof(Avx).GetMethod(nameof(Avx.MaskStore), new Type[] { typeof(Single*), typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Pointer.Box(_dataTable.outArrayPtr, typeof(Single*)),
Avx.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
Avx.MaskStore(
(Single*)_dataTable.outArrayPtr,
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
Avx.MaskStore((Single*)_dataTable.outArrayPtr, left, right);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var left = Avx.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector128((Single*)(_dataTable.inArray2Ptr));
Avx.MaskStore((Single*)_dataTable.outArrayPtr, left, right);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var left = Avx.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr));
Avx.MaskStore((Single*)_dataTable.outArrayPtr, left, right);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new StoreBinaryOpTest__MaskStoreSingle();
Avx.MaskStore((Single*)_dataTable.outArrayPtr, test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
Avx.MaskStore((Single*)_dataTable.outArrayPtr, _fld1, _fld2);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
Avx.MaskStore((Single*)_dataTable.outArrayPtr, test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), left);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits((BitConverter.SingleToInt32Bits(left[0]) < 0) ? right[0] : BitConverter.SingleToInt32Bits(result[0])))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits((BitConverter.SingleToInt32Bits(left[i]) < 0) ? right[i] : BitConverter.SingleToInt32Bits(result[i])))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.MaskStore)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* 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 InsertInt641()
{
var test = new SimpleUnaryOpTest__InsertInt641();
try
{
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();
}
}
catch (PlatformNotSupportedException)
{
test.Succeeded = true;
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__InsertInt641
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Int64);
private const int RetElementCount = VectorSize / sizeof(Int64);
private static Int64[] _data = new Int64[Op1ElementCount];
private static Vector128<Int64> _clsVar;
private Vector128<Int64> _fld;
private SimpleUnaryOpTest__DataTable<Int64, Int64> _dataTable;
static SimpleUnaryOpTest__InsertInt641()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (long)0; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar), ref Unsafe.As<Int64, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__InsertInt641()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (long)0; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld), ref Unsafe.As<Int64, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (long)0; }
_dataTable = new SimpleUnaryOpTest__DataTable<Int64, Int64>(_data, new Int64[RetElementCount], VectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse41.Insert(
Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr),
(long)2,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse41.Insert(
Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr)),
(long)2,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse41.Insert(
Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr)),
(long)2,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Int64>), typeof(Int64), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr),
(long)2,
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Int64>), typeof(Int64), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr)),
(long)2,
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Int64>), typeof(Int64), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr)),
(long)2,
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse41.Insert(
_clsVar,
(long)2,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr);
var result = Sse41.Insert(firstOp, (long)2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr));
var result = Sse41.Insert(firstOp, (long)2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr));
var result = Sse41.Insert(firstOp, (long)2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__InsertInt641();
var result = Sse41.Insert(test._fld, (long)2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse41.Insert(_fld, (long)2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Int64> firstOp, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray = new Int64[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray = new Int64[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int64[] firstOp, Int64[] result, [CallerMemberName] string method = "")
{
for (var i = 0; i < RetElementCount; i++)
{
if ((i == 1 ? result[i] != 2 : result[i] != 0))
{
Succeeded = false;
break;
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.Insert)}<Int64>(Vector128<Int64><9>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Java.Lang;
using Android.App;
using Android.Content;
using Android.Graphics;
using Android.Media;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace LeanCloud.Internal {
/// <summary>
/// A simple implementation of the NotificationCompat class from Android.Support.V4.
/// </summary>
/// <remarks>
/// It only differentiates between devices before and after JellyBean because the only extra feature
/// that we currently support between the two device types is BigTextStyle notifications.
/// This class takes advantage of lazy class loading to eliminate warnings of type
/// 'Could not find class...'
/// </remarks>
internal class NotificationCompat {
#pragma warning disable 612, 618
public const int PriorityDefault = 0;
private static NotificationCompatImpl impl;
private static NotificationCompatImpl Impl {
get {
if (impl == null) {
if (Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.JellyBean) {
impl = new NotificationCompatPostJellyBean();
} else {
impl = new NotificationCompatImplBase();
}
}
return impl;
}
}
public interface NotificationCompatImpl {
Notification Build(Builder b);
}
internal class NotificationCompatImplBase : NotificationCompatImpl {
public Notification Build(Builder b) {
Notification result = b.Notification;
result.SetLatestEventInfo(b.Context, b.ContentTitle, b.ContentText, b.ContentIntent);
return result;
}
}
internal class NotificationCompatPostJellyBean : NotificationCompatImpl {
public Notification Build(Builder b) {
Notification.Builder builder = new Notification.Builder(b.Context);
builder.SetContentTitle(b.ContentTitle)
.SetContentText(b.ContentText)
.SetTicker(b.Notification.TickerText)
.SetSmallIcon(b.Notification.Icon, b.Notification.IconLevel)
.SetContentIntent(b.ContentIntent)
.SetDeleteIntent(b.Notification.DeleteIntent)
.SetAutoCancel((b.Notification.Flags & NotificationFlags.AutoCancel) != 0)
.SetLargeIcon(b.LargeIcon)
.SetDefaults(b.Notification.Defaults);
if (b.Style != null) {
if (b.Style is BigTextStyle) {
BigTextStyle staticStyle = b.Style as BigTextStyle;
Notification.BigTextStyle style = new Notification.BigTextStyle(builder);
style.SetBigContentTitle(staticStyle.BigContentTitle)
.BigText(staticStyle.bigText);
if (staticStyle.SummaryTextSet) {
style.SetSummaryText(staticStyle.SummaryText);
}
}
}
return builder.Build();
}
}
/// <summary>
/// Builder class for <see cref="NotificationCompat"/> objects.
/// </summary>
/// <seealso href="http://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html"/>
/// <remarks>
/// Allows easier control over all the flags, as well as help constructing the typical notification layouts.
/// </remarks>
public class Builder {
private const int MaxCharSequenceLength = 5 * 1024;
public Context Context { get; private set; }
public ICharSequence ContentTitle { get; private set; }
public ICharSequence ContentText { get; private set; }
public PendingIntent ContentIntent { get; private set; }
public Bitmap LargeIcon { get; private set; }
public int Priority { get; private set; }
public Style Style { get; private set; }
[Obsolete]
public Notification Notification { get; private set; }
public Builder(Context context) {
Context = context;
Notification = new Notification();
Notification.When = Java.Lang.JavaSystem.CurrentTimeMillis();
Notification.AudioStreamType = Stream.NotificationDefault;
Priority = PriorityDefault;
}
public Builder SetWhen(long when) {
Notification.When = when;
return this;
}
public Builder SetSmallIcon(int icon) {
Notification.Icon = icon;
return this;
}
public Builder SetSmallIcon(int icon, int iconLevel) {
Notification.Icon = icon;
Notification.IconLevel = iconLevel;
return this;
}
public Builder SetContentTitle(ICharSequence title) {
ContentTitle = limitCharSequenceLength(title);
return this;
}
public Builder SetContentText(ICharSequence text) {
ContentText = limitCharSequenceLength(text);
return this;
}
public Builder SetContentIntent(PendingIntent intent) {
ContentIntent = intent;
return this;
}
public Builder SetDeleteIntent(PendingIntent intent) {
Notification.DeleteIntent = intent;
return this;
}
public Builder SetTicker(ICharSequence tickerText) {
Notification.TickerText = limitCharSequenceLength(tickerText);
return this;
}
public Builder SetLargeIcon(Bitmap icon) {
LargeIcon = icon;
return this;
}
public Builder SetAutoCancel(bool autoCancel) {
setFlag(NotificationFlags.AutoCancel, autoCancel);
return this;
}
public Builder SetDefaults(NotificationDefaults defaults) {
Notification.Defaults = defaults;
if ((defaults & NotificationDefaults.Lights) != 0) {
Notification.Flags |= NotificationFlags.ShowLights;
}
return this;
}
private void setFlag(NotificationFlags mask, bool value) {
if (value) {
Notification.Flags |= mask;
} else {
Notification.Flags &= ~mask;
}
}
public Builder SetPriority(int pri) {
Priority = pri;
return this;
}
public Builder SetStyle(Style style) {
if (Style != style) {
Style = style;
if (Style != null) {
Style.SetBuilder(this);
}
}
return this;
}
public Notification Build() {
return Impl.Build(this);
}
private static ICharSequence limitCharSequenceLength(ICharSequence cs) {
if (cs == null) {
return cs;
}
if (cs.Length() > MaxCharSequenceLength) {
cs = cs.SubSequenceFormatted(0, MaxCharSequenceLength);
}
return cs;
}
}
/// <summary>
/// An object that can apply a rich notification style to a <see cref="NotificationCompat.Builder"/> object.
/// </summary>
public abstract class Style {
protected Builder builder;
public ICharSequence BigContentTitle { get; protected set; }
public ICharSequence SummaryText { get; protected set; }
private bool summaryTextSet = false;
public bool SummaryTextSet {
get { return summaryTextSet; }
protected set { summaryTextSet = value; }
}
public void SetBuilder(Builder builder) {
if (this.builder != builder) {
this.builder = builder;
if (this.builder != null) {
this.builder.SetStyle(this);
}
}
}
public Notification Build() {
Notification notification = null;
if (builder != null) {
notification = builder.Build();
}
return notification;
}
}
public class BigTextStyle : Style {
internal ICharSequence bigText;
public BigTextStyle() {
}
public BigTextStyle(Builder builder) {
SetBuilder(builder);
}
/// <summary>
/// Overrides <see cref="Builder.ContentTitle"/> in the big form of the template.
/// </summary>
/// <remarks>
/// This defaults to the value passed to SetContentTitle().
/// </remarks>
/// <param name="title"></param>
/// <returns></returns>
public BigTextStyle SetBigContentTitle(ICharSequence title) {
BigContentTitle = title;
return this;
}
/// <summary>
/// Set the first line of text after the detail section in the big form of the template.
/// </summary>
/// <param name="summaryText"></param>
/// <returns></returns>
public BigTextStyle SetSummaryText(ICharSequence summaryText) {
SummaryText = summaryText;
SummaryTextSet = true;
return this;
}
/// <summary>
/// Provide the longer text to be displayed in the big form of the
/// template in place of the content text.
/// </summary>
/// <param name="bigText"></param>
/// <returns></returns>
public BigTextStyle BigText(ICharSequence bigText) {
this.bigText = bigText;
return this;
}
}
}
#pragma warning restore 612, 618
}
| |
/*
* MindTouch Dream - a distributed REST framework
* Copyright (C) 2006-2014 MindTouch, Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit mindtouch.com;
* please review the licensing section.
*
* 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;
using System.Collections.Generic;
using System.Threading;
namespace MindTouch.Collections {
/// <summary>
/// Exception thrown by <see cref="BlockingQueue{T}.Enqueue"/> and <see cref="BlockingQueue{T}.Dequeue"/> when the underlying queue has already been closed.
/// </summary>
public class QueueClosedException : Exception {
/// <summary>
/// Create a new exception instance.
/// </summary>
public QueueClosedException() : base("BlockingQueue has already been closed") { }
}
/// <summary>
/// Provides a thread-safe queue that blocks on queue and dequeue operations under lock contention or when no items are available.
/// </summary>
/// <typeparam name="T">Type of the data items in the queue</typeparam>
public interface IBlockingQueue<T> : IEnumerable<T> {
//--- Properties ---
/// <summary>
/// <see langword="True"/> when the queue has been closed and can no longer accept new items, <see langword="False"/> otherwise.
/// </summary>
bool IsClosed { get; }
/// <summary>
/// Total number of items currently in the queue.
/// </summary>
int Count { get; }
//--- Methods ---
/// <summary>
/// Attempt to dequeue an item from the queue.
/// </summary>
/// <remarks>Dequeue timeout can occur either because a lock could not be acquired or because no item was available.</remarks>
/// <param name="timeout">Time to wait for an item to become available.</param>
/// <param name="item">The location for a dequeue item.</param>
/// <returns><see langword="True"/> if an item was dequeued, <see langword="False"/> if the operation timed out instead.</returns>
bool TryDequeue(TimeSpan timeout, out T item);
/// <summary>
/// Blocking dequeue operation. Will not return until an item is available.
/// </summary>
/// <returns>A data item.</returns>
/// <exception cref="QueueClosedException">Thrown when the queue is closed and has no more items.</exception>
T Dequeue();
/// <summary>
/// Enqueue a new item into the queue.
/// </summary>
/// <param name="data">A data item.</param>
/// <exception cref="QueueClosedException">Thrown when the queue is closed and does not accept new items.</exception>
void Enqueue(T data);
/// <summary>
/// Close the queue and stop it from accepting more items.
/// </summary>
/// <remarks>Pending items can still be dequeued.</remarks>
void Close();
}
/// <summary>
/// Provides a thread-safe queue that blocks on queue and dequeue operations under lock contention or when no items are available.
/// </summary>
/// <typeparam name="T">Type of the data items in the queue</typeparam>
public class BlockingQueue<T> : IBlockingQueue<T> {
//--- Class Fields ---
private static readonly log4net.ILog _log = LogUtils.CreateLog();
//--- Fields ---
private readonly Queue<T> _queue = new Queue<T>();
private bool _closed;
//--- Properties ---
/// <summary>
/// <see langword="True"/> when the queue has been closed and can no longer accept new items, <see langword="False"/> otherwise.
/// </summary>
public bool IsClosed { get { return _closed; } }
/// <summary>
/// Total number of items currently in the queue.
/// </summary>
public int Count { get { lock(_queue) return _queue.Count; } }
//--- Methods ----
/// <summary>
/// Blocking dequeue operation. Will not return until an item is available.
/// </summary>
/// <returns>A data item.</returns>
/// <exception cref="QueueClosedException">Thrown when the queue is closed and has no more items.</exception>
public T Dequeue() {
T returnValue;
if(!TryDequeue(TimeSpan.FromMilliseconds(-1), out returnValue)) {
throw new QueueClosedException();
}
return returnValue;
}
/// <summary>
/// Attempt to dequeue an item from the queue.
/// </summary>
/// <remarks>Dequeue timeout can occur either because a lock could not be acquired or because no item was available.</remarks>
/// <param name="timeout">Time to wait for an item to become available.</param>
/// <param name="item">The location for a dequeue item.</param>
/// <returns><see langword="True"/> if an item was dequeued, <see langword="False"/> if the operation timed out instead.</returns>
public bool TryDequeue(TimeSpan timeout, out T item) {
item = default(T);
if(IsClosed && _queue.Count == 0) {
_log.Debug("dropping out of dequeue, queue is empty and closed (1)");
return false;
}
lock(_queue) {
while(_queue.Count == 0 && !IsClosed) {
if(!Monitor.Wait(_queue, timeout, false)) {
_log.Debug("dropping out of dequeue, timed out");
return false;
}
}
if(_queue.Count == 0 && IsClosed) {
_log.Debug("dropping out of dequeue, queue is empty and closed (2)");
return false;
}
item = _queue.Dequeue();
return true;
}
}
/// <summary>
/// Enqueue a new item into the queue.
/// </summary>
/// <param name="data">A data item.</param>
/// <exception cref="QueueClosedException">Thrown when the queue is closed and does not accept new items.</exception>
public void Enqueue(T data) {
if(_closed) {
throw new InvalidOperationException("cannot enqueue new items on a closed queue");
}
lock(_queue) {
_queue.Enqueue(data);
Monitor.PulseAll(_queue);
}
}
/// <summary>
/// Close the queue and stop it from accepting more items.
/// </summary>
/// <remarks>Pending items can still be dequeued.</remarks>
public void Close() {
_log.Debug("closing queue");
_closed = true;
lock(_queue) {
Monitor.PulseAll(_queue);
}
}
//--- IEnumerable<T> Members ---
IEnumerator<T> IEnumerable<T>.GetEnumerator() {
while(true) {
T returnValue;
if(!TryDequeue(TimeSpan.FromMilliseconds(-1), out returnValue)) {
yield break;
}
yield return returnValue;
}
}
//--- IEnumerable Members ---
IEnumerator IEnumerable.GetEnumerator() {
return ((IEnumerable<T>)this).GetEnumerator();
}
}
}
| |
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using System.Globalization;
namespace Signum.Engine.Excel;
public static class ExcelExtensions
{
public static string ToExcelDate(DateTime datetime)
{
return datetime.ToUserInterface().ToOADate().ToString(CultureInfo.InvariantCulture); //Convert to Julean Format
}
public static string ToExcelTime(TimeOnly timeOnly)
{
return timeOnly.ToTimeSpan().TotalDays.ToString(CultureInfo.InvariantCulture);
}
public static DateTime FromExcelDate(string datetime)
{
return DateTime.FromOADate(double.Parse(datetime, CultureInfo.InvariantCulture)).FromUserInterface(); //Convert to Julean Format
}
public static string ToExcelNumber(decimal number)
{
return number.ToString(CultureInfo.InvariantCulture);
}
public static decimal FromExcelNumber(string number)
{
return decimal.Parse(number, CultureInfo.InvariantCulture);
}
public static SheetData ToSheetData(this IEnumerable<Row> rows)
{
return new SheetData(rows.Cast<OpenXmlElement>());
}
public static Row ToRow(this IEnumerable<Cell> rows)
{
return new Row(rows.Cast<OpenXmlElement>());
}
public static WorksheetPart AddWorksheet(this WorkbookPart workbookPart, string name, Worksheet sheet)
{
sheet.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
var result = workbookPart.AddNewPart<WorksheetPart>();
result.Worksheet = sheet;
sheet.Save();
workbookPart.Workbook.Sheets!.Append(
new Sheet
{
Name = name,
SheetId = (uint)workbookPart.Workbook.Sheets.Count() + 1,
Id = workbookPart.GetIdOfPart(result)
});
return result;
}
public static void XLDeleteSheet(this SpreadsheetDocument document, string sheetId)
{
WorkbookPart wbPart = document.WorkbookPart!;
Sheet? theSheet = wbPart.Workbook.Descendants<Sheet>().
Where(s => s.Id == sheetId).FirstOrDefault();
if (theSheet == null)
return;
// Remove the sheet reference from the workbook.
WorksheetPart worksheetPart = (WorksheetPart)(wbPart.GetPartById(theSheet.Id!));
theSheet.Remove();
// Delete the worksheet part.
wbPart.DeletePart(worksheetPart);
}
public static Cell FindCell(this Worksheet worksheet, string addressName)
{
return worksheet.Descendants<Cell>().FirstEx(c => c.CellReference == addressName);
}
public static Cell FindCell(this SheetData sheetData, string addressName)
{
return sheetData.Descendants<Cell>().FirstEx(c => c.CellReference == addressName);
}
public static string GetCellValue(this SpreadsheetDocument document, Worksheet worksheet, string addressName)
{
Cell? theCell = worksheet.Descendants<Cell>().
Where(c => c.CellReference == addressName).FirstOrDefault();
// If the cell doesn't exist, return an empty string:
if (theCell == null)
return "";
return GetCellValue(document, theCell);
}
public static string GetCellValue(this SpreadsheetDocument document, Cell theCell)
{
string value = theCell.InnerText;
// If the cell represents an integer number, you're done.
// For dates, this code returns the serialized value that
// represents the date. The code handles strings and booleans
// individually. For shared strings, the code looks up the corresponding
// value in the shared string table. For booleans, the code converts
// the value into the words TRUE or FALSE.
if (theCell.DataType == null)
return value;
switch (theCell.DataType.Value)
{
case CellValues.SharedString:
// For shared strings, look up the value in the shared strings table.
var stringTable = document.WorkbookPart!.GetPartsOfType<SharedStringTablePart>().FirstOrDefault();
// If the shared string table is missing, something's wrong.
// Just return the index that you found in the cell.
// Otherwise, look up the correct text in the table.
if (stringTable != null)
return stringTable.SharedStringTable.ElementAt(int.Parse(value)).InnerText;
break;
case CellValues.Boolean:
switch (value)
{
case "0":
return "FALSE";
default:
return "TRUE";
}
//break;
}
return value;
}
public static void SetCellValue(this Cell cell, object? value, Type type)
{
if(type == typeof(string))
{
cell.RemoveAllChildren();
cell.Append(new InlineString(new Text((string?)value!)));
cell.DataType = CellValues.InlineString;
}
else
{
string excelValue = value == null ? "" :
type.UnNullify() == typeof(DateTime) ? ExcelExtensions.ToExcelDate(((DateTime)value)) :
type.UnNullify() == typeof(bool) ? (((bool)value) ? "TRUE": "FALSE") :
IsNumber(type.UnNullify()) ? ExcelExtensions.ToExcelNumber(Convert.ToDecimal(value)) :
value.ToString()!;
cell.CellValue = new CellValue(excelValue);
}
}
private static bool IsNumber(Type type)
{
switch (Type.GetTypeCode(type))
{
case TypeCode.Byte:
case TypeCode.Decimal:
case TypeCode.Double:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.SByte:
case TypeCode.Single:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return true;
default:
return false;
}
}
public static WorksheetPart GetWorksheetPartById(this SpreadsheetDocument document, string sheetId)
{
WorkbookPart wbPart = document.WorkbookPart!;
Sheet? theSheet = wbPart.Workbook.Descendants<Sheet>().
Where(s => s.Id == sheetId).FirstOrDefault();
if (theSheet == null)
throw new ArgumentException("Sheet with id {0} not found".FormatWith(sheetId));
// Retrieve a reference to the worksheet part, and then use its Worksheet property to get
// a reference to the cell whose address matches the address you've supplied:
WorksheetPart wsPart = (WorksheetPart)(wbPart.GetPartById(theSheet.Id!));
return wsPart;
}
public static WorksheetPart GetWorksheetPartBySheetName(this SpreadsheetDocument document, string sheetName)
{
WorkbookPart wbPart = document.WorkbookPart!;
Sheet? sheet = wbPart.Workbook.Descendants<Sheet>().
Where(s => s.Name == sheetName).FirstOrDefault();
if (sheet == null)
throw new ArgumentException("Sheet with name {0} not found".FormatWith(sheetName));
// Retrieve a reference to the worksheet part, and then use its Worksheet property to get
// a reference to the cell whose address matches the address you've supplied:
WorksheetPart wsPart = (WorksheetPart)(wbPart.GetPartById(sheet.Id!));
return wsPart;
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using OrchardCore.ContentManagement.Metadata;
using OrchardCore.ContentManagement.Metadata.Models;
using OrchardCore.DisplayManagement;
using OrchardCore.DisplayManagement.Descriptors;
using OrchardCore.DisplayManagement.Handlers;
using OrchardCore.DisplayManagement.Layout;
using OrchardCore.DisplayManagement.ModelBinding;
using OrchardCore.Modules;
namespace OrchardCore.ContentTypes.Editors
{
public class DefaultContentDefinitionDisplayManager : BaseDisplayManager, IContentDefinitionDisplayManager
{
private readonly IEnumerable<IContentDefinitionDisplayHandler> _handlers;
private readonly IShapeTableManager _shapeTableManager;
private readonly IContentDefinitionManager _contentDefinitionManager;
private readonly IShapeFactory _shapeFactory;
private readonly ILayoutAccessor _layoutAccessor;
private readonly ILogger _logger;
public DefaultContentDefinitionDisplayManager(
IEnumerable<IContentDefinitionDisplayHandler> handlers,
IShapeTableManager shapeTableManager,
IContentDefinitionManager contentDefinitionManager,
IShapeFactory shapeFactory,
IEnumerable<IShapePlacementProvider> placementProviders,
ILogger<DefaultContentDefinitionDisplayManager> logger,
ILayoutAccessor layoutAccessor
) : base(shapeFactory, placementProviders)
{
_handlers = handlers;
_shapeTableManager = shapeTableManager;
_contentDefinitionManager = contentDefinitionManager;
_shapeFactory = shapeFactory;
_layoutAccessor = layoutAccessor;
_logger = logger;
}
public async Task<dynamic> BuildTypeEditorAsync(ContentTypeDefinition contentTypeDefinition, IUpdateModel updater, string groupId)
{
if (contentTypeDefinition == null)
{
throw new ArgumentNullException(nameof(contentTypeDefinition));
}
dynamic contentTypeDefinitionShape = await CreateContentShapeAsync("ContentTypeDefinition_Edit");
contentTypeDefinitionShape.ContentTypeDefinition = contentTypeDefinition;
var typeContext = new BuildEditorContext(
contentTypeDefinitionShape,
groupId,
false,
"",
_shapeFactory,
await _layoutAccessor.GetLayoutAsync(),
updater
);
await BindPlacementAsync(typeContext);
await _handlers.InvokeAsync((handler, contentTypeDefinition, typeContext) => handler.BuildTypeEditorAsync(contentTypeDefinition, typeContext), contentTypeDefinition, typeContext, _logger);
return contentTypeDefinitionShape;
}
public async Task<dynamic> UpdateTypeEditorAsync(ContentTypeDefinition contentTypeDefinition, IUpdateModel updater, string groupId)
{
if (contentTypeDefinition == null)
{
throw new ArgumentNullException(nameof(contentTypeDefinition));
}
dynamic contentTypeDefinitionShape = await CreateContentShapeAsync("ContentTypeDefinition_Edit");
contentTypeDefinitionShape.ContentTypeDefinition = contentTypeDefinition;
var layout = await _layoutAccessor.GetLayoutAsync();
await _contentDefinitionManager.AlterTypeDefinitionAsync(contentTypeDefinition.Name, async typeBuilder =>
{
var typeContext = new UpdateTypeEditorContext(
typeBuilder,
contentTypeDefinitionShape,
groupId,
false,
_shapeFactory,
layout,
updater
);
await BindPlacementAsync(typeContext);
await _handlers.InvokeAsync((handler, contentTypeDefinition, typeContext) => handler.UpdateTypeEditorAsync(contentTypeDefinition, typeContext), contentTypeDefinition, typeContext, _logger);
});
return contentTypeDefinitionShape;
}
public async Task<dynamic> BuildPartEditorAsync(ContentPartDefinition contentPartDefinition, IUpdateModel updater, string groupId)
{
if (contentPartDefinition == null)
{
throw new ArgumentNullException(nameof(contentPartDefinition));
}
var contentPartDefinitionShape = await CreateContentShapeAsync("ContentPartDefinition_Edit");
var partContext = new BuildEditorContext(
contentPartDefinitionShape,
groupId,
false,
"",
_shapeFactory,
await _layoutAccessor.GetLayoutAsync(),
updater
);
await BindPlacementAsync(partContext);
await _handlers.InvokeAsync((handler, contentPartDefinition, partContext) => handler.BuildPartEditorAsync(contentPartDefinition, partContext), contentPartDefinition, partContext, _logger);
return contentPartDefinitionShape;
}
public async Task<dynamic> UpdatePartEditorAsync(ContentPartDefinition contentPartDefinition, IUpdateModel updater, string groupId)
{
if (contentPartDefinition == null)
{
throw new ArgumentNullException(nameof(contentPartDefinition));
}
var contentPartDefinitionShape = await CreateContentShapeAsync("ContentPartDefinition_Edit");
UpdatePartEditorContext partContext = null;
var layout = await _layoutAccessor.GetLayoutAsync();
await _contentDefinitionManager.AlterPartDefinitionAsync(contentPartDefinition.Name, async partBuilder =>
{
partContext = new UpdatePartEditorContext(
partBuilder,
contentPartDefinitionShape,
groupId,
false,
_shapeFactory,
layout,
updater
);
await BindPlacementAsync(partContext);
await _handlers.InvokeAsync((handler, contentPartDefinition, partContext) => handler.UpdatePartEditorAsync(contentPartDefinition, partContext), contentPartDefinition, partContext, _logger);
});
return contentPartDefinitionShape;
}
public async Task<dynamic> BuildTypePartEditorAsync(ContentTypePartDefinition contentTypePartDefinition, IUpdateModel updater, string groupId = "")
{
if (contentTypePartDefinition == null)
{
throw new ArgumentNullException(nameof(contentTypePartDefinition));
}
dynamic typePartDefinitionShape = await CreateContentShapeAsync("ContentTypePartDefinition_Edit");
typePartDefinitionShape.ContentPart = contentTypePartDefinition;
var partContext = new BuildEditorContext(
typePartDefinitionShape,
groupId,
false,
"",
_shapeFactory,
await _layoutAccessor.GetLayoutAsync(),
updater
);
await BindPlacementAsync(partContext);
await _handlers.InvokeAsync((handler, contentTypePartDefinition, partContext) => handler.BuildTypePartEditorAsync(contentTypePartDefinition, partContext), contentTypePartDefinition, partContext, _logger);
return typePartDefinitionShape;
}
public async Task<dynamic> UpdateTypePartEditorAsync(ContentTypePartDefinition contentTypePartDefinition, IUpdateModel updater, string groupId = "")
{
if (contentTypePartDefinition == null)
{
throw new ArgumentNullException(nameof(contentTypePartDefinition));
}
dynamic typePartDefinitionShape = await CreateContentShapeAsync("ContentTypePartDefinition_Edit");
var layout = await _layoutAccessor.GetLayoutAsync();
await _contentDefinitionManager.AlterTypeDefinitionAsync(contentTypePartDefinition.ContentTypeDefinition.Name, typeBuilder =>
{
return typeBuilder.WithPartAsync(contentTypePartDefinition.Name, async typePartBuilder =>
{
typePartDefinitionShape.ContentPart = contentTypePartDefinition;
var partContext = new UpdateTypePartEditorContext(
typePartBuilder,
typePartDefinitionShape,
groupId,
false,
_shapeFactory,
layout,
updater
);
await BindPlacementAsync(partContext);
await _handlers.InvokeAsync((handler, contentTypePartDefinition, partContext) => handler.UpdateTypePartEditorAsync(contentTypePartDefinition, partContext), contentTypePartDefinition, partContext, _logger);
});
});
return typePartDefinitionShape;
}
public async Task<dynamic> BuildPartFieldEditorAsync(ContentPartFieldDefinition contentPartFieldDefinition, IUpdateModel updater, string groupId = "")
{
if (contentPartFieldDefinition == null)
{
throw new ArgumentNullException(nameof(contentPartFieldDefinition));
}
dynamic partFieldDefinitionShape = await CreateContentShapeAsync("ContentPartFieldDefinition_Edit");
partFieldDefinitionShape.ContentField = contentPartFieldDefinition;
var fieldContext = new BuildEditorContext(
partFieldDefinitionShape,
groupId,
false,
"",
_shapeFactory,
await _layoutAccessor.GetLayoutAsync(),
updater
);
await BindPlacementAsync(fieldContext);
await _handlers.InvokeAsync((handler, contentPartFieldDefinition, fieldContext) => handler.BuildPartFieldEditorAsync(contentPartFieldDefinition, fieldContext), contentPartFieldDefinition, fieldContext, _logger);
return partFieldDefinitionShape;
}
public async Task<dynamic> UpdatePartFieldEditorAsync(ContentPartFieldDefinition contentPartFieldDefinition, IUpdateModel updater, string groupId = "")
{
if (contentPartFieldDefinition == null)
{
throw new ArgumentNullException(nameof(contentPartFieldDefinition));
}
var contentPartDefinition = contentPartFieldDefinition.PartDefinition;
dynamic partFieldDefinitionShape = await CreateContentShapeAsync("ContentPartFieldDefinition_Edit");
var layout = await _layoutAccessor.GetLayoutAsync();
await _contentDefinitionManager.AlterPartDefinitionAsync(contentPartDefinition.Name, partBuilder =>
{
return partBuilder.WithFieldAsync(contentPartFieldDefinition.Name, async partFieldBuilder =>
{
partFieldDefinitionShape.ContentField = contentPartFieldDefinition;
var fieldContext = new UpdatePartFieldEditorContext(
partFieldBuilder,
partFieldDefinitionShape,
groupId,
false,
_shapeFactory,
layout,
updater
);
await BindPlacementAsync(fieldContext);
await _handlers.InvokeAsync((handler, contentPartFieldDefinition, fieldContext) => handler.UpdatePartFieldEditorAsync(contentPartFieldDefinition, fieldContext), contentPartFieldDefinition, fieldContext, _logger);
});
});
return partFieldDefinitionShape;
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Java.Nio.Channels.Spi.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 Java.Nio.Channels.Spi
{
/// <summary>
/// <para><c> SelectorProvider </c> is an abstract base class that declares methods for providing instances of DatagramChannel, Pipe, java.nio.channels.Selector , ServerSocketChannel, and SocketChannel. All the methods of this class are thread-safe.</para><para>A provider instance can be retrieved through a system property or the configuration file in a jar file; if no provider is available that way then the system default provider is returned. </para>
/// </summary>
/// <java-name>
/// java/nio/channels/spi/SelectorProvider
/// </java-name>
[Dot42.DexImport("java/nio/channels/spi/SelectorProvider", AccessFlags = 1057)]
public abstract partial class SelectorProvider
/* scope: __dot42__ */
{
/// <summary>
/// <para>Constructs a new <c> SelectorProvider </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 4)]
protected internal SelectorProvider() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Gets a provider instance by executing the following steps when called for the first time: <ul><li><para>if the system property "java.nio.channels.spi.SelectorProvider" is set, the value of this property is the class name of the provider returned; </para></li><li><para>if there is a provider-configuration file named "java.nio.channels.spi.SelectorProvider" in META-INF/services of a jar file valid in the system class loader, the first class name is the provider's class name; </para></li><li><para>otherwise, a system default provider will be returned. </para></li></ul></para><para></para>
/// </summary>
/// <returns>
/// <para>the provider. </para>
/// </returns>
/// <java-name>
/// provider
/// </java-name>
[Dot42.DexImport("provider", "()Ljava/nio/channels/spi/SelectorProvider;", AccessFlags = 41)]
public static global::Java.Nio.Channels.Spi.SelectorProvider Provider() /* MethodBuilder.Create */
{
return default(global::Java.Nio.Channels.Spi.SelectorProvider);
}
/// <summary>
/// <para>Creates a new open <c> DatagramChannel </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the new channel. </para>
/// </returns>
/// <java-name>
/// openDatagramChannel
/// </java-name>
[Dot42.DexImport("openDatagramChannel", "()Ljava/nio/channels/DatagramChannel;", AccessFlags = 1025)]
public abstract global::Java.Nio.Channels.DatagramChannel OpenDatagramChannel() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Creates a new <c> Pipe </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the new pipe. </para>
/// </returns>
/// <java-name>
/// openPipe
/// </java-name>
[Dot42.DexImport("openPipe", "()Ljava/nio/channels/Pipe;", AccessFlags = 1025)]
public abstract global::Java.Nio.Channels.Pipe OpenPipe() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Creates a new selector.</para><para></para>
/// </summary>
/// <returns>
/// <para>the new selector. </para>
/// </returns>
/// <java-name>
/// openSelector
/// </java-name>
[Dot42.DexImport("openSelector", "()Ljava/nio/channels/spi/AbstractSelector;", AccessFlags = 1025)]
public abstract global::Java.Nio.Channels.Spi.AbstractSelector OpenSelector() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Creates a new open <c> ServerSocketChannel </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the new channel. </para>
/// </returns>
/// <java-name>
/// openServerSocketChannel
/// </java-name>
[Dot42.DexImport("openServerSocketChannel", "()Ljava/nio/channels/ServerSocketChannel;", AccessFlags = 1025)]
public abstract global::Java.Nio.Channels.ServerSocketChannel OpenServerSocketChannel() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Create a new open <c> SocketChannel </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the new channel. </para>
/// </returns>
/// <java-name>
/// openSocketChannel
/// </java-name>
[Dot42.DexImport("openSocketChannel", "()Ljava/nio/channels/SocketChannel;", AccessFlags = 1025)]
public abstract global::Java.Nio.Channels.SocketChannel OpenSocketChannel() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the channel inherited from the process that created this VM. On Android, this method always returns null because stdin and stdout are never connected to a socket.</para><para></para>
/// </summary>
/// <returns>
/// <para>the channel. </para>
/// </returns>
/// <java-name>
/// inheritedChannel
/// </java-name>
[Dot42.DexImport("inheritedChannel", "()Ljava/nio/channels/Channel;", AccessFlags = 1)]
public virtual global::Java.Nio.Channels.IChannel InheritedChannel() /* MethodBuilder.Create */
{
return default(global::Java.Nio.Channels.IChannel);
}
}
/// <summary>
/// <para><c> AbstractSelectableChannel </c> is the base implementation class for selectable channels. It declares methods for registering, unregistering and closing selectable channels. It is thread-safe. </para>
/// </summary>
/// <java-name>
/// java/nio/channels/spi/AbstractSelectableChannel
/// </java-name>
[Dot42.DexImport("java/nio/channels/spi/AbstractSelectableChannel", AccessFlags = 1057)]
public abstract partial class AbstractSelectableChannel : global::Java.Nio.Channels.SelectableChannel
/* scope: __dot42__ */
{
/// <summary>
/// <para>Constructs a new <c> AbstractSelectableChannel </c> .</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/nio/channels/spi/SelectorProvider;)V", AccessFlags = 4)]
protected internal AbstractSelectableChannel(global::Java.Nio.Channels.Spi.SelectorProvider selectorProvider) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the selector provider that has created this channel.</para><para><para>java.nio.channels.SelectableChannel::provider() </para></para>
/// </summary>
/// <returns>
/// <para>this channel's selector provider. </para>
/// </returns>
/// <java-name>
/// provider
/// </java-name>
[Dot42.DexImport("provider", "()Ljava/nio/channels/spi/SelectorProvider;", AccessFlags = 17)]
public override global::Java.Nio.Channels.Spi.SelectorProvider Provider() /* MethodBuilder.Create */
{
return default(global::Java.Nio.Channels.Spi.SelectorProvider);
}
/// <summary>
/// <para>Indicates whether this channel is registered with one or more selectors.</para><para></para>
/// </summary>
/// <returns>
/// <para><c> true </c> if this channel is registered with a selector, <c> false </c> otherwise. </para>
/// </returns>
/// <java-name>
/// isRegistered
/// </java-name>
[Dot42.DexImport("isRegistered", "()Z", AccessFlags = 49)]
public override bool IsRegistered() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Gets this channel's selection key for the specified selector.</para><para></para>
/// </summary>
/// <returns>
/// <para>the selection key for the channel or <c> null </c> if this channel has not been registered with <c> selector </c> . </para>
/// </returns>
/// <java-name>
/// keyFor
/// </java-name>
[Dot42.DexImport("keyFor", "(Ljava/nio/channels/Selector;)Ljava/nio/channels/SelectionKey;", AccessFlags = 49)]
public override global::Java.Nio.Channels.SelectionKey KeyFor(global::Java.Nio.Channels.Selector selector) /* MethodBuilder.Create */
{
return default(global::Java.Nio.Channels.SelectionKey);
}
/// <summary>
/// <para>Registers this channel with the specified selector for the specified interest set. If the channel is already registered with the selector, the interest set is updated to <c> interestSet </c> and the corresponding selection key is returned. If the channel is not yet registered, this method calls the <c> register </c> method of <c> selector </c> and adds the selection key to this channel's key set.</para><para></para>
/// </summary>
/// <returns>
/// <para>the selection key for this registration. </para>
/// </returns>
/// <java-name>
/// register
/// </java-name>
[Dot42.DexImport("register", "(Ljava/nio/channels/Selector;ILjava/lang/Object;)Ljava/nio/channels/SelectionKey;" +
"", AccessFlags = 17)]
public override global::Java.Nio.Channels.SelectionKey Register(global::Java.Nio.Channels.Selector selector, int interestSet, object attachment) /* MethodBuilder.Create */
{
return default(global::Java.Nio.Channels.SelectionKey);
}
/// <summary>
/// <para>Implements the channel closing behavior. Calls <c> implCloseSelectableChannel() </c> first, then loops through the list of selection keys and cancels them, which unregisters this channel from all selectors it is registered with.</para><para></para>
/// </summary>
/// <java-name>
/// implCloseChannel
/// </java-name>
[Dot42.DexImport("implCloseChannel", "()V", AccessFlags = 52)]
protected internal override void ImplCloseChannel() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Implements the closing function of the SelectableChannel. This method is called from <c> implCloseChannel() </c> .</para><para></para>
/// </summary>
/// <java-name>
/// implCloseSelectableChannel
/// </java-name>
[Dot42.DexImport("implCloseSelectableChannel", "()V", AccessFlags = 1028)]
protected internal abstract void ImplCloseSelectableChannel() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Indicates whether this channel is in blocking mode.</para><para></para>
/// </summary>
/// <returns>
/// <para><c> true </c> if this channel is blocking, <c> false </c> otherwise. </para>
/// </returns>
/// <java-name>
/// isBlocking
/// </java-name>
[Dot42.DexImport("isBlocking", "()Z", AccessFlags = 17)]
public override bool IsBlocking() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Gets the object used for the synchronization of <c> register </c> and <c> configureBlocking </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the synchronization object. </para>
/// </returns>
/// <java-name>
/// blockingLock
/// </java-name>
[Dot42.DexImport("blockingLock", "()Ljava/lang/Object;", AccessFlags = 17)]
public override object BlockingLock() /* MethodBuilder.Create */
{
return default(object);
}
/// <summary>
/// <para>Sets the blocking mode of this channel. A call to this method blocks if other calls to this method or to <c> register </c> are executing. The actual setting of the mode is done by calling <c> implConfigureBlocking(boolean) </c> .</para><para><para>java.nio.channels.SelectableChannel::configureBlocking(boolean) </para></para>
/// </summary>
/// <returns>
/// <para>this channel. </para>
/// </returns>
/// <java-name>
/// configureBlocking
/// </java-name>
[Dot42.DexImport("configureBlocking", "(Z)Ljava/nio/channels/SelectableChannel;", AccessFlags = 17)]
public override global::Java.Nio.Channels.SelectableChannel ConfigureBlocking(bool blockingMode) /* MethodBuilder.Create */
{
return default(global::Java.Nio.Channels.SelectableChannel);
}
/// <summary>
/// <para>Implements the configuration of blocking/non-blocking mode.</para><para></para>
/// </summary>
/// <java-name>
/// implConfigureBlocking
/// </java-name>
[Dot42.DexImport("implConfigureBlocking", "(Z)V", AccessFlags = 1028)]
protected internal abstract void ImplConfigureBlocking(bool blocking) /* MethodBuilder.Create */ ;
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal AbstractSelectableChannel() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <summary>
/// <para><c> AbstractSelectionKey </c> is the base implementation class for selection keys. It implements validation and cancellation methods. </para>
/// </summary>
/// <java-name>
/// java/nio/channels/spi/AbstractSelectionKey
/// </java-name>
[Dot42.DexImport("java/nio/channels/spi/AbstractSelectionKey", AccessFlags = 1057)]
public abstract partial class AbstractSelectionKey : global::Java.Nio.Channels.SelectionKey
/* scope: __dot42__ */
{
/// <summary>
/// <para>Constructs a new <c> AbstractSelectionKey </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 4)]
protected internal AbstractSelectionKey() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Indicates whether this key is valid. A key is valid as long as it has not been canceled.</para><para></para>
/// </summary>
/// <returns>
/// <para><c> true </c> if this key has not been canceled, <c> false </c> otherwise. </para>
/// </returns>
/// <java-name>
/// isValid
/// </java-name>
[Dot42.DexImport("isValid", "()Z", AccessFlags = 17)]
public override bool IsValid() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Cancels this key. </para><para>A key that has been canceled is no longer valid. Calling this method on an already canceled key does nothing. </para>
/// </summary>
/// <java-name>
/// cancel
/// </java-name>
[Dot42.DexImport("cancel", "()V", AccessFlags = 17)]
public override void Cancel() /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para><c> AbstractInterruptibleChannel </c> is the root class for interruptible channels. </para><para>The basic usage pattern for an interruptible channel is to invoke <c> begin() </c> before any I/O operation that potentially blocks indefinitely, then <c> end(boolean) </c> after completing the operation. The argument to the <c> end </c> method should indicate if the I/O operation has actually completed so that any change may be visible to the invoker. </para>
/// </summary>
/// <java-name>
/// java/nio/channels/spi/AbstractInterruptibleChannel
/// </java-name>
[Dot42.DexImport("java/nio/channels/spi/AbstractInterruptibleChannel", AccessFlags = 1057)]
public abstract partial class AbstractInterruptibleChannel : global::Java.Nio.Channels.IChannel, global::Java.Nio.Channels.IInterruptibleChannel
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 4)]
protected internal AbstractInterruptibleChannel() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns true if this channel is open. </para>
/// </summary>
/// <java-name>
/// isOpen
/// </java-name>
[Dot42.DexImport("isOpen", "()Z", AccessFlags = 49)]
public bool IsOpen() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Closes an open channel. If the channel is already closed then this method has no effect, otherwise it closes the receiver via the <c> implCloseChannel </c> method. </para><para>If an attempt is made to perform an operation on a closed channel then a java.nio.channels.ClosedChannelException is thrown. </para><para>If multiple threads attempt to simultaneously close a channel, then only one thread will run the closure code and the others will be blocked until the first one completes.</para><para><para>java.nio.channels.Channel::close() </para></para>
/// </summary>
/// <java-name>
/// close
/// </java-name>
[Dot42.DexImport("close", "()V", AccessFlags = 17)]
public void Close() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Indicates the beginning of a code section that includes an I/O operation that is potentially blocking. After this operation, the application should invoke the corresponding <c> end(boolean) </c> method. </para>
/// </summary>
/// <java-name>
/// begin
/// </java-name>
[Dot42.DexImport("begin", "()V", AccessFlags = 20)]
protected internal void Begin() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Indicates the end of a code section that has been started with <c> begin() </c> and that includes a potentially blocking I/O operation.</para><para></para>
/// </summary>
/// <java-name>
/// end
/// </java-name>
[Dot42.DexImport("end", "(Z)V", AccessFlags = 20)]
protected internal void End(bool success) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Implements the channel closing behavior. </para><para>Closes the channel with a guarantee that the channel is not currently closed through another invocation of <c> close() </c> and that the method is thread-safe. </para><para>Any outstanding threads blocked on I/O operations on this channel must be released with either a normal return code, or by throwing an <c> AsynchronousCloseException </c> .</para><para></para>
/// </summary>
/// <java-name>
/// implCloseChannel
/// </java-name>
[Dot42.DexImport("implCloseChannel", "()V", AccessFlags = 1028)]
protected internal abstract void ImplCloseChannel() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para><c> AbstractSelector </c> is the base implementation class for selectors. It realizes the interruption of selection by <c> begin </c> and <c> end </c> . It also holds the cancellation and the deletion of the key set. </para>
/// </summary>
/// <java-name>
/// java/nio/channels/spi/AbstractSelector
/// </java-name>
[Dot42.DexImport("java/nio/channels/spi/AbstractSelector", AccessFlags = 1057)]
public abstract partial class AbstractSelector : global::Java.Nio.Channels.Selector
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Ljava/nio/channels/spi/SelectorProvider;)V", AccessFlags = 4)]
protected internal AbstractSelector(global::Java.Nio.Channels.Spi.SelectorProvider selectorProvider) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Closes this selector. This method does nothing if this selector is already closed. The actual closing must be implemented by subclasses in <c> implCloseSelector() </c> . </para>
/// </summary>
/// <java-name>
/// close
/// </java-name>
[Dot42.DexImport("close", "()V", AccessFlags = 17)]
public override void Close() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Implements the closing of this channel. </para>
/// </summary>
/// <java-name>
/// implCloseSelector
/// </java-name>
[Dot42.DexImport("implCloseSelector", "()V", AccessFlags = 1028)]
protected internal abstract void ImplCloseSelector() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns true if this selector is open. </para>
/// </summary>
/// <java-name>
/// isOpen
/// </java-name>
[Dot42.DexImport("isOpen", "()Z", AccessFlags = 17)]
public override bool IsOpen() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Returns this selector's provider. </para>
/// </summary>
/// <java-name>
/// provider
/// </java-name>
[Dot42.DexImport("provider", "()Ljava/nio/channels/spi/SelectorProvider;", AccessFlags = 17)]
public override global::Java.Nio.Channels.Spi.SelectorProvider Provider() /* MethodBuilder.Create */
{
return default(global::Java.Nio.Channels.Spi.SelectorProvider);
}
/// <summary>
/// <para>Returns this channel's set of canceled selection keys. </para>
/// </summary>
/// <java-name>
/// cancelledKeys
/// </java-name>
[Dot42.DexImport("cancelledKeys", "()Ljava/util/Set;", AccessFlags = 20, Signature = "()Ljava/util/Set<Ljava/nio/channels/SelectionKey;>;")]
protected internal global::Java.Util.ISet<global::Java.Nio.Channels.SelectionKey> CancelledKeys() /* MethodBuilder.Create */
{
return default(global::Java.Util.ISet<global::Java.Nio.Channels.SelectionKey>);
}
/// <summary>
/// <para>Registers <c> channel </c> with this selector.</para><para></para>
/// </summary>
/// <returns>
/// <para>the key related to the channel and this selector. </para>
/// </returns>
/// <java-name>
/// register
/// </java-name>
[Dot42.DexImport("register", "(Ljava/nio/channels/spi/AbstractSelectableChannel;ILjava/lang/Object;)Ljava/nio/c" +
"hannels/SelectionKey;", AccessFlags = 1028)]
protected internal abstract global::Java.Nio.Channels.SelectionKey Register(global::Java.Nio.Channels.Spi.AbstractSelectableChannel channel, int operations, object attachment) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Deletes the key from the channel's key set. </para>
/// </summary>
/// <java-name>
/// deregister
/// </java-name>
[Dot42.DexImport("deregister", "(Ljava/nio/channels/spi/AbstractSelectionKey;)V", AccessFlags = 20)]
protected internal void Deregister(global::Java.Nio.Channels.Spi.AbstractSelectionKey key) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Indicates the beginning of a code section that includes an I/O operation that is potentially blocking. After this operation, the application should invoke the corresponding <c> end(boolean) </c> method. </para>
/// </summary>
/// <java-name>
/// begin
/// </java-name>
[Dot42.DexImport("begin", "()V", AccessFlags = 20)]
protected internal void Begin() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Indicates the end of a code section that has been started with <c> begin() </c> and that includes a potentially blocking I/O operation. </para>
/// </summary>
/// <java-name>
/// end
/// </java-name>
[Dot42.DexImport("end", "()V", AccessFlags = 20)]
protected internal void End() /* MethodBuilder.Create */
{
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal AbstractSelector() /* TypeBuilder.AddDefaultConstructor */
{
}
}
}
| |
#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.Linq;
using Boo.Lang.Compiler.TypeSystem.Builders;
using Boo.Lang.Compiler.TypeSystem.Internal;
namespace Boo.Lang.Compiler.Steps
{
using System.Collections;
using Boo.Lang;
using Boo.Lang.Compiler.Ast;
using Boo.Lang.Compiler.TypeSystem;
public class ProcessSharedLocals : AbstractTransformerCompilerStep
{
Method _currentMethod;
ClassDefinition _sharedLocalsClass;
Hashtable _mappings = new Hashtable();
readonly List<ReferenceExpression> _references = new List<ReferenceExpression>();
readonly List<ILocalEntity> _shared = new List<ILocalEntity>();
int _closureDepth;
override public void Dispose()
{
_shared.Clear();
_references.Clear();
_mappings.Clear();
base.Dispose();
}
override public void OnField(Field node)
{
}
override public void OnInterfaceDefinition(InterfaceDefinition node)
{
}
override public void OnEnumDefinition(EnumDefinition node)
{
}
override public void OnConstructor(Constructor node)
{
OnMethod(node);
}
override public void OnMethod(Method node)
{
_references.Clear();
_mappings.Clear();
_currentMethod = node;
_sharedLocalsClass = null;
_closureDepth = 0;
Visit(node.Body);
CreateSharedLocalsClass();
if (null != _sharedLocalsClass)
{
node.DeclaringType.Members.Add(_sharedLocalsClass);
Map();
}
}
override public void OnBlockExpression(BlockExpression node)
{
++_closureDepth;
Visit(node.Body);
--_closureDepth;
}
override public void OnGeneratorExpression(GeneratorExpression node)
{
++_closureDepth;
Visit(node.Iterator);
Visit(node.Expression);
Visit(node.Filter);
--_closureDepth;
}
override public void OnReferenceExpression(ReferenceExpression node)
{
ILocalEntity local = node.Entity as ILocalEntity;
if (null == local) return;
if (local.IsPrivateScope) return;
_references.Add(node);
if (_closureDepth == 0) return;
local.IsShared = _currentMethod.Locals.ContainsEntity(local)
|| _currentMethod.Parameters.ContainsEntity(local);
}
void Map()
{
IType type = (IType)_sharedLocalsClass.Entity;
InternalLocal locals = CodeBuilder.DeclareLocal(_currentMethod, "$locals", type);
foreach (ReferenceExpression reference in _references)
{
IField mapped = (IField)_mappings[reference.Entity];
if (null == mapped) continue;
reference.ParentNode.Replace(
reference,
CodeBuilder.CreateMemberReference(
CodeBuilder.CreateReference(locals),
mapped));
}
Block initializationBlock = new Block();
initializationBlock.Add(CodeBuilder.CreateAssignment(
CodeBuilder.CreateReference(locals),
CodeBuilder.CreateConstructorInvocation(type.GetConstructors().First())));
InitializeSharedParameters(initializationBlock, locals);
_currentMethod.Body.Statements.Insert(0, initializationBlock);
foreach (IEntity entity in _mappings.Keys)
{
_currentMethod.Locals.RemoveByEntity(entity);
}
}
void InitializeSharedParameters(Block block, InternalLocal locals)
{
foreach (Node node in _currentMethod.Parameters)
{
InternalParameter param = (InternalParameter)node.Entity;
if (param.IsShared)
{
block.Add(
CodeBuilder.CreateAssignment(
CodeBuilder.CreateMemberReference(
CodeBuilder.CreateReference(locals),
(IField)_mappings[param]),
CodeBuilder.CreateReference(param)));
}
}
}
void CreateSharedLocalsClass()
{
_shared.Clear();
CollectSharedLocalEntities(_currentMethod.Locals);
CollectSharedLocalEntities(_currentMethod.Parameters);
if (_shared.Count > 0)
{
BooClassBuilder builder = CodeBuilder.CreateClass(Context.GetUniqueName(_currentMethod.Name, "locals"));
builder.Modifiers |= TypeMemberModifiers.Internal;
builder.AddBaseType(TypeSystemServices.ObjectType);
var genericsSet = new System.Collections.Generic.HashSet<string>();
foreach (ILocalEntity local in _shared)
{
Field field = builder.AddInternalField(
string.Format("${0}", local.Name),
local.Type);
if (local.Type is IGenericParameter && !genericsSet.Contains(local.Type.Name))
{
builder.AddGenericParameter(local.Type.Name);
genericsSet.Add(local.Type.Name);
}
_mappings[local] = field.Entity;
}
builder.AddConstructor().Body.Add(
CodeBuilder.CreateSuperConstructorInvocation(TypeSystemServices.ObjectType));
_sharedLocalsClass = builder.ClassDefinition;
}
}
void CollectSharedLocalEntities<T>(System.Collections.Generic.IEnumerable<T> nodes) where T : Node
{
foreach (T node in nodes)
{
var local = (ILocalEntity)node.Entity;
if (local.IsShared)
_shared.Add(local);
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Compute.V1.Snippets
{
using Google.Api.Gax;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using lro = Google.LongRunning;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedServiceAttachmentsClientSnippets
{
/// <summary>Snippet for AggregatedList</summary>
public void AggregatedListRequestObject()
{
// Snippet: AggregatedList(AggregatedListServiceAttachmentsRequest, CallSettings)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = ServiceAttachmentsClient.Create();
// Initialize request argument(s)
AggregatedListServiceAttachmentsRequest request = new AggregatedListServiceAttachmentsRequest
{
OrderBy = "",
Project = "",
Filter = "",
IncludeAllScopes = false,
ReturnPartialSuccess = false,
};
// Make the request
PagedEnumerable<ServiceAttachmentAggregatedList, KeyValuePair<string, ServiceAttachmentsScopedList>> response = serviceAttachmentsClient.AggregatedList(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (KeyValuePair<string, ServiceAttachmentsScopedList> item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ServiceAttachmentAggregatedList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, ServiceAttachmentsScopedList> item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<KeyValuePair<string, ServiceAttachmentsScopedList>> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (KeyValuePair<string, ServiceAttachmentsScopedList> item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for AggregatedListAsync</summary>
public async Task AggregatedListRequestObjectAsync()
{
// Snippet: AggregatedListAsync(AggregatedListServiceAttachmentsRequest, CallSettings)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = await ServiceAttachmentsClient.CreateAsync();
// Initialize request argument(s)
AggregatedListServiceAttachmentsRequest request = new AggregatedListServiceAttachmentsRequest
{
OrderBy = "",
Project = "",
Filter = "",
IncludeAllScopes = false,
ReturnPartialSuccess = false,
};
// Make the request
PagedAsyncEnumerable<ServiceAttachmentAggregatedList, KeyValuePair<string, ServiceAttachmentsScopedList>> response = serviceAttachmentsClient.AggregatedListAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((KeyValuePair<string, ServiceAttachmentsScopedList> item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ServiceAttachmentAggregatedList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, ServiceAttachmentsScopedList> item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<KeyValuePair<string, ServiceAttachmentsScopedList>> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (KeyValuePair<string, ServiceAttachmentsScopedList> item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for AggregatedList</summary>
public void AggregatedList()
{
// Snippet: AggregatedList(string, string, int?, CallSettings)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = ServiceAttachmentsClient.Create();
// Initialize request argument(s)
string project = "";
// Make the request
PagedEnumerable<ServiceAttachmentAggregatedList, KeyValuePair<string, ServiceAttachmentsScopedList>> response = serviceAttachmentsClient.AggregatedList(project);
// Iterate over all response items, lazily performing RPCs as required
foreach (KeyValuePair<string, ServiceAttachmentsScopedList> item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ServiceAttachmentAggregatedList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, ServiceAttachmentsScopedList> item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<KeyValuePair<string, ServiceAttachmentsScopedList>> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (KeyValuePair<string, ServiceAttachmentsScopedList> item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for AggregatedListAsync</summary>
public async Task AggregatedListAsync()
{
// Snippet: AggregatedListAsync(string, string, int?, CallSettings)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = await ServiceAttachmentsClient.CreateAsync();
// Initialize request argument(s)
string project = "";
// Make the request
PagedAsyncEnumerable<ServiceAttachmentAggregatedList, KeyValuePair<string, ServiceAttachmentsScopedList>> response = serviceAttachmentsClient.AggregatedListAsync(project);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((KeyValuePair<string, ServiceAttachmentsScopedList> item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ServiceAttachmentAggregatedList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, ServiceAttachmentsScopedList> item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<KeyValuePair<string, ServiceAttachmentsScopedList>> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (KeyValuePair<string, ServiceAttachmentsScopedList> item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for Delete</summary>
public void DeleteRequestObject()
{
// Snippet: Delete(DeleteServiceAttachmentRequest, CallSettings)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = ServiceAttachmentsClient.Create();
// Initialize request argument(s)
DeleteServiceAttachmentRequest request = new DeleteServiceAttachmentRequest
{
RequestId = "",
Region = "",
Project = "",
ServiceAttachment = "",
};
// Make the request
lro::Operation<Operation, Operation> response = serviceAttachmentsClient.Delete(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = serviceAttachmentsClient.PollOnceDelete(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteAsync</summary>
public async Task DeleteRequestObjectAsync()
{
// Snippet: DeleteAsync(DeleteServiceAttachmentRequest, CallSettings)
// Additional: DeleteAsync(DeleteServiceAttachmentRequest, CancellationToken)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = await ServiceAttachmentsClient.CreateAsync();
// Initialize request argument(s)
DeleteServiceAttachmentRequest request = new DeleteServiceAttachmentRequest
{
RequestId = "",
Region = "",
Project = "",
ServiceAttachment = "",
};
// Make the request
lro::Operation<Operation, Operation> response = await serviceAttachmentsClient.DeleteAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await serviceAttachmentsClient.PollOnceDeleteAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Delete</summary>
public void Delete()
{
// Snippet: Delete(string, string, string, CallSettings)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = ServiceAttachmentsClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
string serviceAttachment = "";
// Make the request
lro::Operation<Operation, Operation> response = serviceAttachmentsClient.Delete(project, region, serviceAttachment);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = serviceAttachmentsClient.PollOnceDelete(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteAsync</summary>
public async Task DeleteAsync()
{
// Snippet: DeleteAsync(string, string, string, CallSettings)
// Additional: DeleteAsync(string, string, string, CancellationToken)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = await ServiceAttachmentsClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
string serviceAttachment = "";
// Make the request
lro::Operation<Operation, Operation> response = await serviceAttachmentsClient.DeleteAsync(project, region, serviceAttachment);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await serviceAttachmentsClient.PollOnceDeleteAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Get</summary>
public void GetRequestObject()
{
// Snippet: Get(GetServiceAttachmentRequest, CallSettings)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = ServiceAttachmentsClient.Create();
// Initialize request argument(s)
GetServiceAttachmentRequest request = new GetServiceAttachmentRequest
{
Region = "",
Project = "",
ServiceAttachment = "",
};
// Make the request
ServiceAttachment response = serviceAttachmentsClient.Get(request);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetRequestObjectAsync()
{
// Snippet: GetAsync(GetServiceAttachmentRequest, CallSettings)
// Additional: GetAsync(GetServiceAttachmentRequest, CancellationToken)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = await ServiceAttachmentsClient.CreateAsync();
// Initialize request argument(s)
GetServiceAttachmentRequest request = new GetServiceAttachmentRequest
{
Region = "",
Project = "",
ServiceAttachment = "",
};
// Make the request
ServiceAttachment response = await serviceAttachmentsClient.GetAsync(request);
// End snippet
}
/// <summary>Snippet for Get</summary>
public void Get()
{
// Snippet: Get(string, string, string, CallSettings)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = ServiceAttachmentsClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
string serviceAttachment = "";
// Make the request
ServiceAttachment response = serviceAttachmentsClient.Get(project, region, serviceAttachment);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetAsync()
{
// Snippet: GetAsync(string, string, string, CallSettings)
// Additional: GetAsync(string, string, string, CancellationToken)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = await ServiceAttachmentsClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
string serviceAttachment = "";
// Make the request
ServiceAttachment response = await serviceAttachmentsClient.GetAsync(project, region, serviceAttachment);
// End snippet
}
/// <summary>Snippet for GetIamPolicy</summary>
public void GetIamPolicyRequestObject()
{
// Snippet: GetIamPolicy(GetIamPolicyServiceAttachmentRequest, CallSettings)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = ServiceAttachmentsClient.Create();
// Initialize request argument(s)
GetIamPolicyServiceAttachmentRequest request = new GetIamPolicyServiceAttachmentRequest
{
Region = "",
Resource = "",
Project = "",
OptionsRequestedPolicyVersion = 0,
};
// Make the request
Policy response = serviceAttachmentsClient.GetIamPolicy(request);
// End snippet
}
/// <summary>Snippet for GetIamPolicyAsync</summary>
public async Task GetIamPolicyRequestObjectAsync()
{
// Snippet: GetIamPolicyAsync(GetIamPolicyServiceAttachmentRequest, CallSettings)
// Additional: GetIamPolicyAsync(GetIamPolicyServiceAttachmentRequest, CancellationToken)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = await ServiceAttachmentsClient.CreateAsync();
// Initialize request argument(s)
GetIamPolicyServiceAttachmentRequest request = new GetIamPolicyServiceAttachmentRequest
{
Region = "",
Resource = "",
Project = "",
OptionsRequestedPolicyVersion = 0,
};
// Make the request
Policy response = await serviceAttachmentsClient.GetIamPolicyAsync(request);
// End snippet
}
/// <summary>Snippet for GetIamPolicy</summary>
public void GetIamPolicy()
{
// Snippet: GetIamPolicy(string, string, string, CallSettings)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = ServiceAttachmentsClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
string resource = "";
// Make the request
Policy response = serviceAttachmentsClient.GetIamPolicy(project, region, resource);
// End snippet
}
/// <summary>Snippet for GetIamPolicyAsync</summary>
public async Task GetIamPolicyAsync()
{
// Snippet: GetIamPolicyAsync(string, string, string, CallSettings)
// Additional: GetIamPolicyAsync(string, string, string, CancellationToken)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = await ServiceAttachmentsClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
string resource = "";
// Make the request
Policy response = await serviceAttachmentsClient.GetIamPolicyAsync(project, region, resource);
// End snippet
}
/// <summary>Snippet for Insert</summary>
public void InsertRequestObject()
{
// Snippet: Insert(InsertServiceAttachmentRequest, CallSettings)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = ServiceAttachmentsClient.Create();
// Initialize request argument(s)
InsertServiceAttachmentRequest request = new InsertServiceAttachmentRequest
{
RequestId = "",
Region = "",
Project = "",
ServiceAttachmentResource = new ServiceAttachment(),
};
// Make the request
lro::Operation<Operation, Operation> response = serviceAttachmentsClient.Insert(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = serviceAttachmentsClient.PollOnceInsert(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for InsertAsync</summary>
public async Task InsertRequestObjectAsync()
{
// Snippet: InsertAsync(InsertServiceAttachmentRequest, CallSettings)
// Additional: InsertAsync(InsertServiceAttachmentRequest, CancellationToken)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = await ServiceAttachmentsClient.CreateAsync();
// Initialize request argument(s)
InsertServiceAttachmentRequest request = new InsertServiceAttachmentRequest
{
RequestId = "",
Region = "",
Project = "",
ServiceAttachmentResource = new ServiceAttachment(),
};
// Make the request
lro::Operation<Operation, Operation> response = await serviceAttachmentsClient.InsertAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await serviceAttachmentsClient.PollOnceInsertAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Insert</summary>
public void Insert()
{
// Snippet: Insert(string, string, ServiceAttachment, CallSettings)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = ServiceAttachmentsClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
ServiceAttachment serviceAttachmentResource = new ServiceAttachment();
// Make the request
lro::Operation<Operation, Operation> response = serviceAttachmentsClient.Insert(project, region, serviceAttachmentResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = serviceAttachmentsClient.PollOnceInsert(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for InsertAsync</summary>
public async Task InsertAsync()
{
// Snippet: InsertAsync(string, string, ServiceAttachment, CallSettings)
// Additional: InsertAsync(string, string, ServiceAttachment, CancellationToken)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = await ServiceAttachmentsClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
ServiceAttachment serviceAttachmentResource = new ServiceAttachment();
// Make the request
lro::Operation<Operation, Operation> response = await serviceAttachmentsClient.InsertAsync(project, region, serviceAttachmentResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await serviceAttachmentsClient.PollOnceInsertAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for List</summary>
public void ListRequestObject()
{
// Snippet: List(ListServiceAttachmentsRequest, CallSettings)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = ServiceAttachmentsClient.Create();
// Initialize request argument(s)
ListServiceAttachmentsRequest request = new ListServiceAttachmentsRequest
{
Region = "",
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedEnumerable<ServiceAttachmentList, ServiceAttachment> response = serviceAttachmentsClient.List(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (ServiceAttachment item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ServiceAttachmentList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ServiceAttachment item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ServiceAttachment> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ServiceAttachment item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAsync</summary>
public async Task ListRequestObjectAsync()
{
// Snippet: ListAsync(ListServiceAttachmentsRequest, CallSettings)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = await ServiceAttachmentsClient.CreateAsync();
// Initialize request argument(s)
ListServiceAttachmentsRequest request = new ListServiceAttachmentsRequest
{
Region = "",
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedAsyncEnumerable<ServiceAttachmentList, ServiceAttachment> response = serviceAttachmentsClient.ListAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((ServiceAttachment item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ServiceAttachmentList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ServiceAttachment item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ServiceAttachment> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ServiceAttachment item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for List</summary>
public void List()
{
// Snippet: List(string, string, string, int?, CallSettings)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = ServiceAttachmentsClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
// Make the request
PagedEnumerable<ServiceAttachmentList, ServiceAttachment> response = serviceAttachmentsClient.List(project, region);
// Iterate over all response items, lazily performing RPCs as required
foreach (ServiceAttachment item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ServiceAttachmentList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ServiceAttachment item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ServiceAttachment> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ServiceAttachment item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAsync</summary>
public async Task ListAsync()
{
// Snippet: ListAsync(string, string, string, int?, CallSettings)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = await ServiceAttachmentsClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
// Make the request
PagedAsyncEnumerable<ServiceAttachmentList, ServiceAttachment> response = serviceAttachmentsClient.ListAsync(project, region);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((ServiceAttachment item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ServiceAttachmentList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ServiceAttachment item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ServiceAttachment> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ServiceAttachment item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for Patch</summary>
public void PatchRequestObject()
{
// Snippet: Patch(PatchServiceAttachmentRequest, CallSettings)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = ServiceAttachmentsClient.Create();
// Initialize request argument(s)
PatchServiceAttachmentRequest request = new PatchServiceAttachmentRequest
{
RequestId = "",
Region = "",
Project = "",
ServiceAttachment = "",
ServiceAttachmentResource = new ServiceAttachment(),
};
// Make the request
lro::Operation<Operation, Operation> response = serviceAttachmentsClient.Patch(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = serviceAttachmentsClient.PollOncePatch(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for PatchAsync</summary>
public async Task PatchRequestObjectAsync()
{
// Snippet: PatchAsync(PatchServiceAttachmentRequest, CallSettings)
// Additional: PatchAsync(PatchServiceAttachmentRequest, CancellationToken)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = await ServiceAttachmentsClient.CreateAsync();
// Initialize request argument(s)
PatchServiceAttachmentRequest request = new PatchServiceAttachmentRequest
{
RequestId = "",
Region = "",
Project = "",
ServiceAttachment = "",
ServiceAttachmentResource = new ServiceAttachment(),
};
// Make the request
lro::Operation<Operation, Operation> response = await serviceAttachmentsClient.PatchAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await serviceAttachmentsClient.PollOncePatchAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Patch</summary>
public void Patch()
{
// Snippet: Patch(string, string, string, ServiceAttachment, CallSettings)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = ServiceAttachmentsClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
string serviceAttachment = "";
ServiceAttachment serviceAttachmentResource = new ServiceAttachment();
// Make the request
lro::Operation<Operation, Operation> response = serviceAttachmentsClient.Patch(project, region, serviceAttachment, serviceAttachmentResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = serviceAttachmentsClient.PollOncePatch(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for PatchAsync</summary>
public async Task PatchAsync()
{
// Snippet: PatchAsync(string, string, string, ServiceAttachment, CallSettings)
// Additional: PatchAsync(string, string, string, ServiceAttachment, CancellationToken)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = await ServiceAttachmentsClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
string serviceAttachment = "";
ServiceAttachment serviceAttachmentResource = new ServiceAttachment();
// Make the request
lro::Operation<Operation, Operation> response = await serviceAttachmentsClient.PatchAsync(project, region, serviceAttachment, serviceAttachmentResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await serviceAttachmentsClient.PollOncePatchAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for SetIamPolicy</summary>
public void SetIamPolicyRequestObject()
{
// Snippet: SetIamPolicy(SetIamPolicyServiceAttachmentRequest, CallSettings)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = ServiceAttachmentsClient.Create();
// Initialize request argument(s)
SetIamPolicyServiceAttachmentRequest request = new SetIamPolicyServiceAttachmentRequest
{
Region = "",
Resource = "",
Project = "",
RegionSetPolicyRequestResource = new RegionSetPolicyRequest(),
};
// Make the request
Policy response = serviceAttachmentsClient.SetIamPolicy(request);
// End snippet
}
/// <summary>Snippet for SetIamPolicyAsync</summary>
public async Task SetIamPolicyRequestObjectAsync()
{
// Snippet: SetIamPolicyAsync(SetIamPolicyServiceAttachmentRequest, CallSettings)
// Additional: SetIamPolicyAsync(SetIamPolicyServiceAttachmentRequest, CancellationToken)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = await ServiceAttachmentsClient.CreateAsync();
// Initialize request argument(s)
SetIamPolicyServiceAttachmentRequest request = new SetIamPolicyServiceAttachmentRequest
{
Region = "",
Resource = "",
Project = "",
RegionSetPolicyRequestResource = new RegionSetPolicyRequest(),
};
// Make the request
Policy response = await serviceAttachmentsClient.SetIamPolicyAsync(request);
// End snippet
}
/// <summary>Snippet for SetIamPolicy</summary>
public void SetIamPolicy()
{
// Snippet: SetIamPolicy(string, string, string, RegionSetPolicyRequest, CallSettings)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = ServiceAttachmentsClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
string resource = "";
RegionSetPolicyRequest regionSetPolicyRequestResource = new RegionSetPolicyRequest();
// Make the request
Policy response = serviceAttachmentsClient.SetIamPolicy(project, region, resource, regionSetPolicyRequestResource);
// End snippet
}
/// <summary>Snippet for SetIamPolicyAsync</summary>
public async Task SetIamPolicyAsync()
{
// Snippet: SetIamPolicyAsync(string, string, string, RegionSetPolicyRequest, CallSettings)
// Additional: SetIamPolicyAsync(string, string, string, RegionSetPolicyRequest, CancellationToken)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = await ServiceAttachmentsClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
string resource = "";
RegionSetPolicyRequest regionSetPolicyRequestResource = new RegionSetPolicyRequest();
// Make the request
Policy response = await serviceAttachmentsClient.SetIamPolicyAsync(project, region, resource, regionSetPolicyRequestResource);
// End snippet
}
/// <summary>Snippet for TestIamPermissions</summary>
public void TestIamPermissionsRequestObject()
{
// Snippet: TestIamPermissions(TestIamPermissionsServiceAttachmentRequest, CallSettings)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = ServiceAttachmentsClient.Create();
// Initialize request argument(s)
TestIamPermissionsServiceAttachmentRequest request = new TestIamPermissionsServiceAttachmentRequest
{
Region = "",
Resource = "",
Project = "",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
// Make the request
TestPermissionsResponse response = serviceAttachmentsClient.TestIamPermissions(request);
// End snippet
}
/// <summary>Snippet for TestIamPermissionsAsync</summary>
public async Task TestIamPermissionsRequestObjectAsync()
{
// Snippet: TestIamPermissionsAsync(TestIamPermissionsServiceAttachmentRequest, CallSettings)
// Additional: TestIamPermissionsAsync(TestIamPermissionsServiceAttachmentRequest, CancellationToken)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = await ServiceAttachmentsClient.CreateAsync();
// Initialize request argument(s)
TestIamPermissionsServiceAttachmentRequest request = new TestIamPermissionsServiceAttachmentRequest
{
Region = "",
Resource = "",
Project = "",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
// Make the request
TestPermissionsResponse response = await serviceAttachmentsClient.TestIamPermissionsAsync(request);
// End snippet
}
/// <summary>Snippet for TestIamPermissions</summary>
public void TestIamPermissions()
{
// Snippet: TestIamPermissions(string, string, string, TestPermissionsRequest, CallSettings)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = ServiceAttachmentsClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
string resource = "";
TestPermissionsRequest testPermissionsRequestResource = new TestPermissionsRequest();
// Make the request
TestPermissionsResponse response = serviceAttachmentsClient.TestIamPermissions(project, region, resource, testPermissionsRequestResource);
// End snippet
}
/// <summary>Snippet for TestIamPermissionsAsync</summary>
public async Task TestIamPermissionsAsync()
{
// Snippet: TestIamPermissionsAsync(string, string, string, TestPermissionsRequest, CallSettings)
// Additional: TestIamPermissionsAsync(string, string, string, TestPermissionsRequest, CancellationToken)
// Create client
ServiceAttachmentsClient serviceAttachmentsClient = await ServiceAttachmentsClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
string resource = "";
TestPermissionsRequest testPermissionsRequestResource = new TestPermissionsRequest();
// Make the request
TestPermissionsResponse response = await serviceAttachmentsClient.TestIamPermissionsAsync(project, region, resource, testPermissionsRequestResource);
// End snippet
}
}
}
| |
// Copyright (c) 2014-2019 The Khronos Group Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and/or associated documentation files (the "Materials"),
// to deal in the Materials without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Materials, and to permit persons to whom the
// Materials are 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 Materials.
//
// MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS KHRONOS
// STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS SPECIFICATIONS AND
// HEADER INFORMATION ARE LOCATED AT https://www.khronos.org/registry/
//
// THE MATERIALS ARE 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 MATERIALS OR THE USE OR OTHER DEALINGS
// IN THE MATERIALS.
// This header is automatically generated by the same tool that creates
// the Binary Section of the SPIR-V specification.
// Enumeration tokens for SPIR-V, in various styles:
// C, C++, C++11, JSON, Lua, Python, C#, D
//
// - C will have tokens with a "Spv" prefix, e.g.: SpvSourceLanguageGLSL
// - C++ will have tokens in the "spv" name space, e.g.: spv::SourceLanguageGLSL
// - C++11 will use enum classes in the spv namespace, e.g.: spv::SourceLanguage::GLSL
// - Lua will use tables, e.g.: spv.SourceLanguage.GLSL
// - Python will use dictionaries, e.g.: spv['SourceLanguage']['GLSL']
// - C# will use enum classes in the Specification class located in the "Spv" namespace,
// e.g.: Spv.Specification.SourceLanguage.GLSL
// - D will have tokens under the "spv" module, e.g: spv.SourceLanguage.GLSL
//
// Some tokens act like mask values, which can be OR'd together,
// while others are mutually exclusive. The mask-like ones have
// "Mask" in their name, and a parallel enum that has the shift
// amount (1 << x) for each corresponding enumerant.
namespace Spv
{
public static class Specification
{
public const uint MagicNumber = 0x07230203;
public const uint Version = 0x00010400;
public const uint Revision = 1;
public const uint OpCodeMask = 0xffff;
public const uint WordCountShift = 16;
public enum SourceLanguage
{
Unknown = 0,
ESSL = 1,
GLSL = 2,
OpenCL_C = 3,
OpenCL_CPP = 4,
HLSL = 5,
}
public enum ExecutionModel
{
Vertex = 0,
TessellationControl = 1,
TessellationEvaluation = 2,
Geometry = 3,
Fragment = 4,
GLCompute = 5,
Kernel = 6,
TaskNV = 5267,
MeshNV = 5268,
RayGenerationNV = 5313,
IntersectionNV = 5314,
AnyHitNV = 5315,
ClosestHitNV = 5316,
MissNV = 5317,
CallableNV = 5318,
}
public enum AddressingModel
{
Logical = 0,
Physical32 = 1,
Physical64 = 2,
PhysicalStorageBuffer64EXT = 5348,
}
public enum MemoryModel
{
Simple = 0,
GLSL450 = 1,
OpenCL = 2,
VulkanKHR = 3,
}
public enum ExecutionMode
{
Invocations = 0,
SpacingEqual = 1,
SpacingFractionalEven = 2,
SpacingFractionalOdd = 3,
VertexOrderCw = 4,
VertexOrderCcw = 5,
PixelCenterInteger = 6,
OriginUpperLeft = 7,
OriginLowerLeft = 8,
EarlyFragmentTests = 9,
PointMode = 10,
Xfb = 11,
DepthReplacing = 12,
DepthGreater = 14,
DepthLess = 15,
DepthUnchanged = 16,
LocalSize = 17,
LocalSizeHint = 18,
InputPoints = 19,
InputLines = 20,
InputLinesAdjacency = 21,
Triangles = 22,
InputTrianglesAdjacency = 23,
Quads = 24,
Isolines = 25,
OutputVertices = 26,
OutputPoints = 27,
OutputLineStrip = 28,
OutputTriangleStrip = 29,
VecTypeHint = 30,
ContractionOff = 31,
Initializer = 33,
Finalizer = 34,
SubgroupSize = 35,
SubgroupsPerWorkgroup = 36,
SubgroupsPerWorkgroupId = 37,
LocalSizeId = 38,
LocalSizeHintId = 39,
PostDepthCoverage = 4446,
DenormPreserve = 4459,
DenormFlushToZero = 4460,
SignedZeroInfNanPreserve = 4461,
RoundingModeRTE = 4462,
RoundingModeRTZ = 4463,
StencilRefReplacingEXT = 5027,
OutputLinesNV = 5269,
OutputPrimitivesNV = 5270,
DerivativeGroupQuadsNV = 5289,
DerivativeGroupLinearNV = 5290,
OutputTrianglesNV = 5298,
PixelInterlockOrderedEXT = 5366,
PixelInterlockUnorderedEXT = 5367,
SampleInterlockOrderedEXT = 5368,
SampleInterlockUnorderedEXT = 5369,
ShadingRateInterlockOrderedEXT = 5370,
ShadingRateInterlockUnorderedEXT = 5371,
}
public enum StorageClass
{
UniformConstant = 0,
Input = 1,
Uniform = 2,
Output = 3,
Workgroup = 4,
CrossWorkgroup = 5,
Private = 6,
Function = 7,
Generic = 8,
PushConstant = 9,
AtomicCounter = 10,
Image = 11,
StorageBuffer = 12,
CallableDataNV = 5328,
IncomingCallableDataNV = 5329,
RayPayloadNV = 5338,
HitAttributeNV = 5339,
IncomingRayPayloadNV = 5342,
ShaderRecordBufferNV = 5343,
PhysicalStorageBufferEXT = 5349,
}
public enum Dim
{
Dim1D = 0,
Dim2D = 1,
Dim3D = 2,
Cube = 3,
Rect = 4,
Buffer = 5,
SubpassData = 6,
}
public enum SamplerAddressingMode
{
None = 0,
ClampToEdge = 1,
Clamp = 2,
Repeat = 3,
RepeatMirrored = 4,
}
public enum SamplerFilterMode
{
Nearest = 0,
Linear = 1,
}
public enum ImageFormat
{
Unknown = 0,
Rgba32f = 1,
Rgba16f = 2,
R32f = 3,
Rgba8 = 4,
Rgba8Snorm = 5,
Rg32f = 6,
Rg16f = 7,
R11fG11fB10f = 8,
R16f = 9,
Rgba16 = 10,
Rgb10A2 = 11,
Rg16 = 12,
Rg8 = 13,
R16 = 14,
R8 = 15,
Rgba16Snorm = 16,
Rg16Snorm = 17,
Rg8Snorm = 18,
R16Snorm = 19,
R8Snorm = 20,
Rgba32i = 21,
Rgba16i = 22,
Rgba8i = 23,
R32i = 24,
Rg32i = 25,
Rg16i = 26,
Rg8i = 27,
R16i = 28,
R8i = 29,
Rgba32ui = 30,
Rgba16ui = 31,
Rgba8ui = 32,
R32ui = 33,
Rgb10a2ui = 34,
Rg32ui = 35,
Rg16ui = 36,
Rg8ui = 37,
R16ui = 38,
R8ui = 39,
}
public enum ImageChannelOrder
{
R = 0,
A = 1,
RG = 2,
RA = 3,
RGB = 4,
RGBA = 5,
BGRA = 6,
ARGB = 7,
Intensity = 8,
Luminance = 9,
Rx = 10,
RGx = 11,
RGBx = 12,
Depth = 13,
DepthStencil = 14,
sRGB = 15,
sRGBx = 16,
sRGBA = 17,
sBGRA = 18,
ABGR = 19,
}
public enum ImageChannelDataType
{
SnormInt8 = 0,
SnormInt16 = 1,
UnormInt8 = 2,
UnormInt16 = 3,
UnormShort565 = 4,
UnormShort555 = 5,
UnormInt101010 = 6,
SignedInt8 = 7,
SignedInt16 = 8,
SignedInt32 = 9,
UnsignedInt8 = 10,
UnsignedInt16 = 11,
UnsignedInt32 = 12,
HalfFloat = 13,
Float = 14,
UnormInt24 = 15,
UnormInt101010_2 = 16,
}
public enum ImageOperandsShift
{
Bias = 0,
Lod = 1,
Grad = 2,
ConstOffset = 3,
Offset = 4,
ConstOffsets = 5,
Sample = 6,
MinLod = 7,
MakeTexelAvailableKHR = 8,
MakeTexelVisibleKHR = 9,
NonPrivateTexelKHR = 10,
VolatileTexelKHR = 11,
SignExtend = 12,
ZeroExtend = 13,
}
public enum ImageOperandsMask
{
MaskNone = 0,
Bias = 0x00000001,
Lod = 0x00000002,
Grad = 0x00000004,
ConstOffset = 0x00000008,
Offset = 0x00000010,
ConstOffsets = 0x00000020,
Sample = 0x00000040,
MinLod = 0x00000080,
MakeTexelAvailableKHR = 0x00000100,
MakeTexelVisibleKHR = 0x00000200,
NonPrivateTexelKHR = 0x00000400,
VolatileTexelKHR = 0x00000800,
SignExtend = 0x00001000,
ZeroExtend = 0x00002000,
}
public enum FPFastMathModeShift
{
NotNaN = 0,
NotInf = 1,
NSZ = 2,
AllowRecip = 3,
Fast = 4,
}
public enum FPFastMathModeMask
{
MaskNone = 0,
NotNaN = 0x00000001,
NotInf = 0x00000002,
NSZ = 0x00000004,
AllowRecip = 0x00000008,
Fast = 0x00000010,
}
public enum FPRoundingMode
{
RTE = 0,
RTZ = 1,
RTP = 2,
RTN = 3,
}
public enum LinkageType
{
Export = 0,
Import = 1,
}
public enum AccessQualifier
{
ReadOnly = 0,
WriteOnly = 1,
ReadWrite = 2,
}
public enum FunctionParameterAttribute
{
Zext = 0,
Sext = 1,
ByVal = 2,
Sret = 3,
NoAlias = 4,
NoCapture = 5,
NoWrite = 6,
NoReadWrite = 7,
}
public enum Decoration
{
RelaxedPrecision = 0,
SpecId = 1,
Block = 2,
BufferBlock = 3,
RowMajor = 4,
ColMajor = 5,
ArrayStride = 6,
MatrixStride = 7,
GLSLShared = 8,
GLSLPacked = 9,
CPacked = 10,
BuiltIn = 11,
NoPerspective = 13,
Flat = 14,
Patch = 15,
Centroid = 16,
Sample = 17,
Invariant = 18,
Restrict = 19,
Aliased = 20,
Volatile = 21,
Constant = 22,
Coherent = 23,
NonWritable = 24,
NonReadable = 25,
Uniform = 26,
UniformId = 27,
SaturatedConversion = 28,
Stream = 29,
Location = 30,
Component = 31,
Index = 32,
Binding = 33,
DescriptorSet = 34,
Offset = 35,
XfbBuffer = 36,
XfbStride = 37,
FuncParamAttr = 38,
FPRoundingMode = 39,
FPFastMathMode = 40,
LinkageAttributes = 41,
NoContraction = 42,
InputAttachmentIndex = 43,
Alignment = 44,
MaxByteOffset = 45,
AlignmentId = 46,
MaxByteOffsetId = 47,
NoSignedWrap = 4469,
NoUnsignedWrap = 4470,
ExplicitInterpAMD = 4999,
OverrideCoverageNV = 5248,
PassthroughNV = 5250,
ViewportRelativeNV = 5252,
SecondaryViewportRelativeNV = 5256,
PerPrimitiveNV = 5271,
PerViewNV = 5272,
PerTaskNV = 5273,
PerVertexNV = 5285,
NonUniformEXT = 5300,
RestrictPointerEXT = 5355,
AliasedPointerEXT = 5356,
CounterBuffer = 5634,
HlslCounterBufferGOOGLE = 5634,
HlslSemanticGOOGLE = 5635,
UserSemantic = 5635,
}
public enum BuiltIn
{
Position = 0,
PointSize = 1,
ClipDistance = 3,
CullDistance = 4,
VertexId = 5,
InstanceId = 6,
PrimitiveId = 7,
InvocationId = 8,
Layer = 9,
ViewportIndex = 10,
TessLevelOuter = 11,
TessLevelInner = 12,
TessCoord = 13,
PatchVertices = 14,
FragCoord = 15,
PointCoord = 16,
FrontFacing = 17,
SampleId = 18,
SamplePosition = 19,
SampleMask = 20,
FragDepth = 22,
HelperInvocation = 23,
NumWorkgroups = 24,
WorkgroupSize = 25,
WorkgroupId = 26,
LocalInvocationId = 27,
GlobalInvocationId = 28,
LocalInvocationIndex = 29,
WorkDim = 30,
GlobalSize = 31,
EnqueuedWorkgroupSize = 32,
GlobalOffset = 33,
GlobalLinearId = 34,
SubgroupSize = 36,
SubgroupMaxSize = 37,
NumSubgroups = 38,
NumEnqueuedSubgroups = 39,
SubgroupId = 40,
SubgroupLocalInvocationId = 41,
VertexIndex = 42,
InstanceIndex = 43,
SubgroupEqMask = 4416,
SubgroupEqMaskKHR = 4416,
SubgroupGeMask = 4417,
SubgroupGeMaskKHR = 4417,
SubgroupGtMask = 4418,
SubgroupGtMaskKHR = 4418,
SubgroupLeMask = 4419,
SubgroupLeMaskKHR = 4419,
SubgroupLtMask = 4420,
SubgroupLtMaskKHR = 4420,
BaseVertex = 4424,
BaseInstance = 4425,
DrawIndex = 4426,
DeviceIndex = 4438,
ViewIndex = 4440,
BaryCoordNoPerspAMD = 4992,
BaryCoordNoPerspCentroidAMD = 4993,
BaryCoordNoPerspSampleAMD = 4994,
BaryCoordSmoothAMD = 4995,
BaryCoordSmoothCentroidAMD = 4996,
BaryCoordSmoothSampleAMD = 4997,
BaryCoordPullModelAMD = 4998,
FragStencilRefEXT = 5014,
ViewportMaskNV = 5253,
SecondaryPositionNV = 5257,
SecondaryViewportMaskNV = 5258,
PositionPerViewNV = 5261,
ViewportMaskPerViewNV = 5262,
FullyCoveredEXT = 5264,
TaskCountNV = 5274,
PrimitiveCountNV = 5275,
PrimitiveIndicesNV = 5276,
ClipDistancePerViewNV = 5277,
CullDistancePerViewNV = 5278,
LayerPerViewNV = 5279,
MeshViewCountNV = 5280,
MeshViewIndicesNV = 5281,
BaryCoordNV = 5286,
BaryCoordNoPerspNV = 5287,
FragSizeEXT = 5292,
FragmentSizeNV = 5292,
FragInvocationCountEXT = 5293,
InvocationsPerPixelNV = 5293,
LaunchIdNV = 5319,
LaunchSizeNV = 5320,
WorldRayOriginNV = 5321,
WorldRayDirectionNV = 5322,
ObjectRayOriginNV = 5323,
ObjectRayDirectionNV = 5324,
RayTminNV = 5325,
RayTmaxNV = 5326,
InstanceCustomIndexNV = 5327,
ObjectToWorldNV = 5330,
WorldToObjectNV = 5331,
HitTNV = 5332,
HitKindNV = 5333,
IncomingRayFlagsNV = 5351,
WarpsPerSMNV = 5374,
SMCountNV = 5375,
WarpIDNV = 5376,
SMIDNV = 5377,
}
public enum SelectionControlShift
{
Flatten = 0,
DontFlatten = 1,
}
public enum SelectionControlMask
{
MaskNone = 0,
Flatten = 0x00000001,
DontFlatten = 0x00000002,
}
public enum LoopControlShift
{
Unroll = 0,
DontUnroll = 1,
DependencyInfinite = 2,
DependencyLength = 3,
MinIterations = 4,
MaxIterations = 5,
IterationMultiple = 6,
PeelCount = 7,
PartialCount = 8,
}
public enum LoopControlMask
{
MaskNone = 0,
Unroll = 0x00000001,
DontUnroll = 0x00000002,
DependencyInfinite = 0x00000004,
DependencyLength = 0x00000008,
MinIterations = 0x00000010,
MaxIterations = 0x00000020,
IterationMultiple = 0x00000040,
PeelCount = 0x00000080,
PartialCount = 0x00000100,
}
public enum FunctionControlShift
{
Inline = 0,
DontInline = 1,
Pure = 2,
Const = 3,
}
public enum FunctionControlMask
{
MaskNone = 0,
Inline = 0x00000001,
DontInline = 0x00000002,
Pure = 0x00000004,
Const = 0x00000008,
}
public enum MemorySemanticsShift
{
Acquire = 1,
Release = 2,
AcquireRelease = 3,
SequentiallyConsistent = 4,
UniformMemory = 6,
SubgroupMemory = 7,
WorkgroupMemory = 8,
CrossWorkgroupMemory = 9,
AtomicCounterMemory = 10,
ImageMemory = 11,
OutputMemoryKHR = 12,
MakeAvailableKHR = 13,
MakeVisibleKHR = 14,
}
public enum MemorySemanticsMask
{
MaskNone = 0,
Acquire = 0x00000002,
Release = 0x00000004,
AcquireRelease = 0x00000008,
SequentiallyConsistent = 0x00000010,
UniformMemory = 0x00000040,
SubgroupMemory = 0x00000080,
WorkgroupMemory = 0x00000100,
CrossWorkgroupMemory = 0x00000200,
AtomicCounterMemory = 0x00000400,
ImageMemory = 0x00000800,
OutputMemoryKHR = 0x00001000,
MakeAvailableKHR = 0x00002000,
MakeVisibleKHR = 0x00004000,
}
public enum MemoryAccessShift
{
Volatile = 0,
Aligned = 1,
Nontemporal = 2,
MakePointerAvailableKHR = 3,
MakePointerVisibleKHR = 4,
NonPrivatePointerKHR = 5,
}
public enum MemoryAccessMask
{
MaskNone = 0,
Volatile = 0x00000001,
Aligned = 0x00000002,
Nontemporal = 0x00000004,
MakePointerAvailableKHR = 0x00000008,
MakePointerVisibleKHR = 0x00000010,
NonPrivatePointerKHR = 0x00000020,
}
public enum Scope
{
CrossDevice = 0,
Device = 1,
Workgroup = 2,
Subgroup = 3,
Invocation = 4,
QueueFamilyKHR = 5,
}
public enum GroupOperation
{
Reduce = 0,
InclusiveScan = 1,
ExclusiveScan = 2,
ClusteredReduce = 3,
PartitionedReduceNV = 6,
PartitionedInclusiveScanNV = 7,
PartitionedExclusiveScanNV = 8,
}
public enum KernelEnqueueFlags
{
NoWait = 0,
WaitKernel = 1,
WaitWorkGroup = 2,
}
public enum KernelProfilingInfoShift
{
CmdExecTime = 0,
}
public enum KernelProfilingInfoMask
{
MaskNone = 0,
CmdExecTime = 0x00000001,
}
public enum Capability
{
Matrix = 0,
Shader = 1,
Geometry = 2,
Tessellation = 3,
Addresses = 4,
Linkage = 5,
Kernel = 6,
Vector16 = 7,
Float16Buffer = 8,
Float16 = 9,
Float64 = 10,
Int64 = 11,
Int64Atomics = 12,
ImageBasic = 13,
ImageReadWrite = 14,
ImageMipmap = 15,
Pipes = 17,
Groups = 18,
DeviceEnqueue = 19,
LiteralSampler = 20,
AtomicStorage = 21,
Int16 = 22,
TessellationPointSize = 23,
GeometryPointSize = 24,
ImageGatherExtended = 25,
StorageImageMultisample = 27,
UniformBufferArrayDynamicIndexing = 28,
SampledImageArrayDynamicIndexing = 29,
StorageBufferArrayDynamicIndexing = 30,
StorageImageArrayDynamicIndexing = 31,
ClipDistance = 32,
CullDistance = 33,
ImageCubeArray = 34,
SampleRateShading = 35,
ImageRect = 36,
SampledRect = 37,
GenericPointer = 38,
Int8 = 39,
InputAttachment = 40,
SparseResidency = 41,
MinLod = 42,
Sampled1D = 43,
Image1D = 44,
SampledCubeArray = 45,
SampledBuffer = 46,
ImageBuffer = 47,
ImageMSArray = 48,
StorageImageExtendedFormats = 49,
ImageQuery = 50,
DerivativeControl = 51,
InterpolationFunction = 52,
TransformFeedback = 53,
GeometryStreams = 54,
StorageImageReadWithoutFormat = 55,
StorageImageWriteWithoutFormat = 56,
MultiViewport = 57,
SubgroupDispatch = 58,
NamedBarrier = 59,
PipeStorage = 60,
GroupNonUniform = 61,
GroupNonUniformVote = 62,
GroupNonUniformArithmetic = 63,
GroupNonUniformBallot = 64,
GroupNonUniformShuffle = 65,
GroupNonUniformShuffleRelative = 66,
GroupNonUniformClustered = 67,
GroupNonUniformQuad = 68,
SubgroupBallotKHR = 4423,
DrawParameters = 4427,
SubgroupVoteKHR = 4431,
StorageBuffer16BitAccess = 4433,
StorageUniformBufferBlock16 = 4433,
StorageUniform16 = 4434,
UniformAndStorageBuffer16BitAccess = 4434,
StoragePushConstant16 = 4435,
StorageInputOutput16 = 4436,
DeviceGroup = 4437,
MultiView = 4439,
VariablePointersStorageBuffer = 4441,
VariablePointers = 4442,
AtomicStorageOps = 4445,
SampleMaskPostDepthCoverage = 4447,
StorageBuffer8BitAccess = 4448,
UniformAndStorageBuffer8BitAccess = 4449,
StoragePushConstant8 = 4450,
DenormPreserve = 4464,
DenormFlushToZero = 4465,
SignedZeroInfNanPreserve = 4466,
RoundingModeRTE = 4467,
RoundingModeRTZ = 4468,
Float16ImageAMD = 5008,
ImageGatherBiasLodAMD = 5009,
FragmentMaskAMD = 5010,
StencilExportEXT = 5013,
ImageReadWriteLodAMD = 5015,
SampleMaskOverrideCoverageNV = 5249,
GeometryShaderPassthroughNV = 5251,
ShaderViewportIndexLayerEXT = 5254,
ShaderViewportIndexLayerNV = 5254,
ShaderViewportMaskNV = 5255,
ShaderStereoViewNV = 5259,
PerViewAttributesNV = 5260,
FragmentFullyCoveredEXT = 5265,
MeshShadingNV = 5266,
ImageFootprintNV = 5282,
FragmentBarycentricNV = 5284,
ComputeDerivativeGroupQuadsNV = 5288,
FragmentDensityEXT = 5291,
ShadingRateNV = 5291,
GroupNonUniformPartitionedNV = 5297,
ShaderNonUniformEXT = 5301,
RuntimeDescriptorArrayEXT = 5302,
InputAttachmentArrayDynamicIndexingEXT = 5303,
UniformTexelBufferArrayDynamicIndexingEXT = 5304,
StorageTexelBufferArrayDynamicIndexingEXT = 5305,
UniformBufferArrayNonUniformIndexingEXT = 5306,
SampledImageArrayNonUniformIndexingEXT = 5307,
StorageBufferArrayNonUniformIndexingEXT = 5308,
StorageImageArrayNonUniformIndexingEXT = 5309,
InputAttachmentArrayNonUniformIndexingEXT = 5310,
UniformTexelBufferArrayNonUniformIndexingEXT = 5311,
StorageTexelBufferArrayNonUniformIndexingEXT = 5312,
RayTracingNV = 5340,
VulkanMemoryModelKHR = 5345,
VulkanMemoryModelDeviceScopeKHR = 5346,
PhysicalStorageBufferAddressesEXT = 5347,
ComputeDerivativeGroupLinearNV = 5350,
CooperativeMatrixNV = 5357,
FragmentShaderSampleInterlockEXT = 5363,
FragmentShaderShadingRateInterlockEXT = 5372,
ShaderSMBuiltinsNV = 5373,
FragmentShaderPixelInterlockEXT = 5378,
SubgroupShuffleINTEL = 5568,
SubgroupBufferBlockIOINTEL = 5569,
SubgroupImageBlockIOINTEL = 5570,
SubgroupImageMediaBlockIOINTEL = 5579,
IntegerFunctions2INTEL = 5584,
SubgroupAvcMotionEstimationINTEL = 5696,
SubgroupAvcMotionEstimationIntraINTEL = 5697,
SubgroupAvcMotionEstimationChromaINTEL = 5698,
}
public enum Op
{
OpNop = 0,
OpUndef = 1,
OpSourceContinued = 2,
OpSource = 3,
OpSourceExtension = 4,
OpName = 5,
OpMemberName = 6,
OpString = 7,
OpLine = 8,
OpExtension = 10,
OpExtInstImport = 11,
OpExtInst = 12,
OpMemoryModel = 14,
OpEntryPoint = 15,
OpExecutionMode = 16,
OpCapability = 17,
OpTypeVoid = 19,
OpTypeBool = 20,
OpTypeInt = 21,
OpTypeFloat = 22,
OpTypeVector = 23,
OpTypeMatrix = 24,
OpTypeImage = 25,
OpTypeSampler = 26,
OpTypeSampledImage = 27,
OpTypeArray = 28,
OpTypeRuntimeArray = 29,
OpTypeStruct = 30,
OpTypeOpaque = 31,
OpTypePointer = 32,
OpTypeFunction = 33,
OpTypeEvent = 34,
OpTypeDeviceEvent = 35,
OpTypeReserveId = 36,
OpTypeQueue = 37,
OpTypePipe = 38,
OpTypeForwardPointer = 39,
OpConstantTrue = 41,
OpConstantFalse = 42,
OpConstant = 43,
OpConstantComposite = 44,
OpConstantSampler = 45,
OpConstantNull = 46,
OpSpecConstantTrue = 48,
OpSpecConstantFalse = 49,
OpSpecConstant = 50,
OpSpecConstantComposite = 51,
OpSpecConstantOp = 52,
OpFunction = 54,
OpFunctionParameter = 55,
OpFunctionEnd = 56,
OpFunctionCall = 57,
OpVariable = 59,
OpImageTexelPointer = 60,
OpLoad = 61,
OpStore = 62,
OpCopyMemory = 63,
OpCopyMemorySized = 64,
OpAccessChain = 65,
OpInBoundsAccessChain = 66,
OpPtrAccessChain = 67,
OpArrayLength = 68,
OpGenericPtrMemSemantics = 69,
OpInBoundsPtrAccessChain = 70,
OpDecorate = 71,
OpMemberDecorate = 72,
OpDecorationGroup = 73,
OpGroupDecorate = 74,
OpGroupMemberDecorate = 75,
OpVectorExtractDynamic = 77,
OpVectorInsertDynamic = 78,
OpVectorShuffle = 79,
OpCompositeConstruct = 80,
OpCompositeExtract = 81,
OpCompositeInsert = 82,
OpCopyObject = 83,
OpTranspose = 84,
OpSampledImage = 86,
OpImageSampleImplicitLod = 87,
OpImageSampleExplicitLod = 88,
OpImageSampleDrefImplicitLod = 89,
OpImageSampleDrefExplicitLod = 90,
OpImageSampleProjImplicitLod = 91,
OpImageSampleProjExplicitLod = 92,
OpImageSampleProjDrefImplicitLod = 93,
OpImageSampleProjDrefExplicitLod = 94,
OpImageFetch = 95,
OpImageGather = 96,
OpImageDrefGather = 97,
OpImageRead = 98,
OpImageWrite = 99,
OpImage = 100,
OpImageQueryFormat = 101,
OpImageQueryOrder = 102,
OpImageQuerySizeLod = 103,
OpImageQuerySize = 104,
OpImageQueryLod = 105,
OpImageQueryLevels = 106,
OpImageQuerySamples = 107,
OpConvertFToU = 109,
OpConvertFToS = 110,
OpConvertSToF = 111,
OpConvertUToF = 112,
OpUConvert = 113,
OpSConvert = 114,
OpFConvert = 115,
OpQuantizeToF16 = 116,
OpConvertPtrToU = 117,
OpSatConvertSToU = 118,
OpSatConvertUToS = 119,
OpConvertUToPtr = 120,
OpPtrCastToGeneric = 121,
OpGenericCastToPtr = 122,
OpGenericCastToPtrExplicit = 123,
OpBitcast = 124,
OpSNegate = 126,
OpFNegate = 127,
OpIAdd = 128,
OpFAdd = 129,
OpISub = 130,
OpFSub = 131,
OpIMul = 132,
OpFMul = 133,
OpUDiv = 134,
OpSDiv = 135,
OpFDiv = 136,
OpUMod = 137,
OpSRem = 138,
OpSMod = 139,
OpFRem = 140,
OpFMod = 141,
OpVectorTimesScalar = 142,
OpMatrixTimesScalar = 143,
OpVectorTimesMatrix = 144,
OpMatrixTimesVector = 145,
OpMatrixTimesMatrix = 146,
OpOuterProduct = 147,
OpDot = 148,
OpIAddCarry = 149,
OpISubBorrow = 150,
OpUMulExtended = 151,
OpSMulExtended = 152,
OpAny = 154,
OpAll = 155,
OpIsNan = 156,
OpIsInf = 157,
OpIsFinite = 158,
OpIsNormal = 159,
OpSignBitSet = 160,
OpLessOrGreater = 161,
OpOrdered = 162,
OpUnordered = 163,
OpLogicalEqual = 164,
OpLogicalNotEqual = 165,
OpLogicalOr = 166,
OpLogicalAnd = 167,
OpLogicalNot = 168,
OpSelect = 169,
OpIEqual = 170,
OpINotEqual = 171,
OpUGreaterThan = 172,
OpSGreaterThan = 173,
OpUGreaterThanEqual = 174,
OpSGreaterThanEqual = 175,
OpULessThan = 176,
OpSLessThan = 177,
OpULessThanEqual = 178,
OpSLessThanEqual = 179,
OpFOrdEqual = 180,
OpFUnordEqual = 181,
OpFOrdNotEqual = 182,
OpFUnordNotEqual = 183,
OpFOrdLessThan = 184,
OpFUnordLessThan = 185,
OpFOrdGreaterThan = 186,
OpFUnordGreaterThan = 187,
OpFOrdLessThanEqual = 188,
OpFUnordLessThanEqual = 189,
OpFOrdGreaterThanEqual = 190,
OpFUnordGreaterThanEqual = 191,
OpShiftRightLogical = 194,
OpShiftRightArithmetic = 195,
OpShiftLeftLogical = 196,
OpBitwiseOr = 197,
OpBitwiseXor = 198,
OpBitwiseAnd = 199,
OpNot = 200,
OpBitFieldInsert = 201,
OpBitFieldSExtract = 202,
OpBitFieldUExtract = 203,
OpBitReverse = 204,
OpBitCount = 205,
OpDPdx = 207,
OpDPdy = 208,
OpFwidth = 209,
OpDPdxFine = 210,
OpDPdyFine = 211,
OpFwidthFine = 212,
OpDPdxCoarse = 213,
OpDPdyCoarse = 214,
OpFwidthCoarse = 215,
OpEmitVertex = 218,
OpEndPrimitive = 219,
OpEmitStreamVertex = 220,
OpEndStreamPrimitive = 221,
OpControlBarrier = 224,
OpMemoryBarrier = 225,
OpAtomicLoad = 227,
OpAtomicStore = 228,
OpAtomicExchange = 229,
OpAtomicCompareExchange = 230,
OpAtomicCompareExchangeWeak = 231,
OpAtomicIIncrement = 232,
OpAtomicIDecrement = 233,
OpAtomicIAdd = 234,
OpAtomicISub = 235,
OpAtomicSMin = 236,
OpAtomicUMin = 237,
OpAtomicSMax = 238,
OpAtomicUMax = 239,
OpAtomicAnd = 240,
OpAtomicOr = 241,
OpAtomicXor = 242,
OpPhi = 245,
OpLoopMerge = 246,
OpSelectionMerge = 247,
OpLabel = 248,
OpBranch = 249,
OpBranchConditional = 250,
OpSwitch = 251,
OpKill = 252,
OpReturn = 253,
OpReturnValue = 254,
OpUnreachable = 255,
OpLifetimeStart = 256,
OpLifetimeStop = 257,
OpGroupAsyncCopy = 259,
OpGroupWaitEvents = 260,
OpGroupAll = 261,
OpGroupAny = 262,
OpGroupBroadcast = 263,
OpGroupIAdd = 264,
OpGroupFAdd = 265,
OpGroupFMin = 266,
OpGroupUMin = 267,
OpGroupSMin = 268,
OpGroupFMax = 269,
OpGroupUMax = 270,
OpGroupSMax = 271,
OpReadPipe = 274,
OpWritePipe = 275,
OpReservedReadPipe = 276,
OpReservedWritePipe = 277,
OpReserveReadPipePackets = 278,
OpReserveWritePipePackets = 279,
OpCommitReadPipe = 280,
OpCommitWritePipe = 281,
OpIsValidReserveId = 282,
OpGetNumPipePackets = 283,
OpGetMaxPipePackets = 284,
OpGroupReserveReadPipePackets = 285,
OpGroupReserveWritePipePackets = 286,
OpGroupCommitReadPipe = 287,
OpGroupCommitWritePipe = 288,
OpEnqueueMarker = 291,
OpEnqueueKernel = 292,
OpGetKernelNDrangeSubGroupCount = 293,
OpGetKernelNDrangeMaxSubGroupSize = 294,
OpGetKernelWorkGroupSize = 295,
OpGetKernelPreferredWorkGroupSizeMultiple = 296,
OpRetainEvent = 297,
OpReleaseEvent = 298,
OpCreateUserEvent = 299,
OpIsValidEvent = 300,
OpSetUserEventStatus = 301,
OpCaptureEventProfilingInfo = 302,
OpGetDefaultQueue = 303,
OpBuildNDRange = 304,
OpImageSparseSampleImplicitLod = 305,
OpImageSparseSampleExplicitLod = 306,
OpImageSparseSampleDrefImplicitLod = 307,
OpImageSparseSampleDrefExplicitLod = 308,
OpImageSparseSampleProjImplicitLod = 309,
OpImageSparseSampleProjExplicitLod = 310,
OpImageSparseSampleProjDrefImplicitLod = 311,
OpImageSparseSampleProjDrefExplicitLod = 312,
OpImageSparseFetch = 313,
OpImageSparseGather = 314,
OpImageSparseDrefGather = 315,
OpImageSparseTexelsResident = 316,
OpNoLine = 317,
OpAtomicFlagTestAndSet = 318,
OpAtomicFlagClear = 319,
OpImageSparseRead = 320,
OpSizeOf = 321,
OpTypePipeStorage = 322,
OpConstantPipeStorage = 323,
OpCreatePipeFromPipeStorage = 324,
OpGetKernelLocalSizeForSubgroupCount = 325,
OpGetKernelMaxNumSubgroups = 326,
OpTypeNamedBarrier = 327,
OpNamedBarrierInitialize = 328,
OpMemoryNamedBarrier = 329,
OpModuleProcessed = 330,
OpExecutionModeId = 331,
OpDecorateId = 332,
OpGroupNonUniformElect = 333,
OpGroupNonUniformAll = 334,
OpGroupNonUniformAny = 335,
OpGroupNonUniformAllEqual = 336,
OpGroupNonUniformBroadcast = 337,
OpGroupNonUniformBroadcastFirst = 338,
OpGroupNonUniformBallot = 339,
OpGroupNonUniformInverseBallot = 340,
OpGroupNonUniformBallotBitExtract = 341,
OpGroupNonUniformBallotBitCount = 342,
OpGroupNonUniformBallotFindLSB = 343,
OpGroupNonUniformBallotFindMSB = 344,
OpGroupNonUniformShuffle = 345,
OpGroupNonUniformShuffleXor = 346,
OpGroupNonUniformShuffleUp = 347,
OpGroupNonUniformShuffleDown = 348,
OpGroupNonUniformIAdd = 349,
OpGroupNonUniformFAdd = 350,
OpGroupNonUniformIMul = 351,
OpGroupNonUniformFMul = 352,
OpGroupNonUniformSMin = 353,
OpGroupNonUniformUMin = 354,
OpGroupNonUniformFMin = 355,
OpGroupNonUniformSMax = 356,
OpGroupNonUniformUMax = 357,
OpGroupNonUniformFMax = 358,
OpGroupNonUniformBitwiseAnd = 359,
OpGroupNonUniformBitwiseOr = 360,
OpGroupNonUniformBitwiseXor = 361,
OpGroupNonUniformLogicalAnd = 362,
OpGroupNonUniformLogicalOr = 363,
OpGroupNonUniformLogicalXor = 364,
OpGroupNonUniformQuadBroadcast = 365,
OpGroupNonUniformQuadSwap = 366,
OpCopyLogical = 400,
OpPtrEqual = 401,
OpPtrNotEqual = 402,
OpPtrDiff = 403,
OpSubgroupBallotKHR = 4421,
OpSubgroupFirstInvocationKHR = 4422,
OpSubgroupAllKHR = 4428,
OpSubgroupAnyKHR = 4429,
OpSubgroupAllEqualKHR = 4430,
OpSubgroupReadInvocationKHR = 4432,
OpGroupIAddNonUniformAMD = 5000,
OpGroupFAddNonUniformAMD = 5001,
OpGroupFMinNonUniformAMD = 5002,
OpGroupUMinNonUniformAMD = 5003,
OpGroupSMinNonUniformAMD = 5004,
OpGroupFMaxNonUniformAMD = 5005,
OpGroupUMaxNonUniformAMD = 5006,
OpGroupSMaxNonUniformAMD = 5007,
OpFragmentMaskFetchAMD = 5011,
OpFragmentFetchAMD = 5012,
OpImageSampleFootprintNV = 5283,
OpGroupNonUniformPartitionNV = 5296,
OpWritePackedPrimitiveIndices4x8NV = 5299,
OpReportIntersectionNV = 5334,
OpIgnoreIntersectionNV = 5335,
OpTerminateRayNV = 5336,
OpTraceNV = 5337,
OpTypeAccelerationStructureNV = 5341,
OpExecuteCallableNV = 5344,
OpTypeCooperativeMatrixNV = 5358,
OpCooperativeMatrixLoadNV = 5359,
OpCooperativeMatrixStoreNV = 5360,
OpCooperativeMatrixMulAddNV = 5361,
OpCooperativeMatrixLengthNV = 5362,
OpBeginInvocationInterlockEXT = 5364,
OpEndInvocationInterlockEXT = 5365,
OpSubgroupShuffleINTEL = 5571,
OpSubgroupShuffleDownINTEL = 5572,
OpSubgroupShuffleUpINTEL = 5573,
OpSubgroupShuffleXorINTEL = 5574,
OpSubgroupBlockReadINTEL = 5575,
OpSubgroupBlockWriteINTEL = 5576,
OpSubgroupImageBlockReadINTEL = 5577,
OpSubgroupImageBlockWriteINTEL = 5578,
OpSubgroupImageMediaBlockReadINTEL = 5580,
OpSubgroupImageMediaBlockWriteINTEL = 5581,
OpUCountLeadingZerosINTEL = 5585,
OpUCountTrailingZerosINTEL = 5586,
OpAbsISubINTEL = 5587,
OpAbsUSubINTEL = 5588,
OpIAddSatINTEL = 5589,
OpUAddSatINTEL = 5590,
OpIAverageINTEL = 5591,
OpUAverageINTEL = 5592,
OpIAverageRoundedINTEL = 5593,
OpUAverageRoundedINTEL = 5594,
OpISubSatINTEL = 5595,
OpUSubSatINTEL = 5596,
OpIMul32x16INTEL = 5597,
OpUMul32x16INTEL = 5598,
OpDecorateString = 5632,
OpDecorateStringGOOGLE = 5632,
OpMemberDecorateString = 5633,
OpMemberDecorateStringGOOGLE = 5633,
OpVmeImageINTEL = 5699,
OpTypeVmeImageINTEL = 5700,
OpTypeAvcImePayloadINTEL = 5701,
OpTypeAvcRefPayloadINTEL = 5702,
OpTypeAvcSicPayloadINTEL = 5703,
OpTypeAvcMcePayloadINTEL = 5704,
OpTypeAvcMceResultINTEL = 5705,
OpTypeAvcImeResultINTEL = 5706,
OpTypeAvcImeResultSingleReferenceStreamoutINTEL = 5707,
OpTypeAvcImeResultDualReferenceStreamoutINTEL = 5708,
OpTypeAvcImeSingleReferenceStreaminINTEL = 5709,
OpTypeAvcImeDualReferenceStreaminINTEL = 5710,
OpTypeAvcRefResultINTEL = 5711,
OpTypeAvcSicResultINTEL = 5712,
OpSubgroupAvcMceGetDefaultInterBaseMultiReferencePenaltyINTEL = 5713,
OpSubgroupAvcMceSetInterBaseMultiReferencePenaltyINTEL = 5714,
OpSubgroupAvcMceGetDefaultInterShapePenaltyINTEL = 5715,
OpSubgroupAvcMceSetInterShapePenaltyINTEL = 5716,
OpSubgroupAvcMceGetDefaultInterDirectionPenaltyINTEL = 5717,
OpSubgroupAvcMceSetInterDirectionPenaltyINTEL = 5718,
OpSubgroupAvcMceGetDefaultIntraLumaShapePenaltyINTEL = 5719,
OpSubgroupAvcMceGetDefaultInterMotionVectorCostTableINTEL = 5720,
OpSubgroupAvcMceGetDefaultHighPenaltyCostTableINTEL = 5721,
OpSubgroupAvcMceGetDefaultMediumPenaltyCostTableINTEL = 5722,
OpSubgroupAvcMceGetDefaultLowPenaltyCostTableINTEL = 5723,
OpSubgroupAvcMceSetMotionVectorCostFunctionINTEL = 5724,
OpSubgroupAvcMceGetDefaultIntraLumaModePenaltyINTEL = 5725,
OpSubgroupAvcMceGetDefaultNonDcLumaIntraPenaltyINTEL = 5726,
OpSubgroupAvcMceGetDefaultIntraChromaModeBasePenaltyINTEL = 5727,
OpSubgroupAvcMceSetAcOnlyHaarINTEL = 5728,
OpSubgroupAvcMceSetSourceInterlacedFieldPolarityINTEL = 5729,
OpSubgroupAvcMceSetSingleReferenceInterlacedFieldPolarityINTEL = 5730,
OpSubgroupAvcMceSetDualReferenceInterlacedFieldPolaritiesINTEL = 5731,
OpSubgroupAvcMceConvertToImePayloadINTEL = 5732,
OpSubgroupAvcMceConvertToImeResultINTEL = 5733,
OpSubgroupAvcMceConvertToRefPayloadINTEL = 5734,
OpSubgroupAvcMceConvertToRefResultINTEL = 5735,
OpSubgroupAvcMceConvertToSicPayloadINTEL = 5736,
OpSubgroupAvcMceConvertToSicResultINTEL = 5737,
OpSubgroupAvcMceGetMotionVectorsINTEL = 5738,
OpSubgroupAvcMceGetInterDistortionsINTEL = 5739,
OpSubgroupAvcMceGetBestInterDistortionsINTEL = 5740,
OpSubgroupAvcMceGetInterMajorShapeINTEL = 5741,
OpSubgroupAvcMceGetInterMinorShapeINTEL = 5742,
OpSubgroupAvcMceGetInterDirectionsINTEL = 5743,
OpSubgroupAvcMceGetInterMotionVectorCountINTEL = 5744,
OpSubgroupAvcMceGetInterReferenceIdsINTEL = 5745,
OpSubgroupAvcMceGetInterReferenceInterlacedFieldPolaritiesINTEL = 5746,
OpSubgroupAvcImeInitializeINTEL = 5747,
OpSubgroupAvcImeSetSingleReferenceINTEL = 5748,
OpSubgroupAvcImeSetDualReferenceINTEL = 5749,
OpSubgroupAvcImeRefWindowSizeINTEL = 5750,
OpSubgroupAvcImeAdjustRefOffsetINTEL = 5751,
OpSubgroupAvcImeConvertToMcePayloadINTEL = 5752,
OpSubgroupAvcImeSetMaxMotionVectorCountINTEL = 5753,
OpSubgroupAvcImeSetUnidirectionalMixDisableINTEL = 5754,
OpSubgroupAvcImeSetEarlySearchTerminationThresholdINTEL = 5755,
OpSubgroupAvcImeSetWeightedSadINTEL = 5756,
OpSubgroupAvcImeEvaluateWithSingleReferenceINTEL = 5757,
OpSubgroupAvcImeEvaluateWithDualReferenceINTEL = 5758,
OpSubgroupAvcImeEvaluateWithSingleReferenceStreaminINTEL = 5759,
OpSubgroupAvcImeEvaluateWithDualReferenceStreaminINTEL = 5760,
OpSubgroupAvcImeEvaluateWithSingleReferenceStreamoutINTEL = 5761,
OpSubgroupAvcImeEvaluateWithDualReferenceStreamoutINTEL = 5762,
OpSubgroupAvcImeEvaluateWithSingleReferenceStreaminoutINTEL = 5763,
OpSubgroupAvcImeEvaluateWithDualReferenceStreaminoutINTEL = 5764,
OpSubgroupAvcImeConvertToMceResultINTEL = 5765,
OpSubgroupAvcImeGetSingleReferenceStreaminINTEL = 5766,
OpSubgroupAvcImeGetDualReferenceStreaminINTEL = 5767,
OpSubgroupAvcImeStripSingleReferenceStreamoutINTEL = 5768,
OpSubgroupAvcImeStripDualReferenceStreamoutINTEL = 5769,
OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeMotionVectorsINTEL = 5770,
OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeDistortionsINTEL = 5771,
OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeReferenceIdsINTEL = 5772,
OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeMotionVectorsINTEL = 5773,
OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeDistortionsINTEL = 5774,
OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeReferenceIdsINTEL = 5775,
OpSubgroupAvcImeGetBorderReachedINTEL = 5776,
OpSubgroupAvcImeGetTruncatedSearchIndicationINTEL = 5777,
OpSubgroupAvcImeGetUnidirectionalEarlySearchTerminationINTEL = 5778,
OpSubgroupAvcImeGetWeightingPatternMinimumMotionVectorINTEL = 5779,
OpSubgroupAvcImeGetWeightingPatternMinimumDistortionINTEL = 5780,
OpSubgroupAvcFmeInitializeINTEL = 5781,
OpSubgroupAvcBmeInitializeINTEL = 5782,
OpSubgroupAvcRefConvertToMcePayloadINTEL = 5783,
OpSubgroupAvcRefSetBidirectionalMixDisableINTEL = 5784,
OpSubgroupAvcRefSetBilinearFilterEnableINTEL = 5785,
OpSubgroupAvcRefEvaluateWithSingleReferenceINTEL = 5786,
OpSubgroupAvcRefEvaluateWithDualReferenceINTEL = 5787,
OpSubgroupAvcRefEvaluateWithMultiReferenceINTEL = 5788,
OpSubgroupAvcRefEvaluateWithMultiReferenceInterlacedINTEL = 5789,
OpSubgroupAvcRefConvertToMceResultINTEL = 5790,
OpSubgroupAvcSicInitializeINTEL = 5791,
OpSubgroupAvcSicConfigureSkcINTEL = 5792,
OpSubgroupAvcSicConfigureIpeLumaINTEL = 5793,
OpSubgroupAvcSicConfigureIpeLumaChromaINTEL = 5794,
OpSubgroupAvcSicGetMotionVectorMaskINTEL = 5795,
OpSubgroupAvcSicConvertToMcePayloadINTEL = 5796,
OpSubgroupAvcSicSetIntraLumaShapePenaltyINTEL = 5797,
OpSubgroupAvcSicSetIntraLumaModeCostFunctionINTEL = 5798,
OpSubgroupAvcSicSetIntraChromaModeCostFunctionINTEL = 5799,
OpSubgroupAvcSicSetBilinearFilterEnableINTEL = 5800,
OpSubgroupAvcSicSetSkcForwardTransformEnableINTEL = 5801,
OpSubgroupAvcSicSetBlockBasedRawSkipSadINTEL = 5802,
OpSubgroupAvcSicEvaluateIpeINTEL = 5803,
OpSubgroupAvcSicEvaluateWithSingleReferenceINTEL = 5804,
OpSubgroupAvcSicEvaluateWithDualReferenceINTEL = 5805,
OpSubgroupAvcSicEvaluateWithMultiReferenceINTEL = 5806,
OpSubgroupAvcSicEvaluateWithMultiReferenceInterlacedINTEL = 5807,
OpSubgroupAvcSicConvertToMceResultINTEL = 5808,
OpSubgroupAvcSicGetIpeLumaShapeINTEL = 5809,
OpSubgroupAvcSicGetBestIpeLumaDistortionINTEL = 5810,
OpSubgroupAvcSicGetBestIpeChromaDistortionINTEL = 5811,
OpSubgroupAvcSicGetPackedIpeLumaModesINTEL = 5812,
OpSubgroupAvcSicGetIpeChromaModeINTEL = 5813,
OpSubgroupAvcSicGetPackedSkcLumaCountThresholdINTEL = 5814,
OpSubgroupAvcSicGetPackedSkcLumaSumThresholdINTEL = 5815,
OpSubgroupAvcSicGetInterRawSadsINTEL = 5816,
}
}
}
| |
namespace BooCompiler.Tests
{
using NUnit.Framework;
[TestFixture]
public class RegressionTestFixture : AbstractCompilerTestCase
{
[Test]
public void array_ldelem()
{
RunCompilerTestCase(@"array_ldelem.boo");
}
[Test]
public void BOO_1005_1()
{
RunCompilerTestCase(@"BOO-1005-1.boo");
}
[Test]
public void BOO_1005_2()
{
RunCompilerTestCase(@"BOO-1005-2.boo");
}
[Test]
public void BOO_1006_1()
{
RunCompilerTestCase(@"BOO-1006-1.boo");
}
[Test]
public void BOO_1008_1()
{
RunCompilerTestCase(@"BOO-1008-1.boo");
}
[Test]
public void BOO_1009_1()
{
RunCompilerTestCase(@"BOO-1009-1.boo");
}
[Test]
public void BOO_1013_1()
{
RunCompilerTestCase(@"BOO-1013-1.boo");
}
[Test]
public void BOO_1013_2()
{
RunCompilerTestCase(@"BOO-1013-2.boo");
}
[Test]
public void BOO_1016_1()
{
RunCompilerTestCase(@"BOO-1016-1.boo");
}
[Test]
public void BOO_1016_2()
{
RunCompilerTestCase(@"BOO-1016-2.boo");
}
[Test]
public void BOO_1027_1()
{
RunCompilerTestCase(@"BOO-1027-1.boo");
}
[Test]
public void BOO_1031_1()
{
RunCompilerTestCase(@"BOO-1031-1.boo");
}
[Test]
public void BOO_1031_2()
{
RunCompilerTestCase(@"BOO-1031-2.boo");
}
[Test]
public void BOO_1031_3()
{
RunCompilerTestCase(@"BOO-1031-3.boo");
}
[Test]
public void BOO_1031_4()
{
RunCompilerTestCase(@"BOO-1031-4.boo");
}
[Test]
public void boo_1032_1()
{
RunCompilerTestCase(@"boo-1032-1.boo");
}
[Test]
public void boo_1032_2()
{
RunCompilerTestCase(@"boo-1032-2.boo");
}
[Test]
public void BOO_1035_1()
{
RunCompilerTestCase(@"BOO-1035-1.boo");
}
[Test]
public void BOO_104_1()
{
RunCompilerTestCase(@"BOO-104-1.boo");
}
[Test]
public void BOO_1040_1()
{
RunCompilerTestCase(@"BOO-1040-1.boo");
}
[Test]
public void BOO_1047()
{
RunCompilerTestCase(@"BOO-1047.boo");
}
[Test]
public void boo_1051()
{
RunCompilerTestCase(@"boo-1051.boo");
}
[Test]
public void BOO_1069_1()
{
RunCompilerTestCase(@"BOO-1069-1.boo");
}
[Test]
public void BOO_1070_1()
{
RunCompilerTestCase(@"BOO-1070-1.boo");
}
[Test]
public void BOO_1071()
{
RunCompilerTestCase(@"BOO-1071.boo");
}
[Test]
public void BOO_1076()
{
RunCompilerTestCase(@"BOO-1076.boo");
}
[Ignore("broken by SRE bug")][Test]
public void BOO_1078_1()
{
RunCompilerTestCase(@"BOO-1078-1.boo");
}
[Test]
public void BOO_1080_1()
{
RunCompilerTestCase(@"BOO-1080-1.boo");
}
[Test]
public void BOO_1082()
{
RunCompilerTestCase(@"BOO-1082.boo");
}
[Test]
public void BOO_1085()
{
RunCompilerTestCase(@"BOO-1085.boo");
}
[Test]
public void BOO_1086()
{
RunCompilerTestCase(@"BOO-1086.boo");
}
[Test]
public void BOO_1088_1()
{
RunCompilerTestCase(@"BOO-1088-1.boo");
}
[Test]
public void BOO_1091_1()
{
RunCompilerTestCase(@"BOO-1091-1.boo");
}
[Test]
public void BOO_1095_1()
{
RunCompilerTestCase(@"BOO-1095-1.boo");
}
[Test]
public void BOO_1111_1()
{
RunCompilerTestCase(@"BOO-1111-1.boo");
}
[Test]
public void BOO_1127_1()
{
RunCompilerTestCase(@"BOO-1127-1.boo");
}
[Test]
public void BOO_1130_1()
{
RunCompilerTestCase(@"BOO-1130-1.boo");
}
[Test]
public void BOO_1135_1()
{
RunCompilerTestCase(@"BOO-1135-1.boo");
}
[Test]
public void BOO_1147_1()
{
RunCompilerTestCase(@"BOO-1147-1.boo");
}
[Test]
public void BOO_1147_2()
{
RunCompilerTestCase(@"BOO-1147-2.boo");
}
[Test]
public void BOO_1154_1()
{
RunCompilerTestCase(@"BOO-1154-1.boo");
}
[Test]
public void BOO_1160_1()
{
RunCompilerTestCase(@"BOO-1160-1.boo");
}
[Test]
public void BOO_1162_1()
{
RunCompilerTestCase(@"BOO-1162-1.boo");
}
[Test]
public void BOO_1170()
{
RunCompilerTestCase(@"BOO-1170.boo");
}
[Test]
public void BOO_1171_1()
{
RunCompilerTestCase(@"BOO-1171-1.boo");
}
[Test]
public void BOO_1176_1()
{
RunCompilerTestCase(@"BOO-1176-1.boo");
}
[Test]
public void BOO_1177_1()
{
RunCompilerTestCase(@"BOO-1177-1.boo");
}
[Test]
public void BOO_1206_1()
{
RunCompilerTestCase(@"BOO-1206-1.boo");
}
[Test]
public void BOO_121_1()
{
RunCompilerTestCase(@"BOO-121-1.boo");
}
[Test]
public void BOO_1210_1()
{
RunCompilerTestCase(@"BOO-1210-1.boo");
}
[Test]
public void BOO_1217_1()
{
RunCompilerTestCase(@"BOO-1217-1.boo");
}
[Test]
public void BOO_122_1()
{
RunCompilerTestCase(@"BOO-122-1.boo");
}
[Test]
public void BOO_1220_1()
{
RunCompilerTestCase(@"BOO-1220-1.boo");
}
[Test]
public void BOO_123_1()
{
RunCompilerTestCase(@"BOO-123-1.boo");
}
[Test]
public void BOO_1256()
{
RunCompilerTestCase(@"BOO-1256.boo");
}
[Test]
public void BOO_1261_1()
{
RunCompilerTestCase(@"BOO-1261-1.boo");
}
[Ignore("WIP")][Test]
public void BOO_1264()
{
RunCompilerTestCase(@"BOO-1264.boo");
}
[Test]
public void BOO_1288()
{
RunCompilerTestCase(@"BOO-1288.boo");
}
[Test]
public void BOO_129_1()
{
RunCompilerTestCase(@"BOO-129-1.boo");
}
[Test]
public void BOO_1290()
{
RunCompilerTestCase(@"BOO-1290.boo");
}
[Test]
public void BOO_1306()
{
RunCompilerTestCase(@"BOO-1306.boo");
}
[Test]
public void BOO_1307()
{
RunCompilerTestCase(@"BOO-1307.boo");
}
[Test]
public void BOO_1308()
{
RunCompilerTestCase(@"BOO-1308.boo");
}
[Test]
public void BOO_138_1()
{
RunCompilerTestCase(@"BOO-138-1.boo");
}
[Test]
public void BOO_145_1()
{
RunCompilerTestCase(@"BOO-145-1.boo");
}
[Test]
public void BOO_176_1()
{
RunCompilerTestCase(@"BOO-176-1.boo");
}
[Test]
public void BOO_178_1()
{
RunCompilerTestCase(@"BOO-178-1.boo");
}
[Test]
public void BOO_178_2()
{
RunCompilerTestCase(@"BOO-178-2.boo");
}
[Test]
public void BOO_189_1()
{
RunCompilerTestCase(@"BOO-189-1.boo");
}
[Test]
public void BOO_189_2()
{
RunCompilerTestCase(@"BOO-189-2.boo");
}
[Test]
public void BOO_195_1()
{
RunCompilerTestCase(@"BOO-195-1.boo");
}
[Test]
public void BOO_203_1()
{
RunCompilerTestCase(@"BOO-203-1.boo");
}
[Test]
public void BOO_210_1()
{
RunCompilerTestCase(@"BOO-210-1.boo");
}
[Test]
public void BOO_226_1()
{
RunCompilerTestCase(@"BOO-226-1.boo");
}
[Test]
public void BOO_226_2()
{
RunCompilerTestCase(@"BOO-226-2.boo");
}
[Test]
public void BOO_227_1()
{
RunCompilerTestCase(@"BOO-227-1.boo");
}
[Test]
public void BOO_231_1()
{
RunCompilerTestCase(@"BOO-231-1.boo");
}
[Test]
public void BOO_241_1()
{
RunCompilerTestCase(@"BOO-241-1.boo");
}
[Test]
public void BOO_248_1()
{
RunCompilerTestCase(@"BOO-248-1.boo");
}
[Test]
public void BOO_260_1()
{
RunCompilerTestCase(@"BOO-260-1.boo");
}
[Test]
public void BOO_265_1()
{
RunCompilerTestCase(@"BOO-265-1.boo");
}
[Test]
public void BOO_270_1()
{
RunCompilerTestCase(@"BOO-270-1.boo");
}
[Test]
public void BOO_281_1()
{
RunCompilerTestCase(@"BOO-281-1.boo");
}
[Test]
public void BOO_281_2()
{
RunCompilerTestCase(@"BOO-281-2.boo");
}
[Test]
public void BOO_301_1()
{
RunCompilerTestCase(@"BOO-301-1.boo");
}
[Test]
public void BOO_301_2()
{
RunCompilerTestCase(@"BOO-301-2.boo");
}
[Test]
public void BOO_308_1()
{
RunCompilerTestCase(@"BOO-308-1.boo");
}
[Test]
public void BOO_308_2()
{
RunCompilerTestCase(@"BOO-308-2.boo");
}
[Test]
public void BOO_313_1()
{
RunCompilerTestCase(@"BOO-313-1.boo");
}
[Test]
public void BOO_313_10()
{
RunCompilerTestCase(@"BOO-313-10.boo");
}
[Test]
public void BOO_313_11()
{
RunCompilerTestCase(@"BOO-313-11.boo");
}
[Test]
public void BOO_313_12()
{
RunCompilerTestCase(@"BOO-313-12.boo");
}
[Test]
public void BOO_313_2()
{
RunCompilerTestCase(@"BOO-313-2.boo");
}
[Test]
public void BOO_313_3()
{
RunCompilerTestCase(@"BOO-313-3.boo");
}
[Test]
public void BOO_313_4()
{
RunCompilerTestCase(@"BOO-313-4.boo");
}
[Test]
public void BOO_313_5()
{
RunCompilerTestCase(@"BOO-313-5.boo");
}
[Test]
public void BOO_313_6()
{
RunCompilerTestCase(@"BOO-313-6.boo");
}
[Test]
public void BOO_313_7()
{
RunCompilerTestCase(@"BOO-313-7.boo");
}
[Test]
public void BOO_313_8()
{
RunCompilerTestCase(@"BOO-313-8.boo");
}
[Test]
public void BOO_313_9()
{
RunCompilerTestCase(@"BOO-313-9.boo");
}
[Test]
public void BOO_327_1()
{
RunCompilerTestCase(@"BOO-327-1.boo");
}
[Test]
public void BOO_338_1()
{
RunCompilerTestCase(@"BOO-338-1.boo");
}
[Test]
public void BOO_356_1()
{
RunCompilerTestCase(@"BOO-356-1.boo");
}
[Test]
public void BOO_357_1()
{
RunCompilerTestCase(@"BOO-357-1.boo");
}
[Test]
public void BOO_357_2()
{
RunCompilerTestCase(@"BOO-357-2.boo");
}
[Test]
public void BOO_366_1()
{
RunCompilerTestCase(@"BOO-366-1.boo");
}
[Test]
public void BOO_366_2()
{
RunCompilerTestCase(@"BOO-366-2.boo");
}
[Test]
public void BOO_367_1()
{
RunCompilerTestCase(@"BOO-367-1.boo");
}
[Test]
public void BOO_368_1()
{
RunCompilerTestCase(@"BOO-368-1.boo");
}
[Test]
public void BOO_369_1()
{
RunCompilerTestCase(@"BOO-369-1.boo");
}
[Test]
public void BOO_369_2()
{
RunCompilerTestCase(@"BOO-369-2.boo");
}
[Test]
public void BOO_372_1()
{
RunCompilerTestCase(@"BOO-372-1.boo");
}
[Test]
public void BOO_390_1()
{
RunCompilerTestCase(@"BOO-390-1.boo");
}
[Test]
public void BOO_396_1()
{
RunCompilerTestCase(@"BOO-396-1.boo");
}
[Test]
public void BOO_398_1()
{
RunCompilerTestCase(@"BOO-398-1.boo");
}
[Test]
public void BOO_40_1()
{
RunCompilerTestCase(@"BOO-40-1.boo");
}
[Test]
public void BOO_407_1()
{
RunCompilerTestCase(@"BOO-407-1.boo");
}
[Test]
public void BOO_408_1()
{
RunCompilerTestCase(@"BOO-408-1.boo");
}
[Test]
public void BOO_411_1()
{
RunCompilerTestCase(@"BOO-411-1.boo");
}
[Test]
public void BOO_417_1()
{
RunCompilerTestCase(@"BOO-417-1.boo");
}
[Test]
public void BOO_420_1()
{
RunCompilerTestCase(@"BOO-420-1.boo");
}
[Test]
public void BOO_440_1()
{
RunCompilerTestCase(@"BOO-440-1.boo");
}
[Test]
public void BOO_440_2()
{
RunCompilerTestCase(@"BOO-440-2.boo");
}
[Test]
public void BOO_440_3()
{
RunCompilerTestCase(@"BOO-440-3.boo");
}
[Test]
public void BOO_441_1()
{
RunCompilerTestCase(@"BOO-441-1.boo");
}
[Test]
public void BOO_441_2()
{
RunCompilerTestCase(@"BOO-441-2.boo");
}
[Test]
public void BOO_46_1()
{
RunCompilerTestCase(@"BOO-46-1.boo");
}
[Test]
public void BOO_46_2()
{
RunCompilerTestCase(@"BOO-46-2.boo");
}
[Test]
public void BOO_464_1()
{
RunCompilerTestCase(@"BOO-464-1.boo");
}
[Test]
public void BOO_474_1()
{
RunCompilerTestCase(@"BOO-474-1.boo");
}
[Test]
public void BOO_540_1()
{
RunCompilerTestCase(@"BOO-540-1.boo");
}
[Test]
public void BOO_540_2()
{
RunCompilerTestCase(@"BOO-540-2.boo");
}
[Test]
public void BOO_549_1()
{
RunCompilerTestCase(@"BOO-549-1.boo");
}
[Test]
public void BOO_569_1()
{
RunCompilerTestCase(@"BOO-569-1.boo");
}
[Test]
public void BOO_585_1()
{
RunCompilerTestCase(@"BOO-585-1.boo");
}
[Test]
public void BOO_590_1()
{
RunCompilerTestCase(@"BOO-590-1.boo");
}
[Test]
public void BOO_603_1()
{
RunCompilerTestCase(@"BOO-603-1.boo");
}
[Test]
public void BOO_605_1()
{
RunCompilerTestCase(@"BOO-605-1.boo");
}
[Test]
public void BOO_608_1()
{
RunCompilerTestCase(@"BOO-608-1.boo");
}
[Test]
public void BOO_612_1()
{
RunCompilerTestCase(@"BOO-612-1.boo");
}
[Test]
public void BOO_612_2()
{
RunCompilerTestCase(@"BOO-612-2.boo");
}
[Test]
public void BOO_632_1()
{
RunCompilerTestCase(@"BOO-632-1.boo");
}
[Test]
public void BOO_642_1()
{
RunCompilerTestCase(@"BOO-642-1.boo");
}
[Test]
public void BOO_650_1()
{
RunCompilerTestCase(@"BOO-650-1.boo");
}
[Test]
public void BOO_651_1()
{
RunCompilerTestCase(@"BOO-651-1.boo");
}
[Test]
public void BOO_656_1()
{
RunCompilerTestCase(@"BOO-656-1.boo");
}
[Test]
public void BOO_662_1()
{
RunCompilerTestCase(@"BOO-662-1.boo");
}
[Test]
public void BOO_662_2()
{
RunCompilerTestCase(@"BOO-662-2.boo");
}
[Test]
public void BOO_684_1()
{
RunCompilerTestCase(@"BOO-684-1.boo");
}
[Test]
public void BOO_685_1()
{
RunCompilerTestCase(@"BOO-685-1.boo");
}
[Test]
public void BOO_697_1()
{
RunCompilerTestCase(@"BOO-697-1.boo");
}
[Test]
public void BOO_698_1()
{
RunCompilerTestCase(@"BOO-698-1.boo");
}
[Test]
public void BOO_705_1()
{
RunCompilerTestCase(@"BOO-705-1.boo");
}
[Test]
public void BOO_707_1()
{
RunCompilerTestCase(@"BOO-707-1.boo");
}
[Test]
public void BOO_709_1()
{
RunCompilerTestCase(@"BOO-709-1.boo");
}
[Test]
public void BOO_710_1()
{
RunCompilerTestCase(@"BOO-710-1.boo");
}
[Test]
public void BOO_714_1()
{
RunCompilerTestCase(@"BOO-714-1.boo");
}
[Test]
public void BOO_719_1()
{
RunCompilerTestCase(@"BOO-719-1.boo");
}
[Test]
public void BOO_719_2()
{
RunCompilerTestCase(@"BOO-719-2.boo");
}
[Test]
public void BOO_723_1()
{
RunCompilerTestCase(@"BOO-723-1.boo");
}
[Test]
public void BOO_724_1()
{
RunCompilerTestCase(@"BOO-724-1.boo");
}
[Test]
public void BOO_724_2()
{
RunCompilerTestCase(@"BOO-724-2.boo");
}
[Test]
public void BOO_725_1()
{
RunCompilerTestCase(@"BOO-725-1.boo");
}
[Test]
public void BOO_729_1()
{
RunCompilerTestCase(@"BOO-729-1.boo");
}
[Test]
public void BOO_736_1()
{
RunCompilerTestCase(@"BOO-736-1.boo");
}
[Test]
public void BOO_739_1()
{
RunCompilerTestCase(@"BOO-739-1.boo");
}
[Test]
public void BOO_739_2()
{
RunCompilerTestCase(@"BOO-739-2.boo");
}
[Test]
public void BOO_747_1()
{
RunCompilerTestCase(@"BOO-747-1.boo");
}
[Test]
public void BOO_747_2()
{
RunCompilerTestCase(@"BOO-747-2.boo");
}
[Test]
public void BOO_748_1()
{
RunCompilerTestCase(@"BOO-748-1.boo");
}
[Test]
public void BOO_75_1()
{
RunCompilerTestCase(@"BOO-75-1.boo");
}
[Test]
public void BOO_753_1()
{
RunCompilerTestCase(@"BOO-753-1.boo");
}
[Test]
public void BOO_753_2()
{
RunCompilerTestCase(@"BOO-753-2.boo");
}
[Test]
public void BOO_76_1()
{
RunCompilerTestCase(@"BOO-76-1.boo");
}
[Test]
public void BOO_76_2()
{
RunCompilerTestCase(@"BOO-76-2.boo");
}
[Test]
public void BOO_77_1()
{
RunCompilerTestCase(@"BOO-77-1.boo");
}
[Test]
public void BOO_770_1()
{
RunCompilerTestCase(@"BOO-770-1.boo");
}
[Ignore("Preference for generic not complete")][Test]
public void BOO_779_1()
{
RunCompilerTestCase(@"BOO-779-1.boo");
}
[Ignore("Preference for generic not complete")][Test]
public void BOO_779_2()
{
RunCompilerTestCase(@"BOO-779-2.boo");
}
[Ignore("Non-IEnumerable definitions of GetEnumerator() not yet supported")][Test]
public void BOO_779_3()
{
RunCompilerTestCase(@"BOO-779-3.boo");
}
[Test]
public void BOO_779_4()
{
RunCompilerTestCase(@"BOO-779-4.boo");
}
[Test]
public void BOO_792_1()
{
RunCompilerTestCase(@"BOO-792-1.boo");
}
[Test]
public void BOO_792_2()
{
RunCompilerTestCase(@"BOO-792-2.boo");
}
[Test]
public void BOO_799_1()
{
RunCompilerTestCase(@"BOO-799-1.boo");
}
[Test]
public void BOO_806_1()
{
RunCompilerTestCase(@"BOO-806-1.boo");
}
[Test]
public void BOO_809_1()
{
RunCompilerTestCase(@"BOO-809-1.boo");
}
[Test]
public void BOO_809_2()
{
RunCompilerTestCase(@"BOO-809-2.boo");
}
[Test]
public void BOO_809_3()
{
RunCompilerTestCase(@"BOO-809-3.boo");
}
[Test]
public void BOO_809_4()
{
RunCompilerTestCase(@"BOO-809-4.boo");
}
[Test]
public void BOO_813_1()
{
RunCompilerTestCase(@"BOO-813-1.boo");
}
[Test]
public void BOO_826()
{
RunCompilerTestCase(@"BOO-826.boo");
}
[Test]
public void BOO_835_1()
{
RunCompilerTestCase(@"BOO-835-1.boo");
}
[Test]
public void BOO_844_1()
{
RunCompilerTestCase(@"BOO-844-1.boo");
}
[Test]
public void BOO_844_2()
{
RunCompilerTestCase(@"BOO-844-2.boo");
}
[Test]
public void BOO_85_1()
{
RunCompilerTestCase(@"BOO-85-1.boo");
}
[Test]
public void BOO_860_1()
{
RunCompilerTestCase(@"BOO-860-1.boo");
}
[Test]
public void BOO_861_1()
{
RunCompilerTestCase(@"BOO-861-1.boo");
}
[Test]
public void BOO_862_1()
{
RunCompilerTestCase(@"BOO-862-1.boo");
}
[Test]
public void BOO_862_2()
{
RunCompilerTestCase(@"BOO-862-2.boo");
}
[Test]
public void BOO_864_1()
{
RunCompilerTestCase(@"BOO-864-1.boo");
}
[Test]
public void BOO_865_1()
{
RunCompilerTestCase(@"BOO-865-1.boo");
}
[Test]
public void BOO_88_1()
{
RunCompilerTestCase(@"BOO-88-1.boo");
}
[Test]
public void BOO_882()
{
RunCompilerTestCase(@"BOO-882.boo");
}
[Test]
public void BOO_893_1()
{
RunCompilerTestCase(@"BOO-893-1.boo");
}
[Test]
public void BOO_90_1()
{
RunCompilerTestCase(@"BOO-90-1.boo");
}
[Test]
public void BOO_913_1()
{
RunCompilerTestCase(@"BOO-913-1.boo");
}
[Test]
public void BOO_935_1()
{
RunCompilerTestCase(@"BOO-935-1.boo");
}
[Test]
public void BOO_935_2()
{
RunCompilerTestCase(@"BOO-935-2.boo");
}
[Test]
public void BOO_948_1()
{
RunCompilerTestCase(@"BOO-948-1.boo");
}
[Test]
public void BOO_949_1()
{
RunCompilerTestCase(@"BOO-949-1.boo");
}
[Test]
public void BOO_949_2()
{
RunCompilerTestCase(@"BOO-949-2.boo");
}
[Test]
public void BOO_952_1()
{
RunCompilerTestCase(@"BOO-952-1.boo");
}
[Test]
public void BOO_955_1()
{
RunCompilerTestCase(@"BOO-955-1.boo");
}
[Test]
public void BOO_958_1()
{
RunCompilerTestCase(@"BOO-958-1.boo");
}
[Test]
public void BOO_960()
{
RunCompilerTestCase(@"BOO-960.boo");
}
[Test]
public void BOO_973_1()
{
RunCompilerTestCase(@"BOO-973-1.boo");
}
[Test]
public void BOO_974_1()
{
RunCompilerTestCase(@"BOO-974-1.boo");
}
[Test]
public void BOO_975_1()
{
RunCompilerTestCase(@"BOO-975-1.boo");
}
[Test]
public void BOO_977_1()
{
RunCompilerTestCase(@"BOO-977-1.boo");
}
[Test]
public void BOO_979_1()
{
RunCompilerTestCase(@"BOO-979-1.boo");
}
[Test]
public void BOO_979_2()
{
RunCompilerTestCase(@"BOO-979-2.boo");
}
[Test]
public void BOO_982_1()
{
RunCompilerTestCase(@"BOO-982-1.boo");
}
[Test]
public void BOO_983_1()
{
RunCompilerTestCase(@"BOO-983-1.boo");
}
[Test]
public void BOO_983_2()
{
RunCompilerTestCase(@"BOO-983-2.boo");
}
[Test]
public void BOO_986_1()
{
RunCompilerTestCase(@"BOO-986-1.boo");
}
[Test]
public void BOO_99_1()
{
RunCompilerTestCase(@"BOO-99-1.boo");
}
[Test]
public void BOO_992_1()
{
RunCompilerTestCase(@"BOO-992-1.boo");
}
[Test]
public void BOO_992_2()
{
RunCompilerTestCase(@"BOO-992-2.boo");
}
[Test]
public void BOO_999_1()
{
RunCompilerTestCase(@"BOO-999-1.boo");
}
[Test]
public void complex_iterators_1()
{
RunCompilerTestCase(@"complex-iterators-1.boo");
}
[Test]
public void duck_default_member_overload()
{
RunCompilerTestCase(@"duck-default-member-overload.boo");
}
[Test]
public void duck_default_setter_overload()
{
RunCompilerTestCase(@"duck-default-setter-overload.boo");
}
[Test]
public void for_re_Split()
{
RunCompilerTestCase(@"for-re-Split.boo");
}
[Test]
public void generators_1()
{
RunCompilerTestCase(@"generators-1.boo");
}
[Test]
public void method_with_type_inference_rule_as_statement()
{
RunCompilerTestCase(@"method-with-type-inference-rule-as-statement.boo");
}
[Test]
public void nullables_and_generators()
{
RunCompilerTestCase(@"nullables-and-generators.boo");
}
[Test]
public void override_inference()
{
RunCompilerTestCase(@"override-inference.boo");
}
override protected string GetRelativeTestCasesPath()
{
return "regression";
}
}
}
| |
#region LGPL License
/*
Axiom Game Engine Library
Copyright (C) 2003 Axiom Project Team
The overall design, and a majority of the core engine and rendering code
contained within this library is a derivative of the open source Object Oriented
Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net.
Many thanks to the OGRE team for maintaining such a high quality project.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#endregion
using System;
namespace Axiom.Core {
/// <summary>
/// This class is necessary so we can store the color components as floating
/// point values in the range [0,1]. It serves as an intermediary to System.Drawing.Color, which
/// stores them as byte values. This doesn't allow for slow color component
/// interpolation, because with the values always being cast back to a byte would lose
/// any small interpolated values (i.e. 223 - .25 as a byte is 223).
/// </summary>
public class ColorEx : IComparable {
#region Member variables
/// <summary>
/// Alpha value [0,1].
/// </summary>
public float a;
/// <summary>
/// Red color component [0,1].
/// </summary>
public float r;
/// <summary>
/// Green color component [0,1].
/// </summary>
public float g;
/// <summary>
/// Blue color component [0,1].
/// </summary>
public float b;
#endregion
#region Constructors
/// <summary>
/// Default constructor.
/// </summary>
public ColorEx() {
// set the color components to a default of 1;
a = 1.0f;
r = 1.0f;
g = 1.0f;
b = 1.0f;
}
/// <summary>
/// Default constructor.
/// </summary>
public ColorEx(float r, float g, float b) : this(1.0f, r, g, b) { }
/// <summary>
/// Constructor taking all component values.
/// </summary>
/// <param name="a">Alpha value.</param>
/// <param name="r">Red color component.</param>
/// <param name="g">Green color component.</param>
/// <param name="b">Blue color component.</param>
public ColorEx(float a, float r, float g, float b) {
this.a = a;
this.r = r;
this.g = g;
this.b = b;
}
/// <summary>
/// Copy constructor.
/// </summary>
public ColorEx(ColorEx other)
: this() {
if (other != null) {
this.a = other.a;
this.r = other.r;
this.g = other.g;
this.b = other.b;
}
}
#endregion Constructors
#region Methods
/// <summary>
/// Returns a copy of this ColorEx instance.
/// </summary>
/// <returns></returns>
public ColorEx Clone() {
return new ColorEx(a, r, g, b);
}
/// <summary>
/// Converts this instance to a <see cref="System.Drawing.Color"/> structure.
/// </summary>
/// <returns></returns>
public System.Drawing.Color ToColor() {
return System.Drawing.Color.FromArgb((int)(a * 255.0f), (int)(r * 255.0f), (int)(g * 255.0f), (int)(b * 255.0f));
}
/// <summary>
/// Converts this color value to packed ABGR format.
/// </summary>
/// <returns></returns>
public uint ToABGR() {
uint result = 0;
result += ((uint)(a * 255.0f)) << 24;
result += ((uint)(b * 255.0f)) << 16;
result += ((uint)(g * 255.0f)) << 8;
result += ((uint)(r * 255.0f));
return result;
}
/// <summary>
/// Converts this color value to packed ARBG format.
/// </summary>
/// <returns></returns>
public uint ToARGB() {
uint result = 0;
result += ((uint)(a * 255.0f)) << 24;
result += ((uint)(r * 255.0f)) << 16;
result += ((uint)(g * 255.0f)) << 8;
result += ((uint)(b * 255.0f));
return result;
}
/// <summary>
/// Populates the color components in a 4 elements array in RGBA order.
/// </summary>
/// <remarks>
/// Primarily used to help in OpenGL.
/// </remarks>
/// <returns></returns>
public void ToArrayRGBA(float[] vals) {
vals[0] = r; vals[1] = g; vals[2] = b; vals[3] = a;
}
/// <summary>
/// Keep all color components in the allowed range of 0.0f .. 1.0f
/// </summary>
public void Saturate() {
a = Math.Min(1.0f, Math.Max(0.0f, a));
r = Math.Min(1.0f, Math.Max(0.0f, r));
g = Math.Min(1.0f, Math.Max(0.0f, g));
b = Math.Min(1.0f, Math.Max(0.0f, b));
}
/// <summary>
/// Static method used to create a new <code>ColorEx</code> instance based
/// on an existing <see cref="System.Drawing.Color"/> structure.
/// </summary>
/// <param name="color">.Net color structure to use as a basis.</param>
/// <returns>A new <code>ColorEx instance.</code></returns>
public static ColorEx FromColor(System.Drawing.Color color) {
return new ColorEx((float)color.A / 255.0f, (float)color.R / 255.0f, (float)color.G / 255.0f, (float)color.B / 255.0f);
}
// arithmetic operations
public static ColorEx operator + (ColorEx c1, ColorEx c2)
{
ColorEx result = new ColorEx();
result.r = c1.r + c2.r;
result.g = c1.g + c2.g;
result.b = c1.b + c2.b;
result.a = c1.a + c2.a;
return result;
}
public static ColorEx operator - (ColorEx c1, ColorEx c2)
{
ColorEx result = new ColorEx();
result.r = c1.r - c2.r;
result.g = c1.g - c2.g;
result.b = c1.b - c2.b;
result.a = c1.a - c2.a;
return result;
}
public static ColorEx operator * (ColorEx c1, ColorEx c2)
{
ColorEx result = new ColorEx();
result.r = c1.r * c2.r;
result.g = c1.g * c2.g;
result.b = c1.b * c2.b;
result.a = c1.a * c2.a;
return result;
}
public static ColorEx operator * (ColorEx c, float scale)
{
ColorEx result = new ColorEx();
result.r = c.r * scale;
result.g = c.g * scale;
result.b = c.b * scale;
result.a = c.a * scale;
return result;
}
#endregion
#region Static color properties
/// <summary>
/// The color Transparent.
/// </summary>
public static ColorEx Transparent {
get {
return new ColorEx(0f, 1f, 1f, 1f);
}
}
/// <summary>
/// The color AliceBlue.
/// </summary>
public static ColorEx AliceBlue {
get {
return new ColorEx(1f, 0.9411765f, 0.972549f, 1f);
}
}
/// <summary>
/// The color AntiqueWhite.
/// </summary>
public static ColorEx AntiqueWhite {
get {
return new ColorEx(1f, 0.9803922f, 0.9215686f, 0.8431373f);
}
}
/// <summary>
/// The color Aqua.
/// </summary>
public static ColorEx Aqua {
get {
return new ColorEx(1f, 0f, 1f, 1f);
}
}
/// <summary>
/// The color Aquamarine.
/// </summary>
public static ColorEx Aquamarine {
get {
return new ColorEx(1f, 0.4980392f, 1f, 0.8313726f);
}
}
/// <summary>
/// The color Azure.
/// </summary>
public static ColorEx Azure {
get {
return new ColorEx(1f, 0.9411765f, 1f, 1f);
}
}
/// <summary>
/// The color Beige.
/// </summary>
public static ColorEx Beige {
get {
return new ColorEx(1f, 0.9607843f, 0.9607843f, 0.8627451f);
}
}
/// <summary>
/// The color Bisque.
/// </summary>
public static ColorEx Bisque {
get {
return new ColorEx(1f, 1f, 0.8941177f, 0.7686275f);
}
}
/// <summary>
/// The color Black.
/// </summary>
public static ColorEx Black {
get {
return new ColorEx(1f, 0f, 0f, 0f);
}
}
/// <summary>
/// The color BlanchedAlmond.
/// </summary>
public static ColorEx BlanchedAlmond {
get {
return new ColorEx(1f, 1f, 0.9215686f, 0.8039216f);
}
}
/// <summary>
/// The color Blue.
/// </summary>
public static ColorEx Blue {
get {
return new ColorEx(1f, 0f, 0f, 1f);
}
}
/// <summary>
/// The color BlueViolet.
/// </summary>
public static ColorEx BlueViolet {
get {
return new ColorEx(1f, 0.5411765f, 0.1686275f, 0.8862745f);
}
}
/// <summary>
/// The color Brown.
/// </summary>
public static ColorEx Brown {
get {
return new ColorEx(1f, 0.6470588f, 0.1647059f, 0.1647059f);
}
}
/// <summary>
/// The color BurlyWood.
/// </summary>
public static ColorEx BurlyWood {
get {
return new ColorEx(1f, 0.8705882f, 0.7215686f, 0.5294118f);
}
}
/// <summary>
/// The color CadetBlue.
/// </summary>
public static ColorEx CadetBlue {
get {
return new ColorEx(1f, 0.372549f, 0.6196079f, 0.627451f);
}
}
/// <summary>
/// The color Chartreuse.
/// </summary>
public static ColorEx Chartreuse {
get {
return new ColorEx(1f, 0.4980392f, 1f, 0f);
}
}
/// <summary>
/// The color Chocolate.
/// </summary>
public static ColorEx Chocolate {
get {
return new ColorEx(1f, 0.8235294f, 0.4117647f, 0.1176471f);
}
}
/// <summary>
/// The color Coral.
/// </summary>
public static ColorEx Coral {
get {
return new ColorEx(1f, 1f, 0.4980392f, 0.3137255f);
}
}
/// <summary>
/// The color CornflowerBlue.
/// </summary>
public static ColorEx CornflowerBlue {
get {
return new ColorEx(1f, 0.3921569f, 0.5843138f, 0.9294118f);
}
}
/// <summary>
/// The color Cornsilk.
/// </summary>
public static ColorEx Cornsilk {
get {
return new ColorEx(1f, 1f, 0.972549f, 0.8627451f);
}
}
/// <summary>
/// The color Crimson.
/// </summary>
public static ColorEx Crimson {
get {
return new ColorEx(1f, 0.8627451f, 0.07843138f, 0.2352941f);
}
}
/// <summary>
/// The color Cyan.
/// </summary>
public static ColorEx Cyan {
get {
return new ColorEx(1f, 0f, 1f, 1f);
}
}
/// <summary>
/// The color DarkBlue.
/// </summary>
public static ColorEx DarkBlue {
get {
return new ColorEx(1f, 0f, 0f, 0.5450981f);
}
}
/// <summary>
/// The color DarkCyan.
/// </summary>
public static ColorEx DarkCyan {
get {
return new ColorEx(1f, 0f, 0.5450981f, 0.5450981f);
}
}
/// <summary>
/// The color DarkGoldenrod.
/// </summary>
public static ColorEx DarkGoldenrod {
get {
return new ColorEx(1f, 0.7215686f, 0.5254902f, 0.04313726f);
}
}
/// <summary>
/// The color DarkGray.
/// </summary>
public static ColorEx DarkGray {
get {
return new ColorEx(1f, 0.6627451f, 0.6627451f, 0.6627451f);
}
}
/// <summary>
/// The color DarkGreen.
/// </summary>
public static ColorEx DarkGreen {
get {
return new ColorEx(1f, 0f, 0.3921569f, 0f);
}
}
/// <summary>
/// The color DarkKhaki.
/// </summary>
public static ColorEx DarkKhaki {
get {
return new ColorEx(1f, 0.7411765f, 0.7176471f, 0.4196078f);
}
}
/// <summary>
/// The color DarkMagenta.
/// </summary>
public static ColorEx DarkMagenta {
get {
return new ColorEx(1f, 0.5450981f, 0f, 0.5450981f);
}
}
/// <summary>
/// The color DarkOliveGreen.
/// </summary>
public static ColorEx DarkOliveGreen {
get {
return new ColorEx(1f, 0.3333333f, 0.4196078f, 0.1843137f);
}
}
/// <summary>
/// The color DarkOrange.
/// </summary>
public static ColorEx DarkOrange {
get {
return new ColorEx(1f, 1f, 0.5490196f, 0f);
}
}
/// <summary>
/// The color DarkOrchid.
/// </summary>
public static ColorEx DarkOrchid {
get {
return new ColorEx(1f, 0.6f, 0.1960784f, 0.8f);
}
}
/// <summary>
/// The color DarkRed.
/// </summary>
public static ColorEx DarkRed {
get {
return new ColorEx(1f, 0.5450981f, 0f, 0f);
}
}
/// <summary>
/// The color DarkSalmon.
/// </summary>
public static ColorEx DarkSalmon {
get {
return new ColorEx(1f, 0.9137255f, 0.5882353f, 0.4784314f);
}
}
/// <summary>
/// The color DarkSeaGreen.
/// </summary>
public static ColorEx DarkSeaGreen {
get {
return new ColorEx(1f, 0.5607843f, 0.7372549f, 0.5450981f);
}
}
/// <summary>
/// The color DarkSlateBlue.
/// </summary>
public static ColorEx DarkSlateBlue {
get {
return new ColorEx(1f, 0.282353f, 0.2392157f, 0.5450981f);
}
}
/// <summary>
/// The color DarkSlateGray.
/// </summary>
public static ColorEx DarkSlateGray {
get {
return new ColorEx(1f, 0.1843137f, 0.3098039f, 0.3098039f);
}
}
/// <summary>
/// The color DarkTurquoise.
/// </summary>
public static ColorEx DarkTurquoise {
get {
return new ColorEx(1f, 0f, 0.8078431f, 0.8196079f);
}
}
/// <summary>
/// The color DarkViolet.
/// </summary>
public static ColorEx DarkViolet {
get {
return new ColorEx(1f, 0.5803922f, 0f, 0.827451f);
}
}
/// <summary>
/// The color DeepPink.
/// </summary>
public static ColorEx DeepPink {
get {
return new ColorEx(1f, 1f, 0.07843138f, 0.5764706f);
}
}
/// <summary>
/// The color DeepSkyBlue.
/// </summary>
public static ColorEx DeepSkyBlue {
get {
return new ColorEx(1f, 0f, 0.7490196f, 1f);
}
}
/// <summary>
/// The color DimGray.
/// </summary>
public static ColorEx DimGray {
get {
return new ColorEx(1f, 0.4117647f, 0.4117647f, 0.4117647f);
}
}
/// <summary>
/// The color DodgerBlue.
/// </summary>
public static ColorEx DodgerBlue {
get {
return new ColorEx(1f, 0.1176471f, 0.5647059f, 1f);
}
}
/// <summary>
/// The color Firebrick.
/// </summary>
public static ColorEx Firebrick {
get {
return new ColorEx(1f, 0.6980392f, 0.1333333f, 0.1333333f);
}
}
/// <summary>
/// The color FloralWhite.
/// </summary>
public static ColorEx FloralWhite {
get {
return new ColorEx(1f, 1f, 0.9803922f, 0.9411765f);
}
}
/// <summary>
/// The color ForestGreen.
/// </summary>
public static ColorEx ForestGreen {
get {
return new ColorEx(1f, 0.1333333f, 0.5450981f, 0.1333333f);
}
}
/// <summary>
/// The color Fuchsia.
/// </summary>
public static ColorEx Fuchsia {
get {
return new ColorEx(1f, 1f, 0f, 1f);
}
}
/// <summary>
/// The color Gainsboro.
/// </summary>
public static ColorEx Gainsboro {
get {
return new ColorEx(1f, 0.8627451f, 0.8627451f, 0.8627451f);
}
}
/// <summary>
/// The color GhostWhite.
/// </summary>
public static ColorEx GhostWhite {
get {
return new ColorEx(1f, 0.972549f, 0.972549f, 1f);
}
}
/// <summary>
/// The color Gold.
/// </summary>
public static ColorEx Gold {
get {
return new ColorEx(1f, 1f, 0.8431373f, 0f);
}
}
/// <summary>
/// The color Goldenrod.
/// </summary>
public static ColorEx Goldenrod {
get {
return new ColorEx(1f, 0.854902f, 0.6470588f, 0.1254902f);
}
}
/// <summary>
/// The color Gray.
/// </summary>
public static ColorEx Gray {
get {
return new ColorEx(1f, 0.5019608f, 0.5019608f, 0.5019608f);
}
}
/// <summary>
/// The color Green.
/// </summary>
public static ColorEx Green {
get {
return new ColorEx(1f, 0f, 0.5019608f, 0f);
}
}
/// <summary>
/// The color GreenYellow.
/// </summary>
public static ColorEx GreenYellow {
get {
return new ColorEx(1f, 0.6784314f, 1f, 0.1843137f);
}
}
/// <summary>
/// The color Honeydew.
/// </summary>
public static ColorEx Honeydew {
get {
return new ColorEx(1f, 0.9411765f, 1f, 0.9411765f);
}
}
/// <summary>
/// The color HotPink.
/// </summary>
public static ColorEx HotPink {
get {
return new ColorEx(1f, 1f, 0.4117647f, 0.7058824f);
}
}
/// <summary>
/// The color IndianRed.
/// </summary>
public static ColorEx IndianRed {
get {
return new ColorEx(1f, 0.8039216f, 0.3607843f, 0.3607843f);
}
}
/// <summary>
/// The color Indigo.
/// </summary>
public static ColorEx Indigo {
get {
return new ColorEx(1f, 0.2941177f, 0f, 0.509804f);
}
}
/// <summary>
/// The color Ivory.
/// </summary>
public static ColorEx Ivory {
get {
return new ColorEx(1f, 1f, 1f, 0.9411765f);
}
}
/// <summary>
/// The color Khaki.
/// </summary>
public static ColorEx Khaki {
get {
return new ColorEx(1f, 0.9411765f, 0.9019608f, 0.5490196f);
}
}
/// <summary>
/// The color Lavender.
/// </summary>
public static ColorEx Lavender {
get {
return new ColorEx(1f, 0.9019608f, 0.9019608f, 0.9803922f);
}
}
/// <summary>
/// The color LavenderBlush.
/// </summary>
public static ColorEx LavenderBlush {
get {
return new ColorEx(1f, 1f, 0.9411765f, 0.9607843f);
}
}
/// <summary>
/// The color LawnGreen.
/// </summary>
public static ColorEx LawnGreen {
get {
return new ColorEx(1f, 0.4862745f, 0.9882353f, 0f);
}
}
/// <summary>
/// The color LemonChiffon.
/// </summary>
public static ColorEx LemonChiffon {
get {
return new ColorEx(1f, 1f, 0.9803922f, 0.8039216f);
}
}
/// <summary>
/// The color LightBlue.
/// </summary>
public static ColorEx LightBlue {
get {
return new ColorEx(1f, 0.6784314f, 0.8470588f, 0.9019608f);
}
}
/// <summary>
/// The color LightCoral.
/// </summary>
public static ColorEx LightCoral {
get {
return new ColorEx(1f, 0.9411765f, 0.5019608f, 0.5019608f);
}
}
/// <summary>
/// The color LightCyan.
/// </summary>
public static ColorEx LightCyan {
get {
return new ColorEx(1f, 0.8784314f, 1f, 1f);
}
}
/// <summary>
/// The color LightGoldenrodYellow.
/// </summary>
public static ColorEx LightGoldenrodYellow {
get {
return new ColorEx(1f, 0.9803922f, 0.9803922f, 0.8235294f);
}
}
/// <summary>
/// The color LightGreen.
/// </summary>
public static ColorEx LightGreen {
get {
return new ColorEx(1f, 0.5647059f, 0.9333333f, 0.5647059f);
}
}
/// <summary>
/// The color LightGray.
/// </summary>
public static ColorEx LightGray {
get {
return new ColorEx(1f, 0.827451f, 0.827451f, 0.827451f);
}
}
/// <summary>
/// The color LightPink.
/// </summary>
public static ColorEx LightPink {
get {
return new ColorEx(1f, 1f, 0.7137255f, 0.7568628f);
}
}
/// <summary>
/// The color LightSalmon.
/// </summary>
public static ColorEx LightSalmon {
get {
return new ColorEx(1f, 1f, 0.627451f, 0.4784314f);
}
}
/// <summary>
/// The color LightSeaGreen.
/// </summary>
public static ColorEx LightSeaGreen {
get {
return new ColorEx(1f, 0.1254902f, 0.6980392f, 0.6666667f);
}
}
/// <summary>
/// The color LightSkyBlue.
/// </summary>
public static ColorEx LightSkyBlue {
get {
return new ColorEx(1f, 0.5294118f, 0.8078431f, 0.9803922f);
}
}
/// <summary>
/// The color LightSlateGray.
/// </summary>
public static ColorEx LightSlateGray {
get {
return new ColorEx(1f, 0.4666667f, 0.5333334f, 0.6f);
}
}
/// <summary>
/// The color LightSteelBlue.
/// </summary>
public static ColorEx LightSteelBlue {
get {
return new ColorEx(1f, 0.6901961f, 0.7686275f, 0.8705882f);
}
}
/// <summary>
/// The color LightYellow.
/// </summary>
public static ColorEx LightYellow {
get {
return new ColorEx(1f, 1f, 1f, 0.8784314f);
}
}
/// <summary>
/// The color Lime.
/// </summary>
public static ColorEx Lime {
get {
return new ColorEx(1f, 0f, 1f, 0f);
}
}
/// <summary>
/// The color LimeGreen.
/// </summary>
public static ColorEx LimeGreen {
get {
return new ColorEx(1f, 0.1960784f, 0.8039216f, 0.1960784f);
}
}
/// <summary>
/// The color Linen.
/// </summary>
public static ColorEx Linen {
get {
return new ColorEx(1f, 0.9803922f, 0.9411765f, 0.9019608f);
}
}
/// <summary>
/// The color Magenta.
/// </summary>
public static ColorEx Magenta {
get {
return new ColorEx(1f, 1f, 0f, 1f);
}
}
/// <summary>
/// The color Maroon.
/// </summary>
public static ColorEx Maroon {
get {
return new ColorEx(1f, 0.5019608f, 0f, 0f);
}
}
/// <summary>
/// The color MediumAquamarine.
/// </summary>
public static ColorEx MediumAquamarine {
get {
return new ColorEx(1f, 0.4f, 0.8039216f, 0.6666667f);
}
}
/// <summary>
/// The color MediumBlue.
/// </summary>
public static ColorEx MediumBlue {
get {
return new ColorEx(1f, 0f, 0f, 0.8039216f);
}
}
/// <summary>
/// The color MediumOrchid.
/// </summary>
public static ColorEx MediumOrchid {
get {
return new ColorEx(1f, 0.7294118f, 0.3333333f, 0.827451f);
}
}
/// <summary>
/// The color MediumPurple.
/// </summary>
public static ColorEx MediumPurple {
get {
return new ColorEx(1f, 0.5764706f, 0.4392157f, 0.8588235f);
}
}
/// <summary>
/// The color MediumSeaGreen.
/// </summary>
public static ColorEx MediumSeaGreen {
get {
return new ColorEx(1f, 0.2352941f, 0.7019608f, 0.4431373f);
}
}
/// <summary>
/// The color MediumSlateBlue.
/// </summary>
public static ColorEx MediumSlateBlue {
get {
return new ColorEx(1f, 0.4823529f, 0.4078431f, 0.9333333f);
}
}
/// <summary>
/// The color MediumSpringGreen.
/// </summary>
public static ColorEx MediumSpringGreen {
get {
return new ColorEx(1f, 0f, 0.9803922f, 0.6039216f);
}
}
/// <summary>
/// The color MediumTurquoise.
/// </summary>
public static ColorEx MediumTurquoise {
get {
return new ColorEx(1f, 0.282353f, 0.8196079f, 0.8f);
}
}
/// <summary>
/// The color MediumVioletRed.
/// </summary>
public static ColorEx MediumVioletRed {
get {
return new ColorEx(1f, 0.7803922f, 0.08235294f, 0.5215687f);
}
}
/// <summary>
/// The color MidnightBlue.
/// </summary>
public static ColorEx MidnightBlue {
get {
return new ColorEx(1f, 0.09803922f, 0.09803922f, 0.4392157f);
}
}
/// <summary>
/// The color MintCream.
/// </summary>
public static ColorEx MintCream {
get {
return new ColorEx(1f, 0.9607843f, 1f, 0.9803922f);
}
}
/// <summary>
/// The color MistyRose.
/// </summary>
public static ColorEx MistyRose {
get {
return new ColorEx(1f, 1f, 0.8941177f, 0.8823529f);
}
}
/// <summary>
/// The color Moccasin.
/// </summary>
public static ColorEx Moccasin {
get {
return new ColorEx(1f, 1f, 0.8941177f, 0.7098039f);
}
}
/// <summary>
/// The color NavajoWhite.
/// </summary>
public static ColorEx NavajoWhite {
get {
return new ColorEx(1f, 1f, 0.8705882f, 0.6784314f);
}
}
/// <summary>
/// The color Navy.
/// </summary>
public static ColorEx Navy {
get {
return new ColorEx(1f, 0f, 0f, 0.5019608f);
}
}
/// <summary>
/// The color OldLace.
/// </summary>
public static ColorEx OldLace {
get {
return new ColorEx(1f, 0.9921569f, 0.9607843f, 0.9019608f);
}
}
/// <summary>
/// The color Olive.
/// </summary>
public static ColorEx Olive {
get {
return new ColorEx(1f, 0.5019608f, 0.5019608f, 0f);
}
}
/// <summary>
/// The color OliveDrab.
/// </summary>
public static ColorEx OliveDrab {
get {
return new ColorEx(1f, 0.4196078f, 0.5568628f, 0.1372549f);
}
}
/// <summary>
/// The color Orange.
/// </summary>
public static ColorEx Orange {
get {
return new ColorEx(1f, 1f, 0.6470588f, 0f);
}
}
/// <summary>
/// The color OrangeRed.
/// </summary>
public static ColorEx OrangeRed {
get {
return new ColorEx(1f, 1f, 0.2705882f, 0f);
}
}
/// <summary>
/// The color Orchid.
/// </summary>
public static ColorEx Orchid {
get {
return new ColorEx(1f, 0.854902f, 0.4392157f, 0.8392157f);
}
}
/// <summary>
/// The color PaleGoldenrod.
/// </summary>
public static ColorEx PaleGoldenrod {
get {
return new ColorEx(1f, 0.9333333f, 0.9098039f, 0.6666667f);
}
}
/// <summary>
/// The color PaleGreen.
/// </summary>
public static ColorEx PaleGreen {
get {
return new ColorEx(1f, 0.5960785f, 0.9843137f, 0.5960785f);
}
}
/// <summary>
/// The color PaleTurquoise.
/// </summary>
public static ColorEx PaleTurquoise {
get {
return new ColorEx(1f, 0.6862745f, 0.9333333f, 0.9333333f);
}
}
/// <summary>
/// The color PaleVioletRed.
/// </summary>
public static ColorEx PaleVioletRed {
get {
return new ColorEx(1f, 0.8588235f, 0.4392157f, 0.5764706f);
}
}
/// <summary>
/// The color PapayaWhip.
/// </summary>
public static ColorEx PapayaWhip {
get {
return new ColorEx(1f, 1f, 0.9372549f, 0.8352941f);
}
}
/// <summary>
/// The color PeachPuff.
/// </summary>
public static ColorEx PeachPuff {
get {
return new ColorEx(1f, 1f, 0.854902f, 0.7254902f);
}
}
/// <summary>
/// The color Peru.
/// </summary>
public static ColorEx Peru {
get {
return new ColorEx(1f, 0.8039216f, 0.5215687f, 0.2470588f);
}
}
/// <summary>
/// The color Pink.
/// </summary>
public static ColorEx Pink {
get {
return new ColorEx(1f, 1f, 0.7529412f, 0.7960784f);
}
}
/// <summary>
/// The color Plum.
/// </summary>
public static ColorEx Plum {
get {
return new ColorEx(1f, 0.8666667f, 0.627451f, 0.8666667f);
}
}
/// <summary>
/// The color PowderBlue.
/// </summary>
public static ColorEx PowderBlue {
get {
return new ColorEx(1f, 0.6901961f, 0.8784314f, 0.9019608f);
}
}
/// <summary>
/// The color Purple.
/// </summary>
public static ColorEx Purple {
get {
return new ColorEx(1f, 0.5019608f, 0f, 0.5019608f);
}
}
/// <summary>
/// The color Red.
/// </summary>
public static ColorEx Red {
get {
return new ColorEx(1f, 1f, 0f, 0f);
}
}
/// <summary>
/// The color RosyBrown.
/// </summary>
public static ColorEx RosyBrown {
get {
return new ColorEx(1f, 0.7372549f, 0.5607843f, 0.5607843f);
}
}
/// <summary>
/// The color RoyalBlue.
/// </summary>
public static ColorEx RoyalBlue {
get {
return new ColorEx(1f, 0.254902f, 0.4117647f, 0.8823529f);
}
}
/// <summary>
/// The color SaddleBrown.
/// </summary>
public static ColorEx SaddleBrown {
get {
return new ColorEx(1f, 0.5450981f, 0.2705882f, 0.07450981f);
}
}
/// <summary>
/// The color Salmon.
/// </summary>
public static ColorEx Salmon {
get {
return new ColorEx(1f, 0.9803922f, 0.5019608f, 0.4470588f);
}
}
/// <summary>
/// The color SandyBrown.
/// </summary>
public static ColorEx SandyBrown {
get {
return new ColorEx(1f, 0.9568627f, 0.6431373f, 0.3764706f);
}
}
/// <summary>
/// The color SeaGreen.
/// </summary>
public static ColorEx SeaGreen {
get {
return new ColorEx(1f, 0.1803922f, 0.5450981f, 0.3411765f);
}
}
/// <summary>
/// The color SeaShell.
/// </summary>
public static ColorEx SeaShell {
get {
return new ColorEx(1f, 1f, 0.9607843f, 0.9333333f);
}
}
/// <summary>
/// The color Sienna.
/// </summary>
public static ColorEx Sienna {
get {
return new ColorEx(1f, 0.627451f, 0.3215686f, 0.1764706f);
}
}
/// <summary>
/// The color Silver.
/// </summary>
public static ColorEx Silver {
get {
return new ColorEx(1f, 0.7529412f, 0.7529412f, 0.7529412f);
}
}
/// <summary>
/// The color SkyBlue.
/// </summary>
public static ColorEx SkyBlue {
get {
return new ColorEx(1f, 0.5294118f, 0.8078431f, 0.9215686f);
}
}
/// <summary>
/// The color SlateBlue.
/// </summary>
public static ColorEx SlateBlue {
get {
return new ColorEx(1f, 0.4156863f, 0.3529412f, 0.8039216f);
}
}
/// <summary>
/// The color SlateGray.
/// </summary>
public static ColorEx SlateGray {
get {
return new ColorEx(1f, 0.4392157f, 0.5019608f, 0.5647059f);
}
}
/// <summary>
/// The color Snow.
/// </summary>
public static ColorEx Snow {
get {
return new ColorEx(1f, 1f, 0.9803922f, 0.9803922f);
}
}
/// <summary>
/// The color SpringGreen.
/// </summary>
public static ColorEx SpringGreen {
get {
return new ColorEx(1f, 0f, 1f, 0.4980392f);
}
}
/// <summary>
/// The color SteelBlue.
/// </summary>
public static ColorEx SteelBlue {
get {
return new ColorEx(1f, 0.2745098f, 0.509804f, 0.7058824f);
}
}
/// <summary>
/// The color Tan.
/// </summary>
public static ColorEx Tan {
get {
return new ColorEx(1f, 0.8235294f, 0.7058824f, 0.5490196f);
}
}
/// <summary>
/// The color Teal.
/// </summary>
public static ColorEx Teal {
get {
return new ColorEx(1f, 0f, 0.5019608f, 0.5019608f);
}
}
/// <summary>
/// The color Thistle.
/// </summary>
public static ColorEx Thistle {
get {
return new ColorEx(1f, 0.8470588f, 0.7490196f, 0.8470588f);
}
}
/// <summary>
/// The color Tomato.
/// </summary>
public static ColorEx Tomato {
get {
return new ColorEx(1f, 1f, 0.3882353f, 0.2784314f);
}
}
/// <summary>
/// The color Turquoise.
/// </summary>
public static ColorEx Turquoise {
get {
return new ColorEx(1f, 0.2509804f, 0.8784314f, 0.8156863f);
}
}
/// <summary>
/// The color Violet.
/// </summary>
public static ColorEx Violet {
get {
return new ColorEx(1f, 0.9333333f, 0.509804f, 0.9333333f);
}
}
/// <summary>
/// The color Wheat.
/// </summary>
public static ColorEx Wheat {
get {
return new ColorEx(1f, 0.9607843f, 0.8705882f, 0.7019608f);
}
}
/// <summary>
/// The color White.
/// </summary>
public static ColorEx White {
get {
return new ColorEx(1f, 1f, 1f, 1f);
}
}
/// <summary>
/// The color WhiteSmoke.
/// </summary>
public static ColorEx WhiteSmoke {
get {
return new ColorEx(1f, 0.9607843f, 0.9607843f, 0.9607843f);
}
}
/// <summary>
/// The color Yellow.
/// </summary>
public static ColorEx Yellow {
get {
return new ColorEx(1f, 1f, 1f, 0f);
}
}
/// <summary>
/// The color YellowGreen.
/// </summary>
public static ColorEx YellowGreen {
get {
return new ColorEx(1f, 0.6039216f, 0.8039216f, 0.1960784f);
}
}
/// <summary>
/// The color with all elements zero.
/// </summary>
public static ColorEx Zero {
get {
return new ColorEx(0f, 0f, 0f, 0f);
}
}
public static ColorEx Parse_0_255_String(string parsableText)
{
if(parsableText == null)
throw new ArgumentException("The parsableText parameter cannot be null.");
string[] vals = parsableText.TrimStart('(','[','<').TrimEnd(')',']','>').Split(',');
if(vals.Length < 3)
throw new FormatException(string.Format("Cannot parse the text '{0}' because it must of the form (r,g,b) or (r,g,b,a)",
parsableText));
float r, g, b, a;
try
{
r = int.Parse(vals[0].Trim()) / 255f;
g = int.Parse(vals[1].Trim()) / 255f;
b = int.Parse(vals[2].Trim()) / 255f;
if (vals.Length == 4)
a = int.Parse(vals[3].Trim()) / 255f;
else
a = 1.0f;
}
catch(Exception)
{
throw new FormatException("The parts of the ColorEx in Parse_0_255 must be integers");
}
return new ColorEx(a, r, g, b);
}
public string To_0_255_String()
{
return string.Format("({0},{1},{2},{3})",
(int)(r * 255f),
(int)(g * 255f),
(int)(b * 255f),
(int)(a * 255f));
}
public override string ToString()
{
return string.Format("({0},{1},{2},{3})",r, g, b, a);
}
#endregion Static color properties
#region Object overloads
/// <summary>
/// Override GetHashCode.
/// </summary>
/// <remarks>
/// Done mainly to quash warnings, no real need for it.
/// </remarks>
/// <returns></returns>
public override int GetHashCode() {
return (int)this.ToARGB();
}
#endregion Object overloads
#region IComparable Members
/// <summary>
/// Used to compare 2 ColorEx objects for equality.
/// </summary>
/// <param name="obj">An instance of a ColorEx object to compare to this instance.</param>
/// <returns>0 if they are equal, 1 if they are not.</returns>
public int CompareTo(object obj) {
ColorEx other = obj as ColorEx;
if(this.a == other.a &&
this.r == other.r &&
this.g == other.g &&
this.b == other.b) {
return 0;
}
return 1;
}
#endregion
}
}
| |
using System;
using Xunit;
using System.IO;
using System.Text;
namespace Pfim.Tests
{
public class TargaTests
{
[Fact]
public void ParseTargaTrue24SingleColor()
{
byte[] expected = new byte[64 * 64 * 3];
for (int i = 0; i < expected.Length; i += 3)
{
expected[i] = 255;
expected[i + 1] = 176;
expected[i + 2] = 0;
}
var image = Pfim.FromFile(Path.Combine("data", "true-24.tga"));
Assert.Equal(expected, image.Data);
}
[Fact]
public void ParseTargaTrue32SingleColor()
{
byte[] expected = new byte[64 * 64 * 4];
for (int i = 0; i < expected.Length; i += 4)
{
expected[i] = 0;
expected[i + 1] = 0;
expected[i + 2] = 127;
expected[i + 3] = 255;
}
var image = Pfim.FromFile(Path.Combine("data", "true-32.tga"));
Assert.Equal(expected, image.Data);
}
[Fact]
public void ParseTarga32SingleSmallRunLength()
{
byte[] data = new byte[8];
byte[] stream = {129, 2, 4, 6, 8};
CompressedTarga.RunLength(data, stream, 0, 0, 4);
Assert.Equal(new byte[] {2, 4, 6, 8, 2, 4, 6, 8}, data);
}
[Fact]
public void ParseTarga24SingleSmallRunLength()
{
byte[] data = new byte[6];
byte[] stream = {129, 2, 4, 6};
CompressedTarga.RunLength(data, stream, 0, 0, 3);
Assert.Equal(new byte[] {2, 4, 6, 2, 4, 6}, data);
}
[Fact]
public void ParseTarga24RunLength()
{
byte[] data = new byte[18];
byte[] stream = {132, 2, 4, 6, 128, 8, 10, 12};
CompressedTarga.RunLength(data, stream, 0, 0, 3);
Assert.Equal(new byte[] {2, 4, 6, 2, 4, 6, 2, 4, 6, 2, 4, 6, 2, 4, 6, 0, 0, 0}, data);
}
[Fact]
public void ParseTarga32RunLength()
{
byte[] data = new byte[64 * 4];
int i = 0;
for (; i < 32 * 4; i += 4)
{
data[i] = 0;
data[i + 1] = 216;
data[i + 2] = 255;
data[i + 3] = 255;
}
for (; i < 32 * 4 + 16 * 4; i += 4)
{
data[i] = 255;
data[i + 1] = 148;
data[i + 2] = 0;
data[i + 3] = 255;
}
for (; i < 32 * 4 + 16 * 4 + 8 * 4; i += 4)
{
data[i] = 0;
data[i + 1] = 255;
data[i + 2] = 76;
data[i + 3] = 255;
}
for (; i < 32 * 4 + 16 * 4 + 8 * 4 + 8 * 4; i += 4)
{
data[i] = 0;
data[i + 1] = 0;
data[i + 2] = 255;
data[i + 3] = 255;
}
var image = Pfim.FromFile(Path.Combine("data", "true-32-rle.tga"));
Assert.Equal(data, image.Data);
}
[Fact]
public void ParseTarga24TrueRunLength()
{
byte[] data = new byte[64 * 3];
int i = 0;
for (; i < 32 * 3; i += 3)
{
data[i] = 0;
data[i + 1] = 216;
data[i + 2] = 255;
}
for (; i < 32 * 3 + 16 * 3; i += 3)
{
data[i] = 255;
data[i + 1] = 148;
data[i + 2] = 0;
}
for (; i < 32 * 3 + 16 * 3 + 8 * 3; i += 3)
{
data[i] = 0;
data[i + 1] = 255;
data[i + 2] = 76;
}
for (; i < 32 * 3 + 16 * 3 + 8 * 3 + 8 * 3; i += 3)
{
data[i] = 0;
data[i + 1] = 0;
data[i + 2] = 255;
}
var image = Pfim.FromFile(Path.Combine("data", "true-24-rle.tga"));
Assert.Equal(data, image.Data);
}
[Fact]
public void ParseUncompressedNonSquareTga()
{
var image = Pfim.FromFile(Path.Combine("data", "tiny-rect.tga"));
byte[] data = new byte[12 * 20 * 4];
for (int i = 0; i < data.Length; i += 4)
{
data[i] = 0;
data[i + 1] = 216;
data[i + 2] = 255;
data[i + 3] = 255;
}
Assert.Equal(data, image.Data);
}
[Fact]
public void ParseTrueTarga32MixedEncoding()
{
var image = Pfim.FromFile(Path.Combine("data", "true-32-mixed.tga"));
byte[] data = new byte[256];
for (int i = 0; i < 16 * 4; i += 4)
{
data[i] = 0;
data[i + 1] = 216;
data[i + 2] = 255;
data[i + 3] = 255;
}
Array.Copy(new byte[] {0, 0, 0, 255}, 0, data, 64, 4);
Array.Copy(new byte[] {64, 64, 64, 255}, 0, data, 68, 4);
Array.Copy(new byte[] {0, 0, 255, 255}, 0, data, 72, 4);
Array.Copy(new byte[] {0, 106, 255, 255}, 0, data, 76, 4);
Array.Copy(new byte[] {0, 216, 255, 255}, 0, data, 80, 4);
Array.Copy(new byte[] {0, 255, 182, 255}, 0, data, 84, 4);
Array.Copy(new byte[] {0, 255, 76, 255}, 0, data, 88, 4);
Array.Copy(new byte[] {33, 255, 0, 255}, 0, data, 92, 4);
Array.Copy(new byte[] {144, 255, 0, 255}, 0, data, 96, 4);
Array.Copy(new byte[] {255, 255, 0, 255}, 0, data, 100, 4);
Array.Copy(new byte[] {255, 148, 0, 255}, 0, data, 104, 4);
Array.Copy(new byte[] {255, 38, 0, 255}, 0, data, 108, 4);
Array.Copy(new byte[] {255, 0, 72, 255}, 0, data, 112, 4);
Array.Copy(new byte[] {255, 0, 178, 255}, 0, data, 116, 4);
Array.Copy(new byte[] {220, 0, 255, 255}, 0, data, 120, 4);
Array.Copy(new byte[] {110, 0, 255, 255}, 0, data, 124, 4);
for (int i = 128; i < 192; i += 4)
{
data[i] = 255;
data[i + 1] = 148;
data[i + 2] = 0;
data[i + 3] = 255;
}
for (int i = 192; i < 224; i += 4)
{
data[i] = 0;
data[i + 1] = 255;
data[i + 2] = 76;
data[i + 3] = 255;
}
for (int i = 224; i < 256; i += 4)
{
data[i] = 0;
data[i + 1] = 0;
data[i + 2] = 255;
data[i + 3] = 255;
}
Assert.Equal(data, image.Data);
}
[Fact]
public void ParseLarge32TargetImage()
{
var image = Pfim.FromFile(Path.Combine("data", "true-32-rle-large.tga"));
byte[] data = new byte[1200 * 1200 * 4];
for (int i = 0; i < data.Length; i += 4)
{
data[i] = 0;
data[i + 1] = 51;
data[i + 2] = 127;
data[i + 3] = 255;
}
Assert.Equal(data, image.Data);
}
[Fact]
public void ParseTargaTopLeft()
{
bool seenBlue = false;
var image = Pfim.FromFile(Path.Combine("data", "rgb24_top_left.tga"));
for (int i = 0; i < image.Data.Length; i += 3)
{
seenBlue |= image.Data[i] == 12 && image.Data[i + 1] == 0 && image.Data[i + 2] == 255;
if (image.Data[i] == 255 && image.Data[i + 1] == 4 && image.Data[i + 2] == 4 && !seenBlue)
{
Assert.True(false, "Expected to see blue before red (this could mean that the color channels are swapped)");
}
if (!((image.Data[i] == 0 && image.Data[i + 1] == 255 && image.Data[i + 2] == 0) ||
(image.Data[i] == 255 && image.Data[i + 1] == 0 && image.Data[i + 2] == 12) ||
(image.Data[i] == 255 && image.Data[i + 1] == 255 && image.Data[i + 2] == 255) ||
(image.Data[i + 2] == 255 && image.Data[i + 1] == image.Data[i])))
{
Assert.True(false, $"Did not expect pixel {image.Data[i]} {image.Data[i + 1]} {image.Data[i + 2]}");
}
}
}
[Fact]
public void ParseTargaTopLeftColorMap()
{
var image = Pfim.FromFile(Path.Combine("data", "rgb24_top_left_colormap.tga"), new PfimConfig(applyColorMap: false));
Assert.Equal(8, image.BitsPerPixel);
Assert.Equal(4096, image.Data.Length);
Assert.NotEqual(ImageFormat.Rgb24, image.Format);
image.ApplyColorMap();
Assert.Equal(ImageFormat.Rgb24, image.Format);
Assert.Equal(255, image.Data[0]);
Assert.Equal(255, image.Data[1]);
Assert.Equal(255, image.Data[2]);
Assert.Equal(255, image.Data[3]);
Assert.Equal(255, image.Data[4]);
Assert.Equal(255, image.Data[5]);
}
[Fact]
public void TargaColorMapIdempotent()
{
var image = Pfim.FromFile(Path.Combine("data", "rgb24_top_left_colormap.tga"), new PfimConfig(applyColorMap: false));
var firstData = image.Data;
var firstLen = image.DataLen;
image.ApplyColorMap();
var secondData = image.Data;
var secondLen = image.DataLen;
image.ApplyColorMap();
var thirdData = image.Data;
var thirdLen = image.DataLen;
Assert.NotEqual(firstLen, secondLen);
Assert.Equal(secondLen, thirdLen);
Assert.True(ReferenceEquals(secondData, thirdData));
}
[Fact]
public void ParseTargaTopLeftRleStride()
{
var data = File.ReadAllBytes(Path.Combine("data", "DSCN1910_24bpp_uncompressed_10_2.tga"));
var image = Targa.Create(data, new PfimConfig());
Assert.Equal(461, image.Width);
}
[Fact]
public void ParseTargaTopLeftStride()
{
var data = File.ReadAllBytes(Path.Combine("data", "DSCN1910_24bpp_uncompressed_10_3.tga"));
var image = Targa.Create(data, new PfimConfig());
Assert.Equal(461, image.Width);
Assert.True(image.Data[460 * 3] != 0 && image.Data[461 * 3 + 1] != 0 && image.Data[461 * 3 + 2] != 0);
}
[Fact]
public void ParseLargeTargaTopLeft()
{
var image = Pfim.FromFile(Path.Combine("data", "large-top-left.tga"));
foreach (byte bt in image.Data)
{
Assert.Equal(0, bt);
}
}
[Fact]
public void ParseLargeTargaBottomLeft()
{
var image = Pfim.FromFile(Path.Combine("data", "marbles.tga"));
Assert.Equal(4264260, image.Data.Length);
Assert.Equal(0, image.Data[0]);
Assert.Equal(0, image.Data[1]);
Assert.Equal(0, image.Data[2]);
}
[Fact]
public void ParseMarblesTarga()
{
var image = Pfim.FromFile(Path.Combine("data", "marbles2.tga"));
Assert.Equal(100 * 71 * 3, image.Data.Length);
Assert.Equal(2, image.Data[0]);
Assert.Equal(3, image.Data[1]);
Assert.Equal(3, image.Data[2]);
}
[Fact]
public void ParseTransparentTarga()
{
var image = Pfim.FromFile(Path.Combine("data", "flag_t32.tga"));
for (int i = 0; i < image.Data.Length; i += 4)
{
Assert.Equal(0, image.Data[i + 3]);
}
}
[Fact]
public void InvalidTargaException()
{
var data = Encoding.ASCII.GetBytes("Hello world! A wonderful evening");
var ex = Assert.ThrowsAny<Exception>(() => Pfim.FromStream(new MemoryStream(data)));
Assert.Equal("Detected invalid targa image", ex.Message);
}
}
}
| |
//
// Copyright 2014 Gustavo J Knuppe (https://github.com/knuppe)
//
// 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.
//
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - May you do good and not evil. -
// - May you find forgiveness for yourself and forgive others. -
// - May you share freely, never taking more than you give. -
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//
/*
Copyright (c) 2001, Dr Martin Porter
Copyright (c) 2002, Richard Boulton
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holders 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.
*/
// This file was generated automatically by the Snowball to OpenNLP and
// ported to SharpNL
namespace SharpNL.Stemmer.Snowball {
public class DutchStemmer : SnowballStemmer {
private static DutchStemmer instance;
/// <summary>
/// Gets the <see cref="DutchStemmer"/> instance.
/// </summary>
/// <value>The <see cref="DutchStemmer"/> instance.</value>
public static DutchStemmer Instance => instance ?? (instance = new DutchStemmer());
private DutchStemmer() { }
/// <summary>
/// Reduces the given word into its stem.
/// </summary>
/// <param name="word">The word.</param>
/// <returns>The stemmed word.</returns>
public override string Stem(string word) {
Current = word.ToLowerInvariant();
CanStem();
return Current;
}
private static readonly Among[] a_0 = {
new Among("", -1, 6, null),
new Among("\u00E1", 0, 1, null),
new Among("\u00E4", 0, 1, null),
new Among("\u00E9", 0, 2, null),
new Among("\u00EB", 0, 2, null),
new Among("\u00ED", 0, 3, null),
new Among("\u00EF", 0, 3, null),
new Among("\u00F3", 0, 4, null),
new Among("\u00F6", 0, 4, null),
new Among("\u00FA", 0, 5, null),
new Among("\u00FC", 0, 5, null)
};
private static readonly Among[] a_1 = {
new Among("", -1, 3, null),
new Among("I", 0, 2, null),
new Among("Y", 0, 1, null)
};
private static readonly Among[] a_2 = {
new Among("dd", -1, -1, null),
new Among("kk", -1, -1, null),
new Among("tt", -1, -1, null)
};
private static readonly Among[] a_3 = {
new Among("ene", -1, 2, null),
new Among("se", -1, 3, null),
new Among("en", -1, 2, null),
new Among("heden", 2, 1, null),
new Among("s", -1, 3, null)
};
private static readonly Among[] a_4 = {
new Among("end", -1, 1, null),
new Among("ig", -1, 2, null),
new Among("ing", -1, 1, null),
new Among("lijk", -1, 3, null),
new Among("baar", -1, 4, null),
new Among("bar", -1, 5, null)
};
private static readonly Among[] a_5 = {
new Among("aa", -1, -1, null),
new Among("ee", -1, -1, null),
new Among("oo", -1, -1, null),
new Among("uu", -1, -1, null)
};
private static readonly char[] g_v = {
(char) 17, (char) 65, (char) 16, (char) 1, (char) 0, (char) 0, (char) 0,
(char) 0, (char) 0, (char) 0, (char) 0, (char) 0, (char) 0, (char) 0,
(char) 0, (char) 0, (char) 128
};
private static readonly char[] g_v_I = {
(char) 1, (char) 0, (char) 0, (char) 17, (char) 65, (char) 16, (char) 1,
(char) 0, (char) 0, (char) 0, (char) 0, (char) 0, (char) 0, (char) 0,
(char) 0, (char) 0, (char) 0, (char) 0, (char) 0, (char) 128
};
private static readonly char[] g_v_j = {
(char) 17, (char) 67, (char) 16, (char) 1, (char) 0, (char) 0, (char) 0,
(char) 0, (char) 0, (char) 0, (char) 0, (char) 0, (char) 0, (char) 0,
(char) 0, (char) 0, (char) 128
};
private bool B_e_found;
private int I_p1;
private int I_p2;
private void copy_from(DutchStemmer other) {
I_p2 = other.I_p2;
I_p1 = other.I_p1;
B_e_found = other.B_e_found;
base.copy_from(other);
}
private bool r_prelude() {
var subroot = false;
int among_var;
int v_1;
int v_2;
int v_3;
int v_4;
int v_5;
int v_6;
// (, line 41
// test, line 42
v_1 = cursor;
// repeat, line 42
replab0:
while (true) {
v_2 = cursor;
do {
// (, line 42
// [, line 43
bra = cursor;
// substring, line 43
among_var = find_among(a_0, 11);
if (among_var == 0) {
break;
}
// ], line 43
ket = cursor;
switch (among_var) {
case 0:
subroot = true;
break;
case 1:
// (, line 45
// <-, line 45
slice_from("a");
break;
case 2:
// (, line 47
// <-, line 47
slice_from("e");
break;
case 3:
// (, line 49
// <-, line 49
slice_from("i");
break;
case 4:
// (, line 51
// <-, line 51
slice_from("o");
break;
case 5:
// (, line 53
// <-, line 53
slice_from("u");
break;
case 6:
// (, line 54
// next, line 54
if (cursor >= limit) {
subroot = true;
break;
}
cursor++;
break;
}
if (subroot) {
subroot = false;
break;
}
if (!subroot) {
goto replab0;
}
} while (false);
cursor = v_2;
break;
}
cursor = v_1;
// try, line 57
v_3 = cursor;
do {
// (, line 57
// [, line 57
bra = cursor;
// literal, line 57
if (!(eq_s(1, "y"))) {
cursor = v_3;
break;
}
// ], line 57
ket = cursor;
// <-, line 57
slice_from("Y");
} while (false);
// repeat, line 58
replab3:
while (true) {
v_4 = cursor;
do {
// goto, line 58
while (true) {
v_5 = cursor;
do {
// (, line 58
if (!(in_grouping(g_v, 97, 232))) {
break;
}
// [, line 59
bra = cursor;
// or, line 59
do {
v_6 = cursor;
do {
// (, line 59
// literal, line 59
if (!(eq_s(1, "i"))) {
break;
}
// ], line 59
ket = cursor;
if (!(in_grouping(g_v, 97, 232))) {
break;
}
// <-, line 59
slice_from("I");
subroot = true;
if (subroot) break;
} while (false);
if (subroot) {
subroot = false;
break;
}
cursor = v_6;
// (, line 60
// literal, line 60
if (!(eq_s(1, "y"))) {
subroot = true;
break;
}
// ], line 60
ket = cursor;
// <-, line 60
slice_from("Y");
} while (false);
if (subroot) {
subroot = false;
break;
}
cursor = v_5;
subroot = true;
if (subroot) break;
} while (false);
if (subroot) {
subroot = false;
break;
}
cursor = v_5;
if (cursor >= limit) {
subroot = true;
break;
}
cursor++;
}
if (subroot) {
subroot = false;
break;
}
if (!subroot) {
goto replab3;
}
} while (false);
cursor = v_4;
break;
}
return true;
}
private bool r_mark_regions() {
var subroot = false;
// (, line 64
I_p1 = limit;
I_p2 = limit;
// gopast, line 69
// golab0:
while (true) {
do {
if (!(in_grouping(g_v, 97, 232))) {
break;
}
subroot = true;
if (subroot) break;
} while (false);
if (subroot) {
subroot = false;
break;
}
if (cursor >= limit) {
return false;
}
cursor++;
}
// gopast, line 69
while (true) {
do {
if (!(out_grouping(g_v, 97, 232))) {
break;
}
subroot = true;
if (subroot) break;
} while (false);
if (subroot) {
subroot = false;
break;
}
if (cursor >= limit) {
return false;
}
cursor++;
}
// setmark p1, line 69
I_p1 = cursor;
// try, line 70
do {
// (, line 70
if (!(I_p1 < 3)) {
break;
}
I_p1 = 3;
} while (false);
// gopast, line 71
while (true) {
do {
if (!(in_grouping(g_v, 97, 232))) {
break;
}
subroot = true;
if (subroot) break;
} while (false);
if (subroot) {
subroot = false;
break;
}
if (cursor >= limit) {
return false;
}
cursor++;
}
// gopast, line 71
while (true) {
do {
if (!(out_grouping(g_v, 97, 232))) {
break;
}
subroot = true;
if (subroot) break;
} while (false);
if (subroot) {
subroot = false;
break;
}
if (cursor >= limit) {
return false;
}
cursor++;
}
// setmark p2, line 71
I_p2 = cursor;
return true;
}
private bool r_postlude() {
var subroot = false;
int among_var;
int v_1;
// repeat, line 75
replab0:
while (true) {
v_1 = cursor;
do {
// (, line 75
// [, line 77
bra = cursor;
// substring, line 77
among_var = find_among(a_1, 3);
if (among_var == 0) {
break;
}
// ], line 77
ket = cursor;
switch (among_var) {
case 0:
subroot = true;
break;
case 1:
// (, line 78
// <-, line 78
slice_from("y");
break;
case 2:
// (, line 79
// <-, line 79
slice_from("i");
break;
case 3:
// (, line 80
// next, line 80
if (cursor >= limit) {
subroot = true;
break;
}
cursor++;
break;
}
if (subroot) {
subroot = false;
break;
}
if (!subroot) {
goto replab0;
}
} while (false);
cursor = v_1;
break;
}
return true;
}
private bool r_R1() {
if (!(I_p1 <= cursor)) {
return false;
}
return true;
}
private bool r_R2() {
if (!(I_p2 <= cursor)) {
return false;
}
return true;
}
private bool r_undouble() {
int v_1;
// (, line 90
// test, line 91
v_1 = limit - cursor;
// among, line 91
if (find_among_b(a_2, 3) == 0) {
return false;
}
cursor = limit - v_1;
// [, line 91
ket = cursor;
// next, line 91
if (cursor <= limit_backward) {
return false;
}
cursor--;
// ], line 91
bra = cursor;
// delete, line 91
slice_del();
return true;
}
private bool r_e_ending() {
int v_1;
// (, line 94
// unset e_found, line 95
B_e_found = false;
// [, line 96
ket = cursor;
// literal, line 96
if (!(eq_s_b(1, "e"))) {
return false;
}
// ], line 96
bra = cursor;
// call R1, line 96
if (!r_R1()) {
return false;
}
// test, line 96
v_1 = limit - cursor;
if (!(out_grouping_b(g_v, 97, 232))) {
return false;
}
cursor = limit - v_1;
// delete, line 96
slice_del();
// set e_found, line 97
B_e_found = true;
// call undouble, line 98
if (!r_undouble()) {
return false;
}
return true;
}
private bool r_en_ending() {
int v_1;
int v_2;
// (, line 101
// call R1, line 102
if (!r_R1()) {
return false;
}
// and, line 102
v_1 = limit - cursor;
if (!(out_grouping_b(g_v, 97, 232))) {
return false;
}
cursor = limit - v_1;
// not, line 102
{
v_2 = limit - cursor;
do {
// literal, line 102
if (!(eq_s_b(3, "gem"))) {
break;
}
if ((eq_s_b(3, "gem"))) {
return false;
}
} while (false);
cursor = limit - v_2;
}
// delete, line 102
slice_del();
// call undouble, line 103
if (!r_undouble()) {
return false;
}
return true;
}
private bool r_standard_suffix() {
var subroot = false;
int among_var;
int v_1;
int v_2;
int v_3;
int v_4;
int v_5;
int v_6;
int v_7;
int v_8;
int v_9;
int v_10;
// (, line 106
// do, line 107
v_1 = limit - cursor;
do {
// (, line 107
// [, line 108
ket = cursor;
// substring, line 108
among_var = find_among_b(a_3, 5);
if (among_var == 0) {
break;
}
// ], line 108
bra = cursor;
switch (among_var) {
case 0:
subroot = true;
break;
case 1:
// (, line 110
// call R1, line 110
if (!r_R1()) {
subroot = true;
break;
}
// <-, line 110
slice_from("heid");
break;
case 2:
// (, line 113
// call en_ending, line 113
if (!r_en_ending()) {
subroot = true;
}
break;
case 3:
// (, line 116
// call R1, line 116
if (!r_R1()) {
subroot = true;
break;
}
if (!(out_grouping_b(g_v_j, 97, 232))) {
subroot = true;
break;
}
// delete, line 116
slice_del();
break;
}
if (subroot) {
subroot = false;
break;
}
} while (false);
cursor = limit - v_1;
// do, line 120
v_2 = limit - cursor;
do {
// call e_ending, line 120
if (!r_e_ending()) {
break;
}
} while (false);
cursor = limit - v_2;
// do, line 122
v_3 = limit - cursor;
do {
// (, line 122
// [, line 122
ket = cursor;
// literal, line 122
if (!(eq_s_b(4, "heid"))) {
break;
}
// ], line 122
bra = cursor;
// call R2, line 122
if (!r_R2()) {
break;
}
// not, line 122
{
v_4 = limit - cursor;
do {
// literal, line 122
if (!(eq_s_b(1, "c"))) {
break;
}
subroot = true;
if (subroot) break;
} while (false);
if (subroot) {
subroot = false;
break;
}
cursor = limit - v_4;
}
// delete, line 122
slice_del();
// [, line 123
ket = cursor;
// literal, line 123
if (!(eq_s_b(2, "en"))) {
break;
}
// ], line 123
bra = cursor;
// call en_ending, line 123
if (!r_en_ending()) {
break;
}
} while (false);
cursor = limit - v_3;
// do, line 126
v_5 = limit - cursor;
do {
// (, line 126
// [, line 127
ket = cursor;
// substring, line 127
among_var = find_among_b(a_4, 6);
if (among_var == 0) {
break;
}
// ], line 127
bra = cursor;
switch (among_var) {
case 0:
subroot = true;
break;
case 1:
// (, line 129
// call R2, line 129
if (!r_R2()) {
subroot = true;
goto breaklab4;
}
// delete, line 129
slice_del();
// or, line 130
do {
v_6 = limit - cursor;
// lab6:
do {
// (, line 130
// [, line 130
ket = cursor;
// literal, line 130
if (!(eq_s_b(2, "ig"))) {
break;
}
// ], line 130
bra = cursor;
// call R2, line 130
if (!r_R2()) {
break;
}
// not, line 130
{
v_7 = limit - cursor;
do {
// literal, line 130
if (!(eq_s_b(1, "e"))) {
break;
}
subroot = true;
if (subroot) break;
} while (false);
if (subroot) {
subroot = false;
break;
}
cursor = limit - v_7;
}
// delete, line 130
slice_del();
subroot = true;
if (subroot) break;
} while (false);
if (subroot) {
subroot = false;
break;
}
cursor = limit - v_6;
// call undouble, line 130
if (!r_undouble()) {
subroot = true;
goto breaklab4;
}
} while (false);
break;
case 2:
// (, line 133
// call R2, line 133
if (!r_R2()) {
subroot = true;
goto breaklab4;
}
// not, line 133
{
v_8 = limit - cursor;
do {
// literal, line 133
if (!(eq_s_b(1, "e"))) {
break;
}
subroot = true;
if (subroot) goto breaklab4;
} while (false);
if (subroot) {
subroot = false;
break;
}
cursor = limit - v_8;
}
// delete, line 133
slice_del();
break;
case 3:
// (, line 136
// call R2, line 136
if (!r_R2()) {
subroot = true;
goto breaklab4;
}
// delete, line 136
slice_del();
// call e_ending, line 136
if (!r_e_ending()) {
subroot = true;
}
break;
case 4:
// (, line 139
// call R2, line 139
if (!r_R2()) {
subroot = true;
goto breaklab4;
}
// delete, line 139
slice_del();
break;
case 5:
// (, line 142
// call R2, line 142
if (!r_R2()) {
subroot = true;
goto breaklab4;
}
// Boolean test e_found, line 142
if (!(B_e_found)) {
subroot = true;
goto breaklab4;
}
// delete, line 142
slice_del();
break;
}
breaklab4:
if (subroot) {
subroot = false;
break;
}
} while (false);
cursor = limit - v_5;
// do, line 146
v_9 = limit - cursor;
do {
// (, line 146
if (!(out_grouping_b(g_v_I, 73, 232))) {
break;
}
// test, line 148
v_10 = limit - cursor;
// (, line 148
// among, line 149
if (find_among_b(a_5, 4) == 0) {
break;
}
if (!(out_grouping_b(g_v, 97, 232))) {
break;
}
cursor = limit - v_10;
// [, line 152
ket = cursor;
// next, line 152
if (cursor <= limit_backward) {
break;
}
cursor--;
// ], line 152
bra = cursor;
// delete, line 152
slice_del();
} while (false);
cursor = limit - v_9;
return true;
}
private bool CanStem() {
int v_1;
int v_2;
int v_3;
int v_4;
// (, line 157
// do, line 159
v_1 = cursor;
do {
// call prelude, line 159
if (!r_prelude()) {
break;
}
} while (false);
cursor = v_1;
// do, line 160
v_2 = cursor;
do {
// call mark_regions, line 160
if (!r_mark_regions()) {
break;
}
} while (false);
cursor = v_2;
// backwards, line 161
limit_backward = cursor;
cursor = limit;
// do, line 162
v_3 = limit - cursor;
do {
// call standard_suffix, line 162
if (!r_standard_suffix()) {
break;
}
} while (false);
cursor = limit - v_3;
cursor = limit_backward; // do, line 163
v_4 = cursor;
do {
// call postlude, line 163
if (!r_postlude()) {
break;
}
} while (false);
cursor = v_4;
return true;
}
}
}
| |
// 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.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Composition;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.SolutionCrawler
{
public class WorkCoordinatorTests
{
private const string SolutionCrawler = "SolutionCrawler";
[Fact]
public void RegisterService()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var registrationService = new SolutionCrawlerRegistrationService(
SpecializedCollections.EmptyEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>>(),
AggregateAsynchronousOperationListener.EmptyListeners);
// register and unregister workspace to the service
registrationService.Register(workspace);
registrationService.Unregister(workspace);
}
}
[Fact, WorkItem(747226)]
public void SolutionAdded_Simple()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solutionId = SolutionId.CreateNewId();
var projectId = ProjectId.CreateNewId();
var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(),
projects: new[]
{
ProjectInfo.Create(projectId, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp,
documents: new[]
{
DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D1")
})
});
var worker = ExecuteOperation(workspace, w => w.OnSolutionAdded(solutionInfo));
Assert.Equal(1, worker.SyntaxDocumentIds.Count);
}
}
[Fact]
public void SolutionAdded_Complex()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
var worker = ExecuteOperation(workspace, w => w.OnSolutionAdded(solution));
Assert.Equal(10, worker.SyntaxDocumentIds.Count);
}
}
[Fact]
public void Solution_Remove()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var worker = ExecuteOperation(workspace, w => w.OnSolutionRemoved());
Assert.Equal(10, worker.InvalidateDocumentIds.Count);
}
}
[Fact]
public void Solution_Clear()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var worker = ExecuteOperation(workspace, w => w.ClearSolution());
Assert.Equal(10, worker.InvalidateDocumentIds.Count);
}
}
[Fact]
public void Solution_Reload()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var worker = ExecuteOperation(workspace, w => w.OnSolutionReloaded(solution));
Assert.Equal(0, worker.SyntaxDocumentIds.Count);
}
}
[Fact]
public void Solution_Change()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solutionInfo = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solutionInfo);
WaitWaiter(workspace.ExportProvider);
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.First().DocumentIds[0];
solution = solution.RemoveDocument(documentId);
var changedSolution = solution.AddProject("P3", "P3", LanguageNames.CSharp).AddDocument("D1", "").Project.Solution;
var worker = ExecuteOperation(workspace, w => w.ChangeSolution(changedSolution));
Assert.Equal(1, worker.SyntaxDocumentIds.Count);
}
}
[Fact]
public void Project_Add()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var projectId = ProjectId.CreateNewId();
var projectInfo = ProjectInfo.Create(
projectId, VersionStamp.Create(), "P3", "P3", LanguageNames.CSharp,
documents: new List<DocumentInfo>
{
DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D1"),
DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D2")
});
var worker = ExecuteOperation(workspace, w => w.OnProjectAdded(projectInfo));
Assert.Equal(2, worker.SyntaxDocumentIds.Count);
}
}
[Fact]
public void Project_Remove()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var projectid = workspace.CurrentSolution.ProjectIds[0];
var worker = ExecuteOperation(workspace, w => w.OnProjectRemoved(projectid));
Assert.Equal(0, worker.SyntaxDocumentIds.Count);
Assert.Equal(5, worker.InvalidateDocumentIds.Count);
}
}
[Fact]
public void Project_Change()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solutionInfo = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solutionInfo);
WaitWaiter(workspace.ExportProvider);
var project = workspace.CurrentSolution.Projects.First();
var documentId = project.DocumentIds[0];
var solution = workspace.CurrentSolution.RemoveDocument(documentId);
var worker = ExecuteOperation(workspace, w => w.ChangeProject(project.Id, solution));
Assert.Equal(0, worker.SyntaxDocumentIds.Count);
Assert.Equal(1, worker.InvalidateDocumentIds.Count);
}
}
[Fact]
public void Project_AssemblyName_Change()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solutionInfo = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solutionInfo);
WaitWaiter(workspace.ExportProvider);
var project = workspace.CurrentSolution.Projects.First(p => p.Name == "P1").WithAssemblyName("newName");
var worker = ExecuteOperation(workspace, w => w.ChangeProject(project.Id, project.Solution));
Assert.Equal(0, worker.SyntaxDocumentIds.Count);
Assert.Equal(5, worker.DocumentIds.Count);
}
}
[Fact]
public void Project_AnalyzerOptions_Change()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solutionInfo = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solutionInfo);
WaitWaiter(workspace.ExportProvider);
var project = workspace.CurrentSolution.Projects.First(p => p.Name == "P1").AddAdditionalDocument("a1", SourceText.From("")).Project;
var worker = ExecuteOperation(workspace, w => w.ChangeProject(project.Id, project.Solution));
Assert.Equal(0, worker.SyntaxDocumentIds.Count);
Assert.Equal(5, worker.DocumentIds.Count);
}
}
[Fact]
public void Project_Reload()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var project = solution.Projects[0];
var worker = ExecuteOperation(workspace, w => w.OnProjectReloaded(project));
Assert.Equal(0, worker.SyntaxDocumentIds.Count);
}
}
[Fact]
public void Document_Add()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var project = solution.Projects[0];
var info = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "D6");
var worker = ExecuteOperation(workspace, w => w.OnDocumentAdded(info));
Assert.Equal(1, worker.SyntaxDocumentIds.Count);
Assert.Equal(6, worker.DocumentIds.Count);
}
}
[Fact]
public void Document_Remove()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var id = workspace.CurrentSolution.Projects.First().DocumentIds[0];
var worker = ExecuteOperation(workspace, w => w.OnDocumentRemoved(id));
Assert.Equal(0, worker.SyntaxDocumentIds.Count);
Assert.Equal(4, worker.DocumentIds.Count);
Assert.Equal(1, worker.InvalidateDocumentIds.Count);
}
}
[Fact]
public void Document_Reload()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var id = solution.Projects[0].Documents[0];
var worker = ExecuteOperation(workspace, w => w.OnDocumentReloaded(id));
Assert.Equal(0, worker.SyntaxDocumentIds.Count);
}
}
[Fact]
public void Document_Reanalyze()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var info = solution.Projects[0].Documents[0];
var worker = new Analyzer();
var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(worker), Metadata.Crawler);
var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider));
service.Register(workspace);
// don't rely on background parser to have tree. explicitly do it here.
TouchEverything(workspace.CurrentSolution);
service.Reanalyze(workspace, worker, projectIds: null, documentIds: SpecializedCollections.SingletonEnumerable<DocumentId>(info.Id));
TouchEverything(workspace.CurrentSolution);
Wait(service, workspace);
service.Unregister(workspace);
Assert.Equal(1, worker.SyntaxDocumentIds.Count);
Assert.Equal(1, worker.DocumentIds.Count);
}
}
[WorkItem(670335)]
public void Document_Change()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var id = workspace.CurrentSolution.Projects.First().DocumentIds[0];
var worker = ExecuteOperation(workspace, w => w.ChangeDocument(id, SourceText.From("//")));
Assert.Equal(1, worker.SyntaxDocumentIds.Count);
}
}
[Fact]
public void Document_AdditionalFileChange()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var project = solution.Projects[0];
var ncfile = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "D6");
var worker = ExecuteOperation(workspace, w => w.OnAdditionalDocumentAdded(ncfile));
Assert.Equal(5, worker.SyntaxDocumentIds.Count);
Assert.Equal(5, worker.DocumentIds.Count);
worker = ExecuteOperation(workspace, w => w.ChangeAdditionalDocument(ncfile.Id, SourceText.From("//")));
Assert.Equal(5, worker.SyntaxDocumentIds.Count);
Assert.Equal(5, worker.DocumentIds.Count);
worker = ExecuteOperation(workspace, w => w.OnAdditionalDocumentRemoved(ncfile.Id));
Assert.Equal(5, worker.SyntaxDocumentIds.Count);
Assert.Equal(5, worker.DocumentIds.Count);
}
}
[WorkItem(670335)]
public void Document_Cancellation()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var id = workspace.CurrentSolution.Projects.First().DocumentIds[0];
var analyzer = new Analyzer(waitForCancellation: true);
var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler);
var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider));
service.Register(workspace);
workspace.ChangeDocument(id, SourceText.From("//"));
analyzer.RunningEvent.Wait();
workspace.ChangeDocument(id, SourceText.From("// "));
Wait(service, workspace);
service.Unregister(workspace);
Assert.Equal(1, analyzer.SyntaxDocumentIds.Count);
Assert.Equal(5, analyzer.DocumentIds.Count);
}
}
[WorkItem(670335)]
public void Document_Cancellation_MultipleTimes()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var id = workspace.CurrentSolution.Projects.First().DocumentIds[0];
var analyzer = new Analyzer(waitForCancellation: true);
var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler);
var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider));
service.Register(workspace);
workspace.ChangeDocument(id, SourceText.From("//"));
analyzer.RunningEvent.Wait();
analyzer.RunningEvent.Reset();
workspace.ChangeDocument(id, SourceText.From("// "));
analyzer.RunningEvent.Wait();
workspace.ChangeDocument(id, SourceText.From("// "));
Wait(service, workspace);
service.Unregister(workspace);
Assert.Equal(1, analyzer.SyntaxDocumentIds.Count);
Assert.Equal(5, analyzer.DocumentIds.Count);
}
}
[WorkItem(670335)]
public void Document_InvocationReasons()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var id = workspace.CurrentSolution.Projects.First().DocumentIds[0];
var analyzer = new Analyzer(blockedRun: true);
var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler);
var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider));
service.Register(workspace);
// first invocation will block worker
workspace.ChangeDocument(id, SourceText.From("//"));
analyzer.RunningEvent.Wait();
var openReady = new ManualResetEventSlim(initialState: false);
var closeReady = new ManualResetEventSlim(initialState: false);
workspace.DocumentOpened += (o, e) => openReady.Set();
workspace.DocumentClosed += (o, e) => closeReady.Set();
// cause several different request to queue up
workspace.ChangeDocument(id, SourceText.From("// "));
workspace.OpenDocument(id);
workspace.CloseDocument(id);
openReady.Set();
closeReady.Set();
analyzer.BlockEvent.Set();
Wait(service, workspace);
service.Unregister(workspace);
Assert.Equal(1, analyzer.SyntaxDocumentIds.Count);
Assert.Equal(5, analyzer.DocumentIds.Count);
}
}
[Fact]
public void Document_TopLevelType_Whitespace()
{
var code = @"class C { $$ }";
var textToInsert = " ";
InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public void Document_TopLevelType_Character()
{
var code = @"class C { $$ }";
var textToInsert = "int";
InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public void Document_TopLevelType_NewLine()
{
var code = @"class C { $$ }";
var textToInsert = "\r\n";
InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public void Document_TopLevelType_NewLine2()
{
var code = @"class C { $$";
var textToInsert = "\r\n";
InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public void Document_EmptyFile()
{
var code = @"$$";
var textToInsert = "class";
InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public void Document_TopLevel1()
{
var code = @"class C
{
public void Test($$";
var textToInsert = "int";
InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public void Document_TopLevel2()
{
var code = @"class C
{
public void Test(int $$";
var textToInsert = " ";
InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public void Document_TopLevel3()
{
var code = @"class C
{
public void Test(int i,$$";
var textToInsert = "\r\n";
InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public void Document_InteriorNode1()
{
var code = @"class C
{
public void Test()
{$$";
var textToInsert = "\r\n";
InsertText(code, textToInsert, expectDocumentAnalysis: false);
}
[Fact]
public void Document_InteriorNode2()
{
var code = @"class C
{
public void Test()
{
$$
}";
var textToInsert = "int";
InsertText(code, textToInsert, expectDocumentAnalysis: false);
}
[Fact]
public void Document_InteriorNode_Field()
{
var code = @"class C
{
int i = $$
}";
var textToInsert = "1";
InsertText(code, textToInsert, expectDocumentAnalysis: false);
}
[Fact]
public void Document_InteriorNode_Field1()
{
var code = @"class C
{
int i = 1 + $$
}";
var textToInsert = "1";
InsertText(code, textToInsert, expectDocumentAnalysis: false);
}
[Fact]
public void Document_InteriorNode_Accessor()
{
var code = @"class C
{
public int A
{
get
{
$$
}
}
}";
var textToInsert = "return";
InsertText(code, textToInsert, expectDocumentAnalysis: false);
}
[Fact]
public void Document_TopLevelWhitespace()
{
var code = @"class C
{
/// $$
public int A()
{
}
}";
var textToInsert = "return";
InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public void Document_TopLevelWhitespace2()
{
var code = @"/// $$
class C
{
public int A()
{
}
}";
var textToInsert = "return";
InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public void Document_InteriorNode_Malformed()
{
var code = @"class C
{
public void Test()
{
$$";
var textToInsert = "int";
InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public void VBPropertyTest()
{
var markup = @"Class C
Default Public Property G(x As Integer) As Integer
Get
$$
End Get
Set(value As Integer)
End Set
End Property
End Class";
int position;
string code;
MarkupTestFile.GetPosition(markup, out code, out position);
var root = Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory.ParseCompilationUnit(code);
var property = root.FindToken(position).Parent.FirstAncestorOrSelf<Microsoft.CodeAnalysis.VisualBasic.Syntax.PropertyBlockSyntax>();
var memberId = (new Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxFactsService()).GetMethodLevelMemberId(root, property);
Assert.Equal(0, memberId);
}
[Fact, WorkItem(739943)]
public void SemanticChange_Propagation()
{
var solution = GetInitialSolutionInfoWithP2P();
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var id = solution.Projects[0].Id;
var info = DocumentInfo.Create(DocumentId.CreateNewId(id), "D6");
var worker = ExecuteOperation(workspace, w => w.OnDocumentAdded(info));
Assert.Equal(1, worker.SyntaxDocumentIds.Count);
Assert.Equal(4, worker.DocumentIds.Count);
#if false
Assert.True(1 == worker.SyntaxDocumentIds.Count,
string.Format("Expected 1 SyntaxDocumentIds, Got {0}\n\n{1}", worker.SyntaxDocumentIds.Count, GetListenerTrace(workspace.ExportProvider)));
Assert.True(4 == worker.DocumentIds.Count,
string.Format("Expected 4 DocumentIds, Got {0}\n\n{1}", worker.DocumentIds.Count, GetListenerTrace(workspace.ExportProvider)));
#endif
}
}
[Fact]
public void ProgressReporterTest()
{
var solution = GetInitialSolutionInfoWithP2P();
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
WaitWaiter(workspace.ExportProvider);
var service = workspace.Services.GetService<ISolutionCrawlerService>();
var reporter = service.GetProgressReporter(workspace);
Assert.False(reporter.InProgress);
// set up events
bool started = false;
reporter.Started += (o, a) => { started = true; };
bool stopped = false;
reporter.Stopped += (o, a) => { stopped = true; };
var registrationService = workspace.Services.GetService<ISolutionCrawlerRegistrationService>();
registrationService.Register(workspace);
// first mutation
workspace.OnSolutionAdded(solution);
Wait((SolutionCrawlerRegistrationService)registrationService, workspace);
Assert.True(started);
Assert.True(stopped);
// reset
started = false;
stopped = false;
// second mutation
workspace.OnDocumentAdded(DocumentInfo.Create(DocumentId.CreateNewId(solution.Projects[0].Id), "D6"));
Wait((SolutionCrawlerRegistrationService)registrationService, workspace);
Assert.True(started);
Assert.True(stopped);
registrationService.Unregister(workspace);
}
}
private void InsertText(string code, string text, bool expectDocumentAnalysis, string language = LanguageNames.CSharp)
{
using (var workspace = TestWorkspaceFactory.CreateWorkspaceFromLines(
SolutionCrawler, language, compilationOptions: null, parseOptions: null, content: new string[] { code }))
{
var analyzer = new Analyzer();
var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler);
var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider));
service.Register(workspace);
var testDocument = workspace.Documents.First();
var insertPosition = testDocument.CursorPosition;
var textBuffer = testDocument.GetTextBuffer();
using (var edit = textBuffer.CreateEdit())
{
edit.Insert(insertPosition.Value, text);
edit.Apply();
}
Wait(service, workspace);
service.Unregister(workspace);
Assert.Equal(1, analyzer.SyntaxDocumentIds.Count);
Assert.Equal(expectDocumentAnalysis ? 1 : 0, analyzer.DocumentIds.Count);
}
}
private Analyzer ExecuteOperation(TestWorkspace workspace, Action<TestWorkspace> operation)
{
var worker = new Analyzer();
var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(worker), Metadata.Crawler);
var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider));
service.Register(workspace);
// don't rely on background parser to have tree. explicitly do it here.
TouchEverything(workspace.CurrentSolution);
operation(workspace);
TouchEverything(workspace.CurrentSolution);
Wait(service, workspace);
service.Unregister(workspace);
return worker;
}
private void TouchEverything(Solution solution)
{
foreach (var project in solution.Projects)
{
foreach (var document in project.Documents)
{
document.GetTextAsync().PumpingWait();
document.GetSyntaxRootAsync().PumpingWait();
document.GetSemanticModelAsync().PumpingWait();
}
}
}
private void Wait(SolutionCrawlerRegistrationService service, TestWorkspace workspace)
{
WaitWaiter(workspace.ExportProvider);
service.WaitUntilCompletion_ForTestingPurposesOnly(workspace);
}
private void WaitWaiter(ExportProvider provider)
{
var workspaceWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.Workspace).Value as IAsynchronousOperationWaiter;
workspaceWaiter.CreateWaitTask().PumpingWait();
var solutionCrawlerWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.SolutionCrawler).Value as IAsynchronousOperationWaiter;
solutionCrawlerWaiter.CreateWaitTask().PumpingWait();
}
private static SolutionInfo GetInitialSolutionInfoWithP2P()
{
var projectId1 = ProjectId.CreateNewId();
var projectId2 = ProjectId.CreateNewId();
var projectId3 = ProjectId.CreateNewId();
var projectId4 = ProjectId.CreateNewId();
var projectId5 = ProjectId.CreateNewId();
var solution = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(),
projects: new[]
{
ProjectInfo.Create(projectId1, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp,
documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D1") }),
ProjectInfo.Create(projectId2, VersionStamp.Create(), "P2", "P2", LanguageNames.CSharp,
documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D2") },
projectReferences: new[] { new ProjectReference(projectId1) }),
ProjectInfo.Create(projectId3, VersionStamp.Create(), "P3", "P3", LanguageNames.CSharp,
documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId3), "D3") },
projectReferences: new[] { new ProjectReference(projectId2) }),
ProjectInfo.Create(projectId4, VersionStamp.Create(), "P4", "P4", LanguageNames.CSharp,
documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId4), "D4") }),
ProjectInfo.Create(projectId5, VersionStamp.Create(), "P5", "P5", LanguageNames.CSharp,
documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId5), "D5") },
projectReferences: new[] { new ProjectReference(projectId4) }),
});
return solution;
}
private static SolutionInfo GetInitialSolutionInfo(TestWorkspace workspace)
{
var projectId1 = ProjectId.CreateNewId();
var projectId2 = ProjectId.CreateNewId();
return SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(),
projects: new[]
{
ProjectInfo.Create(projectId1, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp,
documents: new[]
{
DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D1"),
DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D2"),
DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D3"),
DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D4"),
DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D5")
}),
ProjectInfo.Create(projectId2, VersionStamp.Create(), "P2", "P2", LanguageNames.CSharp,
documents: new[]
{
DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D1"),
DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D2"),
DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D3"),
DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D4"),
DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D5")
})
});
}
private IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> GetListeners(ExportProvider provider)
{
return provider.GetExports<IAsynchronousOperationListener, FeatureMetadata>();
}
[Export(typeof(IAsynchronousOperationListener))]
[Export(typeof(IAsynchronousOperationWaiter))]
[Feature(FeatureAttribute.SolutionCrawler)]
private class SolutionCrawlerWaiter : AsynchronousOperationListener { }
[Export(typeof(IAsynchronousOperationListener))]
[Export(typeof(IAsynchronousOperationWaiter))]
[Feature(FeatureAttribute.Workspace)]
private class WorkspaceWaiter : AsynchronousOperationListener { }
private class AnalyzerProvider : IIncrementalAnalyzerProvider
{
private readonly Analyzer _analyzer;
public AnalyzerProvider(Analyzer analyzer)
{
_analyzer = analyzer;
}
public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace)
{
return _analyzer;
}
}
internal class Metadata : IncrementalAnalyzerProviderMetadata
{
public Metadata(params string[] workspaceKinds)
: base(new Dictionary<string, object> { { "WorkspaceKinds", workspaceKinds }, { "HighPriorityForActiveFile", false } })
{
}
public static readonly Metadata Crawler = new Metadata(SolutionCrawler);
}
private class Analyzer : IIncrementalAnalyzer
{
private readonly bool _waitForCancellation;
private readonly bool _blockedRun;
public readonly ManualResetEventSlim BlockEvent;
public readonly ManualResetEventSlim RunningEvent;
public readonly HashSet<DocumentId> SyntaxDocumentIds = new HashSet<DocumentId>();
public readonly HashSet<DocumentId> DocumentIds = new HashSet<DocumentId>();
public readonly HashSet<ProjectId> ProjectIds = new HashSet<ProjectId>();
public readonly HashSet<DocumentId> InvalidateDocumentIds = new HashSet<DocumentId>();
public readonly HashSet<ProjectId> InvalidateProjectIds = new HashSet<ProjectId>();
public Analyzer(bool waitForCancellation = false, bool blockedRun = false)
{
_waitForCancellation = waitForCancellation;
_blockedRun = blockedRun;
this.BlockEvent = new ManualResetEventSlim(initialState: false);
this.RunningEvent = new ManualResetEventSlim(initialState: false);
}
public Task AnalyzeProjectAsync(Project project, bool semanticsChanged, CancellationToken cancellationToken)
{
this.ProjectIds.Add(project.Id);
return SpecializedTasks.EmptyTask;
}
public Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, CancellationToken cancellationToken)
{
if (bodyOpt == null)
{
this.DocumentIds.Add(document.Id);
}
return SpecializedTasks.EmptyTask;
}
public Task AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken)
{
this.SyntaxDocumentIds.Add(document.Id);
Process(document.Id, cancellationToken);
return SpecializedTasks.EmptyTask;
}
public void RemoveDocument(DocumentId documentId)
{
InvalidateDocumentIds.Add(documentId);
}
public void RemoveProject(ProjectId projectId)
{
InvalidateProjectIds.Add(projectId);
}
private void Process(DocumentId documentId, CancellationToken cancellationToken)
{
if (_blockedRun && !RunningEvent.IsSet)
{
this.RunningEvent.Set();
// Wait until unblocked
this.BlockEvent.Wait();
}
if (_waitForCancellation && !RunningEvent.IsSet)
{
this.RunningEvent.Set();
cancellationToken.WaitHandle.WaitOne();
cancellationToken.ThrowIfCancellationRequested();
}
}
#region unused
public Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
public Task DocumentOpenAsync(Document document, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
public Task DocumentCloseAsync(Document document, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
public Task DocumentResetAsync(Document document, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
public bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e)
{
return false;
}
#endregion
}
#if false
private string GetListenerTrace(ExportProvider provider)
{
var sb = new StringBuilder();
var workspaceWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.Workspace).Value as TestAsynchronousOperationListener;
sb.AppendLine("workspace");
sb.AppendLine(workspaceWaiter.Trace());
var solutionCrawlerWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.SolutionCrawler).Value as TestAsynchronousOperationListener;
sb.AppendLine("solutionCrawler");
sb.AppendLine(solutionCrawlerWaiter.Trace());
return sb.ToString();
}
internal abstract partial class TestAsynchronousOperationListener : IAsynchronousOperationListener, IAsynchronousOperationWaiter
{
private readonly object gate = new object();
private readonly HashSet<TaskCompletionSource<bool>> pendingTasks = new HashSet<TaskCompletionSource<bool>>();
private readonly StringBuilder sb = new StringBuilder();
private int counter;
public TestAsynchronousOperationListener()
{
}
public IAsyncToken BeginAsyncOperation(string name, object tag = null)
{
lock (gate)
{
return new AsyncToken(this, name);
}
}
private void Increment(string name)
{
lock (gate)
{
sb.AppendLine("i -> " + name + ":" + counter++);
}
}
private void Decrement(string name)
{
lock (gate)
{
counter--;
if (counter == 0)
{
foreach (var task in pendingTasks)
{
task.SetResult(true);
}
pendingTasks.Clear();
}
sb.AppendLine("d -> " + name + ":" + counter);
}
}
public virtual Task CreateWaitTask()
{
lock (gate)
{
var source = new TaskCompletionSource<bool>();
if (counter == 0)
{
// There is nothing to wait for, so we are immediately done
source.SetResult(true);
}
else
{
pendingTasks.Add(source);
}
return source.Task;
}
}
public bool TrackActiveTokens { get; set; }
public bool HasPendingWork
{
get
{
return counter != 0;
}
}
private class AsyncToken : IAsyncToken
{
private readonly TestAsynchronousOperationListener listener;
private readonly string name;
private bool disposed;
public AsyncToken(TestAsynchronousOperationListener listener, string name)
{
this.listener = listener;
this.name = name;
listener.Increment(name);
}
public void Dispose()
{
lock (listener.gate)
{
if (disposed)
{
throw new InvalidOperationException("Double disposing of an async token");
}
disposed = true;
listener.Decrement(this.name);
}
}
}
public string Trace()
{
return sb.ToString();
}
}
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using System.Threading;
namespace Microsoft.Framework.WebEncoders
{
/// <summary>
/// A class which can perform HTML encoding given an allow list of characters which
/// can be represented unencoded.
/// </summary>
/// <remarks>
/// Instances of this type will always encode a certain set of characters (such as <
/// and >), even if the filter provided in the constructor allows such characters.
/// Once constructed, instances of this class are thread-safe for multiple callers.
/// </remarks>
internal unsafe sealed class HtmlEncoderOld : IHtmlEncoder
{
// The default HtmlEncoder (Basic Latin), instantiated on demand
private static HtmlEncoderOld _defaultEncoder;
// The inner encoder, responsible for the actual encoding routines
private readonly HtmlUnicodeEncoder _innerUnicodeEncoder;
/// <summary>
/// Instantiates an encoder using <see cref="UnicodeRanges.BasicLatin"/> as its allow list.
/// Any character not in the <see cref="UnicodeRanges.BasicLatin"/> range will be escaped.
/// </summary>
public HtmlEncoderOld()
: this(HtmlUnicodeEncoder.BasicLatin)
{
}
/// <summary>
/// Instantiates an encoder specifying which Unicode character ranges are allowed to
/// pass through the encoder unescaped. Any character not in the set of ranges specified
/// by <paramref name="allowedRanges"/> will be escaped.
/// </summary>
public HtmlEncoderOld(params UnicodeRange[] allowedRanges)
: this(new HtmlUnicodeEncoder(new TextEncoderSettings(allowedRanges)))
{
}
/// <summary>
/// Instantiates an encoder using a custom code point filter. Any character not in the
/// set returned by <paramref name="settings"/>'s <see cref="TextEncoderSettings.GetAllowedCodePoints"/>
/// method will be escaped.
/// </summary>
public HtmlEncoderOld(TextEncoderSettings settings)
: this(new HtmlUnicodeEncoder(settings))
{
}
private HtmlEncoderOld(HtmlUnicodeEncoder innerEncoder)
{
Debug.Assert(innerEncoder != null);
_innerUnicodeEncoder = innerEncoder;
}
/// <summary>
/// A default instance of <see cref="HtmlEncoderOld"/>.
/// </summary>
/// <remarks>
/// This normally corresponds to <see cref="UnicodeRanges.BasicLatin"/>. However, this property is
/// settable so that a developer can change the default implementation application-wide.
/// </remarks>
public static HtmlEncoderOld Default
{
get
{
return Volatile.Read(ref _defaultEncoder) ?? CreateDefaultEncoderSlow();
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
Volatile.Write(ref _defaultEncoder, value);
}
}
[MethodImpl(MethodImplOptions.NoInlining)] // the JITter can attempt to inline the caller itself without worrying about us
private static HtmlEncoderOld CreateDefaultEncoderSlow()
{
var onDemandEncoder = new HtmlEncoderOld();
return Interlocked.CompareExchange(ref _defaultEncoder, onDemandEncoder, null) ?? onDemandEncoder;
}
/// <summary>
/// Everybody's favorite HtmlEncode routine.
/// </summary>
public void HtmlEncode(char[] value, int startIndex, int characterCount, TextWriter output)
{
_innerUnicodeEncoder.Encode(value, startIndex, characterCount, output);
}
/// <summary>
/// Everybody's favorite HtmlEncode routine.
/// </summary>
public string HtmlEncode(string value)
{
return _innerUnicodeEncoder.Encode(value);
}
/// <summary>
/// Everybody's favorite HtmlEncode routine.
/// </summary>
public void HtmlEncode(string value, int startIndex, int characterCount, TextWriter output)
{
_innerUnicodeEncoder.Encode(value, startIndex, characterCount, output);
}
private sealed class HtmlUnicodeEncoder : UnicodeEncoderBase
{
// A singleton instance of the basic latin encoder.
private static HtmlUnicodeEncoder _basicLatinSingleton;
// The worst case encoding is 8 output chars per input char: [input] U+FFFF -> [output] ""
// We don't need to worry about astral code points since they consume *two* input chars to
// generate at most 10 output chars (""), which equates to 5 output chars per input char.
private const int MaxOutputCharsPerInputChar = 8;
internal HtmlUnicodeEncoder(TextEncoderSettings filter)
: base(filter, MaxOutputCharsPerInputChar)
{
}
internal static HtmlUnicodeEncoder BasicLatin
{
get
{
HtmlUnicodeEncoder encoder = Volatile.Read(ref _basicLatinSingleton);
if (encoder == null)
{
encoder = new HtmlUnicodeEncoder(new TextEncoderSettings(UnicodeRanges.BasicLatin));
Volatile.Write(ref _basicLatinSingleton, encoder);
}
return encoder;
}
}
// Writes a scalar value as an HTML-encoded entity.
protected override void WriteEncodedScalar(ref Writer writer, uint value)
{
if (value == (uint)'\"') { writer.Write("""); }
else if (value == (uint)'&') { writer.Write("&"); }
else if (value == (uint)'<') { writer.Write("<"); }
else if (value == (uint)'>') { writer.Write(">"); }
else { WriteEncodedScalarAsNumericEntity(ref writer, value); }
}
// Writes a scalar value as an HTML-encoded numeric entity.
private static void WriteEncodedScalarAsNumericEntity(ref Writer writer, uint value)
{
// We're building the characters up in reverse
char* chars = stackalloc char[8 /* "FFFFFFFF" */];
int numCharsWritten = 0;
do
{
Debug.Assert(numCharsWritten < 8, "Couldn't have written 8 characters out by this point.");
// Pop off the last nibble
chars[numCharsWritten++] = HexUtil.UInt32LsbToHexDigit(value & 0xFU);
value >>= 4;
} while (value != 0);
// Finally, write out the HTML-encoded scalar value.
writer.Write('&');
writer.Write('#');
writer.Write('x');
Debug.Assert(numCharsWritten > 0, "At least one character should've been written.");
do
{
writer.Write(chars[--numCharsWritten]);
} while (numCharsWritten != 0);
writer.Write(';');
}
}
}
/// <summary>
/// A class which can perform JavaScript string escaping given an allow list of characters which
/// can be represented unescaped.
/// </summary>
/// <remarks>
/// Instances of this type will always encode a certain set of characters (such as '
/// and "), even if the filter provided in the constructor allows such characters.
/// Once constructed, instances of this class are thread-safe for multiple callers.
/// </remarks>
internal sealed class JavaScriptStringEncoderOld : IJavaScriptStringEncoder
{
// The default JavaScript string encoder (Basic Latin), instantiated on demand
private static JavaScriptStringEncoderOld _defaultEncoder;
// The inner encoder, responsible for the actual encoding routines
private readonly JavaScriptStringUnicodeEncoder _innerUnicodeEncoder;
/// <summary>
/// Instantiates an encoder using <see cref="UnicodeRanges.BasicLatin"/> as its allow list.
/// Any character not in the <see cref="UnicodeRanges.BasicLatin"/> range will be escaped.
/// </summary>
public JavaScriptStringEncoderOld()
: this(JavaScriptStringUnicodeEncoder.BasicLatin)
{
}
/// <summary>
/// Instantiates an encoder specifying which Unicode character ranges are allowed to
/// pass through the encoder unescaped. Any character not in the set of ranges specified
/// by <paramref name="allowedRanges"/> will be escaped.
/// </summary>
public JavaScriptStringEncoderOld(params UnicodeRange[] allowedRanges)
: this(new JavaScriptStringUnicodeEncoder(new TextEncoderSettings(allowedRanges)))
{
}
/// <summary>
/// Instantiates an encoder using a custom code point filter. Any character not in the
/// set returned by <paramref name="settings"/>'s <see cref="TextEncoderSettings.GetAllowedCodePoints"/>
/// method will be escaped.
/// </summary>
public JavaScriptStringEncoderOld(TextEncoderSettings settings)
: this(new JavaScriptStringUnicodeEncoder(settings))
{
}
private JavaScriptStringEncoderOld(JavaScriptStringUnicodeEncoder innerEncoder)
{
Debug.Assert(innerEncoder != null);
_innerUnicodeEncoder = innerEncoder;
}
/// <summary>
/// A default instance of <see cref="JavaScriptStringEncoderOld"/>.
/// </summary>
/// <remarks>
/// This normally corresponds to <see cref="UnicodeRanges.BasicLatin"/>. However, this property is
/// settable so that a developer can change the default implementation application-wide.
/// </remarks>
public static JavaScriptStringEncoderOld Default
{
get
{
return Volatile.Read(ref _defaultEncoder) ?? CreateDefaultEncoderSlow();
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
Volatile.Write(ref _defaultEncoder, value);
}
}
[MethodImpl(MethodImplOptions.NoInlining)] // the JITter can attempt to inline the caller itself without worrying about us
private static JavaScriptStringEncoderOld CreateDefaultEncoderSlow()
{
var onDemandEncoder = new JavaScriptStringEncoderOld();
return Interlocked.CompareExchange(ref _defaultEncoder, onDemandEncoder, null) ?? onDemandEncoder;
}
/// <summary>
/// Everybody's favorite JavaScriptStringEncode routine.
/// </summary>
public void JavaScriptStringEncode(char[] value, int startIndex, int characterCount, TextWriter output)
{
_innerUnicodeEncoder.Encode(value, startIndex, characterCount, output);
}
/// <summary>
/// Everybody's favorite JavaScriptStringEncode routine.
/// </summary>
public string JavaScriptStringEncode(string value)
{
return _innerUnicodeEncoder.Encode(value);
}
/// <summary>
/// Everybody's favorite JavaScriptStringEncode routine.
/// </summary>
public void JavaScriptStringEncode(string value, int startIndex, int characterCount, TextWriter output)
{
_innerUnicodeEncoder.Encode(value, startIndex, characterCount, output);
}
private sealed class JavaScriptStringUnicodeEncoder : UnicodeEncoderBase
{
// A singleton instance of the basic latin encoder.
private static JavaScriptStringUnicodeEncoder _basicLatinSingleton;
// The worst case encoding is 6 output chars per input char: [input] U+FFFF -> [output] "\uFFFF"
// We don't need to worry about astral code points since they're represented as encoded
// surrogate pairs in the output.
private const int MaxOutputCharsPerInputChar = 6;
internal JavaScriptStringUnicodeEncoder(TextEncoderSettings filter)
: base(filter, MaxOutputCharsPerInputChar)
{
// The only interesting characters above and beyond what the base encoder
// already covers are the solidus and reverse solidus.
ForbidCharacter('\\');
ForbidCharacter('/');
}
internal static JavaScriptStringUnicodeEncoder BasicLatin
{
get
{
JavaScriptStringUnicodeEncoder encoder = Volatile.Read(ref _basicLatinSingleton);
if (encoder == null)
{
encoder = new JavaScriptStringUnicodeEncoder(new TextEncoderSettings(UnicodeRanges.BasicLatin));
Volatile.Write(ref _basicLatinSingleton, encoder);
}
return encoder;
}
}
// Writes a scalar value as a JavaScript-escaped character (or sequence of characters).
// See ECMA-262, Sec. 7.8.4, and ECMA-404, Sec. 9
// http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4
// http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf
protected override void WriteEncodedScalar(ref Writer writer, uint value)
{
// ECMA-262 allows encoding U+000B as "\v", but ECMA-404 does not.
// Both ECMA-262 and ECMA-404 allow encoding U+002F SOLIDUS as "\/".
// (In ECMA-262 this character is a NonEscape character.)
// HTML-specific characters (including apostrophe and quotes) will
// be written out as numeric entities for defense-in-depth.
// See UnicodeEncoderBase ctor comments for more info.
if (value == (uint)'\b') { writer.Write(@"\b"); }
else if (value == (uint)'\t') { writer.Write(@"\t"); }
else if (value == (uint)'\n') { writer.Write(@"\n"); }
else if (value == (uint)'\f') { writer.Write(@"\f"); }
else if (value == (uint)'\r') { writer.Write(@"\r"); }
else if (value == (uint)'/') { writer.Write(@"\/"); }
else if (value == (uint)'\\') { writer.Write(@"\\"); }
else { WriteEncodedScalarAsNumericEntity(ref writer, value); }
}
// Writes a scalar value as an JavaScript-escaped character (or sequence of characters).
private static void WriteEncodedScalarAsNumericEntity(ref Writer writer, uint value)
{
if (UnicodeHelpers.IsSupplementaryCodePoint((int)value))
{
// Convert this back to UTF-16 and write out both characters.
char leadingSurrogate, trailingSurrogate;
UnicodeHelpers.GetUtf16SurrogatePairFromAstralScalarValue((int)value, out leadingSurrogate, out trailingSurrogate);
WriteEncodedSingleCharacter(ref writer, leadingSurrogate);
WriteEncodedSingleCharacter(ref writer, trailingSurrogate);
}
else
{
// This is only a single character.
WriteEncodedSingleCharacter(ref writer, value);
}
}
// Writes an encoded scalar value (in the BMP) as a JavaScript-escaped character.
private static void WriteEncodedSingleCharacter(ref Writer writer, uint value)
{
Debug.Assert(!UnicodeHelpers.IsSupplementaryCodePoint((int)value), "The incoming value should've been in the BMP.");
// Encode this as 6 chars "\uFFFF".
writer.Write('\\');
writer.Write('u');
writer.Write(HexUtil.UInt32LsbToHexDigit(value >> 12));
writer.Write(HexUtil.UInt32LsbToHexDigit((value >> 8) & 0xFU));
writer.Write(HexUtil.UInt32LsbToHexDigit((value >> 4) & 0xFU));
writer.Write(HexUtil.UInt32LsbToHexDigit(value & 0xFU));
}
}
}
/// <summary>
/// A class which can perform URL string escaping given an allow list of characters which
/// can be represented unescaped.
/// </summary>
/// <remarks>
/// Instances of this type will always encode a certain set of characters (such as +
/// and ?), even if the filter provided in the constructor allows such characters.
/// Once constructed, instances of this class are thread-safe for multiple callers.
/// </remarks>
internal sealed class UrlEncoderOld : IUrlEncoder
{
// The default URL string encoder (Basic Latin), instantiated on demand
private static UrlEncoderOld _defaultEncoder;
// The inner encoder, responsible for the actual encoding routines
private readonly UrlUnicodeEncoder _innerUnicodeEncoder;
/// <summary>
/// Instantiates an encoder using <see cref="UnicodeRanges.BasicLatin"/> as its allow list.
/// Any character not in the <see cref="UnicodeRanges.BasicLatin"/> range will be escaped.
/// </summary>
public UrlEncoderOld()
: this(UrlUnicodeEncoder.BasicLatin)
{
}
/// <summary>
/// Instantiates an encoder specifying which Unicode character ranges are allowed to
/// pass through the encoder unescaped. Any character not in the set of ranges specified
/// by <paramref name="allowedRanges"/> will be escaped.
/// </summary>
public UrlEncoderOld(params UnicodeRange[] allowedRanges)
: this(new UrlUnicodeEncoder(new TextEncoderSettings(allowedRanges)))
{
}
/// <summary>
/// Instantiates an encoder using a custom code point filter. Any character not in the
/// set returned by <paramref name="settings"/>'s <see cref="TextEncoderSettings.GetAllowedCodePoints"/>
/// method will be escaped.
/// </summary>
public UrlEncoderOld(TextEncoderSettings settings)
: this(new UrlUnicodeEncoder(settings))
{
}
private UrlEncoderOld(UrlUnicodeEncoder innerEncoder)
{
Debug.Assert(innerEncoder != null);
_innerUnicodeEncoder = innerEncoder;
}
/// <summary>
/// A default instance of <see cref="UrlEncoderOld"/>.
/// </summary>
/// <remarks>
/// This normally corresponds to <see cref="UnicodeRanges.BasicLatin"/>. However, this property is
/// settable so that a developer can change the default implementation application-wide.
/// </remarks>
public static UrlEncoderOld Default
{
get
{
return Volatile.Read(ref _defaultEncoder) ?? CreateDefaultEncoderSlow();
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
Volatile.Write(ref _defaultEncoder, value);
}
}
[MethodImpl(MethodImplOptions.NoInlining)] // the JITter can attempt to inline the caller itself without worrying about us
private static UrlEncoderOld CreateDefaultEncoderSlow()
{
var onDemandEncoder = new UrlEncoderOld();
return Interlocked.CompareExchange(ref _defaultEncoder, onDemandEncoder, null) ?? onDemandEncoder;
}
/// <summary>
/// Everybody's favorite UrlEncode routine.
/// </summary>
public void UrlEncode(char[] value, int startIndex, int characterCount, TextWriter output)
{
_innerUnicodeEncoder.Encode(value, startIndex, characterCount, output);
}
/// <summary>
/// Everybody's favorite UrlEncode routine.
/// </summary>
public string UrlEncode(string value)
{
return _innerUnicodeEncoder.Encode(value);
}
/// <summary>
/// Everybody's favorite UrlEncode routine.
/// </summary>
public void UrlEncode(string value, int startIndex, int characterCount, TextWriter output)
{
_innerUnicodeEncoder.Encode(value, startIndex, characterCount, output);
}
private sealed class UrlUnicodeEncoder : UnicodeEncoderBase
{
// A singleton instance of the basic latin encoder.
private static UrlUnicodeEncoder _basicLatinSingleton;
// We perform UTF8 conversion of input, which means that the worst case is
// 9 output chars per input char: [input] U+FFFF -> [output] "%XX%YY%ZZ".
// We don't need to worry about astral code points since they consume 2 input
// chars to produce 12 output chars "%XX%YY%ZZ%WW", which is 6 output chars per input char.
private const int MaxOutputCharsPerInputChar = 9;
internal UrlUnicodeEncoder(TextEncoderSettings filter)
: base(filter, MaxOutputCharsPerInputChar)
{
// Per RFC 3987, Sec. 2.2, we want encodings that are safe for
// four particular components: 'isegment', 'ipath-noscheme',
// 'iquery', and 'ifragment'. The relevant definitions are below.
//
// ipath-noscheme = isegment-nz-nc *( "/" isegment )
//
// isegment = *ipchar
//
// isegment-nz-nc = 1*( iunreserved / pct-encoded / sub-delims
// / "@" )
// ; non-zero-length segment without any colon ":"
//
// ipchar = iunreserved / pct-encoded / sub-delims / ":"
// / "@"
//
// iquery = *( ipchar / iprivate / "/" / "?" )
//
// ifragment = *( ipchar / "/" / "?" )
//
// iunreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" / ucschar
//
// ucschar = %xA0-D7FF / %xF900-FDCF / %xFDF0-FFEF
// / %x10000-1FFFD / %x20000-2FFFD / %x30000-3FFFD
// / %x40000-4FFFD / %x50000-5FFFD / %x60000-6FFFD
// / %x70000-7FFFD / %x80000-8FFFD / %x90000-9FFFD
// / %xA0000-AFFFD / %xB0000-BFFFD / %xC0000-CFFFD
// / %xD0000-DFFFD / %xE1000-EFFFD
//
// pct-encoded = "%" HEXDIG HEXDIG
//
// sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
// / "*" / "+" / "," / ";" / "="
//
// The only common characters between these four components are the
// intersection of 'isegment-nz-nc' and 'ipchar', which is really
// just 'isegment-nz-nc' (colons forbidden).
//
// From this list, the base encoder already forbids "&", "'", "+",
// and we'll additionally forbid "=" since it has special meaning
// in x-www-form-urlencoded representations.
//
// This means that the full list of allowed characters from the
// Basic Latin set is:
// ALPHA / DIGIT / "-" / "." / "_" / "~" / "!" / "$" / "(" / ")" / "*" / "," / ";" / "@"
const string forbiddenChars = @" #%/:=?[\]^`{|}"; // chars from Basic Latin which aren't already disallowed by the base encoder
foreach (char c in forbiddenChars)
{
ForbidCharacter(c);
}
// Specials (U+FFF0 .. U+FFFF) are forbidden by the definition of 'ucschar' above
for (int i = 0; i < 16; i++)
{
ForbidCharacter((char)(0xFFF0 | i));
}
// Supplementary characters are forbidden anyway by the base encoder
}
internal static UrlUnicodeEncoder BasicLatin
{
get
{
UrlUnicodeEncoder encoder = Volatile.Read(ref _basicLatinSingleton);
if (encoder == null)
{
encoder = new UrlUnicodeEncoder(new TextEncoderSettings(UnicodeRanges.BasicLatin));
Volatile.Write(ref _basicLatinSingleton, encoder);
}
return encoder;
}
}
// Writes a scalar value as a percent-encoded sequence of UTF8 bytes, per RFC 3987.
protected override void WriteEncodedScalar(ref Writer writer, uint value)
{
uint asUtf8 = (uint)UnicodeHelpers.GetUtf8RepresentationForScalarValue(value);
do
{
char highNibble, lowNibble;
HexUtil.ByteToHexDigits((byte)asUtf8, out highNibble, out lowNibble);
writer.Write('%');
writer.Write(highNibble);
writer.Write(lowNibble);
} while ((asUtf8 >>= 8) != 0);
}
}
}
}
| |
// 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 osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Online.Chat;
using osu.Game.Users;
using osuTK;
using System;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics.Containers;
using osu.Game.Overlays.Chat;
using osuTK.Input;
namespace osu.Game.Tests.Visual.Online
{
public class TestSceneStandAloneChatDisplay : OsuManualInputManagerTestScene
{
private readonly User admin = new User
{
Username = "HappyStick",
Id = 2,
Colour = "f2ca34"
};
private readonly User redUser = new User
{
Username = "BanchoBot",
Id = 3,
};
private readonly User blueUser = new User
{
Username = "Zallius",
Id = 4,
};
private readonly User longUsernameUser = new User
{
Username = "Very Long Long Username",
Id = 5,
};
[Cached]
private ChannelManager channelManager = new ChannelManager();
private TestStandAloneChatDisplay chatDisplay;
private int messageIdSequence;
private Channel testChannel;
public TestSceneStandAloneChatDisplay()
{
Add(channelManager);
}
[SetUp]
public void SetUp() => Schedule(() =>
{
messageIdSequence = 0;
channelManager.CurrentChannel.Value = testChannel = new Channel();
Children = new[]
{
chatDisplay = new TestStandAloneChatDisplay
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Margin = new MarginPadding(20),
Size = new Vector2(400, 80),
Channel = { Value = testChannel },
},
new TestStandAloneChatDisplay(true)
{
Anchor = Anchor.CentreRight,
Origin = Anchor.CentreRight,
Margin = new MarginPadding(20),
Size = new Vector2(400, 150),
Channel = { Value = testChannel },
}
};
});
[Test]
public void TestSystemMessageOrdering()
{
var standardMessage = new Message(messageIdSequence++)
{
Sender = admin,
Content = "I am a wang!"
};
var infoMessage1 = new InfoMessage($"the system is calling {messageIdSequence++}");
var infoMessage2 = new InfoMessage($"the system is calling {messageIdSequence++}");
AddStep("message from admin", () => testChannel.AddNewMessages(standardMessage));
AddStep("message from system", () => testChannel.AddNewMessages(infoMessage1));
AddStep("message from system", () => testChannel.AddNewMessages(infoMessage2));
AddAssert("message order is correct", () => testChannel.Messages.Count == 3
&& testChannel.Messages[0] == standardMessage
&& testChannel.Messages[1] == infoMessage1
&& testChannel.Messages[2] == infoMessage2);
}
[Test]
public void TestManyMessages()
{
AddStep("message from admin", () => testChannel.AddNewMessages(new Message(messageIdSequence++)
{
Sender = admin,
Content = "I am a wang!"
}));
AddStep("message from team red", () => testChannel.AddNewMessages(new Message(messageIdSequence++)
{
Sender = redUser,
Content = "I am team red."
}));
AddStep("message from team red", () => testChannel.AddNewMessages(new Message(messageIdSequence++)
{
Sender = redUser,
Content = "I plan to win!"
}));
AddStep("message from team blue", () => testChannel.AddNewMessages(new Message(messageIdSequence++)
{
Sender = blueUser,
Content = "Not on my watch. Prepare to eat saaaaaaaaaand. Lots and lots of saaaaaaand."
}));
AddStep("message from admin", () => testChannel.AddNewMessages(new Message(messageIdSequence++)
{
Sender = admin,
Content = "Okay okay, calm down guys. Let's do this!"
}));
AddStep("message from long username", () => testChannel.AddNewMessages(new Message(messageIdSequence++)
{
Sender = longUsernameUser,
Content = "Hi guys, my new username is lit!"
}));
AddStep("message with new date", () => testChannel.AddNewMessages(new Message(messageIdSequence++)
{
Sender = longUsernameUser,
Content = "Message from the future!",
Timestamp = DateTimeOffset.Now
}));
checkScrolledToBottom();
const int messages_per_call = 10;
AddRepeatStep("add many messages", () =>
{
for (int i = 0; i < messages_per_call; i++)
{
testChannel.AddNewMessages(new Message(messageIdSequence++)
{
Sender = longUsernameUser,
Content = "Many messages! " + Guid.NewGuid(),
Timestamp = DateTimeOffset.Now
});
}
}, Channel.MAX_HISTORY / messages_per_call + 5);
AddAssert("Ensure no adjacent day separators", () =>
{
var indices = chatDisplay.FillFlow.OfType<DrawableChannel.DaySeparator>().Select(ds => chatDisplay.FillFlow.IndexOf(ds));
foreach (var i in indices)
{
if (i < chatDisplay.FillFlow.Count && chatDisplay.FillFlow[i + 1] is DrawableChannel.DaySeparator)
return false;
}
return true;
});
checkScrolledToBottom();
}
/// <summary>
/// Tests that when a message gets wrapped by the chat display getting contracted while scrolled to bottom, the chat will still keep scrolling down.
/// </summary>
[Test]
public void TestMessageWrappingKeepsAutoScrolling()
{
fillChat();
// send message with short words for text wrapping to occur when contracting chat.
sendMessage();
AddStep("contract chat", () => chatDisplay.Width -= 100);
checkScrolledToBottom();
AddStep("send another message", () => testChannel.AddNewMessages(new Message(messageIdSequence++)
{
Sender = admin,
Content = "As we were saying...",
}));
checkScrolledToBottom();
}
[Test]
public void TestUserScrollOverride()
{
fillChat();
sendMessage();
checkScrolledToBottom();
AddStep("User scroll up", () =>
{
InputManager.MoveMouseTo(chatDisplay.ScreenSpaceDrawQuad.Centre);
InputManager.PressButton(MouseButton.Left);
InputManager.MoveMouseTo(chatDisplay.ScreenSpaceDrawQuad.Centre + new Vector2(0, chatDisplay.ScreenSpaceDrawQuad.Height));
InputManager.ReleaseButton(MouseButton.Left);
});
checkNotScrolledToBottom();
sendMessage();
checkNotScrolledToBottom();
AddRepeatStep("User scroll to bottom", () =>
{
InputManager.MoveMouseTo(chatDisplay.ScreenSpaceDrawQuad.Centre);
InputManager.PressButton(MouseButton.Left);
InputManager.MoveMouseTo(chatDisplay.ScreenSpaceDrawQuad.Centre - new Vector2(0, chatDisplay.ScreenSpaceDrawQuad.Height));
InputManager.ReleaseButton(MouseButton.Left);
}, 5);
checkScrolledToBottom();
sendMessage();
checkScrolledToBottom();
}
[Test]
public void TestLocalEchoMessageResetsScroll()
{
fillChat();
sendMessage();
checkScrolledToBottom();
AddStep("User scroll up", () =>
{
InputManager.MoveMouseTo(chatDisplay.ScreenSpaceDrawQuad.Centre);
InputManager.PressButton(MouseButton.Left);
InputManager.MoveMouseTo(chatDisplay.ScreenSpaceDrawQuad.Centre + new Vector2(0, chatDisplay.ScreenSpaceDrawQuad.Height));
InputManager.ReleaseButton(MouseButton.Left);
});
checkNotScrolledToBottom();
sendMessage();
checkNotScrolledToBottom();
sendLocalMessage();
checkScrolledToBottom();
sendMessage();
checkScrolledToBottom();
}
private void fillChat()
{
AddStep("fill chat", () =>
{
for (int i = 0; i < 10; i++)
{
testChannel.AddNewMessages(new Message(messageIdSequence++)
{
Sender = longUsernameUser,
Content = $"some stuff {Guid.NewGuid()}",
});
}
});
checkScrolledToBottom();
}
private void sendMessage()
{
AddStep("send lorem ipsum", () => testChannel.AddNewMessages(new Message(messageIdSequence++)
{
Sender = longUsernameUser,
Content = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce et bibendum velit.",
}));
}
private void sendLocalMessage()
{
AddStep("send local echo", () => testChannel.AddLocalEcho(new LocalEchoMessage
{
Sender = longUsernameUser,
Content = "This is a local echo message.",
}));
}
private void checkScrolledToBottom() =>
AddUntilStep("is scrolled to bottom", () => chatDisplay.ScrolledToBottom);
private void checkNotScrolledToBottom() =>
AddUntilStep("not scrolled to bottom", () => !chatDisplay.ScrolledToBottom);
private class TestStandAloneChatDisplay : StandAloneChatDisplay
{
public TestStandAloneChatDisplay(bool textbox = false)
: base(textbox)
{
}
protected DrawableChannel DrawableChannel => InternalChildren.OfType<DrawableChannel>().First();
protected UserTrackingScrollContainer ScrollContainer => (UserTrackingScrollContainer)((Container)DrawableChannel.Child).Child;
public FillFlowContainer FillFlow => (FillFlowContainer)ScrollContainer.Child;
public bool ScrolledToBottom => ScrollContainer.IsScrolledToEnd(1);
}
}
}
| |
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Drawing;
using System.Drawing.Design;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using System.Windows.Forms;
using GongSolutions.Shell.Interop;
using ComTypes = System.Runtime.InteropServices.ComTypes;
namespace GongSolutions.Shell
{
/// <summary>
/// Specifies how list items are displayed in a <see cref="ShellView"/>
/// control.
/// </summary>
public enum ShellViewStyle
{
/// <summary>
/// Each item appears as a full-sized icon with a label below it.
/// </summary>
LargeIcon = 1,
/// <summary>
/// Each item appears as a small icon with a label to its right.
/// </summary>
SmallIcon,
/// <summary>
/// Each item appears as a small icon with a label to its right.
/// Items are arranged in columns with no column headers.
/// </summary>
List,
/// <summary>
/// Each item appears on a separate line with further information
/// about each item arranged in columns. The left-most column
/// contains a small icon and label.
/// </summary>
Details,
/// <summary>
/// Each item appears with a thumbnail picture of the file's content.
/// </summary>
Thumbnail,
/// <summary>
/// Each item appears as a full-sized icon with the item label and
/// file information to the right of it.
/// </summary>
Tile,
/// <summary>
/// Each item appears in a thumbstrip at the bottom of the control,
/// with a large preview of the seleted item appearing above.
/// </summary>
Thumbstrip,
}
/// <summary>
/// Provides a view of a computer's files and folders.
/// </summary>
///
/// <remarks>
/// <para>
/// The <see cref="ShellView"/> control allows you to embed Windows
/// Explorer functionality in your Windows Forms applications. The
/// control provides a view of a single folder's contents, as it would
/// appear in the right-hand pane in Explorer.
/// </para>
///
/// <para>
/// When a new <see cref="ShellView"/> control is added to a form,
/// it displays the contents of the Desktop folder. Other folders
/// can be displayed by calling one of the Navigate methods or setting
/// the <see cref="CurrentFolder"/> property.
/// </para>
/// </remarks>
public class ShellView : Control, INotifyPropertyChanged
{
/// <summary>
/// Constant passed to <see cref="SetColumnWidth"/> which causes a column to be auto-sized.
/// </summary>
public const int ColumnAutoSize = -1;
/// <summary>
/// Constant passed to <see cref="SetColumnWidth"/> which causes a column to be auto-sized
/// to fit the column header text width.
/// </summary>
public const int ColumnAutoSizeToHeader = -2;
/// <summary>
/// Initializes a new instance of the <see cref="ShellView"/> class.
/// </summary>
public ShellView()
{
m_History = new ShellHistory();
m_MultiSelect = true;
m_View = ShellViewStyle.LargeIcon;
Size = new Size(250, 200);
Navigate(ShellItem.Desktop);
}
/// <summary>
/// Copies the currently selected items to the clipboard.
/// </summary>
public void CopySelectedItems()
{
ShellContextMenu contextMenu = new ShellContextMenu(SelectedItems);
contextMenu.InvokeCopy();
}
/// <summary>
/// Cuts the currently selected items.
/// </summary>
public void CutSelectedItems()
{
ShellContextMenu contextMenu = new ShellContextMenu(SelectedItems);
contextMenu.InvokeCut(); ;
}
/// <summary>
/// Creates a new folder in the folder currently being browsed.
/// </summary>
public void CreateNewFolder()
{
string name = "New Folder";
int suffix = 0;
do
{
name = string.Format("{0}\\New Folder ({1})",
CurrentFolder.FileSystemPath, ++suffix);
} while (Directory.Exists(name) || File.Exists(name));
ERROR result = Shell32.SHCreateDirectory(m_ShellViewWindow, name);
switch (result)
{
case ERROR.FILE_EXISTS:
case ERROR.ALREADY_EXISTS:
throw new IOException("The directory already exists");
case ERROR.BAD_PATHNAME:
throw new IOException("Bad pathname");
case ERROR.FILENAME_EXCED_RANGE:
throw new IOException("The filename is too long");
}
}
/// <summary>
/// Deletes the currently selected items.
/// </summary>
public void DeleteSelectedItems()
{
ShellContextMenu contextMenu = new ShellContextMenu(SelectedItems);
contextMenu.InvokeDelete();
}
/// <summary>
/// Navigates to the specified <see cref="ShellItem"/>.
/// </summary>
///
/// <param name="folder">
/// The folder to navigate to.
/// </param>
public void Navigate(ShellItem folder)
{
NavigatingEventArgs e = new NavigatingEventArgs(folder);
if (Navigating != null)
{
Navigating(this, e);
}
if (!e.Cancel)
{
ShellItem previous = m_CurrentFolder;
m_CurrentFolder = folder;
try
{
RecreateShellView();
m_History.Add(folder);
OnNavigated();
}
catch (Exception)
{
m_CurrentFolder = previous;
RecreateShellView();
throw;
}
}
}
/// <summary>
/// Navigates to the specified filesystem directory.
/// </summary>
///
/// <param name="path">
/// The path of the directory to navigate to.
/// </param>
///
/// <exception cref="DirectoryNotFoundException">
/// <paramref name="path"/> is not a valid folder.
/// </exception>
public void Navigate(string path)
{
Navigate(new ShellItem(path));
}
/// <summary>
/// Navigates to the specified standard location.
/// </summary>
///
/// <param name="location">
/// The <see cref="Environment.SpecialFolder"/> to which to navigate.
/// </param>
///
/// <remarks>
/// Standard locations are virtual folders which may be located in
/// different places in different versions of Windows. For example
/// the "My Documents" folder is normally located at C:\My Documents
/// on Windows 98, but is located in the user's "Documents and
/// Settings" folder in Windows XP. Using a standard
/// <see cref="Environment.SpecialFolder"/> to refer to such folders
/// ensures that your application will behave correctly on all
/// versions of Windows.
/// </remarks>
public void Navigate(Environment.SpecialFolder location)
{
// CSIDL_MYDOCUMENTS was introduced in Windows XP but doesn't work
// even on that platform. Use CSIDL_PERSONAL instead.
if (location == Environment.SpecialFolder.MyDocuments)
{
location = Environment.SpecialFolder.Personal;
}
Navigate(new ShellItem(location));
}
/// <summary>
/// Navigates the <see cref="ShellView"/> control to the previous folder
/// in the navigation history.
/// </summary>
///
/// <remarks>
/// <para>
/// The WebBrowser control maintains a history list of all the folders
/// visited during a session. You can use the <see cref="NavigateBack"/>
/// method to implement a <b>Back</b> button similar to the one in
/// Windows Explorer, which will allow your users to return to a
/// previous folder in the navigation history.
/// </para>
///
/// <para>
/// Use the <see cref="CanNavigateBack"/> property to determine whether
/// the navigation history is available and contains a previous page.
/// This property is useful, for example, to change the enabled state
/// of a Back button when the ShellView control navigates to or leaves
/// the beginning of the navigation history.
/// </para>
/// </remarks>
///
/// <exception cref="InvalidOperationException">
/// There is no history to navigate backwards through.
/// </exception>
public void NavigateBack()
{
m_CurrentFolder = m_History.MoveBack();
RecreateShellView();
OnNavigated();
}
/// <summary>
/// Navigates the <see cref="ShellView"/> control backwards to the
/// requested folder in the navigation history.
/// </summary>
///
/// <remarks>
/// The WebBrowser control maintains a history list of all the folders
/// visited during a session. You can use the <see cref="NavigateBack"/>
/// method to implement a drop-down menu on a <b>Back</b> button similar
/// to the one in Windows Explorer, which will allow your users to return
/// to a previous folder in the navigation history.
/// </remarks>
///
/// <param name="folder">
/// The folder to navigate to.
/// </param>
///
/// <exception cref="Exception">
/// The requested folder is not present in the
/// <see cref="ShellView"/>'s 'back' history.
/// </exception>
public void NavigateBack(ShellItem folder)
{
m_History.MoveBack(folder);
m_CurrentFolder = folder;
RecreateShellView();
OnNavigated();
}
/// <summary>
/// Navigates the <see cref="ShellView"/> control to the next folder
/// in the navigation history.
/// </summary>
///
/// <remarks>
/// <para>
/// The WebBrowser control maintains a history list of all the folders
/// visited during a session. You can use the <see cref="NavigateForward"/>
/// method to implement a <b>Forward</b> button similar to the one
/// in Windows Explorer, allowing your users to return to the next
/// folder in the navigation history after navigating backward.
/// </para>
///
/// <para>
/// Use the <see cref="CanNavigateForward"/> property to determine
/// whether the navigation history is available and contains a folder
/// located after the current one. This property is useful, for
/// example, to change the enabled state of a <b>Forward</b> button
/// when the ShellView control navigates to or leaves the end of the
/// navigation history.
/// </para>
/// </remarks>
///
/// <exception cref="InvalidOperationException">
/// There is no history to navigate forwards through.
/// </exception>
public void NavigateForward()
{
m_CurrentFolder = m_History.MoveForward();
RecreateShellView();
OnNavigated();
}
/// <summary>
/// Navigates the <see cref="ShellView"/> control forwards to the
/// requested folder in the navigation history.
/// </summary>
///
/// <remarks>
/// The WebBrowser control maintains a history list of all the folders
/// visited during a session. You can use the
/// <see cref="NavigateForward"/> method to implement a drop-down menu
/// on a <b>Forward</b> button similar to the one in Windows Explorer,
/// which will allow your users to return to a folder in the 'forward'
/// navigation history.
/// </remarks>
///
/// <param name="folder">
/// The folder to navigate to.
/// </param>
///
/// <exception cref="Exception">
/// The requested folder is not present in the
/// <see cref="ShellView"/>'s 'forward' history.
/// </exception>
public void NavigateForward(ShellItem folder)
{
m_History.MoveForward(folder);
m_CurrentFolder = folder;
RecreateShellView();
OnNavigated();
}
/// <summary>
/// Navigates to the parent of the currently displayed folder.
/// </summary>
public void NavigateParent()
{
Navigate(m_CurrentFolder.Parent);
}
/// <summary>
/// Navigates to the folder currently selected in the
/// <see cref="ShellView"/>.
/// </summary>
///
/// <remarks>
/// If the <see cref="ShellView"/>'s <see cref="MultiSelect"/>
/// property is set, and more than one item is selected in the
/// ShellView, the first Folder found will be navigated to.
/// </remarks>
///
/// <returns>
/// <see langword="true"/> if a selected folder could be
/// navigated to, <see langword="false"/> otherwise.
/// </returns>
public bool NavigateSelectedFolder()
{
ShellItem[] selected = SelectedItems;
if (selected.Length > 0)
{
foreach (ShellItem i in selected)
{
if (i.IsFolder)
{
Navigate(i);
return true;
}
}
}
return false;
}
/// <summary>
/// Pastes the contents of the clipboard into the current folder.
/// </summary>
public void PasteClipboard()
{
ShellContextMenu contextMenu = new ShellContextMenu(m_CurrentFolder);
contextMenu.InvokePaste();
}
/// <summary>
/// Refreshes the contents of the <see cref="ShellView"/>.
/// </summary>
public void RefreshContents()
{
if (m_ComInterface != null) m_ComInterface.Refresh();
}
/// <summary>
/// Begins a rename on the item currently selected in the
/// <see cref="ShellView"/>.
/// </summary>
public void RenameSelectedItem()
{
User32.EnumChildWindows(m_ShellViewWindow, RenameCallback, IntPtr.Zero);
}
/// <summary>
/// Gets the width of the specified column.
/// </summary>
/// <param name="column">The column.</param>
/// <returns>Width in pixel</returns>
public int GetColumnWidth(int column)
{
IntPtr wnd = User32.GetWindow(m_ShellViewWindow,GetWindow_Cmd.GW_CHILD);// Get listview
return User32.SendMessage(wnd, MSG.LVM_GETCOLUMNWIDTH,column,0);
}
/// <summary>
/// Resizes the specified column.
/// </summary>
/// <param name="column">The column.</param>
/// <param name="width">
/// The width (in pixels) of the column or a special value : <see cref="ColumnAutoSize"/>,
/// <see cref="ColumnAutoSizeToHeader"/>
/// </param>
public void SetColumnWidth(int column, int width)
{
IntPtr wnd = User32.GetWindow(m_ShellViewWindow, GetWindow_Cmd.GW_CHILD);// Get listview
User32.SendMessage(wnd, MSG.LVM_SETCOLUMNWIDTH, column, width);
}
/// <summary>
/// Selects all items in the <see cref="ShellView"/>.
/// </summary>
public void SelectAll()
{
foreach (ShellItem item in ShellItem)
{
m_ComInterface.SelectItem(Shell32.ILFindLastID(item.Pidl), SVSI.SVSI_SELECT);
}
}
/// <summary>
/// Gets a value indicating whether a new folder can be created in
/// the folder currently being browsed by th <see cref="ShellView"/>.
/// </summary>
[Browsable(false)]
public bool CanCreateFolder
{
get
{
return m_CurrentFolder.IsFileSystem && !m_CurrentFolder.IsReadOnly;
}
}
/// <summary>
/// Gets a value indicating whether a previous page in navigation
/// history is available, which allows the <see cref="NavigateBack"/>
/// method to succeed.
/// </summary>
[Browsable(false)]
public bool CanNavigateBack
{
get { return m_History.CanNavigateBack; }
}
/// <summary>
/// Gets a value indicating whether a subsequent page in navigation
/// history is available, which allows the <see cref="NavigateForward"/>
/// method to succeed.
/// </summary>
[Browsable(false)]
public bool CanNavigateForward
{
get { return m_History.CanNavigateForward; }
}
/// <summary>
/// Gets a value indicating whether the folder currently being browsed
/// by the <see cref="ShellView"/> has parent folder which can be
/// navigated to by calling <see cref="NavigateParent"/>.
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool CanNavigateParent
{
get
{
return m_CurrentFolder != ShellItem.Desktop;
}
}
/// <summary>
/// Gets the control's underlying COM IShellView interface.
/// </summary>
[Browsable(false)]
public IShellView ComInterface
{
get { return m_ComInterface; }
}
/// <summary>
/// Gets/sets a <see cref="ShellItem"/> describing the folder
/// currently being browsed by the <see cref="ShellView"/>.
/// </summary>
[Editor(typeof(ShellItemEditor), typeof(UITypeEditor))]
public ShellItem CurrentFolder
{
get { return m_CurrentFolder; }
set
{
if (value != m_CurrentFolder)
{
Navigate(value);
}
}
}
/// <summary>
/// Gets the <see cref="ShellView"/>'s navigation history.
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public ShellHistory History
{
get { return m_History; }
}
/// <summary>
/// Gets a list of the items currently selected in the
/// <see cref="ShellView"/>
/// </summary>
///
/// <value>
/// A <see cref="ShellItem"/> array detailing the items currently
/// selected in the control. If no items are currently selected,
/// an empty array is returned.
/// </value>
[Browsable(false)]
public ShellItem[] SelectedItems
{
get
{
uint CFSTR_SHELLIDLIST =
User32.RegisterClipboardFormat("Shell IDList Array");
ComTypes.IDataObject selection = GetSelectionDataObject();
if (selection != null)
{
FORMATETC format = new FORMATETC();
STGMEDIUM storage = new STGMEDIUM();
format.cfFormat = (short)CFSTR_SHELLIDLIST;
format.dwAspect = DVASPECT.DVASPECT_CONTENT;
format.lindex = 0;
format.tymed = TYMED.TYMED_HGLOBAL;
if (selection.QueryGetData(ref format) == 0)
{
selection.GetData(ref format, out storage);
int itemCount = Marshal.ReadInt32(storage.unionmember);
ShellItem[] result = new ShellItem[itemCount];
for (int n = 0; n < itemCount; ++n)
{
int offset = Marshal.ReadInt32(storage.unionmember,
8 + (n * 4));
result[n] = new ShellItem(
m_CurrentFolder,
(IntPtr)((int)storage.unionmember + offset));
}
GlobalFree(storage.unionmember);
return result;
}
}
return new ShellItem[0];
}
}
/// <summary>
/// Gets/sets a value indicating whether multiple items can be selected
/// by the user.
/// </summary>
[DefaultValue(true), Category("Behaviour")]
public bool MultiSelect
{
get { return m_MultiSelect; }
set
{
m_MultiSelect = value;
RecreateShellView();
OnNavigated();
}
}
/// <summary>
/// Gets/sets a value indicating whether a "WebView" is displayed on
/// the left of the <see cref="ShellView"/> control.
/// </summary>
///
/// <remarks>
/// The WebView is a strip of HTML that appears to the left of a
/// Windows Explorer window when the window has no Explorer Bar.
/// It displays general system tasks and locations, as well as
/// information about the items selected in the window.
///
/// <para>
/// <b>Important:</b> When <see cref="ShowWebView"/> is set to
/// <see langref="true"/>, the <see cref="SelectionChanged"/>
/// event will not occur. This is due to a limitation in the
/// underlying windows control.
/// </para>
/// </remarks>
[DefaultValue(false), Category("Appearance")]
public bool ShowWebView
{
get { return m_ShowWebView; }
set
{
if (value != m_ShowWebView)
{
m_ShowWebView = value;
m_Browser = null;
RecreateShellView();
OnNavigated();
}
}
}
/// <summary>
/// Gets/sets a <see cref="C:StatusBar"/> control that the
/// <see cref="ShellView"/> should use to display folder details.
/// </summary>
public StatusBar StatusBar
{
get { return ((ShellBrowser)GetShellBrowser()).StatusBar; }
set { ((ShellBrowser)GetShellBrowser()).StatusBar = value; }
}
/// <summary>
/// Gets or sets how items are displayed in the control.
/// </summary>
[DefaultValue(ShellViewStyle.LargeIcon), Category("Appearance")]
public ShellViewStyle View
{
get { return m_View; }
set
{
m_View = value;
RecreateShellView();
OnNavigated();
}
}
/// <summary>
/// Occurs when the <see cref="ShellView"/> control wants to know
/// if it should include an item in its view.
/// </summary>
///
/// <remarks>
/// This event allows the items displayed in the <see cref="ShellView"/>
/// control to be filtered. You may want to to only list files with
/// a certain extension, for example.
/// </remarks>
public event FilterItemEventHandler FilterItem;
/// <summary>
/// Occurs when the <see cref="ShellView"/> control navigates to a
/// new folder.
/// </summary>
public event EventHandler Navigated;
/// <summary>
/// Occurs when the <see cref="ShellView"/> control is about to
/// navigate to a new folder.
/// </summary>
public event NavigatingEventHandler Navigating;
/// <summary>
/// Occurs when the <see cref="ShellView"/>'s current selection
/// changes.
/// </summary>
///
/// <remarks>
/// <b>Important:</b> When <see cref="ShowWebView"/> is set to
/// <see langref="true"/>, this event will not occur. This is due to
/// a limitation in the underlying windows control.
/// </remarks>
public event EventHandler SelectionChanged;
#region Hidden Inherited Properties
/// <summary>
/// This property does not apply to <see cref="ShellView"/>.
/// </summary>
[Browsable(false)]
public override Color BackColor
{
get { return base.BackColor; }
set { base.BackColor = value; }
}
/// <summary>
/// This property does not apply to <see cref="ShellView"/>.
/// </summary>
[Browsable(false)]
public override Image BackgroundImage
{
get { return base.BackgroundImage; }
set { base.BackgroundImage = value; }
}
/// <summary>
/// This property does not apply to <see cref="ShellView"/>.
/// </summary>
[Browsable(false)]
public override ImageLayout BackgroundImageLayout
{
get { return base.BackgroundImageLayout; }
set { base.BackgroundImageLayout = value; }
}
#endregion
#region INotifyPropertyChanged Members
event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
{
add { m_PropertyChanged += value; }
remove { m_PropertyChanged -= value; }
}
#endregion
/// <summary>
/// Overrides <see cref="Control.Dispose(bool)"/>
/// </summary>
///
/// <param name="disposing"/>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (m_ShellViewWindow != IntPtr.Zero)
{
User32.DestroyWindow(m_ShellViewWindow);
m_ShellViewWindow = IntPtr.Zero;
}
}
base.Dispose(disposing);
}
/// <summary>
/// Creates the actual shell view control.
/// </summary>
protected override void OnCreateControl()
{
base.OnCreateControl();
CreateShellView();
OnNavigated();
}
/// <summary>
/// Overrides <see cref="Control.OnPreviewKeyDown"/>.
/// </summary>
///
/// <param name="e"/>
/// <returns/>
protected override void OnPreviewKeyDown(PreviewKeyDownEventArgs e)
{
if ((e.KeyData == Keys.Up) || (e.KeyData == Keys.Down) ||
(e.KeyData == Keys.Left) || (e.KeyData == Keys.Right) ||
(e.KeyData == Keys.Enter) || (e.KeyData == Keys.Delete))
e.IsInputKey = true;
if (e.KeyCode == Keys.Delete) DeleteSelectedItems();
if (e.KeyCode == Keys.F2) RenameSelectedItem();
if (e.Control && e.KeyCode == Keys.A) SelectAll();
if (e.Control && e.KeyCode == Keys.C) CopySelectedItems();
if (e.Control && e.KeyCode == Keys.V) PasteClipboard();
if (e.Control && e.KeyCode == Keys.X) CutSelectedItems();
base.OnPreviewKeyDown(e);
}
/// <summary>
/// Overrides <see cref="Control.OnResize"/>.
/// </summary>
///
/// <param name="eventargs"/>
protected override void OnResize(EventArgs eventargs)
{
base.OnResize(eventargs);
User32.SetWindowPos(m_ShellViewWindow, IntPtr.Zero, 0, 0,
ClientRectangle.Width, ClientRectangle.Height, 0);
}
/// <summary>
/// Overrides <see cref="Control.WndProc"/>
/// </summary>
/// <param name="m"/>
protected override void WndProc(ref Message m)
{
const int CWM_GETISHELLBROWSER = 0x407;
// Windows 9x sends the CWM_GETISHELLBROWSER message and expects
// the IShellBrowser for the window to be returned or an Access
// Violation occurs. This is pseudo-documented in knowledge base
// article Q157247.
if (m.Msg == CWM_GETISHELLBROWSER)
{
m.Result = Marshal.GetComInterfaceForObject(m_Browser,
typeof(IShellBrowser));
}
else
{
base.WndProc(ref m);
}
}
internal bool IncludeItem(IntPtr pidl)
{
if (FilterItem != null)
{
FilterItemEventArgs e = new FilterItemEventArgs(
new ShellItem(m_CurrentFolder, pidl));
FilterItem(this, e);
return e.Include;
}
else
{
return true;
}
}
internal new void OnDoubleClick(EventArgs e)
{
base.OnDoubleClick(e);
}
internal void OnSelectionChanged()
{
if (SelectionChanged != null)
{
SelectionChanged(this, EventArgs.Empty);
}
}
internal ShellItem ShellItem
{
get { return m_CurrentFolder; }
}
void CreateShellView()
{
IShellView previous = m_ComInterface;
Rectangle bounds = ClientRectangle;
FOLDERSETTINGS folderSettings = new FOLDERSETTINGS();
// Create an IShellView object.
m_ComInterface = CreateViewObject(m_CurrentFolder, Handle);
// Set the FOLDERSETTINGS.
folderSettings.ViewMode = (FOLDERVIEWMODE)m_View;
if (!m_ShowWebView)
{
folderSettings.fFlags |= FOLDERFLAGS.NOWEBVIEW;
}
if (!m_MultiSelect)
{
folderSettings.fFlags |= FOLDERFLAGS.SINGLESEL;
}
// Tell the IShellView object to create a view window and
// activate it.
try
{
m_ComInterface.CreateViewWindow(previous, ref folderSettings,
GetShellBrowser(), ref bounds,
out m_ShellViewWindow);
}
catch (COMException ex)
{
// If the operation was cancelled by the user (for example
// because an empty removable media drive was selected,
// then "Cancel" pressed in the resulting dialog) convert
// the exception into something more meaningfil.
if (ex.ErrorCode == unchecked((int)0x800704C7U))
{
throw new UserAbortException(ex);
}
}
m_ComInterface.UIActivate(1);
// Disable the window if in design mode, so that user input is
// passed onto the designer.
if (DesignMode)
{
User32.EnableWindow(m_ShellViewWindow, false);
}
// Destroy the previous view window.
if (previous != null) previous.DestroyViewWindow();
}
void RecreateShellView()
{
if (m_ComInterface != null)
{
CreateShellView();
OnNavigated();
}
if (m_PropertyChanged != null)
{
m_PropertyChanged(this,
new PropertyChangedEventArgs("CurrentFolder"));
}
}
bool RenameCallback(IntPtr hwnd, IntPtr lParam)
{
int itemCount = User32.SendMessage(hwnd,
MSG.LVM_GETITEMCOUNT, 0, 0);
for (int n = 0; n < itemCount; ++n)
{
LVITEMA item = new LVITEMA();
item.mask = LVIF.LVIF_STATE;
item.iItem = n;
item.stateMask = LVIS.LVIS_SELECTED;
User32.SendMessage(hwnd, MSG.LVM_GETITEMA,
0, ref item);
if (item.state != 0)
{
User32.SendMessage(hwnd, MSG.LVM_EDITLABEL, n, 0);
return false;
}
}
return true;
}
ComTypes.IDataObject GetSelectionDataObject()
{
IntPtr result;
if (m_ComInterface == null)
{
return null;
}
m_ComInterface.GetItemObject(SVGIO.SVGIO_SELECTION,
typeof(ComTypes.IDataObject).GUID, out result);
if (result != IntPtr.Zero)
{
ComTypes.IDataObject wrapped =
(ComTypes.IDataObject)
Marshal.GetTypedObjectForIUnknown(result,
typeof(ComTypes.IDataObject));
return wrapped;
}
else
{
return null;
}
}
IShellBrowser GetShellBrowser()
{
if (m_Browser == null)
{
if (m_ShowWebView)
{
m_Browser = new ShellBrowser(this);
}
else
{
m_Browser = new DialogShellBrowser(this);
}
}
return m_Browser;
}
void OnNavigated()
{
if (Navigated != null)
{
Navigated(this, EventArgs.Empty);
}
}
bool ShouldSerializeCurrentFolder()
{
return m_CurrentFolder != ShellItem.Desktop;
}
static IShellView CreateViewObject(ShellItem folder, IntPtr hwndOwner)
{
IntPtr result = folder.GetIShellFolder().CreateViewObject(hwndOwner,
typeof(IShellView).GUID);
return (IShellView)
Marshal.GetTypedObjectForIUnknown(result,
typeof(IShellView));
}
[DllImport("kernel32.dll")]
static extern IntPtr GlobalFree(IntPtr hMem);
bool m_MultiSelect;
ShellHistory m_History;
ShellBrowser m_Browser;
ShellItem m_CurrentFolder;
IShellView m_ComInterface;
IntPtr m_ShellViewWindow;
bool m_ShowWebView;
ShellViewStyle m_View;
PropertyChangedEventHandler m_PropertyChanged;
}
/// <summary>
/// Provides information for FilterItem events.
/// </summary>
public class FilterItemEventArgs : EventArgs
{
/// <summary>
/// Initializes a new instance of the <see cref="FilterItemEventArgs"/>
/// class.
/// </summary>
///
/// <param name="item">
/// The item to be filtered.
/// </param>
internal FilterItemEventArgs(ShellItem item)
{
m_Item = item;
}
/// <summary>
/// Gets/sets a value which will determine whether the item will be
/// included in the <see cref="ShellView"/>.
/// </summary>
public bool Include
{
get { return m_Include; }
set { m_Include = value; }
}
/// <summary>
/// The item to be filtered.
/// </summary>
public ShellItem Item
{
get { return m_Item; }
}
ShellItem m_Item;
bool m_Include = true;
}
/// <summary>
/// Provides information for the <see cref="ShellView.Navigating"/>
/// event.
/// </summary>
public class NavigatingEventArgs : EventArgs
{
/// <summary>
/// Initializes a new instance of the <see cref="NavigatingEventArgs"/>
/// class.
/// </summary>
///
/// <param name="folder">
/// The folder being navigated to.
/// </param>
public NavigatingEventArgs(ShellItem folder)
{
m_Folder = folder;
}
/// <summary>
/// Gets/sets a value indicating whether the navigation should be
/// cancelled.
/// </summary>
public bool Cancel
{
get { return m_Cancel; }
set { m_Cancel = value; }
}
/// <summary>
/// The folder being navigated to.
/// </summary>
public ShellItem Folder
{
get { return m_Folder; }
set { m_Folder = value; }
}
bool m_Cancel;
ShellItem m_Folder;
}
/// <summary>
/// Exception raised when a user aborts a Shell operation.
/// </summary>
public class UserAbortException : ExternalException
{
/// <summary>
/// Initializes a new instance of the
/// <see cref="UserAbortException"/> class.
/// </summary>
///
/// <param name="e">
/// The inner exception.
/// </param>
public UserAbortException(Exception e)
: base("User aborted", e)
{
}
}
/// <summary>
/// Represents the method that will handle FilterItem events.
/// </summary>
public delegate void FilterItemEventHandler(object sender,
FilterItemEventArgs e);
/// <summary>
/// Represents the method that will handle the
/// <see cref="ShellView.Navigating"/> event.
/// </summary>
public delegate void NavigatingEventHandler(object sender,
NavigatingEventArgs e);
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
namespace gView.Framework.OGC.WMS
{
public class CapabilitiesHelper
{
public static NumberFormatInfo Nhi = System.Globalization.CultureInfo.InvariantCulture.NumberFormat;
private object _caps = null;
private WMSLayers _layers = new WMSLayers();
private string[] _imageFormats = null, _getFeatureInfoFormats = null;
private string _getMapOnlineResource = String.Empty, _getFeatureInfoOnlineResource = String.Empty, _getLegendGraphicOnlineResource = String.Empty;
public CapabilitiesHelper(object capabilities)
{
_caps = capabilities;
if (_caps is Version_1_1_1.WMT_MS_Capabilities)
{
Version_1_1_1.WMT_MS_Capabilities caps = (Version_1_1_1.WMT_MS_Capabilities)_caps;
#region GetMap
if (caps.Capability.Request.GetMap != null &&
caps.Capability.Request.GetMap.DCPType != null &&
caps.Capability.Request.GetMap.DCPType.Length > 0)
{
foreach (object http in caps.Capability.Request.GetMap.DCPType[0].HTTP)
{
if (http is Version_1_1_1.Get)
_getMapOnlineResource = ((Version_1_1_1.Get)http).OnlineResource.href;
}
}
if (caps.Capability.Request.GetMap != null)
_imageFormats = caps.Capability.Request.GetMap.Format;
#endregion
#region GetFeatureInfo
if (caps.Capability.Request.GetFeatureInfo != null &&
caps.Capability.Request.GetFeatureInfo.DCPType != null &&
caps.Capability.Request.GetFeatureInfo.DCPType.Length > 0)
{
foreach (object http in caps.Capability.Request.GetFeatureInfo.DCPType[0].HTTP)
{
if (http is Version_1_1_1.Get)
_getFeatureInfoOnlineResource = ((Version_1_1_1.Get)http).OnlineResource.href;
}
}
if (caps.Capability.Request.GetFeatureInfo != null)
_getFeatureInfoFormats = caps.Capability.Request.GetFeatureInfo.Format;
#endregion
#region GetLegendGraphic
if (caps.Capability.Request.GetLegendGraphic != null &&
caps.Capability.Request.GetLegendGraphic.DCPType != null &&
caps.Capability.Request.GetLegendGraphic.DCPType.Length > 0)
{
foreach (object http in caps.Capability.Request.GetLegendGraphic.DCPType[0].HTTP)
{
if (http is Version_1_1_1.Get)
_getLegendGraphicOnlineResource = ((Version_1_1_1.Get)http).OnlineResource.href;
}
}
#endregion
#region Layers
for (int i = 0; i < caps.Capability.Layer.Layer1.Length; i++)
{
Version_1_1_1.Layer layer = caps.Capability.Layer.Layer1[i];
WMSLayer wmslayer = new WMSLayer(layer.Name, layer.Title);
if (layer.Style != null && layer.Style.Length > 0)
{
for (int s = 0; s < layer.Style.Length; s++)
wmslayer.Styles.Add(new WMSStyle(layer.Style[s].Name, layer.Style[s].Title));
}
if (layer.ScaleHint != null)
{
try { wmslayer.MinScale = double.Parse(layer.ScaleHint.min.Replace(",", "."), Nhi) * 2004.4; }
catch { }
try { wmslayer.MaxScale = double.Parse(layer.ScaleHint.max.Replace(",", "."), Nhi) * 2004.4; }
catch { }
}
_layers.Add(wmslayer);
}
#endregion
}
else if (_caps is Version_1_3_0.WMS_Capabilities)
{
Version_1_3_0.WMS_Capabilities caps = (Version_1_3_0.WMS_Capabilities)_caps;
#region GetMap
if (caps.Capability.Request.GetMap.DCPType.Length > 0)
_getMapOnlineResource = caps.Capability.Request.GetMap.DCPType[0].HTTP.Get.OnlineResource.href;
_imageFormats = caps.Capability.Request.GetMap.Format;
#endregion
#region GetFeatureInfo
if (caps.Capability.Request.GetMap.DCPType.Length > 0)
_getFeatureInfoOnlineResource = caps.Capability.Request.GetFeatureInfo.DCPType[0].HTTP.Get.OnlineResource.href;
_getFeatureInfoFormats = caps.Capability.Request.GetFeatureInfo.Format;
#endregion
#region Layers
for (int l = 0; l < caps.Capability.Layer.Length; l++)
{
AddCascadingLayers(caps.Capability.Layer[l], String.Empty);
}
#endregion
}
}
private void AddCascadingLayers(Version_1_3_0.Layer layer, string parentName)
{
if (layer == null) return;
if (layer.Layer1 != null)
{
parentName = String.IsNullOrEmpty(parentName) ? layer.Title : parentName + "/" + layer.Title;
for (int i = 0; i < layer.Layer1.Length; i++)
AddCascadingLayers(layer.Layer1[i], parentName);
}
else
{
string title = String.IsNullOrEmpty(parentName) ? layer.Title : parentName + "/" + layer.Title;
WMSLayer wmslayer = new WMSLayer(layer.Name, title);
if (layer.Style != null && layer.Style.Length > 0)
{
for (int s = 0; s < layer.Style.Length; s++)
wmslayer.Styles.Add(new WMSStyle(layer.Style[s].Name, layer.Style[s].Title));
}
if (layer.MinScaleDenominator > 0.0)
wmslayer.MinScale = layer.MinScaleDenominator;
if (layer.MaxScaleDenominator > 0.0)
wmslayer.MaxScale = layer.MaxScaleDenominator;
_layers.Add(wmslayer);
}
}
public WMSLayers Layers
{
get { return _layers; }
}
public WMSLayers LayersWithStyle
{
get
{
WMSLayers layers = new WMSLayers();
foreach (WMSLayer layer in _layers)
{
if (layer.Styles.Count == 0)
{
layers.Add(layer);
}
else
{
foreach (WMSStyle style in layer.Styles)
{
layers.Add(new WMSLayer(layer.Name + "|" + style.Name, layer.Title + " (" + style.Title + ")"));
}
}
}
return layers;
}
}
public WMSLayer LayerByName(string name)
{
string oName = name.Split('|')[0];
foreach (WMSLayer layer in _layers)
{
if (layer.Name == oName)
return layer;
}
return null;
}
public WMSStyle LayerStyleByName(string name)
{
string[] p = name.Split('|');
if (p.Length != 2)
return null;
WMSLayer layer = LayerByName(name);
if (layer == null)
return null;
foreach (WMSStyle style in layer.Styles)
if (style.Name == p[1])
return style;
return null;
}
public string[] ImageFormats
{
get { return _imageFormats; }
}
public string GetMapOnlineResouce
{
get { return _getMapOnlineResource; }
}
public string[] GetFeatureInfoFormats
{
get { return _getFeatureInfoFormats; }
}
public string GetFeatureInfoOnlineResouce
{
get { return _getFeatureInfoOnlineResource; }
}
public string GetLegendGraphicOnlineResource
{
get { return _getLegendGraphicOnlineResource; }
}
#region Classes
public class WMSLayers : List<WMSLayer>
{
}
public class WMSLayer
{
public string Name = String.Empty;
public string Title = String.Empty;
public List<WMSStyle> Styles = new List<WMSStyle>();
public double MinScale = 0.0;
public double MaxScale = 0.0;
public WMSLayer(string name, string title)
{
Name = name;
Title = title;
}
}
public class WMSStyle
{
public string Name = String.Empty;
public string Title = String.Empty;
public WMSStyle(string name, string title)
{
Name = name;
Title = title;
}
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using OpenMetaverse;
using OpenSim.Framework.Monitoring;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.ScriptEngine.Interfaces;
using OpenSim.Region.ScriptEngine.Shared.Api.Plugins;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using Timer = OpenSim.Region.ScriptEngine.Shared.Api.Plugins.Timer;
namespace OpenSim.Region.ScriptEngine.Shared.Api
{
/// <summary>
/// Handles LSL commands that takes long time and returns an event, for example timers, HTTP requests, etc.
/// </summary>
public class AsyncCommandManager
{
public IScriptEngine m_ScriptEngine;
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static Thread cmdHandlerThread;
private static int cmdHandlerThreadCycleSleepms;
private static Dictionary<IScriptEngine, Dataserver> m_Dataserver =
new Dictionary<IScriptEngine, Dataserver>();
private static Dictionary<IScriptEngine, HttpRequest> m_HttpRequest =
new Dictionary<IScriptEngine, HttpRequest>();
private static Dictionary<IScriptEngine, Listener> m_Listener =
new Dictionary<IScriptEngine, Listener>();
private static List<IScriptEngine> m_ScriptEngines =
new List<IScriptEngine>();
private static Dictionary<IScriptEngine, SensorRepeat> m_SensorRepeat =
new Dictionary<IScriptEngine, SensorRepeat>();
private static Dictionary<IScriptEngine, Timer> m_Timer =
new Dictionary<IScriptEngine, Timer>();
private static Dictionary<IScriptEngine, XmlRequest> m_XmlRequest =
new Dictionary<IScriptEngine, XmlRequest>();
/// <summary>
/// Lock for reading/writing static components of AsyncCommandManager.
/// </summary>
/// <remarks>
/// This lock exists so that multiple threads from different engines and/or different copies of the same engine
/// are prevented from running non-thread safe code (e.g. read/write of lists) concurrently.
/// </remarks>
private static ReaderWriterLock staticLock = new ReaderWriterLock();
public AsyncCommandManager(IScriptEngine _ScriptEngine)
{
m_ScriptEngine = _ScriptEngine;
// If there is more than one scene in the simulator or multiple script engines are used on the same region
// then more than one thread could arrive at this block of code simultaneously. However, it cannot be
// executed concurrently both because concurrent list operations are not thread-safe and because of other
// race conditions such as the later check of cmdHandlerThread == null.
staticLock.AcquireWriterLock(-1);
try
{
if (m_ScriptEngines.Count == 0)
ReadConfig();
if (!m_ScriptEngines.Contains(m_ScriptEngine))
m_ScriptEngines.Add(m_ScriptEngine);
// Create instances of all plugins
if (!m_Dataserver.ContainsKey(m_ScriptEngine))
m_Dataserver[m_ScriptEngine] = new Dataserver(this);
if (!m_Timer.ContainsKey(m_ScriptEngine))
m_Timer[m_ScriptEngine] = new Timer(this);
if (!m_HttpRequest.ContainsKey(m_ScriptEngine))
m_HttpRequest[m_ScriptEngine] = new HttpRequest(this);
if (!m_Listener.ContainsKey(m_ScriptEngine))
m_Listener[m_ScriptEngine] = new Listener(this);
if (!m_SensorRepeat.ContainsKey(m_ScriptEngine))
m_SensorRepeat[m_ScriptEngine] = new SensorRepeat(this);
if (!m_XmlRequest.ContainsKey(m_ScriptEngine))
m_XmlRequest[m_ScriptEngine] = new XmlRequest(this);
StartThread();
}
finally
{
staticLock.ReleaseWriterLock();
}
}
~AsyncCommandManager()
{
// Shut down thread
// try
// {
// if (cmdHandlerThread != null)
// {
// if (cmdHandlerThread.IsAlive == true)
// {
// cmdHandlerThread.Abort();
// //cmdHandlerThread.Join();
// }
// }
// }
// catch
// {
// }
}
public Dataserver DataserverPlugin
{
get
{
staticLock.AcquireReaderLock(-1);
try
{
return m_Dataserver[m_ScriptEngine];
}
finally
{
staticLock.ReleaseReaderLock();
}
}
}
public HttpRequest HttpRequestPlugin
{
get
{
staticLock.AcquireReaderLock(-1);
try
{
return m_HttpRequest[m_ScriptEngine];
}
finally
{
staticLock.ReleaseReaderLock();
}
}
}
public Listener ListenerPlugin
{
get
{
staticLock.AcquireReaderLock(-1);
try
{
return m_Listener[m_ScriptEngine];
}
finally
{
staticLock.ReleaseReaderLock();
}
}
}
public IScriptEngine[] ScriptEngines
{
get
{
staticLock.AcquireReaderLock(-1);
try
{
return m_ScriptEngines.ToArray();
}
finally
{
staticLock.ReleaseReaderLock();
}
}
}
public SensorRepeat SensorRepeatPlugin
{
get
{
staticLock.AcquireReaderLock(-1);
try
{
return m_SensorRepeat[m_ScriptEngine];
}
finally
{
staticLock.ReleaseReaderLock();
}
}
}
public Timer TimerPlugin
{
get
{
staticLock.AcquireReaderLock(-1);
try
{
return m_Timer[m_ScriptEngine];
}
finally
{
staticLock.ReleaseReaderLock();
}
}
}
public XmlRequest XmlRequestPlugin
{
get
{
staticLock.AcquireReaderLock(-1);
try
{
return m_XmlRequest[m_ScriptEngine];
}
finally
{
staticLock.ReleaseReaderLock();
}
}
}
public static void CreateFromData(IScriptEngine engine, uint localID,
UUID itemID, UUID hostID, Object[] data)
{
int idx = 0;
int len;
while (idx < data.Length)
{
string type = data[idx].ToString();
len = (int)data[idx + 1];
idx += 2;
if (len > 0)
{
Object[] item = new Object[len];
Array.Copy(data, idx, item, 0, len);
idx += len;
staticLock.AcquireReaderLock(-1);
try
{
switch (type)
{
case "listener":
m_Listener[engine].CreateFromData(localID, itemID,
hostID, item);
break;
case "timer":
m_Timer[engine].CreateFromData(localID, itemID,
hostID, item);
break;
case "sensor":
m_SensorRepeat[engine].CreateFromData(localID,
itemID, hostID, item);
break;
}
}
finally
{
staticLock.ReleaseReaderLock();
}
}
}
}
/// <summary>
/// Get the dataserver plugin for this script engine.
/// </summary>
/// <param name="engine"></param>
/// <returns></returns>
public static Dataserver GetDataserverPlugin(IScriptEngine engine)
{
staticLock.AcquireReaderLock(-1);
try
{
if (m_Dataserver.ContainsKey(engine))
return m_Dataserver[engine];
else
return null;
}
finally
{
staticLock.ReleaseReaderLock();
}
}
/// <summary>
/// Get the listener plugin for this script engine.
/// </summary>
/// <param name="engine"></param>
/// <returns></returns>
public static Listener GetListenerPlugin(IScriptEngine engine)
{
staticLock.AcquireReaderLock(-1);
try
{
if (m_Listener.ContainsKey(engine))
return m_Listener[engine];
else
return null;
}
finally
{
staticLock.ReleaseReaderLock();
}
}
/// <summary>
/// Get the sensor repeat plugin for this script engine.
/// </summary>
/// <param name="engine"></param>
/// <returns></returns>
public static SensorRepeat GetSensorRepeatPlugin(IScriptEngine engine)
{
staticLock.AcquireReaderLock(-1);
try
{
if (m_SensorRepeat.ContainsKey(engine))
return m_SensorRepeat[engine];
else
return null;
}
finally
{
staticLock.ReleaseReaderLock();
}
}
public static Object[] GetSerializationData(IScriptEngine engine, UUID itemID)
{
List<Object> data = new List<Object>();
staticLock.AcquireReaderLock(-1);
try
{
Object[] listeners = m_Listener[engine].GetSerializationData(itemID);
if (listeners.Length > 0)
{
data.Add("listener");
data.Add(listeners.Length);
data.AddRange(listeners);
}
Object[] timers = m_Timer[engine].GetSerializationData(itemID);
if (timers.Length > 0)
{
data.Add("timer");
data.Add(timers.Length);
data.AddRange(timers);
}
Object[] sensors = m_SensorRepeat[engine].GetSerializationData(itemID);
if (sensors.Length > 0)
{
data.Add("sensor");
data.Add(sensors.Length);
data.AddRange(sensors);
}
}
finally
{
staticLock.ReleaseReaderLock();
}
return data.ToArray();
}
/// <summary>
/// Get the timer plugin for this script engine.
/// </summary>
/// <param name="engine"></param>
/// <returns></returns>
public static Timer GetTimerPlugin(IScriptEngine engine)
{
staticLock.AcquireReaderLock(-1);
try
{
if (m_Timer.ContainsKey(engine))
return m_Timer[engine];
else
return null;
}
finally
{
staticLock.ReleaseReaderLock();
}
}
/// <summary>
/// Unregister a specific script from facilities (and all its pending commands)
/// </summary>
/// <param name="localID"></param>
/// <param name="itemID"></param>
public static void UnregisterScriptFacilities(IScriptEngine engine, uint localID, UUID itemID)
{
staticLock.AcquireReaderLock(-1);
try
{
// Remove dataserver events
m_Dataserver[engine].RemoveEvents(localID, itemID);
// Remove from: Timers
m_Timer[engine].UnSetTimerEvents(localID, itemID);
// Remove from: HttpRequest
IHttpRequestModule iHttpReq = engine.World.RequestModuleInterface<IHttpRequestModule>();
if (iHttpReq != null)
iHttpReq.StopHttpRequestsForScript(itemID);
IWorldComm comms = engine.World.RequestModuleInterface<IWorldComm>();
if (comms != null)
comms.DeleteListener(itemID);
IXMLRPC xmlrpc = engine.World.RequestModuleInterface<IXMLRPC>();
if (xmlrpc != null)
{
xmlrpc.DeleteChannels(itemID);
xmlrpc.CancelSRDRequests(itemID);
}
// Remove Sensors
m_SensorRepeat[engine].UnSetSenseRepeaterEvents(localID, itemID);
}
finally
{
staticLock.ReleaseReaderLock();
}
}
/// <summary>
/// Main loop for the manager thread
/// </summary>
private static void CmdHandlerThreadLoop()
{
while (true)
{
try
{
Thread.Sleep(cmdHandlerThreadCycleSleepms);
DoOneCmdHandlerPass();
Watchdog.UpdateThread();
}
catch (Exception e)
{
m_log.Error("[ASYNC COMMAND MANAGER]: Exception in command handler pass: ", e);
}
}
}
private static void DoOneCmdHandlerPass()
{
staticLock.AcquireReaderLock(-1);
try
{
// Check HttpRequests
m_HttpRequest[m_ScriptEngines[0]].CheckHttpRequests();
// Check XMLRPCRequests
m_XmlRequest[m_ScriptEngines[0]].CheckXMLRPCRequests();
foreach (IScriptEngine s in m_ScriptEngines)
{
// Check Listeners
m_Listener[s].CheckListeners();
// Check timers
m_Timer[s].CheckTimerEvents();
// Check Sensors
m_SensorRepeat[s].CheckSenseRepeaterEvents();
// Check dataserver
m_Dataserver[s].ExpireRequests();
}
}
finally
{
staticLock.ReleaseReaderLock();
}
}
private static void StartThread()
{
if (cmdHandlerThread == null)
{
// Start the thread that will be doing the work
cmdHandlerThread
= Watchdog.StartThread(
CmdHandlerThreadLoop, "AsyncLSLCmdHandlerThread", ThreadPriority.Normal, true, true);
}
}
private void ReadConfig()
{
// cmdHandlerThreadCycleSleepms = m_ScriptEngine.Config.GetInt("AsyncLLCommandLoopms", 100);
// TODO: Make this sane again
cmdHandlerThreadCycleSleepms = 100;
}
}
}
| |
/* Originally started back last year, and completely rewritten from the ground up to handle the
* Profiles for InWorldz, LLC.
* Modified again on 1/22/2011 by Beth Reischl to:
* Pull a couple of DB queries from the Classifieds section that were not needed
* Pulled a DB query from Profiles and modified another one.
* Pulled out the queryParcelUUID from PickInfoUpdate method, this was resulting in null parcel IDs
* being passed all the time.
* Fixed the PickInfoUpdate and PickInfoRequest to show Username, Parcel Information, Region Name, (xyz)
* coords for proper teleportation
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Xml;
using OpenMetaverse;
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Data.SimpleDB;
namespace OpenSimProfile.Modules.OpenProfile
{
public class OpenProfileModule : IRegionModule
{
//
// Log module
//
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
//
// Module vars
//
private IConfigSource m_gConfig;
private bool m_Enabled = true;
private ConnectionFactory _connFactory;
private ConnectionFactory _regionConnFactory;
public void Initialise(Scene scene, IConfigSource config)
{
if (!m_Enabled)
return;
//TODO: At some point, strip this out of the ini file, in Search Module,
// we're going to recycle the Profile connection string however to make
// life a bit easier.
IConfig profileConfig = config.Configs["Startup"];
string connstr = profileConfig.GetString("core_connection_string", String.Empty);
m_log.Info("[PROFILE] Profile module is activated");
//TODO: Bad assumption on my part that we're enabling it and the connstr is actually
// valid, but I'm sick of dinking with this thing :)
m_Enabled = true;
_connFactory = new ConnectionFactory("MySQL", connstr);
string storageConnStr = profileConfig.GetString("storage_connection_string", String.Empty);
_regionConnFactory = new ConnectionFactory("MySQL", storageConnStr);
m_gConfig = config;
// Hook up events
scene.EventManager.OnNewClient += OnNewClient;
}
public void PostInitialise()
{
if (!m_Enabled)
return;
}
public void Close()
{
}
public string Name
{
get { return "ProfileModule"; }
}
public bool IsSharedModule
{
get { return true; }
}
/// New Client Event Handler
private void OnNewClient(IClientAPI client)
{
// Classifieds
client.AddGenericPacketHandler("avatarclassifiedsrequest", HandleAvatarClassifiedsRequest);
client.OnClassifiedInfoUpdate += ClassifiedInfoUpdate;
client.OnClassifiedDelete += ClassifiedDelete;
// Picks
//TODO: there is an error generated here in the Grid as we've removed the
// need for this and wrapped it down below. This needs to be fixed.
// This applies to any reqeusts made for general info.
//client.AddGenericPacketHandler("avatarpicksrequest", HandlePickInfoRequest);
client.AddGenericPacketHandler("pickinforequest", HandlePickInfoRequest);
client.OnPickInfoUpdate += PickInfoUpdate;
client.OnPickDelete += PickDelete;
// Notes
client.AddGenericPacketHandler("avatarnotesrequest", HandleAvatarNotesRequest);
client.OnAvatarNotesUpdate += AvatarNotesUpdate;
// Interests
client.OnRequestAvatarProperties += new RequestAvatarProperties(client_OnRequestAvatarProperties);
client.OnAvatarInterestsUpdate += AvatarInterestsUpdate;
}
void client_OnRequestAvatarProperties(IClientAPI remoteClient, UUID avatarID)
{
List<String> alist = new List<String>();
alist.Add(avatarID.ToString());
HandleAvatarInterestsRequest(remoteClient, alist);
HandleAvatarPicksRequest(remoteClient, alist);
}
// Interests Handler
public void HandleAvatarInterestsRequest(Object sender, List<String> args)
{
IClientAPI remoteClient = (IClientAPI)sender;
UUID avatarID = new UUID(args[0]);
using (ISimpleDB db = _connFactory.GetConnection())
{
uint skillsMask = new uint();
string skillsText = "";
uint wantToMask = new uint();
string wantToText = "";
string languagesText = "";
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?avatarID", avatarID);
string query = "SELECT skillsMask, skillsText, wantToMask, wantToText, languagesText FROM users " +
"WHERE UUID=?avatarID";
List<Dictionary<string, string>> results = db.QueryWithResults(query, parms);
foreach (Dictionary<string, string> row in results)
{
skillsMask = Convert.ToUInt16(row["skillsMask"]);
skillsText = row["skillsText"];
wantToMask = Convert.ToUInt16(row["wantToMask"]);
wantToText = row["wantToText"];
languagesText = row["languagesText"];
}
remoteClient.SendAvatarInterestsReply(avatarID,
wantToMask,
wantToText,
skillsMask,
skillsText,
languagesText);
}
}
// Interests Update
public void AvatarInterestsUpdate(IClientAPI remoteClient, uint querySkillsMask, string querySkillsText, uint queryWantToMask, string queryWantToText, string
queryLanguagesText)
{
UUID avatarID = remoteClient.AgentId;
using (ISimpleDB db = _connFactory.GetConnection())
{
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?avatarID", avatarID);
parms.Add("?skillsMask", querySkillsMask);
parms.Add("?skillsText", querySkillsText);
parms.Add("?wantToMask", queryWantToMask);
parms.Add("?wantToText", queryWantToText);
parms.Add("?languagesText", queryLanguagesText);
string query = "UPDATE users set skillsMask=?wantToMask, skillsText=?wantToText, wantToMask=?skillsMask, " +
"wantToText=?skillsText, languagesText=?languagesText where UUID=?avatarID";
db.QueryNoResults(query, parms);
}
}
// Classifieds Handler
public void HandleAvatarClassifiedsRequest(Object sender, string method, List<String> args)
{
if (!(sender is IClientAPI))
return;
IClientAPI remoteClient = (IClientAPI)sender;
UUID avatarID = new UUID(args[0]);
using (ISimpleDB db = _connFactory.GetConnection())
{
UUID classifiedID = new UUID();
Dictionary<UUID, string> classifieds = new Dictionary<UUID, string>();
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?avatarID", avatarID);
string query = "SELECT classifieduuid, name from classifieds " +
"WHERE creatoruuid=?avatarID";
List<Dictionary<string, string>> results = db.QueryWithResults(query, parms);
foreach (Dictionary<string, string> row in results)
{
classifiedID = UUID.Parse(row["classifieduuid"]);
classifieds[new UUID(row["classifieduuid"].ToString())] = row["name"].ToString();
}
remoteClient.SendAvatarClassifiedReply(avatarID,
classifieds);
}
}
// Classifieds Update
public const int MIN_CLASSIFIED_PRICE = 50;
public void ClassifiedInfoUpdate(UUID queryclassifiedID, uint queryCategory, string queryName, string queryDescription, UUID queryParcelID,
uint queryParentEstate, UUID querySnapshotID, Vector3 queryGlobalPos, byte queryclassifiedFlags,
int queryclassifiedPrice, IClientAPI remoteClient)
{
// getting information lined up for the query
UUID avatarID = remoteClient.AgentId;
UUID regionUUID = remoteClient.Scene.RegionInfo.RegionID;
UUID ParcelID = UUID.Zero;
uint regionX = remoteClient.Scene.RegionInfo.RegionLocX;
uint regionY = remoteClient.Scene.RegionInfo.RegionLocY;
// m_log.DebugFormat("[CLASSIFIED]: Got the RegionX Location as: {0}, and RegionY as: {1}", regionX.ToString(), regionY.ToString());
string regionName = remoteClient.Scene.RegionInfo.RegionName;
int creationDate = Util.UnixTimeSinceEpoch();
int expirationDate = creationDate + 604800;
if (queryclassifiedPrice < MIN_CLASSIFIED_PRICE)
{
m_log.ErrorFormat("[CLASSIFIED]: Got a request for invalid price I'z${0} on a classified from {1}.", queryclassifiedPrice.ToString(), remoteClient.AgentId.ToString());
remoteClient.SendAgentAlertMessage("Error: The minimum price for a classified advertisement is I'z$" + MIN_CLASSIFIED_PRICE.ToString()+".", true);
return;
}
// Check for hacked names that start with special characters
if (!Char.IsLetterOrDigit(queryName, 0))
{
m_log.ErrorFormat("[CLASSIFIED]: Got a hacked request from {0} for invalid name classified name: {1}", remoteClient.AgentId.ToString(), queryName);
remoteClient.SendAgentAlertMessage("Error: The name of your classified must start with a letter or a number. No punctuation is allowed.", true);
return;
}
// In case of insert, original values are the new values (by default)
int origPrice = 0;
int updatedPrice = queryclassifiedPrice;
using (ISimpleDB db = _connFactory.GetConnection())
{
//if this is an existing classified make sure the client is the owner or don't touch it
string existingCheck = "SELECT creatoruuid FROM classifieds WHERE classifieduuid = ?classifiedID";
Dictionary<string, object> checkParms = new Dictionary<string, object>();
checkParms.Add("?classifiedID", queryclassifiedID);
List<Dictionary<string, string>> existingResults = db.QueryWithResults(existingCheck, checkParms);
if (existingResults.Count > 0)
{
string existingAuthor = existingResults[0]["creatoruuid"];
if (existingAuthor != avatarID.ToString())
{
m_log.ErrorFormat("[CLASSIFIED]: Got a request for from {0} to modify a classified from {1}: {2}",
remoteClient.AgentId.ToString(), existingAuthor, queryclassifiedID.ToString());
remoteClient.SendAgentAlertMessage("Error: You do not have permission to modify that classified ad.", true);
return;
}
}
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?avatarID", avatarID);
parms.Add("?classifiedID", queryclassifiedID);
parms.Add("?category", queryCategory);
parms.Add("?name", queryName);
parms.Add("?description", queryDescription);
//parms.Add("?parcelID", queryParcelID);
parms.Add("?parentEstate", queryParentEstate);
parms.Add("?snapshotID", querySnapshotID);
parms.Add("?globalPos", queryGlobalPos);
parms.Add("?classifiedFlags", queryclassifiedFlags);
parms.Add("?classifiedPrice", queryclassifiedPrice);
parms.Add("?creationDate", creationDate);
parms.Add("?expirationDate", expirationDate);
parms.Add("?regionUUID", regionUUID);
parms.Add("?regionName", regionName);
// We need parcelUUID from land to place in the query properly
// However, there can be multiple Parcel UUIDS per region,
// so we need to do some math from the classified entry
// to the positioning of the avatar
// The point we have is a global position value, which means
// we need to to get the location with: (GlobalX / 256) - RegionX and
// (GlobalY / 256) - RegionY for the values of the avatar standign position
// then compare that to the parcels for the closest match
// explode the GlobalPos value off the bat
string origGlobPos = queryGlobalPos.ToString();
string tempAGlobPos = origGlobPos.Replace("<", "");
string tempBGlobPos = tempAGlobPos.Replace(">", "");
char[] delimiterChars = { ',', ' ' };
string[] globalPosBits = tempBGlobPos.Split(delimiterChars);
uint tempAvaXLoc = Convert.ToUInt32(Convert.ToDouble(globalPosBits[0]));
uint tempAvaYLoc = Convert.ToUInt32(Convert.ToDouble(globalPosBits[2]));
uint avaXLoc = tempAvaXLoc - (256 * regionX);
uint avaYLoc = tempAvaYLoc - (256 * regionY);
//uint avatarPosX = (posGlobalX / 256) - regionX;
parms.Add("?avaXLoc", avaXLoc.ToString());
parms.Add("?avaYLoc", avaYLoc.ToString());
string parcelLocate = "select uuid, MIN(ABS(UserLocationX - ?avaXLoc)) as minXValue, MIN(ABS(UserLocationY - ?avaYLoc)) as minYValue from land where RegionUUID=?regionUUID GROUP BY UserLocationX ORDER BY minXValue, minYValue LIMIT 1;";
using (ISimpleDB landDb = _regionConnFactory.GetConnection())
{
List<Dictionary<string, string>> parcelLocated = landDb.QueryWithResults(parcelLocate, parms);
foreach (Dictionary<string, string> row in parcelLocated)
{
ParcelID = new UUID(row["uuid"].ToString());
}
}
parms.Add("?parcelID", ParcelID);
string queryClassifieds = "select * from classifieds where classifieduuid=?classifiedID AND creatoruuid=?avatarID";
List<Dictionary <string, string>> results = db.QueryWithResults(queryClassifieds, parms);
bool isUpdate = false;
int costToApply;
string transactionDesc;
if (results.Count != 0)
{
if (results.Count != 1)
{
remoteClient.SendAgentAlertMessage("Classified record is not consistent. Contact Support for assistance.", false);
m_log.ErrorFormat("[CLASSIFIED]: Error, query for user {0} classified ad {1} returned {2} results.",
avatarID.ToString(), queryclassifiedID.ToString(), results.Count.ToString());
return;
}
// This is an upgrade of a classified ad.
Dictionary<string, string> row = results[0];
isUpdate = true;
transactionDesc = "Classified price change";
origPrice = Convert.ToInt32(row["priceforlisting"]);
// Also preserve original creation date and expiry.
creationDate = Convert.ToInt32(row["creationdate"]);
expirationDate = Convert.ToInt32(row["expirationdate"]);
costToApply = queryclassifiedPrice - origPrice;
if (costToApply < 0) costToApply = 0;
}
else
{
// This is the initial placement of the classified.
transactionDesc = "Classified charge";
creationDate = Util.UnixTimeSinceEpoch();
expirationDate = creationDate + 604800;
costToApply = queryclassifiedPrice;
}
EventManager.ClassifiedPaymentArgs paymentArgs = new EventManager.ClassifiedPaymentArgs(remoteClient.AgentId, queryclassifiedID, origPrice, queryclassifiedPrice, transactionDesc, true);
if (costToApply > 0)
{
// Now check whether the payment is authorized by the currency system.
((Scene)remoteClient.Scene).EventManager.TriggerClassifiedPayment(remoteClient, paymentArgs);
if (!paymentArgs.mIsAuthorized)
return; // already reported to user by the check above.
}
string query;
if (isUpdate)
{
query = "UPDATE classifieds set creationdate=?creationDate, " +
"category=?category, name=?name, description=?description, parceluuid=?parcelID, " +
"parentestate=?parentEstate, snapshotuuid=?snapshotID, simname=?regionName, posglobal=?globalPos, parcelname=?name, " +
" classifiedflags=?classifiedFlags, priceforlisting=?classifiedPrice where classifieduuid=?classifiedID";
}
else
{
query = "INSERT into classifieds (classifieduuid, creatoruuid, creationdate, expirationdate, category, name, " +
"description, parceluuid, parentestate, snapshotuuid, simname, posglobal, parcelname, classifiedflags, priceforlisting) " +
"VALUES (?classifiedID, ?avatarID, ?creationDate, ?expirationDate, ?category, ?name, ?description, ?parcelID, " +
"?parentEstate, ?snapshotID, ?regionName, ?globalPos, ?name, ?classifiedFlags, ?classifiedPrice)";
}
db.QueryNoResults(query, parms);
if (costToApply > 0) // no refunds for lower prices
{
// Handle the actual money transaction here.
paymentArgs.mIsPreCheck = false; // now call it again but for real this time
((Scene)remoteClient.Scene).EventManager.TriggerClassifiedPayment(remoteClient, paymentArgs);
// Errors reported by the payment request above.
}
}
}
// Classifieds Delete
public void ClassifiedDelete(UUID queryClassifiedID, IClientAPI remoteClient)
{
UUID avatarID = remoteClient.AgentId;
UUID classifiedID = queryClassifiedID;
using (ISimpleDB db = _connFactory.GetConnection())
{
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?classifiedID", classifiedID);
parms.Add("?avatarID", avatarID);
string query = "delete from classifieds where classifieduuid=?classifiedID AND creatorUUID=?avatarID";
db.QueryNoResults(query, parms);
}
}
// Picks Handler
public void HandleAvatarPicksRequest(Object sender, List<String> args)
{
if (!(sender is IClientAPI))
return;
IClientAPI remoteClient = (IClientAPI)sender;
UUID avatarID = new UUID(args[0]);
using (ISimpleDB db = _connFactory.GetConnection())
{
UUID picksID = new UUID();
Dictionary<UUID, string> picksRequest = new Dictionary<UUID, string>();
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?avatarID", avatarID);
string query = "SELECT pickuuid, name from userpicks " +
"WHERE creatoruuid=?avatarID";
List<Dictionary<string, string>> results = db.QueryWithResults(query, parms);
foreach (Dictionary<string, string> row in results)
{
picksID = UUID.Parse(row["pickuuid"]);
picksRequest[new UUID(row["pickuuid"].ToString())] = row["name"].ToString();
}
remoteClient.SendAvatarPicksReply(avatarID,
picksRequest);
}
}
// Picks Request
public void HandlePickInfoRequest(Object sender, string method, List<String> args)
{
if (!(sender is IClientAPI))
return;
IClientAPI remoteClient = (IClientAPI)sender;
UUID avatarID = new UUID(args[0]);
UUID pickID = new UUID(args[1]);
using (ISimpleDB db = _connFactory.GetConnection())
{
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?avatarID", avatarID);
parms.Add("?pickID", pickID);
string query = "SELECT * from userpicks WHERE creatoruuid=?avatarID AND pickuuid=?pickID";
List<Dictionary<string, string>> results = db.QueryWithResults(query, parms);
bool topPick = new bool();
UUID parcelUUID = new UUID();
string name = "";
string description = "";
UUID snapshotID = new UUID();
string userName = "";
string originalName = "";
string simName = "";
Vector3 globalPos = new Vector3();
int sortOrder = new int();
bool enabled = new bool();
foreach (Dictionary<string, string> row in results)
{
topPick = Boolean.Parse(row["toppick"]);
parcelUUID = UUID.Parse(row["parceluuid"]);
name = row["name"];
description = row["description"];
snapshotID = UUID.Parse(row["snapshotuuid"]);
userName = row["user"];
//userName = row["simname"];
originalName = row["originalname"];
simName = row["simname"];
globalPos = Vector3.Parse(row["posglobal"]);
sortOrder = Convert.ToInt32(row["sortorder"]);
enabled = Boolean.Parse(row["enabled"]);
}
remoteClient.SendPickInfoReply( pickID, avatarID,
topPick, parcelUUID, name, description,
snapshotID, userName, originalName,
simName, globalPos, sortOrder,
enabled);
}
}
// Picks Update
// pulled the original method due to UUID queryParcelID always being returned as null. If this is ever fixed to where
// the viewer does in fact return the parcelID, then we can put this back in.
//public void PickInfoUpdate(IClientAPI remoteClient, UUID pickID, UUID creatorID, bool topPick, string name, string desc,
// UUID queryParcelID, Vector3 queryGlobalPos, UUID snapshotID, int sortOrder, bool enabled)
public void PickInfoUpdate(IClientAPI remoteClient, UUID pickID, UUID creatorID, bool topPick, string name, string desc,
Vector3 queryGlobalPos, UUID snapshotID, int sortOrder, bool enabled)
{
string userRegion = remoteClient.Scene.RegionInfo.RegionName;
UUID userRegionID = remoteClient.Scene.RegionInfo.RegionID;
string userFName = remoteClient.FirstName;
string userLName = remoteClient.LastName;
string avatarName = userFName + " " + userLName;
string parcelName = name;
UUID tempParcelUUID = UUID.Zero;
UUID avatarID = remoteClient.AgentId;
using (ISimpleDB db = _connFactory.GetConnection())
{
//if this is an existing pick make sure the client is the owner or don't touch it
string existingCheck = "SELECT creatoruuid FROM userpicks WHERE pickuuid = ?pickID";
Dictionary<string, object> checkParms = new Dictionary<string, object>();
checkParms.Add("?pickID", pickID);
List<Dictionary<string, string>> existingResults = db.QueryWithResults(existingCheck, checkParms);
if (existingResults.Count > 0)
{
if (existingResults[0]["creatoruuid"] != avatarID.ToString())
{
return;
}
}
//reassign creator id, it has to be this avatar
creatorID = avatarID;
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?avatarID", avatarID);
parms.Add("?pickID", pickID);
parms.Add("?creatorID", creatorID);
parms.Add("?topPick", topPick);
parms.Add("?name", name);
parms.Add("?desc", desc);
parms.Add("?globalPos", queryGlobalPos);
parms.Add("?snapshotID", snapshotID);
parms.Add("?sortOrder", sortOrder);
parms.Add("?enabled", enabled);
parms.Add("?regionID", userRegionID);
parms.Add("?regionName", userRegion);
// we need to know if we're on a parcel or not, and if so, put it's UUID in there
// viewer isn't giving it to us from what I can determine
// TODO: David will need to clean this up cause more arrays are not my thing :)
string queryParcelUUID = "select UUID from land where regionUUID=?regionID AND name=?name limit 1";
using (ISimpleDB landDb = _regionConnFactory.GetConnection())
{
List<Dictionary<string, string>> simID = landDb.QueryWithResults(queryParcelUUID, parms);
foreach (Dictionary<string, string> row in simID)
{
tempParcelUUID = UUID.Parse(row["UUID"]);
}
}
UUID parcelUUID = tempParcelUUID;
parms.Add("?parcelID", parcelUUID);
m_log.Debug("Got parcel of: " + parcelUUID.ToString());
parms.Add("?parcelName", name);
string queryPicksCount = "select COUNT(pickuuid) from userpicks where pickuuid=?pickID AND " +
"creatoruuid=?creatorID";
List<Dictionary <string, string>> countList = db.QueryWithResults(queryPicksCount, parms);
string query;
string picksCount="";
foreach (Dictionary<string, string> row in countList)
{
picksCount = row["COUNT(pickuuid)"];
}
parms.Add("?avatarName", avatarName);
//TODO: We're defaulting topPick to false for the moment along with enabled default to True
// We'll need to look over the conversion vs MySQL cause data truncating should not happen
if(picksCount == "0")
{
query = "INSERT into userpicks (pickuuid, creatoruuid, toppick, parceluuid, name, description, snapshotuuid, user, " +
"originalname, simname, posglobal, sortorder, enabled) " +
"VALUES (?pickID, ?creatorID, 'false', ?parcelID, ?name, ?desc, ?snapshotID, " +
"?avatarName, ?parcelName, ?regionName, ?globalPos, ?sortOrder, 'true')";
} else
{
query = "UPDATE userpicks set toppick='false', " +
" parceluuid=?parcelID, name=?name, description=?desc, snapshotuuid=?snapshotID, " +
"user=?avatarName, originalname=?parcelName, simname=?regionName, posglobal=?globalPos, sortorder=?sortOrder, " +
" enabled='true' where pickuuid=?pickID";
}
db.QueryNoResults(query, parms);
}
}
// Picks Delete
public void PickDelete(IClientAPI remoteClient, UUID queryPickID)
{
UUID avatarID = remoteClient.AgentId;
using (ISimpleDB db = _connFactory.GetConnection())
{
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?pickID", queryPickID);
parms.Add("?avatarID", avatarID);
string query = "delete from userpicks where pickuuid=?pickID AND creatoruuid=?avatarID";
db.QueryNoResults(query, parms);
}
}
private const string LEGACY_EMPTY = "No notes currently for this avatar!";
public void HandleAvatarNotesRequest(Object sender, string method, List<String> args)
{
if (!(sender is IClientAPI))
return;
IClientAPI remoteClient = (IClientAPI)sender;
UUID avatarID = remoteClient.AgentId;
UUID targetAvatarID = new UUID(args[0]);
using (ISimpleDB db = _connFactory.GetConnection())
{
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?avatarID", avatarID);
parms.Add("?targetID", targetAvatarID);
string query = "SELECT notes from usernotes where useruuid=?avatarID AND targetuuid=?targetID";
List<Dictionary<string, string>> notesResult = db.QueryWithResults(query, parms);
string notes = string.Empty;
if (notesResult.Count > 0)
notes = notesResult[0]["notes"];
if (notes == LEGACY_EMPTY) // filter out the old text that said there was no text. ;)
notes = string.Empty;
remoteClient.SendAvatarNotesReply(targetAvatarID, notes);
}
}
public void AvatarNotesUpdate(IClientAPI remoteClient, UUID queryTargetID, string queryNotes)
{
UUID avatarID = remoteClient.AgentId;
// allow leading spaces for formatting, but TrimEnd will help us detect an empty field other than spaces
string notes = queryNotes.TrimEnd();
// filter out the old text that said there was no text. ;)
if (notes == LEGACY_EMPTY)
notes = string.Empty;
using (ISimpleDB db = _connFactory.GetConnection())
{
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?avatarID", avatarID);
parms.Add("?targetID", queryTargetID);
parms.Add("?notes", notes);
string query;
if (notes == string.Empty)
query = "DELETE FROM usernotes WHERE useruuid=?avatarID AND targetuuid=?targetID";
else
query = "INSERT INTO usernotes(useruuid, targetuuid, notes) VALUES(?avatarID,?targetID,?notes) ON DUPLICATE KEY UPDATE notes=?notes";
db.QueryNoResults(query, parms);
}
}
}
}
| |
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
// offered to the public domain for any use with no restriction
// and also with no warranty of any kind, please enjoy. - David Jeske.
// simple HTTP explanation
// http://www.jmarshall.com/easy/http/
// See also: http://www.codeproject.com/Articles/137979/Simple-HTTP-Server-in-C
namespace vubbiscript
{
public class HttpProcessor {
public TcpClient socket;
public HttpServer srv;
private Stream inputStream;
public StreamWriter outputStream;
public String http_method;
public String http_url;
public String http_protocol_versionstring;
public Hashtable httpHeaders = new Hashtable();
private static int MAX_POST_SIZE = 10 * 1024 * 1024; // 10MB
public HttpProcessor(TcpClient s, HttpServer srv) {
this.socket = s;
this.srv = srv;
}
private string streamReadLine() {
int next_char;
string data = "";
while (true) {
next_char = inputStream.ReadByte();
if (next_char == '\n') { break; }
if (next_char == '\r') { continue; }
if (next_char == -1) { return null; };
data += Convert.ToChar(next_char);
}
return data;
}
public void process() {
// we can't use a StreamReader for input, because it buffers up extra data on us inside it's
// "processed" view of the world, and we want the data raw after the headers
inputStream = new BufferedStream(socket.GetStream());
// we probably shouldn't be using a streamwriter for all output from handlers either
outputStream = new StreamWriter(new BufferedStream(socket.GetStream()));
try {
// Keep processing requests from the browser (keep alive)
while(true) {
parseRequest();
readHeaders();
if (http_method.Equals("GET")) {
handleGETRequest();
} else if (http_method.Equals("POST")) {
handlePOSTRequest();
}
outputStream.Flush();
}
} catch (EndOfStreamException eose) {
if (eose.Message == "EOS_BROWSER") {
return;
}
} catch (Exception e) {
ServerLog.Log ("Exception: " + e.ToString ());
writeFailure();
outputStream.Flush();
} finally {
// bs.Flush(); // flush any remaining output
inputStream = null; outputStream = null; // bs = null;
socket.Close();
}
}
public void parseRequest() {
String request = streamReadLine();
if (request == null) {
// Connection closed by browser
throw new EndOfStreamException("EOS_BROWSER");
}
string[] tokens = request.Split(' ');
if (tokens.Length != 3) {
throw new Exception("invalid http request line");
}
http_method = tokens[0].ToUpper();
http_url = tokens[1];
http_protocol_versionstring = tokens[2];
ServerLog.LogInfo("starting: " + request);
}
public void readHeaders() {
Console.WriteLine("readHeaders()");
String line;
while ((line = streamReadLine()) != null) {
if (line.Equals("")) {
ServerLog.LogInfo("got headers");
return;
}
int separator = line.IndexOf(':');
if (separator == -1) {
throw new Exception("invalid http header line: " + line);
}
String name = line.Substring(0, separator);
int pos = separator + 1;
while ((pos < line.Length) && (line[pos] == ' ')) {
pos++; // strip any spaces
}
string value = line.Substring(pos, line.Length - pos);
ServerLog.LogInfo(String.Format("header: {0}:{1}",name,value));
httpHeaders[name] = value;
}
}
public void handleGETRequest() {
srv.handleGETRequest(this);
}
private const int BUF_SIZE = 4096;
public void handlePOSTRequest() {
// this post data processing just reads everything into a memory stream.
// this is fine for smallish things, but for large stuff we should really
// hand an input stream to the request processor. However, the input stream
// we hand him needs to let him see the "end of the stream" at this content
// length, because otherwise he won't know when he's seen it all!
ServerLog.LogInfo("get post data start");
int content_len = 0;
MemoryStream ms = new MemoryStream();
if (this.httpHeaders.ContainsKey("Content-Length")) {
content_len = Convert.ToInt32(this.httpHeaders["Content-Length"]);
if (content_len > MAX_POST_SIZE) {
throw new Exception(
String.Format("POST Content-Length({0}) too big for this simple server",
content_len));
}
byte[] buf = new byte[BUF_SIZE];
int to_read = content_len;
while (to_read > 0) {
ServerLog.LogInfo(String.Format("starting Read, to_read={0}",to_read));
int numread = this.inputStream.Read(buf, 0, Math.Min(BUF_SIZE, to_read));
ServerLog.LogInfo(String.Format("read finished, numread={0}", numread));
if (numread == 0) {
if (to_read == 0) {
break;
} else {
throw new Exception("client disconnected during post");
}
}
to_read -= numread;
ms.Write(buf, 0, numread);
}
ms.Seek(0, SeekOrigin.Begin);
}
ServerLog.LogInfo("get post data end");
srv.handlePOSTRequest(this, new StreamReader(ms));
}
public void writeSuccess(string content_type="text/html") {
// this is the successful HTTP response line
outputStream.WriteLine("HTTP/1.0 200 OK");
// these are the HTTP headers...
outputStream.WriteLine("Content-Type: " + content_type);
outputStream.WriteLine("Connection: close");
// ..add your own headers here if you like
outputStream.WriteLine(""); // this terminates the HTTP headers.. everything after this is HTTP body..
}
public void writeFailure() {
// this is an http 404 failure response
outputStream.WriteLine("HTTP/1.0 404 File not found");
// these are the HTTP headers
outputStream.WriteLine("Connection: close");
// ..add your own headers here
outputStream.WriteLine(""); // this terminates the HTTP headers.
}
}
public abstract class HttpServer {
protected IPAddress address;
protected int port;
TcpListener listener;
bool is_active = true;
public HttpServer(IPAddress address, int port) {
this.port = port;
this.address = address;
}
public void listen() {
try{
listener = new TcpListener(address, port);
listener.Start();
while (is_active) {
ServerLog.LogInfo ("Listening!");
TcpClient s = listener.AcceptTcpClient();
ServerLog.LogInfo ("Client accepted!");
s.ReceiveTimeout = 1000;// After 1 seconds, time out the read operation!!!
// Why? Because as long as the operation is waiting, this thread is in "native code" and Unity cannot go to "play" mode or reload the scripts!
HttpProcessor processor = new HttpProcessor(s, this);
Thread thread = new Thread(new ThreadStart(processor.process));
thread.Start();
Thread.Sleep(1);
}
} catch(Exception e) {
ServerLog.Log ("Server Listening Exception!");
ServerLog.Log (e);
} finally {
listener.Stop();
listener.Server.Close();
ServerLog.LogInfo ("Listening stopped!");
}
}
public abstract void handleGETRequest(HttpProcessor p);
public abstract void handlePOSTRequest(HttpProcessor p, StreamReader inputData);
}
}
| |
// 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: A representation of an IEEE double precision
** floating point number.
**
**
===========================================================*/
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
namespace System
{
[Serializable]
[StructLayout(LayoutKind.Sequential)]
[TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public struct Double : IComparable, IConvertible, IFormattable, IComparable<Double>, IEquatable<Double>
{
private double m_value; // Do not rename (binary serialization)
//
// Public Constants
//
public const double MinValue = -1.7976931348623157E+308;
public const double MaxValue = 1.7976931348623157E+308;
// Note Epsilon should be a double whose hex representation is 0x1
// on little endian machines.
public const double Epsilon = 4.9406564584124654E-324;
public const double NegativeInfinity = (double)-1.0 / (double)(0.0);
public const double PositiveInfinity = (double)1.0 / (double)(0.0);
public const double NaN = (double)0.0 / (double)0.0;
// We use this explicit definition to avoid the confusion between 0.0 and -0.0.
internal const double NegativeZero = -0.0;
/// <summary>Determines whether the specified value is finite (zero, subnormal, or normal).</summary>
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static bool IsFinite(double d)
{
var bits = BitConverter.DoubleToInt64Bits(d);
return (bits & 0x7FFFFFFFFFFFFFFF) < 0x7FF0000000000000;
}
/// <summary>Determines whether the specified value is infinite.</summary>
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static bool IsInfinity(double d)
{
var bits = BitConverter.DoubleToInt64Bits(d);
return (bits & 0x7FFFFFFFFFFFFFFF) == 0x7FF0000000000000;
}
/// <summary>Determines whether the specified value is NaN.</summary>
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static bool IsNaN(double d)
{
var bits = BitConverter.DoubleToInt64Bits(d);
return (bits & 0x7FFFFFFFFFFFFFFF) > 0x7FF0000000000000;
}
/// <summary>Determines whether the specified value is negative.</summary>
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static bool IsNegative(double d)
{
var bits = unchecked((ulong)BitConverter.DoubleToInt64Bits(d));
return (bits & 0x8000000000000000) == 0x8000000000000000;
}
/// <summary>Determines whether the specified value is negative infinity.</summary>
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsNegativeInfinity(double d)
{
return (d == double.NegativeInfinity);
}
/// <summary>Determines whether the specified value is normal.</summary>
[NonVersionable]
// This is probably not worth inlining, it has branches and should be rarely called
public unsafe static bool IsNormal(double d)
{
var bits = BitConverter.DoubleToInt64Bits(d);
bits &= 0x7FFFFFFFFFFFFFFF;
return (bits < 0x7FF0000000000000) && (bits != 0) && ((bits & 0x7FF0000000000000) != 0);
}
/// <summary>Determines whether the specified value is positive infinity.</summary>
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsPositiveInfinity(double d)
{
return (d == double.PositiveInfinity);
}
/// <summary>Determines whether the specified value is subnormal.</summary>
[NonVersionable]
// This is probably not worth inlining, it has branches and should be rarely called
public unsafe static bool IsSubnormal(double d)
{
var bits = BitConverter.DoubleToInt64Bits(d);
bits &= 0x7FFFFFFFFFFFFFFF;
return (bits < 0x7FF0000000000000) && (bits != 0) && ((bits & 0x7FF0000000000000) == 0);
}
// Compares this object to another object, returning an instance of System.Relation.
// Null is considered less than any instance.
//
// If object is not of type Double, this method throws an ArgumentException.
//
// Returns a value less than zero if this object
//
public int CompareTo(Object value)
{
if (value == null)
{
return 1;
}
if (value is Double)
{
double d = (double)value;
if (m_value < d) return -1;
if (m_value > d) return 1;
if (m_value == d) return 0;
// At least one of the values is NaN.
if (IsNaN(m_value))
return (IsNaN(d) ? 0 : -1);
else
return 1;
}
throw new ArgumentException(SR.Arg_MustBeDouble);
}
public int CompareTo(Double value)
{
if (m_value < value) return -1;
if (m_value > value) return 1;
if (m_value == value) return 0;
// At least one of the values is NaN.
if (IsNaN(m_value))
return (IsNaN(value) ? 0 : -1);
else
return 1;
}
// True if obj is another Double with the same value as the current instance. This is
// a method of object equality, that only returns true if obj is also a double.
public override bool Equals(Object obj)
{
if (!(obj is Double))
{
return false;
}
double temp = ((Double)obj).m_value;
// This code below is written this way for performance reasons i.e the != and == check is intentional.
if (temp == m_value)
{
return true;
}
return IsNaN(temp) && IsNaN(m_value);
}
[NonVersionable]
public static bool operator ==(Double left, Double right)
{
return left == right;
}
[NonVersionable]
public static bool operator !=(Double left, Double right)
{
return left != right;
}
[NonVersionable]
public static bool operator <(Double left, Double right)
{
return left < right;
}
[NonVersionable]
public static bool operator >(Double left, Double right)
{
return left > right;
}
[NonVersionable]
public static bool operator <=(Double left, Double right)
{
return left <= right;
}
[NonVersionable]
public static bool operator >=(Double left, Double right)
{
return left >= right;
}
public bool Equals(Double obj)
{
if (obj == m_value)
{
return true;
}
return IsNaN(obj) && IsNaN(m_value);
}
//The hashcode for a double is the absolute value of the integer representation
//of that double.
//
public unsafe override int GetHashCode()
{
double d = m_value;
if (d == 0)
{
// Ensure that 0 and -0 have the same hash code
return 0;
}
long value = *(long*)(&d);
return unchecked((int)value) ^ ((int)(value >> 32));
}
public override String ToString()
{
return Number.FormatDouble(m_value, null, NumberFormatInfo.CurrentInfo);
}
public String ToString(String format)
{
return Number.FormatDouble(m_value, format, NumberFormatInfo.CurrentInfo);
}
public String ToString(IFormatProvider provider)
{
return Number.FormatDouble(m_value, null, NumberFormatInfo.GetInstance(provider));
}
public String ToString(String format, IFormatProvider provider)
{
return Number.FormatDouble(m_value, format, NumberFormatInfo.GetInstance(provider));
}
public static double Parse(String s)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseDouble(s.AsReadOnlySpan(), NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo);
}
public static double Parse(String s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseDouble(s.AsReadOnlySpan(), style, NumberFormatInfo.CurrentInfo);
}
public static double Parse(String s, IFormatProvider provider)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseDouble(s.AsReadOnlySpan(), NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider));
}
public static double Parse(String s, NumberStyles style, IFormatProvider provider)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseDouble(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider));
}
// Parses a double from a String in the given style. If
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
//
// This method will not throw an OverflowException, but will return
// PositiveInfinity or NegativeInfinity for a number that is too
// large or too small.
public static double Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
return Number.ParseDouble(s, style, NumberFormatInfo.GetInstance(provider));
}
public static bool TryParse(String s, out double result)
{
if (s == null)
{
result = 0;
return false;
}
return TryParse(s.AsReadOnlySpan(), NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result);
}
public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out double result)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
if (s == null)
{
result = 0;
return false;
}
return TryParse(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider), out result);
}
public static bool TryParse(ReadOnlySpan<char> s, out double result, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
private static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out double result)
{
bool success = Number.TryParseDouble(s, style, info, out result);
if (!success)
{
ReadOnlySpan<char> sTrim = StringSpanHelpers.Trim(s);
if (StringSpanHelpers.Equals(sTrim, info.PositiveInfinitySymbol))
{
result = PositiveInfinity;
}
else if (StringSpanHelpers.Equals(sTrim, info.NegativeInfinitySymbol))
{
result = NegativeInfinity;
}
else if (StringSpanHelpers.Equals(sTrim, info.NaNSymbol))
{
result = NaN;
}
else
{
return false; // We really failed
}
}
return true;
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.Double;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(m_value);
}
char IConvertible.ToChar(IFormatProvider provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Double", "Char"));
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(m_value);
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(m_value);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(m_value);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(m_value);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(m_value);
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(m_value);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(m_value);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(m_value);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(m_value);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return m_value;
}
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(m_value);
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Double", "DateTime"));
}
Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
using Android.App;
using Android.OS;
using MvvmCross.Droid.Views;
using Android.Webkit;
using Android.Views;
using Android.Widget;
using Android.Speech.Tts;
using Android.Content;
using Android.Speech;
using ProgrammingSupport.Core.ViewModels;
using System.Collections.Generic;
using AltBeaconOrg.BoundBeacon;
using System.Linq;
using System;
using ProgrammingSupport.Core;
using System.Threading.Tasks;
namespace ProgrammingSupport.Droid.Views
{
[Activity(Label = "View for QuestionViewModel", ScreenOrientation = Android.Content.PM.ScreenOrientation.Landscape)]
public class QuestionView : MvxActivity, TextToSpeech.IOnInitListener, IBeaconConsumer
{
private bool isRecording = false;
private readonly int VOICE = 10;
private TextToSpeech speaker;
private string toSpeak;
private Intent _voiceIntent;
private readonly RangeNotifier _rangeNotifier;
private List<Beacon> _beacons;
private BeaconManager _beaconManager;
AltBeaconOrg.BoundBeacon.Region _tagRegion, _emptyRegion;
private double distanceClosestCSharp = 9999999d;
private double distanceClosestJava = 9999999d;
private WebView _webView;
private RelativeLayout _click;
private ImageView _text;
private bool pizzaFlow = false;
private bool skypeFlow = false;
private bool stackOverflowFlow = false;
private string _question;
public QuestionView()
{
_rangeNotifier = new RangeNotifier();
_beacons = new List<Beacon>();
}
protected override void OnCreate(Bundle bundle)
{
ActionBar.Hide();
base.OnCreate(bundle);
SetContentView(Resource.Layout.FirstView);
(ViewModel as QuestionViewModel).AnswerUpdated += OnAnswerUpdated;
_webView = FindViewById<WebView>(Resource.Id.webview);
_click = FindViewById<RelativeLayout>(Resource.Id.clickLayout);
_text = FindViewById<ImageView>(Resource.Id.txtBubble);
string fileName = "file:///android_asset/Content/southparkidle.gif";
_webView.LoadDataWithBaseURL(null, "<html><body style=\"width: 100%; height:100%; margin:0px; padding:0px;\">\n<img style=\"width: 100%; height:100%; margin:0px; padding:0px;\" id=\"selector\" src=\"" + fileName + "\"></body></html>", "text/html", "utf-8", null);
//_webView.LoadDataWithBaseURL(null, "<html><body style=\"width: 100%; height:100%; margin:0px; padding:0px;\">\n<img style=\"width: 100%; height:100%; margin:0px; padding:0px;\" id=\"selector\" src=\"https://media.giphy.com/media/1iUlZloL4DiH8HL2/giphy.gif\"></body></html>", "text/html", "utf-8", null);
_webView.Settings.JavaScriptEnabled = true;
_webView.SetBackgroundColor(Android.Graphics.Color.Transparent);
string rec = Android.Content.PM.PackageManager.FeatureMicrophone;
if (rec != "android.hardware.microphone")
{
var alert = new AlertDialog.Builder(this);
alert.SetTitle("You don't seem to have a microphone to record with");
alert.Show();
}
else
_click.Click += delegate
{
_text.Visibility = ViewStates.Invisible;
isRecording = !isRecording;
if (isRecording)
{
// create the intent and start the activity
_voiceIntent = new Intent(RecognizerIntent.ActionRecognizeSpeech);
_voiceIntent.PutExtra(RecognizerIntent.ExtraLanguageModel, RecognizerIntent.LanguageModelFreeForm);
// put a message on the modal dialog
_voiceIntent.PutExtra(RecognizerIntent.ExtraPrompt, "Speak now!");
// if there is more then 1.5s of silence, consider the speech over
_voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputCompleteSilenceLengthMillis, 2500);
_voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputPossiblyCompleteSilenceLengthMillis, 2500);
_voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputMinimumLengthMillis, 20000);
_voiceIntent.PutExtra(RecognizerIntent.ExtraMaxResults, 1);
// you can specify other languages recognised here, for example
// voiceIntent.PutExtra(RecognizerIntent.ExtraLanguage, Java.Util.Locale.German);
// if you wish it to recognise the default Locale language and German
// if you do use another locale, regional dialects may not be recognised very well
_voiceIntent.PutExtra(RecognizerIntent.ExtraLanguage, Java.Util.Locale.English);
StartActivityForResult(_voiceIntent, VOICE);
}
};
// ActionBar.Hide();
// base.OnCreate(bundle);
// SetContentView(Resource.Layout.QuestionView);
//_click = FindViewById<LinearLayout>(Resource.Id.clickLayout);
//string rec = Android.Content.PM.PackageManager.FeatureMicrophone;
//if (rec != "android.hardware.microphone")
//{
// var alert = new AlertDialog.Builder(this);
// alert.SetTitle("You don't seem to have a microphone to record with");
// alert.Show();
//}
//else
// _click.Click += delegate
// {
// isRecording = !isRecording;
// if (isRecording)
// {
// _voiceIntent = new Intent(RecognizerIntent.ActionRecognizeSpeech);
// _voiceIntent.PutExtra(RecognizerIntent.ExtraLanguageModel, RecognizerIntent.LanguageModelFreeForm);
// _voiceIntent.PutExtra(RecognizerIntent.ExtraPrompt, "Speak now!");
// _voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputCompleteSilenceLengthMillis, 3000);
// _voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputPossiblyCompleteSilenceLengthMillis, 3000);
// _voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputMinimumLengthMillis, 20000);
// _voiceIntent.PutExtra(RecognizerIntent.ExtraMaxResults, 1);
// _voiceIntent.PutExtra(RecognizerIntent.ExtraLanguage, Java.Util.Locale.English);
// StartActivityForResult(_voiceIntent, VOICE);
// }
// };
StartBeaconManager();
}
protected override async void OnActivityResult(int requestCode, Result resultVal, Intent data)
{
//var skypeButton = FindViewById<Button>(Resource.Id.skypeButton);
//var answerButton = FindViewById<Button>(Resource.Id.answerButton);
//var kyleButton = FindViewById<Button>(Resource.Id.kyleButton);
if (requestCode == VOICE)
{
if (resultVal == Result.Ok)
{
var matches = data.GetStringArrayListExtra(RecognizerIntent.ExtraResults);
if (matches.Count != 0)
{
string textInput = matches[0];
// limit the output to 500 characters
if (textInput.Length > 500)
textInput = textInput.Substring(0, 500);
var ditIsResult = textInput.ToLower();
if (stackOverflowFlow)
{
if (ditIsResult.Contains("yes"))
{
(ViewModel as QuestionViewModel).Question = _question;
}
else if (ditIsResult.Contains("no"))
{
Speak("Stay ignorant, you hillbilly!");
pizzaFlow = false;
_text.SetImageResource(Resource.Drawable.txtIgnorant);
_text.Visibility = ViewStates.Visible;
pizzaFlow = false;
}
stackOverflowFlow = false;
}
else if (skypeFlow)
{
if (ditIsResult.Contains("yes"))
{
Speak("Opening Skype Bot for you.");
skypeFlow = false;
(ViewModel as QuestionViewModel).GoToSkypeCommand.Execute(null);
skypeFlow = false;
}
else if (ditIsResult.Contains("no"))
{
Speak("Why did you ask then, you stupid asshole!");
skypeFlow = false;
_text.SetImageResource(Resource.Drawable.txtWhyAsk);
_text.Visibility = ViewStates.Visible;
skypeFlow = false;
}
else
{
Speak("Speak up, you mumbling idiot!");
_text.SetImageResource(Resource.Drawable.txtSpeakUp);
_text.Visibility = ViewStates.Visible;
}
}
else if (pizzaFlow)
{
if (ditIsResult.Contains("yes"))
{
Speak("I will get you a pepperoni pizza, buddy!");
pizzaFlow = false;
_text.SetImageResource(Resource.Drawable.txtPizzaYes);
_text.Visibility = ViewStates.Visible;
pizzaFlow = false;
}
else if (ditIsResult.Contains("no"))
{
Speak("More for me, you fat duck!");
pizzaFlow = false;
_text.SetImageResource(Resource.Drawable.txtPizzaNo);
_text.Visibility = ViewStates.Visible;
pizzaFlow = false;
}
else
{
Speak("Speak up, you mumbling idiot!");
_text.SetImageResource(Resource.Drawable.txtSpeakUp);
_text.Visibility = ViewStates.Visible;
}
}
else if ((ditIsResult.Contains("skype") && ditIsResult.Contains("open")) || (ditIsResult.Contains("skype") && ditIsResult.Contains("bot")) || ditIsResult.Contains("skype"))
{
//(ViewModel as QuestionViewModel).Question = textInput;
skypeFlow = true;
Speak("Do you want to see our Skype bot?");
_text.SetImageResource(Resource.Drawable.txtSkypeBot);
_text.Visibility = ViewStates.Visible;
}
else if ((ditIsResult.Contains("pizza")))
{
pizzaFlow = true;
Speak("Would you like a pizza?");
_text.SetImageResource(Resource.Drawable.txtPizza);
_text.Visibility = ViewStates.Visible;
}
else if (ditIsResult.Contains("alexa") || ditIsResult.Contains("alaxa"))
{
Speak("Bros before hos! That girl never listens to you and just plays Train whenever she wants.");
}
else
{
Speak("You want to search Stackoverflow for: " + textInput + "?");
_question = textInput;
_text.SetImageResource(Resource.Drawable.txtSearchSO);
_text.Visibility = ViewStates.Visible;
stackOverflowFlow = true;
}
}
else
Speak("No speech was recognised");
isRecording = false;
}
}
base.OnActivityResult(requestCode, resultVal, data);
}
private void OnAnswerUpdated(string answer)
{
if (answer == "NoResults!")
{
Speak("I am sorry, I could not find " + (ViewModel as QuestionViewModel).Question + ". Would you like a pizza?");
_text.SetImageResource(Resource.Drawable.txtPizza);
_text.Visibility = ViewStates.Visible;
pizzaFlow = true;
}
else
{
(ViewModel as QuestionViewModel).GoToAnswerCommand.Execute(null);
}
}
public void Speak(string text)
{
toSpeak = text;
if (speaker == null)
{
speaker = new TextToSpeech(this, this);
speaker.SetPitch(1.5f);
speaker.SetSpeechRate(1.5f);
speaker.SetLanguage(Java.Util.Locale.English);
}
else
{
var p = new Dictionary<string, string>();
speaker.Speak(toSpeak, QueueMode.Flush, p);
}
}
void TextToSpeech.IOnInitListener.OnInit(OperationResult status)
{
if (status.Equals(OperationResult.Success))
{
var p = new Dictionary<string, string>();
speaker.Speak(toSpeak, QueueMode.Flush, p);
}
}
public override void OnBackPressed()
{
speaker?.Stop();
base.OnBackPressed();
}
private void RangingBeaconsInRegion(object sender, RangeEventArgs e)
{
var allBeacons = new List<Beacon>();
if (e.Beacons.Count > 0)
{
foreach (var b in e.Beacons)
{
allBeacons.Add(b);
}
_beacons = allBeacons.OrderBy(b => b.Distance).ToList();
double distance = 9999999999d;
foreach (var beacon in _beacons)
{
var uuid = beacon.Id1.ToString().ToUpper();
var major = beacon.Id2.ToString().ToUpper();
var minor = beacon.Id3.ToString().ToUpper();
var distanceOfBeacon = beacon.Distance;
if (distanceOfBeacon < distance)
{
distance = distanceOfBeacon;
if (minor == "1" && major == "1" && uuid == "EBEFD083-70A2-47C8-9837-E7B5634DF524") // CSharp
{
if (distance < 3)
{
BeaconStats.ClosestArea = EArea.CSharp;
BeaconStats.ProximityToClosestArea = EProximity.OnTop;
}
else if (distance >= 3 && distance < 10)
{
BeaconStats.ClosestArea = EArea.CSharp;
BeaconStats.ProximityToClosestArea = EProximity.Close;
}
else if (distance >= 10 && distance < 20)
{
BeaconStats.ClosestArea = EArea.CSharp;
BeaconStats.ProximityToClosestArea = EProximity.Medium;
}
else if (distance >= 20 && distance < 50)
BeaconStats.ProximityToClosestArea = EProximity.Far;
else
BeaconStats.ProximityToClosestArea = EProximity.Unknown;
}
else // Java
{
if (distance < 1)
{
BeaconStats.ClosestArea = EArea.Java;
BeaconStats.ProximityToClosestArea = EProximity.OnTop;
}
}
}
}
}
}
private void StartBeaconManager()
{
_beaconManager = BeaconManager.GetInstanceForApplication(this);
var iBeaconParser = new BeaconParser();
iBeaconParser.SetBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24");
_beaconManager.BeaconParsers.Add(iBeaconParser);
_beaconManager.Bind(this);
_rangeNotifier.DidRangeBeaconsInRegionComplete += RangingBeaconsInRegion;
if (_beaconManager.IsBound(this))
{
_beaconManager.SetBackgroundMode(false);
}
}
void IBeaconConsumer.OnBeaconServiceConnect()
{
_beaconManager.SetForegroundBetweenScanPeriod(1000);
_beaconManager.SetRangeNotifier(_rangeNotifier);
//_tagRegion = new AltBeaconOrg.BoundBeacon.Region("Id", Identifier.Parse("EBEFD083-70A2-47C8-9837-E7B5634DF524"), null, null);
_emptyRegion = new AltBeaconOrg.BoundBeacon.Region("Id", null, null, null);
//_beaconManager.StartRangingBeaconsInRegion(_tagRegion);
_beaconManager.StartRangingBeaconsInRegion(_emptyRegion);
}
}
}
| |
using System;
using System.Collections;
using System.Data;
using System.Data.Common;
namespace SqlProfiler
{
/// <summary>
/// Generic <see cref="DbDataReader"/> wrapper - prototype only, not currently implemented or used
/// </summary>
public class ReaderWrapper : DbDataReader
{
/// <summary>
/// Position based indexer
/// </summary>
/// <param name="ordinal">Index</param>
/// <returns></returns>
public override object this[int ordinal] => throw new NotImplementedException();
/// <summary>
/// Name based indexer
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public override object this[string name] => throw new NotImplementedException();
/// <summary>
/// Wrapped <see cref="DbDataReader.Depth"/> property
/// </summary>
public override int Depth => throw new NotImplementedException();
/// <summary>
/// Wrapped <see cref="DbDataReader.FieldCount"/> property
/// </summary>
public override int FieldCount => throw new NotImplementedException();
/// <summary>
/// Wrapped <see cref="DbDataReader.HasRows"/> property
/// </summary>
public override bool HasRows => throw new NotImplementedException();
/// <summary>
/// Wrapped <see cref="DbDataReader.IsClosed"/> property
/// </summary>
public override bool IsClosed => throw new NotImplementedException();
/// <summary>
/// Wrapped <see cref="DbDataReader.RecordsAffected"/> property
/// </summary>
public override int RecordsAffected => throw new NotImplementedException();
#if NETFRAMEWORK
/// <summary>
/// Wrapped <see cref="DbDataReader.Close"/> method
/// </summary>
public override void Close()
{
throw new NotImplementedException();
}
#endif
/// <summary>
/// Wrapped <see cref="DbDataReader.GetBoolean(int)"/> method
/// </summary>
public override bool GetBoolean(int ordinal)
{
throw new NotImplementedException();
}
/// <summary>
/// Wrapped <see cref="DbDataReader.GetByte(int)"/> method
/// </summary>
public override byte GetByte(int ordinal)
{
throw new NotImplementedException();
}
/// <summary>
/// Wrapped <see cref="DbDataReader.GetBytes(int, long, byte[], int, int)"/> method
/// </summary>
public override long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length)
{
throw new NotImplementedException();
}
/// <summary>
/// Wrapped <see cref="DbDataReader.GetChar(int)"/> method
/// </summary>
public override char GetChar(int ordinal)
{
throw new NotImplementedException();
}
/// <summary>
/// Wrapped <see cref="DbDataReader.GetChars(int, long, char[], int, int)"/> method
/// </summary>
public override long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length)
{
throw new NotImplementedException();
}
/// <summary>
/// Wrapped <see cref="DbDataReader.GetDataTypeName(int)"/> method
/// </summary>
public override string GetDataTypeName(int ordinal)
{
throw new NotImplementedException();
}
/// <summary>
/// Wrapped <see cref="DbDataReader.GetDateTime(int)"/> method
/// </summary>
public override DateTime GetDateTime(int ordinal)
{
throw new NotImplementedException();
}
/// <summary>
/// Wrapped <see cref="DbDataReader.GetDecimal(int)"/> method
/// </summary>
public override decimal GetDecimal(int ordinal)
{
throw new NotImplementedException();
}
/// <summary>
/// Wrapped <see cref="DbDataReader.GetDouble(int)"/> method
/// </summary>
public override double GetDouble(int ordinal)
{
throw new NotImplementedException();
}
/// <summary>
/// Wrapped <see cref="DbDataReader.GetEnumerator"/> method
/// </summary>
public override IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
/// <summary>
/// Wrapped <see cref="DbDataReader.GetFieldType(int)"/> method
/// </summary>
public override Type GetFieldType(int ordinal)
{
throw new NotImplementedException();
}
/// <summary>
/// Wrapped <see cref="DbDataReader.GetFloat(int)"/> method
/// </summary>
public override float GetFloat(int ordinal)
{
throw new NotImplementedException();
}
/// <summary>
/// Wrapped <see cref="DbDataReader.GetGuid(int)"/> method
/// </summary>
public override Guid GetGuid(int ordinal)
{
throw new NotImplementedException();
}
/// <summary>
/// Wrapped <see cref="DbDataReader.GetInt16(int)"/> method
/// </summary>
public override short GetInt16(int ordinal)
{
throw new NotImplementedException();
}
/// <summary>
/// Wrapped <see cref="DbDataReader.GetInt32(int)"/> method
/// </summary>
public override int GetInt32(int ordinal)
{
throw new NotImplementedException();
}
/// <summary>
/// Wrapped <see cref="DbDataReader.GetInt64(int)"/> method
/// </summary>
public override long GetInt64(int ordinal)
{
throw new NotImplementedException();
}
/// <summary>
/// Wrapped <see cref="DbDataReader.GetName(int)"/> method
/// </summary>
public override string GetName(int ordinal)
{
throw new NotImplementedException();
}
/// <summary>
/// Wrapped <see cref="DbDataReader.GetOrdinal(string)"/> method
/// </summary>
public override int GetOrdinal(string name)
{
throw new NotImplementedException();
}
#if NETFRAMEWORK
/// <summary>
/// Wrapped <see cref="DbDataReader.GetSchemaTable"/> method
/// </summary>
public override DataTable GetSchemaTable()
{
throw new NotImplementedException();
}
#endif
/// <summary>
/// Wrapped <see cref="DbDataReader.GetString(int)"/> method
/// </summary>
public override string GetString(int ordinal)
{
throw new NotImplementedException();
}
/// <summary>
/// Wrapped <see cref="DbDataReader.GetValue(int)"/> method
/// </summary>
public override object GetValue(int ordinal)
{
throw new NotImplementedException();
}
/// <summary>
/// Wrapped <see cref="DbDataReader.GetValues(object[])"/> method
/// </summary>
public override int GetValues(object[] values)
{
throw new NotImplementedException();
}
/// <summary>
/// Wrapped <see cref="DbDataReader.IsDBNull(int)"/> method
/// </summary>
public override bool IsDBNull(int ordinal)
{
throw new NotImplementedException();
}
/// <summary>
/// Wrapped <see cref="DbDataReader.NextResult()"/> method
/// </summary>
public override bool NextResult()
{
throw new NotImplementedException();
}
/// <summary>
/// Wrapped <see cref="DbDataReader.Read()"/> method
/// </summary>
public override bool Read()
{
throw new NotImplementedException();
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Binary
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Binary.Metadata;
using Apache.Ignite.Core.Impl.Binary.Structure;
using Apache.Ignite.Core.Impl.Common;
/// <summary>
/// Binary writer implementation.
/// </summary>
internal class BinaryWriter : IBinaryWriter, IBinaryRawWriter
{
/** Marshaller. */
private readonly Marshaller _marsh;
/** Stream. */
private readonly IBinaryStream _stream;
/** Builder (used only during build). */
private BinaryObjectBuilder _builder;
/** Handles. */
private BinaryHandleDictionary<object, long> _hnds;
/** Metadatas collected during this write session. */
private IDictionary<int, BinaryType> _metas;
/** Current stack frame. */
private Frame _frame;
/** Whether we are currently detaching an object. */
private bool _detaching;
/** Schema holder. */
private readonly BinaryObjectSchemaHolder _schema = BinaryObjectSchemaHolder.Current;
/// <summary>
/// Gets the marshaller.
/// </summary>
internal Marshaller Marshaller
{
get { return _marsh; }
}
/// <summary>
/// Write named boolean value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Boolean value.</param>
public void WriteBoolean(string fieldName, bool val)
{
WriteFieldId(fieldName, BinaryUtils.TypeBool);
WriteBooleanField(val);
}
/// <summary>
/// Writes the boolean field.
/// </summary>
/// <param name="val">if set to <c>true</c> [value].</param>
internal void WriteBooleanField(bool val)
{
_stream.WriteByte(BinaryUtils.TypeBool);
_stream.WriteBool(val);
}
/// <summary>
/// Write boolean value.
/// </summary>
/// <param name="val">Boolean value.</param>
public void WriteBoolean(bool val)
{
_stream.WriteBool(val);
}
/// <summary>
/// Write named boolean array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Boolean array.</param>
public void WriteBooleanArray(string fieldName, bool[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayBool);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayBool);
BinaryUtils.WriteBooleanArray(val, _stream);
}
}
/// <summary>
/// Write boolean array.
/// </summary>
/// <param name="val">Boolean array.</param>
public void WriteBooleanArray(bool[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayBool);
BinaryUtils.WriteBooleanArray(val, _stream);
}
}
/// <summary>
/// Write named byte value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Byte value.</param>
public void WriteByte(string fieldName, byte val)
{
WriteFieldId(fieldName, BinaryUtils.TypeByte);
WriteByteField(val);
}
/// <summary>
/// Write byte field value.
/// </summary>
/// <param name="val">Byte value.</param>
internal void WriteByteField(byte val)
{
_stream.WriteByte(BinaryUtils.TypeByte);
_stream.WriteByte(val);
}
/// <summary>
/// Write byte value.
/// </summary>
/// <param name="val">Byte value.</param>
public void WriteByte(byte val)
{
_stream.WriteByte(val);
}
/// <summary>
/// Write named byte array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Byte array.</param>
public void WriteByteArray(string fieldName, byte[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayByte);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayByte);
BinaryUtils.WriteByteArray(val, _stream);
}
}
/// <summary>
/// Write byte array.
/// </summary>
/// <param name="val">Byte array.</param>
public void WriteByteArray(byte[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayByte);
BinaryUtils.WriteByteArray(val, _stream);
}
}
/// <summary>
/// Write named short value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Short value.</param>
public void WriteShort(string fieldName, short val)
{
WriteFieldId(fieldName, BinaryUtils.TypeShort);
WriteShortField(val);
}
/// <summary>
/// Write short field value.
/// </summary>
/// <param name="val">Short value.</param>
internal void WriteShortField(short val)
{
_stream.WriteByte(BinaryUtils.TypeShort);
_stream.WriteShort(val);
}
/// <summary>
/// Write short value.
/// </summary>
/// <param name="val">Short value.</param>
public void WriteShort(short val)
{
_stream.WriteShort(val);
}
/// <summary>
/// Write named short array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Short array.</param>
public void WriteShortArray(string fieldName, short[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayShort);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayShort);
BinaryUtils.WriteShortArray(val, _stream);
}
}
/// <summary>
/// Write short array.
/// </summary>
/// <param name="val">Short array.</param>
public void WriteShortArray(short[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayShort);
BinaryUtils.WriteShortArray(val, _stream);
}
}
/// <summary>
/// Write named char value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Char value.</param>
public void WriteChar(string fieldName, char val)
{
WriteFieldId(fieldName, BinaryUtils.TypeChar);
WriteCharField(val);
}
/// <summary>
/// Write char field value.
/// </summary>
/// <param name="val">Char value.</param>
internal void WriteCharField(char val)
{
_stream.WriteByte(BinaryUtils.TypeChar);
_stream.WriteChar(val);
}
/// <summary>
/// Write char value.
/// </summary>
/// <param name="val">Char value.</param>
public void WriteChar(char val)
{
_stream.WriteChar(val);
}
/// <summary>
/// Write named char array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Char array.</param>
public void WriteCharArray(string fieldName, char[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayChar);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayChar);
BinaryUtils.WriteCharArray(val, _stream);
}
}
/// <summary>
/// Write char array.
/// </summary>
/// <param name="val">Char array.</param>
public void WriteCharArray(char[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayChar);
BinaryUtils.WriteCharArray(val, _stream);
}
}
/// <summary>
/// Write named int value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Int value.</param>
public void WriteInt(string fieldName, int val)
{
WriteFieldId(fieldName, BinaryUtils.TypeInt);
WriteIntField(val);
}
/// <summary>
/// Writes the int field.
/// </summary>
/// <param name="val">The value.</param>
internal void WriteIntField(int val)
{
_stream.WriteByte(BinaryUtils.TypeInt);
_stream.WriteInt(val);
}
/// <summary>
/// Write int value.
/// </summary>
/// <param name="val">Int value.</param>
public void WriteInt(int val)
{
_stream.WriteInt(val);
}
/// <summary>
/// Write named int array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Int array.</param>
public void WriteIntArray(string fieldName, int[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayInt);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayInt);
BinaryUtils.WriteIntArray(val, _stream);
}
}
/// <summary>
/// Write int array.
/// </summary>
/// <param name="val">Int array.</param>
public void WriteIntArray(int[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayInt);
BinaryUtils.WriteIntArray(val, _stream);
}
}
/// <summary>
/// Write named long value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Long value.</param>
public void WriteLong(string fieldName, long val)
{
WriteFieldId(fieldName, BinaryUtils.TypeLong);
WriteLongField(val);
}
/// <summary>
/// Writes the long field.
/// </summary>
/// <param name="val">The value.</param>
internal void WriteLongField(long val)
{
_stream.WriteByte(BinaryUtils.TypeLong);
_stream.WriteLong(val);
}
/// <summary>
/// Write long value.
/// </summary>
/// <param name="val">Long value.</param>
public void WriteLong(long val)
{
_stream.WriteLong(val);
}
/// <summary>
/// Write named long array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Long array.</param>
public void WriteLongArray(string fieldName, long[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayLong);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayLong);
BinaryUtils.WriteLongArray(val, _stream);
}
}
/// <summary>
/// Write long array.
/// </summary>
/// <param name="val">Long array.</param>
public void WriteLongArray(long[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayLong);
BinaryUtils.WriteLongArray(val, _stream);
}
}
/// <summary>
/// Write named float value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Float value.</param>
public void WriteFloat(string fieldName, float val)
{
WriteFieldId(fieldName, BinaryUtils.TypeFloat);
WriteFloatField(val);
}
/// <summary>
/// Writes the float field.
/// </summary>
/// <param name="val">The value.</param>
internal void WriteFloatField(float val)
{
_stream.WriteByte(BinaryUtils.TypeFloat);
_stream.WriteFloat(val);
}
/// <summary>
/// Write float value.
/// </summary>
/// <param name="val">Float value.</param>
public void WriteFloat(float val)
{
_stream.WriteFloat(val);
}
/// <summary>
/// Write named float array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Float array.</param>
public void WriteFloatArray(string fieldName, float[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayFloat);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayFloat);
BinaryUtils.WriteFloatArray(val, _stream);
}
}
/// <summary>
/// Write float array.
/// </summary>
/// <param name="val">Float array.</param>
public void WriteFloatArray(float[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayFloat);
BinaryUtils.WriteFloatArray(val, _stream);
}
}
/// <summary>
/// Write named double value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Double value.</param>
public void WriteDouble(string fieldName, double val)
{
WriteFieldId(fieldName, BinaryUtils.TypeDouble);
WriteDoubleField(val);
}
/// <summary>
/// Writes the double field.
/// </summary>
/// <param name="val">The value.</param>
internal void WriteDoubleField(double val)
{
_stream.WriteByte(BinaryUtils.TypeDouble);
_stream.WriteDouble(val);
}
/// <summary>
/// Write double value.
/// </summary>
/// <param name="val">Double value.</param>
public void WriteDouble(double val)
{
_stream.WriteDouble(val);
}
/// <summary>
/// Write named double array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Double array.</param>
public void WriteDoubleArray(string fieldName, double[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayDouble);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayDouble);
BinaryUtils.WriteDoubleArray(val, _stream);
}
}
/// <summary>
/// Write double array.
/// </summary>
/// <param name="val">Double array.</param>
public void WriteDoubleArray(double[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayDouble);
BinaryUtils.WriteDoubleArray(val, _stream);
}
}
/// <summary>
/// Write named decimal value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Decimal value.</param>
public void WriteDecimal(string fieldName, decimal? val)
{
WriteFieldId(fieldName, BinaryUtils.TypeDecimal);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeDecimal);
BinaryUtils.WriteDecimal(val.Value, _stream);
}
}
/// <summary>
/// Write decimal value.
/// </summary>
/// <param name="val">Decimal value.</param>
public void WriteDecimal(decimal? val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeDecimal);
BinaryUtils.WriteDecimal(val.Value, _stream);
}
}
/// <summary>
/// Write named decimal array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Decimal array.</param>
public void WriteDecimalArray(string fieldName, decimal?[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayDecimal);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayDecimal);
BinaryUtils.WriteDecimalArray(val, _stream);
}
}
/// <summary>
/// Write decimal array.
/// </summary>
/// <param name="val">Decimal array.</param>
public void WriteDecimalArray(decimal?[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayDecimal);
BinaryUtils.WriteDecimalArray(val, _stream);
}
}
/// <summary>
/// Write named date value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Date value.</param>
public void WriteTimestamp(string fieldName, DateTime? val)
{
WriteFieldId(fieldName, BinaryUtils.TypeTimestamp);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeTimestamp);
BinaryUtils.WriteTimestamp(val.Value, _stream);
}
}
/// <summary>
/// Write date value.
/// </summary>
/// <param name="val">Date value.</param>
public void WriteTimestamp(DateTime? val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeTimestamp);
BinaryUtils.WriteTimestamp(val.Value, _stream);
}
}
/// <summary>
/// Write named date array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Date array.</param>
public void WriteTimestampArray(string fieldName, DateTime?[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeTimestamp);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayTimestamp);
BinaryUtils.WriteTimestampArray(val, _stream);
}
}
/// <summary>
/// Write date array.
/// </summary>
/// <param name="val">Date array.</param>
public void WriteTimestampArray(DateTime?[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayTimestamp);
BinaryUtils.WriteTimestampArray(val, _stream);
}
}
/// <summary>
/// Write named string value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">String value.</param>
public void WriteString(string fieldName, string val)
{
WriteFieldId(fieldName, BinaryUtils.TypeString);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeString);
BinaryUtils.WriteString(val, _stream);
}
}
/// <summary>
/// Write string value.
/// </summary>
/// <param name="val">String value.</param>
public void WriteString(string val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeString);
BinaryUtils.WriteString(val, _stream);
}
}
/// <summary>
/// Write named string array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">String array.</param>
public void WriteStringArray(string fieldName, string[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayString);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayString);
BinaryUtils.WriteStringArray(val, _stream);
}
}
/// <summary>
/// Write string array.
/// </summary>
/// <param name="val">String array.</param>
public void WriteStringArray(string[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayString);
BinaryUtils.WriteStringArray(val, _stream);
}
}
/// <summary>
/// Write named GUID value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">GUID value.</param>
public void WriteGuid(string fieldName, Guid? val)
{
WriteFieldId(fieldName, BinaryUtils.TypeGuid);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeGuid);
BinaryUtils.WriteGuid(val.Value, _stream);
}
}
/// <summary>
/// Write GUID value.
/// </summary>
/// <param name="val">GUID value.</param>
public void WriteGuid(Guid? val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeGuid);
BinaryUtils.WriteGuid(val.Value, _stream);
}
}
/// <summary>
/// Write named GUID array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">GUID array.</param>
public void WriteGuidArray(string fieldName, Guid?[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayGuid);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayGuid);
BinaryUtils.WriteGuidArray(val, _stream);
}
}
/// <summary>
/// Write GUID array.
/// </summary>
/// <param name="val">GUID array.</param>
public void WriteGuidArray(Guid?[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayGuid);
BinaryUtils.WriteGuidArray(val, _stream);
}
}
/// <summary>
/// Write named enum value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Enum value.</param>
public void WriteEnum<T>(string fieldName, T val)
{
WriteFieldId(fieldName, BinaryUtils.TypeEnum);
WriteEnum(val);
}
/// <summary>
/// Write enum value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="val">Enum value.</param>
public void WriteEnum<T>(T val)
{
// ReSharper disable once CompareNonConstrainedGenericWithNull
if (val == null)
WriteNullField();
else
{
var desc = _marsh.GetDescriptor(val.GetType());
var metaHnd = _marsh.GetBinaryTypeHandler(desc);
_stream.WriteByte(BinaryUtils.TypeEnum);
BinaryUtils.WriteEnum(this, val);
SaveMetadata(desc, metaHnd.OnObjectWriteFinished());
}
}
/// <summary>
/// Write named enum array.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Enum array.</param>
public void WriteEnumArray<T>(string fieldName, T[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayEnum);
WriteEnumArray(val);
}
/// <summary>
/// Write enum array.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="val">Enum array.</param>
public void WriteEnumArray<T>(T[] val)
{
WriteEnumArrayInternal(val, null);
}
/// <summary>
/// Writes the enum array.
/// </summary>
/// <param name="val">The value.</param>
/// <param name="elementTypeId">The element type id.</param>
public void WriteEnumArrayInternal(Array val, int? elementTypeId)
{
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayEnum);
BinaryUtils.WriteArray(val, this, elementTypeId);
}
}
/// <summary>
/// Write named object value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Object value.</param>
public void WriteObject<T>(string fieldName, T val)
{
WriteFieldId(fieldName, BinaryUtils.TypeObject);
// ReSharper disable once CompareNonConstrainedGenericWithNull
if (val == null)
WriteNullField();
else
Write(val);
}
/// <summary>
/// Write object value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="val">Object value.</param>
public void WriteObject<T>(T val)
{
Write(val);
}
/// <summary>
/// Write named object array.
/// </summary>
/// <typeparam name="T">Element type.</typeparam>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Object array.</param>
public void WriteArray<T>(string fieldName, T[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArray);
WriteArray(val);
}
/// <summary>
/// Write object array.
/// </summary>
/// <typeparam name="T">Element type.</typeparam>
/// <param name="val">Object array.</param>
public void WriteArray<T>(T[] val)
{
WriteArrayInternal(val);
}
/// <summary>
/// Write object array.
/// </summary>
/// <param name="val">Object array.</param>
public void WriteArrayInternal(Array val)
{
if (val == null)
WriteNullRawField();
else
{
if (WriteHandle(_stream.Position, val))
return;
_stream.WriteByte(BinaryUtils.TypeArray);
BinaryUtils.WriteArray(val, this);
}
}
/// <summary>
/// Write named collection.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Collection.</param>
public void WriteCollection(string fieldName, ICollection val)
{
WriteFieldId(fieldName, BinaryUtils.TypeCollection);
WriteCollection(val);
}
/// <summary>
/// Write collection.
/// </summary>
/// <param name="val">Collection.</param>
public void WriteCollection(ICollection val)
{
if (val == null)
WriteNullField();
else
{
if (WriteHandle(_stream.Position, val))
return;
WriteByte(BinaryUtils.TypeCollection);
BinaryUtils.WriteCollection(val, this);
}
}
/// <summary>
/// Write named dictionary.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Dictionary.</param>
public void WriteDictionary(string fieldName, IDictionary val)
{
WriteFieldId(fieldName, BinaryUtils.TypeDictionary);
WriteDictionary(val);
}
/// <summary>
/// Write dictionary.
/// </summary>
/// <param name="val">Dictionary.</param>
public void WriteDictionary(IDictionary val)
{
if (val == null)
WriteNullField();
else
{
if (WriteHandle(_stream.Position, val))
return;
WriteByte(BinaryUtils.TypeDictionary);
BinaryUtils.WriteDictionary(val, this);
}
}
/// <summary>
/// Write NULL field.
/// </summary>
private void WriteNullField()
{
_stream.WriteByte(BinaryUtils.HdrNull);
}
/// <summary>
/// Write NULL raw field.
/// </summary>
private void WriteNullRawField()
{
_stream.WriteByte(BinaryUtils.HdrNull);
}
/// <summary>
/// Get raw writer.
/// </summary>
/// <returns>
/// Raw writer.
/// </returns>
public IBinaryRawWriter GetRawWriter()
{
if (_frame.RawPos == 0)
_frame.RawPos = _stream.Position;
return this;
}
/// <summary>
/// Set new builder.
/// </summary>
/// <param name="builder">Builder.</param>
/// <returns>Previous builder.</returns>
internal BinaryObjectBuilder SetBuilder(BinaryObjectBuilder builder)
{
BinaryObjectBuilder ret = _builder;
_builder = builder;
return ret;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="marsh">Marshaller.</param>
/// <param name="stream">Stream.</param>
internal BinaryWriter(Marshaller marsh, IBinaryStream stream)
{
_marsh = marsh;
_stream = stream;
}
/// <summary>
/// Write object.
/// </summary>
/// <param name="obj">Object.</param>
public void Write<T>(T obj)
{
// Handle special case for null.
// ReSharper disable once CompareNonConstrainedGenericWithNull
if (obj == null)
{
_stream.WriteByte(BinaryUtils.HdrNull);
return;
}
// We use GetType() of a real object instead of typeof(T) to take advantage of
// automatic Nullable'1 unwrapping.
Type type = obj.GetType();
// Handle common case when primitive is written.
if (type.IsPrimitive)
{
WritePrimitive(obj, type);
return;
}
// Handle enums.
if (type.IsEnum)
{
WriteEnum(obj);
return;
}
// Handle special case for builder.
if (WriteBuilderSpecials(obj))
return;
// Are we dealing with a well-known type?
var handler = BinarySystemHandlers.GetWriteHandler(type);
if (handler != null)
{
if (handler.SupportsHandles && WriteHandle(_stream.Position, obj))
return;
handler.Write(this, obj);
return;
}
// Suppose that we faced normal object and perform descriptor lookup.
var desc = _marsh.GetDescriptor(type);
// Writing normal object.
var pos = _stream.Position;
// Dealing with handles.
if (desc.Serializer.SupportsHandles && WriteHandle(pos, obj))
return;
// Skip header length as not everything is known now
_stream.Seek(BinaryObjectHeader.Size, SeekOrigin.Current);
// Write type name for unregistered types
if (!desc.IsRegistered)
WriteString(type.AssemblyQualifiedName);
var headerSize = _stream.Position - pos;
// Preserve old frame.
var oldFrame = _frame;
// Push new frame.
_frame.RawPos = 0;
_frame.Pos = pos;
_frame.Struct = new BinaryStructureTracker(desc, desc.WriterTypeStructure);
_frame.HasCustomTypeData = false;
var schemaIdx = _schema.PushSchema();
try
{
// Write object fields.
desc.Serializer.WriteBinary(obj, this);
var dataEnd = _stream.Position;
// Write schema
var schemaOffset = dataEnd - pos;
int schemaId;
var flags = desc.UserType
? BinaryObjectHeader.Flag.UserType
: BinaryObjectHeader.Flag.None;
if (_frame.HasCustomTypeData)
flags |= BinaryObjectHeader.Flag.CustomDotNetType;
if (Marshaller.CompactFooter && desc.UserType)
flags |= BinaryObjectHeader.Flag.CompactFooter;
var hasSchema = _schema.WriteSchema(_stream, schemaIdx, out schemaId, ref flags);
if (hasSchema)
{
flags |= BinaryObjectHeader.Flag.HasSchema;
// Calculate and write header.
if (_frame.RawPos > 0)
_stream.WriteInt(_frame.RawPos - pos); // raw offset is in the last 4 bytes
// Update schema in type descriptor
if (desc.Schema.Get(schemaId) == null)
desc.Schema.Add(schemaId, _schema.GetSchema(schemaIdx));
}
else
schemaOffset = headerSize;
if (_frame.RawPos > 0)
flags |= BinaryObjectHeader.Flag.HasRaw;
var len = _stream.Position - pos;
var comparer = BinaryUtils.GetEqualityComparer(desc);
var hashCode = comparer.GetHashCode(Stream, pos + BinaryObjectHeader.Size,
dataEnd - pos - BinaryObjectHeader.Size, _schema, schemaIdx, _marsh, desc);
var header = new BinaryObjectHeader(desc.IsRegistered ? desc.TypeId : BinaryUtils.TypeUnregistered,
hashCode, len, schemaId, schemaOffset, flags);
BinaryObjectHeader.Write(header, _stream, pos);
Stream.Seek(pos + len, SeekOrigin.Begin); // Seek to the end
}
finally
{
_schema.PopSchema(schemaIdx);
}
// Apply structure updates if any.
_frame.Struct.UpdateWriterStructure(this);
// Restore old frame.
_frame = oldFrame;
}
/// <summary>
/// Marks current object with a custom type data flag.
/// </summary>
public void SetCustomTypeDataFlag(bool hasCustomTypeData)
{
_frame.HasCustomTypeData = hasCustomTypeData;
}
/// <summary>
/// Write primitive type.
/// </summary>
/// <param name="val">Object.</param>
/// <param name="type">Type.</param>
private unsafe void WritePrimitive<T>(T val, Type type)
{
// .Net defines 14 primitive types. We support 12 - excluding IntPtr and UIntPtr.
// Types check sequence is designed to minimize comparisons for the most frequent types.
if (type == typeof(int))
WriteIntField(TypeCaster<int>.Cast(val));
else if (type == typeof(long))
WriteLongField(TypeCaster<long>.Cast(val));
else if (type == typeof(bool))
WriteBooleanField(TypeCaster<bool>.Cast(val));
else if (type == typeof(byte))
WriteByteField(TypeCaster<byte>.Cast(val));
else if (type == typeof(short))
WriteShortField(TypeCaster<short>.Cast(val));
else if (type == typeof(char))
WriteCharField(TypeCaster<char>.Cast(val));
else if (type == typeof(float))
WriteFloatField(TypeCaster<float>.Cast(val));
else if (type == typeof(double))
WriteDoubleField(TypeCaster<double>.Cast(val));
else if (type == typeof(sbyte))
{
var val0 = TypeCaster<sbyte>.Cast(val);
WriteByteField(*(byte*)&val0);
}
else if (type == typeof(ushort))
{
var val0 = TypeCaster<ushort>.Cast(val);
WriteShortField(*(short*) &val0);
}
else if (type == typeof(uint))
{
var val0 = TypeCaster<uint>.Cast(val);
WriteIntField(*(int*)&val0);
}
else if (type == typeof(ulong))
{
var val0 = TypeCaster<ulong>.Cast(val);
WriteLongField(*(long*)&val0);
}
else
throw BinaryUtils.GetUnsupportedTypeException(type, val);
}
/// <summary>
/// Try writing object as special builder type.
/// </summary>
/// <param name="obj">Object.</param>
/// <returns>True if object was written, false otherwise.</returns>
private bool WriteBuilderSpecials<T>(T obj)
{
if (_builder != null)
{
// Special case for binary object during build.
BinaryObject portObj = obj as BinaryObject;
if (portObj != null)
{
if (!WriteHandle(_stream.Position, portObj))
_builder.ProcessBinary(_stream, portObj);
return true;
}
// Special case for builder during build.
BinaryObjectBuilder portBuilder = obj as BinaryObjectBuilder;
if (portBuilder != null)
{
if (!WriteHandle(_stream.Position, portBuilder))
_builder.ProcessBuilder(_stream, portBuilder);
return true;
}
}
return false;
}
/// <summary>
/// Add handle to handles map.
/// </summary>
/// <param name="pos">Position in stream.</param>
/// <param name="obj">Object.</param>
/// <returns><c>true</c> if object was written as handle.</returns>
private bool WriteHandle(long pos, object obj)
{
if (_hnds == null)
{
// Cache absolute handle position.
_hnds = new BinaryHandleDictionary<object, long>(obj, pos, ReferenceEqualityComparer<object>.Instance);
return false;
}
long hndPos;
if (!_hnds.TryGetValue(obj, out hndPos))
{
// Cache absolute handle position.
_hnds.Add(obj, pos);
return false;
}
_stream.WriteByte(BinaryUtils.HdrHnd);
// Handle is written as difference between position before header and handle position.
_stream.WriteInt((int)(pos - hndPos));
return true;
}
/// <summary>
/// Perform action with detached semantics.
/// </summary>
/// <param name="a"></param>
internal void WithDetach(Action<BinaryWriter> a)
{
if (_detaching)
a(this);
else
{
_detaching = true;
BinaryHandleDictionary<object, long> oldHnds = _hnds;
_hnds = null;
try
{
a(this);
}
finally
{
_detaching = false;
if (oldHnds != null)
{
// Merge newly recorded handles with old ones and restore old on the stack.
// Otherwise we can use current handles right away.
if (_hnds != null)
oldHnds.Merge(_hnds);
_hnds = oldHnds;
}
}
}
}
/// <summary>
/// Stream.
/// </summary>
internal IBinaryStream Stream
{
get { return _stream; }
}
/// <summary>
/// Gets collected metadatas.
/// </summary>
/// <returns>Collected metadatas (if any).</returns>
internal ICollection<BinaryType> GetBinaryTypes()
{
return _metas == null ? null : _metas.Values;
}
/// <summary>
/// Write field ID.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="fieldTypeId">Field type ID.</param>
private void WriteFieldId(string fieldName, byte fieldTypeId)
{
if (_frame.RawPos != 0)
throw new BinaryObjectException("Cannot write named fields after raw data is written.");
var fieldId = _frame.Struct.GetFieldId(fieldName, fieldTypeId);
_schema.PushField(fieldId, _stream.Position - _frame.Pos);
}
/// <summary>
/// Saves metadata for this session.
/// </summary>
/// <param name="desc">The descriptor.</param>
/// <param name="fields">Fields metadata.</param>
internal void SaveMetadata(IBinaryTypeDescriptor desc, IDictionary<string, BinaryField> fields)
{
Debug.Assert(desc != null);
if (_metas == null)
{
_metas = new Dictionary<int, BinaryType>(1)
{
{desc.TypeId, new BinaryType(desc, fields)}
};
}
else
{
BinaryType meta;
if (_metas.TryGetValue(desc.TypeId, out meta))
meta.UpdateFields(fields);
else
_metas[desc.TypeId] = new BinaryType(desc, fields);
}
}
/// <summary>
/// Stores current writer stack frame.
/// </summary>
private struct Frame
{
/** Current object start position. */
public int Pos;
/** Current raw position. */
public int RawPos;
/** Current type structure tracker. */
public BinaryStructureTracker Struct;
/** Custom type data. */
public bool HasCustomTypeData;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
#if !CORECLR
namespace Microsoft.CodeAnalysis
{
internal sealed class FusionAssemblyIdentity
{
[Flags]
internal enum ASM_DISPLAYF
{
VERSION = 0x01,
CULTURE = 0x02,
PUBLIC_KEY_TOKEN = 0x04,
PUBLIC_KEY = 0x08,
CUSTOM = 0x10,
PROCESSORARCHITECTURE = 0x20,
LANGUAGEID = 0x40,
RETARGET = 0x80,
CONFIG_MASK = 0x100,
MVID = 0x200,
CONTENT_TYPE = 0x400,
FULL = VERSION | CULTURE | PUBLIC_KEY_TOKEN | RETARGET | PROCESSORARCHITECTURE | CONTENT_TYPE
}
internal enum PropertyId
{
PUBLIC_KEY = 0, // 0
PUBLIC_KEY_TOKEN, // 1
HASH_VALUE, // 2
NAME, // 3
MAJOR_VERSION, // 4
MINOR_VERSION, // 5
BUILD_NUMBER, // 6
REVISION_NUMBER, // 7
CULTURE, // 8
PROCESSOR_ID_ARRAY, // 9
OSINFO_ARRAY, // 10
HASH_ALGID, // 11
ALIAS, // 12
CODEBASE_URL, // 13
CODEBASE_LASTMOD, // 14
NULL_PUBLIC_KEY, // 15
NULL_PUBLIC_KEY_TOKEN, // 16
CUSTOM, // 17
NULL_CUSTOM, // 18
MVID, // 19
FILE_MAJOR_VERSION, // 20
FILE_MINOR_VERSION, // 21
FILE_BUILD_NUMBER, // 22
FILE_REVISION_NUMBER, // 23
RETARGET, // 24
SIGNATURE_BLOB, // 25
CONFIG_MASK, // 26
ARCHITECTURE, // 27
CONTENT_TYPE, // 28
MAX_PARAMS // 29
}
private static class CANOF
{
public const uint PARSE_DISPLAY_NAME = 0x1;
public const uint SET_DEFAULT_VALUES = 0x2;
}
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("CD193BC0-B4BC-11d2-9833-00C04FC31D2E")]
internal unsafe interface IAssemblyName
{
void SetProperty(PropertyId id, void* data, uint size);
[PreserveSig]
int GetProperty(PropertyId id, void* data, ref uint size);
[PreserveSig]
int Finalize();
[PreserveSig]
int GetDisplayName(byte* buffer, ref uint characterCount, ASM_DISPLAYF dwDisplayFlags);
[PreserveSig]
int __BindToObject(/*...*/);
[PreserveSig]
int __GetName(/*...*/);
[PreserveSig]
int GetVersion(out uint versionHi, out uint versionLow);
[PreserveSig]
int IsEqual(IAssemblyName pName, uint dwCmpFlags);
[PreserveSig]
int Clone(out IAssemblyName pName);
}
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("7c23ff90-33af-11d3-95da-00a024a85b51")]
internal interface IApplicationContext
{
}
// NOTE: The CLR caches assembly identities, but doesn't do so in a threadsafe manner.
// Wrap all calls to this with a lock.
private static object s_assemblyIdentityGate = new object();
private static int CreateAssemblyNameObject(out IAssemblyName ppEnum, string szAssemblyName, uint dwFlags, IntPtr pvReserved)
{
lock (s_assemblyIdentityGate)
{
return RealCreateAssemblyNameObject(out ppEnum, szAssemblyName, dwFlags, pvReserved);
}
}
[DllImport("clr", EntryPoint = "CreateAssemblyNameObject", CharSet = CharSet.Unicode, PreserveSig = true)]
private static extern int RealCreateAssemblyNameObject(out IAssemblyName ppEnum, [MarshalAs(UnmanagedType.LPWStr)]string szAssemblyName, uint dwFlags, IntPtr pvReserved);
private const int ERROR_INSUFFICIENT_BUFFER = unchecked((int)0x8007007A);
private const int FUSION_E_INVALID_NAME = unchecked((int)0x80131047);
internal static unsafe string GetDisplayName(IAssemblyName nameObject, ASM_DISPLAYF displayFlags)
{
int hr;
uint characterCountIncludingTerminator = 0;
hr = nameObject.GetDisplayName(null, ref characterCountIncludingTerminator, displayFlags);
if (hr == 0)
{
return string.Empty;
}
if (hr != ERROR_INSUFFICIENT_BUFFER)
{
throw Marshal.GetExceptionForHR(hr);
}
byte[] data = new byte[(int)characterCountIncludingTerminator * 2];
fixed (byte* p = data)
{
hr = nameObject.GetDisplayName(p, ref characterCountIncludingTerminator, displayFlags);
if (hr != 0)
{
throw Marshal.GetExceptionForHR(hr);
}
return Marshal.PtrToStringUni((IntPtr)p, (int)characterCountIncludingTerminator - 1);
}
}
internal static unsafe byte[] GetPropertyBytes(IAssemblyName nameObject, PropertyId propertyId)
{
int hr;
uint size = 0;
hr = nameObject.GetProperty(propertyId, null, ref size);
if (hr == 0)
{
return null;
}
if (hr != ERROR_INSUFFICIENT_BUFFER)
{
throw Marshal.GetExceptionForHR(hr);
}
byte[] data = new byte[(int)size];
fixed (byte* p = data)
{
hr = nameObject.GetProperty(propertyId, p, ref size);
if (hr != 0)
{
throw Marshal.GetExceptionForHR(hr);
}
}
return data;
}
internal static unsafe string GetPropertyString(IAssemblyName nameObject, PropertyId propertyId)
{
byte[] data = GetPropertyBytes(nameObject, propertyId);
if (data == null)
{
return null;
}
fixed (byte* p = data)
{
return Marshal.PtrToStringUni((IntPtr)p, (data.Length / 2) - 1);
}
}
internal static unsafe Version GetVersion(IAssemblyName nameObject)
{
uint hi, lo;
int hr = nameObject.GetVersion(out hi, out lo);
if (hr != 0)
{
Debug.Assert(hr == FUSION_E_INVALID_NAME);
return null;
}
return new Version((int)(hi >> 16), (int)(hi & 0xffff), (int)(lo >> 16), (int)(lo & 0xffff));
}
internal static unsafe uint? GetPropertyWord(IAssemblyName nameObject, PropertyId propertyId)
{
uint result;
uint size = sizeof(uint);
int hr = nameObject.GetProperty(propertyId, &result, ref size);
if (hr != 0)
{
throw Marshal.GetExceptionForHR(hr);
}
if (size == 0)
{
return null;
}
return result;
}
internal static string GetCulture(IAssemblyName nameObject)
{
return GetPropertyString(nameObject, PropertyId.CULTURE);
}
internal static ProcessorArchitecture GetProcessorArchitecture(IAssemblyName nameObject)
{
return (ProcessorArchitecture)(GetPropertyWord(nameObject, PropertyId.ARCHITECTURE) ?? 0);
}
/// <summary>
/// Creates <see cref="IAssemblyName"/> object by parsing given display name.
/// </summary>
internal static IAssemblyName ToAssemblyNameObject(string displayName)
{
// CLR doesn't handle \0 in the display name well:
if (displayName.IndexOf('\0') >= 0)
{
return null;
}
Debug.Assert(displayName != null);
IAssemblyName result;
int hr = CreateAssemblyNameObject(out result, displayName, CANOF.PARSE_DISPLAY_NAME, IntPtr.Zero);
if (hr != 0)
{
return null;
}
Debug.Assert(result != null);
return result;
}
/// <summary>
/// Selects the candidate assembly with the largest version number. Uses culture as a tie-breaker if it is provided.
/// All candidates are assumed to have the same name and must include versions and cultures.
/// </summary>
internal static IAssemblyName GetBestMatch(IEnumerable<IAssemblyName> candidates, string preferredCultureOpt)
{
IAssemblyName bestCandidate = null;
Version bestVersion = null;
string bestCulture = null;
foreach (var candidate in candidates)
{
if (bestCandidate != null)
{
Version candidateVersion = GetVersion(candidate);
Debug.Assert(candidateVersion != null);
if (bestVersion == null)
{
bestVersion = GetVersion(bestCandidate);
Debug.Assert(bestVersion != null);
}
int cmp = bestVersion.CompareTo(candidateVersion);
if (cmp == 0)
{
if (preferredCultureOpt != null)
{
string candidateCulture = GetCulture(candidate);
Debug.Assert(candidateCulture != null);
if (bestCulture == null)
{
bestCulture = GetCulture(candidate);
Debug.Assert(bestCulture != null);
}
// we have exactly the preferred culture or
// we have neutral culture and the best candidate's culture isn't the preferred one:
if (StringComparer.OrdinalIgnoreCase.Equals(candidateCulture, preferredCultureOpt) ||
candidateCulture.Length == 0 && !StringComparer.OrdinalIgnoreCase.Equals(bestCulture, preferredCultureOpt))
{
bestCandidate = candidate;
bestVersion = candidateVersion;
bestCulture = candidateCulture;
}
}
}
else if (cmp < 0)
{
bestCandidate = candidate;
bestVersion = candidateVersion;
}
}
else
{
bestCandidate = candidate;
}
}
return bestCandidate;
}
}
}
#endif // !CORECLR
| |
// Copyright 2018 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 Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.Util.Shopping.v201809;
using Google.Api.Ads.AdWords.v201809;
using System;
using System.Collections.Generic;
namespace Google.Api.Ads.AdWords.Examples.CSharp.v201809
{
/// <summary>
/// This code example adds a Smart Shopping campaign with an ad group and ad group ad.
/// </summary>
public class AddSmartShoppingAd : ExampleBase
{
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description
{
get
{
return "This code example adds a Smart Shopping campaign with an ad group and " +
"ad group ad.";
}
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args)
{
AddSmartShoppingAd codeExample = new AddSmartShoppingAd();
Console.WriteLine(codeExample.Description);
try
{
long merchantId = long.Parse("INSERT_MERCHANT_ID_HERE");
bool createDefaultPartition = false;
codeExample.Run(new AdWordsUser(), merchantId, createDefaultPartition);
}
catch (Exception e)
{
Console.WriteLine("An exception occurred while running this code example. {0}",
ExampleUtilities.FormatException(e));
}
}
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="user">The Google Ads user.</param>
/// <param name="merchantId">The Merchant Center ID for the new campaign.</param>
/// <param name="createDefaultPartition">If <c>true</c>, a default product partition for
/// all products will be created.</param>
public void Run(AdWordsUser user, long merchantId, bool createDefaultPartition)
{
Budget budget = CreateBudget(user);
Campaign campaign =
CreateSmartShoppingCampaign(user, budget.budgetId, merchantId);
AdGroup adGroup = CreateSmartShoppingAdGroup(user, campaign.id);
CreateSmartShoppingAd(user, adGroup.id);
if (createDefaultPartition)
{
CreateDefaultPartition(user, adGroup.id);
}
}
/// <summary>
/// Creates a non-shared budget for a Smart Shopping campaign. Smart Shopping campaigns
/// support only non-shared budgets.
/// </summary>
/// <param name="user">The Google Ads user.</param>
/// <returns>The newly created budget.</returns>
private Budget CreateBudget(AdWordsUser user)
{
using (BudgetService budgetService =
(BudgetService) user.GetService(AdWordsService.v201809.BudgetService))
{
// Create a budget.
Budget budget = new Budget()
{
name = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString(),
amount = new Money()
{
// This budget equals 50.00 units of your account's currency, e.g.,
// 50 USD if your currency is USD.
microAmount = 50_000_000L
},
deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD,
// Non-shared budgets are required for Smart Shopping campaigns.
isExplicitlyShared = false
};
// Create operation.
BudgetOperation budgetOperation = new BudgetOperation()
{
operand = budget,
@operator = Operator.ADD
};
// Add the budget.
Budget newBudget = budgetService.mutate(
new BudgetOperation[] { budgetOperation }).value[0];
Console.WriteLine($"Budget with name '{newBudget.name}' and ID " +
$"{newBudget.budgetId} was added.");
return newBudget;
}
}
/// <summary>
/// Creates a Smart Shopping campaign.
/// </summary>
/// <param name="user">The Google Ads user.</param>
/// <param name="budgetId">The budget ID.</param>
/// <param name="merchantId">The merchant center account ID.</param>
/// <returns>The newly created campaign.</returns>
private Campaign CreateSmartShoppingCampaign(AdWordsUser user, long budgetId,
long merchantId)
{
using (CampaignService campaignService =
(CampaignService) user.GetService(AdWordsService.v201809.CampaignService))
{
// Create a campaign with required and optional settings.
Campaign campaign = new Campaign()
{
name = "Smart Shopping campaign #" + ExampleUtilities.GetRandomString(),
// The advertisingChannelType is what makes this a Shopping campaign.
advertisingChannelType = AdvertisingChannelType.SHOPPING,
// Sets the advertisingChannelSubType to SHOPPING_GOAL_OPTIMIZED_ADS to
// make this a Smart Shopping campaign.
advertisingChannelSubType =
AdvertisingChannelSubType.SHOPPING_GOAL_OPTIMIZED_ADS,
// Recommendation: Set the campaign to PAUSED when creating it to stop
// the ads from immediately serving. Set to ENABLED once you've added
// targeting and the ads are ready to serve.
status = CampaignStatus.PAUSED,
// Set a budget.
budget = new Budget()
{
budgetId = budgetId
},
// Set bidding strategy. Only MAXIMIZE_CONVERSION_VALUE is supported.
biddingStrategyConfiguration = new BiddingStrategyConfiguration()
{
biddingStrategyType = BiddingStrategyType.MAXIMIZE_CONVERSION_VALUE
},
// All Shopping campaigns need a ShoppingSetting.
settings = new Setting[]
{
new ShoppingSetting()
{
salesCountry = "US",
merchantId = merchantId
}
}
};
// Create operation.
CampaignOperation campaignOperation = new CampaignOperation()
{
operand = campaign,
@operator = Operator.ADD
};
// Make the mutate request and retrieve the result.
Campaign newCampaign =
campaignService.mutate(new CampaignOperation[] { campaignOperation }).value[0];
// Display result.
Console.WriteLine($"Smart Shopping campaign with name '{newCampaign.name}' and " +
$"ID {newCampaign.id} was added.");
return newCampaign;
}
}
/// <summary>
/// Creates a Smart Shopping ad group by setting the ad group type to
/// SHOPPING_GOAL_OPTIMIZED_ADS.
/// </summary>
/// <param name="user">The Google Ads user.</param>
/// <param name="campaignId">The campaign ID.</param>
private AdGroup CreateSmartShoppingAdGroup(AdWordsUser user, long campaignId)
{
using (AdGroupService adGroupService =
(AdGroupService) user.GetService(AdWordsService.v201809.AdGroupService))
{
// Create ad group.
AdGroup adGroup = new AdGroup()
{
campaignId = campaignId,
name = "Smart Shopping ad group #" + ExampleUtilities.GetRandomString(),
// Set the ad group type to SHOPPING_GOAL_OPTIMIZED_ADS.
adGroupType = AdGroupType.SHOPPING_GOAL_OPTIMIZED_ADS
};
// Create operation.
AdGroupOperation adGroupOperation = new AdGroupOperation()
{
operand = adGroup,
@operator = Operator.ADD
};
// Make the mutate request.
AdGroup newAdGroup =
adGroupService.mutate(new AdGroupOperation[] { adGroupOperation }).value[0];
// Display result.
Console.WriteLine($"Smart Shopping ad group with name '{adGroup.name}' and " +
$"ID {adGroup.id} was added.");
return newAdGroup;
}
}
/// <summary>
/// Creates the smart shopping ad.
/// </summary>
/// <param name="user">The Google Ads user.</param>
/// <param name="adGroupId">The ad group ID.</param>
private void CreateSmartShoppingAd(AdWordsUser user, long adGroupId)
{
using (AdGroupAdService adGroupAdService =
(AdGroupAdService) user.GetService(AdWordsService.v201809.AdGroupAdService))
{
// Create ad group ad.
AdGroupAd adGroupAd = new AdGroupAd()
{
adGroupId = adGroupId,
// Create a Smart Shopping ad (Goal-optimized Shopping ad).
ad = new GoalOptimizedShoppingAd() { }
};
// Create operation.
AdGroupAdOperation adGroupAdOperation = new AdGroupAdOperation()
{
operand = adGroupAd,
@operator = Operator.ADD
};
// Make the mutate request.
AdGroupAd newAdGroupAd = adGroupAdService.mutate(
new AdGroupAdOperation[] { adGroupAdOperation }).value[0];
// Display result.
Console.WriteLine($"Smart Shopping ad with ID {newAdGroupAd.ad.id} was added.");
}
}
/// <summary>
/// Creates the default partition.
/// </summary>
/// <param name="user">The user.</param>
/// <param name="adGroupId">The ad group ID.</param>
private void CreateDefaultPartition(AdWordsUser user, long adGroupId)
{
// Create an ad group criterion for 'All products' using the ProductPartitionTree
// utility.
ProductPartitionTree productPartitionTree =
ProductPartitionTree.CreateAdGroupTree(adGroupId, new List<AdGroupCriterion>());
AdGroupCriterionOperation[] mutateOperations =
productPartitionTree.GetMutateOperations();
using (AdGroupCriterionService adGroupCriterionService =
(AdGroupCriterionService) user.GetService(
AdWordsService.v201809.AdGroupCriterionService))
{
AdGroupCriterionReturnValue adGroupCriterionResult =
adGroupCriterionService.mutate(mutateOperations);
// Display result.
foreach (AdGroupCriterion adGroupCriterion in adGroupCriterionResult.value)
{
Console.WriteLine(
$"Ad group criterion with ID {adGroupCriterion.criterion.id} in ad " +
$"group with ID {adGroupCriterion.adGroupId} was added.");
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using NwaDg.Web.Areas.HelpPage.ModelDescriptions;
using NwaDg.Web.Areas.HelpPage.Models;
namespace NwaDg.Web.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Linq;
using CppSharp.AST;
using CppSharp.AST.Extensions;
using CppSharp.Generators.CSharp;
using CppSharp.Passes;
using NUnit.Framework;
namespace CppSharp.Generator.Tests.AST
{
[TestFixture]
public class TestAST : ASTTestFixture
{
[OneTimeSetUp]
public void Init()
{
CppSharp.AST.Type.TypePrinterDelegate = type =>
{
PrimitiveType primitiveType;
return type.IsPrimitiveType(out primitiveType) ? primitiveType.ToString() : string.Empty;
};
ParseLibrary("AST.h", "ASTExtensions.h");
}
[OneTimeTearDown]
public void CleanUp()
{
ParserOptions.Dispose();
}
[Test]
public void TestASTParameter()
{
var func = AstContext.FindFunction("TestParameterProperties").FirstOrDefault();
Assert.IsNotNull(func);
var paramNames = new[] { "a", "b", "c" };
var paramTypes = new[]
{
new QualifiedType(new BuiltinType(PrimitiveType.Bool)),
new QualifiedType(
new PointerType()
{
Modifier = PointerType.TypeModifier.LVReference,
QualifiedPointee = new QualifiedType(
new BuiltinType(PrimitiveType.Short),
new TypeQualifiers { IsConst = true })
}),
new QualifiedType(
new PointerType
{
Modifier = PointerType.TypeModifier.Pointer,
QualifiedPointee = new QualifiedType(new BuiltinType(PrimitiveType.Int))
})
};
for (int i = 0; i < func.Parameters.Count; i++)
{
var param = func.Parameters[i];
Assert.AreEqual(paramNames[i], param.Name, "Parameter.Name");
Assert.AreEqual(paramTypes[i], param.QualifiedType, "Parameter.QualifiedType");
Assert.AreEqual(i, param.Index, "Parameter.Index");
}
Assert.IsTrue(func.Parameters[2].HasDefaultValue, "Parameter.HasDefaultValue");
}
[Test]
public void TestASTHelperMethods()
{
var @class = AstContext.FindClass("Math::Complex").FirstOrDefault();
Assert.IsNotNull(@class, "Couldn't find Math::Complex class.");
var plusOperator = @class.FindOperator(CXXOperatorKind.Plus).FirstOrDefault();
Assert.IsNotNull(plusOperator, "Couldn't find operator+ in Math::Complex class.");
var typedef = AstContext.FindTypedef("Math::Single").FirstOrDefault();
Assert.IsNotNull(typedef);
}
#region TestVisitor
class TestVisitor : IDeclVisitor<bool>
{
public bool VisitDeclaration(Declaration decl)
{
throw new System.NotImplementedException();
}
public bool VisitTranslationUnit(TranslationUnit unit)
{
throw new System.NotImplementedException();
}
public bool VisitClassDecl(Class @class)
{
throw new System.NotImplementedException();
}
public bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecialization specialization)
{
throw new NotImplementedException();
}
public bool VisitFieldDecl(Field field)
{
throw new System.NotImplementedException();
}
public bool VisitFunctionDecl(Function function)
{
throw new System.NotImplementedException();
}
public bool VisitMethodDecl(Method method)
{
return true;
}
public bool VisitParameterDecl(Parameter parameter)
{
throw new System.NotImplementedException();
}
public bool VisitTypedefDecl(TypedefDecl typedef)
{
throw new System.NotImplementedException();
}
public bool VisitTypeAliasDecl(TypeAlias typeAlias)
{
throw new NotImplementedException();
}
public bool VisitEnumDecl(Enumeration @enum)
{
throw new System.NotImplementedException();
}
public bool VisitEnumItemDecl(Enumeration.Item item)
{
throw new NotImplementedException();
}
public bool VisitVariableDecl(Variable variable)
{
throw new System.NotImplementedException();
}
public bool VisitClassTemplateDecl(ClassTemplate template)
{
throw new System.NotImplementedException();
}
public bool VisitFunctionTemplateDecl(FunctionTemplate template)
{
throw new System.NotImplementedException();
}
public bool VisitMacroDefinition(MacroDefinition macro)
{
throw new System.NotImplementedException();
}
public bool VisitNamespace(Namespace @namespace)
{
throw new System.NotImplementedException();
}
public bool VisitEvent(Event @event)
{
throw new System.NotImplementedException();
}
public bool VisitProperty(Property property)
{
throw new System.NotImplementedException();
}
public bool VisitFriend(Friend friend)
{
throw new System.NotImplementedException();
}
public bool VisitTemplateParameterDecl(TypeTemplateParameter templateParameter)
{
throw new NotImplementedException();
}
public bool VisitNonTypeTemplateParameterDecl(NonTypeTemplateParameter nonTypeTemplateParameter)
{
throw new NotImplementedException();
}
public bool VisitTemplateTemplateParameterDecl(TemplateTemplateParameter templateTemplateParameter)
{
throw new NotImplementedException();
}
public bool VisitTypeAliasTemplateDecl(TypeAliasTemplate typeAliasTemplate)
{
throw new NotImplementedException();
}
public bool VisitFunctionTemplateSpecializationDecl(FunctionTemplateSpecialization specialization)
{
throw new NotImplementedException();
}
public bool VisitVarTemplateDecl(VarTemplate template)
{
throw new NotImplementedException();
}
public bool VisitVarTemplateSpecializationDecl(VarTemplateSpecialization template)
{
throw new NotImplementedException();
}
public bool VisitTypedefNameDecl(TypedefNameDecl typedef)
{
throw new NotImplementedException();
}
}
#endregion
[Test]
public void TestASTVisitor()
{
var testVisitor = new TestVisitor();
var plusOperator = AstContext.TranslationUnits
.SelectMany(u => u.Namespaces.Where(n => n.Name == "Math"))
.SelectMany(n => n.Classes.Where(c => c.Name == "Complex"))
.SelectMany(c => c.Methods.Where(m => m.OperatorKind == CXXOperatorKind.Plus))
.First();
Assert.IsTrue(plusOperator.Visit(testVisitor));
}
[Test]
public void TestASTEnumItemByName()
{
var @enum = AstContext.FindEnum("TestASTEnumItemByName").Single();
Assert.NotNull(@enum);
Assert.IsTrue(@enum.ItemsByName.ContainsKey("TestItemByName"));
}
[Test]
public void TestASTFunctionTemplates()
{
var @class = AstContext.FindClass("TestTemplateFunctions").FirstOrDefault();
Assert.IsNotNull(@class, "Couldn't find TestTemplateFunctions class.");
Assert.AreEqual(6, @class.Templates.Count);
var twoParamMethodTemplate = @class.Templates.OfType<FunctionTemplate>()
.FirstOrDefault(t => t.Name == "MethodTemplateWithTwoTypeParameter");
Assert.IsNotNull(twoParamMethodTemplate);
Assert.AreEqual(2, twoParamMethodTemplate.Parameters.Count);
Assert.AreEqual("T", twoParamMethodTemplate.Parameters[0].Name);
Assert.AreEqual("S", twoParamMethodTemplate.Parameters[1].Name);
var twoParamMethod = twoParamMethodTemplate.TemplatedFunction as Method;
Assert.IsNotNull(twoParamMethod);
Assert.IsInstanceOf<TemplateParameterType>(twoParamMethod.Parameters[0].Type);
Assert.IsInstanceOf<TemplateParameterType>(twoParamMethod.Parameters[1].Type);
Assert.AreEqual(twoParamMethodTemplate.Parameters[0],
((TemplateParameterType) twoParamMethod.Parameters[0].Type).Parameter);
Assert.AreEqual(twoParamMethodTemplate.Parameters[1],
((TemplateParameterType) twoParamMethod.Parameters[1].Type).Parameter);
Assert.AreEqual(0, ((TemplateParameterType) twoParamMethod.Parameters[0].Type).Index);
Assert.AreEqual(1, ((TemplateParameterType) twoParamMethod.Parameters[1].Type).Index);
}
[Test]
public void TestASTClassTemplates()
{
var template = AstContext.TranslationUnits
.SelectMany(u => u.Templates.OfType<ClassTemplate>())
.FirstOrDefault(t => t.Name == "TestTemplateClass");
Assert.IsNotNull(template, "Couldn't find TestTemplateClass class.");
Assert.AreEqual(1, template.Parameters.Count);
var templateTypeParameter = template.Parameters[0];
Assert.AreEqual("T", templateTypeParameter.Name);
var ctor = template.TemplatedClass.Constructors
.FirstOrDefault(c => c.Parameters.Count == 1 && c.Parameters[0].Name == "v");
Assert.IsNotNull(ctor);
var paramType = ctor.Parameters[0].Type as TemplateParameterType;
Assert.IsNotNull(paramType);
Assert.AreEqual(templateTypeParameter, paramType.Parameter);
Assert.AreEqual(5, template.Specializations.Count);
Assert.AreEqual(TemplateSpecializationKind.ExplicitInstantiationDefinition, template.Specializations[0].SpecializationKind);
Assert.AreEqual(TemplateSpecializationKind.ExplicitInstantiationDefinition, template.Specializations[3].SpecializationKind);
Assert.AreEqual(TemplateSpecializationKind.Undeclared, template.Specializations[4].SpecializationKind);
var typeDef = AstContext.FindTypedef("TestTemplateClassInt").FirstOrDefault();
Assert.IsNotNull(typeDef, "Couldn't find TestTemplateClassInt typedef.");
var integerInst = typeDef.Type as TemplateSpecializationType;
Assert.AreEqual(1, integerInst.Arguments.Count);
var intArgument = integerInst.Arguments[0];
Assert.AreEqual(new BuiltinType(PrimitiveType.Int), intArgument.Type.Type);
ClassTemplateSpecialization classTemplateSpecialization;
Assert.IsTrue(typeDef.Type.TryGetDeclaration(out classTemplateSpecialization));
Assert.AreSame(classTemplateSpecialization.TemplatedDecl.TemplatedClass, template.TemplatedClass);
}
[Test]
public void TestFindClassInNamespace()
{
Assert.IsNotNull(AstContext.FindClass("HiddenInNamespace").FirstOrDefault());
}
[Test]
public void TestLineNumber()
{
Assert.AreEqual(70, AstContext.FindClass("HiddenInNamespace").First().LineNumberStart);
}
[Test]
public void TestLineNumberOfFriend()
{
Assert.AreEqual(93, AstContext.FindFunction("operator+").First().LineNumberStart);
}
static string StripWindowsNewLines(string text)
{
return text.ReplaceLineBreaks(string.Empty);
}
[Test]
public void TestSignature()
{
Assert.AreEqual("void testSignature()", AstContext.FindFunction("testSignature").Single().Signature);
Assert.AreEqual("void testImpl(){}",
StripWindowsNewLines(AstContext.FindFunction("testImpl").Single().Signature));
Assert.AreEqual("void testConstSignature() const",
AstContext.FindClass("HasConstFunction").Single().FindMethod("testConstSignature").Signature);
Assert.AreEqual("void testConstSignatureWithTrailingMacro() const",
AstContext.FindClass("HasConstFunction").Single().FindMethod("testConstSignatureWithTrailingMacro").Signature);
// TODO: restore when the const of a return type is fixed properly
//Assert.AreEqual("const int& testConstRefSignature()", AstContext.FindClass("HasConstFunction").Single().FindMethod("testConstRefSignature").Signature);
//Assert.AreEqual("const int& testStaticConstRefSignature()", AstContext.FindClass("HasConstFunction").Single().FindMethod("testStaticConstRefSignature").Signature);
}
[Test]
public void TestAmbiguity()
{
new CheckAmbiguousFunctions { Context = Driver.Context }.VisitASTContext(AstContext);
Assert.IsTrue(AstContext.FindClass("HasAmbiguousFunctions").Single().FindMethod("ambiguous").IsAmbiguous);
}
[Test]
public void TestAtomics()
{
var type = AstContext.FindClass("Atomics").Single().Fields
.Find(f => f.Name == "AtomicInt").Type as BuiltinType;
Assert.IsTrue(type != null && type.IsPrimitiveType(PrimitiveType.Int));
}
[Test]
public void TestMacroLineNumber()
{
Assert.AreEqual(103, AstContext.FindClass("HasAmbiguousFunctions").First().Specifiers.Last().LineNumberStart);
}
[Test]
public void TestImplicitDeclaration()
{
Assert.IsTrue(AstContext.FindClass("ImplicitCtor").First().Constructors.First(
c => c.Parameters.Count == 0).IsImplicit);
}
[Test]
public void TestSpecializationArguments()
{
var classTemplate = AstContext.FindDecl<ClassTemplate>("TestSpecializationArguments").FirstOrDefault();
Assert.IsTrue(classTemplate.Specializations[0].Arguments[0].Type.Type.IsPrimitiveType(PrimitiveType.Int));
}
[Test]
public void TestFunctionInstantiatedFrom()
{
var classTemplate = AstContext.FindDecl<ClassTemplate>("TestSpecializationArguments").FirstOrDefault();
Assert.AreEqual(classTemplate.Specializations[0].Constructors.First(
c => !c.IsCopyConstructor && !c.IsMoveConstructor).InstantiatedFrom,
classTemplate.TemplatedClass.Constructors.First(c => !c.IsCopyConstructor && !c.IsMoveConstructor));
}
[Test]
public void TestComments()
{
var @class = AstContext.FindCompleteClass("TestComments");
var commentClass = @class.Comment.FullComment.CommentToString(CommentKind.BCPLSlash);
Assert.AreEqual(@"/// <summary>
/// <para>Hash set/map base class.</para>
/// <para>Note that to prevent extra memory use due to vtable pointer, %HashBase intentionally does not declare a virtual destructor</para>
/// <para>and therefore %HashBase pointers should never be used.</para>
/// </summary>".Replace("\r", string.Empty), commentClass.Replace("\r", string.Empty));
var method = @class.Methods.First(m => m.Name == "GetIOHandlerControlSequence");
var commentMethod = method.Comment.FullComment.CommentToString(CommentKind.BCPL);
Assert.AreEqual(@"// <summary>
// <para>Get the string that needs to be written to the debugger stdin file</para>
// <para>handle when a control character is typed.</para>
// </summary>
// <param name=""ch"">The character that was typed along with the control key</param>
// <returns>
// <para>The string that should be written into the file handle that is</para>
// <para>feeding the input stream for the debugger, or NULL if there is</para>
// <para>no string for this control key.</para>
// </returns>
// <remarks>
// <para>Some GUI programs will intercept "control + char" sequences and want</para>
// <para>to have them do what normally would happen when using a real</para>
// <para>terminal, so this function allows GUI programs to emulate this</para>
// <para>functionality.</para>
// </remarks>".Replace("\r", string.Empty), commentMethod.Replace("\r", string.Empty));
var methodTestDoxygen = @class.Methods.First(m => m.Name == "SBAttachInfo");
var commentMethodDoxygen = methodTestDoxygen.Comment.FullComment.CommentToString(CommentKind.BCPLSlash);
Assert.AreEqual(@"/// <summary>Attach to a process by name.</summary>
/// <param name=""path"">A full or partial name for the process to attach to.</param>
/// <param name=""wait_for"">
/// <para>If <c>false,</c> attach to an existing process whose name matches.</para>
/// <para>If <c>true,</c> then wait for the next process whose name matches.</para>
/// </param>
/// <remarks>
/// <para>This function implies that a future call to SBTarget::Attach(...)</para>
/// <para>will be synchronous.</para>
/// </remarks>".Replace("\r", string.Empty), commentMethodDoxygen.Replace("\r", string.Empty));
var methodDoxygenCustomTags = @class.Methods.First(m => m.Name == "glfwDestroyWindow");
new CleanCommentsPass { }.VisitFull(methodDoxygenCustomTags.Comment.FullComment);
var commentMethodDoxygenCustomTag = methodDoxygenCustomTags.Comment.FullComment.CommentToString(CommentKind.BCPLSlash);
Assert.AreEqual(@"/// <summary>Destroys the specified window and its context.</summary>
/// <param name=""window"">The window to destroy.</param>
/// <remarks>
/// <para>This function destroys the specified window and its context. On calling</para>
/// <para>this function, no further callbacks will be called for that window.</para>
/// <para>If the context of the specified window is current on the main thread, it is</para>
/// <para>detached before being destroyed.</para>
/// <para>The context of the specified window must not be current on any other</para>
/// <para>thread when this function is called.</para>
/// <para>This function must not be called from a callback.</para>
/// <para>This function must only be called from the main thread.</para>
/// <para>Added in version 3.0. Replaces `glfwCloseWindow`.</para>
/// </remarks>".Replace("\r", string.Empty), commentMethodDoxygenCustomTag.Replace("\r", string.Empty));
}
[Test]
public void TestCompletionOfClassTemplates()
{
var templates = AstContext.FindDecl<ClassTemplate>("ForwardedTemplate").ToList();
var template = templates.Single(t => t.DebugText.Replace("\r", string.Empty) ==
"template <typename T>\r\nclass ForwardedTemplate\r\n{\r\n}".Replace("\r", string.Empty));
Assert.IsFalse(template.IsIncomplete);
}
[Test]
public void TestOriginalNamesOfSpecializations()
{
var template = AstContext.FindDecl<ClassTemplate>("TestSpecializationArguments").First();
Assert.That(template.Specializations[0].Constructors.First().QualifiedName,
Is.Not.EqualTo(template.Specializations[1].Constructors.First().QualifiedName));
}
[Test]
public void TestPrintingConstPointerWithConstType()
{
var cppTypePrinter = new CppTypePrinter { PrintScopeKind = TypePrintScopeKind.Qualified };
var builtin = new BuiltinType(PrimitiveType.Char);
var pointee = new QualifiedType(builtin, new TypeQualifiers { IsConst = true });
var pointer = new QualifiedType(new PointerType(pointee), new TypeQualifiers { IsConst = true });
var type = pointer.Visit(cppTypePrinter);
Assert.That(type, Is.EqualTo("const char* const"));
}
[Test]
public void TestPrintingSpecializationWithConstValue()
{
var template = AstContext.FindDecl<ClassTemplate>("TestSpecializationArguments").First();
var cppTypePrinter = new CppTypePrinter { PrintScopeKind = TypePrintScopeKind.Qualified };
Assert.That(template.Specializations.Last().Visit(cppTypePrinter),
Is.EqualTo("TestSpecializationArguments<const TestASTEnumItemByName>"));
}
[Test]
public void TestLayoutBase()
{
var @class = AstContext.FindCompleteClass("TestComments");
Assert.That(@class.Layout.Bases.Count, Is.EqualTo(0));
}
[Test]
public void TestFunctionSpecifications()
{
var constExprNoExcept = AstContext.FindFunction("constExprNoExcept").First();
Assert.IsTrue(constExprNoExcept.IsConstExpr);
var functionType = (FunctionType) constExprNoExcept.FunctionType.Type;
Assert.That(functionType.ExceptionSpecType,
Is.EqualTo(ExceptionSpecType.BasicNoexcept));
var regular = AstContext.FindFunction("testSignature").First();
Assert.IsFalse(regular.IsConstExpr);
var regularFunctionType = (FunctionType) regular.FunctionType.Type;
Assert.That(regularFunctionType.ExceptionSpecType,
Is.EqualTo(ExceptionSpecType.None));
}
[Test]
public void TestFunctionSpecializationInfo()
{
var functionWithSpecInfo = AstContext.FindFunction(
"functionWithSpecInfo").First(f => !f.IsDependent);
var @float = new QualifiedType(new BuiltinType(PrimitiveType.Float));
Assert.That(functionWithSpecInfo.SpecializationInfo.Arguments.Count, Is.EqualTo(2));
foreach (var arg in functionWithSpecInfo.SpecializationInfo.Arguments)
Assert.That(arg.Type, Is.EqualTo(@float));
}
[Test]
public void TestVolatile()
{
var cppTypePrinter = new CppTypePrinter { PrintScopeKind = TypePrintScopeKind.Qualified };
var builtin = new BuiltinType(PrimitiveType.Char);
var pointee = new QualifiedType(builtin, new TypeQualifiers { IsConst = true, IsVolatile = true });
var type = pointee.Visit(cppTypePrinter);
Assert.That(type, Is.EqualTo("const volatile char"));
}
[Test]
public void TestFindFunctionInNamespace()
{
var function = AstContext.FindFunction("Math::function").FirstOrDefault();
Assert.That(function, Is.Not.Null);
}
[Test]
public void TestPrintNestedInSpecialization()
{
var template = AstContext.FindDecl<ClassTemplate>("TestTemplateClass").First();
var cppTypePrinter = new CppTypePrinter { PrintScopeKind = TypePrintScopeKind.Qualified };
Assert.That(template.Specializations[3].Classes[0].Visit(cppTypePrinter),
Is.EqualTo("TestTemplateClass<Math::Complex>::NestedInTemplate"));
}
[Test]
public void TestPrintQualifiedSpecialization()
{
var functionWithSpecializationArg = AstContext.FindFunction("functionWithSpecializationArg").First();
var cppTypePrinter = new CppTypePrinter { PrintScopeKind = TypePrintScopeKind.Qualified };
Assert.That(functionWithSpecializationArg.Parameters[0].Visit(cppTypePrinter),
Is.EqualTo("const TestTemplateClass<int>"));
}
[Test]
public void TestDependentNameType()
{
var template = AstContext.FindDecl<ClassTemplate>(
"TestSpecializationArguments").First();
var type = template.TemplatedClass.Fields[0].Type.Visit(
new CSharpTypePrinter(Driver.Context));
Assert.That($"{type}",
Is.EqualTo("global::Test.TestTemplateClass<T>.NestedInTemplate"));
}
[Test]
public void TestTemplateConstructorName()
{
new CleanInvalidDeclNamesPass { Context = Driver.Context }.VisitASTContext(AstContext);
var template = AstContext.FindClass("TestTemplateClass").First();
foreach (var constructor in template.Constructors)
Assert.That(constructor.Name, Is.EqualTo("TestTemplateClass<T>"));
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace SP.Cmd.Deploy
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate (object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
public static string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
public static string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
namespace FFmpegDotNet.Interop.Codecs
{
/// <summary>
/// Identify the syntax and semantics of the bitstream. The principle is roughly: two decoders with the same ID can decode the same streams, two encoders
/// with the same ID can encode compatible streams. There may be slight deviations from the principle due to implementation details.
/// </summary>
public enum AVCodecID
{
#region General Codecs
AV_CODEC_ID_NONE,
#endregion
#region Video Codecs
AV_CODEC_ID_MPEG1VIDEO,
/// <summary>
/// preferred ID for MPEG-1/2 video decoding.
/// </summary>
AV_CODEC_ID_MPEG2VIDEO,
AV_CODEC_ID_MPEG2VIDEO_XVMC,
AV_CODEC_ID_H261,
AV_CODEC_ID_H263,
AV_CODEC_ID_RV10,
AV_CODEC_ID_RV20,
AV_CODEC_ID_MJPEG,
AV_CODEC_ID_MJPEGB,
AV_CODEC_ID_LJPEG,
AV_CODEC_ID_SP5X,
AV_CODEC_ID_JPEGLS,
AV_CODEC_ID_MPEG4,
AV_CODEC_ID_RAWVIDEO,
AV_CODEC_ID_MSMPEG4V1,
AV_CODEC_ID_MSMPEG4V2,
AV_CODEC_ID_MSMPEG4V3,
AV_CODEC_ID_WMV1,
AV_CODEC_ID_WMV2,
AV_CODEC_ID_H263P,
AV_CODEC_ID_H263I,
AV_CODEC_ID_FLV1,
AV_CODEC_ID_SVQ1,
AV_CODEC_ID_SVQ3,
AV_CODEC_ID_DVVIDEO,
AV_CODEC_ID_HUFFYUV,
AV_CODEC_ID_CYUV,
AV_CODEC_ID_H264,
AV_CODEC_ID_INDEO3,
AV_CODEC_ID_VP3,
AV_CODEC_ID_THEORA,
AV_CODEC_ID_ASV1,
AV_CODEC_ID_ASV2,
AV_CODEC_ID_FFV1,
AV_CODEC_ID_4XM,
AV_CODEC_ID_VCR1,
AV_CODEC_ID_CLJR,
AV_CODEC_ID_MDEC,
AV_CODEC_ID_ROQ,
AV_CODEC_ID_INTERPLAY_VIDEO,
AV_CODEC_ID_XAN_WC3,
AV_CODEC_ID_XAN_WC4,
AV_CODEC_ID_RPZA,
AV_CODEC_ID_CINEPAK,
AV_CODEC_ID_WS_VQA,
AV_CODEC_ID_MSRLE,
AV_CODEC_ID_MSVIDEO1,
AV_CODEC_ID_IDCIN,
AV_CODEC_ID_8BPS,
AV_CODEC_ID_SMC,
AV_CODEC_ID_FLIC,
AV_CODEC_ID_TRUEMOTION1,
AV_CODEC_ID_VMDVIDEO,
AV_CODEC_ID_MSZH,
AV_CODEC_ID_ZLIB,
AV_CODEC_ID_QTRLE,
AV_CODEC_ID_TSCC,
AV_CODEC_ID_ULTI,
AV_CODEC_ID_QDRAW,
AV_CODEC_ID_VIXL,
AV_CODEC_ID_QPEG,
AV_CODEC_ID_PNG,
AV_CODEC_ID_PPM,
AV_CODEC_ID_PBM,
AV_CODEC_ID_PGM,
AV_CODEC_ID_PGMYUV,
AV_CODEC_ID_PAM,
AV_CODEC_ID_FFVHUFF,
AV_CODEC_ID_RV30,
AV_CODEC_ID_RV40,
AV_CODEC_ID_VC1,
AV_CODEC_ID_WMV3,
AV_CODEC_ID_LOCO,
AV_CODEC_ID_WNV1,
AV_CODEC_ID_AASC,
AV_CODEC_ID_INDEO2,
AV_CODEC_ID_FRAPS,
AV_CODEC_ID_TRUEMOTION2,
AV_CODEC_ID_BMP,
AV_CODEC_ID_CSCD,
AV_CODEC_ID_MMVIDEO,
AV_CODEC_ID_ZMBV,
AV_CODEC_ID_AVS,
AV_CODEC_ID_SMACKVIDEO,
AV_CODEC_ID_NUV,
AV_CODEC_ID_KMVC,
AV_CODEC_ID_FLASHSV,
AV_CODEC_ID_CAVS,
AV_CODEC_ID_JPEG2000,
AV_CODEC_ID_VMNC,
AV_CODEC_ID_VP5,
AV_CODEC_ID_VP6,
AV_CODEC_ID_VP6F,
AV_CODEC_ID_TARGA,
AV_CODEC_ID_DSICINVIDEO,
AV_CODEC_ID_TIERTEXSEQVIDEO,
AV_CODEC_ID_TIFF,
AV_CODEC_ID_GIF,
AV_CODEC_ID_DXA,
AV_CODEC_ID_DNXHD,
AV_CODEC_ID_THP,
AV_CODEC_ID_SGI,
AV_CODEC_ID_C93,
AV_CODEC_ID_BETHSOFTVID,
AV_CODEC_ID_PTX,
AV_CODEC_ID_TXD,
AV_CODEC_ID_VP6A,
AV_CODEC_ID_AMV,
AV_CODEC_ID_VB,
AV_CODEC_ID_PCX,
AV_CODEC_ID_SUNRAST,
AV_CODEC_ID_INDEO4,
AV_CODEC_ID_INDEO5,
AV_CODEC_ID_MIMIC,
AV_CODEC_ID_RL2,
AV_CODEC_ID_ESCAPE124,
AV_CODEC_ID_DIRAC,
AV_CODEC_ID_BFI,
AV_CODEC_ID_CMV,
AV_CODEC_ID_MOTIONPIXELS,
AV_CODEC_ID_TGV,
AV_CODEC_ID_TGQ,
AV_CODEC_ID_TQI,
AV_CODEC_ID_AURA,
AV_CODEC_ID_AURA2,
AV_CODEC_ID_V210X,
AV_CODEC_ID_TMV,
AV_CODEC_ID_V210,
AV_CODEC_ID_DPX,
AV_CODEC_ID_MAD,
AV_CODEC_ID_FRWU,
AV_CODEC_ID_FLASHSV2,
AV_CODEC_ID_CDGRAPHICS,
AV_CODEC_ID_R210,
AV_CODEC_ID_ANM,
AV_CODEC_ID_BINKVIDEO,
AV_CODEC_ID_IFF_ILBM,
AV_CODEC_ID_KGV1,
AV_CODEC_ID_YOP,
AV_CODEC_ID_VP8,
AV_CODEC_ID_PICTOR,
AV_CODEC_ID_ANSI,
AV_CODEC_ID_A64_MULTI,
AV_CODEC_ID_A64_MULTI5,
AV_CODEC_ID_R10K,
AV_CODEC_ID_MXPEG,
AV_CODEC_ID_LAGARITH,
AV_CODEC_ID_PRORES,
AV_CODEC_ID_JV,
AV_CODEC_ID_DFA,
AV_CODEC_ID_WMV3IMAGE,
AV_CODEC_ID_VC1IMAGE,
AV_CODEC_ID_UTVIDEO,
AV_CODEC_ID_BMV_VIDEO,
AV_CODEC_ID_VBLE,
AV_CODEC_ID_DXTORY,
AV_CODEC_ID_V410,
AV_CODEC_ID_XWD,
AV_CODEC_ID_CDXL,
AV_CODEC_ID_XBM,
AV_CODEC_ID_ZEROCODEC,
AV_CODEC_ID_MSS1,
AV_CODEC_ID_MSA1,
AV_CODEC_ID_TSCC2,
AV_CODEC_ID_MTS2,
AV_CODEC_ID_CLLC,
AV_CODEC_ID_MSS2,
AV_CODEC_ID_VP9,
AV_CODEC_ID_AIC,
AV_CODEC_ID_ESCAPE130,
AV_CODEC_ID_G2M,
AV_CODEC_ID_WEBP,
AV_CODEC_ID_HNM4_VIDEO,
AV_CODEC_ID_HEVC,
AV_CODEC_ID_FIC,
AV_CODEC_ID_ALIAS_PIX,
AV_CODEC_ID_BRENDER_PIX,
AV_CODEC_ID_PAF_VIDEO,
AV_CODEC_ID_EXR,
AV_CODEC_ID_VP7,
AV_CODEC_ID_SANM,
AV_CODEC_ID_SGIRLE,
AV_CODEC_ID_MVC1,
AV_CODEC_ID_MVC2,
AV_CODEC_ID_HQX,
AV_CODEC_ID_TDSC,
AV_CODEC_ID_HQ_HQA,
AV_CODEC_ID_HAP,
AV_CODEC_ID_DDS,
AV_CODEC_ID_DXV,
AV_CODEC_ID_SCREENPRESSO,
AV_CODEC_ID_RSCC,
AV_CODEC_ID_Y41P = 0x8000,
AV_CODEC_ID_AVRP,
AV_CODEC_ID_012V,
AV_CODEC_ID_AVUI,
AV_CODEC_ID_AYUV,
AV_CODEC_ID_TARGA_Y216,
AV_CODEC_ID_V308,
AV_CODEC_ID_V408,
AV_CODEC_ID_YUV4,
AV_CODEC_ID_AVRN,
AV_CODEC_ID_CPIA,
AV_CODEC_ID_XFACE,
AV_CODEC_ID_SNOW,
AV_CODEC_ID_SMVJPEG,
AV_CODEC_ID_APNG,
AV_CODEC_ID_DAALA,
AV_CODEC_ID_CFHD,
AV_CODEC_ID_TRUEMOTION2RT,
AV_CODEC_ID_M101,
AV_CODEC_ID_MAGICYUV,
AV_CODEC_ID_SHEERVIDEO,
AV_CODEC_ID_YLC,
#endregion
#region Various PCM Codecs
/// <summary>
/// A dummy id pointing at the start of audio codecs.
/// </summary>
AV_CODEC_ID_FIRST_AUDIO = 0x10000,
AV_CODEC_ID_PCM_S16LE = 0x10000,
AV_CODEC_ID_PCM_S16BE,
AV_CODEC_ID_PCM_U16LE,
AV_CODEC_ID_PCM_U16BE,
AV_CODEC_ID_PCM_S8,
AV_CODEC_ID_PCM_U8,
AV_CODEC_ID_PCM_MULAW,
AV_CODEC_ID_PCM_ALAW,
AV_CODEC_ID_PCM_S32LE,
AV_CODEC_ID_PCM_S32BE,
AV_CODEC_ID_PCM_U32LE,
AV_CODEC_ID_PCM_U32BE,
AV_CODEC_ID_PCM_S24LE,
AV_CODEC_ID_PCM_S24BE,
AV_CODEC_ID_PCM_U24LE,
AV_CODEC_ID_PCM_U24BE,
AV_CODEC_ID_PCM_S24DAUD,
AV_CODEC_ID_PCM_ZORK,
AV_CODEC_ID_PCM_S16LE_PLANAR,
AV_CODEC_ID_PCM_DVD,
AV_CODEC_ID_PCM_F32BE,
AV_CODEC_ID_PCM_F32LE,
AV_CODEC_ID_PCM_F64BE,
AV_CODEC_ID_PCM_F64LE,
AV_CODEC_ID_PCM_BLURAY,
AV_CODEC_ID_PCM_LXF,
AV_CODEC_ID_S302M,
AV_CODEC_ID_PCM_S8_PLANAR,
AV_CODEC_ID_PCM_S24LE_PLANAR,
AV_CODEC_ID_PCM_S32LE_PLANAR,
/// <summary>
/// A new PCM "codecs" should be added right below this line starting with an explicit value of for example 0x10800.
/// </summary>
AV_CODEC_ID_PCM_S16BE_PLANAR,
#endregion
#region Various ADPCM Codecs
AV_CODEC_ID_ADPCM_IMA_QT = 0x11000,
AV_CODEC_ID_ADPCM_IMA_WAV,
AV_CODEC_ID_ADPCM_IMA_DK3,
AV_CODEC_ID_ADPCM_IMA_DK4,
AV_CODEC_ID_ADPCM_IMA_WS,
AV_CODEC_ID_ADPCM_IMA_SMJPEG,
AV_CODEC_ID_ADPCM_MS,
AV_CODEC_ID_ADPCM_4XM,
AV_CODEC_ID_ADPCM_XA,
AV_CODEC_ID_ADPCM_ADX,
AV_CODEC_ID_ADPCM_EA,
AV_CODEC_ID_ADPCM_G726,
AV_CODEC_ID_ADPCM_CT,
AV_CODEC_ID_ADPCM_SWF,
AV_CODEC_ID_ADPCM_YAMAHA,
AV_CODEC_ID_ADPCM_SBPRO_4,
AV_CODEC_ID_ADPCM_SBPRO_3,
AV_CODEC_ID_ADPCM_SBPRO_2,
AV_CODEC_ID_ADPCM_THP,
AV_CODEC_ID_ADPCM_IMA_AMV,
AV_CODEC_ID_ADPCM_EA_R1,
AV_CODEC_ID_ADPCM_EA_R3,
AV_CODEC_ID_ADPCM_EA_R2,
AV_CODEC_ID_ADPCM_IMA_EA_SEAD,
AV_CODEC_ID_ADPCM_IMA_EA_EACS,
AV_CODEC_ID_ADPCM_EA_XAS,
AV_CODEC_ID_ADPCM_EA_MAXIS_XA,
AV_CODEC_ID_ADPCM_IMA_ISS,
AV_CODEC_ID_ADPCM_G722,
AV_CODEC_ID_ADPCM_IMA_APC,
AV_CODEC_ID_ADPCM_VIMA,
AV_CODEC_ID_VIMA = AV_CODEC_ID_ADPCM_VIMA,
AV_CODEC_ID_ADPCM_AFC = 0x11800,
AV_CODEC_ID_ADPCM_IMA_OKI,
AV_CODEC_ID_ADPCM_DTK,
AV_CODEC_ID_ADPCM_IMA_RAD,
AV_CODEC_ID_ADPCM_G726LE,
AV_CODEC_ID_ADPCM_THP_LE,
AV_CODEC_ID_ADPCM_PSX,
AV_CODEC_ID_ADPCM_AICA,
AV_CODEC_ID_ADPCM_IMA_DAT4,
AV_CODEC_ID_ADPCM_MTAF,
/// <summary>
/// AMR.
/// </summary>
AV_CODEC_ID_AMR_NB = 0x12000,
AV_CODEC_ID_AMR_WB,
/// <summary>
/// RealAudio codecs.
/// </summary>
AV_CODEC_ID_RA_144 = 0x13000,
AV_CODEC_ID_RA_288,
/// <summary>
/// Various DPCM codecs
/// </summary>
AV_CODEC_ID_ROQ_DPCM = 0x14000,
AV_CODEC_ID_INTERPLAY_DPCM,
AV_CODEC_ID_XAN_DPCM,
AV_CODEC_ID_SOL_DPCM,
AV_CODEC_ID_SDX2_DPCM = 0x14800,
#endregion
#region Audio Codecs
AV_CODEC_ID_MP2 = 0x15000,
/// <summary>
/// The preferred ID for decoding MPEG audio layer 1, 2 or 3.
/// </summary>
AV_CODEC_ID_MP3,
AV_CODEC_ID_AAC,
AV_CODEC_ID_AC3,
AV_CODEC_ID_DTS,
AV_CODEC_ID_VORBIS,
AV_CODEC_ID_DVAUDIO,
AV_CODEC_ID_WMAV1,
AV_CODEC_ID_WMAV2,
AV_CODEC_ID_MACE3,
AV_CODEC_ID_MACE6,
AV_CODEC_ID_VMDAUDIO,
AV_CODEC_ID_FLAC,
AV_CODEC_ID_MP3ADU,
AV_CODEC_ID_MP3ON4,
AV_CODEC_ID_SHORTEN,
AV_CODEC_ID_ALAC,
AV_CODEC_ID_WESTWOOD_SND1,
/// <summary>
/// As in Berlin toast format.
/// </summary>
AV_CODEC_ID_GSM,
AV_CODEC_ID_QDM2,
AV_CODEC_ID_COOK,
AV_CODEC_ID_TRUESPEECH,
AV_CODEC_ID_TTA,
AV_CODEC_ID_SMACKAUDIO,
AV_CODEC_ID_QCELP,
AV_CODEC_ID_WAVPACK,
AV_CODEC_ID_DSICINAUDIO,
AV_CODEC_ID_IMC,
AV_CODEC_ID_MUSEPACK7,
AV_CODEC_ID_MLP,
/// <summary>
/// As found in WAV.
/// </summary>
AV_CODEC_ID_GSM_MS,
AV_CODEC_ID_ATRAC3,
AV_CODEC_ID_VOXWARE,
AV_CODEC_ID_APE,
AV_CODEC_ID_NELLYMOSER,
AV_CODEC_ID_MUSEPACK8,
AV_CODEC_ID_SPEEX,
AV_CODEC_ID_WMAVOICE,
AV_CODEC_ID_WMAPRO,
AV_CODEC_ID_WMALOSSLESS,
AV_CODEC_ID_ATRAC3P,
AV_CODEC_ID_EAC3,
AV_CODEC_ID_SIPR,
AV_CODEC_ID_MP1,
AV_CODEC_ID_TWINVQ,
AV_CODEC_ID_TRUEHD,
AV_CODEC_ID_MP4ALS,
AV_CODEC_ID_ATRAC1,
AV_CODEC_ID_BINKAUDIO_RDFT,
AV_CODEC_ID_BINKAUDIO_DCT,
AV_CODEC_ID_AAC_LATM,
AV_CODEC_ID_QDMC,
AV_CODEC_ID_CELT,
AV_CODEC_ID_G723_1,
AV_CODEC_ID_G729,
AV_CODEC_ID_8SVX_EXP,
AV_CODEC_ID_8SVX_FIB,
AV_CODEC_ID_BMV_AUDIO,
AV_CODEC_ID_RALF,
AV_CODEC_ID_IAC,
AV_CODEC_ID_ILBC,
AV_CODEC_ID_OPUS,
AV_CODEC_ID_COMFORT_NOISE,
AV_CODEC_ID_TAK,
AV_CODEC_ID_METASOUND,
AV_CODEC_ID_PAF_AUDIO,
AV_CODEC_ID_ON2AVC,
AV_CODEC_ID_DSS_SP,
AV_CODEC_ID_FFWAVESYNTH = 0x15800,
AV_CODEC_ID_SONIC,
AV_CODEC_ID_SONIC_LS,
AV_CODEC_ID_EVRC,
AV_CODEC_ID_SMV,
AV_CODEC_ID_DSD_LSBF,
AV_CODEC_ID_DSD_MSBF,
AV_CODEC_ID_DSD_LSBF_PLANAR,
AV_CODEC_ID_DSD_MSBF_PLANAR,
AV_CODEC_ID_4GV,
AV_CODEC_ID_INTERPLAY_ACM,
AV_CODEC_ID_XMA1,
AV_CODEC_ID_XMA2,
AV_CODEC_ID_DST,
#endregion
#region Subtitle Codecs
/// <summary>
/// A dummy ID pointing at the start of subtitle codecs.
/// </summary>
AV_CODEC_ID_FIRST_SUBTITLE = 0x17000,
AV_CODEC_ID_DVD_SUBTITLE = 0x17000,
AV_CODEC_ID_DVB_SUBTITLE,
/// <summary>
/// Raw UTF-8 text.
/// </summary>
AV_CODEC_ID_TEXT,
AV_CODEC_ID_XSUB,
AV_CODEC_ID_SSA,
AV_CODEC_ID_MOV_TEXT,
AV_CODEC_ID_HDMV_PGS_SUBTITLE,
AV_CODEC_ID_DVB_TELETEXT,
AV_CODEC_ID_SRT,
AV_CODEC_ID_MICRODVD = 0x17800,
AV_CODEC_ID_EIA_608,
AV_CODEC_ID_JACOSUB,
AV_CODEC_ID_SAMI,
AV_CODEC_ID_REALTEXT,
AV_CODEC_ID_STL,
AV_CODEC_ID_SUBVIEWER1,
AV_CODEC_ID_SUBVIEWER,
AV_CODEC_ID_SUBRIP,
AV_CODEC_ID_WEBVTT,
AV_CODEC_ID_MPL2,
AV_CODEC_ID_VPLAYER,
AV_CODEC_ID_PJS,
AV_CODEC_ID_ASS,
/// <summary>
/// Other specific kind of codecs (generally used for attachments).
/// </summary>
AV_CODEC_ID_HDMV_TEXT_SUBTITLE,
/// <summary>
/// A dummy ID pointing at the start of various fake codecs.
/// </summary>
AV_CODEC_ID_FIRST_UNKNOWN = 0x18000,
AV_CODEC_ID_TTF = 0x18000,
AV_CODEC_ID_BINTEXT = 0x18800,
AV_CODEC_ID_XBIN,
AV_CODEC_ID_IDF,
AV_CODEC_ID_OTF,
AV_CODEC_ID_SMPTE_KLV,
AV_CODEC_ID_DVD_NAV,
AV_CODEC_ID_TIMED_ID3,
AV_CODEC_ID_BIN_DATA,
/// <summary>
/// The codec ID is not known (like AV_CODEC_ID_NONE) but lavf should attempt to identify it.
/// </summary>
AV_CODEC_ID_PROBE = 0x19000,
/// <summary>
/// A fake codec to indicate a raw MPEG-2 TS stream (only used by libavformat).
/// </summary>
AV_CODEC_ID_MPEG2TS = 0x20000,
/// <summary>
/// A fake codec to indicate a MPEG-4 Systems stream (only used by libavformat).
/// </summary>
AV_CODEC_ID_MPEG4SYSTEMS = 0x20001,
/// <summary>
/// A dummy codec for streams containing only metadata information.
/// </summary>
AV_CODEC_ID_FFMETADATA = 0x21000,
/// <summary>
/// A passthrough codec, AVFrames wrapped in AVPacket.
/// </summary>
AV_CODEC_ID_WRAPPED_AVFRAME = 0x21001
#endregion
}
}
| |
/*
* Copyright (c) 2015, InWorldz Halcyon Developers
* 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 halcyon nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenMetaverse;
using TransactionInfoBlock = OpenMetaverse.Packets.MoneyBalanceReplyPacket.TransactionInfoBlock;
using OpenSim.Framework;
using OpenSim.Region.Framework.Scenes;
using System.Net;
using System.Xml;
using OpenSim.Region.Framework.Interfaces;
using log4net;
using System.Reflection;
using OpenMetaverse.StructuredData;
namespace OpenSim.Region.CoreModules.Agent.BotManager
{
public class BotClient : IBot, IClientAPI
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
#region Declares
private UUID m_UUID, m_sessionId;
public string m_firstName, m_lastName;
private int m_animationSequenceNumber = 1;
private uint m_circuitCode;
private Scene m_scene;
private Dictionary<string, UUID> m_defaultAnimations = new Dictionary<string, UUID>();
private bool m_frozenUser = false;
private bool m_closing = false;
#endregion
#region Constructor
public BotClient(string firstName, string lastName, Scene scene, Vector3 startPos, UUID ownerID)
{
m_circuitCode = (uint)Util.RandomClass.Next(0, int.MaxValue);
m_UUID = UUID.Random();
m_sessionId = UUID.Random();
m_firstName = firstName;
m_lastName = lastName;
m_scene = scene;
StartPos = startPos;
OwnerID = ownerID;
MovementController = new BotMovementController(this);
RegisteredScriptsForPathUpdateEvents = new List<UUID>();
TimeCreated = DateTime.Now;
InitDefaultAnimations();
}
#endregion
#region IBot Properties
public UUID OwnerID { get; private set; }
public OpenMetaverse.UUID AgentID { get { return m_UUID; } }
public BotMovementController MovementController { get; private set; }
public List<UUID> RegisteredScriptsForPathUpdateEvents { get; private set; }
public DateTime TimeCreated { get; private set; }
public bool Frozen { get { return m_frozenUser; } }
#endregion
#region IBot Methods
#region Bot Property Methods
public void Close()
{
if (!m_closing)
{
m_closing = true;
MovementController.StopMovement();
m_scene.RemoveClient(AgentID);
// Fire the callback for this connection closing
if (OnConnectionClosed != null)
OnConnectionClosed(this);
}
}
#endregion
#region Region Interaction Methods
public bool SitOnObject(UUID objectID)
{
if (m_frozenUser)
return false;
ScenePresence sp = m_scene.GetScenePresence(m_UUID);
if (sp == null)
return false;
SceneObjectPart child = m_scene.GetSceneObjectPart(objectID);
if (child == null)
return false;
sp.HandleAgentRequestSit(sp.ControllingClient, AgentID, objectID, Vector3.Zero);
return true;
}
public bool StandUp()
{
if (m_frozenUser)
return false;
ScenePresence sp = m_scene.GetScenePresence(m_UUID);
if (sp == null)
return false;
sp.StandUp(false, true);
return true;
}
public bool TouchObject(UUID objectID)
{
if (m_frozenUser)
return false;
ScenePresence sp = m_scene.GetScenePresence(AgentID);
if (sp == null)
return false;
SceneObjectPart part = m_scene.GetSceneObjectPart(objectID);
if (part == null)
return false;
m_scene.ProcessObjectGrab(part.LocalId, Vector3.Zero, this, null);
m_scene.ProcessObjectDeGrab(part.LocalId, this, null);
return true;
}
#endregion
#region Bot Animation Methods
public bool StartAnimation(UUID animID, string anim, UUID objectID)
{
if (m_frozenUser)
return false;
ScenePresence sp = m_scene.GetScenePresence(AgentID);
if (sp == null)
return false;
if (animID == UUID.Zero)
sp.AddAnimation(anim, objectID);
else
sp.AddAnimation(animID, objectID);
return true;
}
public bool StopAnimation(UUID animID, string anim)
{
if (m_frozenUser)
return false;
ScenePresence sp = m_scene.GetScenePresence(AgentID);
if (sp == null)
return false;
if (animID == UUID.Zero)
sp.RemoveAnimation(anim);
else
sp.RemoveAnimation(animID);
return true;
}
#endregion
#region Bot Movement Methods
public bool SetSpeed(float speed)
{
if (m_frozenUser)
return false;
ScenePresence sp = m_scene.GetScenePresence(AgentID);
if (sp == null)
return false;
sp.SpeedModifier = speed;
return true;
}
#endregion
#region Chat Methods
public void Say(int channel, string message, ChatTypeEnum sourceType)
{
if (m_frozenUser)
return;
if (channel == 0 && sourceType != ChatTypeEnum.StartTyping && sourceType != ChatTypeEnum.StopTyping)
{
message = message.Trim();
if (string.IsNullOrEmpty(message))
{
return;
}
}
if (sourceType == ChatTypeEnum.StartTyping)
{
StartAnimation(UUID.Zero, "TYPE", UUID.Zero);
}
else if (sourceType == ChatTypeEnum.StopTyping)
{
StopAnimation(UUID.Zero, "TYPE");
}
OSChatMessage chatFromClient = new OSChatMessage();
chatFromClient.Channel = channel;
chatFromClient.From = Name;
chatFromClient.Message = message;
chatFromClient.Position = StartPos;
chatFromClient.Scene = m_scene;
chatFromClient.SenderUUID = AgentId;
chatFromClient.Type = sourceType;
// Force avatar position to be server-known avatar position. (Former contents of FixPositionOfChatMessage.)
ScenePresence avatar;
if (m_scene.TryGetAvatar(m_UUID, out avatar))
chatFromClient.Position = avatar.AbsolutePosition;
OnChatFromClient(this, chatFromClient);
}
public void SendInstantMessage(UUID agentId, string message)
{
if (m_frozenUser)
return;
// We may be able to use ClientView.SendInstantMessage here, but we need a client instance.
// InstantMessageModule.OnInstantMessage searches through a list of scenes for a client matching the toAgent,
// but I don't think we have a list of scenes available from here.
// (We also don't want to duplicate the code in OnInstantMessage if we can avoid it.)
// user is a UUID
// client.SendInstantMessage(m_host.UUID, fromSession, message, user, imSessionID, m_host.Name, AgentManager.InstantMessageDialog.MessageFromAgent, (uint)Util.UnixTimeSinceEpoch());
UUID friendTransactionID = UUID.Random();
//m_pendingFriendRequests.Add(friendTransactionID, fromAgentID);
GridInstantMessage msg = new GridInstantMessage();
msg.fromAgentID = new Guid(AgentID.ToString());
msg.toAgentID = agentId.Guid;
msg.imSessionID = new Guid(friendTransactionID.ToString()); // This is the item we're mucking with here
msg.timestamp = (uint)Util.UnixTimeSinceEpoch();// timestamp;
msg.fromAgentName = Name;
// Cap the message length at 1024.
if (message != null && message.Length > 1024)
msg.message = message.Substring(0, 1024);
else
msg.message = message;
msg.dialog = (byte)InstantMessageDialog.MessageFromAgent;
msg.fromGroup = false;// fromGroup;
msg.offline = (byte)0; //offline;
msg.ParentEstateID = 0; //ParentEstateID;
ScenePresence sp = m_scene.GetScenePresence(AgentID);
msg.Position = sp.AbsolutePosition;
msg.RegionID = m_scene.RegionInfo.RegionID.Guid;//RegionID.Guid;
// binaryBucket is the SL URL without the prefix, e.g. "Region/x/y/z"
string url = Util.LocationShortCode(m_scene.RegionInfo.RegionName, msg.Position, "/");
byte[] bucket = Utils.StringToBytes(url);
msg.binaryBucket = new byte[bucket.Length];// binaryBucket;
bucket.CopyTo(msg.binaryBucket, 0);
IMessageTransferModule transferModule = m_scene.RequestModuleInterface<IMessageTransferModule>();
if (transferModule != null)
{
transferModule.SendInstantMessage(msg, delegate(bool success) { });
}
}
public void SendChatMessage(string message, byte type, OpenMetaverse.Vector3 fromPos, string fromName, OpenMetaverse.UUID fromAgentID, OpenMetaverse.UUID ownerID, byte source, byte audible)
{
}
#endregion
#region Give Inventory
public void GiveInventoryObject(SceneObjectPart part, string objName, UUID objId, byte assetType, UUID destId)
{
if (m_frozenUser)
return;
// check if destination is an avatar
if (!String.IsNullOrEmpty(m_scene.CommsManager.UserService.Key2Name(destId, false)))
{
if (m_scene.GetScenePresence(destId) == null || m_scene.GetScenePresence(destId).IsChildAgent)
return;//Only allow giving items to users in the sim
// destination is an avatar
InventoryItemBase agentItem =
m_scene.MoveTaskInventoryItem(destId, UUID.Zero, part, objId);
if (agentItem == null)
return;
byte dialog = (byte)InstantMessageDialog.InventoryOffered;
byte[] bucket = new byte[17];
bucket[0] = assetType;
agentItem.ID.ToBytes(bucket, 1);
ScenePresence sp = m_scene.GetScenePresence(AgentID);
string URL = Util.LocationURL(m_scene.RegionInfo.RegionName, sp.AbsolutePosition);
GridInstantMessage msg = new GridInstantMessage(m_scene,
AgentID, Name, destId,
dialog, false, "'" + objName + "' ( " + URL + " )",
agentItem.ID, true, sp.AbsolutePosition,
bucket);
IMessageTransferModule transferModule = m_scene.RequestModuleInterface<IMessageTransferModule>();
if (transferModule != null)
{
transferModule.SendInstantMessage(msg, delegate(bool success) { });
}
}
}
#endregion
#endregion
#region IClientAPI Properties / Methods
public OpenMetaverse.Vector3 StartPos
{
get;
set;
}
public OpenMetaverse.UUID AgentId
{
get { return m_UUID; }
}
public OpenMetaverse.UUID SessionId
{
get { return m_sessionId; }
}
public OpenMetaverse.UUID SecureSessionId
{
get { return UUID.Zero; }
}
public OpenMetaverse.UUID ActiveGroupId
{
get { return UUID.Zero; }
}
public string ActiveGroupName
{
get { return String.Empty; }
}
public ulong ActiveGroupPowers
{
get { return 0; }
}
public ulong GetGroupPowers(OpenMetaverse.UUID groupID) { return 0; }
public ulong? GetGroupPowersOrNull(OpenMetaverse.UUID groupID) { return null; }
public bool IsGroupMember(OpenMetaverse.UUID GroupID) { return false; }
public string FirstName
{
get { return m_firstName; }
}
public string LastName
{
get { return m_lastName; }
}
public IScene Scene
{
get { return m_scene; }
}
public int NextAnimationSequenceNumber
{
get { return m_animationSequenceNumber++; }
}
public string Name
{
get { return FirstName + " " + LastName; }
}
public bool IsActive
{
get;
set;
}
public bool SendLogoutPacketWhenClosing
{
set { }
}
public bool DebugCrossings
{
get { return false; }
set { }
}
public uint NeighborsRange
{
get { return 1U; }
set { }
}
public uint CircuitCode
{
get { return m_circuitCode; }
}
#pragma warning disable 0067 // disable "X is never used"
public event Action<int> OnSetThrottles;
public event GenericMessage OnGenericMessage;
public event ImprovedInstantMessage OnInstantMessage;
public event ChatMessage OnChatFromClient;
public event TextureRequest OnRequestTexture;
public event RezObject OnRezObject;
public event RestoreObject OnRestoreObject;
public event ModifyTerrain OnModifyTerrain;
public event BakeTerrain OnBakeTerrain;
public event EstateChangeInfo OnEstateChangeInfo;
public event SimWideDeletesDelegate OnSimWideDeletes;
public event SetAppearance OnSetAppearance;
public event AvatarNowWearing OnAvatarNowWearing;
public event RezSingleAttachmentFromInv OnRezSingleAttachmentFromInv;
public event RezMultipleAttachmentsFromInv OnRezMultipleAttachmentsFromInv;
public event UUIDNameRequest OnDetachAttachmentIntoInv;
public event ObjectAttach OnObjectAttach;
public event ObjectDeselect OnObjectDetach;
public event ObjectDrop OnObjectDrop;
public event StartAnim OnStartAnim;
public event StopAnim OnStopAnim;
public event LinkObjects OnLinkObjects;
public event DelinkObjects OnDelinkObjects;
public event RequestMapBlocks OnRequestMapBlocks;
public event RequestMapName OnMapNameRequest;
public event TeleportLocationRequest OnTeleportLocationRequest;
public event DisconnectUser OnDisconnectUser;
public event RequestAvatarProperties OnRequestAvatarProperties;
public event RequestAvatarInterests OnRequestAvatarInterests;
public event SetAlwaysRun OnSetAlwaysRun;
public event TeleportLandmarkRequest OnTeleportLandmarkRequest;
public event DeRezObjects OnDeRezObjects;
public event Action<IClientAPI> OnRegionHandShakeReply;
public event GenericCall2 OnRequestWearables;
public event GenericCall2 OnCompleteMovementToRegion;
public event UpdateAgent OnAgentUpdate;
public event AgentRequestSit OnAgentRequestSit;
public event AgentSit OnAgentSit;
public event AvatarPickerRequest OnAvatarPickerRequest;
public event Action<IClientAPI> OnRequestAvatarsData;
public event AddNewPrim OnAddPrim;
public event FetchInventory OnAgentDataUpdateRequest;
public event TeleportLocationRequest OnSetStartLocationRequest;
public event RequestGodlikePowers OnRequestGodlikePowers;
public event GodKickUser OnGodKickUser;
public event ObjectDuplicate OnObjectDuplicate;
public event ObjectDuplicateOnRay OnObjectDuplicateOnRay;
public event GrabObject OnGrabObject;
public event DeGrabObject OnDeGrabObject;
public event MoveObject OnGrabUpdate;
public event SpinStart OnSpinStart;
public event SpinObject OnSpinUpdate;
public event SpinStop OnSpinStop;
public event UpdateShape OnUpdatePrimShape;
public event ObjectExtraParams OnUpdateExtraParams;
public event ObjectRequest OnObjectRequest;
public event ObjectSelect OnObjectSelect;
public event ObjectDeselect OnObjectDeselect;
public event GenericCall7 OnObjectDescription;
public event GenericCall7 OnObjectName;
public event GenericCall7 OnObjectClickAction;
public event GenericCall7 OnObjectMaterial;
public event RequestObjectPropertiesFamily OnRequestObjectPropertiesFamily;
public event UpdatePrimFlags OnUpdatePrimFlags;
public event UpdatePrimTexture OnUpdatePrimTexture;
public event UpdateVectorWithUndoSupport OnUpdatePrimGroupPosition;
public event UpdateVectorWithUndoSupport OnUpdatePrimSinglePosition;
public event UpdatePrimRotation OnUpdatePrimGroupRotation;
public event UpdatePrimSingleRotation OnUpdatePrimSingleRotation;
public event UpdatePrimSingleRotationPosition OnUpdatePrimSingleRotationPosition;
public event UpdatePrimGroupRotation OnUpdatePrimGroupMouseRotation;
public event UpdateVector OnUpdatePrimScale;
public event UpdateVector OnUpdatePrimGroupScale;
public event StatusChange OnChildAgentStatus;
public event GenericCall2 OnStopMovement;
public event Action<OpenMetaverse.UUID> OnRemoveAvatar;
public event ObjectPermissions OnObjectPermissions;
public event CreateNewInventoryItem OnCreateNewInventoryItem;
public event LinkInventoryItem OnLinkInventoryItem;
public event CreateInventoryFolder OnCreateNewInventoryFolder;
public event UpdateInventoryFolder OnUpdateInventoryFolder;
public event MoveInventoryFolder OnMoveInventoryFolder;
public event FetchInventoryDescendents OnFetchInventoryDescendents;
public event PurgeInventoryDescendents OnPurgeInventoryDescendents;
public event FetchInventory OnFetchInventory;
public event RequestTaskInventory OnRequestTaskInventory;
public event UpdateInventoryItem OnUpdateInventoryItem;
public event CopyInventoryItem OnCopyInventoryItem;
public event MoveInventoryItem OnMoveInventoryItem;
public event RemoveInventoryFolder OnRemoveInventoryFolder;
public event RemoveInventoryItem OnRemoveInventoryItem;
public event RemoveInventoryItem OnPreRemoveInventoryItem;
public event UDPAssetUploadRequest OnAssetUploadRequest;
public event XferReceive OnXferReceive;
public event RequestXfer OnRequestXfer;
public event ConfirmXfer OnConfirmXfer;
public event AbortXfer OnAbortXfer;
public event RezScript OnRezScript;
public event UpdateTaskInventory OnUpdateTaskInventory;
public event MoveTaskInventory OnMoveTaskItem;
public event RemoveTaskInventory OnRemoveTaskItem;
public event RequestAsset OnRequestAsset;
public event UUIDNameRequest OnNameFromUUIDRequest;
public event ParcelAccessListRequest OnParcelAccessListRequest;
public event ParcelAccessListUpdateRequest OnParcelAccessListUpdateRequest;
public event ParcelPropertiesRequest OnParcelPropertiesRequest;
public event ParcelDivideRequest OnParcelDivideRequest;
public event ParcelJoinRequest OnParcelJoinRequest;
public event ParcelPropertiesUpdateRequest OnParcelPropertiesUpdateRequest;
public event ParcelSelectObjects OnParcelSelectObjects;
public event ParcelObjectOwnerRequest OnParcelObjectOwnerRequest;
public event ParcelAbandonRequest OnParcelAbandonRequest;
public event ParcelGodForceOwner OnParcelGodForceOwner;
public event ParcelReclaim OnParcelReclaim;
public event ParcelReturnObjectsRequest OnParcelReturnObjectsRequest;
public event ParcelDeedToGroup OnParcelDeedToGroup;
public event RegionInfoRequest OnRegionInfoRequest;
public event EstateCovenantRequest OnEstateCovenantRequest;
public event FriendActionDelegate OnApproveFriendRequest;
public event FriendActionDelegate OnDenyFriendRequest;
public event FriendshipTermination OnTerminateFriendship;
public event MoneyTransferRequest OnMoneyTransferRequest;
public event EconomyDataRequest OnEconomyDataRequest;
public event MoneyBalanceRequest OnMoneyBalanceRequest;
public event UpdateAvatarProperties OnUpdateAvatarProperties;
public event AvatarInterestsUpdate OnAvatarInterestsUpdate;
public event ParcelBuy OnParcelBuy;
public event RequestPayPrice OnRequestPayPrice;
public event ObjectSaleInfo OnObjectSaleInfo;
public event ObjectBuy OnObjectBuy;
public event BuyObjectInventory OnBuyObjectInventory;
public event RequestTerrain OnRequestTerrain;
public event RequestTerrain OnUploadTerrain;
public event ObjectIncludeInSearch OnObjectIncludeInSearch;
public event UUIDNameRequest OnTeleportHomeRequest;
public event ScriptAnswer OnScriptAnswer;
public event AgentSit OnUndo;
public event AgentSit OnRedo;
public event LandUndo OnLandUndo;
public event ForceReleaseControls OnForceReleaseControls;
public event GodLandStatRequest OnLandStatRequest;
public event DetailedEstateDataRequest OnDetailedEstateDataRequest;
public event SetEstateFlagsRequest OnSetEstateFlagsRequest;
public event SetEstateTerrainBaseTexture OnSetEstateTerrainBaseTexture;
public event SetEstateTerrainDetailTexture OnSetEstateTerrainDetailTexture;
public event SetEstateTerrainTextureHeights OnSetEstateTerrainTextureHeights;
public event CommitEstateTerrainTextureRequest OnCommitEstateTerrainTextureRequest;
public event SetRegionTerrainSettings OnSetRegionTerrainSettings;
public event EstateRestartSimRequest OnEstateRestartSimRequest;
public event EstateChangeCovenantRequest OnEstateChangeCovenantRequest;
public event UpdateEstateAccessDeltaRequest OnUpdateEstateAccessDeltaRequest;
public event SimulatorBlueBoxMessageRequest OnSimulatorBlueBoxMessageRequest;
public event EstateBlueBoxMessageRequest OnEstateBlueBoxMessageRequest;
public event EstateDebugRegionRequest OnEstateDebugRegionRequest;
public event EstateTeleportOneUserHomeRequest OnEstateTeleportOneUserHomeRequest;
public event EstateTeleportAllUsersHomeRequest OnEstateTeleportAllUsersHomeRequest;
public event UUIDNameRequest OnUUIDGroupNameRequest;
public event RegionHandleRequest OnRegionHandleRequest;
public event ParcelInfoRequest OnParcelInfoRequest;
public event RequestObjectPropertiesFamily OnObjectGroupRequest;
public event ScriptReset OnScriptReset;
public event GetScriptRunning OnGetScriptRunning;
public event SetScriptRunning OnSetScriptRunning;
public event UpdateVector OnAutoPilotGo;
public event TerrainUnacked OnUnackedTerrain;
public event ActivateGestures OnActivateGestures;
public event DeactivateGestures OnDeactivateGestures;
public event ObjectOwner OnObjectOwner;
public event DirPlacesQuery OnDirPlacesQuery;
public event DirFindQuery OnDirFindQuery;
public event DirLandQuery OnDirLandQuery;
public event DirPopularQuery OnDirPopularQuery;
public event DirClassifiedQuery OnDirClassifiedQuery;
public event EventInfoRequest OnEventInfoRequest;
public event ParcelSetOtherCleanTime OnParcelSetOtherCleanTime;
public event MapItemRequest OnMapItemRequest;
public event OfferCallingCard OnOfferCallingCard;
public event AcceptCallingCard OnAcceptCallingCard;
public event DeclineCallingCard OnDeclineCallingCard;
public event SoundTrigger OnSoundTrigger;
public event StartLure OnStartLure;
public event TeleportLureRequest OnTeleportLureRequest;
public event NetworkStats OnNetworkStatsUpdate;
public event ClassifiedInfoRequest OnClassifiedInfoRequest;
public event ClassifiedInfoUpdate OnClassifiedInfoUpdate;
public event ClassifiedDelete OnClassifiedDelete;
public event ClassifiedDelete OnClassifiedGodDelete;
public event EventNotificationAddRequest OnEventNotificationAddRequest;
public event EventNotificationRemoveRequest OnEventNotificationRemoveRequest;
public event EventGodDelete OnEventGodDelete;
public event ParcelDwellRequest OnParcelDwellRequest;
public event UserInfoRequest OnUserInfoRequest;
public event UpdateUserInfo OnUpdateUserInfo;
public event RetrieveInstantMessages OnRetrieveInstantMessages;
public event PickDelete OnPickDelete;
public event PickGodDelete OnPickGodDelete;
public event PickInfoUpdate OnPickInfoUpdate;
public event AvatarNotesUpdate OnAvatarNotesUpdate;
public event MuteListRequest OnMuteListRequest;
public event MuteListEntryUpdate OnUpdateMuteListEntry;
public event MuteListEntryRemove OnRemoveMuteListEntry;
public event PlacesQuery OnPlacesQuery;
public event GrantUserRights OnGrantUserRights;
public event FreezeUserUpdate OnParcelFreezeUser;
public event EjectUserUpdate OnParcelEjectUser;
public event GroupVoteHistoryRequest OnGroupVoteHistoryRequest;
public event GroupAccountDetailsRequest OnGroupAccountDetailsRequest;
public event GroupAccountSummaryRequest OnGroupAccountSummaryRequest;
public event GroupAccountTransactionsRequest OnGroupAccountTransactionsRequest;
public event AgentCachedTextureRequest OnAgentCachedTextureRequest;
public event ActivateGroup OnActivateGroup;
public event GodlikeMessage OnGodlikeMessage;
public event GodlikeMessage OnEstateTelehubRequest;
#pragma warning restore 0067
public System.Net.IPEndPoint RemoteEndPoint
{
get { return new IPEndPoint(IPAddress.Loopback, 0); }
}
public bool IsLoggingOut
{
get;
set;
}
public void SetDebugPacketLevel(int newDebug)
{
}
public void ProcessInPacket(OpenMetaverse.Packets.Packet NewPack)
{
}
public void Kick(string message)
{
}
public void Start()
{
}
public void SendWearables(AvatarWearable[] wearables, int serial)
{
}
public void SendAppearance(AvatarAppearance app, Vector3 hover)
{
}
public void SendStartPingCheck(byte seq)
{
}
public void SendKillObject(ulong regionHandle, uint localID)
{
}
public void SendKillObjects(ulong regionHandle, uint[] localIDs)
{
}
public void SendNonPermanentKillObject(ulong regionHandle, uint localID)
{
}
public void SendNonPermanentKillObjects(ulong regionHandle, uint[] localIDs)
{
}
public void SendAnimations(OpenMetaverse.UUID[] animID, int[] seqs, OpenMetaverse.UUID sourceAgentId, OpenMetaverse.UUID[] objectIDs)
{
}
public void SendRegionHandshake(RegionInfo regionInfo, RegionHandshakeArgs args)
{
}
public void SendInstantMessage(GridInstantMessage im)
{
}
public void SendGenericMessage(string method, List<string> message)
{
}
public void SendLayerData(float[] map)
{
}
public void SendLayerData(int px, int py, float[] map)
{
}
public void SendWindData(OpenMetaverse.Vector2[] windSpeeds)
{
}
public void SendCloudData(float[] cloudCover)
{
}
public void MoveAgentIntoRegion(RegionInfo regInfo, OpenMetaverse.Vector3 pos, OpenMetaverse.Vector3 look)
{
}
public void InformClientOfNeighbour(ulong neighbourHandle, System.Net.IPEndPoint neighbourExternalEndPoint)
{
}
public AgentCircuitData RequestClientInfo()
{
AgentCircuitData agentData = new AgentCircuitData();
agentData.AgentID = AgentId;
// agentData.Appearance
// agentData.BaseFolder
agentData.CapsPath = String.Empty;
agentData.child = false;
agentData.CircuitCode = m_circuitCode;
agentData.ClientVersion = "Bot";
agentData.FirstName = m_firstName;
// agentData.InventoryFolder
agentData.LastName = m_lastName;
agentData.SecureSessionID = SecureSessionId;
agentData.SessionID = m_sessionId;
// agentData.startpos
return agentData;
}
public void SendMapBlock(List<MapBlockData> mapBlocks, uint flag)
{
}
public void SendLocalTeleport(OpenMetaverse.Vector3 position, OpenMetaverse.Vector3 lookAt, uint flags)
{
}
public void SendTeleportFailed(string reason)
{
}
public void SendTeleportLocationStart()
{
}
public void SendMoneyBalance(UUID transaction, bool success, string description, int balance, TransactionInfoBlock transInfo)
{
}
public void SendPayPrice(OpenMetaverse.UUID objectID, int[] payPrice)
{
}
public void SendAvatarData(ulong regionHandle, string firstName, string lastName, string grouptitle, OpenMetaverse.UUID avatarID, uint avatarLocalID,
OpenMetaverse.Vector3 Pos, byte[] textureEntry, uint parentID, OpenMetaverse.Quaternion rotation, OpenMetaverse.Vector4 collisionPlane,
OpenMetaverse.Vector3 velocity, bool immediate)
{
}
public void SendAvatarTerseUpdate(ulong regionHandle, ushort timeDilation, uint localID, OpenMetaverse.Vector3 position, OpenMetaverse.Vector3 velocity, OpenMetaverse.Vector3 acceleration, OpenMetaverse.Quaternion rotation, OpenMetaverse.UUID agentid, OpenMetaverse.Vector4 collisionPlane)
{
}
public void SendCoarseLocationUpdate(List<OpenMetaverse.UUID> users, List<OpenMetaverse.Vector3> CoarseLocations)
{
}
public void AttachObject(uint localID, OpenMetaverse.Quaternion rotation, byte attachPoint, OpenMetaverse.UUID ownerID)
{
}
public void SetChildAgentThrottle(byte[] throttle)
{
}
public void SendPrimitiveToClient(object sop, uint clientFlags, OpenMetaverse.Vector3 lpos, PrimUpdateFlags updateFlags)
{
}
public void SendPrimitiveToClientImmediate(object sop, uint clientFlags, OpenMetaverse.Vector3 lpos)
{
}
public void SendPrimTerseUpdate(object sop)
{
}
public void SendInventoryFolderDetails(OpenMetaverse.UUID ownerID, InventoryFolderBase folder, List<InventoryItemBase> items, List<InventoryFolderBase> folders, bool fetchFolders, bool fetchItems)
{
}
public void FlushPrimUpdates()
{
}
public void SendInventoryItemDetails(OpenMetaverse.UUID ownerID, InventoryItemBase item)
{
}
public void SendInventoryItemCreateUpdate(InventoryItemBase Item, uint callbackId)
{
}
public void SendRemoveInventoryItem(OpenMetaverse.UUID itemID)
{
}
public void SendTakeControls(int controls, bool TakeControls, bool passToAgent)
{
}
public void SendTakeControls2(int controls1, bool takeControls1, bool passToAgent1,
int controls2, bool takeControls2, bool passToAgent2)
{
}
public void SendTaskInventory(OpenMetaverse.UUID taskID, short serial, byte[] fileName)
{
}
public void SendBulkUpdateInventory(InventoryNodeBase node)
{
}
public void SendXferPacket(ulong xferID, uint packet, byte[] data)
{
}
public void SendEconomyData(float EnergyEfficiency, int ObjectCapacity, int ObjectCount, int PriceEnergyUnit, int PriceGroupCreate, int PriceObjectClaim, float PriceObjectRent, float PriceObjectScaleFactor, int PriceParcelClaim, float PriceParcelClaimFactor, int PriceParcelRent, int PricePublicObjectDecay, int PricePublicObjectDelete, int PriceRentLight, int PriceUpload, int TeleportMinPrice, float TeleportPriceExponent)
{
}
public void SendAvatarPickerReply(AvatarPickerReplyAgentDataArgs AgentData, List<AvatarPickerReplyDataArgs> Data)
{
}
public void SendAgentDataUpdate(OpenMetaverse.UUID agentid, OpenMetaverse.UUID activegroupid, string firstname, string lastname, ulong grouppowers, string groupname, string grouptitle)
{
}
public void SendPreLoadSound(OpenMetaverse.UUID objectID, OpenMetaverse.UUID ownerID, OpenMetaverse.UUID soundID)
{
}
public void SendPlayAttachedSound(OpenMetaverse.UUID soundID, OpenMetaverse.UUID objectID, OpenMetaverse.UUID ownerID, float gain, byte flags)
{
}
public void SendTriggeredSound(OpenMetaverse.UUID soundID, OpenMetaverse.UUID ownerID, OpenMetaverse.UUID objectID, OpenMetaverse.UUID parentID, ulong handle, OpenMetaverse.Vector3 position, float gain)
{
}
public void SendAttachedSoundGainChange(OpenMetaverse.UUID objectID, float gain)
{
}
public void SendNameReply(OpenMetaverse.UUID profileId, string firstname, string lastname)
{
}
public void SendAlertMessage(string message)
{
}
public void SendAlertMessage(string message, string infoMessage, OSD extraParams)
{
/* no op */
}
public void SendAgentAlertMessage(string message, bool modal)
{
}
public void SendLoadURL(string objectname, OpenMetaverse.UUID objectID, OpenMetaverse.UUID ownerID, bool groupOwned, string message, string url)
{
}
public void SendDialog(string objectname, OpenMetaverse.UUID objectID, OpenMetaverse.UUID ownerID, string ownerFirstname, string ownerLastname, string msg, OpenMetaverse.UUID textureID, int ch, string[] buttonlabels)
{
}
public void SendSunPos(OpenMetaverse.Vector3 sunPos, OpenMetaverse.Vector3 sunVel, ulong CurrentTime, uint SecondsPerSunCycle, uint SecondsPerYear, float OrbitalPosition)
{
}
public void SendViewerEffect(OpenMetaverse.Packets.ViewerEffectPacket.EffectBlock[] effectBlocks)
{
}
public void SendViewerTime(int phase)
{
}
private void InitDefaultAnimations()
{
try
{
using (XmlTextReader reader = new XmlTextReader("data/avataranimations.xml"))
{
XmlDocument doc = new XmlDocument();
doc.Load(reader);
if (doc.DocumentElement != null)
foreach (XmlNode nod in doc.DocumentElement.ChildNodes)
{
if (nod.Attributes["name"] != null)
{
string name = nod.Attributes["name"].Value.ToLower();
string id = nod.InnerText;
m_defaultAnimations.Add(name, (UUID)id);
}
}
}
}
catch (Exception)
{
}
}
public OpenMetaverse.UUID GetDefaultAnimation(string name)
{
if (m_defaultAnimations.ContainsKey(name.ToLower()))
return m_defaultAnimations[name.ToLower()];
return UUID.Zero;
}
public void SendAvatarProperties(OpenMetaverse.UUID avatarID, string aboutText, string bornOn, byte[] charterMember, string flAbout, uint flags, OpenMetaverse.UUID flImageID, OpenMetaverse.UUID imageID, string profileURL, OpenMetaverse.UUID partnerID)
{
}
public void SendAvatarInterests(OpenMetaverse.UUID avatarID, uint skillsMask, string skillsText, uint wantToMask, string wantToText, string languagesText)
{
}
public void SendScriptQuestion(OpenMetaverse.UUID taskID, string taskName, string ownerName, OpenMetaverse.UUID itemID, int question)
{
}
public void SendHealth(float health)
{
}
public void SendEstateUUIDList(OpenMetaverse.UUID invoice, int whichList, OpenMetaverse.UUID[] UUIDList, uint estateID)
{
}
public void SendBannedUserList(OpenMetaverse.UUID invoice, EstateBan[] banlist, uint estateID)
{
}
public void SendRegionInfoToEstateMenu(RegionInfoForEstateMenuArgs args)
{
}
public void SendEstateCovenantInformation(OpenMetaverse.UUID covenant, uint lastUpdated)
{
}
public void SendDetailedEstateData(OpenMetaverse.UUID invoice, string estateName, uint estateID, uint parentEstate, uint estateFlags, uint sunPosition, OpenMetaverse.UUID covenant, uint covenantLastUpdated, string abuseEmail, OpenMetaverse.UUID estateOwner)
{
}
public void SendLandProperties(int sequence_id, bool snap_selection, int request_result, LandData landData, float simObjectBonusFactor, int parcelObjectCapacity, int simObjectCapacity, uint regionFlags)
{
}
public void SendLandAccessListData(List<OpenMetaverse.UUID> avatars, uint accessFlag, int localLandID)
{
}
public void SendForceClientSelectObjects(List<uint> objectIDs)
{
}
public void SendLandObjectOwners(LandData land, List<OpenMetaverse.UUID> groups, Dictionary<OpenMetaverse.UUID, int> ownersAndCount)
{
}
public void SendLandParcelOverlay(byte[] data, int sequence_id)
{
}
public void SendParcelMediaCommand(uint flags, ParcelMediaCommandEnum command, float time)
{
}
public void SendParcelMediaUpdate(string mediaUrl, OpenMetaverse.UUID mediaTextureID, byte autoScale, string mediaType, string mediaDesc, int mediaWidth, int mediaHeight, byte mediaLoop)
{
}
public void SendAssetUploadCompleteMessage(sbyte AssetType, bool Success, OpenMetaverse.UUID AssetFullID)
{
}
public void SendConfirmXfer(ulong xferID, uint PacketID)
{
}
public void SendXferRequest(ulong XferID, short AssetType, OpenMetaverse.UUID vFileID, byte FilePath, byte[] FileName)
{
}
public void SendInitiateDownload(string simFileName, string clientFileName)
{
}
public void SendImageFirstPart(ushort numParts, OpenMetaverse.UUID ImageUUID, uint ImageSize, byte[] ImageData, byte imageCodec)
{
}
public void SendImageNextPart(ushort partNumber, OpenMetaverse.UUID imageUuid, byte[] imageData)
{
}
public void SendImageNotFound(OpenMetaverse.UUID imageid)
{
}
public void SendDisableSimulator()
{
}
public void SendSimStats(SimStats stats)
{
}
public void SendObjectPropertiesFamilyData(uint RequestFlags, OpenMetaverse.UUID ObjectUUID, OpenMetaverse.UUID OwnerID, OpenMetaverse.UUID GroupID, uint BaseMask, uint OwnerMask, uint GroupMask, uint EveryoneMask, uint NextOwnerMask, int OwnershipCost, byte SaleType, int SalePrice, uint Category, OpenMetaverse.UUID LastOwnerID, string ObjectName, string Description)
{
}
public void SendObjectPropertiesReply(OpenMetaverse.UUID ItemID, ulong CreationDate, OpenMetaverse.UUID CreatorUUID, OpenMetaverse.UUID FolderUUID, OpenMetaverse.UUID FromTaskUUID, OpenMetaverse.UUID GroupUUID, short InventorySerial, OpenMetaverse.UUID LastOwnerUUID, OpenMetaverse.UUID ObjectUUID, OpenMetaverse.UUID OwnerUUID, string TouchTitle, byte[] TextureID, string SitTitle, string ItemName, string ItemDescription, uint OwnerMask, uint NextOwnerMask, uint GroupMask, uint EveryoneMask, uint BaseMask, uint FoldedOwnerMask, uint FoldedNextOwnerMask, byte saleType, int salePrice)
{
}
public void SendAgentOffline(OpenMetaverse.UUID[] agentIDs)
{
}
public void SendAgentOnline(OpenMetaverse.UUID[] agentIDs)
{
}
public void SendSitResponse(OpenMetaverse.UUID TargetID, OpenMetaverse.Vector3 OffsetPos, OpenMetaverse.Quaternion SitOrientation, bool autopilot, OpenMetaverse.Vector3 CameraAtOffset, OpenMetaverse.Vector3 CameraEyeOffset, bool ForceMouseLook)
{
}
public void SendAdminResponse(OpenMetaverse.UUID Token, uint AdminLevel)
{
}
public void SendGroupMembership(GroupMembershipData[] GroupMembership)
{
}
public void SendGroupNameReply(OpenMetaverse.UUID groupLLUID, string GroupName)
{
}
public void SendJoinGroupReply(OpenMetaverse.UUID groupID, bool success)
{
}
public void SendEjectGroupMemberReply(OpenMetaverse.UUID agentID, OpenMetaverse.UUID groupID, bool success)
{
}
public void SendLeaveGroupReply(OpenMetaverse.UUID groupID, bool success)
{
}
public void SendCreateGroupReply(OpenMetaverse.UUID groupID, bool success, string message)
{
}
public void SendLandStatReply(uint reportType, uint requestFlags, uint resultCount, List<LandStatReportItem> lsrpl)
{
}
public void SendScriptRunningReply(OpenMetaverse.UUID objectID, OpenMetaverse.UUID itemID, bool running)
{
}
public void SendAsset(AssetBase asset, AssetRequestInfo req)
{
}
public void SendTexture(AssetBase TextureAsset)
{
}
public byte[] GetThrottlesPacked(float multiplier)
{
return new byte[0];
}
public event ViewerEffectEventHandler OnViewerEffect;
public event Action<IClientAPI> OnLogout;
public event Action<IClientAPI> OnConnectionClosed;
public void SendBlueBoxMessage(OpenMetaverse.UUID FromAvatarID, string FromAvatarName, string Message)
{
}
public void SendLogoutPacket()
{
}
public void SetClientInfo(ClientInfo info)
{
}
public void SetClientOption(string option, string value)
{
}
public string GetClientOption(string option)
{
return String.Empty;
}
public void SendSetFollowCamProperties(OpenMetaverse.UUID objectID, Dictionary<int, float> parameters)
{
}
public void SendClearFollowCamProperties(OpenMetaverse.UUID objectID)
{
}
public void SendRegionHandle(OpenMetaverse.UUID regoinID, ulong handle)
{
}
public void SendParcelInfo(RegionInfo info, LandData land, OpenMetaverse.UUID parcelID, uint x, uint y)
{
}
public void SendScriptTeleportRequest(string objName, string simName, OpenMetaverse.Vector3 pos, OpenMetaverse.Vector3 lookAt)
{
}
public void SendDirPlacesReply(OpenMetaverse.UUID queryID, DirPlacesReplyData[] data)
{
}
public void SendDirPeopleReply(OpenMetaverse.UUID queryID, DirPeopleReplyData[] data)
{
}
public void SendDirEventsReply(OpenMetaverse.UUID queryID, DirEventsReplyData[] data)
{
}
public void SendDirGroupsReply(OpenMetaverse.UUID queryID, DirGroupsReplyData[] data)
{
}
public void SendDirClassifiedReply(OpenMetaverse.UUID queryID, DirClassifiedReplyData[] data)
{
}
public void SendDirLandReply(OpenMetaverse.UUID queryID, DirLandReplyData[] data)
{
}
public void SendDirPopularReply(OpenMetaverse.UUID queryID, DirPopularReplyData[] data)
{
}
public void SendEventInfoReply(EventData info)
{
}
public void SendMapItemReply(mapItemReply[] replies, uint mapitemtype, uint flags)
{
}
public void SendAvatarGroupsReply(OpenMetaverse.UUID avatarID, GroupMembershipData[] data)
{
}
public void SendOfferCallingCard(OpenMetaverse.UUID srcID, OpenMetaverse.UUID transactionID)
{
}
public void SendAcceptCallingCard(OpenMetaverse.UUID transactionID)
{
}
public void SendDeclineCallingCard(OpenMetaverse.UUID transactionID)
{
}
public void SendTerminateFriend(OpenMetaverse.UUID exFriendID)
{
}
public void SendAvatarClassifiedReply(OpenMetaverse.UUID targetID, OpenMetaverse.UUID[] classifiedID, string[] name)
{
}
public void SendAvatarInterestsReply(OpenMetaverse.UUID avatarID, uint skillsMask, string skillsText, uint wantToMask, string wantToTask, string languagesText)
{
}
public void SendClassifiedInfoReply(OpenMetaverse.UUID classifiedID, OpenMetaverse.UUID creatorID, uint creationDate, uint expirationDate, uint category, string name, string description, OpenMetaverse.UUID parcelID, uint parentEstate, OpenMetaverse.UUID snapshotID, string simName, OpenMetaverse.Vector3 globalPos, string parcelName, byte classifiedFlags, int price)
{
}
public void SendAgentDropGroup(OpenMetaverse.UUID groupID)
{
}
public void RefreshGroupMembership()
{
}
public void SendAvatarNotesReply(OpenMetaverse.UUID targetID, string text)
{
}
public void SendAvatarPicksReply(OpenMetaverse.UUID targetID, Dictionary<OpenMetaverse.UUID, string> picks)
{
}
public void SendPickInfoReply(OpenMetaverse.UUID pickID, OpenMetaverse.UUID creatorID, bool topPick, OpenMetaverse.UUID parcelID, string name, string desc, OpenMetaverse.UUID snapshotID, string user, string originalName, string simName, OpenMetaverse.Vector3 posGlobal, int sortOrder, bool enabled)
{
}
public void SendAvatarClassifiedReply(OpenMetaverse.UUID targetID, Dictionary<OpenMetaverse.UUID, string> classifieds)
{
}
public void SendParcelDwellReply(int localID, OpenMetaverse.UUID parcelID, float dwell)
{
}
public void SendUserInfoReply(bool imViaEmail, bool visible, string email)
{
}
public void SendUseCachedMuteList()
{
}
public void SendMuteListUpdate(string filename)
{
}
public void KillEndDone()
{
}
public bool AddGenericPacketHandler(string MethodName, GenericMessage handler)
{
return false;
}
public void SendChangeUserRights(OpenMetaverse.UUID agent, OpenMetaverse.UUID agentRelated, int relatedRights)
{
}
public void SendTextBoxRequest(string message, int chatChannel, string objectname, OpenMetaverse.UUID ownerID, string firstName, string lastName, OpenMetaverse.UUID objectId)
{
}
public void FreezeMe(uint flags, OpenMetaverse.UUID whoKey, string whoName)
{
bool freeze = ((flags & 1) == 0);
if (freeze != m_frozenUser)
{
m_frozenUser = freeze;
if (m_frozenUser)
{
SendAgentAlertMessage(whoName + " has frozen you in place. You will be unable to move or interact until you log off and start a new session, or until " + whoName + " unfreezes you.", true);
m_log.WarnFormat("{0} has frozen {1} [{2}].", this.Name, whoName, whoKey);
}
else
{
SendAgentAlertMessage(whoName + " has unfrozen you. You are free to move and interact again.", true);
m_log.WarnFormat("{0} has unfrozen {1} [{2}].", this.Name, whoName, whoKey);
}
}
}
public void SendAbortXfer(ulong id, int result)
{
}
public void RunAttachmentOperation(Action action)
{
action();
}
public void SendAgentCachedTexture(List<CachedAgentArgs> args)
{
}
public void SendTelehubInfo(OpenMetaverse.Vector3 TelehubPos, OpenMetaverse.Quaternion TelehubRot, List<OpenMetaverse.Vector3> SpawnPoint, OpenMetaverse.UUID ObjectID, string nameT)
{
}
#endregion
public void HandleWithInventoryWriteThread(Action toHandle)
{
}
public System.Threading.Tasks.Task PauseUpdatesAndFlush()
{
return null;
}
public void ResumeUpdates(IEnumerable<uint> excludeObjectIds)
{
}
public void WaitForClose()
{
}
public void AfterAttachedToConnection(OpenSim.Framework.AgentCircuitData c)
{
}
public List<AgentGroupData> GetAllGroupPowers()
{
return new List<AgentGroupData>();
}
public void SetGroupPowers(IEnumerable<AgentGroupData> groupPowers)
{
}
public int GetThrottleTotal()
{
return 0;
}
public void SetActiveGroupInfo(AgentGroupData activeGroup)
{
}
}
}
| |
using System;
using System.Linq;
using CppSharp.AST;
using CppSharp.AST.Extensions;
using CppSharp.Generators.C;
using CppSharp.Generators.CSharp;
using CppSharp.Passes;
using NUnit.Framework;
namespace CppSharp.Generator.Tests.AST
{
[TestFixture]
public class TestAST : ASTTestFixture
{
public TestAST() : base("AST.h", "ASTExtensions.h")
{
}
[Test]
public void TestASTParameter()
{
var func = AstContext.FindFunction("TestParameterProperties").FirstOrDefault();
Assert.IsNotNull(func);
var paramNames = new[] { "a", "b", "c" };
var paramTypes = new[]
{
new QualifiedType(new BuiltinType(PrimitiveType.Bool)),
new QualifiedType(
new PointerType()
{
Modifier = PointerType.TypeModifier.LVReference,
QualifiedPointee = new QualifiedType(
new BuiltinType(PrimitiveType.Short),
new TypeQualifiers { IsConst = true })
}),
new QualifiedType(
new PointerType
{
Modifier = PointerType.TypeModifier.Pointer,
QualifiedPointee = new QualifiedType(new BuiltinType(PrimitiveType.Int))
})
};
for (int i = 0; i < func.Parameters.Count; i++)
{
var param = func.Parameters[i];
Assert.AreEqual(paramNames[i], param.Name, "Parameter.Name");
Assert.AreEqual(paramTypes[i], param.QualifiedType, "Parameter.QualifiedType");
Assert.AreEqual(i, param.Index, "Parameter.Index");
}
Assert.IsTrue(func.Parameters[2].HasDefaultValue, "Parameter.HasDefaultValue");
}
[Test]
public void TestASTHelperMethods()
{
var @namespace = AstContext.FindDecl<Namespace>("Math").FirstOrDefault();
Assert.IsNotNull(@namespace, "Couldn't find Math namespace.");
var @class = @namespace.FindClass("Complex");
Assert.IsNotNull(@class, "Couldn't find Math::Complex class.");
var plusOperator = @class.FindOperator(CXXOperatorKind.Plus).FirstOrDefault();
Assert.IsNotNull(plusOperator, "Couldn't find operator+ in Math::Complex class.");
var typedef = @namespace.FindTypedef("Single");
Assert.IsNotNull(typedef);
}
#region TestVisitor
class TestVisitor : IDeclVisitor<bool>
{
public bool VisitDeclaration(Declaration decl)
{
throw new System.NotImplementedException();
}
public bool VisitTranslationUnit(TranslationUnit unit)
{
throw new System.NotImplementedException();
}
public bool VisitClassDecl(Class @class)
{
throw new System.NotImplementedException();
}
public bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecialization specialization)
{
throw new NotImplementedException();
}
public bool VisitFieldDecl(Field field)
{
throw new System.NotImplementedException();
}
public bool VisitFunctionDecl(Function function)
{
throw new System.NotImplementedException();
}
public bool VisitMethodDecl(Method method)
{
return true;
}
public bool VisitParameterDecl(Parameter parameter)
{
throw new System.NotImplementedException();
}
public bool VisitTypedefDecl(TypedefDecl typedef)
{
throw new System.NotImplementedException();
}
public bool VisitTypeAliasDecl(TypeAlias typeAlias)
{
throw new NotImplementedException();
}
public bool VisitEnumDecl(Enumeration @enum)
{
throw new System.NotImplementedException();
}
public bool VisitEnumItemDecl(Enumeration.Item item)
{
throw new NotImplementedException();
}
public bool VisitVariableDecl(Variable variable)
{
throw new System.NotImplementedException();
}
public bool VisitClassTemplateDecl(ClassTemplate template)
{
throw new System.NotImplementedException();
}
public bool VisitFunctionTemplateDecl(FunctionTemplate template)
{
throw new System.NotImplementedException();
}
public bool VisitMacroDefinition(MacroDefinition macro)
{
throw new System.NotImplementedException();
}
public bool VisitNamespace(Namespace @namespace)
{
throw new System.NotImplementedException();
}
public bool VisitEvent(Event @event)
{
throw new System.NotImplementedException();
}
public bool VisitProperty(Property property)
{
throw new System.NotImplementedException();
}
public bool VisitFriend(Friend friend)
{
throw new System.NotImplementedException();
}
public bool VisitTemplateParameterDecl(TypeTemplateParameter templateParameter)
{
throw new NotImplementedException();
}
public bool VisitNonTypeTemplateParameterDecl(NonTypeTemplateParameter nonTypeTemplateParameter)
{
throw new NotImplementedException();
}
public bool VisitTemplateTemplateParameterDecl(TemplateTemplateParameter templateTemplateParameter)
{
throw new NotImplementedException();
}
public bool VisitTypeAliasTemplateDecl(TypeAliasTemplate typeAliasTemplate)
{
throw new NotImplementedException();
}
public bool VisitFunctionTemplateSpecializationDecl(FunctionTemplateSpecialization specialization)
{
throw new NotImplementedException();
}
public bool VisitVarTemplateDecl(VarTemplate template)
{
throw new NotImplementedException();
}
public bool VisitVarTemplateSpecializationDecl(VarTemplateSpecialization template)
{
throw new NotImplementedException();
}
public bool VisitTypedefNameDecl(TypedefNameDecl typedef)
{
throw new NotImplementedException();
}
public bool VisitUnresolvedUsingDecl(UnresolvedUsingTypename unresolvedUsingTypename)
{
throw new NotImplementedException();
}
}
#endregion
[Test]
public void TestASTVisitor()
{
var testVisitor = new TestVisitor();
var plusOperator = AstContext.TranslationUnits
.SelectMany(u => u.Namespaces.Where(n => n.Name == "Math"))
.SelectMany(n => n.Classes.Where(c => c.Name == "Complex"))
.SelectMany(c => c.Methods.Where(m => m.OperatorKind == CXXOperatorKind.Plus))
.First();
Assert.IsTrue(plusOperator.Visit(testVisitor));
}
[Test]
public void TestASTEnumItemByName()
{
var @enum = AstContext.FindEnum("TestASTEnumItemByName").Single();
Assert.NotNull(@enum);
Assert.IsTrue(@enum.ItemsByName.ContainsKey("TestItemByName"));
}
[Test]
public void TestASTFunctionTemplates()
{
var @class = AstContext.FindClass("TestTemplateFunctions").FirstOrDefault();
Assert.IsNotNull(@class, "Couldn't find TestTemplateFunctions class.");
Assert.AreEqual(6, @class.Templates.Count());
var twoParamMethodTemplate = @class.Templates.OfType<FunctionTemplate>()
.FirstOrDefault(t => t.Name == "MethodTemplateWithTwoTypeParameter");
Assert.IsNotNull(twoParamMethodTemplate);
Assert.AreEqual(2, twoParamMethodTemplate.Parameters.Count);
Assert.AreEqual("T", twoParamMethodTemplate.Parameters[0].Name);
Assert.AreEqual("S", twoParamMethodTemplate.Parameters[1].Name);
var twoParamMethod = twoParamMethodTemplate.TemplatedFunction as Method;
Assert.IsNotNull(twoParamMethod);
Assert.IsInstanceOf<TemplateParameterType>(twoParamMethod.Parameters[0].Type);
Assert.IsInstanceOf<TemplateParameterType>(twoParamMethod.Parameters[1].Type);
Assert.AreEqual(twoParamMethodTemplate.Parameters[0],
((TemplateParameterType) twoParamMethod.Parameters[0].Type).Parameter);
Assert.AreEqual(twoParamMethodTemplate.Parameters[1],
((TemplateParameterType) twoParamMethod.Parameters[1].Type).Parameter);
Assert.AreEqual(0, ((TemplateParameterType) twoParamMethod.Parameters[0].Type).Index);
Assert.AreEqual(1, ((TemplateParameterType) twoParamMethod.Parameters[1].Type).Index);
}
[Test]
public void TestASTClassTemplates()
{
var template = AstContext.TranslationUnits
.SelectMany(u => u.Templates.OfType<ClassTemplate>())
.FirstOrDefault(t => t.Name == "TestTemplateClass");
Assert.IsNotNull(template, "Couldn't find TestTemplateClass class.");
Assert.AreEqual(1, template.Parameters.Count);
var templateTypeParameter = template.Parameters[0];
Assert.AreEqual("T", templateTypeParameter.Name);
var ctor = template.TemplatedClass.Constructors
.FirstOrDefault(c => c.Parameters.Count == 1 && c.Parameters[0].Name == "v");
Assert.IsNotNull(ctor);
var paramType = ctor.Parameters[0].Type as TemplateParameterType;
Assert.IsNotNull(paramType);
Assert.AreEqual(templateTypeParameter, paramType.Parameter);
Assert.AreEqual(6, template.Specializations.Count);
Assert.AreEqual(TemplateSpecializationKind.ExplicitInstantiationDefinition, template.Specializations[0].SpecializationKind);
Assert.AreEqual(TemplateSpecializationKind.ExplicitInstantiationDefinition, template.Specializations[4].SpecializationKind);
Assert.AreEqual(TemplateSpecializationKind.Undeclared, template.Specializations[5].SpecializationKind);
var typeDef = AstContext.FindTypedef("TestTemplateClassInt").FirstOrDefault();
Assert.IsNotNull(typeDef, "Couldn't find TestTemplateClassInt typedef.");
var integerInst = typeDef.Type as TemplateSpecializationType;
Assert.AreEqual(1, integerInst.Arguments.Count);
var intArgument = integerInst.Arguments[0];
Assert.AreEqual(new BuiltinType(PrimitiveType.Int), intArgument.Type.Type);
ClassTemplateSpecialization classTemplateSpecialization;
Assert.IsTrue(typeDef.Type.TryGetDeclaration(out classTemplateSpecialization));
Assert.AreSame(classTemplateSpecialization.TemplatedDecl.TemplatedClass, template.TemplatedClass);
}
[Test]
public void TestDeprecatedAttrs()
{
var deprecated_func = AstContext.FindFunction("deprecated_func");
Assert.IsNotNull(deprecated_func);
Assert.IsTrue(deprecated_func.First().IsDeprecated);
var non_deprecated_func = AstContext.FindFunction("non_deprecated_func");
Assert.IsNotNull(non_deprecated_func);
Assert.IsFalse(non_deprecated_func.First().IsDeprecated);
}
[Test]
public void TestFindClassInNamespace()
{
Assert.IsNotNull(AstContext.FindClass("HiddenInNamespace").FirstOrDefault());
}
[Test]
public void TestLineNumber()
{
Assert.AreEqual(70, AstContext.FindClass("HiddenInNamespace").First().LineNumberStart);
}
[Test]
public void TestLineNumberOfFriend()
{
Assert.AreEqual(93, AstContext.FindFunction("operator+").First().LineNumberStart);
}
static string StripWindowsNewLines(string text)
{
return text.ReplaceLineBreaks(string.Empty);
}
[Test]
public void TestSignature()
{
Assert.AreEqual("void testSignature()", AstContext.FindFunction("testSignature").Single().Signature);
Assert.AreEqual("void testImpl()",
StripWindowsNewLines(AstContext.FindFunction("testImpl").Single().Signature));
Assert.AreEqual("void testConstSignature() const",
AstContext.FindClass("HasConstFunction").Single().FindMethod("testConstSignature").Signature);
Assert.AreEqual("void testConstSignatureWithTrailingMacro() const",
AstContext.FindClass("HasConstFunction").Single().FindMethod("testConstSignatureWithTrailingMacro").Signature);
// TODO: restore when the const of a return type is fixed properly
//Assert.AreEqual("const int& testConstRefSignature()", AstContext.FindClass("HasConstFunction").Single().FindMethod("testConstRefSignature").Signature);
//Assert.AreEqual("const int& testStaticConstRefSignature()", AstContext.FindClass("HasConstFunction").Single().FindMethod("testStaticConstRefSignature").Signature);
}
[Test]
public void TestAmbiguity()
{
new CheckAmbiguousFunctions { Context = Driver.Context }.VisitASTContext(AstContext);
Assert.IsTrue(AstContext.FindClass("HasAmbiguousFunctions").Single().FindMethod("ambiguous").IsAmbiguous);
}
[Test]
public void TestAtomics()
{
var type = AstContext.FindClass("Atomics").Single().Fields
.Find(f => f.Name == "AtomicInt").Type as BuiltinType;
Assert.IsTrue(type != null && type.IsPrimitiveType(PrimitiveType.Int));
}
[Test]
public void TestMacroLineNumber()
{
Assert.AreEqual(103, AstContext.FindClass("HasAmbiguousFunctions").First().Specifiers.Last().LineNumberStart);
}
[Test]
public void TestImplicitDeclaration()
{
Assert.IsTrue(AstContext.FindClass("ImplicitCtor").First().Constructors.First(
c => c.Parameters.Count == 0).IsImplicit);
}
[Test]
public void TestSpecializationArguments()
{
var classTemplate = AstContext.FindDecl<ClassTemplate>("TestSpecializationArguments").FirstOrDefault();
Assert.IsTrue(classTemplate.Specializations[0].Arguments[0].Type.Type.IsPrimitiveType(PrimitiveType.Int));
}
[Test]
public void TestFunctionInstantiatedFrom()
{
var classTemplate = AstContext.FindDecl<ClassTemplate>("TestSpecializationArguments").FirstOrDefault();
Assert.AreEqual(classTemplate.Specializations[0].Constructors.First(
c => !c.IsCopyConstructor && !c.IsMoveConstructor).InstantiatedFrom,
classTemplate.TemplatedClass.Constructors.First(c => !c.IsCopyConstructor && !c.IsMoveConstructor));
}
[Test]
public void TestCompletionOfClassTemplates()
{
var templates = AstContext.FindDecl<ClassTemplate>("ForwardedTemplate").ToList();
var template = templates.Single(t => t.DebugText.Replace("\r", string.Empty) ==
"template <typename T>\r\nclass ForwardedTemplate\r\n{\r\n}".Replace("\r", string.Empty));
Assert.IsFalse(template.IsIncomplete);
}
[Test]
public void TestOriginalNamesOfSpecializations()
{
var template = AstContext.FindDecl<ClassTemplate>("TestSpecializationArguments").First();
Assert.That(template.Specializations[0].Constructors.First().QualifiedName,
Is.Not.EqualTo(template.Specializations[1].Constructors.First().QualifiedName));
}
[Test]
public void TestPrintingConstPointerWithConstType()
{
var cppTypePrinter = new CppTypePrinter(Context) { ResolveTypeMaps = false };
cppTypePrinter.PushScope(TypePrintScopeKind.Qualified);
var builtin = new BuiltinType(PrimitiveType.Char);
var pointee = new QualifiedType(builtin, new TypeQualifiers { IsConst = true });
var pointer = new QualifiedType(new PointerType(pointee), new TypeQualifiers { IsConst = true });
string type = pointer.Visit(cppTypePrinter);
Assert.That(type, Is.EqualTo("const char* const"));
}
[Test]
public void TestPrintingSpecializationWithConstValue()
{
var template = AstContext.FindDecl<ClassTemplate>("TestSpecializationArguments").First();
var cppTypePrinter = new CppTypePrinter(Context);
cppTypePrinter.PushScope(TypePrintScopeKind.Qualified);
Assert.That(template.Specializations.Last().Visit(cppTypePrinter).Type,
Is.EqualTo("TestSpecializationArguments<const TestASTEnumItemByName>"));
}
[Test]
public void TestLayoutBase()
{
var @class = AstContext.FindCompleteClass("HasConstFunction");
Assert.That(@class.Layout.Bases.Count, Is.EqualTo(0));
}
[Test]
public void TestFunctionSpecifications()
{
var constExpr = AstContext.FindFunction("constExpr").First();
Assert.IsTrue(constExpr.IsConstExpr);
var noExcept = AstContext.FindFunction("noExcept").First();
Assert.That(((FunctionType) noExcept.FunctionType.Type).ExceptionSpecType,
Is.EqualTo(ExceptionSpecType.BasicNoexcept));
var noExceptTrue = AstContext.FindFunction("noExceptTrue").First();
Assert.That(((FunctionType) noExceptTrue.FunctionType.Type).ExceptionSpecType,
Is.EqualTo(ExceptionSpecType.NoexceptTrue));
var noExceptFalse = AstContext.FindFunction("noExceptFalse").First();
Assert.That(((FunctionType) noExceptFalse.FunctionType.Type).ExceptionSpecType,
Is.EqualTo(ExceptionSpecType.NoexceptFalse));
var regular = AstContext.FindFunction("testSignature").First();
Assert.IsFalse(regular.IsConstExpr);
var regularFunctionType = (FunctionType) regular.FunctionType.Type;
Assert.That(regularFunctionType.ExceptionSpecType,
Is.EqualTo(ExceptionSpecType.None));
}
[Test]
public void TestFunctionSpecializationInfo()
{
var functionWithSpecInfo = AstContext.TranslationUnits.Find(
t => t.IsValid && t.FileName == "AST.h").Functions.First(
f => f.Name == "functionWithSpecInfo" && !f.IsDependent);
var @float = new QualifiedType(new BuiltinType(PrimitiveType.Float));
Assert.That(functionWithSpecInfo.SpecializationInfo.Arguments.Count, Is.EqualTo(2));
foreach (var arg in functionWithSpecInfo.SpecializationInfo.Arguments)
Assert.That(arg.Type, Is.EqualTo(@float));
}
[Test]
public void TestVolatile()
{
var cppTypePrinter = new CppTypePrinter(Context);
cppTypePrinter.PushScope(TypePrintScopeKind.Qualified);
var builtin = new BuiltinType(PrimitiveType.Char);
var pointee = new QualifiedType(builtin, new TypeQualifiers { IsConst = true, IsVolatile = true });
var type = pointee.Visit(cppTypePrinter).Type;
Assert.That(type, Is.EqualTo("const volatile char"));
}
[Test]
public void TestFindFunctionInNamespace()
{
var function = AstContext.FindFunction("Math::function").FirstOrDefault();
Assert.That(function, Is.Not.Null);
}
[Test]
public void TestPrintNestedInSpecialization()
{
var template = AstContext.FindDecl<ClassTemplate>("TestTemplateClass").First();
var cppTypePrinter = new CppTypePrinter(Context);
cppTypePrinter.PushScope(TypePrintScopeKind.Qualified);
Assert.That(template.Specializations[4].Classes.First().Visit(cppTypePrinter).Type,
Is.EqualTo("TestTemplateClass<Math::Complex>::NestedInTemplate"));
}
[Test]
public void TestPrintQualifiedSpecialization()
{
var functionWithSpecializationArg = AstContext.FindFunction("functionWithSpecializationArg").First();
var cppTypePrinter = new CppTypePrinter(Context);
cppTypePrinter.PushScope(TypePrintScopeKind.Qualified);
Assert.That(functionWithSpecializationArg.Parameters[0].Visit(cppTypePrinter).Type,
Is.EqualTo("const TestTemplateClass<int>"));
}
[Test]
public void TestDependentNameType()
{
var template = AstContext.FindDecl<ClassTemplate>(
"TestSpecializationArguments").First();
var type = template.TemplatedClass.Fields[0].Type.Visit(
new CSharpTypePrinter(Driver.Context));
Assert.That($"{type}",
Is.EqualTo("global::Test.TestTemplateClass<T>.NestedInTemplate"));
}
[Test]
public void TestTemplateConstructorName()
{
new CleanInvalidDeclNamesPass { Context = Driver.Context }.VisitASTContext(AstContext);
var template = AstContext.FindClass("TestTemplateClass").First();
foreach (var constructor in template.Constructors)
Assert.That(constructor.Name, Is.EqualTo("TestTemplateClass<T>"));
}
[Test]
public void TestClassContext()
{
var @classA = AstContext.FindClass("ClassA").First();
Assert.That(@classA.Classes.Count, Is.EqualTo(0));
Assert.That(@classA.Redeclarations.Count, Is.EqualTo(0));
var @classB = AstContext.FindClass("ClassB").First();
Assert.That(@classB.Redeclarations.Count, Is.EqualTo(1));
var @classC = AstContext.FindClass("ClassC").First();
Assert.That(@classC.Redeclarations.Count, Is.EqualTo(2));
}
[Test]
public void TestPrivateCCtorCopyAssignment()
{
Class @class = AstContext.FindCompleteClass("HasPrivateCCtorCopyAssignment");
Assert.That(@class.Constructors.Any(c => c.Parameters.Count == 0), Is.True);
Assert.That(@class.Constructors.Any(c => c.IsCopyConstructor), Is.True);
Assert.That(@class.Methods.Any(o => o.OperatorKind == CXXOperatorKind.Equal), Is.True);
}
[Test]
public void TestCompletionSpecializationInFunction()
{
Function function = AstContext.FindFunction("returnIncompleteTemplateSpecialization").First();
function.ReturnType.Type.TryGetClass(out Class specialization);
Assert.That(specialization.IsIncomplete, Is.False);
}
[Test]
public void TestPreprocessedEntities()
{
var unit = AstContext.TranslationUnits.First(u => u.FileName == "AST.h");
var macro = unit.PreprocessedEntities.OfType<MacroDefinition>()
.FirstOrDefault(exp => exp.Name == "MACRO");
Assert.NotNull(macro);
Assert.AreEqual("(x, y, z) x##y##z", macro.Expression);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using NuGet.Packaging.Core;
using NuGet.Versioning;
namespace Sleet
{
/// <summary>
/// PackageIndexFile is a simple json index of all ids and versions contained in the feed.
/// </summary>
public class PackageIndexFile : IndexFileBase, IAddRemovePackages, IPackagesLookup, ISymbolsAddRemovePackages, ISymbolsPackagesLookup, IApplyOperations
{
public PackageIndexFile(SleetContext context, string path)
: this(context, path, persistWhenEmpty: false)
{
}
public PackageIndexFile(SleetContext context, string path, bool persistWhenEmpty)
: base(context, path, persistWhenEmpty)
{
}
public PackageIndexFile(SleetContext context, ISleetFile file, bool persistWhenEmpty)
: base(context, file, persistWhenEmpty)
{
}
public Task AddPackageAsync(PackageInput packageInput)
{
return AddPackagesAsync(new[] { packageInput });
}
public Task RemovePackageAsync(PackageIdentity package)
{
return RemovePackagesAsync(new[] { package });
}
public async Task AddPackagesAsync(IEnumerable<PackageInput> packageInputs)
{
// Load existing index
var sets = await GetPackageSetsAsync();
// Add package
await sets.Packages.AddPackagesAsync(packageInputs);
// Write file
await CreateAsync(sets);
}
public async Task RemovePackagesAsync(IEnumerable<PackageIdentity> packages)
{
// Load existing index
var sets = await GetPackageSetsAsync();
var save = false;
// Remove package
foreach (var package in packages)
{
save |= sets.Packages.Index.Remove(package);
}
if (save)
{
// Create updated index
await CreateAsync(sets);
}
}
public async Task AddSymbolsPackageAsync(PackageInput packageInput)
{
// Load existing index
var sets = await GetPackageSetsAsync();
// Add package
await sets.Symbols.AddPackageAsync(packageInput);
// Write file
await CreateAsync(sets);
}
public async Task RemoveSymbolsPackageAsync(PackageIdentity package)
{
// Load existing index
var sets = await GetPackageSetsAsync();
// Remove package
if (sets.Symbols.Index.Remove(package))
{
// Create updated index
await CreateAsync(sets);
}
}
/// <summary>
/// Creates a set of all indexed packages
/// </summary>
public async Task<ISet<PackageIdentity>> GetPackagesAsync()
{
var sets = await GetPackageSetsAsync();
return sets.Packages.Index;
}
public async Task<ISet<PackageIdentity>> GetSymbolsPackagesAsync()
{
var sets = await GetPackageSetsAsync();
return sets.Symbols.Index;
}
public async Task<ISet<PackageIdentity>> GetSymbolsPackagesByIdAsync(string packageId)
{
var packages = await GetSymbolsPackagesAsync();
return GetSetForId(packageId, packages);
}
public async Task<ISet<NuGetVersion>> GetPackageVersions(string packageId)
{
var packages = await GetPackagesByIdAsync(packageId);
return new SortedSet<NuGetVersion>(packages.Select(e => e.Version));
}
public async Task<ISet<NuGetVersion>> GetSymbolsPackageVersions(string packageId)
{
var packages = await GetSymbolsPackagesByIdAsync(packageId);
return new SortedSet<NuGetVersion>(packages.Select(e => e.Version));
}
/// <summary>
/// Returns all packages in the feed.
/// Id -> Version
/// </summary>
public async Task<PackageSets> GetPackageSetsAsync()
{
var index = new PackageSets();
if (await File.ExistsWithFetch(Context.Log, Context.Token))
{
var json = await GetJsonOrTemplateAsync();
var packagesNode = json["packages"] as JObject;
if (packagesNode == null)
{
throw new InvalidDataException("Packages node missing from sleet.packageindex.json");
}
index.Packages = GetPackageSetFromJson(packagesNode);
var symbolsNode = json["symbols"] as JObject;
// This node may not exist for older feeds
if (symbolsNode != null)
{
index.Symbols = GetPackageSetFromJson(symbolsNode);
}
}
return index;
}
private static PackageSet GetPackageSetFromJson(JObject packagesNode)
{
var result = new PackageSet();
foreach (var property in packagesNode.Properties())
{
var versions = (JArray)property.Value;
var id = property.Name;
foreach (var versionEntry in versions)
{
var packageVersion = NuGetVersion.Parse(versionEntry.ToObject<string>());
result.Index.Add(new PackageIdentity(id, packageVersion));
}
}
return result;
}
/// <summary>
/// Find all versions of a package.
/// </summary>
public async Task<ISet<PackageIdentity>> GetPackagesByIdAsync(string packageId)
{
var sets = await GetPackageSetsAsync();
return GetSetForId(packageId, sets.Packages.Index);
}
/// <summary>
/// True if the package exists in the index.
/// </summary>
public async Task<bool> Exists(string packageId, NuGetVersion version)
{
if (packageId == null)
{
throw new ArgumentNullException(nameof(packageId));
}
if (version == null)
{
throw new ArgumentNullException(nameof(version));
}
var byId = await GetPackagesByIdAsync(packageId);
return byId.Contains(new PackageIdentity(packageId, version));
}
public Task<bool> Exists(PackageIdentity package)
{
if (package == null)
{
throw new ArgumentNullException(nameof(package));
}
return Exists(package.Id, package.Version);
}
/// <summary>
/// True if the symbols package exists in the index.
/// </summary>
public async Task<bool> SymbolsExists(string packageId, NuGetVersion version)
{
if (packageId == null)
{
throw new ArgumentNullException(nameof(packageId));
}
if (version == null)
{
throw new ArgumentNullException(nameof(version));
}
var byId = await GetSymbolsPackagesByIdAsync(packageId);
return byId.Contains(new PackageIdentity(packageId, version));
}
public Task<bool> SymbolsExists(PackageIdentity package)
{
if (package == null)
{
throw new ArgumentNullException(nameof(package));
}
return SymbolsExists(package.Id, package.Version);
}
/// <summary>
/// Create the file directly without loading the previous file.
/// </summary>
public async Task CreateAsync(PackageSets index)
{
using (var timer = PerfEntryWrapper.CreateModifyTimer(File, Context))
{
// Create updated index
var json = CreateJson(index);
var isEmpty = (index.Packages.Index.Count < 1) && (index.Symbols.Index.Count < 1);
await SaveAsync(json, isEmpty);
}
}
/// <summary>
/// Empty json file.
/// </summary>
protected override Task<JObject> GetJsonTemplateAsync()
{
return Task.FromResult(new JObject
{
{ "packages", new JObject() },
{ "symbols", new JObject() }
});
}
private static JObject CreateJson(PackageSets index)
{
var json = new JObject
{
{ "packages", CreatePackageSetJson(index.Packages) },
{ "symbols", CreatePackageSetJson(index.Symbols) }
};
return json;
}
private static JObject CreatePackageSetJson(PackageSet packages)
{
var json = new JObject();
var groups = packages.Index.GroupBy(e => e.Id, StringComparer.OrdinalIgnoreCase).ToList();
foreach (var group in groups.OrderBy(e => e.Key, StringComparer.OrdinalIgnoreCase))
{
var versionArray = new JArray(group.OrderByDescending(e => e.Version)
.Select(e => e.Version.ToFullString()));
if (versionArray.Count > 0)
{
json.Add(group.Key, versionArray);
}
}
return json;
}
private static SortedSet<PackageIdentity> GetSetForId(string packageId, IEnumerable<PackageIdentity> packages)
{
return new SortedSet<PackageIdentity>(packages.Where(e => StringComparer.OrdinalIgnoreCase.Equals(packageId, e.Id)));
}
public override async Task<bool> IsEmpty()
{
var sets = await GetPackageSetsAsync();
return sets.Packages.Index.Count == 0 && sets.Symbols.Index.Count == 0;
}
public virtual Task ApplyOperationsAsync(SleetOperations operations)
{
return OperationsUtility.ApplyAddRemoveAsync(this, operations);
}
public Task PreLoadAsync(SleetOperations operations)
{
// Noop
return Task.FromResult(true);
}
}
}
| |
using AutoMapper.Internal;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
namespace AutoMapper.Execution
{
public static class ProxyGenerator
{
private static readonly MethodInfo DelegateCombine = typeof(Delegate).GetMethod(nameof(Delegate.Combine), new[] { typeof(Delegate), typeof(Delegate) });
private static readonly MethodInfo DelegateRemove = typeof(Delegate).GetMethod(nameof(Delegate.Remove));
private static readonly EventInfo PropertyChanged = typeof(INotifyPropertyChanged).GetEvent(nameof(INotifyPropertyChanged.PropertyChanged));
private static readonly ConstructorInfo ProxyBaseCtor = typeof(ProxyBase).GetConstructor(Type.EmptyTypes);
private static readonly ModuleBuilder ProxyModule = CreateProxyModule();
private static readonly LockingConcurrentDictionary<TypeDescription, Type> ProxyTypes = new LockingConcurrentDictionary<TypeDescription, Type>(EmitProxy);
private static ModuleBuilder CreateProxyModule()
{
var builder = AssemblyBuilder.DefineDynamicAssembly(typeof(Mapper).Assembly.GetName(), AssemblyBuilderAccess.Run);
return builder.DefineDynamicModule("AutoMapper.Proxies.emit");
}
private static Type EmitProxy(TypeDescription typeDescription)
{
var interfaceType = typeDescription.Type;
var typeBuilder = GenerateType();
GenerateConstructor();
FieldBuilder propertyChangedField = null;
if (typeof(INotifyPropertyChanged).IsAssignableFrom(interfaceType))
{
GeneratePropertyChanged();
}
GenerateFields();
return typeBuilder.CreateTypeInfo().AsType();
TypeBuilder GenerateType()
{
var propertyNames = string.Join("_", typeDescription.AdditionalProperties.Select(p => p.Name));
var typeName = $"Proxy_{interfaceType.FullName}_{typeDescription.GetHashCode()}_{propertyNames}";
const int MaxTypeNameLength = 1023;
typeName = typeName.Substring(0, Math.Min(MaxTypeNameLength, typeName.Length));
Debug.WriteLine(typeName, "Emitting proxy type");
return ProxyModule.DefineType(typeName,
TypeAttributes.Class | TypeAttributes.Sealed | TypeAttributes.Public, typeof(ProxyBase),
interfaceType.IsInterface ? new[] { interfaceType } : Type.EmptyTypes);
}
void GeneratePropertyChanged()
{
propertyChangedField = typeBuilder.DefineField(PropertyChanged.Name, typeof(PropertyChangedEventHandler), FieldAttributes.Private);
EventAccessor(PropertyChanged.AddMethod, DelegateCombine);
EventAccessor(PropertyChanged.RemoveMethod, DelegateRemove);
}
void EventAccessor(MethodInfo method, MethodInfo delegateMethod)
{
var eventAccessor = typeBuilder.DefineMethod(method.Name,
MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName |
MethodAttributes.NewSlot | MethodAttributes.Virtual, typeof(void),
new[] { typeof(PropertyChangedEventHandler) });
var addIl = eventAccessor.GetILGenerator();
addIl.Emit(OpCodes.Ldarg_0);
addIl.Emit(OpCodes.Dup);
addIl.Emit(OpCodes.Ldfld, propertyChangedField);
addIl.Emit(OpCodes.Ldarg_1);
addIl.Emit(OpCodes.Call, delegateMethod);
addIl.Emit(OpCodes.Castclass, typeof(PropertyChangedEventHandler));
addIl.Emit(OpCodes.Stfld, propertyChangedField);
addIl.Emit(OpCodes.Ret);
typeBuilder.DefineMethodOverride(eventAccessor, method);
}
void GenerateFields()
{
var fieldBuilders = new Dictionary<string, PropertyEmitter>();
foreach (var property in PropertiesToImplement())
{
if (fieldBuilders.TryGetValue(property.Name, out var propertyEmitter))
{
if (propertyEmitter.PropertyType != property.Type && (property.CanWrite || !property.Type.IsAssignableFrom(propertyEmitter.PropertyType)))
{
throw new ArgumentException($"The interface has a conflicting property {property.Name}", nameof(interfaceType));
}
}
else
{
fieldBuilders.Add(property.Name, new PropertyEmitter(typeBuilder, property, propertyChangedField));
}
}
}
List<PropertyDescription> PropertiesToImplement()
{
var propertiesToImplement = new List<PropertyDescription>();
var allInterfaces = new List<Type>(interfaceType.GetInterfaces()) { interfaceType };
// first we collect all properties, those with setters before getters in order to enable less specific redundant getters
foreach (var property in
allInterfaces.Where(intf => intf != typeof(INotifyPropertyChanged))
.SelectMany(intf => intf.GetProperties())
.Select(p => new PropertyDescription(p))
.Concat(typeDescription.AdditionalProperties))
{
if (property.CanWrite)
{
propertiesToImplement.Insert(0, property);
}
else
{
propertiesToImplement.Add(property);
}
}
return propertiesToImplement;
}
void GenerateConstructor()
{
var constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Type.EmptyTypes);
var ctorIl = constructorBuilder.GetILGenerator();
ctorIl.Emit(OpCodes.Ldarg_0);
ctorIl.Emit(OpCodes.Call, ProxyBaseCtor);
ctorIl.Emit(OpCodes.Ret);
}
}
public static Type GetProxyType(Type interfaceType) => ProxyTypes.GetOrAdd(new TypeDescription(interfaceType));
public static Type GetSimilarType(Type sourceType, IEnumerable<PropertyDescription> additionalProperties) =>
ProxyTypes.GetOrAdd(new TypeDescription(sourceType, additionalProperties));
class PropertyEmitter
{
private static readonly MethodInfo ProxyBaseNotifyPropertyChanged = typeof(ProxyBase).GetInstanceMethod("NotifyPropertyChanged");
private readonly FieldBuilder _fieldBuilder;
private readonly MethodBuilder _getterBuilder;
private readonly PropertyBuilder _propertyBuilder;
private readonly MethodBuilder _setterBuilder;
public PropertyEmitter(TypeBuilder owner, PropertyDescription property, FieldBuilder propertyChangedField)
{
var name = property.Name;
var propertyType = property.Type;
_fieldBuilder = owner.DefineField($"<{name}>", propertyType, FieldAttributes.Private);
_propertyBuilder = owner.DefineProperty(name, PropertyAttributes.None, propertyType, null);
_getterBuilder = owner.DefineMethod($"get_{name}",
MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig |
MethodAttributes.SpecialName, propertyType, Type.EmptyTypes);
ILGenerator getterIl = _getterBuilder.GetILGenerator();
getterIl.Emit(OpCodes.Ldarg_0);
getterIl.Emit(OpCodes.Ldfld, _fieldBuilder);
getterIl.Emit(OpCodes.Ret);
_propertyBuilder.SetGetMethod(_getterBuilder);
if (!property.CanWrite)
{
return;
}
_setterBuilder = owner.DefineMethod($"set_{name}",
MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig |
MethodAttributes.SpecialName, typeof(void), new[] { propertyType });
ILGenerator setterIl = _setterBuilder.GetILGenerator();
setterIl.Emit(OpCodes.Ldarg_0);
setterIl.Emit(OpCodes.Ldarg_1);
setterIl.Emit(OpCodes.Stfld, _fieldBuilder);
if (propertyChangedField != null)
{
setterIl.Emit(OpCodes.Ldarg_0);
setterIl.Emit(OpCodes.Dup);
setterIl.Emit(OpCodes.Ldfld, propertyChangedField);
setterIl.Emit(OpCodes.Ldstr, name);
setterIl.Emit(OpCodes.Call, ProxyBaseNotifyPropertyChanged);
}
setterIl.Emit(OpCodes.Ret);
_propertyBuilder.SetSetMethod(_setterBuilder);
}
public Type PropertyType => _propertyBuilder.PropertyType;
}
}
public abstract class ProxyBase
{
public ProxyBase() { }
protected void NotifyPropertyChanged(PropertyChangedEventHandler handler, string method) =>
handler?.Invoke(this, new PropertyChangedEventArgs(method));
}
public readonly struct TypeDescription : IEquatable<TypeDescription>
{
public readonly Type Type;
public readonly PropertyDescription[] AdditionalProperties;
public TypeDescription(Type type) : this(type, Array.Empty<PropertyDescription>()) { }
public TypeDescription(Type type, IEnumerable<PropertyDescription> additionalProperties)
{
Type = type ?? throw new ArgumentNullException(nameof(type));
if (additionalProperties == null)
{
throw new ArgumentNullException(nameof(additionalProperties));
}
AdditionalProperties = additionalProperties.OrderBy(p => p.Name).ToArray();
}
public override int GetHashCode()
{
var hashCode = new HashCode();
hashCode.Add(Type);
foreach (var property in AdditionalProperties)
{
hashCode.Add(property);
}
return hashCode.ToHashCode();
}
public override bool Equals(object other) => other is TypeDescription description && Equals(description);
public bool Equals(TypeDescription other) => Type == other.Type && AdditionalProperties.SequenceEqual(other.AdditionalProperties);
public static bool operator ==(TypeDescription left, TypeDescription right) => left.Equals(right);
public static bool operator !=(TypeDescription left, TypeDescription right) => !left.Equals(right);
}
[DebuggerDisplay("{Name}-{Type.Name}")]
public readonly struct PropertyDescription : IEquatable<PropertyDescription>
{
public readonly string Name;
public readonly Type Type;
public readonly bool CanWrite;
public PropertyDescription(string name, Type type, bool canWrite = true)
{
Name = name;
Type = type;
CanWrite = canWrite;
}
public PropertyDescription(PropertyInfo property)
{
Name = property.Name;
Type = property.PropertyType;
CanWrite = property.CanWrite;
}
public override int GetHashCode() => HashCode.Combine(Name, Type, CanWrite);
public override bool Equals(object other) => other is PropertyDescription description && Equals(description);
public bool Equals(PropertyDescription other) => Name == other.Name && Type == other.Type && CanWrite == other.CanWrite;
public static bool operator ==(PropertyDescription left, PropertyDescription right) => left.Equals(right);
public static bool operator !=(PropertyDescription left, PropertyDescription right) => !left.Equals(right);
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// VirtualNetworkPeeringsOperations operations.
/// </summary>
internal partial class VirtualNetworkPeeringsOperations : IServiceOperations<NetworkClient>, IVirtualNetworkPeeringsOperations
{
/// <summary>
/// Initializes a new instance of the VirtualNetworkPeeringsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal VirtualNetworkPeeringsOperations(NetworkClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkClient
/// </summary>
public NetworkClient Client { get; private set; }
/// <summary>
/// Deletes the specified virtual network peering.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='virtualNetworkPeeringName'>
/// The name of the virtual network peering.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified virtual network peering.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='virtualNetworkPeeringName'>
/// The name of the virtual network peering.
/// </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<VirtualNetworkPeering>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName");
}
if (virtualNetworkPeeringName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkPeeringName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-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("virtualNetworkName", virtualNetworkName);
tracingParameters.Add("virtualNetworkPeeringName", virtualNetworkPeeringName);
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/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings/{virtualNetworkPeeringName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName));
_url = _url.Replace("{virtualNetworkPeeringName}", System.Uri.EscapeDataString(virtualNetworkPeeringName));
_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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<VirtualNetworkPeering>();
_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<VirtualNetworkPeering>(_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 peering in the specified virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='virtualNetworkPeeringName'>
/// The name of the peering.
/// </param>
/// <param name='virtualNetworkPeeringParameters'>
/// Parameters supplied to the create or update virtual network peering
/// 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<VirtualNetworkPeering>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, VirtualNetworkPeering virtualNetworkPeeringParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<VirtualNetworkPeering> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, virtualNetworkPeeringParameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all virtual network peerings in a virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="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<VirtualNetworkPeering>>> ListWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-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("virtualNetworkName", virtualNetworkName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<VirtualNetworkPeering>>();
_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<VirtualNetworkPeering>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified virtual network peering.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='virtualNetworkPeeringName'>
/// The name of the virtual network peering.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName");
}
if (virtualNetworkPeeringName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkPeeringName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-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("virtualNetworkName", virtualNetworkName);
tracingParameters.Add("virtualNetworkPeeringName", virtualNetworkPeeringName);
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/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings/{virtualNetworkPeeringName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName));
_url = _url.Replace("{virtualNetworkPeeringName}", System.Uri.EscapeDataString(virtualNetworkPeeringName));
_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 != 200 && (int)_statusCode != 204 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a peering in the specified virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='virtualNetworkPeeringName'>
/// The name of the peering.
/// </param>
/// <param name='virtualNetworkPeeringParameters'>
/// Parameters supplied to the create or update virtual network peering
/// 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<VirtualNetworkPeering>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, VirtualNetworkPeering virtualNetworkPeeringParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName");
}
if (virtualNetworkPeeringName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkPeeringName");
}
if (virtualNetworkPeeringParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkPeeringParameters");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-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("virtualNetworkName", virtualNetworkName);
tracingParameters.Add("virtualNetworkPeeringName", virtualNetworkPeeringName);
tracingParameters.Add("virtualNetworkPeeringParameters", virtualNetworkPeeringParameters);
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/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings/{virtualNetworkPeeringName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName));
_url = _url.Replace("{virtualNetworkPeeringName}", System.Uri.EscapeDataString(virtualNetworkPeeringName));
_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(virtualNetworkPeeringParameters != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(virtualNetworkPeeringParameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<VirtualNetworkPeering>();
_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<VirtualNetworkPeering>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<VirtualNetworkPeering>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all virtual network peerings in a virtual network.
/// </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<VirtualNetworkPeering>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<VirtualNetworkPeering>>();
_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<VirtualNetworkPeering>>(_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 File Description
//-----------------------------------------------------------------------------
// CustomAvatarAnimationSample.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using CustomAvatarAnimation;
#endregion
namespace CustomAvatarAnimationSample
{
/// <summary>
/// The possible animation types on the avatar.
/// </summary>
public enum AnimationType { Idle1, Idle2, Idle3, Idle4, Walk,
Jump, Kick, Punch, Faint };
/// <summary>
/// This is the main type for your game
/// </summary>
public class CustomAvatarAnimationSampleGame : Microsoft.Xna.Framework.Game
{
#region Graphics Data
GraphicsDeviceManager graphics;
// Model to display the ground
Model groundModel;
// World, View and Projection matricies used for rendering
Matrix world;
Matrix view;
Matrix projection;
// the following constants control the camera's default position
const float CameraDefaultArc = MathHelper.Pi / 10;
const float CameraDefaultRotation = MathHelper.Pi;
const float CameraDefaultDistance = 2.5f;
// Camera values
float cameraArc = CameraDefaultArc;
float cameraRotation = CameraDefaultRotation;
float cameraDistance = CameraDefaultDistance;
#endregion
#region Avatar Data
// The AvatarDescription and AvatarRenderer that are used to render the avatar
AvatarRenderer avatarRenderer;
AvatarDescription avatarDescription;
// Animations that will be used
IAvatarAnimation[] animations;
// Tells us if we are using an idle, walking, or other animations
AnimationType currentType;
#endregion
#region Fields
// Store the current and last gamepad state
GamePadState currentGamePadState;
GamePadState lastGamePadState;
// A random number generator for picking new idle animations
Random random = new Random();
#endregion
#region Initialization
/// <summary>
/// Creates a new AvatarCustomAnimationSample object.
/// </summary>
public CustomAvatarAnimationSampleGame()
{
// initialize the graphics
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
graphics.PreferredBackBufferWidth = 1280;
graphics.PreferredBackBufferHeight = 720;
graphics.PreferMultiSampling = true;
// initialize gamer services
Components.Add(new GamerServicesComponent(this));
SignedInGamer.SignedIn += new EventHandler<SignedInEventArgs>(SignedInGamer_SignedIn);
}
/// <summary>
/// Handle signed in gamer event as start avatar loading
/// </summary>
void SignedInGamer_SignedIn(object sender, SignedInEventArgs e)
{
// Only load the avatar for player one
if (e.Gamer.PlayerIndex == PlayerIndex.One)
{
// Load the player one avatar
LoadAvatar(e.Gamer);
}
}
/// <summary>
/// Load all graphical content.
/// </summary>
protected override void LoadContent()
{
// Load custom animations
CustomAvatarAnimationData animationData;
// We will use 8 different animations
animations = new IAvatarAnimation[9];
// Load the idle animations
for (int i = 0; i < 4; i++)
{
animations[i] = new AvatarAnimation(
(AvatarAnimationPreset)((int)AvatarAnimationPreset.Stand0 + i));
}
// Load the walk animation
animationData = Content.Load<CustomAvatarAnimationData>("Walk");
animations[4] = new CustomAvatarAnimationPlayer(animationData.Name, animationData.Length,
animationData.Keyframes, animationData.ExpressionKeyframes);
// Load the jump animation
animationData = Content.Load<CustomAvatarAnimationData>("Jump");
animations[5] = new CustomAvatarAnimationPlayer(animationData.Name, animationData.Length,
animationData.Keyframes, animationData.ExpressionKeyframes);
// Load the kick animation
animationData = Content.Load<CustomAvatarAnimationData>("Kick");
animations[6] = new CustomAvatarAnimationPlayer(animationData.Name, animationData.Length,
animationData.Keyframes, animationData.ExpressionKeyframes);
// Load the punch animation
animationData = Content.Load<CustomAvatarAnimationData>("Punch");
animations[7] = new CustomAvatarAnimationPlayer(animationData.Name, animationData.Length,
animationData.Keyframes, animationData.ExpressionKeyframes);
// Load the faint animation
animationData = Content.Load<CustomAvatarAnimationData>("Faint");
animations[8] = new CustomAvatarAnimationPlayer(animationData.Name, animationData.Length,
animationData.Keyframes, animationData.ExpressionKeyframes);
// Load the model for the ground
groundModel = Content.Load<Model>("ground");
// Select a random idle animation to start
PlayRandomIdle();
// Create the projection to use
projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f),
GraphicsDevice.Viewport.AspectRatio, .01f, 200.0f);
world = Matrix.Identity;
}
#endregion
#region Updating
protected override void Update(GameTime gameTime)
{
// Get the current gamepad state and store the old
lastGamePadState = currentGamePadState;
currentGamePadState = GamePad.GetState(PlayerIndex.One);
// Allows the game to exit
if (currentGamePadState.Buttons.Back == ButtonState.Pressed)
this.Exit();
// Handle gamer input
HandleAvatarInput(gameTime);
HandleCameraInput();
// Loop animation if we are walking
bool loopAnimation = (currentType == AnimationType.Walk);
// Update the current animation
animations[(int)currentType].Update(gameTime.ElapsedGameTime, loopAnimation);
// Check to see if we need to end the animation
if (!loopAnimation)
{
if (animations[(int)currentType].CurrentPosition ==
animations[(int)currentType].Length)
{
// Start new idle animation
PlayRandomIdle();
}
}
base.Update(gameTime);
}
#endregion
#region Drawing
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// Draw the ground first since the avatar has transparent parts
groundModel.Draw(Matrix.Identity, view, projection);
// Draw the avatar
if (avatarRenderer != null)
{
avatarRenderer.Draw(animations[(int)currentType]);
}
base.Draw(gameTime);
}
#endregion
#region Input Handling
/// <summary>
/// Check for user input to play animations on the avatar
/// </summary>
private void HandleAvatarInput(GameTime gameTime)
{
// Check to see if the user wants to load a random avatar
// by pressing the Right Shoulder
if (currentGamePadState.Buttons.RightShoulder == ButtonState.Pressed &&
lastGamePadState.Buttons.RightShoulder != ButtonState.Pressed)
{
LoadRandomAvatar();
}
// Check to see if the user wants to load the users avatar
// by pressing the Left Shoulder
else if (currentGamePadState.Buttons.LeftShoulder == ButtonState.Pressed &&
lastGamePadState.Buttons.LeftShoulder != ButtonState.Pressed)
{
// Load the users avatar
if (SignedInGamer.SignedInGamers[PlayerIndex.One] != null)
{
LoadAvatar(SignedInGamer.SignedInGamers[PlayerIndex.One]);
}
}
// Check to see if the user wants to play one of the other
// animations by pressing one of the gamepad buttons
if (currentGamePadState.Buttons.A == ButtonState.Pressed &&
lastGamePadState.Buttons.A != ButtonState.Pressed)
{
PlayAnimation(AnimationType.Jump);
}
if (currentGamePadState.Buttons.B == ButtonState.Pressed &&
lastGamePadState.Buttons.B != ButtonState.Pressed)
{
PlayAnimation(AnimationType.Kick);
}
if (currentGamePadState.Buttons.X == ButtonState.Pressed &&
lastGamePadState.Buttons.X != ButtonState.Pressed)
{
PlayAnimation(AnimationType.Punch);
}
if (currentGamePadState.Buttons.Y == ButtonState.Pressed &&
lastGamePadState.Buttons.Y != ButtonState.Pressed)
{
PlayAnimation(AnimationType.Faint);
}
// Update the avatars location
UpdateAvatarMovement(gameTime);
}
/// <summary>
/// Update the avatars movement based on user input
/// </summary>
private void UpdateAvatarMovement(GameTime gameTime)
{
// Create vector from the left thumbstick location
Vector2 leftThumbStick = currentGamePadState.ThumbSticks.Left;
// The direction for our Avatar
Vector3 avatarForward = world.Forward;
// The amount we want to translate
Vector3 translate = Vector3.Zero;
// Clamp thumbstick to make sure the user really wants to move
if (leftThumbStick.Length() > 0.2f)
{
// Create our direction vector
leftThumbStick.Normalize();
// Find the new avatar forward
avatarForward.X = leftThumbStick.X;
avatarForward.Y = 0;
avatarForward.Z = -leftThumbStick.Y;
// Translate the thumbstick using the current camera rotation
avatarForward = Vector3.Transform(avatarForward,
Matrix.CreateRotationY(cameraRotation));
avatarForward.Normalize();
// Determine the amount of translation
translate = avatarForward
* ((float)gameTime.ElapsedGameTime.TotalMilliseconds
* 0.0009f);
// We are now walking
currentType = AnimationType.Walk;
}
else
{
// If we were walking last frame pick a random idle animation
if (currentType == AnimationType.Walk)
{
PlayRandomIdle();
}
}
// Update the world matrix
world.Forward = avatarForward;
// Normalize the matrix
world.Right = Vector3.Cross(world.Forward, Vector3.Up);
world.Right = Vector3.Normalize(world.Right);
world.Up = Vector3.Cross(world.Right, world.Forward);
world.Up = Vector3.Normalize(world.Up);
// Add translation
world.Translation += translate;
// Set the avatar renderer world matrix
if (avatarRenderer != null)
{
avatarRenderer.World = world;
}
}
/// <summary>
/// Move camera based on user input
/// </summary>
private void HandleCameraInput()
{
// should we reset the camera?
if (currentGamePadState.Buttons.RightStick == ButtonState.Pressed)
{
cameraArc = CameraDefaultArc;
cameraDistance = CameraDefaultDistance;
cameraRotation = CameraDefaultRotation;
}
// Update Camera
cameraArc -= currentGamePadState.ThumbSticks.Right.Y * 0.05f;
cameraRotation += currentGamePadState.ThumbSticks.Right.X * 0.1f;
cameraDistance += currentGamePadState.Triggers.Left * 0.1f;
cameraDistance -= currentGamePadState.Triggers.Right * 0.1f;
// Limit the camera movement
if (cameraDistance > 5.0f)
cameraDistance = 5.0f;
else if (cameraDistance < 2.0f)
cameraDistance = 2.0f;
if (cameraArc > MathHelper.Pi / 5)
cameraArc = MathHelper.Pi / 5;
else if (cameraArc < -(MathHelper.Pi / 5))
cameraArc = -(MathHelper.Pi / 5);
// Update the camera position
Vector3 cameraPos = new Vector3(0, cameraDistance, cameraDistance);
cameraPos = Vector3.Transform(cameraPos, Matrix.CreateRotationX(cameraArc));
cameraPos = Vector3.Transform(cameraPos,
Matrix.CreateRotationY(cameraRotation));
cameraPos += world.Translation;
// Create new view matrix
view = Matrix.CreateLookAt(cameraPos, world.Translation
+ new Vector3(0, 1.2f, 0), Vector3.Up);
// Set the new view on the avatar renderer
if (avatarRenderer != null)
{
avatarRenderer.View = view;
}
}
#endregion
#region Animation Selection
/// <summary>
/// Start playing a random idle animation
/// </summary>
private void PlayRandomIdle()
{
PlayAnimation((AnimationType)random.Next((int)AnimationType.Idle4));
}
/// <summary>
/// Start playing one of the other animations that were loaded
/// </summary>
private void PlayAnimation(AnimationType animation)
{
animations[(int)animation].CurrentPosition = TimeSpan.Zero;
currentType = animation;
}
#endregion
#region Avatar Loading
/// <summary>
/// Load the avatar for a gamer
/// </summary>
private void LoadAvatar(Gamer gamer)
{
UnloadAvatar();
AvatarDescription.BeginGetFromGamer(gamer, LoadAvatarDescription, null);
}
/// <summary>
/// AsyncCallback for loading the AvatarDescription
/// </summary>
private void LoadAvatarDescription(IAsyncResult result)
{
// Get the AvatarDescription for the gamer
avatarDescription = AvatarDescription.EndGetFromGamer(result);
// Load the AvatarRenderer if description is valid
if (avatarDescription.IsValid)
{
avatarRenderer = new AvatarRenderer(avatarDescription);
avatarRenderer.Projection = projection;
}
// Load random for an invalid description
else
{
LoadRandomAvatar();
}
}
/// <summary>
/// Load a random avatar
/// </summary>
private void LoadRandomAvatar()
{
UnloadAvatar();
avatarDescription = AvatarDescription.CreateRandom();
avatarRenderer = new AvatarRenderer(avatarDescription);
avatarRenderer.Projection = projection;
}
/// <summary>
/// Unloads the current avatar
/// </summary>
private void UnloadAvatar()
{
// Dispose the current Avatar
if (avatarRenderer != null)
{
avatarRenderer.Dispose();
avatarRenderer = null;
}
}
#endregion
#region Entry Point
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main(string[] args)
{
using (CustomAvatarAnimationSampleGame game =
new CustomAvatarAnimationSampleGame())
{
game.Run();
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using KabMan.Data;
using DevExpress.XtraGrid.Views.Grid;
namespace KabMan.Forms
{
public partial class DCCDetailList : DevExpress.XtraEditors.XtraForm
{
Int64 san1vtport1oldvalue = 0;
Int64 san1vtport2oldvalue = 0;
Int64 san2vtport1oldvalue = 0;
Int64 san2vtport2oldvalue = 0;
#region Properties
private object _DCC_ID = null;
/// <summary>
/// Gets DCC ID which associated to this form
/// </summary>
public long DCC_ID
{
get
{
if (_DCC_ID != null)
{
return Convert.ToInt64(this._DCC_ID);
}
return 0;
}
}
private object _SanGroupId11;
public long SanGroupId11
{
get
{
if (_SanGroupId11 != null)
{
return Convert.ToInt64(this._SanGroupId11);
}
return 0;
}
}
private object _SanGroupId12;
public long SanGroupId12
{
get
{
if (_SanGroupId12 != null)
{
return Convert.ToInt64(this._SanGroupId12);
}
return 0;
}
}
private object _SanGroupId21;
public long SanGroupId21
{
get
{
if (_SanGroupId21 != null)
{
return Convert.ToInt64(this._SanGroupId21);
}
return 0;
}
}
private object _SanGroupId22;
public long SanGroupId22
{
get
{
if (_SanGroupId22!= null)
{
return Convert.ToInt64(this._SanGroupId22);
}
return 0;
}
}
#endregion
#region Constructor
public DCCDetailList()
{
this.Icon = Resources.GetIcon("KabManIcon");
InitializeComponent();
}
public DCCDetailList(object argDCC_ID, string text)
{
this.Icon = Resources.GetIcon("KabManIcon");
this._DCC_ID = argDCC_ID;
// Get sunids from connection object
DataSet ds = DBAssistant.ExecProcedure(sproc.DCC_Select_ById, new Object[] { "@ID", argDCC_ID });
if (ds != null)
{
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
this._SanGroupId11 = ds.Tables[0].Rows[0]["SanGroup11_ID"]; //VTPort1San1
this._SanGroupId12 = ds.Tables[0].Rows[0]["SanGroup12_ID"]; //VTPort1San2
this._SanGroupId21 = ds.Tables[0].Rows[0]["SanGroup21_ID"]; //VTPort2San1
this._SanGroupId22 = ds.Tables[0].Rows[0]["SanGroup22_ID"]; //VTPort2San2
}
}
}
InitializeComponent();
this.Text = text;
}
public DCCDetailList(object argDCC_ID, Int64 sanGroupId11, Int64 sanGroupId12, Int64 sanGroupId21, Int64 sanGroupId22)
{
this.Icon = Resources.GetIcon("KabManIcon");
this._DCC_ID = argDCC_ID;
this._SanGroupId11 = sanGroupId11;
this._SanGroupId12 = sanGroupId12;
this._SanGroupId21 = sanGroupId21;
this._SanGroupId22 = sanGroupId22;
InitializeComponent();
}
public DCCDetailList(object argDCCID, string text, Int64 sanGroupId11, Int64 sanGroupId12, Int64 sanGroupId21, Int64 sanGroupId22)
{
this._DCC_ID = argDCCID;
this._SanGroupId11 = sanGroupId11;
this._SanGroupId12 = sanGroupId12;
this._SanGroupId21 = sanGroupId21;
this._SanGroupId22 = sanGroupId22;
InitializeComponent();
this.Text = text;
}
#endregion
private void DCCDetailList_Load(object sender, EventArgs e)
{
if (this.DCC_ID > 0)
{
DCCSan1Grid.DataSource = DBAssistant.ExecProcedure(sproc.DCCDetail_Select_BySanValue, new object[] { "@DCC_ID", this.DCC_ID, "@SanValue", 1 }).Tables[0];
DCCSan2Grid.DataSource = DBAssistant.ExecProcedure(sproc.DCCDetail_Select_BySanValue, new object[] { "@DCC_ID", this.DCC_ID, "@SanValue", 2 }).Tables[0];
LoadSanValues();
}
}
private void LoadSanValues()
{
setVTPortRepositoryDataSource4SAN11();
setVTPortRepositoryDataSource4SAN12();
setVTPortRepositoryDataSource4SAN21();
setVTPortRepositoryDataSource4SAN22();
}
private void setVTPortRepositoryDataSource4SAN11()
{
DataSet ds = DBAssistant.ExecProcedure(sproc.VTPort_For_Dcc1_BySanGroupId, new object[] { "@SanID", SanGroupId11 });
repVtPort1San1.DataSource = ds.Tables[0];
}
private void setVTPortRepositoryDataSource4SAN12()
{
DataSet ds = DBAssistant.ExecProcedure(sproc.VTPort_For_Dcc2_BySanGroupId, new object[] { "@SanID", SanGroupId21 });
repVtPort1San2.DataSource = ds.Tables[0];
}
private void setVTPortRepositoryDataSource4SAN21()
{
DataSet ds = DBAssistant.ExecProcedure(sproc.VTPort_For_Dcc1_BySanGroupId, new object[] { "@SanID", SanGroupId12 });
repVtPort2San1.DataSource = ds.Tables[0];
}
private void setVTPortRepositoryDataSource4SAN22()
{
DataSet ds = DBAssistant.ExecProcedure(sproc.VTPort_For_Dcc2_BySanGroupId, new object[] { "@SanID", SanGroupId22 });
repVtPort2San2.DataSource = ds.Tables[0];
}
private void CSan1View_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
{
if (e.Column == gridColumn4)
{
object dccDetailId = CSan1View.GetRowCellValue(e.RowHandle, "ID");
object newVtPortId = e.Value;
if (Int64.Parse(newVtPortId.ToString()) != this.san1vtport1oldvalue)
{
if (XtraMessageBox.Show("Do you wish to edit this row?", "Confirmation", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
DBAssistant.ExecProcedure(sproc.DccDetail_VTPort_Update, new object[] { "@DccDetailID", dccDetailId, "@NewObjectId", newVtPortId, "@Type", "1" });
this.san1vtport1oldvalue = Int64.Parse(newVtPortId.ToString());
LoadSanValues();
}
}
}
else if (e.Column == gridColumn7)
{
object dccDetailId = CSan1View.GetRowCellValue(e.RowHandle, "ID");
object newVtPortId = e.Value;
if (Int64.Parse(newVtPortId.ToString()) != this.san1vtport2oldvalue)
{
if (XtraMessageBox.Show("Do you wish to edit this row?", "Confirmation", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
DBAssistant.ExecProcedure(sproc.DccDetail_VTPort_Update, new object[] { "@DccDetailID", dccDetailId, "@NewObjectId", newVtPortId, "@Type", "2" });
this.san1vtport2oldvalue = Int64.Parse(newVtPortId.ToString());
LoadSanValues();
}
}
}
}
private void CSan1View_ShownEditor(object sender, EventArgs e)
{
//GridView gridView = sender as GridView;
//if (gridView.FocusedColumn == gridColumn4 || gridView.FocusedColumn == gridColumn7)
// if (XtraMessageBox.Show("Do you wish to edit this row?", "Confirmation", MessageBoxButtons.YesNo) == DialogResult.No)
// gridView.CloseEditor();
// else
// {
// if (gridView.ActiveEditor != null)
// gridView.ActiveEditor.SelectAll();
// }
}
private void CSan2View_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
{
if (e.Column == gridColumn17)
{
object dccDetailId = CSan2View.GetRowCellValue(e.RowHandle, "ID");
object newVtPortId = e.Value;
if (Int64.Parse(newVtPortId.ToString()) != this.san2vtport1oldvalue)
{
if (XtraMessageBox.Show("Do you wish to edit this row?", "Confirmation", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
DBAssistant.ExecProcedure(sproc.DccDetail_VTPort_Update, new object[] { "@DccDetailID", dccDetailId, "@NewObjectId", newVtPortId, "@Type", "1" });
this.san2vtport1oldvalue = Int64.Parse(newVtPortId.ToString());
LoadSanValues();
}
}
}
else if (e.Column == gridColumn19)
{
object dccDetailId = CSan2View.GetRowCellValue(e.RowHandle, "ID");
object newVtPortId = e.Value;
if (Int64.Parse(newVtPortId.ToString()) != this.san2vtport2oldvalue)
{
if (XtraMessageBox.Show("Do you wish to edit this row?", "Confirmation", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
DBAssistant.ExecProcedure(sproc.DccDetail_VTPort_Update, new object[] { "@DccDetailID", dccDetailId, "@NewObjectId", newVtPortId, "@Type", "2" });
this.san2vtport2oldvalue = Int64.Parse(newVtPortId.ToString());
LoadSanValues();
}
}
}
}
private void CSan2View_ShownEditor(object sender, EventArgs e)
{
//GridView gridView = sender as GridView;
//if (gridView.FocusedColumn == gridColumn4 || gridView.FocusedColumn == gridColumn7)
// if (XtraMessageBox.Show("Do you wish to edit this row?", "Confirmation", MessageBoxButtons.YesNo) == DialogResult.No)
// gridView.CloseEditor();
// else
// {
// if (gridView.ActiveEditor != null)
// gridView.ActiveEditor.SelectAll();
// }
}
private void CSan1View_RowClick(object sender, RowClickEventArgs e)
{
//object vtport1id = CSan1View.GetRowCellValue(e.RowHandle, "VTPORT1DetailId");
//object vtport2id = CSan1View.GetRowCellValue(e.RowHandle, "VTPORT2DetailId");
//this.san1vtport1oldvalue = Int64.Parse(vtport1id.ToString());
//this.san1vtport2oldvalue = Int64.Parse(vtport2id.ToString());
}
private void CSan1View_Click(object sender, EventArgs e)
{
object vtport1id = this.CSan1View.GetFocusedRowCellValue("VTPORT1DetailId");
object vtport2id = this.CSan1View.GetFocusedRowCellValue("VTPORT2DetailId");
this.san1vtport1oldvalue = Int64.Parse(vtport1id.ToString());
this.san1vtport2oldvalue = Int64.Parse(vtport2id.ToString());
}
private void CSan2View_Click(object sender, EventArgs e)
{
object vtport1id = this.CSan1View.GetFocusedRowCellValue("VTPORT1DetailId");
object vtport2id = this.CSan1View.GetFocusedRowCellValue("VTPORT2DetailId");
this.san2vtport1oldvalue = Int64.Parse(vtport1id.ToString());
this.san2vtport2oldvalue = Int64.Parse(vtport2id.ToString());
}
private void repVtPort2San1_Popup(object sender, EventArgs e)
{
//DataView view = ((DataTable)repVtPort2San1.DataSource).DefaultView;
//view.RowFilter = "VTPORT1Id=" + CSan2View.GetFocusedRowCellValue("VTPORT1Id").ToString();
}
private void repVtPort2San1_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
{
//DataView view = ((DataTable)repVtPort2San1.DataSource).DefaultView;
//view.RowFilter = "";
}
private void repVtPort1San2_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
{
//DataView view = ((DataTable)repVtPort1San2.DataSource).DefaultView;
//view.RowFilter = "";
}
private void repVtPort1San2_Popup(object sender, EventArgs e)
{
//DataView view = ((DataTable)repVtPort1San2.DataSource).DefaultView;
//view.RowFilter = "VTPORT2Id=" + CSan1View.GetFocusedRowCellValue("VTPORT2Id").ToString();
}
private void repVtPort2San2_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
{
//DataView view = ((DataTable)repVtPort2San2.DataSource).DefaultView;
//view.RowFilter = "";
}
private void repVtPort2San2_Popup(object sender, EventArgs e)
{
//DataView view = ((DataTable)repVtPort2San2.DataSource).DefaultView;
//view.RowFilter = "VTPORT2Id=" + CSan2View.GetFocusedRowCellValue("VTPORT2Id").ToString();
}
private void repVtPort1San1_Popup(object sender, EventArgs e)
{
//DataView view = ((DataTable)repVtPort1San1.DataSource).DefaultView;
//view.RowFilter = "VTPORT1Id=" + CSan1View.GetFocusedRowCellValue("VTPORT1Id").ToString();
}
private void repVtPort1San1_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
{
//DataView view = ((DataTable)repVtPort1San1.DataSource).DefaultView;
//view.RowFilter = "";
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using Xunit;
namespace System.IO.Tests
{
public static class PathTests
{
[Theory]
[InlineData(null, null, null)]
[InlineData(null, "exe", null)]
[InlineData("", "", "")]
[InlineData("file.exe", null, "file")]
[InlineData("file.exe", "", "file.")]
[InlineData("file", "exe", "file.exe")]
[InlineData("file", ".exe", "file.exe")]
[InlineData("file.txt", "exe", "file.exe")]
[InlineData("file.txt", ".exe", "file.exe")]
[InlineData("file.txt.bin", "exe", "file.txt.exe")]
[InlineData("dir/file.t", "exe", "dir/file.exe")]
[InlineData("dir/file.exe", "t", "dir/file.t")]
[InlineData("dir/file", "exe", "dir/file.exe")]
public static void ChangeExtension(string path, string newExtension, string expected)
{
if (expected != null)
expected = expected.Replace('/', Path.DirectorySeparatorChar);
if (path != null)
path = path.Replace('/', Path.DirectorySeparatorChar);
Assert.Equal(expected, Path.ChangeExtension(path, newExtension));
}
[Theory]
[InlineData(null, null)]
[InlineData("", null)]
[InlineData(".", "")]
[InlineData("..", "")]
[InlineData("baz", "")]
public static void GetDirectoryName(string path, string expected)
{
Assert.Equal(expected, Path.GetDirectoryName(path));
}
[Theory]
[InlineData(@"dir/baz", "dir")]
[InlineData(@"dir\baz", "dir")]
[InlineData(@"dir\baz\bar", @"dir\baz")]
[InlineData(@"dir\\baz", "dir")]
[InlineData(@" dir\baz", " dir")]
[InlineData(@" C:\dir\baz", @"C:\dir")]
[InlineData(@"..\..\files.txt", @"..\..")]
[InlineData(@"C:\", null)]
[InlineData(@"C:", null)]
[PlatformSpecific(PlatformID.Windows)]
public static void GetDirectoryName_Windows(string path, string expected)
{
Assert.Equal(expected, Path.GetDirectoryName(path));
}
[Theory]
[InlineData(@"dir/baz", @"dir")]
[InlineData(@"dir//baz", @"dir")]
[InlineData(@"dir\baz", @"")]
[InlineData(@"dir/baz/bar", @"dir/baz")]
[InlineData(@"../../files.txt", @"../..")]
[InlineData(@"/", null)]
[PlatformSpecific(PlatformID.AnyUnix)]
public static void GetDirectoryName_Unix(string path, string expected)
{
Assert.Equal(expected, Path.GetDirectoryName(path));
}
[Fact]
public static void GetDirectoryName_CurrentDirectory()
{
string curDir = Directory.GetCurrentDirectory();
Assert.Equal(curDir, Path.GetDirectoryName(Path.Combine(curDir, "baz")));
Assert.Equal(null, Path.GetDirectoryName(Path.GetPathRoot(curDir)));
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Fact]
public static void GetDirectoryName_ControlCharacters_Unix()
{
Assert.Equal(new string('\t', 1), Path.GetDirectoryName(Path.Combine(new string('\t', 1), "file")));
Assert.Equal(new string('\b', 2), Path.GetDirectoryName(Path.Combine(new string('\b', 2), "fi le")));
Assert.Equal(new string('\v', 3), Path.GetDirectoryName(Path.Combine(new string('\v', 3), "fi\nle")));
Assert.Equal(new string('\n', 4), Path.GetDirectoryName(Path.Combine(new string('\n', 4), "fi\rle")));
}
[Theory]
[InlineData("file.exe", ".exe")]
[InlineData("file", "")]
[InlineData(null, null)]
[InlineData("file.", "")]
[InlineData("file.s", ".s")]
[InlineData("test/file", "")]
[InlineData("test/file.extension", ".extension")]
public static void GetExtension(string path, string expected)
{
if (path != null)
{
path = path.Replace('/', Path.DirectorySeparatorChar);
}
Assert.Equal(expected, Path.GetExtension(path));
Assert.Equal(!string.IsNullOrEmpty(expected), Path.HasExtension(path));
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Theory]
[InlineData("file.e xe", ".e xe")]
[InlineData("file. ", ". ")]
[InlineData(" file. ", ". ")]
[InlineData(" file.extension", ".extension")]
[InlineData("file.exten\tsion", ".exten\tsion")]
public static void GetExtension_Unix(string path, string expected)
{
Assert.Equal(expected, Path.GetExtension(path));
Assert.Equal(!string.IsNullOrEmpty(expected), Path.HasExtension(path));
}
public static IEnumerable<object[]> GetFileName_TestData()
{
yield return new object[] { null, null };
yield return new object[] { ".", "." };
yield return new object[] { "..", ".." };
yield return new object[] { "file", "file" };
yield return new object[] { "file.", "file." };
yield return new object[] { "file.exe", "file.exe" };
yield return new object[] { Path.Combine("baz", "file.exe"), "file.exe" };
yield return new object[] { Path.Combine("bar", "baz", "file.exe"), "file.exe" };
yield return new object[] { Path.Combine("bar", "baz", "file.exe") + Path.DirectorySeparatorChar, "" };
}
[Theory]
[MemberData(nameof(GetFileName_TestData))]
public static void GetFileName(string path, string expected)
{
Assert.Equal(expected, Path.GetFileName(path));
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Fact]
public static void GetFileName_Unix()
{
Assert.Equal(" . ", Path.GetFileName(" . "));
Assert.Equal(" .. ", Path.GetFileName(" .. "));
Assert.Equal("fi le", Path.GetFileName("fi le"));
Assert.Equal("fi le", Path.GetFileName("fi le"));
Assert.Equal("fi le", Path.GetFileName(Path.Combine("b \r\n ar", "fi le")));
}
public static IEnumerable<object[]> GetFileNameWithoutExtension_TestData()
{
yield return new object[] { null, null };
yield return new object[] { "", "" };
yield return new object[] { "file", "file" };
yield return new object[] { "file.exe", "file" };
yield return new object[] { Path.Combine("bar", "baz", "file.exe"), "file" };
yield return new object[] { Path.Combine("bar", "baz") + Path.DirectorySeparatorChar, "" };
}
[Theory]
[MemberData(nameof(GetFileNameWithoutExtension_TestData))]
public static void GetFileNameWithoutExtension(string path, string expected)
{
Assert.Equal(expected, Path.GetFileNameWithoutExtension(path));
}
[Fact]
public static void GetPathRoot()
{
Assert.Null(Path.GetPathRoot(null));
Assert.Equal(string.Empty, Path.GetPathRoot(string.Empty));
string cwd = Directory.GetCurrentDirectory();
Assert.Equal(cwd.Substring(0, cwd.IndexOf(Path.DirectorySeparatorChar) + 1), Path.GetPathRoot(cwd));
Assert.True(Path.IsPathRooted(cwd));
Assert.Equal(string.Empty, Path.GetPathRoot(@"file.exe"));
Assert.False(Path.IsPathRooted("file.exe"));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"\\test\unc\path\to\something", @"\\test\unc")]
[InlineData(@"\\a\b\c\d\e", @"\\a\b")]
[InlineData(@"\\a\b\", @"\\a\b")]
[InlineData(@"\\a\b", @"\\a\b")]
[InlineData(@"\\test\unc", @"\\test\unc")]
[InlineData(@"\\?\UNC\test\unc\path\to\something", @"\\?\UNC\test\unc")]
[InlineData(@"\\?\UNC\test\unc", @"\\?\UNC\test\unc")]
[InlineData(@"\\?\UNC\a\b", @"\\?\UNC\a\b")]
[InlineData(@"\\?\UNC\a\b\", @"\\?\UNC\a\b")]
[InlineData(@"\\?\C:\foo\bar.txt", @"\\?\C:\")]
public static void GetPathRoot_Windows_UncAndExtended(string value, string expected)
{
Assert.True(Path.IsPathRooted(value));
Assert.Equal(expected, Path.GetPathRoot(value));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"C:", @"C:")]
[InlineData(@"C:\", @"C:\")]
[InlineData(@"C:\\", @"C:\")]
[InlineData(@"C://", @"C:\")]
[InlineData(@"C:\foo", @"C:\")]
[InlineData(@"C:\\foo", @"C:\")]
[InlineData(@"C://foo", @"C:\")]
public static void GetPathRoot_Windows(string value, string expected)
{
Assert.True(Path.IsPathRooted(value));
Assert.Equal(expected, Path.GetPathRoot(value));
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Fact]
public static void GetPathRoot_Unix()
{
// slashes are normal filename characters
string uncPath = @"\\test\unc\path\to\something";
Assert.False(Path.IsPathRooted(uncPath));
Assert.Equal(string.Empty, Path.GetPathRoot(uncPath));
}
[Fact]
public static void GetRandomFileName()
{
char[] invalidChars = Path.GetInvalidFileNameChars();
var fileNames = new HashSet<string>();
for (int i = 0; i < 100; i++)
{
string s = Path.GetRandomFileName();
Assert.Equal(s.Length, 8 + 1 + 3);
Assert.Equal(s[8], '.');
Assert.Equal(-1, s.IndexOfAny(invalidChars));
Assert.True(fileNames.Add(s));
}
}
[Fact]
public static void GetInvalidPathChars()
{
Assert.NotNull(Path.GetInvalidPathChars());
Assert.NotSame(Path.GetInvalidPathChars(), Path.GetInvalidPathChars());
Assert.Equal((IEnumerable<char>)Path.GetInvalidPathChars(), Path.GetInvalidPathChars());
Assert.True(Path.GetInvalidPathChars().Length > 0);
Assert.All(Path.GetInvalidPathChars(), c =>
{
string bad = c.ToString();
Assert.Throws<ArgumentException>(() => Path.ChangeExtension(bad, "ok"));
Assert.Throws<ArgumentException>(() => Path.Combine(bad, "ok"));
Assert.Throws<ArgumentException>(() => Path.Combine("ok", "ok", bad));
Assert.Throws<ArgumentException>(() => Path.Combine("ok", "ok", bad, "ok"));
Assert.Throws<ArgumentException>(() => Path.Combine(bad, bad, bad, bad, bad));
Assert.Throws<ArgumentException>(() => Path.GetDirectoryName(bad));
Assert.Throws<ArgumentException>(() => Path.GetExtension(bad));
Assert.Throws<ArgumentException>(() => Path.GetFileName(bad));
Assert.Throws<ArgumentException>(() => Path.GetFileNameWithoutExtension(bad));
Assert.Throws<ArgumentException>(() => Path.GetFullPath(bad));
Assert.Throws<ArgumentException>(() => Path.GetPathRoot(bad));
Assert.Throws<ArgumentException>(() => Path.IsPathRooted(bad));
});
}
[Fact]
public static void GetInvalidFileNameChars()
{
Assert.NotNull(Path.GetInvalidFileNameChars());
Assert.NotSame(Path.GetInvalidFileNameChars(), Path.GetInvalidFileNameChars());
Assert.Equal((IEnumerable<char>)Path.GetInvalidFileNameChars(), Path.GetInvalidFileNameChars());
Assert.True(Path.GetInvalidFileNameChars().Length > 0);
}
[Fact]
[OuterLoop]
public static void GetInvalidFileNameChars_OtherCharsValid()
{
string curDir = Directory.GetCurrentDirectory();
var invalidChars = new HashSet<char>(Path.GetInvalidFileNameChars());
for (int i = 0; i < char.MaxValue; i++)
{
char c = (char)i;
if (!invalidChars.Contains(c))
{
string name = "file" + c + ".txt";
Assert.Equal(Path.Combine(curDir, name), Path.GetFullPath(name));
}
}
}
[Fact]
public static void GetTempPath_Default()
{
string tmpPath = Path.GetTempPath();
Assert.False(string.IsNullOrEmpty(tmpPath));
Assert.Equal(tmpPath, Path.GetTempPath());
Assert.Equal(Path.DirectorySeparatorChar, tmpPath[tmpPath.Length - 1]);
Assert.True(Directory.Exists(tmpPath));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"C:\Users\someuser\AppData\Local\Temp\", @"C:\Users\someuser\AppData\Local\Temp")]
[InlineData(@"C:\Users\someuser\AppData\Local\Temp\", @"C:\Users\someuser\AppData\Local\Temp\")]
[InlineData(@"C:\", @"C:\")]
[InlineData(@"C:\tmp\", @"C:\tmp")]
[InlineData(@"C:\tmp\", @"C:\tmp\")]
public static void GetTempPath_SetEnvVar_Windows(string expected, string newTempPath)
{
GetTempPath_SetEnvVar("TMP", expected, newTempPath);
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Theory]
[InlineData("/tmp/", "/tmp")]
[InlineData("/tmp/", "/tmp/")]
[InlineData("/", "/")]
[InlineData("/var/tmp/", "/var/tmp")]
[InlineData("/var/tmp/", "/var/tmp/")]
[InlineData("~/", "~")]
[InlineData("~/", "~/")]
[InlineData(".tmp/", ".tmp")]
[InlineData("./tmp/", "./tmp")]
[InlineData("/home/someuser/sometempdir/", "/home/someuser/sometempdir/")]
[InlineData("/home/someuser/some tempdir/", "/home/someuser/some tempdir/")]
[InlineData("/tmp/", null)]
public static void GetTempPath_SetEnvVar_Unix(string expected, string newTempPath)
{
GetTempPath_SetEnvVar("TMPDIR", expected, newTempPath);
}
private static void GetTempPath_SetEnvVar(string envVar, string expected, string newTempPath)
{
string original = Path.GetTempPath();
Assert.NotNull(original);
try
{
Environment.SetEnvironmentVariable(envVar, newTempPath);
Assert.Equal(
Path.GetFullPath(expected),
Path.GetFullPath(Path.GetTempPath()));
}
finally
{
Environment.SetEnvironmentVariable(envVar, original);
Assert.Equal(original, Path.GetTempPath());
}
}
[Fact]
public static void GetTempFileName()
{
string tmpFile = Path.GetTempFileName();
try
{
Assert.True(File.Exists(tmpFile));
Assert.Equal(".tmp", Path.GetExtension(tmpFile), ignoreCase: true, ignoreLineEndingDifferences: false, ignoreWhiteSpaceDifferences: false);
Assert.Equal(-1, tmpFile.IndexOfAny(Path.GetInvalidPathChars()));
using (FileStream fs = File.OpenRead(tmpFile))
{
Assert.Equal(0, fs.Length);
}
Assert.Equal(Path.Combine(Path.GetTempPath(), Path.GetFileName(tmpFile)), tmpFile);
}
finally
{
File.Delete(tmpFile);
}
}
[Fact]
public static void GetFullPath_InvalidArgs()
{
Assert.Throws<ArgumentNullException>(() => Path.GetFullPath(null));
Assert.Throws<ArgumentException>(() => Path.GetFullPath(string.Empty));
}
public static IEnumerable<object[]> GetFullPath_BasicExpansions_TestData()
{
string curDir = Directory.GetCurrentDirectory();
yield return new object[] { curDir, curDir }; // Current directory => current directory
yield return new object[] { ".", curDir }; // "." => current directory
yield return new object[] { "..", Path.GetDirectoryName(curDir) }; // "." => up a directory
yield return new object[] { Path.Combine(curDir, ".", ".", ".", ".", "."), curDir }; // "dir/./././." => "dir"
yield return new object[] { curDir + new string(Path.DirectorySeparatorChar, 3) + ".", curDir }; // "dir///." => "dir"
yield return new object[] { Path.Combine(curDir, "..", Path.GetFileName(curDir), ".", "..", Path.GetFileName(curDir)), curDir }; // "dir/../dir/./../dir" => "dir"
yield return new object[] { Path.Combine(Path.GetPathRoot(curDir), "somedir", ".."), Path.GetPathRoot(curDir) }; // "C:\somedir\.." => "C:\"
yield return new object[] { Path.Combine(Path.GetPathRoot(curDir), "."), Path.GetPathRoot(curDir) }; // "C:\." => "C:\"
yield return new object[] { Path.Combine(Path.GetPathRoot(curDir), "..", "..", "..", ".."), Path.GetPathRoot(curDir) }; // "C:\..\..\..\.." => "C:\"
yield return new object[] { Path.GetPathRoot(curDir) + new string(Path.DirectorySeparatorChar, 3), Path.GetPathRoot(curDir) }; // "C:\\\" => "C:\"
// Path longer than MaxPath that normalizes down to less than MaxPath
const int Iters = 10000;
var longPath = new StringBuilder(curDir, curDir.Length + (Iters * 2));
for (int i = 0; i < 10000; i++)
{
longPath.Append(Path.DirectorySeparatorChar).Append('.');
}
yield return new object[] { longPath.ToString(), curDir };
}
[Theory]
[MemberData(nameof(GetFullPath_BasicExpansions_TestData))]
public static void GetFullPath_BasicExpansions(string path, string expected)
{
Assert.Equal(expected, Path.GetFullPath(path));
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Fact]
public static void GetFullPath_Unix_Whitespace()
{
string curDir = Directory.GetCurrentDirectory();
Assert.Equal("/ / ", Path.GetFullPath("/ // "));
Assert.Equal(Path.Combine(curDir, " "), Path.GetFullPath(" "));
Assert.Equal(Path.Combine(curDir, "\r\n"), Path.GetFullPath("\r\n"));
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Theory]
[InlineData("http://www.microsoft.com")]
[InlineData("file://somefile")]
public static void GetFullPath_Unix_URIsAsFileNames(string uriAsFileName)
{
// URIs are valid filenames, though the multiple slashes will be consolidated in GetFullPath
Assert.Equal(
Path.Combine(Directory.GetCurrentDirectory(), uriAsFileName.Replace("//", "/")),
Path.GetFullPath(uriAsFileName));
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_NormalizedLongPathTooLong()
{
// Try out a long path that normalizes down to more than MaxPath
string curDir = Directory.GetCurrentDirectory();
const int Iters = 260;
var longPath = new StringBuilder(curDir, curDir.Length + (Iters * 4));
for (int i = 0; i < Iters; i++)
{
longPath.Append(Path.DirectorySeparatorChar).Append('a').Append(Path.DirectorySeparatorChar).Append('.');
}
// Now no longer throws unless over ~32K
Assert.NotNull(Path.GetFullPath(longPath.ToString()));
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_AlternateDataStreamsNotSupported()
{
// Throws via our invalid colon filtering
Assert.Throws<NotSupportedException>(() => Path.GetFullPath(@"bad:path"));
Assert.Throws<NotSupportedException>(() => Path.GetFullPath(@"C:\some\bad:path"));
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_URIFormatNotSupported()
{
// Throws via our invalid colon filtering
Assert.Throws<NotSupportedException>(() => Path.GetFullPath("http://www.microsoft.com"));
Assert.Throws<NotSupportedException>(() => Path.GetFullPath("file://www.microsoft.com"));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"bad::$DATA")]
[InlineData(@"C :")]
[InlineData(@"C :\somedir")]
public static void GetFullPath_Windows_NotSupportedExceptionPaths(string path)
{
// Many of these used to throw ArgumentException despite being documented as NotSupportedException
Assert.Throws<NotSupportedException>(() => Path.GetFullPath(path));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"C:...")]
[InlineData(@"C:...\somedir")]
[InlineData(@"\.. .\")]
[InlineData(@"\. .\")]
[InlineData(@"\ .\")]
public static void GetFullPath_Windows_LegacyArgumentExceptionPaths(string path)
{
// These paths are legitimate Windows paths that can be created without extended syntax.
// We now allow them through.
Path.GetFullPath(path);
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_MaxPathNotTooLong()
{
// Shouldn't throw anymore
Path.GetFullPath(@"C:\" + new string('a', 255) + @"\");
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_PathTooLong()
{
Assert.Throws<PathTooLongException>(() => Path.GetFullPath(@"C:\" + new string('a', short.MaxValue) + @"\"));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"C:\", @"C:\")]
[InlineData(@"C:\.", @"C:\")]
[InlineData(@"C:\..", @"C:\")]
[InlineData(@"C:\..\..", @"C:\")]
[InlineData(@"C:\A\..", @"C:\")]
[InlineData(@"C:\..\..\A\..", @"C:\")]
public static void GetFullPath_Windows_RelativeRoot(string path, string expected)
{
Assert.Equal(Path.GetFullPath(path), expected);
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_StrangeButLegalPaths()
{
// These are legal and creatable without using extended syntax if you use a trailing slash
// (such as "md ...\"). We used to filter these out, but now allow them to prevent apps from
// being blocked when they hit these paths.
string curDir = Directory.GetCurrentDirectory();
Assert.NotEqual(
Path.GetFullPath(curDir + Path.DirectorySeparatorChar),
Path.GetFullPath(curDir + Path.DirectorySeparatorChar + ". " + Path.DirectorySeparatorChar));
Assert.NotEqual(
Path.GetFullPath(Path.GetDirectoryName(curDir) + Path.DirectorySeparatorChar),
Path.GetFullPath(curDir + Path.DirectorySeparatorChar + "..." + Path.DirectorySeparatorChar));
Assert.NotEqual(
Path.GetFullPath(Path.GetDirectoryName(curDir) + Path.DirectorySeparatorChar),
Path.GetFullPath(curDir + Path.DirectorySeparatorChar + ".. " + Path.DirectorySeparatorChar));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"\\?\C:\ ")]
[InlineData(@"\\?\C:\ \ ")]
[InlineData(@"\\?\C:\ .")]
[InlineData(@"\\?\C:\ ..")]
[InlineData(@"\\?\C:\...")]
[InlineData(@"\\?\GLOBALROOT\")]
[InlineData(@"\\?\")]
[InlineData(@"\\?\.")]
[InlineData(@"\\?\..")]
[InlineData(@"\\?\\")]
[InlineData(@"\\?\C:\\")]
[InlineData(@"\\?\C:\|")]
[InlineData(@"\\?\C:\.")]
[InlineData(@"\\?\C:\..")]
[InlineData(@"\\?\C:\Foo\.")]
[InlineData(@"\\?\C:\Foo\..")]
[InlineData(@"\\?\UNC\")]
[InlineData(@"\\?\UNC\server")]
[InlineData(@"\\?\UNC\server\")]
[InlineData(@"\\?\UNC\server\\")]
[InlineData(@"\\?\UNC\server\..")]
[InlineData(@"\\?\UNC\server\share\.")]
[InlineData(@"\\?\UNC\server\share\..")]
[InlineData(@"\\?\UNC\a\b\\")]
[InlineData(@"\\.\UNC\")]
[InlineData(@"\\.\UNC\server")]
[InlineData(@"\\.\UNC\server\")]
[InlineData(@"\\.\UNC\server\\")]
[InlineData(@"\\.\UNC\server\..")]
[InlineData(@"\\.\UNC\server\share\.")]
[InlineData(@"\\.\UNC\server\share\..")]
[InlineData(@"\\.\UNC\a\b\\")]
[InlineData(@"\\.\")]
[InlineData(@"\\.\.")]
[InlineData(@"\\.\..")]
[InlineData(@"\\.\\")]
[InlineData(@"\\.\C:\\")]
[InlineData(@"\\.\C:\|")]
[InlineData(@"\\.\C:\.")]
[InlineData(@"\\.\C:\..")]
[InlineData(@"\\.\C:\Foo\.")]
[InlineData(@"\\.\C:\Foo\..")]
public static void GetFullPath_Windows_ValidExtendedPaths(string path)
{
// None of these should throw
if (path.StartsWith(@"\\?\"))
{
Assert.Equal(path, Path.GetFullPath(path));
}
else
{
Path.GetFullPath(path);
}
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"\\server\share", @"\\server\share")]
[InlineData(@"\\server\share", @" \\server\share")]
[InlineData(@"\\server\share\dir", @"\\server\share\dir")]
[InlineData(@"\\server\share", @"\\server\share\.")]
[InlineData(@"\\server\share", @"\\server\share\..")]
[InlineData(@"\\server\share\", @"\\server\share\ ")]
[InlineData(@"\\server\ share\", @"\\server\ share\")]
[InlineData(@"\\?\UNC\server\share", @"\\?\UNC\server\share")]
[InlineData(@"\\?\UNC\server\share\dir", @"\\?\UNC\server\share\dir")]
[InlineData(@"\\?\UNC\server\share\. ", @"\\?\UNC\server\share\. ")]
[InlineData(@"\\?\UNC\server\share\.. ", @"\\?\UNC\server\share\.. ")]
[InlineData(@"\\?\UNC\server\share\ ", @"\\?\UNC\server\share\ ")]
[InlineData(@"\\?\UNC\server\ share\", @"\\?\UNC\server\ share\")]
public static void GetFullPath_Windows_UNC_Valid(string expected, string input)
{
Assert.Equal(expected, Path.GetFullPath(input));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"\\")]
[InlineData(@"\\server")]
[InlineData(@"\\server\")]
[InlineData(@"\\server\\")]
[InlineData(@"\\server\..")]
public static void GetFullPath_Windows_UNC_Invalid(string invalidPath)
{
Assert.Throws<ArgumentException>(() => Path.GetFullPath(invalidPath));
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_83Paths()
{
// Create a temporary file name with a name longer than 8.3 such that it'll need to be shortened.
string tempFilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".txt");
File.Create(tempFilePath).Dispose();
try
{
// Get its short name
var sb = new StringBuilder(260);
if (GetShortPathName(tempFilePath, sb, sb.Capacity) > 0) // only proceed if we could successfully create the short name
{
string shortName = sb.ToString();
// Make sure the shortened name expands back to the original one
Assert.Equal(tempFilePath, Path.GetFullPath(shortName));
// Should work with device paths that aren't well-formed extended syntax
Assert.Equal(@"\\.\" + tempFilePath, Path.GetFullPath(@"\\.\" + shortName));
Assert.Equal(@"\\?\" + tempFilePath, Path.GetFullPath(@"//?/" + shortName));
// Shouldn't mess with well-formed extended syntax
Assert.Equal(@"\\?\" + shortName, Path.GetFullPath(@"\\?\" + shortName));
// Validate case where short name doesn't expand to a real file
string invalidShortName = @"S:\DOESNT~1\USERNA~1.RED\LOCALS~1\Temp\bg3ylpzp";
Assert.Equal(invalidShortName, Path.GetFullPath(invalidShortName));
// Same thing, but with a long path that normalizes down to a short enough one
const int Iters = 1000;
var shortLongName = new StringBuilder(invalidShortName, invalidShortName.Length + (Iters * 2));
for (int i = 0; i < Iters; i++)
{
shortLongName.Append(Path.DirectorySeparatorChar).Append('.');
}
Assert.Equal(invalidShortName, Path.GetFullPath(shortLongName.ToString()));
}
}
finally
{
File.Delete(tempFilePath);
}
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData('*')]
[InlineData('?')]
public static void GetFullPath_Windows_Wildcards(char wildcard)
{
Assert.Throws<ArgumentException>("path", () => Path.GetFullPath("test" + wildcard + "ing"));
}
// Windows-only P/Invoke to create 8.3 short names from long names
[DllImport("kernel32.dll", CharSet = CharSet.Ansi)]
private static extern uint GetShortPathName(string lpszLongPath, StringBuilder lpszShortPath, int cchBuffer);
}
}
| |
//
// Booter.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
// Crazy Banshee Boot Procedure
//
// [Exec or DBus Activation] <---------------------------------------------------------.
// | |
// v |
// [Bootloader (Banshee.exe)] |
// | |
// v yes |
// <org.bansheeproject.Banshee?> -------> [Load DBus Proxy Client (Halie.exe)] -----. |
// |no | |
// v yes | |
// <org.bansheeproject.CollectionIndexer?> -------> [Tell Indexer to Reboot] -----/IPC/'
// |no |
// v yes |
// <command line contains --indexer?> -------> [Load Indexer Client (Beroe.exe)] |
// |no |
// v yes |
// <command line contains --client=XYZ> -------> [Load XYZ Client] |
// |no |
// v |
// [Load Primary Interface Client (Nereid.exe)] <-----------------------------------'
//
using System;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Mono.Unix;
using DBus;
using Hyena;
using Hyena.CommandLine;
using Banshee.Base;
using Banshee.ServiceStack;
using Banshee.Collection.Indexer;
namespace Booter
{
public static class Booter
{
public static void Main ()
{
Application.InitializePaths ();
if (CheckHelpVersion ()) {
return;
}
if (!DBusConnection.GrabDefaultName ()) {
// DBus Command/Query/File Proxy Client
BootClient ("Halie");
NotifyStartupComplete ();
} else if (DBusConnection.NameHasOwner ("CollectionIndexer")) {
// Tell the existing indexer to start Banshee when it's done
IIndexerClient indexer = DBusServiceManager.FindInstance<IIndexerClient> ("CollectionIndexer", "/IndexerClient");
try {
indexer.Hello ();
indexer.RebootWhenFinished (Environment.GetCommandLineArgs ());
Log.Warning ("The Banshee indexer is currently running. Banshee will be started when the indexer finishes.");
} catch (Exception e) {
Log.Error ("CollectionIndexer found on the Bus, but doesn't say Hello", e);
}
} else if (ApplicationContext.CommandLine.Contains ("indexer")) {
// Indexer Client
BootClient ("Beroe");
} else if (ApplicationContext.CommandLine.Contains ("client")) {
BootClient (Path.GetFileNameWithoutExtension (ApplicationContext.CommandLine["client"]));
} else {
BootClient ("Nereid");
}
}
private static void BootClient (string clientName)
{
AppDomain.CurrentDomain.ExecuteAssembly (Path.Combine (Path.GetDirectoryName (
Assembly.GetEntryAssembly ().Location), String.Format ("{0}.exe", clientName)));
}
[DllImport ("libgdk-win32-2.0-0.dll")]
private static extern bool gdk_init_check (IntPtr argc, IntPtr argv);
[DllImport ("libgdk-win32-2.0-0.dll")]
private static extern void gdk_notify_startup_complete ();
private static void NotifyStartupComplete ()
{
try {
if (gdk_init_check (IntPtr.Zero, IntPtr.Zero)) {
gdk_notify_startup_complete ();
}
} catch (Exception e) {
Log.Error ("Problem with NotifyStartupComplete", e);
}
}
private static bool CheckHelpVersion ()
{
if (ApplicationContext.CommandLine.ContainsStart ("help")) {
ShowHelp ();
return true;
} else if (ApplicationContext.CommandLine.Contains ("version")) {
ShowVersion ();
return true;
}
return false;
}
private static void ShowHelp ()
{
Console.WriteLine ("Usage: {0} [options...] [files|URIs...]", "banshee");
Console.WriteLine ();
string css_file = Path.Combine (Paths.ApplicationData, "gtk.css").Replace (
Environment.GetFolderPath (Environment.SpecialFolder.Personal), "~");
Layout commands = new Layout (
new LayoutGroup ("help", Catalog.GetString ("Help Options"),
new LayoutOption ("help", Catalog.GetString ("Show this help")),
new LayoutOption ("help-playback", Catalog.GetString ("Show options for controlling playback")),
new LayoutOption ("help-query-track", Catalog.GetString ("Show options for querying the playing track")),
new LayoutOption ("help-query-player", Catalog.GetString ("Show options for querying the playing engine")),
new LayoutOption ("help-ui", Catalog.GetString ("Show options for the user interface")),
new LayoutOption ("help-debug", Catalog.GetString ("Show options for developers and debugging")),
new LayoutOption ("help-all", Catalog.GetString ("Show all option groups")),
new LayoutOption ("version", Catalog.GetString ("Show version information"))
),
new LayoutGroup ("playback", Catalog.GetString ("Playback Control Options"),
new LayoutOption ("next", Catalog.GetString ("Play the next track, optionally restarting if the 'restart' value is set")),
new LayoutOption ("previous", Catalog.GetString ("Play the previous track, optionally restarting if the 'restart' value is set")),
new LayoutOption ("restart-or-previous", Catalog.GetString ("If the current song has been played longer than 4 seconds then restart it, otherwise the same as --previous")),
new LayoutOption ("play-enqueued", Catalog.GetString ("Automatically start playing any tracks enqueued on the command line")),
new LayoutOption ("play", Catalog.GetString ("Start playback")),
new LayoutOption ("pause", Catalog.GetString ("Pause playback")),
new LayoutOption ("toggle-playing", Catalog.GetString ("Toggle playback")),
new LayoutOption ("stop", Catalog.GetString ("Completely stop playback")),
new LayoutOption ("stop-when-finished", Catalog.GetString (
"Enable or disable playback stopping after the currently playing track (value should be either 'true' or 'false')")),
new LayoutOption ("set-volume=LEVEL", Catalog.GetString ("Set the playback volume (0-100), prefix with +/- for relative values")),
new LayoutOption ("set-position=POS", Catalog.GetString ("Seek to a specific point (seconds, float)")),
new LayoutOption ("set-rating=RATING", Catalog.GetString ("Set the currently played track's rating (0 to 5)"))
),
new LayoutGroup ("query-player", Catalog.GetString ("Player Engine Query Options"),
new LayoutOption ("query-current-state", Catalog.GetString ("Current player state")),
new LayoutOption ("query-last-state", Catalog.GetString ("Last player state")),
new LayoutOption ("query-can-pause", Catalog.GetString ("Query whether the player can be paused")),
new LayoutOption ("query-can-seek", Catalog.GetString ("Query whether the player can seek")),
new LayoutOption ("query-volume", Catalog.GetString ("Player volume")),
new LayoutOption ("query-position", Catalog.GetString ("Player position in currently playing track"))
),
new LayoutGroup ("query-track", Catalog.GetString ("Playing Track Metadata Query Options"),
new LayoutOption ("query-uri", Catalog.GetString ("URI")),
new LayoutOption ("query-artist", Catalog.GetString ("Artist Name")),
new LayoutOption ("query-album", Catalog.GetString ("Album Title")),
new LayoutOption ("query-title", Catalog.GetString ("Track Title")),
new LayoutOption ("query-duration", Catalog.GetString ("Duration")),
new LayoutOption ("query-track-number", Catalog.GetString ("Track Number")),
new LayoutOption ("query-track-count", Catalog.GetString ("Track Count")),
new LayoutOption ("query-disc", Catalog.GetString ("Disc Number")),
new LayoutOption ("query-year", Catalog.GetString ("Year")),
new LayoutOption ("query-rating", Catalog.GetString ("Rating")),
new LayoutOption ("query-score", Catalog.GetString ("Score")),
new LayoutOption ("query-bit-rate", Catalog.GetString ("Bit Rate"))
),
new LayoutGroup ("ui", Catalog.GetString ("User Interface Options"),
new LayoutOption ("show|--present", Catalog.GetString ("Present the user interface on the active workspace")),
new LayoutOption ("fullscreen", Catalog.GetString ("Enter the full-screen mode")),
new LayoutOption ("hide", Catalog.GetString ("Hide the user interface")),
new LayoutOption ("no-present", Catalog.GetString ("Do not present the user interface, regardless of any other options")),
new LayoutOption ("show-import-media", Catalog.GetString ("Present the import media dialog box")),
new LayoutOption ("show-about", Catalog.GetString ("Present the about dialog")),
new LayoutOption ("show-open-location", Catalog.GetString ("Present the open location dialog")),
new LayoutOption ("show-preferences", Catalog.GetString ("Present the preferences dialog"))
),
new LayoutGroup ("debugging", Catalog.GetString ("Debugging and Development Options"),
new LayoutOption ("debug", Catalog.GetString ("Enable general debugging features")),
new LayoutOption ("debug-sql", Catalog.GetString ("Enable debugging output of SQL queries")),
new LayoutOption ("debug-addins", Catalog.GetString ("Enable debugging output of Mono.Addins")),
new LayoutOption ("db=FILE", Catalog.GetString ("Specify an alternate database to use")),
new LayoutOption ("fetch-artwork", Catalog.GetString ("Force fetching of missing cover artwork")),
new LayoutOption ("gconf-base-key=KEY", Catalog.GetString ("Specify an alternate key, default is /apps/banshee-1/")),
new LayoutOption ("uninstalled", Catalog.GetString ("Optimize instance for running uninstalled; " +
"most notably, this will create an alternate Mono.Addins database in the working directory")),
new LayoutOption ("disable-dbus", Catalog.GetString ("Disable DBus support completely")),
new LayoutOption ("no-gtkcss", String.Format (Catalog.GetString (
"Skip loading a custom gtk.css file ({0}) if it exists"), css_file)),
new LayoutOption ("debug-gtkcss", String.Format (Catalog.GetString (
"Reload the custom gtk.css file ({0}) every 5 seconds"), css_file))
)
);
if (ApplicationContext.CommandLine.Contains ("help-all")) {
Console.WriteLine (commands);
return;
}
List<string> errors = null;
foreach (KeyValuePair<string, string> argument in ApplicationContext.CommandLine.Arguments) {
switch (argument.Key) {
case "help": Console.WriteLine (commands.ToString ("help")); break;
case "help-debug": Console.WriteLine (commands.ToString ("debugging")); break;
case "help-query-track": Console.WriteLine (commands.ToString ("query-track")); break;
case "help-query-player": Console.WriteLine (commands.ToString ("query-player")); break;
case "help-ui": Console.WriteLine (commands.ToString ("ui")); break;
case "help-playback": Console.WriteLine (commands.ToString ("playback")); break;
default:
if (argument.Key.StartsWith ("help")) {
(errors ?? (errors = new List<string> ())).Add (argument.Key);
}
break;
}
}
if (errors != null) {
Console.WriteLine (commands.LayoutLine (String.Format (Catalog.GetString (
"The following help arguments are invalid: {0}"),
Hyena.Collections.CollectionExtensions.Join (errors, "--", null, ", "))));
}
}
private static void ShowVersion ()
{
Console.WriteLine ("Banshee {0} ({1}) http://banshee.fm", Application.DisplayVersion, Application.Version);
Console.WriteLine ("Copyright 2005-{0} Novell, Inc. and Contributors.", DateTime.Now.Year);
}
}
}
| |
// 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.Runtime.InteropServices;
using System.Threading.Tasks;
using EnvDTE;
using EnvDTE80;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.CodeModel
{
public class FileCodeImportTests : AbstractFileCodeElementTests
{
public FileCodeImportTests()
: base(@"using System;
using Foo = System.Data;")
{
}
private async Task<CodeImport> GetCodeImportAsync(object path)
{
return (CodeImport)await GetCodeElementAsync(path);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task Name()
{
CodeImport import = await GetCodeImportAsync(1);
Assert.Throws<COMException>(() => { var value = import.Name; });
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task FullName()
{
CodeImport import = await GetCodeImportAsync(1);
Assert.Throws<COMException>(() => { var value = import.FullName; });
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task Kind()
{
CodeImport import = await GetCodeImportAsync(1);
Assert.Equal(vsCMElement.vsCMElementImportStmt, import.Kind);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task Namespace()
{
CodeImport import = await GetCodeImportAsync(1);
Assert.Equal("System", import.Namespace);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task Alias()
{
CodeImport import = await GetCodeImportAsync(2);
Assert.Equal("Foo", import.Alias);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetStartPoint_Attributes()
{
CodeImport import = await GetCodeImportAsync(2);
Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartAttributes));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetStartPoint_AttributesWithDelimiter()
{
CodeImport import = await GetCodeImportAsync(2);
Assert.Throws<COMException>(() => import.GetStartPoint(vsCMPart.vsCMPartAttributesWithDelimiter));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetStartPoint_Body()
{
CodeImport import = await GetCodeImportAsync(2);
Assert.Throws<COMException>(() => import.GetStartPoint(vsCMPart.vsCMPartBody));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetStartPoint_BodyWithDelimiter()
{
CodeImport import = await GetCodeImportAsync(2);
Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartBodyWithDelimiter));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetStartPoint_Header()
{
CodeImport import = await GetCodeImportAsync(2);
Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartHeader));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetStartPoint_HeaderWithAttributes()
{
CodeImport import = await GetCodeImportAsync(2);
Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartHeaderWithAttributes));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetStartPoint_Name()
{
CodeImport import = await GetCodeImportAsync(2);
Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartName));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetStartPoint_Navigate()
{
CodeImport import = await GetCodeImportAsync(2);
TextPoint startPoint = import.GetStartPoint(vsCMPart.vsCMPartNavigate);
Assert.Equal(2, startPoint.Line);
Assert.Equal(13, startPoint.LineCharOffset);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetStartPoint_Whole()
{
CodeImport import = await GetCodeImportAsync(2);
Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartWhole));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetStartPoint_WholeWithAttributes()
{
CodeImport import = await GetCodeImportAsync(2);
TextPoint startPoint = import.GetStartPoint(vsCMPart.vsCMPartWholeWithAttributes);
Assert.Equal(2, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetEndPoint_Attributes()
{
CodeImport import = await GetCodeImportAsync(2);
Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartAttributes));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetEndPoint_AttributesWithDelimiter()
{
CodeImport import = await GetCodeImportAsync(2);
Assert.Throws<COMException>(() => import.GetEndPoint(vsCMPart.vsCMPartAttributesWithDelimiter));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetEndPoint_Body()
{
CodeImport import = await GetCodeImportAsync(2);
Assert.Throws<COMException>(() => import.GetEndPoint(vsCMPart.vsCMPartBody));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetEndPoint_BodyWithDelimiter()
{
CodeImport import = await GetCodeImportAsync(2);
Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartBodyWithDelimiter));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetEndPoint_Header()
{
CodeImport import = await GetCodeImportAsync(2);
Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartHeader));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetEndPoint_HeaderWithAttributes()
{
CodeImport import = await GetCodeImportAsync(2);
Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartHeaderWithAttributes));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetEndPoint_Name()
{
CodeImport import = await GetCodeImportAsync(2);
Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartName));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetEndPoint_Navigate()
{
CodeImport import = await GetCodeImportAsync(2);
TextPoint endPoint = import.GetEndPoint(vsCMPart.vsCMPartNavigate);
Assert.Equal(2, endPoint.Line);
Assert.Equal(24, endPoint.LineCharOffset);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetEndPoint_Whole()
{
CodeImport import = await GetCodeImportAsync(2);
Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartWhole));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task GetEndPoint_WholeWithAttributes()
{
CodeImport import = await GetCodeImportAsync(2);
TextPoint endPoint = import.GetEndPoint(vsCMPart.vsCMPartWholeWithAttributes);
Assert.Equal(2, endPoint.Line);
Assert.Equal(25, endPoint.LineCharOffset);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task StartPoint()
{
CodeImport import = await GetCodeImportAsync(2);
TextPoint startPoint = import.StartPoint;
Assert.Equal(2, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public async Task EndPoint()
{
CodeImport import = await GetCodeImportAsync(2);
TextPoint endPoint = import.EndPoint;
Assert.Equal(2, endPoint.Line);
Assert.Equal(25, endPoint.LineCharOffset);
}
}
}
| |
// 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 Microsoft.Protocols.TestTools.StackSdk;
using Microsoft.Protocols.TestTools.StackSdk.Messages;
namespace Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Cifs
{
/// <summary>
/// Packets for SmbNtTransactSecondary Request
/// </summary>
public class SmbNtTransactSecondaryRequestPacket : SmbSingleRequestPacket
{
#region Fields
private SMB_COM_NT_TRANSACT_SECONDARY_Request_SMB_Parameters smbParameters;
private SMB_COM_NT_TRANSACT_SECONDARY_Request_SMB_Data smbData;
#endregion
#region Properties
/// <summary>
/// get or set the Smb_Parameters:SMB_COM_NT_TRANSACT_SECONDARY_Request_SMB_Parameters
/// </summary>
public SMB_COM_NT_TRANSACT_SECONDARY_Request_SMB_Parameters SmbParameters
{
get
{
return this.smbParameters;
}
set
{
this.smbParameters = value;
}
}
/// <summary>
/// get or set the Smb_Data:SMB_COM_NT_TRANSACT_SECONDARY_Request_SMB_Data
/// </summary>
public SMB_COM_NT_TRANSACT_SECONDARY_Request_SMB_Data SmbData
{
get
{
return this.smbData;
}
set
{
this.smbData = value;
}
}
#endregion
#region Constructor
/// <summary>
/// Constructor.
/// </summary>
public SmbNtTransactSecondaryRequestPacket()
: base()
{
this.InitDefaultValue();
}
/// <summary>
/// Constructor: Create a request directly from a buffer.
/// </summary>
public SmbNtTransactSecondaryRequestPacket(byte[] data)
: base(data)
{
}
/// <summary>
/// Deep copy constructor.
/// </summary>
public SmbNtTransactSecondaryRequestPacket(SmbNtTransactSecondaryRequestPacket packet)
: base(packet)
{
this.InitDefaultValue();
this.smbParameters.WordCount = packet.SmbParameters.WordCount;
if (packet.smbParameters.Reserved1 != null)
{
this.smbParameters.Reserved1 = new byte[packet.smbParameters.Reserved1.Length];
Array.Copy(packet.smbParameters.Reserved1, this.smbParameters.Reserved1,
packet.smbParameters.Reserved1.Length);
}
else
{
this.smbParameters.Reserved1 = new byte[0];
}
this.smbParameters.TotalParameterCount = packet.SmbParameters.TotalParameterCount;
this.smbParameters.TotalDataCount = packet.SmbParameters.TotalDataCount;
this.smbParameters.ParameterCount = packet.SmbParameters.ParameterCount;
this.smbParameters.ParameterOffset = packet.SmbParameters.ParameterOffset;
this.smbParameters.ParameterDisplacement = packet.SmbParameters.ParameterDisplacement;
this.smbParameters.DataCount = packet.SmbParameters.DataCount;
this.smbParameters.DataOffset = packet.SmbParameters.DataOffset;
this.smbParameters.DataDisplacement = packet.SmbParameters.DataDisplacement;
this.smbParameters.Reserved2 = packet.SmbParameters.Reserved2;
this.smbData.ByteCount = packet.SmbData.ByteCount;
if (packet.smbData.Pad1 != null)
{
this.smbData.Pad1 = new byte[packet.smbData.Pad1.Length];
Array.Copy(packet.smbData.Pad1, this.smbData.Pad1, packet.smbData.Pad1.Length);
}
else
{
this.smbData.Pad1 = new byte[0];
}
this.smbData.NT_Trans_Parameters = new byte[packet.smbParameters.ParameterCount];
if (packet.smbData.NT_Trans_Parameters != null)
{
Array.Copy(packet.smbData.NT_Trans_Parameters,
this.smbData.NT_Trans_Parameters, packet.smbParameters.ParameterCount);
}
else
{
this.smbData.NT_Trans_Parameters = new byte[0];
}
if (packet.smbData.Pad2 != null)
{
this.smbData.Pad2 = new byte[packet.smbData.Pad2.Length];
Array.Copy(packet.smbData.Pad2, this.smbData.Pad2, packet.smbData.Pad2.Length);
}
else
{
this.smbData.Pad2 = new byte[0];
}
this.smbData.NT_Trans_Data = new byte[packet.smbParameters.DataCount];
if (this.smbData.NT_Trans_Data != null)
{
Array.Copy(packet.smbData.NT_Trans_Data, this.smbData.NT_Trans_Data, packet.smbParameters.DataCount);
}
else
{
this.smbData.NT_Trans_Data = new byte[0];
}
}
#endregion
#region Methods
/// <summary>
/// to update fields about size and offset automatly.
/// </summary>
internal void UpdateCountAndOffset()
{
int byteCount = 0;
if (this.smbData.NT_Trans_Parameters != null)
{
this.smbParameters.ParameterCount = (ushort)smbData.NT_Trans_Parameters.Length;
byteCount += this.smbData.NT_Trans_Parameters.Length;
}
this.smbParameters.ParameterOffset = (ushort)(this.HeaderSize + this.smbParameters.WordCount * 2
+ SmbComTransactionPacket.SmbParametersWordCountLength + SmbComTransactionPacket.SmbDataByteCountLength);
if (this.smbData.Pad1 != null)
{
this.smbParameters.ParameterOffset += (ushort)this.smbData.Pad1.Length;
byteCount += this.smbData.Pad1.Length;
}
if (this.smbData.NT_Trans_Data != null)
{
this.smbParameters.DataCount = (ushort)this.smbData.NT_Trans_Data.Length;
byteCount += this.smbData.NT_Trans_Data.Length;
}
this.smbParameters.DataOffset = (ushort)(this.smbParameters.ParameterOffset +
this.smbParameters.ParameterCount);
if (this.smbData.Pad2 != null)
{
this.smbParameters.DataOffset += (ushort)this.smbData.Pad2.Length;
byteCount += this.smbData.Pad2.Length;
}
this.smbData.ByteCount = (ushort)byteCount;
}
#endregion
#region override methods
/// <summary>
/// to create an instance of the StackPacket class that is identical to the current StackPacket.
/// </summary>
/// <returns>a new Packet cloned from this.</returns>
public override StackPacket Clone()
{
return new SmbNtTransactSecondaryRequestPacket(this);
}
/// <summary>
/// Encode the struct of SMB_COM_NT_TRANSACT_SECONDARY_Request_SMB_Parameters
/// into the struct of SmbParameters
/// </summary>
protected override void EncodeParameters()
{
this.smbParametersBlock = TypeMarshal.ToStruct<SmbParameters>(
CifsMessageUtils.ToBytes<SMB_COM_NT_TRANSACT_SECONDARY_Request_SMB_Parameters>(this.smbParameters));
}
/// <summary>
/// Encode the struct of SMB_COM_NT_TRANSACT_SECONDARY_Request_SMB_Data into the struct of SmbData
/// </summary>
protected override void EncodeData()
{
int byteCount = 0;
if (this.smbData.Pad1 != null)
{
byteCount += this.smbData.Pad1.Length;
}
if (this.smbData.NT_Trans_Parameters != null)
{
byteCount += this.smbData.NT_Trans_Parameters.Length;
}
if (this.smbData.Pad2 != null)
{
byteCount += this.smbData.Pad2.Length;
}
if (this.smbData.NT_Trans_Data != null)
{
byteCount += this.smbData.NT_Trans_Data.Length;
}
this.smbDataBlock.ByteCount = this.smbData.ByteCount;
this.smbDataBlock.Bytes = new byte[byteCount];
if (this.smbData.ByteCount > 0)
{
using (MemoryStream memoryStream = new MemoryStream(this.smbDataBlock.Bytes))
{
using (Channel channel = new Channel(null, memoryStream))
{
channel.BeginWriteGroup();
if (this.SmbData.Pad1 != null)
{
channel.WriteBytes(this.SmbData.Pad1);
}
if (this.SmbData.NT_Trans_Parameters != null)
{
channel.WriteBytes(this.SmbData.NT_Trans_Parameters);
}
if (this.SmbData.Pad2 != null)
{
channel.WriteBytes(this.SmbData.Pad2);
}
if (this.SmbData.NT_Trans_Data != null)
{
channel.WriteBytes(this.SmbData.NT_Trans_Data);
}
channel.EndWriteGroup();
}
}
}
}
/// <summary>
/// to decode the smb parameters: from the general SmbParameters to the concrete Smb Parameters.
/// </summary>
protected override void DecodeParameters()
{
this.smbParameters = TypeMarshal.ToStruct<SMB_COM_NT_TRANSACT_SECONDARY_Request_SMB_Parameters>(
TypeMarshal.ToBytes(this.smbParametersBlock));
}
/// <summary>
/// to decode the smb data: from the general SmbDada to the concrete Smb Data.
/// </summary>
protected override void DecodeData()
{
this.smbData = new SMB_COM_NT_TRANSACT_SECONDARY_Request_SMB_Data();
using (MemoryStream memoryStream = new MemoryStream(CifsMessageUtils.ToBytes<SmbData>(this.smbDataBlock)))
{
using (Channel channel = new Channel(null, memoryStream))
{
this.smbData.ByteCount = channel.Read<ushort>();
this.smbData.Pad1 = channel.ReadBytes((int)(this.smbParameters.ParameterOffset - this.HeaderSize
- this.smbParameters.WordCount * 2 - SmbComTransactionPacket.SmbParametersWordCountLength
- SmbComTransactionPacket.SmbDataByteCountLength));
this.smbData.NT_Trans_Parameters = channel.ReadBytes((int)this.smbParameters.ParameterCount);
this.smbData.Pad2 = channel.ReadBytes((int)(this.smbParameters.DataOffset
- this.smbParameters.ParameterOffset - this.smbParameters.ParameterCount));
this.smbData.NT_Trans_Data = channel.ReadBytes((int)this.smbParameters.DataCount);
}
}
}
#endregion
#region initialize fields with default value
/// <summary>
/// init packet, set default field data
/// </summary>
private void InitDefaultValue()
{
this.smbData.Pad1 = new byte[0];
this.smbData.Pad2 = new byte[0];
this.smbData.NT_Trans_Data = new byte[0];
this.smbData.NT_Trans_Parameters = new byte[0];
this.smbParameters.Reserved1 = new byte[0];
}
#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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers
{
internal partial class XmlDocCommentCompletionProvider : AbstractDocCommentCompletionProvider
{
internal override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options)
{
return text[characterPosition] == '<';
}
protected override async Task<IEnumerable<CompletionItem>> GetItemsWorkerAsync(
Document document, int position,
CompletionTrigger trigger, CancellationToken cancellationToken)
{
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var token = tree.FindTokenOnLeftOfPosition(position, cancellationToken);
var parentTrivia = token.GetAncestor<DocumentationCommentTriviaSyntax>();
if (parentTrivia == null)
{
return null;
}
var items = new List<CompletionItem>();
var attachedToken = parentTrivia.ParentTrivia.Token;
if (attachedToken.Kind() == SyntaxKind.None)
{
return null;
}
var semanticModel = await document.GetSemanticModelForNodeAsync(attachedToken.Parent, cancellationToken).ConfigureAwait(false);
ISymbol declaredSymbol = null;
var memberDeclaration = attachedToken.GetAncestor<MemberDeclarationSyntax>();
if (memberDeclaration != null)
{
declaredSymbol = semanticModel.GetDeclaredSymbol(memberDeclaration, cancellationToken);
}
else
{
var typeDeclaration = attachedToken.GetAncestor<TypeDeclarationSyntax>();
if (typeDeclaration != null)
{
declaredSymbol = semanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken);
}
}
// User is trying to write a name, try to suggest only names.
if (token.Parent.IsKind(SyntaxKind.XmlNameAttribute) ||
(token.Parent.IsKind(SyntaxKind.IdentifierName) && token.Parent.IsParentKind(SyntaxKind.XmlNameAttribute)))
{
string parentElementName = null;
var emptyElement = token.GetAncestor<XmlEmptyElementSyntax>();
if (emptyElement != null)
{
parentElementName = emptyElement.Name.LocalName.Text;
}
if (parentElementName == ParamRefTagName)
{
return GetParamNameItems(declaredSymbol);
}
else if (parentElementName == TypeParamRefTagName)
{
return GetTypeParamNameItems(declaredSymbol);
}
}
if (token.Parent.Kind() == SyntaxKind.XmlEmptyElement || token.Parent.Kind() == SyntaxKind.XmlText ||
(token.Parent.IsKind(SyntaxKind.XmlElementEndTag) && token.IsKind(SyntaxKind.GreaterThanToken)) ||
(token.Parent.IsKind(SyntaxKind.XmlName) && token.Parent.IsParentKind(SyntaxKind.XmlEmptyElement)))
{
// The user is typing inside an XmlElement
if (token.Parent.Parent.Kind() == SyntaxKind.XmlElement ||
token.Parent.Parent.IsParentKind(SyntaxKind.XmlElement))
{
items.AddRange(GetNestedTags(declaredSymbol));
}
if (token.Parent.Parent.Kind() == SyntaxKind.XmlElement && ((XmlElementSyntax)token.Parent.Parent).StartTag.Name.LocalName.ValueText == ListTagName)
{
items.AddRange(GetListItems());
}
if (token.Parent.IsParentKind(SyntaxKind.XmlEmptyElement) && token.Parent.Parent.IsParentKind(SyntaxKind.XmlElement))
{
var element = (XmlElementSyntax)token.Parent.Parent.Parent;
if (element.StartTag.Name.LocalName.ValueText == ListTagName)
{
items.AddRange(GetListItems());
}
}
if (token.Parent.Parent.Kind() == SyntaxKind.XmlElement && ((XmlElementSyntax)token.Parent.Parent).StartTag.Name.LocalName.ValueText == ListHeaderTagName)
{
items.AddRange(GetListHeaderItems());
}
if (token.Parent.Parent is DocumentationCommentTriviaSyntax ||
(token.Parent.Parent.IsKind(SyntaxKind.XmlEmptyElement) && token.Parent.Parent.Parent is DocumentationCommentTriviaSyntax))
{
items.AddRange(GetTopLevelSingleUseNames(parentTrivia));
items.AddRange(GetTopLevelRepeatableItems());
items.AddRange(GetTagsForSymbol(declaredSymbol, parentTrivia));
}
}
if (token.Parent.Kind() == SyntaxKind.XmlElementStartTag)
{
var startTag = (XmlElementStartTagSyntax)token.Parent;
if (token == startTag.GreaterThanToken && startTag.Name.LocalName.ValueText == ListTagName)
{
items.AddRange(GetListItems());
}
if (token == startTag.GreaterThanToken && startTag.Name.LocalName.ValueText == ListHeaderTagName)
{
items.AddRange(GetListHeaderItems());
}
}
items.AddRange(GetAlwaysVisibleItems());
return items;
}
private IEnumerable<CompletionItem> GetTopLevelSingleUseNames(DocumentationCommentTriviaSyntax parentTrivia)
{
var names = new HashSet<string>(new[] { SummaryTagName, RemarksTagName, ExampleTagName, CompletionListTagName });
RemoveExistingTags(parentTrivia, names, (x) => x.StartTag.Name.LocalName.ValueText);
return names.Select(GetItem);
}
private void RemoveExistingTags(DocumentationCommentTriviaSyntax parentTrivia, ISet<string> names, Func<XmlElementSyntax, string> selector)
{
if (parentTrivia != null)
{
foreach (var node in parentTrivia.Content)
{
var element = node as XmlElementSyntax;
if (element != null)
{
names.Remove(selector(element));
}
}
}
}
private IEnumerable<CompletionItem> GetTagsForSymbol(ISymbol symbol, DocumentationCommentTriviaSyntax trivia)
{
if (symbol is IMethodSymbol)
{
return GetTagsForMethod((IMethodSymbol)symbol, trivia);
}
if (symbol is IPropertySymbol)
{
return GetTagsForProperty((IPropertySymbol)symbol, trivia);
}
if (symbol is INamedTypeSymbol)
{
return GetTagsForType((INamedTypeSymbol)symbol, trivia);
}
return SpecializedCollections.EmptyEnumerable<CompletionItem>();
}
private IEnumerable<CompletionItem> GetTagsForType(INamedTypeSymbol symbol, DocumentationCommentTriviaSyntax trivia)
{
var items = new List<CompletionItem>();
var typeParameters = symbol.TypeParameters.Select(p => p.Name).ToSet();
RemoveExistingTags(trivia, typeParameters, x => AttributeSelector(x, TypeParamTagName));
items.AddRange(typeParameters.Select(t => CreateCompletionItem(FormatParameter(TypeParamTagName, t))));
return items;
}
private string AttributeSelector(XmlElementSyntax element, string attribute)
{
if (!element.StartTag.IsMissing && !element.EndTag.IsMissing)
{
var startTag = element.StartTag;
var nameAttribute = startTag.Attributes.OfType<XmlNameAttributeSyntax>().FirstOrDefault(a => a.Name.LocalName.ValueText == NameAttributeName);
if (nameAttribute != null)
{
if (startTag.Name.LocalName.ValueText == attribute)
{
return nameAttribute.Identifier.Identifier.ValueText;
}
}
}
return null;
}
private IEnumerable<CompletionItem> GetTagsForProperty(IPropertySymbol symbol, DocumentationCommentTriviaSyntax trivia)
{
var items = new List<CompletionItem>();
if (symbol.IsIndexer)
{
var parameters = symbol.GetParameters().Select(p => p.Name).ToSet();
RemoveExistingTags(trivia, parameters, x => AttributeSelector(x, ParamTagName));
items.AddRange(parameters.Select(p => CreateCompletionItem(FormatParameter(ParamTagName, p))));
}
var typeParameters = symbol.GetTypeArguments().Select(p => p.Name).ToSet();
items.AddRange(typeParameters.Select(t => CreateCompletionItem(TypeParamTagName, NameAttributeName, t)));
items.Add(CreateCompletionItem("value"));
return items;
}
private IEnumerable<CompletionItem> GetTagsForMethod(IMethodSymbol symbol, DocumentationCommentTriviaSyntax trivia)
{
var items = new List<CompletionItem>();
var parameters = symbol.GetParameters().Select(p => p.Name).ToSet();
var typeParameters = symbol.TypeParameters.Select(t => t.Name).ToSet();
RemoveExistingTags(trivia, parameters, x => AttributeSelector(x, ParamTagName));
RemoveExistingTags(trivia, typeParameters, x => AttributeSelector(x, TypeParamTagName));
items.AddRange(parameters.Select(p => CreateCompletionItem(FormatParameter(ParamTagName, p))));
items.AddRange(typeParameters.Select(t => CreateCompletionItem(FormatParameter(TypeParamTagName, t))));
// Provide a return completion item in case the function returns something
var returns = true;
foreach (var node in trivia.Content)
{
var element = node as XmlElementSyntax;
if (element != null && !element.StartTag.IsMissing && !element.EndTag.IsMissing)
{
var startTag = element.StartTag;
if (startTag.Name.LocalName.ValueText == ReturnsTagName)
{
returns = false;
break;
}
}
}
if (returns && !symbol.ReturnsVoid)
{
items.Add(CreateCompletionItem(ReturnsTagName));
}
return items;
}
protected IEnumerable<CompletionItem> GetParamNameItems(ISymbol declaredSymbol)
{
var items = declaredSymbol?.GetParameters()
.Select(parameter => CreateCompletionItem(parameter.Name));
return items ?? SpecializedCollections.EmptyEnumerable<CompletionItem>();
}
protected IEnumerable<CompletionItem> GetTypeParamNameItems(ISymbol declaredSymbol)
{
var items = declaredSymbol?.GetTypeParameters()
.Select(typeParameter => CreateCompletionItem(typeParameter.Name));
return items ?? SpecializedCollections.EmptyEnumerable<CompletionItem>();
}
private static CompletionItemRules s_defaultRules =
CompletionItemRules.Create(
filterCharacterRules: FilterRules,
commitCharacterRules: ImmutableArray.Create(CharacterSetModificationRule.Create(CharacterSetModificationKind.Add, '>', '\t')),
enterKeyRule: EnterKeyRule.Never);
protected override CompletionItemRules GetCompletionItemRules(string displayText)
{
var commitRules = s_defaultRules.CommitCharacterRules;
if (displayText.Contains("\""))
{
commitRules = commitRules.Add(WithoutQuoteRule);
}
if (displayText.Contains(" "))
{
commitRules = commitRules.Add(WithoutSpaceRule);
}
return s_defaultRules.WithCommitCharacterRules(commitRules);
}
}
}
| |
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using HETSAPI.Models;
namespace HETSAPI.ViewModels
{
/// <summary>
/// User View Model
/// </summary>
[DataContract]
public sealed class UserViewModel : IEquatable<UserViewModel>
{
/// <summary>
/// User View Model Constructor
/// </summary>
public UserViewModel()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="UserViewModel" /> class.
/// </summary>
/// <param name="id">Id (required).</param>
/// <param name="active">Active (required).</param>
/// <param name="givenName">GivenName.</param>
/// <param name="surname">Surname.</param>
/// <param name="email">Email.</param>
/// <param name="smUserId">SmUserId.</param>
/// <param name="userRoles">UserRoles.</param>
/// <param name="district">The District to which this User is affliated..</param>
public UserViewModel(int id, bool active, string givenName = null, string surname = null, string email = null,
string smUserId = null, List<UserRole> userRoles = null, District district = null)
{
Id = id;
Active = active;
GivenName = givenName;
Surname = surname;
Email = email;
SmUserId = smUserId;
UserRoles = userRoles;
District = district;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id")]
public int Id { get; set; }
/// <summary>
/// Gets or Sets Active
/// </summary>
[DataMember(Name="active")]
public bool Active { get; set; }
/// <summary>
/// Gets or Sets GivenName
/// </summary>
[DataMember(Name="givenName")]
public string GivenName { get; set; }
/// <summary>
/// Gets or Sets Surname
/// </summary>
[DataMember(Name="surname")]
public string Surname { get; set; }
/// <summary>
/// Gets or Sets Email
/// </summary>
[DataMember(Name="email")]
public string Email { get; set; }
/// <summary>
/// Gets or Sets SmUserId
/// </summary>
[DataMember(Name="smUserId")]
public string SmUserId { get; set; }
/// <summary>
/// Gets or Sets UserRoles
/// </summary>
[DataMember(Name="userRoles")]
public List<UserRole> UserRoles { get; set; }
/// <summary>
/// The District to which this User is affliated.
/// </summary>
/// <value>The District to which this User is affliated.</value>
[DataMember(Name="district")]
[MetaData (Description = "The District to which this User is affliated.")]
public District District { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class UserViewModel {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Active: ").Append(Active).Append("\n");
sb.Append(" GivenName: ").Append(GivenName).Append("\n");
sb.Append(" Surname: ").Append(Surname).Append("\n");
sb.Append(" Email: ").Append(Email).Append("\n");
sb.Append(" SmUserId: ").Append(SmUserId).Append("\n");
sb.Append(" UserRoles: ").Append(UserRoles).Append("\n");
sb.Append(" District: ").Append(District).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
if (obj is null) { return false; }
if (ReferenceEquals(this, obj)) { return true; }
return obj.GetType() == GetType() && Equals((UserViewModel)obj);
}
/// <summary>
/// Returns true if UserViewModel instances are equal
/// </summary>
/// <param name="other">Instance of UserViewModel to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(UserViewModel other)
{
if (other is null) { return false; }
if (ReferenceEquals(this, other)) { return true; }
return
(
Id == other.Id ||
Id.Equals(other.Id)
) &&
(
Active == other.Active ||
Active.Equals(other.Active)
) &&
(
GivenName == other.GivenName ||
GivenName != null &&
GivenName.Equals(other.GivenName)
) &&
(
Surname == other.Surname ||
Surname != null &&
Surname.Equals(other.Surname)
) &&
(
Email == other.Email ||
Email != null &&
Email.Equals(other.Email)
) &&
(
SmUserId == other.SmUserId ||
SmUserId != null &&
SmUserId.Equals(other.SmUserId)
) &&
(
UserRoles == other.UserRoles ||
UserRoles != null &&
UserRoles.SequenceEqual(other.UserRoles)
) &&
(
District == other.District ||
District != null &&
District.Equals(other.District)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks
hash = hash * 59 + Id.GetHashCode();
hash = hash * 59 + Active.GetHashCode();
if (GivenName != null)
{
hash = hash * 59 + GivenName.GetHashCode();
}
if (Surname != null)
{
hash = hash * 59 + Surname.GetHashCode();
}
if (Email != null)
{
hash = hash * 59 + Email.GetHashCode();
}
if (SmUserId != null)
{
hash = hash * 59 + SmUserId.GetHashCode();
}
if (UserRoles != null)
{
hash = hash * 59 + UserRoles.GetHashCode();
}
if (District != null)
{
hash = hash * 59 + District.GetHashCode();
}
return hash;
}
}
#region Operators
/// <summary>
/// Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(UserViewModel left, UserViewModel right)
{
return Equals(left, right);
}
/// <summary>
/// Not Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(UserViewModel left, UserViewModel right)
{
return !Equals(left, right);
}
#endregion Operators
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
namespace System.Collections.Immutable
{
/// <content>
/// Contains the inner <see cref="ImmutableSortedSet{T}.Builder"/> class.
/// </content>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")]
public sealed partial class ImmutableSortedSet<T>
{
/// <summary>
/// A sorted set that mutates with little or no memory allocations,
/// can produce and/or build on immutable sorted set instances very efficiently.
/// </summary>
/// <remarks>
/// <para>
/// While <see cref="ImmutableSortedSet{T}.Union"/> and other bulk change methods
/// already provide fast bulk change operations on the collection, this class allows
/// multiple combinations of changes to be made to a set with equal efficiency.
/// </para>
/// <para>
/// Instance members of this class are <em>not</em> thread-safe.
/// </para>
/// </remarks>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")]
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "Ignored")]
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(ImmutableSortedSetBuilderDebuggerProxy<>))]
public sealed class Builder : ISortKeyCollection<T>, IReadOnlyCollection<T>, ISet<T>, ICollection
{
/// <summary>
/// The root of the binary tree that stores the collection. Contents are typically not entirely frozen.
/// </summary>
private ImmutableSortedSet<T>.Node _root = ImmutableSortedSet<T>.Node.EmptyNode;
/// <summary>
/// The comparer to use for sorting the set.
/// </summary>
private IComparer<T> _comparer = Comparer<T>.Default;
/// <summary>
/// Caches an immutable instance that represents the current state of the collection.
/// </summary>
/// <value>Null if no immutable view has been created for the current version.</value>
private ImmutableSortedSet<T> _immutable;
/// <summary>
/// A number that increments every time the builder changes its contents.
/// </summary>
private int _version;
/// <summary>
/// The object callers may use to synchronize access to this collection.
/// </summary>
private object _syncRoot;
/// <summary>
/// Initializes a new instance of the <see cref="Builder"/> class.
/// </summary>
/// <param name="set">A set to act as the basis for a new set.</param>
internal Builder(ImmutableSortedSet<T> set)
{
Requires.NotNull(set, "set");
_root = set._root;
_comparer = set.KeyComparer;
_immutable = set;
}
#region ISet<T> Properties
/// <summary>
/// Gets the number of elements in this set.
/// </summary>
public int Count
{
get { return this.Root.Count; }
}
/// <summary>
/// Gets a value indicating whether this instance is read-only.
/// </summary>
/// <value>Always <c>false</c>.</value>
bool ICollection<T>.IsReadOnly
{
get { return false; }
}
#endregion
/// <summary>
/// Gets the element of the set at the given index.
/// </summary>
/// <param name="index">The 0-based index of the element in the set to return.</param>
/// <returns>The element at the given position.</returns>
/// <remarks>
/// No index setter is offered because the element being replaced may not sort
/// to the same position in the sorted collection as the replacing element.
/// </remarks>
public T this[int index]
{
get { return _root[index]; }
}
/// <summary>
/// Gets the maximum value in the collection, as defined by the comparer.
/// </summary>
/// <value>The maximum value in the set.</value>
public T Max
{
get { return _root.Max; }
}
/// <summary>
/// Gets the minimum value in the collection, as defined by the comparer.
/// </summary>
/// <value>The minimum value in the set.</value>
public T Min
{
get { return _root.Min; }
}
/// <summary>
/// Gets or sets the <see cref="IComparer{T}"/> object that is used to determine equality for the values in the <see cref="ImmutableSortedSet{T}"/>.
/// </summary>
/// <value>The comparer that is used to determine equality for the values in the set.</value>
/// <remarks>
/// When changing the comparer in such a way as would introduce collisions, the conflicting elements are dropped,
/// leaving only one of each matching pair in the collection.
/// </remarks>
public IComparer<T> KeyComparer
{
get
{
return _comparer;
}
set
{
Requires.NotNull(value, "value");
if (value != _comparer)
{
var newRoot = Node.EmptyNode;
foreach (T item in this)
{
bool mutated;
newRoot = newRoot.Add(item, value, out mutated);
}
_immutable = null;
_comparer = value;
this.Root = newRoot;
}
}
}
/// <summary>
/// Gets the current version of the contents of this builder.
/// </summary>
internal int Version
{
get { return _version; }
}
/// <summary>
/// Gets or sets the root node that represents the data in this collection.
/// </summary>
private Node Root
{
get
{
return _root;
}
set
{
// We *always* increment the version number because some mutations
// may not create a new value of root, although the existing root
// instance may have mutated.
_version++;
if (_root != value)
{
_root = value;
// Clear any cached value for the immutable view since it is now invalidated.
_immutable = null;
}
}
}
#region ISet<T> Methods
/// <summary>
/// Adds an element to the current set and returns a value to indicate if the
/// element was successfully added.
/// </summary>
/// <param name="item">The element to add to the set.</param>
/// <returns>true if the element is added to the set; false if the element is already in the set.</returns>
public bool Add(T item)
{
bool mutated;
this.Root = this.Root.Add(item, _comparer, out mutated);
return mutated;
}
/// <summary>
/// Removes all elements in the specified collection from the current set.
/// </summary>
/// <param name="other">The collection of items to remove from the set.</param>
public void ExceptWith(IEnumerable<T> other)
{
Requires.NotNull(other, "other");
foreach (T item in other)
{
bool mutated;
this.Root = this.Root.Remove(item, _comparer, out mutated);
}
}
/// <summary>
/// Modifies the current set so that it contains only elements that are also in a specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
public void IntersectWith(IEnumerable<T> other)
{
Requires.NotNull(other, "other");
var result = ImmutableSortedSet<T>.Node.EmptyNode;
foreach (T item in other)
{
if (this.Contains(item))
{
bool mutated;
result = result.Add(item, _comparer, out mutated);
}
}
this.Root = result;
}
/// <summary>
/// Determines whether the current set is a proper (strict) subset of a specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is a correct subset of other; otherwise, false.</returns>
public bool IsProperSubsetOf(IEnumerable<T> other)
{
return this.ToImmutable().IsProperSubsetOf(other);
}
/// <summary>
/// Determines whether the current set is a proper (strict) superset of a specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is a superset of other; otherwise, false.</returns>
public bool IsProperSupersetOf(IEnumerable<T> other)
{
return this.ToImmutable().IsProperSupersetOf(other);
}
/// <summary>
/// Determines whether the current set is a subset of a specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is a subset of other; otherwise, false.</returns>
public bool IsSubsetOf(IEnumerable<T> other)
{
return this.ToImmutable().IsSubsetOf(other);
}
/// <summary>
/// Determines whether the current set is a superset of a specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is a superset of other; otherwise, false.</returns>
public bool IsSupersetOf(IEnumerable<T> other)
{
return this.ToImmutable().IsSupersetOf(other);
}
/// <summary>
/// Determines whether the current set overlaps with the specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set and other share at least one common element; otherwise, false.</returns>
public bool Overlaps(IEnumerable<T> other)
{
return this.ToImmutable().Overlaps(other);
}
/// <summary>
/// Determines whether the current set and the specified collection contain the same elements.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is equal to other; otherwise, false.</returns>
public bool SetEquals(IEnumerable<T> other)
{
return this.ToImmutable().SetEquals(other);
}
/// <summary>
/// Modifies the current set so that it contains only elements that are present either in the current set or in the specified collection, but not both.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
public void SymmetricExceptWith(IEnumerable<T> other)
{
this.Root = this.ToImmutable().SymmetricExcept(other)._root;
}
/// <summary>
/// Modifies the current set so that it contains all elements that are present in both the current set and in the specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
public void UnionWith(IEnumerable<T> other)
{
Requires.NotNull(other, "other");
foreach (T item in other)
{
bool mutated;
this.Root = this.Root.Add(item, _comparer, out mutated);
}
}
/// <summary>
/// Adds an element to the current set and returns a value to indicate if the
/// element was successfully added.
/// </summary>
/// <param name="item">The element to add to the set.</param>
void ICollection<T>.Add(T item)
{
this.Add(item);
}
/// <summary>
/// Removes all elements from this set.
/// </summary>
public void Clear()
{
this.Root = ImmutableSortedSet<T>.Node.EmptyNode;
}
/// <summary>
/// Determines whether the set contains a specific value.
/// </summary>
/// <param name="item">The object to locate in the set.</param>
/// <returns>true if item is found in the set; false otherwise.</returns>
public bool Contains(T item)
{
return this.Root.Contains(item, _comparer);
}
/// <summary>
/// See <see cref="ICollection{T}"/>
/// </summary>
void ICollection<T>.CopyTo(T[] array, int arrayIndex)
{
_root.CopyTo(array, arrayIndex);
}
/// <summary>
/// Removes the first occurrence of a specific object from the set.
/// </summary>
/// <param name="item">The object to remove from the set.</param>
/// <returns><c>true</c> if the item was removed from the set; <c>false</c> if the item was not found in the set.</returns>
public bool Remove(T item)
{
bool mutated;
this.Root = this.Root.Remove(item, _comparer, out mutated);
return mutated;
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>A enumerator that can be used to iterate through the collection.</returns>
public ImmutableSortedSet<T>.Enumerator GetEnumerator()
{
return this.Root.GetEnumerator(this);
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>A enumerator that can be used to iterate through the collection.</returns>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return this.Root.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>A enumerator that can be used to iterate through the collection.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
/// <summary>
/// Returns an <see cref="IEnumerable{T}"/> that iterates over this
/// collection in reverse order.
/// </summary>
/// <returns>
/// An enumerator that iterates over the <see cref="ImmutableSortedSet{T}.Builder"/>
/// in reverse order.
/// </returns>
[Pure]
public IEnumerable<T> Reverse()
{
return new ReverseEnumerable(_root);
}
/// <summary>
/// Creates an immutable sorted set based on the contents of this instance.
/// </summary>
/// <returns>An immutable set.</returns>
/// <remarks>
/// This method is an O(n) operation, and approaches O(1) time as the number of
/// actual mutations to the set since the last call to this method approaches 0.
/// </remarks>
public ImmutableSortedSet<T> ToImmutable()
{
// Creating an instance of ImmutableSortedSet<T> with our root node automatically freezes our tree,
// ensuring that the returned instance is immutable. Any further mutations made to this builder
// will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked.
if (_immutable == null)
{
_immutable = ImmutableSortedSet<T>.Wrap(this.Root, _comparer);
}
return _immutable;
}
#region ICollection members
/// <summary>
/// Copies the elements of the <see cref="ICollection"/> to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ICollection"/>. The <see cref="Array"/> must have zero-based indexing.</param>
/// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param>
void ICollection.CopyTo(Array array, int arrayIndex)
{
this.Root.CopyTo(array, arrayIndex);
}
/// <summary>
/// Gets a value indicating whether access to the <see cref="ICollection"/> is synchronized (thread safe).
/// </summary>
/// <returns>true if access to the <see cref="ICollection"/> is synchronized (thread safe); otherwise, false.</returns>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
bool ICollection.IsSynchronized
{
get { return false; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the <see cref="ICollection"/>.
/// </summary>
/// <returns>An object that can be used to synchronize access to the <see cref="ICollection"/>.</returns>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
#endregion
}
}
/// <summary>
/// A simple view of the immutable collection that the debugger can show to the developer.
/// </summary>
internal class ImmutableSortedSetBuilderDebuggerProxy<T>
{
/// <summary>
/// The collection to be enumerated.
/// </summary>
private readonly ImmutableSortedSet<T>.Builder _set;
/// <summary>
/// The simple view of the collection.
/// </summary>
private T[] _contents;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableSortedSetBuilderDebuggerProxy{T}"/> class.
/// </summary>
/// <param name="builder">The collection to display in the debugger</param>
public ImmutableSortedSetBuilderDebuggerProxy(ImmutableSortedSet<T>.Builder builder)
{
Requires.NotNull(builder, "builder");
_set = builder;
}
/// <summary>
/// Gets a simple debugger-viewable collection.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public T[] Contents
{
get
{
if (_contents == null)
{
_contents = _set.ToArray(_set.Count);
}
return _contents;
}
}
}
}
| |
/*
* Copyright 2012-2021 The Pkcs11Interop Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <jimrich@jimrich.sk>
*/
using System;
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.HighLevelAPI;
using Net.Pkcs11Interop.HighLevelAPI.MechanismParams;
using Net.Pkcs11Interop.LowLevelAPI80.MechanismParams;
using NativeULong = System.UInt64;
// Note: Code in this file is generated automatically.
namespace Net.Pkcs11Interop.HighLevelAPI80.MechanismParams
{
/// <summary>
/// Resulting key handles and initialization vectors after performing a DeriveKey method with the CKM_SSL3_KEY_AND_MAC_DERIVE mechanism
/// </summary>
public class CkSsl3KeyMatOut : ICkSsl3KeyMatOut
{
/// <summary>
/// Flag indicating whether instance has been disposed
/// </summary>
private bool _disposed = false;
/// <summary>
/// Low level structure
/// </summary>
internal CK_SSL3_KEY_MAT_OUT _lowLevelStruct = new CK_SSL3_KEY_MAT_OUT();
/// <summary>
/// Key handle for the resulting Client MAC Secret key
/// </summary>
public IObjectHandle ClientMacSecret
{
get
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
return new ObjectHandle(_lowLevelStruct.ClientMacSecret);
}
}
/// <summary>
/// Key handle for the resulting Server MAC Secret key
/// </summary>
public IObjectHandle ServerMacSecret
{
get
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
return new ObjectHandle(_lowLevelStruct.ServerMacSecret);
}
}
/// <summary>
/// Key handle for the resulting Client Secret key
/// </summary>
public IObjectHandle ClientKey
{
get
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
return new ObjectHandle(_lowLevelStruct.ClientKey);
}
}
/// <summary>
/// Key handle for the resulting Server Secret key
/// </summary>
public IObjectHandle ServerKey
{
get
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
return new ObjectHandle(_lowLevelStruct.ServerKey);
}
}
/// <summary>
/// Initialization vector (IV) created for the client
/// </summary>
public byte[] IVClient
{
get
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
return (_ivLength < 1) ? null : UnmanagedMemory.Read(_lowLevelStruct.IVClient, ConvertUtils.UInt64ToInt32(_ivLength));
}
}
/// <summary>
/// Initialization vector (IV) created for the server
/// </summary>
public byte[] IVServer
{
get
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
return (_ivLength < 1) ? null : UnmanagedMemory.Read(_lowLevelStruct.IVServer, ConvertUtils.UInt64ToInt32(_ivLength));
}
}
/// <summary>
/// The length of initialization vectors
/// </summary>
private NativeULong _ivLength = 0;
/// <summary>
/// Initializes a new instance of the CkSsl3KeyMatOut class.
/// </summary>
/// <param name='ivLength'>Length of initialization vectors or 0 if IVs are not required</param>
internal CkSsl3KeyMatOut(NativeULong ivLength)
{
_lowLevelStruct.ClientMacSecret = 0;
_lowLevelStruct.ServerMacSecret = 0;
_lowLevelStruct.ClientKey = 0;
_lowLevelStruct.ServerKey = 0;
_lowLevelStruct.IVClient = IntPtr.Zero;
_lowLevelStruct.IVServer = IntPtr.Zero;
_ivLength = ivLength;
if (_ivLength > 0)
{
_lowLevelStruct.IVClient = UnmanagedMemory.Allocate(ConvertUtils.UInt64ToInt32(_ivLength));
_lowLevelStruct.IVServer = UnmanagedMemory.Allocate(ConvertUtils.UInt64ToInt32(_ivLength));
}
}
#region IDisposable
/// <summary>
/// Disposes object
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes object
/// </summary>
/// <param name="disposing">Flag indicating whether managed resources should be disposed</param>
protected virtual void Dispose(bool disposing)
{
if (!this._disposed)
{
if (disposing)
{
// Dispose managed objects
}
// Dispose unmanaged objects
UnmanagedMemory.Free(ref _lowLevelStruct.IVClient);
UnmanagedMemory.Free(ref _lowLevelStruct.IVServer);
_disposed = true;
}
}
/// <summary>
/// Class destructor that disposes object if caller forgot to do so
/// </summary>
~CkSsl3KeyMatOut()
{
Dispose(false);
}
#endregion
}
}
| |
using System;
using System.Threading;
using Lucene.Net.Attributes;
using Lucene.Net.Documents;
namespace Lucene.Net.Index
{
using Lucene.Net.Search;
using Lucene.Net.Store;
using Lucene.Net.Support;
/*
/// Copyright 2004 The Apache Software Foundation
///
/// 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 Lucene.Net.Util;
using NUnit.Framework;
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using OpenMode_e = Lucene.Net.Index.IndexWriterConfig.OpenMode_e;
[TestFixture]
public class TestStressIndexing : LuceneTestCase
{
private abstract class TimedThread : ThreadClass
{
internal volatile bool Failed;
internal int Count;
internal static int RUN_TIME_MSEC = AtLeast(1000);
internal TimedThread[] AllThreads;
public abstract void DoWork();
internal TimedThread(TimedThread[] threads)
{
this.AllThreads = threads;
}
public override void Run()
{
long stopTime = Environment.TickCount + RUN_TIME_MSEC;
Count = 0;
try
{
do
{
if (AnyErrors())
{
break;
}
DoWork();
Count++;
} while (Environment.TickCount < stopTime);
}
catch (Exception e)
{
Console.WriteLine(Thread.CurrentThread + ": exc");
Console.WriteLine(e.StackTrace);
Failed = true;
}
}
internal virtual bool AnyErrors()
{
for (int i = 0; i < AllThreads.Length; i++)
{
if (AllThreads[i] != null && AllThreads[i].Failed)
{
return true;
}
}
return false;
}
}
private class IndexerThread : TimedThread
{
internal IndexWriter Writer;
internal int NextID;
public IndexerThread(IndexWriter writer, TimedThread[] threads)
: base(threads)
{
this.Writer = writer;
}
public override void DoWork()
{
// Add 10 docs:
for (int j = 0; j < 10; j++)
{
Documents.Document d = new Documents.Document();
int n = Random().Next();
d.Add(NewStringField("id", Convert.ToString(NextID++), Field.Store.YES));
d.Add(NewTextField("contents", English.IntToEnglish(n), Field.Store.NO));
Writer.AddDocument(d);
}
// Delete 5 docs:
int deleteID = NextID - 1;
for (int j = 0; j < 5; j++)
{
Writer.DeleteDocuments(new Term("id", "" + deleteID));
deleteID -= 2;
}
}
}
private class SearcherThread : TimedThread
{
internal Directory Directory;
public SearcherThread(Directory directory, TimedThread[] threads)
: base(threads)
{
this.Directory = directory;
}
public override void DoWork()
{
for (int i = 0; i < 100; i++)
{
IndexReader ir = DirectoryReader.Open(Directory);
IndexSearcher @is = NewSearcher(ir);
ir.Dispose();
}
Count += 100;
}
}
/*
Run one indexer and 2 searchers against single index as
stress test.
*/
public virtual void RunStressTest(Directory directory, IConcurrentMergeScheduler mergeScheduler)
{
IndexWriter modifier = new IndexWriter(directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(OpenMode_e.CREATE).SetMaxBufferedDocs(10).SetMergeScheduler(mergeScheduler));
modifier.Commit();
TimedThread[] threads = new TimedThread[4];
int numThread = 0;
// One modifier that writes 10 docs then removes 5, over
// and over:
IndexerThread indexerThread = new IndexerThread(modifier, threads);
threads[numThread++] = indexerThread;
indexerThread.Start();
IndexerThread indexerThread2 = new IndexerThread(modifier, threads);
threads[numThread++] = indexerThread2;
indexerThread2.Start();
// Two searchers that constantly just re-instantiate the
// searcher:
SearcherThread searcherThread1 = new SearcherThread(directory, threads);
threads[numThread++] = searcherThread1;
searcherThread1.Start();
SearcherThread searcherThread2 = new SearcherThread(directory, threads);
threads[numThread++] = searcherThread2;
searcherThread2.Start();
for (int i = 0; i < numThread; i++)
{
threads[i].Join();
}
modifier.Dispose();
for (int i = 0; i < numThread; i++)
{
Assert.IsTrue(!threads[i].Failed);
}
//System.out.println(" Writer: " + indexerThread.count + " iterations");
//System.out.println("Searcher 1: " + searcherThread1.count + " searchers created");
//System.out.println("Searcher 2: " + searcherThread2.count + " searchers created");
}
/*
Run above stress test against RAMDirectory and then
FSDirectory.
*/
[Test]
public virtual void TestStressIndexAndSearching([ValueSource(typeof(ConcurrentMergeSchedulers), "Values")]IConcurrentMergeScheduler scheduler)
{
Directory directory = NewDirectory();
MockDirectoryWrapper wrapper = directory as MockDirectoryWrapper;
if (wrapper != null)
{
wrapper.AssertNoUnrefencedFilesOnClose = true;
}
RunStressTest(directory, scheduler);
directory.Dispose();
}
}
}
| |
using System;
using System.Collections;
using Intel.UPNP;
using Intel.UPNP.AV;
using Intel.UPNP.AV.CdsMetadata;
using Intel.UPNP.AV.MediaServer;
using Intel.UPNP.AV.MediaServer.CP;
using System.Windows.Forms;
namespace Intel.UPNP.AV.MediaServer.CP
{
/// <summary>
/// Summary description for ServerBrowser.
/// </summary>
public class ServerBrowser
{
public delegate void Delegate_ContentFound(ServerBrowser sender, IUPnPMedia[] added);
public event Delegate_ContentFound OnIncrementalUpdate;
public event Delegate_ContentFound OnRefreshComplete;
private CpMediaServer m_Server = null;
private uint m_BrowseSize = 20;
private uint m_CurrentIndex = 0;
private string m_Filter = "*";
private string m_SortString = "";
private string m_Context = null;
private IMediaContainer m_Container = null;
private ArrayList m_Children = new ArrayList();
/// <summary>
/// Sets the server that this object browses.
/// Must set <see cref="ServerBrowser.Context"/>
/// and call <see cref="Refresh"/>.
/// </summary>
public CpMediaServer Server
{
get
{
return this.m_Server;
}
set
{
if (this.m_Server != value)
{
this.m_Server = value;
this.m_Container = this.m_Server.Root;
}
}
}
/// <summary>
/// <para>
/// Changes this object's browsing context to provided container.
/// Must set <see cref="ServerBrowser.Server"/> beforehand
/// and must call <see cref="ServerBrowser.Refresh"/> afterwards.
/// </para>
/// </summary>
public IMediaContainer Context
{
get
{
return this.m_Container;
}
set
{
CpRootCollectionContainer cprc = value as CpRootCollectionContainer;
this.m_Container = value;
if (cprc == null)
{
this.SetContext(this.m_Container.ID);
}
else
{
this.SetContext(null);
}
}
}
public void Refresh()
{
CpRootCollectionContainer cprc = this.m_Container as CpRootCollectionContainer;
if (cprc == null)
{
lock (this)
{
this.m_CurrentIndex = 0;
this.m_Server.RequestBrowse(
this.m_Context,
CpContentDirectory.Enum_A_ARG_TYPE_BrowseFlag.BROWSEDIRECTCHILDREN,
this.m_Filter,
this.m_CurrentIndex,
this.m_BrowseSize,
this.m_SortString,
this.m_Container,
new CpMediaServer.Delegate_OnBrowseDone1 (Sink_OnBrowse)
);
}
}
}
/// <summary>
/// Manually sets the context, using the provided objectID value.
/// </summary>
/// <param name="context">objectID of a container object</param>
private void SetContext(string context)
{
this.m_Context = context;
}
private void DoNextBrowse()
{
lock (this)
{
this.m_Server.RequestBrowse(
this.m_Context,
CpContentDirectory.Enum_A_ARG_TYPE_BrowseFlag.BROWSEDIRECTCHILDREN,
this.m_Filter,
this.m_CurrentIndex,
this.m_BrowseSize,
this.m_SortString,
this.m_Container,
new CpMediaServer.Delegate_OnBrowseDone1 (Sink_OnBrowse)
);
}
}
/// <summary>
/// Returns the currentcontext (objectID) in string form.
/// </summary>
/// <param name="context"></param>
private string GetContext(string context)
{
return this.m_Context;
}
private void Sink_OnBrowse(CpMediaServer server, System.String ObjectID, Intel.UPNP.AV.CpContentDirectory.Enum_A_ARG_TYPE_BrowseFlag BrowseFlag, System.String Filter, System.UInt32 StartingIndex, System.UInt32 RequestedCount, System.String SortCriteria, UPnPInvokeException e, Exception parseError, object _Tag, IUPnPMedia[] Result, System.UInt32 NumberReturned, System.UInt32 TotalMatches, System.UInt32 UpdateID)
{
if (server == this.m_Server)
{
if (ObjectID == this.m_Context)
{
if (_Tag == this.m_Container)
{
if ((e != null) || (parseError != null))
{
//error encountered
}
else
{
// add children
this.m_Children.AddRange(Result);
this.m_Container.AddObjects(Result, true);
if (this.OnIncrementalUpdate != null)
{
this.OnIncrementalUpdate(this, Result);
}
if (
((this.m_Children.Count == TotalMatches) && (NumberReturned > 0)) ||
((TotalMatches == 0) && (NumberReturned > 0))
)
{
// more items to come
this.m_CurrentIndex = NumberReturned;
DoNextBrowse();
}
else
{
lock (this)
{
// no more items, prune children from m_Container
ArrayList remove = new ArrayList();
foreach (IUPnPMedia m1 in this.m_Container.CompleteList)
{
bool found = false;
foreach (IUPnPMedia m2 in this.m_Children)
{
if (m1 == m2)
{
found = true;
break;
}
}
if (found == false)
{
remove.Add(m1);
}
}
this.m_Container.RemoveObjects(remove);
}
if (this.OnRefreshComplete != null)
{
IUPnPMedia[] list = (IUPnPMedia[]) this.m_Children.ToArray(typeof(IUPnPMedia));
this.OnRefreshComplete(this, list);
}
}
}
}
}
}
}
/// <summary>
/// Changes the number of objects that this objects requests
/// when browsing a server. The change is immediate, causing
/// all subsequent browse requests to use the new browsing size.
/// </summary>
public uint BrowseSize
{
get
{
return this.m_BrowseSize;
}
set
{
this.m_BrowseSize = value;
}
}
}
}
| |
using Aspose.Email.Live.Demos.UI.Models;
using Aspose.Email.Live.Demos.UI.Services.Email;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
namespace Aspose.Email.Live.Demos.UI.Controllers
{
using Aspose.Email.Live.Demos.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
///<Summary>
/// AsposeViewerController class to get document page
///</Summary>
public class AsposeEmailViewerController : AsposeEmailBaseApiController
{
public AsposeEmailViewerController(ILogger<AsposeEmailViewerController> logger,
IConfiguration config,
IStorageService storageService,
IEmailService emailService)
: base(logger, config, storageService, emailService)
{
}
///<Summary>
/// DocumentPages method to get document pages
///</Summary>
[HttpGet("DocumentPages")]
public async Task<List<string>> BuildAndStoreDocumentPages(string file, string folderName)
{
var logMessage = "ControllerName = AsposeViewerController, MethodName = DocumentPages, Folder = " + folderName;
var output = new List<string>();
try
{
var viewerImages = await GetDocumentPages(file, folderName);
var names = viewerImages.GetOrderedPageNames();
var format = "Page {0} ({1})";
output.Add(names.Length.ToString());
var imagesFolderName = Guid.NewGuid().ToString();
for (int k = 0; k < names.Length; k++)
{
using (var fileStream = viewerImages.OpenReadStream(names[k]))
{
var imageName = string.Format(format, k + 1, names[k]);
await StorageService.SaveFile(fileStream, imagesFolderName, imageName);
fileStream.Position = 0;
using (var image = Aspose.Imaging.Image.Load(fileStream))
{
var token = new JObject()
{
{ "ImageName", imageName },
{ "ImageSize", $"{image.Width} x {image.Height}" },
{ "ImageFolderName", imagesFolderName }
};
output.Add(token.ToString());
}
}
}
Logger.LogInformation(logMessage, AsposeEmail, file);
}
catch(BadRequestException ex)
{
throw;
}
catch (Exception ex)
{
Logger.LogError(ex, logMessage, AsposeEmail, file);
throw;
}
return output;
}
private async Task<ViewerImagesOutputHandler> GetDocumentPages(
string file,
string folderName)
{
if (file.IsNullOrWhiteSpace())
throw new BadRequestException("File name not provided");
if (folderName.IsNullOrWhiteSpace())
throw new BadRequestException("Folder name not provided");
var filename = file;
// Page file name format
var format = "Page {0} ({1})";
// We will save all outputs in viewer format
var viewerImagesHandler = new ViewerImagesOutputHandler(format + ".jpg");
// Convert main file to jpg images
using (var input = await StorageService.ReadFile(folderName, filename))
{
EmailService.Convert(input, filename, viewerImagesHandler, "jpg");
// TODO: add full support for downloading attachments images (not only on viewing)
//input.Position = 0;
//service.ExtractAttachmentsAsJpgImages(input, filename, viewerImagesHandler);
}
//await viewerImagesHandler.SaveAllImagesInStorage();
return viewerImagesHandler;
}
///<Summary>
/// DownloadDocument method to download document
///</Summary>
[HttpGet("DownloadDocument")]
public async Task<IActionResult> DownloadDocument(string file, string folderName)
{
string logMsg = "ControllerName = AsposeEmailViewerController, MethodName = DownloadDocument, Folder = " + folderName;
try
{
using (var stream = await StorageService.ReadFile(folderName, file))
{
Logger.LogInformation(logMsg, AsposeEmail, file);
using (var ms = new MemoryStream())
{
await stream.CopyToAsync(ms);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(ms.ToArray())
};
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = file
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return result.ToActionResult();
}
}
}
catch (Exception x)
{
Logger.LogError(x, logMsg, AsposeEmail, file);
throw;
}
}
///<Summary>
/// PageImage method to get page image
///</Summary>
[HttpGet("PageImage")]
public async Task<IActionResult> PageImage(string imageFolderName, string imageFileName)
{
return (await GetImageFromStorage(imageFolderName, imageFileName)).ToActionResult();
}
private async Task<HttpResponseMessage> GetImageFromStorage(string imageFolderName, string imageFileName)
{
if (!await StorageService.IsFileExists(imageFolderName, imageFileName))
{
return new HttpResponseMessage(HttpStatusCode.NoContent);
}
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var fileExt = Path.GetExtension(imageFileName).ToLower();
string contentType = null;
switch (fileExt)
{
case ".png":
case ".apng":
contentType = "image/png";
break;
case ".jpg":
case ".jpeg":
contentType = "image/jpeg";
break;
case ".gif":
contentType = "image/gif";
break;
case ".webp":
contentType = "image/webp";
break;
case ".svg":
contentType = "image/svg+xml";
break;
}
if (contentType != null)
{
using (var imageStream = await StorageService.ReadFile(imageFolderName, imageFileName))
{
using (var ms = new MemoryStream())
{
await imageStream.CopyToAsync(ms);
result.Content = new ByteArrayContent(ms.ToArray());
result.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
return result;
}
}
}
using (var imageStream = await StorageService.ReadFile(imageFolderName, imageFileName))
{
var image = System.Drawing.Image.FromStream(imageStream);
var memoryStream = new MemoryStream();
image.Save(memoryStream, ImageFormat.Jpeg);
result.Content = new ByteArrayContent(memoryStream.ToArray());
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
}
return result;
}
}
}
| |
using System;
using System.IO;
using System.Collections;
using System.Collections.Specialized;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace SpiffLib {
class TBitmapTools {
public static Bitmap ScaleBitmap(Bitmap bm, double nScale, Palette palFixed) {
Color[] aclrSpecial = new Color[] {
// side colors
Color.FromArgb(0, 116, 232),
Color.FromArgb(0, 96, 196),
Color.FromArgb(0, 64, 120),
Color.FromArgb(0, 48, 92),
Color.FromArgb(0, 32, 64),
// transparent
Color.FromArgb(255, 0, 255),
// shadow
Color.FromArgb(156, 212, 248),
};
Bitmap bmNew = new Bitmap((int)Math.Floor(bm.Width * nScale + 0.5), (int)Math.Floor(bm.Height * nScale + 0.5));
for (int y = 0; y < bmNew.Height; y++) {
for (int x = 0; x < bmNew.Width; x++) {
double nWidthRatio = (double)bm.Width / (double)bmNew.Width;
double xLeft = (double)x * nWidthRatio;
double nHeightRatio = (double)bm.Height / (double)bmNew.Height;
double yTop = (double)y * nHeightRatio;
double xRight = xLeft + 1.0 * nWidthRatio;
if (xRight > bm.Width)
xRight = bm.Width;
double yBottom = yTop + 1.0 * nHeightRatio;
if (yBottom > bm.Height)
yBottom = bm.Height;
DoubleRect drc = new DoubleRect(xLeft, yTop, xRight, yBottom);
Color clrSample = SampleGobBitmap(bm, drc, aclrSpecial, 4);
if (palFixed != null) {
bool fSpecial = false;
foreach (Color clrSpecial in aclrSpecial) {
if (clrSample == clrSpecial) {
fSpecial = true;
break;
}
}
if (!fSpecial)
clrSample = palFixed[palFixed.FindClosestEntry(clrSample)];
}
bmNew.SetPixel(x, y, clrSample);
}
}
return bmNew;
}
static Color SampleGobBitmap(Bitmap bm, DoubleRect drc, Color[] aclrSpecial, int iclrSideLast) {
int r = 0;
int g = 0;
int b = 0;
// First figure out amount of special color
double nAreaSide = 0.0;
double nAreaSpecial = 0.0;
double nAreaTotal = drc.Width * drc.Height;
double[] anAreaColorSpecial = new double[aclrSpecial.Length];
for (int y = (int)Math.Floor(drc.top); y < (int)Math.Ceiling(drc.bottom); y++) {
for (int x = (int)Math.Floor(drc.left); x < (int)Math.Ceiling(drc.right); x++) {
// Calc the area taken by this pixel fragment
DoubleRect drcPixel = new DoubleRect(x, y, x + 1.0, y + 1.0);
drcPixel.Intersect(drc);
double nAreaPixel = drcPixel.Width * drcPixel.Height;
// Is this is a special color? Remember which and area taken
Color clr = bm.GetPixel(x, y);
for (int iclr = 0; iclr < aclrSpecial.Length; iclr++) {
if (clr == aclrSpecial[iclr]) {
anAreaColorSpecial[iclr] += nAreaPixel;
nAreaSpecial += nAreaPixel;
if (iclr <= iclrSideLast)
nAreaSide += nAreaPixel;
break;
}
}
}
}
// If percent of special color area is over a given threshold, return a special color
if (nAreaSpecial / nAreaTotal >= 0.5) {
// Which was most popular?
double nAreaMax = -1.0;
int iclrMax = -1;
for (int iclr = 0; iclr < aclrSpecial.Length; iclr++) {
if (anAreaColorSpecial[iclr] > nAreaMax) {
nAreaMax = anAreaColorSpecial[iclr];
iclrMax = iclr;
}
}
// If not a side color, return it
if (iclrMax > iclrSideLast && nAreaMax > nAreaSide)
return aclrSpecial[iclrMax];
// Otherwise blend and color match side colors.
nAreaTotal = nAreaSide;
for (int y = (int)Math.Floor(drc.top); y < (int)Math.Ceiling(drc.bottom); y++) {
for (int x = (int)Math.Floor(drc.left); x < (int)Math.Ceiling(drc.right); x++) {
// Is this is a special color? Remember which and area taken
bool fSideColor = false;
Color clr = bm.GetPixel(x, y);
for (int iclr = 0; iclr < aclrSpecial.Length; iclr++) {
if (clr == aclrSpecial[iclr]) {
if (iclr <= iclrSideLast)
fSideColor = true;
break;
}
}
if (!fSideColor)
continue;
// Calc the % of whole taken by this pixel fragment
DoubleRect drcPixel = new DoubleRect(x, y, x + 1.0, y + 1.0);
drcPixel.Intersect(drc);
double nAreaPixel = drcPixel.Width * drcPixel.Height;
double nPercentPixel = nAreaPixel / nAreaTotal;
// Add in the color components
r += (int)(clr.R * nPercentPixel);
g += (int)(clr.G * nPercentPixel);
b += (int)(clr.B * nPercentPixel);
}
}
// Now color match to the closest side color
int dMax = int.MaxValue;
int iclrClosest = -1;
for (int iclr = 0; iclr <= iclrSideLast; iclr++) {
Color clrSide = aclrSpecial[iclr];
int dr = r - clrSide.R;
int dg = g - clrSide.G;
int db = b - clrSide.B;
int d = dr * dr + dg * dg + db * db;
if (d < dMax) {
dMax = d;
iclrClosest = iclr;
}
}
// Have our color...
return aclrSpecial[iclrClosest];
}
// Otherwise add in the color components of each non-special color pixel fragment.
// Subtract the special color area from the total area since we won't be
// including it.
nAreaTotal -= nAreaSpecial;
for (int y = (int)Math.Floor(drc.top); y < (int)Math.Ceiling(drc.bottom); y++) {
for (int x = (int)Math.Floor(drc.left); x < (int)Math.Ceiling(drc.right); x++) {
// Is this is a special color? If so ignore it
bool fSpecial = false;
Color clr = bm.GetPixel(x, y);
for (int iclr = 0; iclr < aclrSpecial.Length; iclr++) {
if (clr == aclrSpecial[iclr]) {
fSpecial = true;
break;
}
}
if (fSpecial)
continue;
// Calc the % of whole taken by this pixel fragment
DoubleRect drcPixel = new DoubleRect(x, y, x + 1.0, y + 1.0);
drcPixel.Intersect(drc);
double nAreaPixel = drcPixel.Width * drcPixel.Height;
double nPercentPixel = nAreaPixel / nAreaTotal;
// Add in the color components
r += (int)(clr.R * nPercentPixel);
g += (int)(clr.G * nPercentPixel);
b += (int)(clr.B * nPercentPixel);
}
}
return Color.FromArgb(r, g, b);
}
}
}
| |
// Copyright (c) 2014 SIL International
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)
// Parts based on code by MJ Hutchinson http://mjhutchinson.com/journal/2010/01/25/integrating_gtk_application_mac
// Parts based on code by bugsnag-dotnet (https://github.com/bugsnag/bugsnag-dotnet/blob/v1.4/src/Bugsnag/Diagnostics.cs)
using System;
using System.Diagnostics;
#if !NETSTANDARD2_0
using System.Management;
#endif
using System.Runtime.InteropServices;
namespace SIL.PlatformUtilities
{
public static class Platform
{
private static bool? _isMono;
private static string _sessionManager;
public static bool IsUnix => Environment.OSVersion.Platform == PlatformID.Unix;
public static bool IsWasta => IsUnix && System.IO.File.Exists("/etc/wasta-release");
public static bool IsCinnamon => IsUnix && SessionManager.StartsWith("/usr/bin/cinnamon-session");
public static bool IsMono
{
get
{
if (_isMono == null)
_isMono = Type.GetType("Mono.Runtime") != null;
return (bool)_isMono;
}
}
public static bool IsDotNet => !IsMono;
#if NETSTANDARD2_0
public static bool IsLinux => RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
public static bool IsMac => RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
public static bool IsWindows => RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
public static bool IsDotNetCore => RuntimeInformation.FrameworkDescription == ".NET Core";
public static bool IsDotNetFramework => IsDotNet && RuntimeInformation.FrameworkDescription == ".NET Framework";
#elif NET461
private static readonly string UnixNameMac = "Darwin";
private static readonly string UnixNameLinux = "Linux";
public static bool IsLinux => IsUnix && UnixName == UnixNameLinux;
public static bool IsMac => IsUnix && UnixName == UnixNameMac;
public static bool IsWindows => !IsUnix;
public static bool IsDotNetCore => false;
public static bool IsDotNetFramework => IsDotNet;
private static string _unixName;
private static string UnixName
{
get
{
if (_unixName == null)
{
IntPtr buf = IntPtr.Zero;
try
{
buf = Marshal.AllocHGlobal(8192);
// This is a hacktastic way of getting sysname from uname ()
if (uname(buf) == 0)
_unixName = Marshal.PtrToStringAnsi(buf);
}
catch
{
_unixName = String.Empty;
}
finally
{
if (buf != IntPtr.Zero)
Marshal.FreeHGlobal(buf);
}
}
return _unixName;
}
}
[DllImport("libc")]
private static extern int uname(IntPtr buf);
#endif
/// <summary>
/// On a Unix machine this gets the current desktop environment (gnome/xfce/...), on
/// non-Unix machines the platform name.
/// </summary>
public static string DesktopEnvironment
{
get
{
if (!IsUnix)
return Environment.OSVersion.Platform.ToString();
// see http://unix.stackexchange.com/a/116694
// and http://askubuntu.com/a/227669
string currentDesktop = Environment.GetEnvironmentVariable("XDG_CURRENT_DESKTOP");
if (string.IsNullOrEmpty(currentDesktop))
{
var dataDirs = Environment.GetEnvironmentVariable("XDG_DATA_DIRS");
if (dataDirs != null)
{
dataDirs = dataDirs.ToLowerInvariant();
if (dataDirs.Contains("xfce"))
currentDesktop = "XFCE";
else if (dataDirs.Contains("kde"))
currentDesktop = "KDE";
else if (dataDirs.Contains("gnome"))
currentDesktop = "Gnome";
}
if (string.IsNullOrEmpty(currentDesktop))
currentDesktop = Environment.GetEnvironmentVariable("GDMSESSION") ?? string.Empty;
}
// Special case for Wasta 12
else if (currentDesktop == "GNOME" && Environment.GetEnvironmentVariable("GDMSESSION") == "cinnamon")
currentDesktop = Environment.GetEnvironmentVariable("GDMSESSION");
return currentDesktop?.ToLowerInvariant();
}
}
/// <summary>
/// Get the currently running desktop environment (like Unity, Gnome shell etc)
/// </summary>
public static string DesktopEnvironmentInfoString
{
get
{
if (!IsUnix)
return string.Empty;
// see http://unix.stackexchange.com/a/116694
// and http://askubuntu.com/a/227669
string currentDesktop = DesktopEnvironment;
string mirSession = Environment.GetEnvironmentVariable("MIR_SERVER_NAME");
var additionalInfo = string.Empty;
if (!string.IsNullOrEmpty(mirSession))
additionalInfo = " [display server: Mir]";
string gdmSession = Environment.GetEnvironmentVariable("GDMSESSION") ?? "not set";
return $"{currentDesktop} ({gdmSession}{additionalInfo})";
}
}
private static string SessionManager
{
get
{
if (_sessionManager == null)
{
IntPtr buf = IntPtr.Zero;
try
{
// This is the only way I've figured out to get the session manager: read the
// symbolic link destination value.
buf = Marshal.AllocHGlobal(8192);
var len = readlink("/etc/alternatives/x-session-manager", buf, 8192);
if (len > 0)
{
// For some reason, Marshal.PtrToStringAnsi() sometimes returns null in Mono.
// Copying the bytes and then converting them to a string avoids that problem.
// Filenames are likely to be in UTF-8 on Linux if they are not pure ASCII.
var bytes = new byte[len];
Marshal.Copy(buf, bytes, 0, len);
_sessionManager = System.Text.Encoding.UTF8.GetString(bytes);
}
if (_sessionManager == null)
_sessionManager = string.Empty;
}
catch
{
_sessionManager = string.Empty;
}
finally
{
if (buf != IntPtr.Zero)
Marshal.FreeHGlobal(buf);
}
}
return _sessionManager;
}
}
[DllImport("libc")]
private static extern int readlink(string path, IntPtr buf, int bufsiz);
[DllImport("__Internal", EntryPoint = "mono_get_runtime_build_info")]
private static extern string GetMonoVersion();
/// <summary>
/// Gets the version of the currently running Mono (e.g.
/// "5.0.1.1 (2017-02/5077205 Thu May 25 09:16:53 UTC 2017)"), or the empty string
/// on Windows.
/// </summary>
public static string MonoVersion => IsMono ? GetMonoVersion() : string.Empty;
/// <summary>
/// Gets a string that describes the OS, e.g. 'Windows 10' or 'Ubuntu 16.04 LTS'
/// </summary>
/// <remarks>Note that you might have to add an app.config file to your executable
/// that lists the supported Windows versions in order to get the correct Windows version
/// reported (https://msdn.microsoft.com/en-us/library/windows/desktop/aa374191.aspx)!
/// </remarks>
public static string OperatingSystemDescription
{
get
{
switch (Environment.OSVersion.Platform)
{
// Platform is Windows 95, Windows 98, Windows 98 Second Edition,
// or Windows Me.
case PlatformID.Win32Windows:
// Platform is Windows 95, Windows 98, Windows 98 Second Edition,
// or Windows Me.
switch (Environment.OSVersion.Version.Minor)
{
case 0:
return "Windows 95";
case 10:
return "Windows 98";
case 90:
return "Windows Me";
default:
return "UNKNOWN";
}
case PlatformID.Win32NT:
return GetWin32NTVersion();
case PlatformID.Unix:
case PlatformID.MacOSX:
return UnixOrMacVersion();
default:
return "UNKNOWN";
}
}
}
/// <summary>
/// Detects the current operating system version if its Win32 NT
/// </summary>
/// <returns>The operation system version</returns>
private static string GetWin32NTVersion()
{
switch (Environment.OSVersion.Version.Major)
{
case 3:
return "Windows NT 3.51";
case 4:
return "Windows NT 4.0";
case 5:
return Environment.OSVersion.Version.Minor == 0 ? "Windows 2000" : "Windows XP";
case 6:
switch (Environment.OSVersion.Version.Minor)
{
case 0:
return "Windows Server 2008";
case 1:
return IsWindowsServer ? "Windows Server 2008 R2" : "Windows 7";
case 2:
return IsWindowsServer ? "Windows Server 2012" : "Windows 8";
case 3:
return IsWindowsServer ? "Windows Server 2012 R2" : "Windows 8.1";
default:
return "UNKNOWN";
}
case 10:
return "Windows 10";
default:
return "UNKNOWN";
}
}
// https://stackoverflow.com/a/3138781/487503
private static bool IsWindowsServer => IsOS(OS_ANYSERVER);
private const int OS_ANYSERVER = 29;
[DllImport("shlwapi.dll", SetLastError=true)]
private static extern bool IsOS(int os);
/// <summary>
/// Determines the OS version if on a UNIX based system
/// </summary>
/// <returns></returns>
private static string UnixOrMacVersion()
{
if (RunTerminalCommand("uname") == "Darwin")
{
var osName = RunTerminalCommand("sw_vers", "-productName");
var osVersion = RunTerminalCommand("sw_vers", "-productVersion");
return osName + " (" + osVersion + ")";
}
var distro = RunTerminalCommand("bash", "-c \"[ $(which lsb_release) ] && lsb_release -d -s\"");
return string.IsNullOrEmpty(distro) ? "UNIX" : distro;
}
/// <summary>
/// Executes a command with arguments, used to send terminal commands in UNIX systems
/// </summary>
/// <param name="cmd">The command to send</param>
/// <param name="args">The arguments to send</param>
/// <returns>The returned output</returns>
private static string RunTerminalCommand(string cmd, string args = null)
{
var proc = new Process {
EnableRaisingEvents = false,
StartInfo = {
FileName = cmd,
Arguments = args,
UseShellExecute = false,
RedirectStandardOutput = true
}
};
proc.Start();
proc.WaitForExit();
var output = proc.StandardOutput.ReadToEnd();
return output.Trim();
}
}
}
| |
namespace Theater
{
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using SystemActors;
using SystemMessages;
public class ActorSystem
{
protected IDictionary <string, ActorReference> ActorReferences = new Dictionary <string, ActorReference> ();
protected ActorSystemConfiguration Configuration;
protected ConcurrentPriorityQueue <Envelope> EnvelopeQueue = new ConcurrentPriorityQueue <Envelope> ();
protected IDictionary <string, Mailbox> Mailboxes = new Dictionary <string, Mailbox> ();
protected IList <ActorReference> Processors = new List <ActorReference> ();
protected SpinLock Spin = new SpinLock ();
public ActorSystem (ActorSystemConfiguration configuration)
{
Configuration = configuration;
DeadLetter = ActorOf <DeadLetterActor> ();
for (var i = 0; i < configuration.NumberOfThreads; i++)
{
Processors.Add (ActorOf <EnvelopeProcessor> ($"EnvelopeProcessor@{i}", i));
}
}
public ActorSystem () : this (new ActorSystemConfiguration ())
{
}
public ActorReference DeadLetter { get; set; }
public void Shutdown ()
{
foreach (var processor in Processors)
{
processor.Tell (new EnvelopeProcessorShutdownMessage
{
Cause = @"ActorSystem requested shutdown"
}, null, Priorities.RealTime);
}
}
public void Tell (ActorReference target, object message, ActorReference sender = null, Priorities priority = Priorities.Normal)
{
var envelope = new Envelope
{
Message = message,
Sender = sender,
Target = target
};
EnvelopeQueue.Enqueue (envelope, priority);
}
public Task <object> Ask (ActorReference target, object message, ActorReference sender, Priorities priority = Priorities.Normal)
{
if (sender == target)
{
throw new Exception ("An actor cannot Ask to itself.");
}
var envelope = new Envelope
{
Message = message,
Sender = sender,
Target = target,
TaskCompletionSource = new TaskCompletionSource <object> ()
};
sender.PendingReplies++;
EnvelopeQueue.Enqueue (envelope, priority);
return envelope.TaskCompletionSource.Task;
}
public ActorReference ActorOf <T> (string name, object initializationData, Mailbox mailbox) where T : Actor, new ()
{
var reference = CreateActorReference (name, mailbox);
Actor actor = new T ();
actor.Self = reference;
reference.State = ActorStates.Initializing;
actor.Initialize (initializationData);
var lockTaken = false;
try
{
Spin.Enter (ref lockTaken);
reference.State = ActorStates.Idle;
mailbox.EnqueueActor (actor);
}
finally
{
if (lockTaken)
{
Spin.Exit (false);
}
}
return reference;
}
public ActorReference ActorOf <T> (string name = null, object initializationData = null) where T : Actor, new ()
{
var normalizedName = NormalizeName <T> (name);
return ActorOf <T> (normalizedName, initializationData, CreateMailbox (normalizedName));
}
public ActorReference ClusterOf <T> (string name = null, object initializationData = null) where T : Actor, new ()
{
var normalizedName = NormalizeName <T> (name);
var mailbox = CreateMailbox (normalizedName);
var reference = CreateActorReference (normalizedName, mailbox);
for (var i = 0; i < Configuration.NumberOfThreads; i++)
{
ActorOf <T> ($"{normalizedName}@{i}", initializationData, mailbox);
}
return reference;
}
protected string NormalizeName <T> (string name)
{
if (string.IsNullOrEmpty (name))
{
name = typeof (T).Name;
}
return name;
}
protected Mailbox CreateMailbox (string name)
{
var lockTaken = false;
try
{
Spin.Enter (ref lockTaken);
if (Mailboxes.ContainsKey (name))
{
throw new Exception ("There's already a Mailbox with this name. Possible duplicate actor.");
}
var mailbox = new Mailbox ();
Mailboxes.Add (name, mailbox);
return mailbox;
}
finally
{
if (lockTaken)
{
Spin.Exit (false);
}
}
}
protected ActorReference CreateActorReference (string name, Mailbox mailbox)
{
var lockTaken = false;
try
{
Spin.Enter (ref lockTaken);
ActorReference reference;
if (!ActorReferences.TryGetValue (name, out reference))
{
reference = new ActorReference
{
Name = name,
ActorSystem = this,
Mailbox = mailbox
};
ActorReferences.Add (name, reference);
}
else
{
reference.Mailbox = mailbox;
}
return reference;
}
finally
{
if (lockTaken)
{
Spin.Exit (false);
}
}
}
public ActorReference FindActor (string name)
{
var lockTaken = false;
try
{
Spin.Enter (ref lockTaken);
ActorReference reference;
if (ActorReferences.TryGetValue (name, out reference))
{
return reference;
}
else
{
reference = new ActorReference
{
Name = name,
ActorSystem = this
};
ActorReferences.Add (name, reference);
return reference;
}
}
finally
{
if (lockTaken)
{
Spin.Exit (false);
}
}
}
public bool DequeueEnvelopeAndMatchingActor (uint processorAffinity, out Envelope envelope, out Actor actor)
{
var lockTaken = false;
try
{
Spin.Enter (ref lockTaken);
envelope = EnvelopeQueue.Dequeue (item => ((item.Target.ProcessorAffinity & processorAffinity) != 0)
&& ((item.Message is IInternalMessage) || item.Target.Mailbox.Available));
if (envelope != null)
{
actor = (envelope.Message is IInternalMessage)
? null
: envelope.Target.Mailbox.DequeueActor ();
return true;
}
else
{
actor = null;
return false;
}
}
finally
{
if (lockTaken)
{
Spin.Exit (false);
}
}
}
public void EnqueueActorBackToMailbox (Mailbox mailbox, Actor actor)
{
var lockTaken = false;
try
{
Spin.Enter (ref lockTaken);
mailbox.EnqueueActor (actor);
}
finally
{
if (lockTaken)
{
Spin.Exit (false);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Pathoschild.Stardew.Common.Items.ItemData;
using Pathoschild.Stardew.Common.UI;
using StardewModdingAPI;
using StardewValley;
using StardewValley.Locations;
using StardewValley.Menus;
using StardewValley.Objects;
using StardewValley.Tools;
using SObject = StardewValley.Object;
namespace Pathoschild.Stardew.Common
{
/// <summary>Provides common utility methods for interacting with the game code shared by my various mods.</summary>
internal static class CommonHelper
{
/*********
** Fields
*********/
/// <summary>A blank pixel which can be colorized and stretched to draw geometric shapes.</summary>
private static readonly Lazy<Texture2D> LazyPixel = new Lazy<Texture2D>(() =>
{
Texture2D pixel = new Texture2D(Game1.graphics.GraphicsDevice, 1, 1);
pixel.SetData(new[] { Color.White });
return pixel;
});
/// <summary>The width of the borders drawn by <see cref="DrawTab"/>.</summary>
public const int ButtonBorderWidth = 4 * Game1.pixelZoom;
/*********
** Accessors
*********/
/// <summary>A blank pixel which can be colorized and stretched to draw geometric shapes.</summary>
public static Texture2D Pixel => CommonHelper.LazyPixel.Value;
/// <summary>The width of the horizontal and vertical scroll edges (between the origin position and start of content padding).</summary>
public static readonly Vector2 ScrollEdgeSize = new Vector2(CommonSprites.Scroll.TopLeft.Width * Game1.pixelZoom, CommonSprites.Scroll.TopLeft.Height * Game1.pixelZoom);
/*********
** Public methods
*********/
/****
** Enums
****/
/// <summary>Get the values in an enum.</summary>
/// <typeparam name="TValue">The enum value type.</typeparam>
public static IEnumerable<TValue> GetEnumValues<TValue>() where TValue : struct
{
return Enum.GetValues(typeof(TValue)).Cast<TValue>();
}
/****
** Game
****/
/// <summary>Get all game locations.</summary>
/// <param name="includeTempLevels">Whether to include temporary mine/dungeon locations.</param>
public static IEnumerable<GameLocation> GetLocations(bool includeTempLevels = false)
{
var locations = Game1.locations
.Concat(
from location in Game1.locations.OfType<BuildableGameLocation>()
from building in location.buildings
where building.indoors.Value != null
select building.indoors.Value
);
if (includeTempLevels)
locations = locations.Concat(MineShaft.activeMines).Concat(VolcanoDungeon.activeLevels);
return locations;
}
/// <summary>Get a player's current tile position.</summary>
/// <param name="player">The player to check.</param>
public static Vector2 GetPlayerTile(Farmer player)
{
Vector2 position = player?.Position ?? Vector2.Zero;
return new Vector2((int)(position.X / Game1.tileSize), (int)(position.Y / Game1.tileSize)); // note: player.getTileLocationPoint() isn't reliable in many cases, e.g. right after a warp when riding a horse
}
/// <summary>Get the item type for an item to disambiguate IDs.</summary>
/// <param name="item">The item to check.</param>
public static ItemType GetItemType(this Item item)
{
switch (item)
{
case Boots:
return ItemType.Boots;
case Clothing:
return ItemType.Clothing;
case Furniture:
return ItemType.Furniture;
case Hat:
return ItemType.Hat;
case MeleeWeapon:
case Slingshot:
return ItemType.Weapon;
case Ring:
return ItemType.Ring;
case Tool:
return ItemType.Tool;
case Wallpaper wallpaper:
return wallpaper.isFloor.Value
? ItemType.Flooring
: ItemType.Wallpaper;
case SObject obj:
return obj.bigCraftable.Value
? ItemType.BigCraftable
: ItemType.Object;
default:
return ItemType.Unknown;
}
}
/****
** Fonts
****/
/// <summary>Get the dimensions of a space character.</summary>
/// <param name="font">The font to measure.</param>
public static float GetSpaceWidth(SpriteFont font)
{
return font.MeasureString("A B").X - font.MeasureString("AB").X;
}
/****
** UI
****/
/// <summary>Draw a sprite to the screen.</summary>
/// <param name="batch">The sprite batch.</param>
/// <param name="sheet">The sprite sheet containing the sprite.</param>
/// <param name="sprite">The sprite coordinates and dimensions in the sprite sheet.</param>
/// <param name="x">The X-position at which to draw the sprite.</param>
/// <param name="y">The X-position at which to draw the sprite.</param>
/// <param name="width">The width to draw.</param>
/// <param name="height">The height to draw.</param>
/// <param name="color">The color to tint the sprite.</param>
public static void Draw(this SpriteBatch batch, Texture2D sheet, Rectangle sprite, int x, int y, int width, int height, Color? color = null)
{
batch.Draw(sheet, new Rectangle(x, y, width, height), sprite, color ?? Color.White);
}
/// <summary>Draw a pretty hover box for the given text.</summary>
/// <param name="spriteBatch">The sprite batch being drawn.</param>
/// <param name="label">The text to display.</param>
/// <param name="position">The position at which to draw the text.</param>
/// <param name="wrapWidth">The maximum width to display.</param>
public static Vector2 DrawHoverBox(SpriteBatch spriteBatch, string label, in Vector2 position, float wrapWidth)
{
const int paddingSize = 27;
const int gutterSize = 20;
Vector2 labelSize = spriteBatch.DrawTextBlock(Game1.smallFont, label, position + new Vector2(gutterSize), wrapWidth); // draw text to get wrapped text dimensions
IClickableMenu.drawTextureBox(spriteBatch, Game1.menuTexture, new Rectangle(0, 256, 60, 60), (int)position.X, (int)position.Y, (int)labelSize.X + paddingSize + gutterSize, (int)labelSize.Y + paddingSize, Color.White);
spriteBatch.DrawTextBlock(Game1.smallFont, label, position + new Vector2(gutterSize), wrapWidth); // draw again over texture box
return labelSize + new Vector2(paddingSize);
}
/// <summary>Draw a tab texture to the screen.</summary>
/// <param name="spriteBatch">The sprite batch to which to draw.</param>
/// <param name="x">The X position at which to draw.</param>
/// <param name="y">The Y position at which to draw.</param>
/// <param name="innerWidth">The width of the button's inner content.</param>
/// <param name="innerHeight">The height of the button's inner content.</param>
/// <param name="innerDrawPosition">The position at which the content should be drawn.</param>
/// <param name="align">The button's horizontal alignment relative to <paramref name="x"/>. The possible values are 0 (left), 1 (center), or 2 (right).</param>
/// <param name="alpha">The button opacity, as a value from 0 (transparent) to 1 (opaque).</param>
/// <param name="forIcon">Whether the button will contain an icon instead of text.</param>
/// <param name="drawShadow">Whether to draw a shadow under the tab.</param>
public static void DrawTab(SpriteBatch spriteBatch, int x, int y, int innerWidth, int innerHeight, out Vector2 innerDrawPosition, int align = 0, float alpha = 1, bool forIcon = false, bool drawShadow = true)
{
// calculate outer coordinates
int outerWidth = innerWidth + CommonHelper.ButtonBorderWidth * 2;
int outerHeight = innerHeight + Game1.tileSize / 3;
int offsetX = align switch
{
1 => -outerWidth / 2,
2 => -outerWidth,
_ => 0
};
// calculate inner coordinates
{
int iconOffsetX = forIcon ? -Game1.pixelZoom : 0;
int iconOffsetY = forIcon ? 2 * -Game1.pixelZoom : 0;
innerDrawPosition = new Vector2(x + CommonHelper.ButtonBorderWidth + offsetX + iconOffsetX, y + CommonHelper.ButtonBorderWidth + iconOffsetY);
}
// draw texture
IClickableMenu.drawTextureBox(spriteBatch, Game1.menuTexture, new Rectangle(0, 256, 60, 60), x + offsetX, y, outerWidth, outerHeight + Game1.tileSize / 16, Color.White * alpha, drawShadow: drawShadow);
}
/// <summary>Draw a button background.</summary>
/// <param name="spriteBatch">The sprite batch to which to draw.</param>
/// <param name="position">The top-left pixel coordinate at which to draw the button.</param>
/// <param name="contentSize">The button content's pixel size.</param>
/// <param name="contentPos">The pixel position at which the content begins.</param>
/// <param name="bounds">The button's outer bounds.</param>
/// <param name="padding">The padding between the content and border.</param>
public static void DrawButton(SpriteBatch spriteBatch, in Vector2 position, in Vector2 contentSize, out Vector2 contentPos, out Rectangle bounds, int padding = 0)
{
CommonHelper.DrawContentBox(
spriteBatch: spriteBatch,
texture: CommonSprites.Button.Sheet,
background: CommonSprites.Button.Background,
top: CommonSprites.Button.Top,
right: CommonSprites.Button.Right,
bottom: CommonSprites.Button.Bottom,
left: CommonSprites.Button.Left,
topLeft: CommonSprites.Button.TopLeft,
topRight: CommonSprites.Button.TopRight,
bottomRight: CommonSprites.Button.BottomRight,
bottomLeft: CommonSprites.Button.BottomLeft,
position: position,
contentSize: contentSize,
contentPos: out contentPos,
bounds: out bounds,
padding: padding
);
}
/// <summary>Draw a scroll background.</summary>
/// <param name="spriteBatch">The sprite batch to which to draw.</param>
/// <param name="position">The top-left pixel coordinate at which to draw the scroll.</param>
/// <param name="contentSize">The scroll content's pixel size.</param>
/// <param name="contentPos">The pixel position at which the content begins.</param>
/// <param name="bounds">The scroll's outer bounds.</param>
/// <param name="padding">The padding between the content and border.</param>
public static void DrawScroll(SpriteBatch spriteBatch, in Vector2 position, in Vector2 contentSize, out Vector2 contentPos, out Rectangle bounds, int padding = 5)
{
CommonHelper.DrawContentBox(
spriteBatch: spriteBatch,
texture: CommonSprites.Scroll.Sheet,
background: in CommonSprites.Scroll.Background,
top: CommonSprites.Scroll.Top,
right: CommonSprites.Scroll.Right,
bottom: CommonSprites.Scroll.Bottom,
left: CommonSprites.Scroll.Left,
topLeft: CommonSprites.Scroll.TopLeft,
topRight: CommonSprites.Scroll.TopRight,
bottomRight: CommonSprites.Scroll.BottomRight,
bottomLeft: CommonSprites.Scroll.BottomLeft,
position: position,
contentSize: contentSize,
contentPos: out contentPos,
bounds: out bounds,
padding: padding
);
}
/// <summary>Draw a generic content box like a scroll or button.</summary>
/// <param name="spriteBatch">The sprite batch to which to draw.</param>
/// <param name="texture">The texture to draw.</param>
/// <param name="background">The source rectangle for the background.</param>
/// <param name="top">The source rectangle for the top border.</param>
/// <param name="right">The source rectangle for the right border.</param>
/// <param name="bottom">The source rectangle for the bottom border.</param>
/// <param name="left">The source rectangle for the left border.</param>
/// <param name="topLeft">The source rectangle for the top-left corner.</param>
/// <param name="topRight">The source rectangle for the top-right corner.</param>
/// <param name="bottomRight">The source rectangle for the bottom-right corner.</param>
/// <param name="bottomLeft">The source rectangle for the bottom-left corner.</param>
/// <param name="position">The top-left pixel coordinate at which to draw the button.</param>
/// <param name="contentSize">The button content's pixel size.</param>
/// <param name="contentPos">The pixel position at which the content begins.</param>
/// <param name="bounds">The box's outer bounds.</param>
/// <param name="padding">The padding between the content and border.</param>
public static void DrawContentBox(SpriteBatch spriteBatch, Texture2D texture, in Rectangle background, in Rectangle top, in Rectangle right, in Rectangle bottom, in Rectangle left, in Rectangle topLeft, in Rectangle topRight, in Rectangle bottomRight, in Rectangle bottomLeft, in Vector2 position, in Vector2 contentSize, out Vector2 contentPos, out Rectangle bounds, int padding)
{
CommonHelper.GetContentBoxDimensions(topLeft, contentSize, padding, out int innerWidth, out int innerHeight, out int outerWidth, out int outerHeight, out int cornerWidth, out int cornerHeight);
int x = (int)position.X;
int y = (int)position.Y;
// draw scroll background
spriteBatch.Draw(texture, new Rectangle(x + cornerWidth, y + cornerHeight, innerWidth, innerHeight), background, Color.White);
// draw borders
spriteBatch.Draw(texture, new Rectangle(x + cornerWidth, y, innerWidth, cornerHeight), top, Color.White);
spriteBatch.Draw(texture, new Rectangle(x + cornerWidth, y + cornerHeight + innerHeight, innerWidth, cornerHeight), bottom, Color.White);
spriteBatch.Draw(texture, new Rectangle(x, y + cornerHeight, cornerWidth, innerHeight), left, Color.White);
spriteBatch.Draw(texture, new Rectangle(x + cornerWidth + innerWidth, y + cornerHeight, cornerWidth, innerHeight), right, Color.White);
// draw corners
spriteBatch.Draw(texture, new Rectangle(x, y, cornerWidth, cornerHeight), topLeft, Color.White);
spriteBatch.Draw(texture, new Rectangle(x, y + cornerHeight + innerHeight, cornerWidth, cornerHeight), bottomLeft, Color.White);
spriteBatch.Draw(texture, new Rectangle(x + cornerWidth + innerWidth, y, cornerWidth, cornerHeight), topRight, Color.White);
spriteBatch.Draw(texture, new Rectangle(x + cornerWidth + innerWidth, y + cornerHeight + innerHeight, cornerWidth, cornerHeight), bottomRight, Color.White);
// set out params
contentPos = new Vector2(x + cornerWidth + padding, y + cornerHeight + padding);
bounds = new Rectangle(x, y, outerWidth, outerHeight);
}
/// <summary>Show an informational message to the player.</summary>
/// <param name="message">The message to show.</param>
/// <param name="duration">The number of milliseconds during which to keep the message on the screen before it fades (or <c>null</c> for the default time).</param>
public static void ShowInfoMessage(string message, int? duration = null)
{
Game1.addHUDMessage(new HUDMessage(message, HUDMessage.error_type) { noIcon = true, timeLeft = duration ?? HUDMessage.defaultTime });
}
/// <summary>Show an error message to the player.</summary>
/// <param name="message">The message to show.</param>
public static void ShowErrorMessage(string message)
{
Game1.addHUDMessage(new HUDMessage(message, HUDMessage.error_type));
}
/// <summary>Calculate the outer dimension for a content box.</summary>
/// <param name="contentSize">The size of the content within the box.</param>
/// <param name="padding">The padding within the content area.</param>
/// <param name="innerWidth">The width of the inner content area, including padding.</param>
/// <param name="innerHeight">The height of the inner content area, including padding.</param>
/// <param name="labelOuterWidth">The outer pixel width.</param>
/// <param name="outerHeight">The outer pixel height.</param>
/// <param name="borderWidth">The width of the left and right border textures.</param>
/// <param name="borderHeight">The height of the top and bottom border textures.</param>
public static void GetScrollDimensions(Vector2 contentSize, int padding, out int innerWidth, out int innerHeight, out int labelOuterWidth, out int outerHeight, out int borderWidth, out int borderHeight)
{
CommonHelper.GetContentBoxDimensions(CommonSprites.Scroll.TopLeft, contentSize, padding, out innerWidth, out innerHeight, out labelOuterWidth, out outerHeight, out borderWidth, out borderHeight);
}
/// <summary>Calculate the outer dimension for a content box.</summary>
/// <param name="topLeft">The source rectangle for the top-left corner of the content box.</param>
/// <param name="contentSize">The size of the content within the box.</param>
/// <param name="padding">The padding within the content area.</param>
/// <param name="innerWidth">The width of the inner content area, including padding.</param>
/// <param name="innerHeight">The height of the inner content area, including padding.</param>
/// <param name="outerWidth">The outer pixel width.</param>
/// <param name="outerHeight">The outer pixel height.</param>
/// <param name="borderWidth">The width of the left and right border textures.</param>
/// <param name="borderHeight">The height of the top and bottom border textures.</param>
public static void GetContentBoxDimensions(Rectangle topLeft, Vector2 contentSize, int padding, out int innerWidth, out int innerHeight, out int outerWidth, out int outerHeight, out int borderWidth, out int borderHeight)
{
borderWidth = topLeft.Width * Game1.pixelZoom;
borderHeight = topLeft.Height * Game1.pixelZoom;
innerWidth = (int)(contentSize.X + padding * 2);
innerHeight = (int)(contentSize.Y + padding * 2);
outerWidth = innerWidth + borderWidth * 2;
outerHeight = innerHeight + borderHeight * 2;
}
/****
** Drawing
****/
/// <summary>Draw a sprite to the screen.</summary>
/// <param name="batch">The sprite batch.</param>
/// <param name="x">The X-position at which to start the line.</param>
/// <param name="y">The X-position at which to start the line.</param>
/// <param name="size">The line dimensions.</param>
/// <param name="color">The color to tint the sprite.</param>
public static void DrawLine(this SpriteBatch batch, float x, float y, in Vector2 size, in Color? color = null)
{
batch.Draw(CommonHelper.Pixel, new Rectangle((int)x, (int)y, (int)size.X, (int)size.Y), color ?? Color.White);
}
/// <summary>Draw a block of text to the screen with the specified wrap width.</summary>
/// <param name="batch">The sprite batch.</param>
/// <param name="font">The sprite font.</param>
/// <param name="text">The block of text to write.</param>
/// <param name="position">The position at which to draw the text.</param>
/// <param name="wrapWidth">The width at which to wrap the text.</param>
/// <param name="color">The text color.</param>
/// <param name="bold">Whether to draw bold text.</param>
/// <param name="scale">The font scale.</param>
/// <returns>Returns the text dimensions.</returns>
public static Vector2 DrawTextBlock(this SpriteBatch batch, SpriteFont font, string text, in Vector2 position, float wrapWidth, in Color? color = null, bool bold = false, float scale = 1)
{
if (text == null)
return new Vector2(0, 0);
// get word list
List<string> words = new List<string>();
foreach (string word in text.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries))
{
// split on newlines
string wordPart = word;
int newlineIndex;
while ((newlineIndex = wordPart.IndexOf(Environment.NewLine, StringComparison.Ordinal)) >= 0)
{
if (newlineIndex == 0)
{
words.Add(Environment.NewLine);
wordPart = wordPart.Substring(Environment.NewLine.Length);
}
else if (newlineIndex > 0)
{
words.Add(wordPart.Substring(0, newlineIndex));
words.Add(Environment.NewLine);
wordPart = wordPart.Substring(newlineIndex + Environment.NewLine.Length);
}
}
// add remaining word (after newline split)
if (wordPart.Length > 0)
words.Add(wordPart);
}
// track draw values
float xOffset = 0;
float yOffset = 0;
float lineHeight = font.MeasureString("ABC").Y * scale;
float spaceWidth = CommonHelper.GetSpaceWidth(font) * scale;
float blockWidth = 0;
float blockHeight = lineHeight;
foreach (string word in words)
{
// check wrap width
float wordWidth = font.MeasureString(word).X * scale;
if (word == Environment.NewLine || ((wordWidth + xOffset) > wrapWidth && (int)xOffset != 0))
{
xOffset = 0;
yOffset += lineHeight;
blockHeight += lineHeight;
}
if (word == Environment.NewLine)
continue;
// draw text
Vector2 wordPosition = new Vector2(position.X + xOffset, position.Y + yOffset);
if (bold)
Utility.drawBoldText(batch, word, font, wordPosition, color ?? Color.Black, scale);
else
batch.DrawString(font, word, wordPosition, color ?? Color.Black, 0, Vector2.Zero, scale, SpriteEffects.None, 1);
// update draw values
if (xOffset + wordWidth > blockWidth)
blockWidth = xOffset + wordWidth;
xOffset += wordWidth + spaceWidth;
}
// return text position & dimensions
return new Vector2(blockWidth, blockHeight);
}
/****
** Error handling
****/
/// <summary>Intercept errors thrown by the action.</summary>
/// <param name="monitor">Encapsulates monitoring and logging.</param>
/// <param name="verb">The verb describing where the error occurred (e.g. "looking that up"). This is displayed on the screen, so it should be simple and avoid characters that might not be available in the sprite font.</param>
/// <param name="action">The action to invoke.</param>
/// <param name="onError">A callback invoked if an error is intercepted.</param>
public static void InterceptErrors(this IMonitor monitor, string verb, Action action, Action<Exception> onError = null)
{
monitor.InterceptErrors(verb, null, action, onError);
}
/// <summary>Intercept errors thrown by the action.</summary>
/// <param name="monitor">Encapsulates monitoring and logging.</param>
/// <param name="verb">The verb describing where the error occurred (e.g. "looking that up"). This is displayed on the screen, so it should be simple and avoid characters that might not be available in the sprite font.</param>
/// <param name="detailedVerb">A more detailed form of <see cref="verb"/> if applicable. This is displayed in the log, so it can be more technical and isn't constrained by the sprite font.</param>
/// <param name="action">The action to invoke.</param>
/// <param name="onError">A callback invoked if an error is intercepted.</param>
public static void InterceptErrors(this IMonitor monitor, string verb, string detailedVerb, Action action, Action<Exception> onError = null)
{
try
{
action();
}
catch (Exception ex)
{
monitor.InterceptError(ex, verb, detailedVerb);
onError?.Invoke(ex);
}
}
/// <summary>Log an error and warn the user.</summary>
/// <param name="monitor">Encapsulates monitoring and logging.</param>
/// <param name="ex">The exception to handle.</param>
/// <param name="verb">The verb describing where the error occurred (e.g. "looking that up"). This is displayed on the screen, so it should be simple and avoid characters that might not be available in the sprite font.</param>
/// <param name="detailedVerb">A more detailed form of <see cref="verb"/> if applicable. This is displayed in the log, so it can be more technical and isn't constrained by the sprite font.</param>
public static void InterceptError(this IMonitor monitor, Exception ex, string verb, string detailedVerb = null)
{
detailedVerb ??= verb;
monitor.Log($"Something went wrong {detailedVerb}:\n{ex}", LogLevel.Error);
CommonHelper.ShowErrorMessage($"Huh. Something went wrong {verb}. The error log has the technical details.");
}
/****
** File handling
****/
/// <summary>Get the MD5 hash for a file.</summary>
/// <param name="absolutePath">The absolute file path.</param>
public static string GetFileHash(string absolutePath)
{
using FileStream stream = File.OpenRead(absolutePath);
using MD5 md5 = MD5.Create();
byte[] hash = md5.ComputeHash(stream);
return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Data;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Pomelo.EntityFrameworkCore.MySql.Storage.Internal;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.TestUtilities;
using Microsoft.EntityFrameworkCore.TestUtilities.Xunit;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
// ReSharper disable InconsistentNaming
namespace Microsoft.EntityFrameworkCore
{
[MySqlCondition(MySqlCondition.IsNotSqlAzure)]
public class EverythingIsBytesMySqlTest : BuiltInDataTypesTestBase<EverythingIsBytesMySqlTest.EverythingIsBytesMySqlFixture>
{
public EverythingIsBytesMySqlTest(EverythingIsBytesMySqlFixture fixture)
: base(fixture)
{
}
[ConditionalFact]
public virtual void Columns_have_expected_data_types()
{
var actual = BuiltInDataTypesMySqlTest.QueryForColumnTypes(CreateContext());
const string expected = @"BinaryForeignKeyDataType.BinaryKeyDataTypeId ---> [nullable varbinary] [MaxLength = 900]
BinaryForeignKeyDataType.Id ---> [varbinary] [MaxLength = 4]
BinaryKeyDataType.Id ---> [varbinary] [MaxLength = 900]
BuiltInDataTypes.Enum16 ---> [varbinary] [MaxLength = 2]
BuiltInDataTypes.Enum32 ---> [varbinary] [MaxLength = 4]
BuiltInDataTypes.Enum64 ---> [varbinary] [MaxLength = 8]
BuiltInDataTypes.Enum8 ---> [varbinary] [MaxLength = 1]
BuiltInDataTypes.EnumS8 ---> [varbinary] [MaxLength = 1]
BuiltInDataTypes.EnumU16 ---> [varbinary] [MaxLength = 2]
BuiltInDataTypes.EnumU32 ---> [varbinary] [MaxLength = 4]
BuiltInDataTypes.EnumU64 ---> [varbinary] [MaxLength = 8]
BuiltInDataTypes.Id ---> [varbinary] [MaxLength = 4]
BuiltInDataTypes.PartitionId ---> [varbinary] [MaxLength = 4]
BuiltInDataTypes.TestBoolean ---> [varbinary] [MaxLength = 1]
BuiltInDataTypes.TestByte ---> [varbinary] [MaxLength = 1]
BuiltInDataTypes.TestCharacter ---> [varbinary] [MaxLength = 2]
BuiltInDataTypes.TestDateTime ---> [varbinary] [MaxLength = 8]
BuiltInDataTypes.TestDateTimeOffset ---> [varbinary] [MaxLength = 12]
BuiltInDataTypes.TestDecimal ---> [varbinary] [MaxLength = 16]
BuiltInDataTypes.TestDouble ---> [varbinary] [MaxLength = 8]
BuiltInDataTypes.TestInt16 ---> [varbinary] [MaxLength = 2]
BuiltInDataTypes.TestInt32 ---> [varbinary] [MaxLength = 4]
BuiltInDataTypes.TestInt64 ---> [varbinary] [MaxLength = 8]
BuiltInDataTypes.TestSignedByte ---> [varbinary] [MaxLength = 1]
BuiltInDataTypes.TestSingle ---> [varbinary] [MaxLength = 4]
BuiltInDataTypes.TestTimeSpan ---> [varbinary] [MaxLength = 8]
BuiltInDataTypes.TestUnsignedInt16 ---> [varbinary] [MaxLength = 2]
BuiltInDataTypes.TestUnsignedInt32 ---> [varbinary] [MaxLength = 4]
BuiltInDataTypes.TestUnsignedInt64 ---> [varbinary] [MaxLength = 8]
BuiltInDataTypesShadow.Enum16 ---> [varbinary] [MaxLength = 2]
BuiltInDataTypesShadow.Enum32 ---> [varbinary] [MaxLength = 4]
BuiltInDataTypesShadow.Enum64 ---> [varbinary] [MaxLength = 8]
BuiltInDataTypesShadow.Enum8 ---> [varbinary] [MaxLength = 1]
BuiltInDataTypesShadow.EnumS8 ---> [varbinary] [MaxLength = 1]
BuiltInDataTypesShadow.EnumU16 ---> [varbinary] [MaxLength = 2]
BuiltInDataTypesShadow.EnumU32 ---> [varbinary] [MaxLength = 4]
BuiltInDataTypesShadow.EnumU64 ---> [varbinary] [MaxLength = 8]
BuiltInDataTypesShadow.Id ---> [varbinary] [MaxLength = 4]
BuiltInDataTypesShadow.PartitionId ---> [varbinary] [MaxLength = 4]
BuiltInDataTypesShadow.TestBoolean ---> [varbinary] [MaxLength = 1]
BuiltInDataTypesShadow.TestByte ---> [varbinary] [MaxLength = 1]
BuiltInDataTypesShadow.TestCharacter ---> [varbinary] [MaxLength = 2]
BuiltInDataTypesShadow.TestDateTime ---> [varbinary] [MaxLength = 8]
BuiltInDataTypesShadow.TestDateTimeOffset ---> [varbinary] [MaxLength = 12]
BuiltInDataTypesShadow.TestDecimal ---> [varbinary] [MaxLength = 16]
BuiltInDataTypesShadow.TestDouble ---> [varbinary] [MaxLength = 8]
BuiltInDataTypesShadow.TestInt16 ---> [varbinary] [MaxLength = 2]
BuiltInDataTypesShadow.TestInt32 ---> [varbinary] [MaxLength = 4]
BuiltInDataTypesShadow.TestInt64 ---> [varbinary] [MaxLength = 8]
BuiltInDataTypesShadow.TestSignedByte ---> [varbinary] [MaxLength = 1]
BuiltInDataTypesShadow.TestSingle ---> [varbinary] [MaxLength = 4]
BuiltInDataTypesShadow.TestTimeSpan ---> [varbinary] [MaxLength = 8]
BuiltInDataTypesShadow.TestUnsignedInt16 ---> [varbinary] [MaxLength = 2]
BuiltInDataTypesShadow.TestUnsignedInt32 ---> [varbinary] [MaxLength = 4]
BuiltInDataTypesShadow.TestUnsignedInt64 ---> [varbinary] [MaxLength = 8]
BuiltInNullableDataTypes.Enum16 ---> [nullable varbinary] [MaxLength = 2]
BuiltInNullableDataTypes.Enum32 ---> [nullable varbinary] [MaxLength = 4]
BuiltInNullableDataTypes.Enum64 ---> [nullable varbinary] [MaxLength = 8]
BuiltInNullableDataTypes.Enum8 ---> [nullable varbinary] [MaxLength = 1]
BuiltInNullableDataTypes.EnumS8 ---> [nullable varbinary] [MaxLength = 1]
BuiltInNullableDataTypes.EnumU16 ---> [nullable varbinary] [MaxLength = 2]
BuiltInNullableDataTypes.EnumU32 ---> [nullable varbinary] [MaxLength = 4]
BuiltInNullableDataTypes.EnumU64 ---> [nullable varbinary] [MaxLength = 8]
BuiltInNullableDataTypes.Id ---> [varbinary] [MaxLength = 4]
BuiltInNullableDataTypes.PartitionId ---> [varbinary] [MaxLength = 4]
BuiltInNullableDataTypes.TestByteArray ---> [nullable varbinary] [MaxLength = -1]
BuiltInNullableDataTypes.TestNullableBoolean ---> [nullable varbinary] [MaxLength = 1]
BuiltInNullableDataTypes.TestNullableByte ---> [nullable varbinary] [MaxLength = 1]
BuiltInNullableDataTypes.TestNullableCharacter ---> [nullable varbinary] [MaxLength = 2]
BuiltInNullableDataTypes.TestNullableDateTime ---> [nullable varbinary] [MaxLength = 8]
BuiltInNullableDataTypes.TestNullableDateTimeOffset ---> [nullable varbinary] [MaxLength = 12]
BuiltInNullableDataTypes.TestNullableDecimal ---> [nullable varbinary] [MaxLength = 16]
BuiltInNullableDataTypes.TestNullableDouble ---> [nullable varbinary] [MaxLength = 8]
BuiltInNullableDataTypes.TestNullableInt16 ---> [nullable varbinary] [MaxLength = 2]
BuiltInNullableDataTypes.TestNullableInt32 ---> [nullable varbinary] [MaxLength = 4]
BuiltInNullableDataTypes.TestNullableInt64 ---> [nullable varbinary] [MaxLength = 8]
BuiltInNullableDataTypes.TestNullableSignedByte ---> [nullable varbinary] [MaxLength = 1]
BuiltInNullableDataTypes.TestNullableSingle ---> [nullable varbinary] [MaxLength = 4]
BuiltInNullableDataTypes.TestNullableTimeSpan ---> [nullable varbinary] [MaxLength = 8]
BuiltInNullableDataTypes.TestNullableUnsignedInt16 ---> [nullable varbinary] [MaxLength = 2]
BuiltInNullableDataTypes.TestNullableUnsignedInt32 ---> [nullable varbinary] [MaxLength = 4]
BuiltInNullableDataTypes.TestNullableUnsignedInt64 ---> [nullable varbinary] [MaxLength = 8]
BuiltInNullableDataTypes.TestString ---> [nullable varbinary] [MaxLength = -1]
BuiltInNullableDataTypesShadow.Enum16 ---> [nullable varbinary] [MaxLength = 2]
BuiltInNullableDataTypesShadow.Enum32 ---> [nullable varbinary] [MaxLength = 4]
BuiltInNullableDataTypesShadow.Enum64 ---> [nullable varbinary] [MaxLength = 8]
BuiltInNullableDataTypesShadow.Enum8 ---> [nullable varbinary] [MaxLength = 1]
BuiltInNullableDataTypesShadow.EnumS8 ---> [nullable varbinary] [MaxLength = 1]
BuiltInNullableDataTypesShadow.EnumU16 ---> [nullable varbinary] [MaxLength = 2]
BuiltInNullableDataTypesShadow.EnumU32 ---> [nullable varbinary] [MaxLength = 4]
BuiltInNullableDataTypesShadow.EnumU64 ---> [nullable varbinary] [MaxLength = 8]
BuiltInNullableDataTypesShadow.Id ---> [varbinary] [MaxLength = 4]
BuiltInNullableDataTypesShadow.PartitionId ---> [varbinary] [MaxLength = 4]
BuiltInNullableDataTypesShadow.TestByteArray ---> [nullable varbinary] [MaxLength = -1]
BuiltInNullableDataTypesShadow.TestNullableBoolean ---> [nullable varbinary] [MaxLength = 1]
BuiltInNullableDataTypesShadow.TestNullableByte ---> [nullable varbinary] [MaxLength = 1]
BuiltInNullableDataTypesShadow.TestNullableCharacter ---> [nullable varbinary] [MaxLength = 2]
BuiltInNullableDataTypesShadow.TestNullableDateTime ---> [nullable varbinary] [MaxLength = 8]
BuiltInNullableDataTypesShadow.TestNullableDateTimeOffset ---> [nullable varbinary] [MaxLength = 12]
BuiltInNullableDataTypesShadow.TestNullableDecimal ---> [nullable varbinary] [MaxLength = 16]
BuiltInNullableDataTypesShadow.TestNullableDouble ---> [nullable varbinary] [MaxLength = 8]
BuiltInNullableDataTypesShadow.TestNullableInt16 ---> [nullable varbinary] [MaxLength = 2]
BuiltInNullableDataTypesShadow.TestNullableInt32 ---> [nullable varbinary] [MaxLength = 4]
BuiltInNullableDataTypesShadow.TestNullableInt64 ---> [nullable varbinary] [MaxLength = 8]
BuiltInNullableDataTypesShadow.TestNullableSignedByte ---> [nullable varbinary] [MaxLength = 1]
BuiltInNullableDataTypesShadow.TestNullableSingle ---> [nullable varbinary] [MaxLength = 4]
BuiltInNullableDataTypesShadow.TestNullableTimeSpan ---> [nullable varbinary] [MaxLength = 8]
BuiltInNullableDataTypesShadow.TestNullableUnsignedInt16 ---> [nullable varbinary] [MaxLength = 2]
BuiltInNullableDataTypesShadow.TestNullableUnsignedInt32 ---> [nullable varbinary] [MaxLength = 4]
BuiltInNullableDataTypesShadow.TestNullableUnsignedInt64 ---> [nullable varbinary] [MaxLength = 8]
BuiltInNullableDataTypesShadow.TestString ---> [nullable varbinary] [MaxLength = -1]
EmailTemplate.Id ---> [varbinary] [MaxLength = 16]
EmailTemplate.TemplateType ---> [varbinary] [MaxLength = 4]
MaxLengthDataTypes.ByteArray5 ---> [nullable varbinary] [MaxLength = 5]
MaxLengthDataTypes.ByteArray9000 ---> [nullable varbinary] [MaxLength = -1]
MaxLengthDataTypes.Id ---> [varbinary] [MaxLength = 4]
MaxLengthDataTypes.String3 ---> [nullable varbinary] [MaxLength = 3]
MaxLengthDataTypes.String9000 ---> [nullable varbinary] [MaxLength = -1]
StringForeignKeyDataType.Id ---> [varbinary] [MaxLength = 4]
StringForeignKeyDataType.StringKeyDataTypeId ---> [nullable varbinary] [MaxLength = 900]
StringKeyDataType.Id ---> [varbinary] [MaxLength = 900]
UnicodeDataTypes.Id ---> [varbinary] [MaxLength = 4]
UnicodeDataTypes.StringAnsi ---> [nullable varbinary] [MaxLength = -1]
UnicodeDataTypes.StringAnsi3 ---> [nullable varbinary] [MaxLength = 3]
UnicodeDataTypes.StringAnsi9000 ---> [nullable varbinary] [MaxLength = -1]
UnicodeDataTypes.StringDefault ---> [nullable varbinary] [MaxLength = -1]
UnicodeDataTypes.StringUnicode ---> [nullable varbinary] [MaxLength = -1]
";
Assert.Equal(expected, actual, ignoreLineEndingDifferences: true);
}
public class EverythingIsBytesMySqlFixture : BuiltInDataTypesFixtureBase
{
public override bool StrictEquality => true;
public override bool SupportsAnsi => true;
public override bool SupportsUnicodeToAnsiConversion => false;
public override bool SupportsLargeStringComparisons => true;
protected override string StoreName { get; } = "EverythingIsBytes";
protected override ITestStoreFactory TestStoreFactory => MySqlBytesTestStoreFactory.Instance;
public override bool SupportsBinaryKeys => true;
public override DateTime DefaultDateTime => new DateTime();
public override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder builder)
=> base
.AddOptions(builder)
.ConfigureWarnings(
c => c.Log(RelationalEventId.QueryClientEvaluationWarning)
.Log(MySqlEventId.DecimalTypeDefaultWarning));
}
public class MySqlBytesTestStoreFactory : MySqlTestStoreFactory
{
public static new MySqlBytesTestStoreFactory Instance { get; } = new MySqlBytesTestStoreFactory();
public override IServiceCollection AddProviderServices(IServiceCollection serviceCollection)
=> base.AddProviderServices(
serviceCollection.AddSingleton<IRelationalTypeMappingSource, MySqlBytesTypeMappingSource>());
}
public class MySqlBytesTypeMappingSource : RelationalTypeMappingSource
{
#if Test21
private readonly MySqlByteArrayTypeMapping _rowversion
= new MySqlByteArrayTypeMapping("rowversion", dbType: DbType.Binary, size: 8);
private readonly MySqlByteArrayTypeMapping _variableLengthBinary
= new MySqlByteArrayTypeMapping("varbinary");
private readonly MySqlByteArrayTypeMapping _fixedLengthBinary
= new MySqlByteArrayTypeMapping("binary");
#else
private readonly MySqlByteArrayTypeMapping _rowversion
= new MySqlByteArrayTypeMapping("rowversion", size: 8);
private readonly MySqlByteArrayTypeMapping _variableLengthBinary
= new MySqlByteArrayTypeMapping();
private readonly MySqlByteArrayTypeMapping _fixedLengthBinary
= new MySqlByteArrayTypeMapping(fixedLength: true);
#endif
private readonly Dictionary<string, RelationalTypeMapping> _storeTypeMappings;
public MySqlBytesTypeMappingSource(
TypeMappingSourceDependencies dependencies,
RelationalTypeMappingSourceDependencies relationalDependencies)
: base(dependencies, relationalDependencies)
{
_storeTypeMappings
= new Dictionary<string, RelationalTypeMapping>(StringComparer.OrdinalIgnoreCase)
{
{ "binary varying", _variableLengthBinary },
{ "binary", _fixedLengthBinary },
{ "image", _variableLengthBinary },
{ "rowversion", _rowversion },
{ "varbinary", _variableLengthBinary }
};
}
protected override RelationalTypeMapping FindMapping(in RelationalTypeMappingInfo mappingInfo)
=> FindRawMapping(mappingInfo)?.Clone(mappingInfo);
private RelationalTypeMapping FindRawMapping(RelationalTypeMappingInfo mappingInfo)
{
var clrType = mappingInfo.ClrType;
var storeTypeName = mappingInfo.StoreTypeName;
var storeTypeNameBase = mappingInfo.StoreTypeNameBase;
if (storeTypeName != null)
{
if (_storeTypeMappings.TryGetValue(storeTypeName, out var mapping)
|| _storeTypeMappings.TryGetValue(storeTypeNameBase, out mapping))
{
return clrType == null
|| mapping.ClrType == clrType
? mapping
: null;
}
}
if (clrType != null)
{
if (clrType == typeof(byte[]))
{
if (mappingInfo.IsRowVersion == true)
{
return _rowversion;
}
var isFixedLength = mappingInfo.IsFixedLength == true;
var size = mappingInfo.Size ?? (mappingInfo.IsKeyOrIndex ? (int?)900 : null);
if (size > 8000)
{
size = isFixedLength ? 8000 : (int?)null;
}
#if Test21
return new MySqlByteArrayTypeMapping(
"varbinary(" + (size == null ? "max" : size.ToString()) + ")",
DbType.Binary,
size);
#else
return new MySqlByteArrayTypeMapping(
"varbinary(" + (size == null ? "max" : size.ToString()) + ")",
size,
isFixedLength,
storeTypePostfix: size == null ? StoreTypePostfix.None : (StoreTypePostfix?)null);
#endif
}
}
return null;
}
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using Newtonsoft.Json;
using QuantConnect.Interfaces;
using QuantConnect.Orders.Serialization;
using QuantConnect.Orders.TimeInForces;
using QuantConnect.Securities;
using QuantConnect.Securities.Positions;
using static QuantConnect.StringExtensions;
namespace QuantConnect.Orders
{
/// <summary>
/// Order struct for placing new trade
/// </summary>
public abstract class Order
{
private volatile int _incrementalId;
private decimal _quantity;
private decimal _price;
/// <summary>
/// Order ID.
/// </summary>
public int Id { get; internal set; }
/// <summary>
/// Order id to process before processing this order.
/// </summary>
public int ContingentId { get; internal set; }
/// <summary>
/// Brokerage Id for this order for when the brokerage splits orders into multiple pieces
/// </summary>
public List<string> BrokerId { get; internal set; }
/// <summary>
/// Symbol of the Asset
/// </summary>
public Symbol Symbol { get; internal set; }
/// <summary>
/// Price of the Order.
/// </summary>
public decimal Price
{
get { return _price; }
internal set { _price = value.Normalize(); }
}
/// <summary>
/// Currency for the order price
/// </summary>
public string PriceCurrency { get; internal set; }
/// <summary>
/// Gets the utc time the order was created.
/// </summary>
public DateTime Time { get; internal set; }
/// <summary>
/// Gets the utc time this order was created. Alias for <see cref="Time"/>
/// </summary>
public DateTime CreatedTime => Time;
/// <summary>
/// Gets the utc time the last fill was received, or null if no fills have been received
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public DateTime? LastFillTime { get; internal set; }
/// <summary>
/// Gets the utc time this order was last updated, or null if the order has not been updated.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public DateTime? LastUpdateTime { get; internal set; }
/// <summary>
/// Gets the utc time this order was canceled, or null if the order was not canceled.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public DateTime? CanceledTime { get; internal set; }
/// <summary>
/// Number of shares to execute.
/// </summary>
public decimal Quantity
{
get { return _quantity; }
internal set { _quantity = value.Normalize(); }
}
/// <summary>
/// Order Type
/// </summary>
public abstract OrderType Type { get; }
/// <summary>
/// Status of the Order
/// </summary>
public OrderStatus Status { get; set; }
/// <summary>
/// Order Time In Force
/// </summary>
[JsonIgnore]
public TimeInForce TimeInForce => Properties.TimeInForce;
/// <summary>
/// Tag the order with some custom data
/// </summary>
[DefaultValue(""), JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
public string Tag { get; internal set; }
/// <summary>
/// Additional properties of the order
/// </summary>
public IOrderProperties Properties { get; private set; }
/// <summary>
/// The symbol's security type
/// </summary>
public SecurityType SecurityType => Symbol.ID.SecurityType;
/// <summary>
/// Order Direction Property based off Quantity.
/// </summary>
public OrderDirection Direction
{
get
{
if (Quantity > 0)
{
return OrderDirection.Buy;
}
if (Quantity < 0)
{
return OrderDirection.Sell;
}
return OrderDirection.Hold;
}
}
/// <summary>
/// Get the absolute quantity for this order
/// </summary>
[JsonIgnore]
public decimal AbsoluteQuantity => Math.Abs(Quantity);
/// <summary>
/// Gets the executed value of this order. If the order has not yet filled,
/// then this will return zero.
/// </summary>
public decimal Value => Quantity * Price;
/// <summary>
/// Gets the price data at the time the order was submitted
/// </summary>
public OrderSubmissionData OrderSubmissionData { get; internal set; }
/// <summary>
/// Returns true if the order is a marketable order.
/// </summary>
public bool IsMarketable
{
get
{
if (Type == OrderType.Limit)
{
// check if marketable limit order using bid/ask prices
var limitOrder = (LimitOrder)this;
return OrderSubmissionData != null &&
(Direction == OrderDirection.Buy && limitOrder.LimitPrice >= OrderSubmissionData.AskPrice ||
Direction == OrderDirection.Sell && limitOrder.LimitPrice <= OrderSubmissionData.BidPrice);
}
return Type == OrderType.Market;
}
}
/// <summary>
/// Added a default constructor for JSON Deserialization:
/// </summary>
protected Order()
{
Time = new DateTime();
PriceCurrency = string.Empty;
Symbol = Symbol.Empty;
Status = OrderStatus.None;
Tag = string.Empty;
BrokerId = new List<string>();
Properties = new OrderProperties();
}
/// <summary>
/// New order constructor
/// </summary>
/// <param name="symbol">Symbol asset we're seeking to trade</param>
/// <param name="quantity">Quantity of the asset we're seeking to trade</param>
/// <param name="time">Time the order was placed</param>
/// <param name="tag">User defined data tag for this order</param>
/// <param name="properties">The order properties for this order</param>
protected Order(Symbol symbol, decimal quantity, DateTime time, string tag = "", IOrderProperties properties = null)
{
Time = time;
PriceCurrency = string.Empty;
Quantity = quantity;
Symbol = symbol;
Status = OrderStatus.None;
Tag = tag;
BrokerId = new List<string>();
Properties = properties ?? new OrderProperties();
}
/// <summary>
/// Creates an enumerable containing each position resulting from executing this order.
/// </summary>
/// <remarks>
/// This is provided in anticipation of a new combo order type that will need to override this method,
/// returning a position for each 'leg' of the order.
/// </remarks>
/// <returns>An enumerable of positions matching the results of executing this order</returns>
public virtual IEnumerable<IPosition> CreatePositions(SecurityManager securities)
{
var security = securities[Symbol];
yield return new Position(security, Quantity);
}
/// <summary>
/// Gets the value of this order at the given market price in units of the account currency
/// NOTE: Some order types derive value from other parameters, such as limit prices
/// </summary>
/// <param name="security">The security matching this order's symbol</param>
/// <returns>The value of this order given the current market price</returns>
public decimal GetValue(Security security)
{
var value = GetValueImpl(security);
return value*security.QuoteCurrency.ConversionRate*security.SymbolProperties.ContractMultiplier;
}
/// <summary>
/// Gets the order value in units of the security's quote currency for a single unit.
/// A single unit here is a single share of stock, or a single barrel of oil, or the
/// cost of a single share in an option contract.
/// </summary>
/// <param name="security">The security matching this order's symbol</param>
protected abstract decimal GetValueImpl(Security security);
/// <summary>
/// Gets a new unique incremental id for this order
/// </summary>
/// <returns>Returns a new id for this order</returns>
internal int GetNewId()
{
return Interlocked.Increment(ref _incrementalId);
}
/// <summary>
/// Modifies the state of this order to match the update request
/// </summary>
/// <param name="request">The request to update this order object</param>
public virtual void ApplyUpdateOrderRequest(UpdateOrderRequest request)
{
if (request.OrderId != Id)
{
throw new ArgumentException("Attempted to apply updates to the incorrect order!");
}
if (request.Quantity.HasValue)
{
Quantity = request.Quantity.Value;
}
if (request.Tag != null)
{
Tag = request.Tag;
}
}
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns>
/// A string that represents the current object.
/// </returns>
/// <filterpriority>2</filterpriority>
public override string ToString()
{
var tag = string.IsNullOrEmpty(Tag) ? string.Empty : $": {Tag}";
return Invariant($"OrderId: {Id} (BrokerId: {string.Join(",", BrokerId)}) {Status} {Type} order for {Quantity} unit{(Quantity == 1 ? "" : "s")} of {Symbol}{tag}");
}
/// <summary>
/// Creates a deep-copy clone of this order
/// </summary>
/// <returns>A copy of this order</returns>
public abstract Order Clone();
/// <summary>
/// Copies base Order properties to the specified order
/// </summary>
/// <param name="order">The target of the copy</param>
protected void CopyTo(Order order)
{
order.Id = Id;
order.Time = Time;
order.LastFillTime = LastFillTime;
order.LastUpdateTime = LastUpdateTime;
order.CanceledTime = CanceledTime;
order.BrokerId = BrokerId.ToList();
order.ContingentId = ContingentId;
order.Price = Price;
order.PriceCurrency = PriceCurrency;
order.Quantity = Quantity;
order.Status = Status;
order.Symbol = Symbol;
order.Tag = Tag;
order.Properties = Properties.Clone();
order.OrderSubmissionData = OrderSubmissionData?.Clone();
}
/// <summary>
/// Creates a new Order instance from a SerializedOrder instance
/// </summary>
/// <remarks>Used by the <see cref="SerializedOrderJsonConverter"/></remarks>
public static Order FromSerialized(SerializedOrder serializedOrder)
{
var sid = SecurityIdentifier.Parse(serializedOrder.Symbol);
var symbol = new Symbol(sid, sid.Symbol);
TimeInForce timeInForce = null;
var type = System.Type.GetType($"QuantConnect.Orders.TimeInForces.{serializedOrder.TimeInForceType}", throwOnError: false, ignoreCase: true);
if (type != null)
{
timeInForce = (TimeInForce) Activator.CreateInstance(type, true);
if (timeInForce is GoodTilDateTimeInForce)
{
var expiry = QuantConnect.Time.UnixTimeStampToDateTime(serializedOrder.TimeInForceExpiry.Value);
timeInForce = new GoodTilDateTimeInForce(expiry);
}
}
var createdTime = QuantConnect.Time.UnixTimeStampToDateTime(serializedOrder.CreatedTime);
var order = CreateOrder(serializedOrder.OrderId, serializedOrder.Type, symbol, serializedOrder.Quantity,
DateTime.SpecifyKind(createdTime, DateTimeKind.Utc),
serializedOrder.Tag,
new OrderProperties { TimeInForce = timeInForce },
serializedOrder.LimitPrice ?? 0,
serializedOrder.StopPrice ?? 0,
serializedOrder.TriggerPrice ?? 0);
order.OrderSubmissionData = new OrderSubmissionData(serializedOrder.SubmissionBidPrice,
serializedOrder.SubmissionAskPrice,
serializedOrder.SubmissionLastPrice);
order.BrokerId = serializedOrder.BrokerId;
order.ContingentId = serializedOrder.ContingentId;
order.Price = serializedOrder.Price;
order.PriceCurrency = serializedOrder.PriceCurrency;
order.Status = serializedOrder.Status;
if (serializedOrder.LastFillTime.HasValue)
{
var time = QuantConnect.Time.UnixTimeStampToDateTime(serializedOrder.LastFillTime.Value);
order.LastFillTime = DateTime.SpecifyKind(time, DateTimeKind.Utc);
}
if (serializedOrder.LastUpdateTime.HasValue)
{
var time = QuantConnect.Time.UnixTimeStampToDateTime(serializedOrder.LastUpdateTime.Value);
order.LastUpdateTime = DateTime.SpecifyKind(time, DateTimeKind.Utc);
}
if (serializedOrder.CanceledTime.HasValue)
{
var time = QuantConnect.Time.UnixTimeStampToDateTime(serializedOrder.CanceledTime.Value);
order.CanceledTime = DateTime.SpecifyKind(time, DateTimeKind.Utc);
}
return order;
}
/// <summary>
/// Creates an <see cref="Order"/> to match the specified <paramref name="request"/>
/// </summary>
/// <param name="request">The <see cref="SubmitOrderRequest"/> to create an order for</param>
/// <returns>The <see cref="Order"/> that matches the request</returns>
public static Order CreateOrder(SubmitOrderRequest request)
{
return CreateOrder(request.OrderId, request.OrderType, request.Symbol, request.Quantity, request.Time,
request.Tag, request.OrderProperties, request.LimitPrice, request.StopPrice, request.TriggerPrice);
}
private static Order CreateOrder(int orderId, OrderType type, Symbol symbol, decimal quantity, DateTime time,
string tag, IOrderProperties properties, decimal limitPrice, decimal stopPrice, decimal triggerPrice)
{
Order order;
switch (type)
{
case OrderType.Market:
order = new MarketOrder(symbol, quantity, time, tag, properties);
break;
case OrderType.Limit:
order = new LimitOrder(symbol, quantity, limitPrice, time, tag, properties);
break;
case OrderType.StopMarket:
order = new StopMarketOrder(symbol, quantity, stopPrice, time, tag, properties);
break;
case OrderType.StopLimit:
order = new StopLimitOrder(symbol, quantity, stopPrice, limitPrice, time, tag, properties);
break;
case OrderType.LimitIfTouched:
order = new LimitIfTouchedOrder(symbol, quantity, triggerPrice, limitPrice, time, tag, properties);
break;
case OrderType.MarketOnOpen:
order = new MarketOnOpenOrder(symbol, quantity, time, tag, properties);
break;
case OrderType.MarketOnClose:
order = new MarketOnCloseOrder(symbol, quantity, time, tag, properties);
break;
case OrderType.OptionExercise:
order = new OptionExerciseOrder(symbol, quantity, time, tag, properties);
break;
default:
throw new ArgumentOutOfRangeException();
}
order.Status = OrderStatus.New;
order.Id = orderId;
return order;
}
}
}
| |
//
// 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.Sql.LegacySdk;
using Microsoft.Azure.Management.Sql.LegacySdk.Models;
namespace Microsoft.Azure.Management.Sql.LegacySdk
{
/// <summary>
/// The Windows Azure SQL Database management API provides a RESTful set of
/// web services that interact with Windows Azure SQL Database services to
/// manage your databases. The API enables users to create, retrieve,
/// update, and delete databases and servers.
/// </summary>
public static partial class ServerAdministratorOperationsExtensions
{
/// <summary>
/// Begins creating a new Azure SQL Server Active Directory
/// Administrator or updating an existing Azure SQL Server Active
/// Directory Administrator. To determine the status of the operation
/// call GetServerAdministratorOperationStatus.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IServerAdministratorOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server to which the Azure SQL
/// Server Active Directory administrator belongs
/// </param>
/// <param name='administratorName'>
/// Required. The name of the Azure SQL Server Active Directory
/// Administrator.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for createing or updating an
/// Active Directory Administrator.
/// </param>
/// <returns>
/// Response for long running Azure SQL Server Active Directory
/// Administrator operations.
/// </returns>
public static ServerAdministratorCreateOrUpdateResponse BeginCreateOrUpdate(this IServerAdministratorOperations operations, string resourceGroupName, string serverName, string administratorName, ServerAdministratorCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServerAdministratorOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, serverName, administratorName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Begins creating a new Azure SQL Server Active Directory
/// Administrator or updating an existing Azure SQL Server Active
/// Directory Administrator. To determine the status of the operation
/// call GetServerAdministratorOperationStatus.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IServerAdministratorOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server to which the Azure SQL
/// Server Active Directory administrator belongs
/// </param>
/// <param name='administratorName'>
/// Required. The name of the Azure SQL Server Active Directory
/// Administrator.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for createing or updating an
/// Active Directory Administrator.
/// </param>
/// <returns>
/// Response for long running Azure SQL Server Active Directory
/// Administrator operations.
/// </returns>
public static Task<ServerAdministratorCreateOrUpdateResponse> BeginCreateOrUpdateAsync(this IServerAdministratorOperations operations, string resourceGroupName, string serverName, string administratorName, ServerAdministratorCreateOrUpdateParameters parameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, serverName, administratorName, parameters, CancellationToken.None);
}
/// <summary>
/// Begins deleting an existing Azure SQL Server Active Directory
/// Administrator.To determine the status of the operation call
/// GetServerAdministratorDeleteOperationStatus.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IServerAdministratorOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server to which the Azure SQL
/// Server Active Directory administrator belongs
/// </param>
/// <param name='administratorName'>
/// Required. The name of the Azure SQL Server Active Directory
/// Administrator.
/// </param>
/// <returns>
/// Response for long running Azure SQL Server Active Directory
/// administrator delete operations.
/// </returns>
public static ServerAdministratorDeleteResponse BeginDelete(this IServerAdministratorOperations operations, string resourceGroupName, string serverName, string administratorName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServerAdministratorOperations)s).BeginDeleteAsync(resourceGroupName, serverName, administratorName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Begins deleting an existing Azure SQL Server Active Directory
/// Administrator.To determine the status of the operation call
/// GetServerAdministratorDeleteOperationStatus.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IServerAdministratorOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server to which the Azure SQL
/// Server Active Directory administrator belongs
/// </param>
/// <param name='administratorName'>
/// Required. The name of the Azure SQL Server Active Directory
/// Administrator.
/// </param>
/// <returns>
/// Response for long running Azure SQL Server Active Directory
/// administrator delete operations.
/// </returns>
public static Task<ServerAdministratorDeleteResponse> BeginDeleteAsync(this IServerAdministratorOperations operations, string resourceGroupName, string serverName, string administratorName)
{
return operations.BeginDeleteAsync(resourceGroupName, serverName, administratorName, CancellationToken.None);
}
/// <summary>
/// Creates a new Azure SQL Server Active Directory Administrator or
/// updates an existing Azure SQL Server Active Directory
/// Administrator.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IServerAdministratorOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the Azure SQL
/// Server Active Directory Administrator is hosted.
/// </param>
/// <param name='administratorName'>
/// Required. The name of the Azure SQL Server Active Directory
/// Administrator to be operated on (Updated or created).
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for creating or updating a Server
/// Administrator.
/// </param>
/// <returns>
/// Response for long running Azure SQL Server Active Directory
/// Administrator operations.
/// </returns>
public static ServerAdministratorCreateOrUpdateResponse CreateOrUpdate(this IServerAdministratorOperations operations, string resourceGroupName, string serverName, string administratorName, ServerAdministratorCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServerAdministratorOperations)s).CreateOrUpdateAsync(resourceGroupName, serverName, administratorName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new Azure SQL Server Active Directory Administrator or
/// updates an existing Azure SQL Server Active Directory
/// Administrator.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IServerAdministratorOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the Azure SQL
/// Server Active Directory Administrator is hosted.
/// </param>
/// <param name='administratorName'>
/// Required. The name of the Azure SQL Server Active Directory
/// Administrator to be operated on (Updated or created).
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for creating or updating a Server
/// Administrator.
/// </param>
/// <returns>
/// Response for long running Azure SQL Server Active Directory
/// Administrator operations.
/// </returns>
public static Task<ServerAdministratorCreateOrUpdateResponse> CreateOrUpdateAsync(this IServerAdministratorOperations operations, string resourceGroupName, string serverName, string administratorName, ServerAdministratorCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, serverName, administratorName, parameters, CancellationToken.None);
}
/// <summary>
/// Deletes an existing Azure SQL Server Active Directory Administrator.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IServerAdministratorOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server to which the Azure SQL
/// Server Active Directory administrator belongs
/// </param>
/// <param name='administratorName'>
/// Required. The name of the Azure SQL Server Active Directory
/// Administrator to be operated on (Updated or created).
/// </param>
/// <returns>
/// Response for long running Azure SQL Server Active Directory
/// administrator delete operations.
/// </returns>
public static ServerAdministratorDeleteResponse Delete(this IServerAdministratorOperations operations, string resourceGroupName, string serverName, string administratorName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServerAdministratorOperations)s).DeleteAsync(resourceGroupName, serverName, administratorName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes an existing Azure SQL Server Active Directory Administrator.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IServerAdministratorOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server to which the Azure SQL
/// Server Active Directory administrator belongs
/// </param>
/// <param name='administratorName'>
/// Required. The name of the Azure SQL Server Active Directory
/// Administrator to be operated on (Updated or created).
/// </param>
/// <returns>
/// Response for long running Azure SQL Server Active Directory
/// administrator delete operations.
/// </returns>
public static Task<ServerAdministratorDeleteResponse> DeleteAsync(this IServerAdministratorOperations operations, string resourceGroupName, string serverName, string administratorName)
{
return operations.DeleteAsync(resourceGroupName, serverName, administratorName, CancellationToken.None);
}
/// <summary>
/// Returns an Azure SQL Server Administrator.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IServerAdministratorOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server to which the Azure SQL
/// Server Active Directory administrator belongs.
/// </param>
/// <param name='administratorName'>
/// Required. The name of the Azure SQL Server Active Directory
/// Administrator.
/// </param>
/// <returns>
/// Represents the response to a Get Azure SQL Server Active Directory
/// Administrators request.
/// </returns>
public static ServerAdministratorGetResponse Get(this IServerAdministratorOperations operations, string resourceGroupName, string serverName, string administratorName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServerAdministratorOperations)s).GetAsync(resourceGroupName, serverName, administratorName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns an Azure SQL Server Administrator.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IServerAdministratorOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server to which the Azure SQL
/// Server Active Directory administrator belongs.
/// </param>
/// <param name='administratorName'>
/// Required. The name of the Azure SQL Server Active Directory
/// Administrator.
/// </param>
/// <returns>
/// Represents the response to a Get Azure SQL Server Active Directory
/// Administrators request.
/// </returns>
public static Task<ServerAdministratorGetResponse> GetAsync(this IServerAdministratorOperations operations, string resourceGroupName, string serverName, string administratorName)
{
return operations.GetAsync(resourceGroupName, serverName, administratorName, CancellationToken.None);
}
/// <summary>
/// Gets the status of an Azure SQL Server Active Directory
/// Administrator delete operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IServerAdministratorOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation
/// </param>
/// <returns>
/// Response for long running Azure SQL Server Active Directory
/// administrator delete operations.
/// </returns>
public static ServerAdministratorDeleteResponse GetServerAdministratorDeleteOperationStatus(this IServerAdministratorOperations operations, string operationStatusLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServerAdministratorOperations)s).GetServerAdministratorDeleteOperationStatusAsync(operationStatusLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the status of an Azure SQL Server Active Directory
/// Administrator delete operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IServerAdministratorOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation
/// </param>
/// <returns>
/// Response for long running Azure SQL Server Active Directory
/// administrator delete operations.
/// </returns>
public static Task<ServerAdministratorDeleteResponse> GetServerAdministratorDeleteOperationStatusAsync(this IServerAdministratorOperations operations, string operationStatusLink)
{
return operations.GetServerAdministratorDeleteOperationStatusAsync(operationStatusLink, CancellationToken.None);
}
/// <summary>
/// Gets the status of an Azure SQL Server Active Directory
/// Administrator create or update operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IServerAdministratorOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation
/// </param>
/// <returns>
/// Response for long running Azure SQL Server Active Directory
/// Administrator operations.
/// </returns>
public static ServerAdministratorCreateOrUpdateResponse GetServerAdministratorOperationStatus(this IServerAdministratorOperations operations, string operationStatusLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServerAdministratorOperations)s).GetServerAdministratorOperationStatusAsync(operationStatusLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the status of an Azure SQL Server Active Directory
/// Administrator create or update operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IServerAdministratorOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation
/// </param>
/// <returns>
/// Response for long running Azure SQL Server Active Directory
/// Administrator operations.
/// </returns>
public static Task<ServerAdministratorCreateOrUpdateResponse> GetServerAdministratorOperationStatusAsync(this IServerAdministratorOperations operations, string operationStatusLink)
{
return operations.GetServerAdministratorOperationStatusAsync(operationStatusLink, CancellationToken.None);
}
/// <summary>
/// Returns a list of Azure SQL Server Administrators.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IServerAdministratorOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server to which the Azure SQL
/// Server Active Directory administrators belongs.
/// </param>
/// <returns>
/// Represents the response to a List Azure SQL Active Directory
/// Administrators request.
/// </returns>
public static ServerAdministratorListResponse List(this IServerAdministratorOperations operations, string resourceGroupName, string serverName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServerAdministratorOperations)s).ListAsync(resourceGroupName, serverName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns a list of Azure SQL Server Administrators.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IServerAdministratorOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server to which the Azure SQL
/// Server Active Directory administrators belongs.
/// </param>
/// <returns>
/// Represents the response to a List Azure SQL Active Directory
/// Administrators request.
/// </returns>
public static Task<ServerAdministratorListResponse> ListAsync(this IServerAdministratorOperations operations, string resourceGroupName, string serverName)
{
return operations.ListAsync(resourceGroupName, serverName, CancellationToken.None);
}
}
}
| |
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using tomware.Microwf.Domain;
using tomware.Microwf.Infrastructure;
using tomware.Microwf.Tests.Integration.Utils;
using Xunit;
namespace tomware.Microwf.Tests.Integration.Infrastructure
{
public class WorkItemServiceTest
{
[Fact]
public async Task WorkItemService_GetUpCommingsAsync_UpCommingsReturned()
{
// Arrange
var diHelper = new DITestHelper();
var serviceProvider = diHelper.BuildDefault();
var context = serviceProvider.GetRequiredService<TestDbContext>();
var service = serviceProvider.GetRequiredService<IWorkItemService>();
var dueDate = SystemTime.Now().AddMinutes(2);
var workItems = this.GetWorkItems(dueDate);
await context.WorkItems.AddRangeAsync(workItems);
await context.SaveChangesAsync();
var parameters = new PagingParameters();
// Act
var upcommings = await service.GetUpCommingsAsync(parameters);
// Assert
Assert.NotNull(upcommings);
Assert.Equal(2, upcommings.Count);
}
[Fact]
public async Task WorkItemService_GetFailedAsync_FailedReturned()
{
// Arrange
var diHelper = new DITestHelper();
var serviceProvider = diHelper.BuildDefault();
var context = serviceProvider.GetRequiredService<TestDbContext>();
var service = serviceProvider.GetRequiredService<IWorkItemService>();
var workItems = this.GetWorkItems();
workItems.First().Retries = 4;
await context.WorkItems.AddRangeAsync(workItems);
await context.SaveChangesAsync();
var parameters = new PagingParameters();
// Act
var failed = await service.GetFailedAsync(parameters);
// Assert
Assert.NotNull(failed);
Assert.Single(failed);
Assert.Equal(1, failed.First().Id);
Assert.Equal(4, failed.First().Retries);
}
[Fact]
public async Task WorkItemService_ResumeWorkItemsAsync_TwoItemsResumed()
{
// Arrange
var diHelper = new DITestHelper();
var serviceProvider = diHelper.BuildDefault();
var context = serviceProvider.GetRequiredService<TestDbContext>();
await context.WorkItems.AddRangeAsync(this.GetWorkItems());
await context.SaveChangesAsync();
var service = serviceProvider.GetRequiredService<IWorkItemService>();
// Act
IEnumerable<WorkItem> resumedItems = await service.ResumeWorkItemsAsync();
// Assert
Assert.Equal(2, resumedItems.Count());
}
[Fact]
public async Task WorkItemService_PersistWorkItemsAsync_TwoItemsPersisted()
{
// Arrange
var diHelper = new DITestHelper();
var serviceProvider = diHelper.BuildDefault();
var context = serviceProvider.GetRequiredService<TestDbContext>();
var service = serviceProvider.GetRequiredService<IWorkItemService>();
var workItems = this.GetWorkItems();
// Act
await service.PersistWorkItemsAsync(workItems);
// Assert
Assert.Equal(2, context.WorkItems.Count());
}
[Fact]
public async Task WorkItemService_PersistWorkItemsAsync_OneItemPersistedOneItemUpdated()
{
// Arrange
var diHelper = new DITestHelper();
var serviceProvider = diHelper.BuildDefault();
var context = serviceProvider.GetRequiredService<TestDbContext>();
var service = serviceProvider.GetRequiredService<IWorkItemService>();
var workItems = this.GetWorkItems();
var firstWorkItem = workItems.First();
firstWorkItem.WorkflowType = "firstCopy";
await context.WorkItems.AddAsync(firstWorkItem);
await context.SaveChangesAsync();
firstWorkItem.WorkflowType = "first";
// Act
await service.PersistWorkItemsAsync(workItems);
// Assert
Assert.Equal(2, context.WorkItems.Count());
Assert.Equal("first", context.WorkItems.First().WorkflowType);
}
[Fact]
public async Task WorkItemService_Reschedule_WorkItemRescheduled()
{
// Arrange
var diHelper = new DITestHelper();
var serviceProvider = diHelper.BuildDefault();
var context = serviceProvider.GetRequiredService<TestDbContext>();
var service = serviceProvider.GetRequiredService<IWorkItemService>();
var repository = serviceProvider.GetRequiredService<IWorkItemRepository>();
var workItems = this.GetWorkItems();
await context.WorkItems.AddRangeAsync(workItems);
await context.SaveChangesAsync();
var dueDate = SystemTime.Now().AddMinutes(1);
var model = new tomware.Microwf.Infrastructure.WorkItemDto
{
Id = 1,
DueDate = dueDate
};
// Act
await service.Reschedule(model);
// Assert
var rescheduledItem = await repository.GetByIdAsync(1);
Assert.NotNull(rescheduledItem);
Assert.Equal(rescheduledItem.DueDate, dueDate);
}
[Fact]
public async Task WorkItemService_DeleteAsync_OneItemDeleted()
{
// Arrange
var diHelper = new DITestHelper();
var serviceProvider = diHelper.BuildDefault();
var context = serviceProvider.GetRequiredService<TestDbContext>();
var service = serviceProvider.GetRequiredService<IWorkItemService>();
var workItems = this.GetWorkItems();
await context.WorkItems.AddRangeAsync(workItems);
await context.SaveChangesAsync();
// Act
await service.DeleteAsync(1);
// Assert
Assert.Equal(1, context.WorkItems.Count());
Assert.Equal(2, context.WorkItems.First().Id);
}
private List<WorkItem> GetWorkItems(DateTime? dueDate = null)
{
List<WorkItem> workItems = new List<WorkItem>() {
new WorkItem {
Id = 1,
WorkflowType = "first",
TriggerName = "triggerFirst",
EntityId = 1,
DueDate = dueDate ?? SystemTime.Now()
},
new WorkItem {
Id = 2,
WorkflowType = "second",
TriggerName = "triggerSecond",
EntityId = 1,
DueDate = dueDate ?? SystemTime.Now()
}
};
return workItems;
}
}
}
| |
// Copyright (c) 2021 Alachisoft
//
// 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.Text;
using System.Collections;
using System.IO;
namespace Alachisoft.NCache.Common.Monitoring
{
public class Logger
{
private TextWriter _writer;
const string STERIC = "*****************************************************************************************************";
public const string TIME_FORMAT = "dd-MM-yy HH:mm:ss:ffff";
private object _sync_mutex = new object();
/// <summary>
/// True if writer is not instantiated, false otherwise
/// </summary>
public bool IsWriterNull
{
get
{
if (_writer == null) return true;
else return false;
}
}
/// <summary>
/// Creates logs in installation folder
/// </summary>
/// <param name="fileName">name of file</param>
/// <param name="directory">directory in which the logs are to be made</param>
public void Initialize(string fileName, string directory)
{
Initialize(fileName, null, directory);
}
/// <summary>
/// Creates logs in provided folder
/// </summary>
/// <param name="fileName">name of file</param>
/// <param name="filepath">path where logs are to be created</param>
/// <param name="directory">directory in which the logs are to be made</param>
public void Initialize(string fileName, string filepath, string directory)
{
lock (_sync_mutex)
{
string filename = fileName + "." +
Environment.MachineName.ToLower() + "." +
DateTime.Now.ToString("dd-MM-yy HH-mm-ss") + @".logs.txt";
if (filepath == null || filepath == string.Empty)
{
if (!DirectoryUtil.SearchGlobalDirectory("log-files", false, out filepath))
{
try
{
DirectoryUtil.SearchLocalDirectory("log-files", true, out filepath);
}
catch (Exception ex)
{
throw new Exception("Unable to initialize the log file", ex);
}
}
}
try
{
filepath = Path.Combine(filepath, directory);
if (!Directory.Exists(filepath)) Directory.CreateDirectory(filepath);
filepath = Path.Combine(filepath, filename);
_writer = TextWriter.Synchronized(new StreamWriter(filepath, false));
}
catch (Exception)
{
throw;
}
}
}
public void WriteClientActivities(Hashtable activityTable,bool completed)
{
if (activityTable != null)
{
try
{
string status = completed ? "completed" : "in_execution";
WriteSingleLine("CLIENT ACTIVITY LOG [clients :" + activityTable.Count + " status : " + status + "]");
IDictionaryEnumerator ide = activityTable.GetEnumerator();
while (ide.MoveNext())
{
ClienfInfo cInfo = ide.Key as ClienfInfo;
ArrayList activities = ide.Value as ArrayList;
if (cInfo != null)
{
WriteSingleLine(STERIC);
WriteSingleLine("client [id :" + cInfo.ID + " address :" + cInfo.Address + "]");
WriteSingleLine(STERIC);
}
if (activities != null && activities.Count > 0)
{
foreach (ClientActivity cActivity in activities)
{
WriteClientActivity(cActivity);
}
}
else
{
WriteSingleLine("No activity observered");
}
WriteSingleLine("activity for client_id :" + cInfo.ID + " ends here");
WriteSingleLine("");
}
}
catch (Exception e)
{
}
}
}
public void WriteSingleLine(string logText)
{
if (_writer != null)
{
lock (_sync_mutex)
{
_writer.WriteLine(logText);
_writer.Flush();
}
}
}
public void WriteClientActivity(ClientActivity activity)
{
if (_writer != null && activity != null)
{
TimeSpan tspan = activity.EndTime - activity.StartTime;
WriteSingleLine("activity [duration(ms) :" +tspan.TotalMilliseconds + " start_time :" + activity.StartTime.ToString(TIME_FORMAT) + " end_time :" + activity.EndTime.ToString(TIME_FORMAT) + "]");
if (activity.Activities != null)
{
for (int i = 0; i < activity.Activities.Count; i++)
{
MethodActivity mActivity = activity.Activities[i] as MethodActivity;
if (mActivity != null)
{
int space2 = 40;
string line = null;
line = mActivity.Time.ToString(TIME_FORMAT) + ": " + mActivity.MethodName.PadRight(space2, ' ') + mActivity.Log;
lock (_sync_mutex)
{
_writer.WriteLine(line);
_writer.Flush();
}
}
}
}
WriteSingleLine("activity ends");
WriteSingleLine("");
}
}
/// <summary>
/// Close writer
/// </summary>
public void Close()
{
lock (_sync_mutex)
{
if (_writer != null)
{
lock (_writer)
{
_writer.Close();
_writer = null;
}
}
}
}
}
}
| |
// leveldb-sharp
//
// Copyright (c) 2011 The LevelDB Authors
// Copyright (c) 2012-2013, Mirco Bauer <meebey@meebey.net>
// Copyright (c) 2013 Behrooz Amoozad <behrooz0az@gmail.com>
// 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.
using System;
using System.Text;
using System.Runtime.InteropServices;
namespace LevelDB
{
/// <summary>
/// Native method P/Invoke declarations for LevelDB
/// </summary>
public static class Native
{
public static void CheckError (string error)
{
if (String.IsNullOrEmpty (error)) {
return;
}
throw new ApplicationException (error);
}
public static void CheckError (IntPtr error)
{
if (error == IntPtr.Zero) {
return;
}
CheckError (GetAndReleaseString (error));
}
public static UIntPtr GetArrayLength (byte[] value)
{
if (value == null || value.Length == 0) {
return UIntPtr.Zero;
}
return new UIntPtr ((uint)(value.Length));
}
public static string GetAndReleaseString (IntPtr ptr)
{
if (ptr == IntPtr.Zero) {
return null;
}
var str = Marshal.PtrToStringAnsi (ptr);
leveldb_free (ptr);
return str;
}
public static byte[] GetAndReleaseArray (IntPtr ptr, int length)
{
if (ptr == IntPtr.Zero) {
return null;
}
byte[] arr = new byte[length];
Marshal.Copy (ptr, arr, 0, length);
leveldb_free (ptr);
return arr;
}
#region DB operations
#region leveldb_open
// extern leveldb_t* leveldb_open(const leveldb_options_t* options, const char* name, char** errptr);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr leveldb_open (IntPtr options, string name, out IntPtr error);
public static IntPtr leveldb_open (IntPtr options, string name, out string error)
{
IntPtr errorPtr;
var db = leveldb_open (options, name, out errorPtr);
error = GetAndReleaseString (errorPtr);
return db;
}
public static IntPtr leveldb_open (IntPtr options, string name)
{
string error;
var db = leveldb_open (options, name, out error);
CheckError (error);
return db;
}
#endregion
// extern void leveldb_close(leveldb_t* db);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_close (IntPtr db);
#region leveldb_put
// extern void leveldb_put(leveldb_t* db, const leveldb_writeoptions_t* options, const char* key, size_t keylen, const char* val, size_t vallen, char** errptr);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_put (IntPtr db,
IntPtr writeOptions,
byte[] key,
UIntPtr keyLength,
byte[] value,
UIntPtr valueLength,
out IntPtr error);
public static void leveldb_put (IntPtr db,
IntPtr writeOptions,
byte[] key,
UIntPtr keyLength,
byte[] value,
UIntPtr valueLength,
out string error)
{
IntPtr errorPtr;
leveldb_put (db, writeOptions, key, keyLength, value, valueLength,
out errorPtr);
error = GetAndReleaseString (errorPtr);
}
public static void leveldb_put (IntPtr db,
IntPtr writeOptions,
byte[] key,
byte[] value)
{
string error;
var keyLength = GetArrayLength (key);
var valueLength = GetArrayLength (value);
Native.leveldb_put (db, writeOptions,
key, keyLength,
value, valueLength, out error);
CheckError (error);
}
public static void leveldb_put (IntPtr db,
IntPtr writeOptions,
string key,
string value,
System.Text.Encoding encoding)
{
leveldb_put (db, writeOptions, encoding.GetBytes (key), encoding.GetBytes (value));
}
public static void leveldb_put (IntPtr db,
IntPtr writeOptions,
string key,
string value)
{
leveldb_put (db, writeOptions, key, value, System.Text.Encoding.Default);
}
#endregion
#region leveldb_delete
// extern void leveldb_delete(leveldb_t* db, const leveldb_writeoptions_t* options, const char* key, size_t keylen, char** errptr);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_delete (IntPtr db, IntPtr writeOptions, byte[] key, UIntPtr keylen, out IntPtr error);
public static void leveldb_delete (IntPtr db, IntPtr writeOptions, byte[] key, UIntPtr keylen, out string error)
{
IntPtr errorPtr;
leveldb_delete (db, writeOptions, key, keylen, out errorPtr);
error = GetAndReleaseString (errorPtr);
}
public static void leveldb_delete (IntPtr db, IntPtr writeOptions, byte[] key)
{
string error;
var keyLength = GetArrayLength (key);
leveldb_delete (db, writeOptions, key, keyLength, out error);
CheckError (error);
}
public static void leveldb_delete (IntPtr db, IntPtr writeOptions, string key, System.Text.Encoding encoding)
{
leveldb_delete (db, writeOptions, encoding.GetBytes (key));
}
public static void leveldb_delete (IntPtr db, IntPtr writeOptions, string key)
{
leveldb_delete (db, writeOptions, key, System.Text.Encoding.Default);
}
#endregion
#region leveldb_write
// extern void leveldb_write(leveldb_t* db, const leveldb_writeoptions_t* options, leveldb_writebatch_t* batch, char** errptr);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_write (IntPtr db, IntPtr writeOptions, IntPtr writeBatch, out IntPtr error);
public static void leveldb_write (IntPtr db, IntPtr writeOptions, IntPtr writeBatch, out string error)
{
IntPtr errorPtr;
leveldb_write (db, writeOptions, writeBatch, out errorPtr);
error = GetAndReleaseString (errorPtr);
}
public static void leveldb_write (IntPtr db, IntPtr writeOptions, IntPtr writeBatch)
{
string error;
leveldb_write (db, writeOptions, writeBatch, out error);
CheckError (error);
}
#endregion
#region leveldb_get
// extern char* leveldb_get(leveldb_t* db, const leveldb_readoptions_t* options, const char* key, size_t keylen, size_t* vallen, char** errptr);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr leveldb_get (IntPtr db,
IntPtr readOptions,
byte[] key,
UIntPtr keyLength,
out UIntPtr valueLength,
out IntPtr error);
public static IntPtr leveldb_get (IntPtr db,
IntPtr readOptions,
byte[] key,
UIntPtr keyLength,
out UIntPtr valueLength,
out string error)
{
IntPtr errorPtr;
var valuePtr = leveldb_get (db, readOptions, key, keyLength,
out valueLength, out errorPtr);
error = GetAndReleaseString (errorPtr);
return valuePtr;
}
public static Slice leveldb_get_slice (IntPtr db,
IntPtr readOptions,
byte[] key)
{
UIntPtr valueLength;
string error;
var keyLength = GetArrayLength (key);
var valuePtr = leveldb_get (db, readOptions, key, keyLength,
out valueLength, out error);
CheckError (error);
if (valuePtr == IntPtr.Zero || valueLength == UIntPtr.Zero) {
return null;
}
return new Slice (valuePtr, (int)valueLength, true);
}
public static byte[] leveldb_get_raw (IntPtr db,
IntPtr readOptions,
byte[] key)
{
UIntPtr valueLength;
string error;
var keyLength = GetArrayLength (key);
var valuePtr = leveldb_get (db, readOptions, key, keyLength,
out valueLength, out error);
CheckError (error);
if (valuePtr == IntPtr.Zero || valueLength == UIntPtr.Zero) {
return null;
}
byte[] buffer = new byte[(int)valueLength];
Marshal.Copy (valuePtr, buffer, 0, (int)valueLength);
leveldb_free (valuePtr);
return buffer;
}
public static byte[] leveldb_get_raw (IntPtr db,
IntPtr readOptions,
string key, System.Text.Encoding encoding)
{
return leveldb_get_raw (db, readOptions, encoding.GetBytes (key));
}
public static byte[] leveldb_get_raw (IntPtr db,
IntPtr readOptions,
string key)
{
return leveldb_get_raw (db, readOptions, key, System.Text.Encoding.Default);
}
public static string leveldb_get (IntPtr db,
IntPtr readOptions,
string key, System.Text.Encoding encoding)
{
byte[] bytes = leveldb_get_raw (db, readOptions, encoding.GetBytes (key));
if (bytes == null)
return null;
return encoding.GetString (bytes);
}
public static string leveldb_get (IntPtr db,
IntPtr readOptions,
byte[] key, System.Text.Encoding encoding)
{
return encoding.GetString (leveldb_get_raw (db, readOptions, key));
}
public static string leveldb_get (IntPtr db,
IntPtr readOptions,
string key)
{
return leveldb_get (db, readOptions, key, System.Text.Encoding.Default);
}
#endregion
// extern leveldb_iterator_t* leveldb_create_iterator(leveldb_t* db, const leveldb_readoptions_t* options);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr leveldb_create_iterator (IntPtr db, IntPtr readOptions);
// extern const leveldb_snapshot_t* leveldb_create_snapshot(leveldb_t* db);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr leveldb_create_snapshot (IntPtr db);
// extern void leveldb_release_snapshot(leveldb_t* db, const leveldb_snapshot_t* snapshot);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_release_snapshot (IntPtr db, IntPtr snapshot);
/// <summary>
/// Returns NULL if property name is unknown.
/// Else returns a pointer to a malloc()-ed null-terminated value.
/// </summary>
// extern char* leveldb_property_value(leveldb_t* db, const char* propname);
[DllImport ("leveldb", EntryPoint = "leveldb_property_value", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr leveldb_property_value_native (IntPtr db, string propname);
public static string leveldb_property_value (IntPtr db, string propname)
{
var valuePtr = leveldb_property_value_native (db, propname);
if (valuePtr == IntPtr.Zero) {
return null;
}
var value = Marshal.PtrToStringAnsi (valuePtr);
leveldb_free (valuePtr);
return value;
}
// extern void leveldb_approximate_sizes(
// leveldb_t* db, int num_ranges,
// const char* const* range_start_key,
// const size_t* range_start_key_len,
// const char* const* range_limit_key,
// const size_t* range_limit_key_len,
// uint64_t* sizes);
/// <summary>
/// Compact the underlying storage for the key range [startKey,limitKey].
/// In particular, deleted and overwritten versions are discarded,
/// and the data is rearranged to reduce the cost of operations
/// needed to access the data. This operation should typically only
/// be invoked by users who understand the underlying implementation.
///
/// startKey==null is treated as a key before all keys in the database.
/// limitKey==null is treated as a key after all keys in the database.
/// Therefore the following call will compact the entire database:
/// leveldb_compact_range(db, null, null);
/// </summary>
// extern void leveldb_compact_range(leveldb_t* db,
// const char* start_key, size_t start_key_len,
// const char* limit_key, size_t limit_key_len);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_compact_range (IntPtr db,
byte[] startKey,
UIntPtr startKeyLen,
byte[] limitKey,
UIntPtr limitKeyLen);
public static void leveldb_compact_range_raw (IntPtr db,
byte[] startKey,
byte[] limitKey)
{
leveldb_compact_range (db,
startKey, GetArrayLength (startKey),
limitKey, GetArrayLength (limitKey));
}
public static void leveldb_compact_range (IntPtr db,
string startKey,
string limitKey,
System.Text.Encoding encoding)
{
leveldb_compact_range_raw (db,
encoding.GetBytes (startKey ?? ""),
encoding.GetBytes (limitKey ?? ""));
}
public static void leveldb_compact_range (IntPtr db,
string startKey,
string limitKey)
{
leveldb_compact_range (db,
startKey,
limitKey,
System.Text.Encoding.Default);
}
#endregion
#region Management operations
#region leveldb_destroy_db
// extern void leveldb_destroy_db(const leveldb_options_t* options, const char* name, char** errptr);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_destroy_db (IntPtr options, string path, out IntPtr error);
public static void leveldb_destroy_db (IntPtr options, string path, out string error)
{
IntPtr errorPtr;
leveldb_destroy_db (options, path, out errorPtr);
error = GetAndReleaseString (errorPtr);
}
public static void leveldb_destroy_db (IntPtr options, string path)
{
string error;
leveldb_destroy_db (options, path, out error);
CheckError (error);
}
#endregion
#region leveldb_repair_db
// extern void leveldb_repair_db(const leveldb_options_t* options, const char* name, char** errptr);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_repair_db (IntPtr options, string path, out IntPtr error);
public static void leveldb_repair_db (IntPtr options, string path, out string error)
{
IntPtr errorPtr;
leveldb_repair_db (options, path, out errorPtr);
error = GetAndReleaseString (errorPtr);
}
public static void leveldb_repair_db (IntPtr options, string path)
{
string error;
leveldb_repair_db (options, path, out error);
CheckError (error);
}
#endregion
#endregion
#region Write batch
// extern leveldb_writebatch_t* leveldb_writebatch_create();
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr leveldb_writebatch_create ();
// extern void leveldb_writebatch_destroy(leveldb_writebatch_t*);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_writebatch_destroy (IntPtr writeBatch);
// extern void leveldb_writebatch_clear(leveldb_writebatch_t*);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_writebatch_clear (IntPtr writeBatch);
// extern void leveldb_writebatch_put(leveldb_writebatch_t*, const char* key, size_t klen, const char* val, size_t vlen);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_writebatch_put (IntPtr writeBatch,
byte[] key,
UIntPtr keyLength,
byte[] value,
UIntPtr valueLength);
public static void leveldb_writebatch_put (IntPtr writeBatch,
byte[] key,
byte[] value)
{
var keyLength = GetArrayLength (key);
var valueLength = GetArrayLength (value);
Native.leveldb_writebatch_put (writeBatch,
key, keyLength,
value, valueLength);
}
public static void leveldb_writebatch_put (IntPtr writeBatch,
string key,
string value,
System.Text.Encoding encoding)
{
leveldb_writebatch_put (writeBatch, encoding.GetBytes (key), encoding.GetBytes (value));
}
public static void leveldb_writebatch_put (IntPtr writeBatch,
string key,
string value)
{
leveldb_writebatch_put (writeBatch, key, value, System.Text.Encoding.Default);
}
// extern void leveldb_writebatch_delete(leveldb_writebatch_t*, const char* key, size_t klen);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_writebatch_delete (IntPtr writeBatch, byte[] key, UIntPtr keylen);
public static void leveldb_writebatch_delete (IntPtr writeBatch, byte[] key)
{
var keyLength = GetArrayLength (key);
leveldb_writebatch_delete (writeBatch, key, keyLength);
}
public static void leveldb_writebatch_delete (IntPtr writeBatch, string key, System.Text.Encoding encoding)
{
leveldb_writebatch_delete (writeBatch, encoding.GetBytes (key));
}
public static void leveldb_writebatch_delete (IntPtr writeBatch, string key)
{
leveldb_writebatch_delete (writeBatch, key, System.Text.Encoding.Default);
}
// TODO:
// extern void leveldb_writebatch_iterate(leveldb_writebatch_t*, void* state, void (*put)(void*, const char* k, size_t klen, const char* v, size_t vlen), void (*deleted)(void*, const char* k, size_t klen));
#endregion
#region Options
// extern leveldb_options_t* leveldb_options_create();
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr leveldb_options_create ();
// extern void leveldb_options_destroy(leveldb_options_t*);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_options_destroy (IntPtr options);
// extern void leveldb_options_set_comparator(leveldb_options_t*, leveldb_comparator_t*);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_options_set_comparator (IntPtr options, IntPtr comparator);
/// <summary>
/// If true, the database will be created if it is missing.
/// Default: false
/// </summary>
// extern void leveldb_options_set_create_if_missing(leveldb_options_t*, unsigned char);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_options_set_create_if_missing (IntPtr options, bool value);
/// <summary>
/// If true, an error is raised if the database already exists.
/// Default: false
/// </summary>
// extern void leveldb_options_set_error_if_exists(leveldb_options_t*, unsigned char);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_options_set_error_if_exists (IntPtr options, bool value);
/// <summary>
/// If true, the implementation will do aggressive checking of the
/// data it is processing and will stop early if it detects any
/// errors. This may have unforeseen ramifications: for example, a
/// corruption of one DB entry may cause a large number of entries to
/// become unreadable or for the entire DB to become unopenable.
/// Default: false
/// </summary>
// extern void leveldb_options_set_paranoid_checks(leveldb_options_t*, unsigned char);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_options_set_paranoid_checks (IntPtr options, bool value);
/// <summary>
/// Number of open files that can be used by the DB. You may need to
/// increase this if your database has a large working set (budget
/// one open file per 2MB of working set).
/// Default: 1000
/// </summary>
// extern void leveldb_options_set_max_open_files(leveldb_options_t*, int);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_options_set_max_open_files (IntPtr options, int value);
/// <summary>
/// Each block is individually compressed before being written to
/// persistent storage. Compression is on by default since the default
/// compression method is very fast, and is automatically disabled for
/// uncompressible data. In rare cases, applications may want to
/// disable compression entirely, but should only do so if benchmarks
/// show a performance improvement.
/// Default: 1 (SnappyCompression)
/// </summary>
/// <seealso cref="T:CompressionType"/>
// extern void leveldb_options_set_compression(leveldb_options_t*, int);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_options_set_compression (IntPtr options, int value);
/// <summary>
/// Control over blocks (user data is stored in a set of blocks, and
/// a block is the unit of reading from disk).
///
/// If non-NULL, use the specified cache for blocks.
/// If NULL, leveldb will automatically create and use an 8MB internal cache.
/// Default: NULL
/// </summary>
// extern void leveldb_options_set_cache(leveldb_options_t*, leveldb_cache_t*);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_options_set_cache (IntPtr options, IntPtr cache);
public static void leveldb_options_set_cache_size (IntPtr options, int capacity)
{
var cache = leveldb_cache_create_lru ((UIntPtr)capacity);
leveldb_options_set_cache (options, cache);
}
/// <summary>
/// Approximate size of user data packed per block. Note that the
/// block size specified here corresponds to uncompressed data. The
/// actual size of the unit read from disk may be smaller if
/// compression is enabled. This parameter can be changed dynamically.
///
/// Default: 4K
/// </summary>
// extern void leveldb_options_set_block_size(leveldb_options_t*, size_t);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_options_set_block_size (IntPtr options, UIntPtr size);
public static void leveldb_options_set_block_size (IntPtr options, int size)
{
leveldb_options_set_block_size (options, (UIntPtr)size);
}
/// <summary>
/// Amount of data to build up in memory (backed by an unsorted log
/// on disk) before converting to a sorted on-disk file.
///
/// Larger values increase performance, especially during bulk loads.
/// Up to two write buffers may be held in memory at the same time,
/// so you may wish to adjust this parameter to control memory usage.
/// Also, a larger write buffer will result in a longer recovery time
/// the next time the database is opened.
///
/// Default: 4MB
/// </summary>
// extern void leveldb_options_set_write_buffer_size(leveldb_options_t*, size_t);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_options_set_write_buffer_size (IntPtr options, UIntPtr size);
public static void leveldb_options_set_write_buffer_size (IntPtr options, int size)
{
leveldb_options_set_write_buffer_size (options, (UIntPtr)size);
}
/// <summary>
/// Number of keys between restart points for delta encoding of keys.
/// This parameter can be changed dynamically. Most clients should
/// leave this parameter alone.
/// Default: 16
/// </summary>
// extern void leveldb_options_set_block_restart_interval(leveldb_options_t*, int);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_options_set_block_restart_interval (IntPtr options, int interval);
#endregion
#region Read Options
// extern leveldb_readoptions_t* leveldb_readoptions_create();
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr leveldb_readoptions_create ();
// extern void leveldb_readoptions_destroy(leveldb_readoptions_t*);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_readoptions_destroy (IntPtr readOptions);
// extern void leveldb_readoptions_set_verify_checksums(leveldb_readoptions_t*, unsigned char);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_readoptions_set_verify_checksums (IntPtr readOptions, bool value);
// extern void leveldb_readoptions_set_fill_cache(leveldb_readoptions_t*, unsigned char);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_readoptions_set_fill_cache (IntPtr readOptions, bool value);
// extern void leveldb_readoptions_set_snapshot(leveldb_readoptions_t*, const leveldb_snapshot_t*);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_readoptions_set_snapshot (IntPtr readOptions, IntPtr snapshot);
#endregion
#region Write Options
// extern leveldb_writeoptions_t* leveldb_writeoptions_create();
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr leveldb_writeoptions_create ();
// extern void leveldb_writeoptions_destroy(leveldb_writeoptions_t*);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_writeoptions_destroy (IntPtr writeOptions);
// extern void leveldb_writeoptions_set_sync(leveldb_writeoptions_t*, unsigned char);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_writeoptions_set_sync (IntPtr writeOptions, bool value);
#endregion
#region Iterator
// extern void leveldb_iter_seek_to_first(leveldb_iterator_t*);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_iter_seek_to_first (IntPtr iter);
// extern void leveldb_iter_seek_to_last(leveldb_iterator_t*);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_iter_seek_to_last (IntPtr iter);
// extern void leveldb_iter_seek(leveldb_iterator_t*, const char* k, size_t klen);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_iter_seek (IntPtr iter, byte[] key, UIntPtr keyLength);
public static void leveldb_iter_seek (IntPtr iter, byte[] key)
{
var keyLength = GetArrayLength (key);
leveldb_iter_seek (iter, key, keyLength);
}
public static void leveldb_iter_seek (IntPtr iter, string key, System.Text.Encoding encoding)
{
leveldb_iter_seek (iter, encoding.GetBytes (key));
}
public static void leveldb_iter_seek (IntPtr iter, string key)
{
leveldb_iter_seek (iter, key, System.Text.Encoding.Default);
}
// extern unsigned char leveldb_iter_valid(const leveldb_iterator_t*);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern bool leveldb_iter_valid (IntPtr iter);
// extern void leveldb_iter_prev(leveldb_iterator_t*);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_iter_prev (IntPtr iter);
// extern void leveldb_iter_next(leveldb_iterator_t*);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_iter_next (IntPtr iter);
// extern const char* leveldb_iter_key(const leveldb_iterator_t*, size_t* klen);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr leveldb_iter_key (IntPtr iter, out UIntPtr keyLength);
public static byte[] leveldb_iter_key_raw (IntPtr iter)
{
UIntPtr keyLength;
var keyPtr = leveldb_iter_key (iter, out keyLength);
if (keyPtr == IntPtr.Zero || keyLength == UIntPtr.Zero) {
return null;
}
byte[] key = new byte[(int)keyLength];
Marshal.Copy (keyPtr, key, 0, (int)keyLength);
return key;
}
public static string leveldb_iter_key (IntPtr iter, System.Text.Encoding encoding)
{
return encoding.GetString (leveldb_iter_key_raw (iter));
}
public static string leveldb_iter_key (IntPtr iter)
{
return leveldb_iter_key (iter, System.Text.Encoding.Default);
}
// extern const char* leveldb_iter_value(const leveldb_iterator_t*, size_t* vlen);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr leveldb_iter_value (IntPtr iter, out UIntPtr valueLength);
public static byte[] leveldb_iter_value_raw (IntPtr iter)
{
UIntPtr valueLength;
var valuePtr = leveldb_iter_value (iter, out valueLength);
if (valuePtr == IntPtr.Zero || valueLength == UIntPtr.Zero) {
return null;
}
byte[] value = new byte[(int)valueLength];
Marshal.Copy (valuePtr, value, 0, (int)valueLength);
return value;
}
public static string leveldb_iter_value (IntPtr iter, System.Text.Encoding encoding)
{
return encoding.GetString (leveldb_iter_value_raw (iter));
}
public static string leveldb_iter_value (IntPtr iter)
{
return leveldb_iter_value (iter, System.Text.Encoding.Default);
}
// extern void leveldb_iter_destroy(leveldb_iterator_t*);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_iter_destroy (IntPtr iter);
// TODO:
// extern void leveldb_iter_get_error(const leveldb_iterator_t*, char** errptr);
#endregion
#region Cache
// extern leveldb_cache_t* leveldb_cache_create_lru(size_t capacity);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr leveldb_cache_create_lru (UIntPtr capacity);
// extern void leveldb_cache_destroy(leveldb_cache_t* cache);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_cache_destroy (IntPtr cache);
#endregion
#region Env
// TODO:
// extern leveldb_env_t* leveldb_create_default_env();
// extern void leveldb_env_destroy(leveldb_env_t*);
#endregion
#region Utility
/// <summary>
/// Calls free(ptr).
/// REQUIRES: ptr was malloc()-ed and returned by one of the routines
/// in this file. Note that in certain cases (typically on Windows),
/// you may need to call this routine instead of free(ptr) to dispose
/// of malloc()-ed memory returned by this library.
/// </summary>
// extern void leveldb_free(void* ptr);
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern void leveldb_free (IntPtr ptr);
/// <summary>
/// Return the major version number for this release.
/// </summary>
// extern int leveldb_major_version();
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern int leveldb_major_version ();
/// <summary>
/// Return the minor version number for this release.
/// </summary>
// extern int leveldb_minor_version();
[DllImport ("leveldb", CallingConvention = CallingConvention.Cdecl)]
public static extern int leveldb_minor_version ();
#endregion
public static void Dump (IntPtr db)
{
var options = Native.leveldb_readoptions_create ();
IntPtr iter = Native.leveldb_create_iterator (db, options);
for (Native.leveldb_iter_seek_to_first (iter);
Native.leveldb_iter_valid (iter);
Native.leveldb_iter_next (iter)) {
byte[] key = Native.leveldb_iter_key_raw (iter);
byte[] value = Native.leveldb_iter_value_raw (iter);
Console.WriteLine ("'{0}' => '{1}'", key, value);
}
Native.leveldb_iter_destroy (iter);
}
}
}
| |
// Copyright (c) 2015 SharpYaml - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// -------------------------------------------------------------------------------
// SharpYaml is a fork of YamlDotNet https://github.com/aaubry/YamlDotNet
// published with the following license:
// -------------------------------------------------------------------------------
//
// Copyright (c) 2008, 2009, 2010, 2011, 2012 Antoine Aubry
//
// 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 SharpYaml;
using SharpYaml.Events;
using System.Collections.Generic;
namespace SharpYaml.Serialization
{
/// <summary>
/// Represents a single node in the YAML document.
/// </summary>
public abstract class YamlNode
{
/// <summary>
/// Gets or sets the anchor of the node.
/// </summary>
/// <value>The anchor.</value>
public string Anchor { get; set; }
/// <summary>
/// Gets or sets the tag of the node.
/// </summary>
/// <value>The tag.</value>
public string Tag { get; set; }
/// <summary>
/// Gets the position in the input stream where the event that originated the node starts.
/// </summary>
public Mark Start { get; private set; }
/// <summary>
/// Gets the position in the input stream where the event that originated the node ends.
/// </summary>
public Mark End { get; private set; }
/// <summary>
/// Loads the specified event.
/// </summary>
/// <param name="yamlEvent">The event.</param>
/// <param name="state">The state of the document.</param>
internal void Load(NodeEvent yamlEvent, DocumentLoadingState state)
{
Tag = yamlEvent.Tag;
if (yamlEvent.Anchor != null)
{
Anchor = yamlEvent.Anchor;
state.AddAnchor(this);
}
Start = yamlEvent.Start;
End = yamlEvent.End;
}
/// <summary>
/// Parses the node represented by the next event in <paramref name="events" />.
/// </summary>
/// <param name="events">The events.</param>
/// <param name="state">The state.</param>
/// <returns>Returns the node that has been parsed.</returns>
static internal YamlNode ParseNode(EventReader events, DocumentLoadingState state)
{
if (events.Accept<Scalar>())
{
return new YamlScalarNode(events, state);
}
if (events.Accept<SequenceStart>())
{
return new YamlSequenceNode(events, state);
}
if (events.Accept<MappingStart>())
{
return new YamlMappingNode(events, state);
}
if (events.Accept<AnchorAlias>())
{
AnchorAlias alias = events.Expect<AnchorAlias>();
return state.GetNode(alias.Value, false, alias.Start, alias.End) ?? new YamlAliasNode(alias.Value);
}
throw new ArgumentException("The current event is of an unsupported type.", "events");
}
/// <summary>
/// Resolves the aliases that could not be resolved when the node was created.
/// </summary>
/// <param name="state">The state of the document.</param>
internal abstract void ResolveAliases(DocumentLoadingState state);
/// <summary>
/// Saves the current node to the specified emitter.
/// </summary>
/// <param name="emitter">The emitter where the node is to be saved.</param>
/// <param name="state">The state.</param>
internal void Save(IEmitter emitter, EmitterState state)
{
if (!string.IsNullOrEmpty(Anchor) && !state.EmittedAnchors.Add(Anchor))
{
emitter.Emit(new AnchorAlias(Anchor));
}
else
{
Emit(emitter, state);
}
}
/// <summary>
/// Saves the current node to the specified emitter.
/// </summary>
/// <param name="emitter">The emitter where the node is to be saved.</param>
/// <param name="state">The state.</param>
internal abstract void Emit(IEmitter emitter, EmitterState state);
/// <summary>
/// Accepts the specified visitor by calling the appropriate Visit method on it.
/// </summary>
/// <param name="visitor">
/// A <see cref="IYamlVisitor"/>.
/// </param>
public abstract void Accept(IYamlVisitor visitor);
/// <summary>
/// Provides a basic implementation of Object.Equals
/// </summary>
protected bool Equals(YamlNode other)
{
// Do not use the anchor in the equality comparison because that would prevent anchored nodes from being found in dictionaries.
return SafeEquals(Tag, other.Tag);
}
/// <summary>
/// Gets a value indicating whether two objects are equal.
/// </summary>
protected static bool SafeEquals(object first, object second)
{
if (first != null)
{
return first.Equals(second);
}
else if (second != null)
{
return second.Equals(first);
}
else
{
return true;
}
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object"/>.
/// </returns>
public override int GetHashCode()
{
// Do not use the anchor in the hash code because that would prevent anchored nodes from being found in dictionaries.
return GetHashCode(Tag);
}
/// <summary>
/// Gets the hash code of the specified object, or zero if the object is null.
/// </summary>
protected static int GetHashCode(object value)
{
return value == null ? 0 : value.GetHashCode();
}
/// <summary>
/// Combines two hash codes into one.
/// </summary>
protected static int CombineHashCodes(int h1, int h2)
{
return unchecked(((h1 << 5) + h1) ^ h2);
}
/// <summary>
/// Gets all nodes from the document, starting on the current node.
/// </summary>
public abstract IEnumerable<YamlNode> AllNodes
{
get;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Threading.Tasks.Tests
{
public class YieldAwaitableTests
{
// awaiting Task.Yield
[Fact]
public static void RunAsyncYieldAwaiterTests()
{
// Test direct usage works even though it's not encouraged
{
for (int i = 0; i < 2; i++)
{
SynchronizationContext.SetSynchronizationContext(new ValidateCorrectContextSynchronizationContext());
var ya = i == 0 ? new YieldAwaitable.YieldAwaiter() : new YieldAwaitable().GetAwaiter();
var mres = new ManualResetEventSlim();
Assert.False(ya.IsCompleted, "RunAsyncYieldAwaiterTests > FAILURE. YieldAwaiter.IsCompleted should always be false.");
ya.OnCompleted(() =>
{
Assert.True(ValidateCorrectContextSynchronizationContext.IsPostedInContext, "RunAsyncYieldAwaiterTests > FAILURE. Expected to post in target context.");
mres.Set();
});
mres.Wait();
ya.GetResult();
SynchronizationContext.SetSynchronizationContext(null);
}
}
{
// Yield when there's a current sync context
SynchronizationContext.SetSynchronizationContext(new ValidateCorrectContextSynchronizationContext());
var ya = Task.Yield().GetAwaiter();
try { ya.GetResult(); }
catch
{
Assert.True(false, string.Format("RunAsyncYieldAwaiterTests > FAILURE. YieldAwaiter.GetResult threw inappropriately"));
}
var mres = new ManualResetEventSlim();
Assert.False(ya.IsCompleted, "RunAsyncYieldAwaiterTests > FAILURE. YieldAwaiter.IsCompleted should always be false.");
ya.OnCompleted(() =>
{
Assert.True(ValidateCorrectContextSynchronizationContext.IsPostedInContext, " > FAILURE. Expected to post in target context.");
mres.Set();
});
mres.Wait();
ya.GetResult();
SynchronizationContext.SetSynchronizationContext(null);
}
{
// Yield when there's a current TaskScheduler
Task.Factory.StartNew(() =>
{
try
{
var ya = Task.Yield().GetAwaiter();
try { ya.GetResult(); }
catch
{
Assert.True(false, string.Format(" > FAILURE. YieldAwaiter.GetResult threw inappropriately"));
}
var mres = new ManualResetEventSlim();
Assert.False(ya.IsCompleted, " > FAILURE. YieldAwaiter.IsCompleted should always be false.");
ya.OnCompleted(() =>
{
Assert.True(TaskScheduler.Current is QUWITaskScheduler, " > FAILURE. Expected to queue into target scheduler.");
mres.Set();
});
mres.Wait();
ya.GetResult();
}
catch { Assert.True(false, string.Format(" > FAILURE. Unexpected exception from Yield")); }
}, CancellationToken.None, TaskCreationOptions.None, new QUWITaskScheduler()).Wait();
}
{
// Yield when there's a current TaskScheduler and SynchronizationContext.Current is the base SynchronizationContext
Task.Factory.StartNew(() =>
{
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
try
{
var ya = Task.Yield().GetAwaiter();
try { ya.GetResult(); }
catch
{
Assert.True(false, string.Format(" > FAILURE. YieldAwaiter.GetResult threw inappropriately"));
}
var mres = new ManualResetEventSlim();
Assert.False(ya.IsCompleted, " > FAILURE. YieldAwaiter.IsCompleted should always be false.");
ya.OnCompleted(() =>
{
Assert.True(TaskScheduler.Current is QUWITaskScheduler, " > FAILURE. Expected to queue into target scheduler.");
mres.Set();
});
mres.Wait();
ya.GetResult();
}
catch { Assert.True(false, string.Format(" > FAILURE. Unexpected exception from Yield")); }
SynchronizationContext.SetSynchronizationContext(null);
}, CancellationToken.None, TaskCreationOptions.None, new QUWITaskScheduler()).Wait();
}
{
// OnCompleted grabs the current context, not Task.Yield nor GetAwaiter
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
var ya = Task.Yield().GetAwaiter();
SynchronizationContext.SetSynchronizationContext(new ValidateCorrectContextSynchronizationContext());
try { ya.GetResult(); }
catch
{
Assert.True(false, string.Format(" > FAILURE. YieldAwaiter.GetResult threw inappropriately"));
}
var mres = new ManualResetEventSlim();
Assert.False(ya.IsCompleted, " > FAILURE. YieldAwaiter.IsCompleted should always be false.");
ya.OnCompleted(() =>
{
Assert.True(ValidateCorrectContextSynchronizationContext.IsPostedInContext, " > FAILURE. Expected to post in target context.");
mres.Set();
});
mres.Wait();
ya.GetResult();
SynchronizationContext.SetSynchronizationContext(null);
}
}
// awaiting Task.Yield
[Fact]
public static void RunAsyncYieldAwaiterTests_Negative()
{
// Yield when there's a current sync context
SynchronizationContext.SetSynchronizationContext(new ValidateCorrectContextSynchronizationContext());
var ya = Task.Yield().GetAwaiter();
Assert.Throws<ArgumentNullException>(() => { ya.OnCompleted(null); });
}
#region Helper Methods / Classes
private class ValidateCorrectContextSynchronizationContext : SynchronizationContext
{
[ThreadStatic]
internal static bool IsPostedInContext;
internal int PostCount;
internal int SendCount;
public override void Post(SendOrPostCallback d, object state)
{
Interlocked.Increment(ref PostCount);
Task.Run(() =>
{
IsPostedInContext = true;
d(state);
IsPostedInContext = false;
});
}
public override void Send(SendOrPostCallback d, object state)
{
Interlocked.Increment(ref SendCount);
d(state);
}
}
/// <summary>A scheduler that queues to the TP and tracks the number of times QueueTask and TryExecuteTaskInline are invoked.</summary>
private class QUWITaskScheduler : TaskScheduler
{
private int _queueTaskCount;
private int _tryExecuteTaskInlineCount;
public int QueueTaskCount { get { return _queueTaskCount; } }
public int TryExecuteTaskInlineCount { get { return _tryExecuteTaskInlineCount; } }
protected override IEnumerable<Task> GetScheduledTasks() { return null; }
protected override void QueueTask(Task task)
{
Interlocked.Increment(ref _queueTaskCount);
Task.Run(() => TryExecuteTask(task));
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
Interlocked.Increment(ref _tryExecuteTaskInlineCount);
return TryExecuteTask(task);
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Compute
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Rest.Azure.OData;
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>
/// VirtualMachineExtensionImagesOperations operations.
/// </summary>
internal partial class VirtualMachineExtensionImagesOperations : IServiceOperations<ComputeManagementClient>, IVirtualMachineExtensionImagesOperations
{
/// <summary>
/// Initializes a new instance of the VirtualMachineExtensionImagesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal VirtualMachineExtensionImagesOperations(ComputeManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the ComputeManagementClient
/// </summary>
public ComputeManagementClient Client { get; private set; }
/// <summary>
/// Gets a virtual machine extension image.
/// </summary>
/// <param name='location'>
/// </param>
/// <param name='publisherName'>
/// </param>
/// <param name='type'>
/// </param>
/// <param name='version'>
/// </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<VirtualMachineExtensionImage>> GetWithHttpMessagesAsync(string location, string publisherName, string type, string version, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (location == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "location");
}
if (publisherName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "publisherName");
}
if (type == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "type");
}
if (version == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "version");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-04-30-preview";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("location", location);
tracingParameters.Add("publisherName", publisherName);
tracingParameters.Add("type", type);
tracingParameters.Add("version", version);
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}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmextension/types/{type}/versions/{version}").ToString();
_url = _url.Replace("{location}", System.Uri.EscapeDataString(location));
_url = _url.Replace("{publisherName}", System.Uri.EscapeDataString(publisherName));
_url = _url.Replace("{type}", System.Uri.EscapeDataString(type));
_url = _url.Replace("{version}", System.Uri.EscapeDataString(version));
_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 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 (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 (Newtonsoft.Json.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<VirtualMachineExtensionImage>();
_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<VirtualMachineExtensionImage>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.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 a list of virtual machine extension image types.
/// </summary>
/// <param name='location'>
/// </param>
/// <param name='publisherName'>
/// </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<IList<VirtualMachineExtensionImage>>> ListTypesWithHttpMessagesAsync(string location, string publisherName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (location == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "location");
}
if (publisherName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "publisherName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-04-30-preview";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("location", location);
tracingParameters.Add("publisherName", publisherName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListTypes", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmextension/types").ToString();
_url = _url.Replace("{location}", System.Uri.EscapeDataString(location));
_url = _url.Replace("{publisherName}", System.Uri.EscapeDataString(publisherName));
_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 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 (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 (Newtonsoft.Json.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<IList<VirtualMachineExtensionImage>>();
_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<IList<VirtualMachineExtensionImage>>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.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 a list of virtual machine extension image versions.
/// </summary>
/// <param name='location'>
/// </param>
/// <param name='publisherName'>
/// </param>
/// <param name='type'>
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the 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<IList<VirtualMachineExtensionImage>>> ListVersionsWithHttpMessagesAsync(string location, string publisherName, string type, ODataQuery<VirtualMachineExtensionImage> odataQuery = default(ODataQuery<VirtualMachineExtensionImage>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (location == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "location");
}
if (publisherName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "publisherName");
}
if (type == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "type");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-04-30-preview";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("odataQuery", odataQuery);
tracingParameters.Add("location", location);
tracingParameters.Add("publisherName", publisherName);
tracingParameters.Add("type", type);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListVersions", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmextension/types/{type}/versions").ToString();
_url = _url.Replace("{location}", System.Uri.EscapeDataString(location));
_url = _url.Replace("{publisherName}", System.Uri.EscapeDataString(publisherName));
_url = _url.Replace("{type}", System.Uri.EscapeDataString(type));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
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 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 (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 (Newtonsoft.Json.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<IList<VirtualMachineExtensionImage>>();
_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<IList<VirtualMachineExtensionImage>>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.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;
}
}
}
| |
using UnityEngine;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using DG.Tweening;
using Jammer.Events;
using Jammer.Scenes;
using Jammer.UI;
namespace Jammer {
/// <summary>
/// Contains basic App/Game logic that belongs in all games.
/// </summary>
public class GameManager : Singleton<GameManager> {
/// <summary>
/// Static constructor. Not inherited and only executed once for generics.
/// initialize here even before the Initialize() method
/// </summary>
static GameManager() {
// default static settings
Log.LogLevels = LogLevels.Info | LogLevels.Warning | LogLevels.Error;
}
/// <summary>
/// Application wide settings. These are serialized to application.txt in JSON format.
/// </summary>
public ApplicationSettings ApplicationSettings { get; set; }
/// <summary>
/// Focused when application is focused
/// </summary>
public bool Focused { get; set; }
/// <summary>
/// Game finite state machine
/// </summary>
public GameState State { get { return GetState(); } set { SetState(value); }}
private GameState state = GameState.New;
/// <summary>
/// Log granularity
/// </summary>
public LogLevels LogLevels { get { return GetLogLevels(); } set { SetLogLevels(value); }}
private LogLevels logLevels = Log.LogLevels;
/// <summary>
/// Initialize happens on Awake for new Singletons
/// </summary>
protected override void Initialize() {
Log.Verbose(string.Format("GameManager.Initialize() ID={0}", GetInstanceID()));
base.Initialize();
// signal loading state
State = GameState.Loading;
// App starts focused
Focused = true;
// create settings at their defaults
ApplicationSettings = new ApplicationSettings();
//
// DOTween
//
// initialize with the preferences set in DOTween's Utility Panel
DOTween.Init();
//
// Newtonsoft.Json default serialization settings
//
// http://www.newtonsoft.com/json/help/html/SerializationSettings.htm
JsonConvert.DefaultSettings = (() => new JsonSerializerSettings {
// add '$type' only if needed.
// NOTE: Can't use Binder in NET35 || NET20
TypeNameHandling = TypeNameHandling.Auto,
// don't write properties at default values, use
// [System.ComponentModel.DefaultValue(x)] to mark defaults that cannot
// be directly determined naturally, i.e. int defaults to 0.
DefaultValueHandling = DefaultValueHandling.Ignore,
Converters = { new StringEnumConverter { CamelCaseText = false }},
// The default is to write all keys in camelCase. This can be overridden at
// the field/property level using attributes
ContractResolver = new CamelCasePropertyNamesContractResolver(),
// pretty print
Formatting = Formatting.Indented,
});
// read command line options
if (ApplicationHelper.IsDesktop()) {
string[] args = System.Environment.GetCommandLineArgs();
string commandLine = string.Join(" ", args);
foreach (string arg in args) {
// store all settings the given folder
if (Regex.IsMatch(arg, @"--settings-folder")) {
// This handles quoted paths with spaces but leaves the quotes in place
Regex regex = new Regex(@"--settings-folder\s+(?<path>[\""].+?[\""]|[^ ]+)");
Match match = regex.Match(commandLine);
if (match.Success) {
string path = match.Groups["path"].Value;
if (!Path.IsPathRooted(path)) {
// convert to absolute path
path = Path.Combine(Directory.GetCurrentDirectory(), path);
}
if (Directory.Exists(path)) {
Log.Debug(string.Format("GameManager.Initialize() Settings.DataPath: {0}", path));
Settings.DataPath = path;
}
else {
Log.Error(string.Format("GameManager.Initialize() requested settings folder {0} does not exist", path));
}
}
}
}
}
// load the data, defaults to empty string
string json = Settings.GetString(SettingsKey.Application);
if (json != "") {
DeserializeSettings(json);
}
#if JAMER_LOG_DEBUG
LogLevels |= LogLevels.Debug;
#endif
#if JAMMER_LOG_VERBOSE
LogLevels |= LogLevels.Verbose;
#endif
#if JAMMER_CONSOLE
// log debug console from resources
CreatePrefab(name: "Console");
#endif
}
protected void OnEnable() {
Log.Verbose(string.Format("GameManager.OnEnable() this={0}", this));
if (MenuManager.Instance == null) {
UnityEngine.SceneManagement.SceneManager.LoadScene(sceneName: ApplicationConstants.UIScene, mode: UnityEngine.SceneManagement.LoadSceneMode.Additive);
}
SubscribeEvents();
// signal game started
State = GameState.Started;
}
protected virtual void OnDisable(){
Log.Verbose(string.Format("GameManager.OnDisable()"));
UnsubscribeEvents();
}
protected virtual void SubscribeEvents() {
Log.Verbose(string.Format("GameManager.SubscribeEvents()"));
Events.AddListener<LoadSceneCommandEvent>(OnLoadSceneCommand);
}
protected virtual void UnsubscribeEvents() {
Log.Verbose(string.Format("GameManager.UnsubscribeEvents()"));
Events.RemoveListener<LoadSceneCommandEvent>(OnLoadSceneCommand);
}
/// <summary>
/// Request/Announce scene loading
/// </summary>
void OnLoadSceneCommand(LoadSceneCommandEvent e) {
if (e.Handled) {
Log.Debug(string.Format("GameManager.OnLoadSceneCommand({0})", e));
if (e.SceneName == ApplicationConstants.MainScene) {
State = GameState.Ready;
}
}
}
// Event order:
//
// App initially starts:
// OnApplicationFocus(true) is called
// App is soft closed:
// OnApplicationFocus(false) is called
// OnApplicationPause(true) is called
// App is brought forward after soft closing:
// OnApplicationPause(false) is called
// OnApplicationFocus(true) is called
protected void OnApplicationPause(bool pauseStatus) {
Log.Verbose(string.Format("GameManager.OnApplicationPause(pauseStatus: {0})", pauseStatus));
}
protected void OnApplicationFocus(bool focusStatus) {
//Log.Verbose(string.Format("GameManager.OnApplicationFocus(focusStatus: {0})", focusStatus));
Focused = focusStatus;
if (UnityEngine.EventSystems.EventSystem.current != null) {
// toggle navigation events
UnityEngine.EventSystems.EventSystem.current.sendNavigationEvents = Focused;
}
}
public void SaveSettings() {
Log.Debug(string.Format("GameManager.SaveSettings()"));
string json = SerializeSettings();
Settings.SetString(SettingsKey.Application, json);
Settings.Save();
}
/// <summary>
/// Serialize to a dictionary of strings. Return a JSON string.
/// </summary>
public string SerializeSettings(bool prettyPrint = true) {
Log.Debug(string.Format("GameManager.SerializeSettings()"));
Formatting formatting = Formatting.None;
if (prettyPrint) {
formatting = Formatting.Indented;
}
return JsonConvert.SerializeObject(value: ApplicationSettings, formatting: formatting);
}
/// <summary>
/// Deserialize the application settings from a JSON string as a dictionary
/// of strings.
/// </summary>
public bool DeserializeSettings(string json) {
Log.Debug(string.Format("GameManager.DeserializeSettings({0}) this={1}", json, this));
bool result = false;
try {
if (string.IsNullOrEmpty(json)) {
throw new System.InvalidOperationException("json string is empty or null");
}
ApplicationSettings = JsonConvert.DeserializeObject<ApplicationSettings>(json);
result = true;
}
catch (System.Exception e) {
Log.Error(string.Format("GameManager.DeserializeSettings() failed with {0}", e.ToString()));
}
return result;
}
/// <summary>
/// Create a prefab by name, loading from Resources. Returns null if the prefab can't be loaded.
/// </summary>
public GameObject CreatePrefab(string name, GameObject parent = null, string folder = null) {
string path;
GameObject prefab;
// must use POSIX style slashes
if (string.IsNullOrEmpty(folder)) {
path = name;
}
else {
path = folder + "/" + name;
}
Log.Debug(string.Format("Product.Load() loading asset {0}", path));
// this is the "live" prefab, not an instance clone that lives in the scene
prefab = (GameObject) Resources.Load(path);
if (prefab != null) {
// an instance clone that lives in the scene
prefab = (GameObject) UnityEngine.Object.Instantiate(prefab);
// remove the "(clone)" from the name
prefab.name = name;
// assign parent if not given so the the instance will be cleaned up with the scene
if (parent == null) {
// this gameObject
parent = gameObject;
}
prefab.transform.SetParent(parent.transform, worldPositionStays: true);
}
return prefab;
}
private LogLevels GetLogLevels() {
return logLevels;
}
private void SetLogLevels(LogLevels value) {
logLevels = value;
Log.LogLevels = logLevels;
}
private GameState GetState() {
return state;
}
private void SetState(GameState value) {
Log.Verbose(string.Format("GameManager.SetState(value: {0})", value));
state = value;
switch(state) {
// TODO: add handler for user initiated new game
case GameState.New:
break;
// TODO: add handler
case GameState.Ready:
break;
}
// publish state change event
Events.Raise(new GameStateEvent(){ Game=this, State=state });
}
private void Update() {
if (!Focused) return;
// game manager only handles input if the menus are closed
if (MenuManager.Instance.State == MenuState.Closed) {
HandleInput();
}
}
/// <summary>
/// Global input handler
/// </summary>
private void HandleInput() {
if (Input.GetKeyDown(KeyCode.Escape)) {
Log.Verbose(string.Format("GameManager.HandleInput() KeyCode.Escape, opening main menu"));
Events.Raise(new MenuCommandEvent(){ Handled=false, MenuId=MenuId.Main, State=MenuState.Open });
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
public class MyDispose : IDisposable
{
public int DisposeCounter = 0;
private bool disposed = false;
public void Dispose()
{
disposed = true;
DisposeCounter++;
}
public bool IsDisposed
{
get
{
return disposed;
}
set
{
disposed = value;
}
}
}
public class Test
{
// OUT:
// TRUE if the object was DISPOSED
// FALSE if the object was NOT DISPOSED
public bool BrokenSwitch(int msg, MyDispose m)
{
bool result = true;
switch (msg)
{
case 0:
using (m)
{
if (m.IsDisposed)
{
break;
}
result = false;
}
break;
default:
break;
}
return result;
}
// OUT:
// TRUE if the object was DISPOSED
// FALSE if the object was NOT DISPOSED
public bool WorkingSwitch(int msg, MyDispose m)
{
bool result = true;
switch (msg)
{
case 0:
using (m)
{
if (!m.IsDisposed)
{
result = false;
}
}
break;
default:
break;
}
return result;
}
// OUT:
// TRUE if the object was DISPOSED
// FALSE if the object was NOT DISPOSED
public bool ReturnFromUsing(MyDispose m)
{
using (m)
{
if (!m.IsDisposed)
{
return false;
}
}
return true;
}
// OUT:
// TRUE if the object was DISPOSED
// FALSE if the object was NOT DISPOSED
public bool GotoFromUsing(MyDispose m)
{
using (m)
{
if (!m.IsDisposed)
{
goto EXIT;
}
}
return true;
EXIT:
return false;
}
public int SwitchTests()
{
MyDispose m = new MyDispose();
bool wasDisposed;
// Called with object not disposed
m.DisposeCounter = 0;
m.IsDisposed = false;
wasDisposed = BrokenSwitch(0, m);
if (1 != m.DisposeCounter)
{
Console.WriteLine("SwitchTests1: MyDispose.Dispose() called too many times 1 != {0}", m.DisposeCounter);
return -1;
}
m.DisposeCounter = 0;
m.IsDisposed = false;
wasDisposed = WorkingSwitch(0, m) || wasDisposed;
if (1 != m.DisposeCounter)
{
Console.WriteLine("SwitchTests2: MyDispose.Dispose() called too many times 12 != {0}", m.DisposeCounter);
return -1;
}
if (wasDisposed)
{
// the object should not have been disposed entering
// these method calls
// if the object was disposed then there was an issue
Console.WriteLine("SwitchTests1: Object was Disposed upon entering the method call (in error)");
return -2;
}
// called with object disposed
m.DisposeCounter = 0;
m.IsDisposed = true;
wasDisposed = BrokenSwitch(0, m);
if (1 != m.DisposeCounter)
{
Console.WriteLine("SwitchTests3: MyDispose.Dispose() called too many times 1 != {0}", m.DisposeCounter);
return -1;
}
m.DisposeCounter = 0;
m.IsDisposed = true;
wasDisposed = WorkingSwitch(0, m) && wasDisposed;
if (1 != m.DisposeCounter)
{
Console.WriteLine("SwitchTests4: MyDispose.Dispose() called too many times 1 != {0}", m.DisposeCounter);
return -1;
}
if (!wasDisposed)
{
// the object should have been disposed entering
// these method calls
// if the object was not disposed then there was an issue
Console.WriteLine("SwitchTests2: Object was not Disposed upon entering the method call (in error)");
return -2;
}
return 0;
}
public int ReturnTests()
{
MyDispose m = new MyDispose();
bool wasDisposed;
// Called with object not disposed
m.DisposeCounter = 0;
m.IsDisposed = false;
wasDisposed = ReturnFromUsing(m);
if (1 != m.DisposeCounter)
{
Console.WriteLine("ReturnTests1: MyDispose.Dispose() called too many times 1 != {0}", m.DisposeCounter);
return -1;
}
if (wasDisposed)
{
// the object should not have been disposed entering
// this method call
// if the object was disposed then there was an issue
Console.WriteLine("ReturnTests1: Object was Disposed upon entering the method call (in error)");
return -2;
}
// called with object disposed
m.DisposeCounter = 0;
m.IsDisposed = true;
wasDisposed = ReturnFromUsing(m);
if (1 != m.DisposeCounter)
{
Console.WriteLine("ReturnTests2: MyDispose.Dispose() called too many times 1 != {0}", m.DisposeCounter);
return -1;
}
if (!wasDisposed)
{
// the object should have been disposed entering
// this method call
// if the object was not disposed then there was an issue
Console.WriteLine("ReturnTests2: Object was not Disposed upon entering the method call (in error)");
return -2;
}
return 0;
}
public int GotoTests()
{
MyDispose m = new MyDispose();
bool wasDisposed;
// Called with object not disposed
m.DisposeCounter = 0;
m.IsDisposed = false;
wasDisposed = GotoFromUsing(m);
if (1 != m.DisposeCounter)
{
Console.WriteLine("GotoTests1: MyDispose.Dispose() called too many times 1 != {0}", m.DisposeCounter);
return -1;
}
if (wasDisposed)
{
// the object should not have been disposed entering
// this method call
// if the object was disposed then there was an issue
Console.WriteLine("GotoTests1: Object was Disposed upon entering the method call (in error)");
return -2;
}
// called with object disposed
m.DisposeCounter = 0;
m.IsDisposed = true;
wasDisposed = GotoFromUsing(m);
if (1 != m.DisposeCounter)
{
Console.WriteLine("GotoTests2: MyDispose.Dispose() called too many times 1 != {0}", m.DisposeCounter);
return -1;
}
if (!wasDisposed)
{
// the object should have been disposed entering
// this method call
// if the object was not disposed then there was an issue
Console.WriteLine("GotoTests2: Object was not Disposed upon entering the method call (in error)");
return -2;
}
return 0;
}
public static int Main()
{
Test t = new Test();
int retVal = 0;
// using in switch statements
retVal += t.SwitchTests();
// return from using
retVal += t.ReturnTests();
// goto out of a using
retVal += t.GotoTests();
if (0 == retVal)
{
Console.WriteLine("PASS");
return 100;
}
else
{
Console.WriteLine("FAIL");
return 0;
}
}
}
| |
using System;
using System.IO;
public abstract class ProfileReader {
public Profile Profile;
BinaryReader br;
int end_t = int.MaxValue;
long startpos;
public ProfileReader (Profile p)
{
Profile = p;
}
public ProfileReader (Profile p, int start_t, int end_t)
{
int ev = p.Metadata.GetTimelineBefore (EventType.Checkpoint, start_t);
if (ev != -1)
startpos = p.Metadata.GetTimeline (ev).FilePos;
else
startpos = 0;
this.end_t = end_t;
Profile = p;
}
int context_size;
int type_size;
public void Read ()
{
using (br = new BinaryReader (File.OpenRead (Profile.Filename))) {
ProfilerSignature.ReadHeader (br, true);
if (startpos != 0)
br.BaseStream.Seek (startpos, SeekOrigin.Begin);
while (true) {
int time = br.ReadInt32 ();
// eof
if (time == -1)
return;
bool is_alloc = (time & (int)(1 << 31)) == 0;
time &= int.MaxValue;
// we are done
if (time > end_t)
return;
if (is_alloc) {
// allocation
int ctx = br.ReadInt32 ();
AllocationSeen (time, GetContext (ctx), br.BaseStream.Position);
} else {
EventType event_type = (EventType) br.ReadInt32 ();
int event_num = br.ReadInt32 ();
switch (event_type) {
case EventType.GC:
GcSeen (time, event_num);
break;
case EventType.HeapResize:
GcHeapResize (time, event_num, br.ReadInt32 ());
break;
case EventType.Checkpoint:
context_size = br.ReadInt32 ();
type_size = br.ReadInt32 ();
Checkpoint (time, event_num);
break;
}
}
}
}
}
protected void ReadGcFreed ()
{
while (true) {
long pos = br.ReadInt64 ();
int alloc_time = br.ReadInt32 ();
int alloc_ctx = br.ReadInt32 ();
if (pos == 0 && alloc_time == 0 && alloc_ctx == 0)
return;
GcFreedSeen (alloc_time, GetContext (alloc_ctx), pos);
}
}
protected abstract void AllocationSeen (int time, Context ctx, long pos);
protected abstract void GcSeen (int time, int event_num);
protected abstract void GcFreedSeen (int time, Context ctx, long pos);
protected virtual void GcHeapResize (int time, int event_num, int new_size)
{
}
protected void ReadCheckpoint (out int [] type_data, out int [] ctx_insts)
{
ctx_insts = new int [ContextTableSize];
type_data = new int [TypeTableSize];
for (int i = 0; i < context_size; i ++)
ctx_insts [i] = br.ReadInt32 ();
for (int i = 0; i < type_size; i ++)
type_data [i] = br.ReadInt32 ();
}
protected virtual void Checkpoint (int time, int event_num)
{
int cb = (context_size + type_size) * 4;
br.BaseStream.Seek (cb, SeekOrigin.Current);
}
public string GetTypeName (int idx)
{
return Profile.GetTypeName (idx);
}
public string GetMethodName (int idx)
{
return Profile.GetMethodName (idx);
}
public int [] GetBacktrace (int idx)
{
return Profile.GetBacktrace (idx);
}
public Context GetContext (int idx)
{
return Profile.GetContext (idx);
}
public int TypeTableSize {
get { return Profile.TypeTableSize; }
}
public int ContextTableSize {
get { return Profile.ContextTableSize; }
}
public Timeline [] Timeline {
get { return Profile.Timeline; }
}
}
public class Metadata {
const int BacktraceSize = 5;
string [] typeTable;
string [] methodTable;
int [][] backtraceTable;
Context [] contextTable;
Timeline [] timeline;
long [] type_max;
public int TypeTableSize { get { return typeTable.Length; } }
public int ContextTableSize { get { return contextTable.Length; } }
public Timeline [] Timeline { get { return timeline; } }
public long [] TypeMax { get { return type_max; } }
public string GetTypeName (int idx)
{
return typeTable [idx];
}
public string GetMethodName (int idx)
{
return methodTable [idx];
}
public int [] GetBacktrace (int idx)
{
return backtraceTable [idx];
}
public Context GetContext (int idx)
{
return contextTable [idx];
}
public int GetTimelineBefore (EventType e, int time)
{
int last = -1;
for (int i = 0; i < timeline.Length; i ++) {
if (timeline [i].Time >= time)
break;
if (timeline [i].Event == e)
last = i;
}
return last;
}
public Timeline GetTimeline (int idx)
{
return timeline [idx];
}
public Metadata (Profile p)
{
using (BinaryReader br = new BinaryReader (File.OpenRead (p.Filename))) {
br.BaseStream.Seek (-8, SeekOrigin.End);
br.BaseStream.Seek (br.ReadInt64 (), SeekOrigin.Begin);
ProfilerSignature.ReadHeader (br, false);
typeTable = ReadStringTable (br);
methodTable = ReadStringTable (br);
backtraceTable = ReadBacktraceTable (br);
contextTable = ReadContextTable (br);
timeline = ReadTimeline (br);
type_max = ReadTypeMaxTable (br);
}
}
public void Dump ()
{
foreach (Context c in contextTable) {
Console.WriteLine ("size {0}, type {1}", c.Size, typeTable [c.Type]);
foreach (int i in backtraceTable [c.Backtrace])
Console.WriteLine (" {0} {1}", i, methodTable [i]);
Console.WriteLine ();
}
}
long [] ReadTypeMaxTable (BinaryReader br)
{
int sz = br.ReadInt32 ();
long [] ret = new long [sz];
for (int i = 0; i < sz; i ++)
ret [i] = br.ReadInt64 ();
return ret;
}
string [] ReadStringTable (BinaryReader br)
{
int sz = br.ReadInt32 ();
string [] ret = new string [sz];
for (int i = 0; i < sz; i ++)
ret [i] = br.ReadString ();
return ret;
}
int [] [] ReadBacktraceTable (BinaryReader br)
{
int sz = br.ReadInt32 ();
int [][] t = new int [sz] [];
for (int i = 0; i < sz; i ++) {
int szz = br.ReadInt32 ();
t [i] = new int [szz];
for (int j = 0; j < BacktraceSize; j ++) {
int n = br.ReadInt32 ();
if (j < szz)
t [i] [j] = n;
}
}
return t;
}
Context [] ReadContextTable (BinaryReader br)
{
int sz = br.ReadInt32 ();
Context [] d = new Context [sz];
for (int i = 0; i < sz; i ++) {
d [i].Id = i;
d [i].Type = br.ReadInt32 ();
d [i].Size = br.ReadInt32 ();
d [i].Backtrace = br.ReadInt32 ();
}
return d;
}
Timeline [] ReadTimeline (BinaryReader br)
{
int sz = br.ReadInt32 ();
Timeline [] d = new Timeline [sz];
for (int i = 0; i < sz; i ++) {
d [i].Id = i;
d [i].Time = br.ReadInt32 ();
d [i].Event = (EventType) br.ReadInt32 ();
d [i].SizeHigh = br.ReadInt32 ();
d [i].SizeLow = br.ReadInt32 ();
d [i].FilePos = br.ReadInt64 ();
}
return d;
}
}
class ProfilerSignature {
static readonly byte [] DumpSignature = {
0x68, 0x30, 0xa4, 0x57, 0x18, 0xec, 0xd6, 0xa1,
0x61, 0x9c, 0x1d, 0x43, 0xe1, 0x47, 0x27, 0xb6
};
static readonly byte [] MetaSignature = {
0xe4, 0x37, 0x29, 0x60, 0x3e, 0x31, 0x89, 0x12,
0xaa, 0x93, 0xc8, 0x76, 0xf4, 0x6a, 0x95, 0x11
};
const int Version = 6;
public static void ReadHeader (BinaryReader br, bool is_dump)
{
byte [] s = is_dump ? DumpSignature : MetaSignature;
byte [] sig = br.ReadBytes (s.Length);
for (int i = 0; i < s.Length; i ++) {
if (sig [i] != s [i])
throw new Exception ("Invalid file format");
}
int ver = br.ReadInt32 ();
if (ver != Version)
throw new Exception (String.Format ("Wrong version: expected {0}, got {1}", Version, ver));
}
}
public enum EventType {
GC = 0,
HeapResize = 1,
Checkpoint = 2
}
public struct Timeline {
public int Id;
public int Time;
public EventType Event;
public int SizeHigh, SizeLow;
public long FilePos;
}
public struct Context {
public int Id;
public int Type;
public int Size;
public int Backtrace;
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace AzureCloudAppWeb
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
//
// 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;
using Microsoft.Azure.Management.Automation;
using Microsoft.Azure.Management.Automation.Models;
namespace Microsoft.Azure.Management.Automation
{
public static partial class HybridRunbookWorkerGroupOperationsExtensions
{
/// <summary>
/// Delete a hybrid runbook worker group. (see
/// http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IHybridRunbookWorkerGroupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. Automation account name.
/// </param>
/// <param name='hybridRunbookWorkerGroupName'>
/// Required. The hybrid runbook worker group name
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this IHybridRunbookWorkerGroupOperations operations, string resourceGroupName, string automationAccount, string hybridRunbookWorkerGroupName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IHybridRunbookWorkerGroupOperations)s).DeleteAsync(resourceGroupName, automationAccount, hybridRunbookWorkerGroupName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete a hybrid runbook worker group. (see
/// http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IHybridRunbookWorkerGroupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. Automation account name.
/// </param>
/// <param name='hybridRunbookWorkerGroupName'>
/// Required. The hybrid runbook worker group name
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this IHybridRunbookWorkerGroupOperations operations, string resourceGroupName, string automationAccount, string hybridRunbookWorkerGroupName)
{
return operations.DeleteAsync(resourceGroupName, automationAccount, hybridRunbookWorkerGroupName, CancellationToken.None);
}
/// <summary>
/// Retrieve a hybrid runbook worker group. (see
/// http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IHybridRunbookWorkerGroupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='hybridRunbookWorkerGroupName'>
/// Required. The hybrid runbook worker group name
/// </param>
/// <returns>
/// The response model for the get hybrid runbook worker group
/// operation.
/// </returns>
public static HybridRunbookWorkerGroupGetResponse Get(this IHybridRunbookWorkerGroupOperations operations, string resourceGroupName, string automationAccount, string hybridRunbookWorkerGroupName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IHybridRunbookWorkerGroupOperations)s).GetAsync(resourceGroupName, automationAccount, hybridRunbookWorkerGroupName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve a hybrid runbook worker group. (see
/// http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IHybridRunbookWorkerGroupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='hybridRunbookWorkerGroupName'>
/// Required. The hybrid runbook worker group name
/// </param>
/// <returns>
/// The response model for the get hybrid runbook worker group
/// operation.
/// </returns>
public static Task<HybridRunbookWorkerGroupGetResponse> GetAsync(this IHybridRunbookWorkerGroupOperations operations, string resourceGroupName, string automationAccount, string hybridRunbookWorkerGroupName)
{
return operations.GetAsync(resourceGroupName, automationAccount, hybridRunbookWorkerGroupName, CancellationToken.None);
}
/// <summary>
/// Retrieve a list of hybrid runbook worker groups. (see
/// http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IHybridRunbookWorkerGroupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Optional. The parameters supplied to the list job stream's stream
/// items operation.
/// </param>
/// <returns>
/// The response model for the list hybrid runbook worker groups.
/// </returns>
public static HybridRunbookWorkerGroupsListResponse List(this IHybridRunbookWorkerGroupOperations operations, string resourceGroupName, string automationAccount, HybridRunbookWorkerGroupListParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IHybridRunbookWorkerGroupOperations)s).ListAsync(resourceGroupName, automationAccount, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve a list of hybrid runbook worker groups. (see
/// http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IHybridRunbookWorkerGroupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Optional. The parameters supplied to the list job stream's stream
/// items operation.
/// </param>
/// <returns>
/// The response model for the list hybrid runbook worker groups.
/// </returns>
public static Task<HybridRunbookWorkerGroupsListResponse> ListAsync(this IHybridRunbookWorkerGroupOperations operations, string resourceGroupName, string automationAccount, HybridRunbookWorkerGroupListParameters parameters)
{
return operations.ListAsync(resourceGroupName, automationAccount, parameters, CancellationToken.None);
}
/// <summary>
/// Retrieve next list of hybrid runbook worker groups. (see
/// http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IHybridRunbookWorkerGroupOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The link to retrieve next set of items.
/// </param>
/// <returns>
/// The response model for the list hybrid runbook worker groups.
/// </returns>
public static HybridRunbookWorkerGroupsListResponse ListNext(this IHybridRunbookWorkerGroupOperations operations, string nextLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IHybridRunbookWorkerGroupOperations)s).ListNextAsync(nextLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve next list of hybrid runbook worker groups. (see
/// http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IHybridRunbookWorkerGroupOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The link to retrieve next set of items.
/// </param>
/// <returns>
/// The response model for the list hybrid runbook worker groups.
/// </returns>
public static Task<HybridRunbookWorkerGroupsListResponse> ListNextAsync(this IHybridRunbookWorkerGroupOperations operations, string nextLink)
{
return operations.ListNextAsync(nextLink, CancellationToken.None);
}
/// <summary>
/// Update a hybrid runbook worker group. (see
/// http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IHybridRunbookWorkerGroupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='hybridRunbookWorkerGroupName'>
/// Required. The hybrid runbook worker group name
/// </param>
/// <param name='parameters'>
/// Required. The hybrid runbook worker group
/// </param>
/// <returns>
/// The response model for the patch hybrid runbook worker group
/// operation.
/// </returns>
public static HybridRunbookWorkerGroupPatchResponse Patch(this IHybridRunbookWorkerGroupOperations operations, string resourceGroupName, string automationAccount, string hybridRunbookWorkerGroupName, HybridRunbookWorkerGroupPatchParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IHybridRunbookWorkerGroupOperations)s).PatchAsync(resourceGroupName, automationAccount, hybridRunbookWorkerGroupName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Update a hybrid runbook worker group. (see
/// http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IHybridRunbookWorkerGroupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='hybridRunbookWorkerGroupName'>
/// Required. The hybrid runbook worker group name
/// </param>
/// <param name='parameters'>
/// Required. The hybrid runbook worker group
/// </param>
/// <returns>
/// The response model for the patch hybrid runbook worker group
/// operation.
/// </returns>
public static Task<HybridRunbookWorkerGroupPatchResponse> PatchAsync(this IHybridRunbookWorkerGroupOperations operations, string resourceGroupName, string automationAccount, string hybridRunbookWorkerGroupName, HybridRunbookWorkerGroupPatchParameters parameters)
{
return operations.PatchAsync(resourceGroupName, automationAccount, hybridRunbookWorkerGroupName, parameters, CancellationToken.None);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.VpcAccess.V1.Snippets
{
using Google.Api.Gax;
using Google.Api.Gax.ResourceNames;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedVpcAccessServiceClientSnippets
{
/// <summary>Snippet for CreateConnector</summary>
public void CreateConnectorRequestObject()
{
// Snippet: CreateConnector(CreateConnectorRequest, CallSettings)
// Create client
VpcAccessServiceClient vpcAccessServiceClient = VpcAccessServiceClient.Create();
// Initialize request argument(s)
CreateConnectorRequest request = new CreateConnectorRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
ConnectorId = "",
Connector = new Connector(),
};
// Make the request
Operation<Connector, OperationMetadata> response = vpcAccessServiceClient.CreateConnector(request);
// Poll until the returned long-running operation is complete
Operation<Connector, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Connector result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Connector, OperationMetadata> retrievedResponse = vpcAccessServiceClient.PollOnceCreateConnector(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Connector retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateConnectorAsync</summary>
public async Task CreateConnectorRequestObjectAsync()
{
// Snippet: CreateConnectorAsync(CreateConnectorRequest, CallSettings)
// Additional: CreateConnectorAsync(CreateConnectorRequest, CancellationToken)
// Create client
VpcAccessServiceClient vpcAccessServiceClient = await VpcAccessServiceClient.CreateAsync();
// Initialize request argument(s)
CreateConnectorRequest request = new CreateConnectorRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
ConnectorId = "",
Connector = new Connector(),
};
// Make the request
Operation<Connector, OperationMetadata> response = await vpcAccessServiceClient.CreateConnectorAsync(request);
// Poll until the returned long-running operation is complete
Operation<Connector, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Connector result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Connector, OperationMetadata> retrievedResponse = await vpcAccessServiceClient.PollOnceCreateConnectorAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Connector retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateConnector</summary>
public void CreateConnector()
{
// Snippet: CreateConnector(string, string, Connector, CallSettings)
// Create client
VpcAccessServiceClient vpcAccessServiceClient = VpcAccessServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
string connectorId = "";
Connector connector = new Connector();
// Make the request
Operation<Connector, OperationMetadata> response = vpcAccessServiceClient.CreateConnector(parent, connectorId, connector);
// Poll until the returned long-running operation is complete
Operation<Connector, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Connector result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Connector, OperationMetadata> retrievedResponse = vpcAccessServiceClient.PollOnceCreateConnector(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Connector retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateConnectorAsync</summary>
public async Task CreateConnectorAsync()
{
// Snippet: CreateConnectorAsync(string, string, Connector, CallSettings)
// Additional: CreateConnectorAsync(string, string, Connector, CancellationToken)
// Create client
VpcAccessServiceClient vpcAccessServiceClient = await VpcAccessServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
string connectorId = "";
Connector connector = new Connector();
// Make the request
Operation<Connector, OperationMetadata> response = await vpcAccessServiceClient.CreateConnectorAsync(parent, connectorId, connector);
// Poll until the returned long-running operation is complete
Operation<Connector, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Connector result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Connector, OperationMetadata> retrievedResponse = await vpcAccessServiceClient.PollOnceCreateConnectorAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Connector retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateConnector</summary>
public void CreateConnectorResourceNames()
{
// Snippet: CreateConnector(LocationName, string, Connector, CallSettings)
// Create client
VpcAccessServiceClient vpcAccessServiceClient = VpcAccessServiceClient.Create();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
string connectorId = "";
Connector connector = new Connector();
// Make the request
Operation<Connector, OperationMetadata> response = vpcAccessServiceClient.CreateConnector(parent, connectorId, connector);
// Poll until the returned long-running operation is complete
Operation<Connector, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Connector result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Connector, OperationMetadata> retrievedResponse = vpcAccessServiceClient.PollOnceCreateConnector(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Connector retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateConnectorAsync</summary>
public async Task CreateConnectorResourceNamesAsync()
{
// Snippet: CreateConnectorAsync(LocationName, string, Connector, CallSettings)
// Additional: CreateConnectorAsync(LocationName, string, Connector, CancellationToken)
// Create client
VpcAccessServiceClient vpcAccessServiceClient = await VpcAccessServiceClient.CreateAsync();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
string connectorId = "";
Connector connector = new Connector();
// Make the request
Operation<Connector, OperationMetadata> response = await vpcAccessServiceClient.CreateConnectorAsync(parent, connectorId, connector);
// Poll until the returned long-running operation is complete
Operation<Connector, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Connector result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Connector, OperationMetadata> retrievedResponse = await vpcAccessServiceClient.PollOnceCreateConnectorAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Connector retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for GetConnector</summary>
public void GetConnectorRequestObject()
{
// Snippet: GetConnector(GetConnectorRequest, CallSettings)
// Create client
VpcAccessServiceClient vpcAccessServiceClient = VpcAccessServiceClient.Create();
// Initialize request argument(s)
GetConnectorRequest request = new GetConnectorRequest
{
ConnectorName = ConnectorName.FromProjectLocationConnector("[PROJECT]", "[LOCATION]", "[CONNECTOR]"),
};
// Make the request
Connector response = vpcAccessServiceClient.GetConnector(request);
// End snippet
}
/// <summary>Snippet for GetConnectorAsync</summary>
public async Task GetConnectorRequestObjectAsync()
{
// Snippet: GetConnectorAsync(GetConnectorRequest, CallSettings)
// Additional: GetConnectorAsync(GetConnectorRequest, CancellationToken)
// Create client
VpcAccessServiceClient vpcAccessServiceClient = await VpcAccessServiceClient.CreateAsync();
// Initialize request argument(s)
GetConnectorRequest request = new GetConnectorRequest
{
ConnectorName = ConnectorName.FromProjectLocationConnector("[PROJECT]", "[LOCATION]", "[CONNECTOR]"),
};
// Make the request
Connector response = await vpcAccessServiceClient.GetConnectorAsync(request);
// End snippet
}
/// <summary>Snippet for GetConnector</summary>
public void GetConnector()
{
// Snippet: GetConnector(string, CallSettings)
// Create client
VpcAccessServiceClient vpcAccessServiceClient = VpcAccessServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/connectors/[CONNECTOR]";
// Make the request
Connector response = vpcAccessServiceClient.GetConnector(name);
// End snippet
}
/// <summary>Snippet for GetConnectorAsync</summary>
public async Task GetConnectorAsync()
{
// Snippet: GetConnectorAsync(string, CallSettings)
// Additional: GetConnectorAsync(string, CancellationToken)
// Create client
VpcAccessServiceClient vpcAccessServiceClient = await VpcAccessServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/connectors/[CONNECTOR]";
// Make the request
Connector response = await vpcAccessServiceClient.GetConnectorAsync(name);
// End snippet
}
/// <summary>Snippet for GetConnector</summary>
public void GetConnectorResourceNames()
{
// Snippet: GetConnector(ConnectorName, CallSettings)
// Create client
VpcAccessServiceClient vpcAccessServiceClient = VpcAccessServiceClient.Create();
// Initialize request argument(s)
ConnectorName name = ConnectorName.FromProjectLocationConnector("[PROJECT]", "[LOCATION]", "[CONNECTOR]");
// Make the request
Connector response = vpcAccessServiceClient.GetConnector(name);
// End snippet
}
/// <summary>Snippet for GetConnectorAsync</summary>
public async Task GetConnectorResourceNamesAsync()
{
// Snippet: GetConnectorAsync(ConnectorName, CallSettings)
// Additional: GetConnectorAsync(ConnectorName, CancellationToken)
// Create client
VpcAccessServiceClient vpcAccessServiceClient = await VpcAccessServiceClient.CreateAsync();
// Initialize request argument(s)
ConnectorName name = ConnectorName.FromProjectLocationConnector("[PROJECT]", "[LOCATION]", "[CONNECTOR]");
// Make the request
Connector response = await vpcAccessServiceClient.GetConnectorAsync(name);
// End snippet
}
/// <summary>Snippet for ListConnectors</summary>
public void ListConnectorsRequestObject()
{
// Snippet: ListConnectors(ListConnectorsRequest, CallSettings)
// Create client
VpcAccessServiceClient vpcAccessServiceClient = VpcAccessServiceClient.Create();
// Initialize request argument(s)
ListConnectorsRequest request = new ListConnectorsRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
// Make the request
PagedEnumerable<ListConnectorsResponse, Connector> response = vpcAccessServiceClient.ListConnectors(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Connector item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListConnectorsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Connector item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Connector> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Connector item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListConnectorsAsync</summary>
public async Task ListConnectorsRequestObjectAsync()
{
// Snippet: ListConnectorsAsync(ListConnectorsRequest, CallSettings)
// Create client
VpcAccessServiceClient vpcAccessServiceClient = await VpcAccessServiceClient.CreateAsync();
// Initialize request argument(s)
ListConnectorsRequest request = new ListConnectorsRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
// Make the request
PagedAsyncEnumerable<ListConnectorsResponse, Connector> response = vpcAccessServiceClient.ListConnectorsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Connector item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListConnectorsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Connector item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Connector> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Connector item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListConnectors</summary>
public void ListConnectors()
{
// Snippet: ListConnectors(string, string, int?, CallSettings)
// Create client
VpcAccessServiceClient vpcAccessServiceClient = VpcAccessServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
// Make the request
PagedEnumerable<ListConnectorsResponse, Connector> response = vpcAccessServiceClient.ListConnectors(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (Connector item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListConnectorsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Connector item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Connector> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Connector item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListConnectorsAsync</summary>
public async Task ListConnectorsAsync()
{
// Snippet: ListConnectorsAsync(string, string, int?, CallSettings)
// Create client
VpcAccessServiceClient vpcAccessServiceClient = await VpcAccessServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
// Make the request
PagedAsyncEnumerable<ListConnectorsResponse, Connector> response = vpcAccessServiceClient.ListConnectorsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Connector item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListConnectorsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Connector item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Connector> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Connector item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListConnectors</summary>
public void ListConnectorsResourceNames()
{
// Snippet: ListConnectors(LocationName, string, int?, CallSettings)
// Create client
VpcAccessServiceClient vpcAccessServiceClient = VpcAccessServiceClient.Create();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
// Make the request
PagedEnumerable<ListConnectorsResponse, Connector> response = vpcAccessServiceClient.ListConnectors(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (Connector item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListConnectorsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Connector item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Connector> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Connector item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListConnectorsAsync</summary>
public async Task ListConnectorsResourceNamesAsync()
{
// Snippet: ListConnectorsAsync(LocationName, string, int?, CallSettings)
// Create client
VpcAccessServiceClient vpcAccessServiceClient = await VpcAccessServiceClient.CreateAsync();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
// Make the request
PagedAsyncEnumerable<ListConnectorsResponse, Connector> response = vpcAccessServiceClient.ListConnectorsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Connector item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListConnectorsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Connector item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Connector> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Connector item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for DeleteConnector</summary>
public void DeleteConnectorRequestObject()
{
// Snippet: DeleteConnector(DeleteConnectorRequest, CallSettings)
// Create client
VpcAccessServiceClient vpcAccessServiceClient = VpcAccessServiceClient.Create();
// Initialize request argument(s)
DeleteConnectorRequest request = new DeleteConnectorRequest
{
ConnectorName = ConnectorName.FromProjectLocationConnector("[PROJECT]", "[LOCATION]", "[CONNECTOR]"),
};
// Make the request
Operation<Empty, OperationMetadata> response = vpcAccessServiceClient.DeleteConnector(request);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = vpcAccessServiceClient.PollOnceDeleteConnector(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteConnectorAsync</summary>
public async Task DeleteConnectorRequestObjectAsync()
{
// Snippet: DeleteConnectorAsync(DeleteConnectorRequest, CallSettings)
// Additional: DeleteConnectorAsync(DeleteConnectorRequest, CancellationToken)
// Create client
VpcAccessServiceClient vpcAccessServiceClient = await VpcAccessServiceClient.CreateAsync();
// Initialize request argument(s)
DeleteConnectorRequest request = new DeleteConnectorRequest
{
ConnectorName = ConnectorName.FromProjectLocationConnector("[PROJECT]", "[LOCATION]", "[CONNECTOR]"),
};
// Make the request
Operation<Empty, OperationMetadata> response = await vpcAccessServiceClient.DeleteConnectorAsync(request);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = await vpcAccessServiceClient.PollOnceDeleteConnectorAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteConnector</summary>
public void DeleteConnector()
{
// Snippet: DeleteConnector(string, CallSettings)
// Create client
VpcAccessServiceClient vpcAccessServiceClient = VpcAccessServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/connectors/[CONNECTOR]";
// Make the request
Operation<Empty, OperationMetadata> response = vpcAccessServiceClient.DeleteConnector(name);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = vpcAccessServiceClient.PollOnceDeleteConnector(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteConnectorAsync</summary>
public async Task DeleteConnectorAsync()
{
// Snippet: DeleteConnectorAsync(string, CallSettings)
// Additional: DeleteConnectorAsync(string, CancellationToken)
// Create client
VpcAccessServiceClient vpcAccessServiceClient = await VpcAccessServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/connectors/[CONNECTOR]";
// Make the request
Operation<Empty, OperationMetadata> response = await vpcAccessServiceClient.DeleteConnectorAsync(name);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = await vpcAccessServiceClient.PollOnceDeleteConnectorAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteConnector</summary>
public void DeleteConnectorResourceNames()
{
// Snippet: DeleteConnector(ConnectorName, CallSettings)
// Create client
VpcAccessServiceClient vpcAccessServiceClient = VpcAccessServiceClient.Create();
// Initialize request argument(s)
ConnectorName name = ConnectorName.FromProjectLocationConnector("[PROJECT]", "[LOCATION]", "[CONNECTOR]");
// Make the request
Operation<Empty, OperationMetadata> response = vpcAccessServiceClient.DeleteConnector(name);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = vpcAccessServiceClient.PollOnceDeleteConnector(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteConnectorAsync</summary>
public async Task DeleteConnectorResourceNamesAsync()
{
// Snippet: DeleteConnectorAsync(ConnectorName, CallSettings)
// Additional: DeleteConnectorAsync(ConnectorName, CancellationToken)
// Create client
VpcAccessServiceClient vpcAccessServiceClient = await VpcAccessServiceClient.CreateAsync();
// Initialize request argument(s)
ConnectorName name = ConnectorName.FromProjectLocationConnector("[PROJECT]", "[LOCATION]", "[CONNECTOR]");
// Make the request
Operation<Empty, OperationMetadata> response = await vpcAccessServiceClient.DeleteConnectorAsync(name);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = await vpcAccessServiceClient.PollOnceDeleteConnectorAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
}
}
| |
// Lucene version compatibility level 4.8.1
using J2N;
using System.Globalization;
namespace Lucene.Net.Analysis.Miscellaneous
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// A BreakIterator-like API for iterating over subwords in text, according to <see cref="WordDelimiterFilter"/> rules.
/// @lucene.internal
/// </summary>
public sealed class WordDelimiterIterator
{
/// <summary>
/// Indicates the end of iteration </summary>
public const int DONE = -1;
public static readonly byte[] DEFAULT_WORD_DELIM_TABLE = LoadDefaultWordDelimTable();
internal char[] text;
private int length;
/// <summary>
/// start position of text, excluding leading delimiters </summary>
private int startBounds;
/// <summary>
/// end position of text, excluding trailing delimiters </summary>
private int endBounds;
/// <summary>
/// Beginning of subword </summary>
internal int current;
/// <summary>
/// End of subword </summary>
internal int end;
/// <summary>does this string end with a possessive such as 's</summary>
private bool hasFinalPossessive = false;
/// <summary>
/// If false, causes case changes to be ignored (subwords will only be generated
/// given SUBWORD_DELIM tokens). (Defaults to true)
/// </summary>
private readonly bool splitOnCaseChange;
/// <summary>
/// If false, causes numeric changes to be ignored (subwords will only be generated
/// given SUBWORD_DELIM tokens). (Defaults to true)
/// </summary>
private readonly bool splitOnNumerics;
/// <summary>
/// If true, causes trailing "'s" to be removed for each subword. (Defaults to true)
/// <p/>
/// "O'Neil's" => "O", "Neil"
/// </summary>
private readonly bool stemEnglishPossessive;
private readonly byte[] charTypeTable;
/// <summary>
/// if true, need to skip over a possessive found in the last call to next() </summary>
private bool skipPossessive = false;
// TODO: should there be a WORD_DELIM category for chars that only separate words (no catenation of subwords will be
// done if separated by these chars?) "," would be an obvious candidate...
private static byte[] LoadDefaultWordDelimTable() // LUCENENET: Avoid static constructors (see https://github.com/apache/lucenenet/pull/224#issuecomment-469284006)
{
var tab = new byte[256];
for (int i = 0; i < 256; i++)
{
byte code = 0;
if (Character.IsLower(i))
{
code |= WordDelimiterFilter.LOWER;
}
else if (Character.IsUpper(i))
{
code |= WordDelimiterFilter.UPPER;
}
else if (Character.IsDigit(i))
{
code |= WordDelimiterFilter.DIGIT;
}
if (code == 0)
{
code = WordDelimiterFilter.SUBWORD_DELIM;
}
tab[i] = code;
}
return tab;
}
/// <summary>
/// Create a new <see cref="WordDelimiterIterator"/> operating with the supplied rules.
/// </summary>
/// <param name="charTypeTable"> table containing character types </param>
/// <param name="splitOnCaseChange"> if true, causes "PowerShot" to be two tokens; ("Power-Shot" remains two parts regards) </param>
/// <param name="splitOnNumerics"> if true, causes "j2se" to be three tokens; "j" "2" "se" </param>
/// <param name="stemEnglishPossessive"> if true, causes trailing "'s" to be removed for each subword: "O'Neil's" => "O", "Neil" </param>
internal WordDelimiterIterator(byte[] charTypeTable, bool splitOnCaseChange, bool splitOnNumerics, bool stemEnglishPossessive)
{
this.charTypeTable = charTypeTable;
this.splitOnCaseChange = splitOnCaseChange;
this.splitOnNumerics = splitOnNumerics;
this.stemEnglishPossessive = stemEnglishPossessive;
}
/// <summary>
/// Advance to the next subword in the string.
/// </summary>
/// <returns> index of the next subword, or <see cref="DONE"/> if all subwords have been returned </returns>
internal int Next()
{
current = end;
if (current == DONE)
{
return DONE;
}
if (skipPossessive)
{
current += 2;
skipPossessive = false;
}
int lastType = 0;
while (current < endBounds && (WordDelimiterFilter.IsSubwordDelim(lastType = CharType(text[current]))))
{
current++;
}
if (current >= endBounds)
{
return end = DONE;
}
for (end = current + 1; end < endBounds; end++)
{
int type = CharType(text[end]);
if (IsBreak(lastType, type))
{
break;
}
lastType = type;
}
if (end < endBounds - 1 && EndsWithPossessive(end + 2))
{
skipPossessive = true;
}
return end;
}
/// <summary>
/// Return the type of the current subword.
/// This currently uses the type of the first character in the subword.
/// </summary>
/// <returns> type of the current word </returns>
internal int Type
{
get
{
if (end == DONE)
{
return 0;
}
int type = CharType(text[current]);
switch (type)
{
// return ALPHA word type for both lower and upper
case WordDelimiterFilter.LOWER:
case WordDelimiterFilter.UPPER:
return WordDelimiterFilter.ALPHA;
default:
return type;
}
}
}
/// <summary>
/// Reset the text to a new value, and reset all state
/// </summary>
/// <param name="text"> New text </param>
/// <param name="length"> length of the text </param>
internal void SetText(char[] text, int length)
{
this.text = text;
this.length = this.endBounds = length;
current = startBounds = end = 0;
skipPossessive = hasFinalPossessive = false;
SetBounds();
}
// ================================================= Helper Methods ================================================
/// <summary>
/// Determines whether the transition from lastType to type indicates a break
/// </summary>
/// <param name="lastType"> Last subword type </param>
/// <param name="type"> Current subword type </param>
/// <returns> <c>true</c> if the transition indicates a break, <c>false</c> otherwise </returns>
private bool IsBreak(int lastType, int type)
{
if ((type & lastType) != 0)
{
return false;
}
if (!splitOnCaseChange && WordDelimiterFilter.IsAlpha(lastType) && WordDelimiterFilter.IsAlpha(type))
{
// ALPHA->ALPHA: always ignore if case isn't considered.
return false;
}
else if (WordDelimiterFilter.IsUpper(lastType) && WordDelimiterFilter.IsAlpha(type))
{
// UPPER->letter: Don't split
return false;
}
else if (!splitOnNumerics && ((WordDelimiterFilter.IsAlpha(lastType) && WordDelimiterFilter.IsDigit(type)) || (WordDelimiterFilter.IsDigit(lastType) && WordDelimiterFilter.IsAlpha(type))))
{
// ALPHA->NUMERIC, NUMERIC->ALPHA :Don't split
return false;
}
return true;
}
/// <summary>
/// Determines if the current word contains only one subword. Note, it could be potentially surrounded by delimiters
/// </summary>
/// <returns> <c>true</c> if the current word contains only one subword, <c>false</c> otherwise </returns>
internal bool IsSingleWord()
{
if (hasFinalPossessive)
{
return current == startBounds && end == endBounds - 2;
}
else
{
return current == startBounds && end == endBounds;
}
}
/// <summary>
/// Set the internal word bounds (remove leading and trailing delimiters). Note, if a possessive is found, don't remove
/// it yet, simply note it.
/// </summary>
private void SetBounds()
{
while (startBounds < length && (WordDelimiterFilter.IsSubwordDelim(CharType(text[startBounds]))))
{
startBounds++;
}
while (endBounds > startBounds && (WordDelimiterFilter.IsSubwordDelim(CharType(text[endBounds - 1]))))
{
endBounds--;
}
if (EndsWithPossessive(endBounds))
{
hasFinalPossessive = true;
}
current = startBounds;
}
/// <summary>
/// Determines if the text at the given position indicates an English possessive which should be removed
/// </summary>
/// <param name="pos"> Position in the text to check if it indicates an English possessive </param>
/// <returns> <c>true</c> if the text at the position indicates an English posessive, <c>false</c> otherwise </returns>
private bool EndsWithPossessive(int pos)
{
return (stemEnglishPossessive &&
pos > 2 &&
text[pos - 2] == '\'' &&
(text[pos - 1] == 's' || text[pos - 1] == 'S') &&
WordDelimiterFilter.IsAlpha(CharType(text[pos - 3])) &&
(pos == endBounds || WordDelimiterFilter.IsSubwordDelim(CharType(text[pos]))));
}
/// <summary>
/// Determines the type of the given character
/// </summary>
/// <param name="ch"> Character whose type is to be determined </param>
/// <returns> Type of the character </returns>
private int CharType(int ch)
{
if (ch < charTypeTable.Length)
{
return charTypeTable[ch];
}
return GetType(ch);
}
/// <summary>
/// Computes the type of the given character
/// </summary>
/// <param name="ch"> Character whose type is to be determined </param>
/// <returns> Type of the character </returns>
public static byte GetType(int ch)
{
switch (Character.GetType(ch))
{
case UnicodeCategory.UppercaseLetter:
return WordDelimiterFilter.UPPER;
case UnicodeCategory.LowercaseLetter:
return WordDelimiterFilter.LOWER;
case UnicodeCategory.TitlecaseLetter:
case UnicodeCategory.ModifierLetter:
case UnicodeCategory.OtherLetter:
case UnicodeCategory.NonSpacingMark:
case UnicodeCategory.EnclosingMark: // depends what it encloses?
case UnicodeCategory.SpacingCombiningMark:
return WordDelimiterFilter.ALPHA;
case UnicodeCategory.DecimalDigitNumber:
case UnicodeCategory.LetterNumber:
case UnicodeCategory.OtherNumber:
return WordDelimiterFilter.DIGIT;
// case Character.SPACE_SEPARATOR:
// case Character.LINE_SEPARATOR:
// case Character.PARAGRAPH_SEPARATOR:
// case Character.CONTROL:
// case Character.FORMAT:
// case Character.PRIVATE_USE:
case UnicodeCategory.Surrogate:
return WordDelimiterFilter.ALPHA | WordDelimiterFilter.DIGIT;
// case Character.DASH_PUNCTUATION:
// case Character.START_PUNCTUATION:
// case Character.END_PUNCTUATION:
// case Character.CONNECTOR_PUNCTUATION:
// case Character.OTHER_PUNCTUATION:
// case Character.MATH_SYMBOL:
// case Character.CURRENCY_SYMBOL:
// case Character.MODIFIER_SYMBOL:
// case Character.OTHER_SYMBOL:
// case Character.INITIAL_QUOTE_PUNCTUATION:
// case Character.FINAL_QUOTE_PUNCTUATION:
default:
return WordDelimiterFilter.SUBWORD_DELIM;
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.