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 TanksOnline.ProjektPZ.Server.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;
}
}
}
| |
// Copyright 2018 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.
using System;
using System.Collections.Generic;
using ArcGISRuntime.Samples.Managers;
using CoreGraphics;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Rasters;
using Esri.ArcGISRuntime.UI.Controls;
using Foundation;
using UIKit;
namespace ArcGISRuntime.Samples.ChangeBlendRenderer
{
[Register("ChangeBlendRenderer")]
[ArcGISRuntime.Samples.Shared.Attributes.OfflineData("7c4c679ab06a4df19dc497f577f111bd", "caeef9aa78534760b07158bb8e068462")]
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Blend renderer",
category: "Layers",
description: "Blend a hillshade with a raster by specifying the elevation data. The resulting raster looks similar to the original raster, but with some terrain shading, giving it a textured look.",
instructions: "Choose and adjust the altitude, azimuth, slope type, and color ramp type settings to update the image.",
tags: new[] { "Elevation", "Hillshade", "RasterLayer", "color ramp", "elevation", "image", "visualization" })]
public class ChangeBlendRenderer : UIViewController
{
// Hold references to UI controls.
private MapView _myMapView;
private BlendSettingsController _settingsVC;
private UIBarButtonItem _updateButton;
public ChangeBlendRenderer()
{
Title = "Blend renderer";
}
private async void Initialize()
{
// Load the raster file using a path on disk.
Raster rasterImagery = new Raster(DataManager.GetDataFolder("7c4c679ab06a4df19dc497f577f111bd", "raster-file", "Shasta.tif"));
// Create the raster layer from the raster.
RasterLayer rasterLayerImagery = new RasterLayer(rasterImagery);
// Create a new map using the raster layer as the base map.
Map map = new Map(new Basemap(rasterLayerImagery));
try
{
// Wait for the layer to load - this enabled being able to obtain the raster layer's extent.
await rasterLayerImagery.LoadAsync();
// Create a new EnvelopeBuilder from the full extent of the raster layer.
EnvelopeBuilder envelopeBuilder = new EnvelopeBuilder(rasterLayerImagery.FullExtent);
// Configure the settings view.
_settingsVC = new BlendSettingsController(map);
// Zoom in the extent just a bit so that raster layer encompasses the entire viewable area of the map.
envelopeBuilder.Expand(0.75);
// Set the viewpoint of the map to the EnvelopeBuilder's extent.
map.InitialViewpoint = new Viewpoint(envelopeBuilder.ToGeometry().Extent);
// Add map to the map view.
_myMapView.Map = map;
// Wait for the map to load.
await map.LoadAsync();
}
catch (Exception e)
{
new UIAlertView("Error", e.ToString(), (IUIAlertViewDelegate) null, "OK", null).Show();
}
}
private void UpdateRenderer_Clicked(object sender, EventArgs e)
{
UINavigationController controller = new UINavigationController(_settingsVC);
controller.ModalPresentationStyle = UIModalPresentationStyle.Popover;
controller.PreferredContentSize = new CGSize(320, 300);
UIPopoverPresentationController pc = controller.PopoverPresentationController;
if (pc != null)
{
pc.BarButtonItem = (UIBarButtonItem) sender;
pc.PermittedArrowDirections = UIPopoverArrowDirection.Down;
pc.Delegate = new PpDelegate();
}
PresentViewController(controller, true, null);
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
Initialize();
}
public override void LoadView()
{
// Create the views.
View = new UIView {BackgroundColor = ApplicationTheme.BackgroundColor};
_myMapView = new MapView();
_myMapView.TranslatesAutoresizingMaskIntoConstraints = false;
_updateButton = new UIBarButtonItem();
_updateButton.Title = "Update renderer";
UIToolbar toolbar = new UIToolbar();
toolbar.TranslatesAutoresizingMaskIntoConstraints = false;
toolbar.Items = new[]
{
new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace),
_updateButton
};
// Add the views.
View.AddSubviews(_myMapView, toolbar);
// Lay out the views.
NSLayoutConstraint.ActivateConstraints(new[]
{
_myMapView.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor),
_myMapView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
_myMapView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),
_myMapView.BottomAnchor.ConstraintEqualTo(toolbar.TopAnchor),
toolbar.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
toolbar.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),
toolbar.BottomAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.BottomAnchor)
});
}
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
// Subscribe to events.
_updateButton.Clicked += UpdateRenderer_Clicked;
}
public override void ViewDidDisappear(bool animated)
{
base.ViewDidDisappear(animated);
// Unsubscribe from events, per best practice.
_updateButton.Clicked -= UpdateRenderer_Clicked;
}
// Force popover to display on iPhone.
private class PpDelegate : UIPopoverPresentationControllerDelegate
{
public override UIModalPresentationStyle GetAdaptivePresentationStyle(
UIPresentationController forPresentationController) => UIModalPresentationStyle.None;
public override UIModalPresentationStyle GetAdaptivePresentationStyle(UIPresentationController controller,
UITraitCollection traitCollection) => UIModalPresentationStyle.None;
}
}
public class BlendSettingsController : UIViewController
{
// Hold references to UI controls.
private readonly Map _map;
private UISegmentedControl _slopeTypesPicker;
private UISegmentedControl _colorRampsPicker;
private UISlider _altitudeSlider;
private UISlider _azimuthSlider;
public BlendSettingsController(Map map)
{
_map = map;
Title = "Hillshade settings";
}
public override void LoadView()
{
// Create the views.
View = new UIView() { BackgroundColor = ApplicationTheme.BackgroundColor };
UIScrollView scrollView = new UIScrollView();
scrollView.TranslatesAutoresizingMaskIntoConstraints = false;
View.AddSubviews(scrollView);
scrollView.TopAnchor.ConstraintEqualTo(View.TopAnchor).Active = true;
scrollView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor).Active = true;
scrollView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor).Active = true;
scrollView.BottomAnchor.ConstraintEqualTo(View.BottomAnchor).Active = true;
UIStackView formContainer = new UIStackView();
formContainer.TranslatesAutoresizingMaskIntoConstraints = false;
formContainer.Spacing = 8;
formContainer.LayoutMarginsRelativeArrangement = true;
formContainer.Alignment = UIStackViewAlignment.Fill;
formContainer.LayoutMargins = new UIEdgeInsets(8, 8, 8, 8);
formContainer.Axis = UILayoutConstraintAxis.Vertical;
formContainer.WidthAnchor.ConstraintEqualTo(320).Active = true;
// Form controls here.
UILabel slopeTypesLabel = new UILabel();
slopeTypesLabel.TranslatesAutoresizingMaskIntoConstraints = false;
slopeTypesLabel.Text = "Slope type:";
formContainer.AddArrangedSubview(slopeTypesLabel);
_slopeTypesPicker = new UISegmentedControl(Enum.GetNames(typeof(SlopeType)));
_slopeTypesPicker.TranslatesAutoresizingMaskIntoConstraints = false;
_slopeTypesPicker.SelectedSegment = 0;
formContainer.AddArrangedSubview(_slopeTypesPicker);
UILabel colorRampsLabel = new UILabel();
colorRampsLabel.TranslatesAutoresizingMaskIntoConstraints = false;
colorRampsLabel.Text = "Color ramp:";
formContainer.AddArrangedSubview(colorRampsLabel);
_colorRampsPicker = new UISegmentedControl(Enum.GetNames(typeof(PresetColorRampType)));
_colorRampsPicker.TranslatesAutoresizingMaskIntoConstraints = false;
_colorRampsPicker.SelectedSegment = 0;
formContainer.AddArrangedSubview(_colorRampsPicker);
UILabel altitudeLabel = new UILabel();
altitudeLabel.TranslatesAutoresizingMaskIntoConstraints = false;
altitudeLabel.Text = "Altitude:";
formContainer.AddArrangedSubview(altitudeLabel);
_altitudeSlider = new UISlider();
_altitudeSlider.TranslatesAutoresizingMaskIntoConstraints = false;
_altitudeSlider.MinValue = 0;
_altitudeSlider.MaxValue = 90;
_altitudeSlider.Value = 45;
formContainer.AddArrangedSubview(_altitudeSlider);
UILabel azimuthLabel = new UILabel();
azimuthLabel.TranslatesAutoresizingMaskIntoConstraints = false;
azimuthLabel.Text = "Azimuth:";
formContainer.AddArrangedSubview(azimuthLabel);
_azimuthSlider = new UISlider();
_azimuthSlider.TranslatesAutoresizingMaskIntoConstraints = false;
_azimuthSlider.MinValue = 0;
_azimuthSlider.MaxValue = 360;
_azimuthSlider.Value = 180;
formContainer.AddArrangedSubview(_azimuthSlider);
// Add the views.
scrollView.AddSubview(formContainer);
// Put the apply button in the top-right part of the popover.
NavigationItem.RightBarButtonItem = new UIBarButtonItem("Apply", UIBarButtonItemStyle.Plain, UpdateRendererButton_Clicked);
// Lay out the views.
formContainer.TopAnchor.ConstraintEqualTo(scrollView.TopAnchor).Active = true;
formContainer.LeadingAnchor.ConstraintEqualTo(scrollView.LeadingAnchor).Active = true;
formContainer.TrailingAnchor.ConstraintEqualTo(scrollView.TrailingAnchor).Active = true;
formContainer.BottomAnchor.ConstraintEqualTo(scrollView.BottomAnchor).Active = true;
// Disable horizontal scrolling.
formContainer.WidthAnchor.ConstraintEqualTo(scrollView.WidthAnchor).Active = true;
}
private void UpdateRendererButton_Clicked(object sender, EventArgs e)
{
try
{
// Define the RasterLayer that will be used to display in the map.
RasterLayer rasterLayerForDisplayInMap;
// Define the ColorRamp that will be used by the BlendRenderer.
ColorRamp colorRamp;
// Get the user choice for the ColorRamps.
string selection = Enum.GetNames(typeof(PresetColorRampType))[_colorRampsPicker.SelectedSegment];
// Based on ColorRamp type chosen by the user, create a different
// RasterLayer and define the appropriate ColorRamp option.
if (selection == "None")
{
// The user chose not to use a specific ColorRamp, therefore
// need to create a RasterLayer based on general imagery (i.e. Shasta.tif)
// for display in the map and use null for the ColorRamp as one of the
// parameters in the BlendRenderer constructor.
// Load the raster file using a path on disk.
Raster rasterImagery = new Raster(DataManager.GetDataFolder("7c4c679ab06a4df19dc497f577f111bd", "raster-file", "Shasta.tif"));
// Create the raster layer from the raster.
rasterLayerForDisplayInMap = new RasterLayer(rasterImagery);
// Set up the ColorRamp as being null.
colorRamp = null;
}
else
{
// The user chose a specific ColorRamp (options: are Elevation, DemScreen, DemLight),
// therefore create a RasterLayer based on an imagery with elevation
// (i.e. Shasta_Elevation.tif) for display in the map. Also create a ColorRamp
// based on the user choice, translated into an Enumeration, as one of the parameters
// in the BlendRenderer constructor.
// Load the raster file using a path on disk.
Raster rasterElevation = new Raster(DataManager.GetDataFolder("caeef9aa78534760b07158bb8e068462", "Shasta_Elevation.tif"));
// Create the raster layer from the raster.
rasterLayerForDisplayInMap = new RasterLayer(rasterElevation);
// Create a ColorRamp based on the user choice, translated into an Enumeration.
PresetColorRampType myPresetColorRampType = (PresetColorRampType) Enum.Parse(typeof(PresetColorRampType), selection);
colorRamp = ColorRamp.Create(myPresetColorRampType, 256);
}
// Define the parameters used by the BlendRenderer constructor.
Raster rasterForMakingBlendRenderer = new Raster(DataManager.GetDataFolder("caeef9aa78534760b07158bb8e068462", "Shasta_Elevation.tif"));
IEnumerable<double> myOutputMinValues = new List<double> {9};
IEnumerable<double> myOutputMaxValues = new List<double> {255};
IEnumerable<double> mySourceMinValues = new List<double>();
IEnumerable<double> mySourceMaxValues = new List<double>();
IEnumerable<double> myNoDataValues = new List<double>();
IEnumerable<double> myGammas = new List<double>();
// Get the user choice for the SlopeType.
string slopeSelection = Enum.GetNames(typeof(SlopeType))[_slopeTypesPicker.SelectedSegment];
SlopeType mySlopeType = (SlopeType) Enum.Parse(typeof(SlopeType), slopeSelection);
rasterLayerForDisplayInMap.Renderer = new BlendRenderer(
rasterForMakingBlendRenderer, // elevationRaster - Raster based on a elevation source.
myOutputMinValues, // outputMinValues - Output stretch values, one for each band.
myOutputMaxValues, // outputMaxValues - Output stretch values, one for each band.
mySourceMinValues, // sourceMinValues - Input stretch values, one for each band.
mySourceMaxValues, // sourceMaxValues - Input stretch values, one for each band.
myNoDataValues, // noDataValues - NoData values, one for each band.
myGammas, // gammas - Gamma adjustment.
colorRamp, // colorRamp - ColorRamp object to use, could be null.
_altitudeSlider.Value, // altitude - Altitude angle of the light source.
_azimuthSlider.Value, // azimuth - Azimuth angle of the light source, measured clockwise from north.
1, // zfactor - Factor to convert z unit to x,y units, default is 1.
mySlopeType, // slopeType - Slope Type.
1, // pixelSizeFactor - Pixel size factor, default is 1.
1, // pixelSizePower - Pixel size power value, default is 1.
8); // outputBitDepth - Output bit depth, default is 8-bit.
// Set the new base map to be the RasterLayer with the BlendRenderer applied.
_map.Basemap = new Basemap(rasterLayerForDisplayInMap);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
}
| |
namespace Gu.Wpf.UiAutomation
{
using System;
using System.Linq;
using System.Windows.Automation;
public static class Conditions
{
public static Condition TrueCondition { get; } = Condition.TrueCondition;
public static Condition Button { get; } = new AndCondition(
ByControlType(ControlType.Button),
new PropertyCondition(AutomationElement.IsTogglePatternAvailableProperty, false));
public static Condition Calendar { get; } = ByControlType(ControlType.Calendar);
public static Condition CalendarDayButton { get; } = ByClassName(nameof(CalendarDayButton));
public static Condition CheckBox { get; } = ByControlType(ControlType.CheckBox);
public static Condition ComboBox { get; } = ByControlType(ControlType.ComboBox);
public static Condition ContextMenu { get; } = ByClassName(nameof(ContextMenu));
public static Condition ControlTypeCustom { get; } = ByControlType(ControlType.Custom);
public static Condition DataGrid { get; } = ByClassName(nameof(DataGrid));
public static Condition DataGridCell { get; } = ByClassName(nameof(DataGridCell));
public static Condition DataGridColumnHeadersPresenter { get; } = ByClassName(nameof(DataGridColumnHeadersPresenter));
public static Condition DataGridColumnHeader { get; } = ByClassName(nameof(DataGridColumnHeader));
public static Condition DataGridRow { get; } = ByClassName(nameof(DataGridRow));
public static Condition DataGridRowHeader { get; } = ByClassName(nameof(DataGridRowHeader));
public static Condition DataGridDetailsPresenter { get; } = ByClassName(nameof(DataGridDetailsPresenter));
public static Condition DataItem { get; } = ByControlType(ControlType.DataItem);
public static Condition DatePicker { get; } = new AndCondition(ByControlType(ControlType.Custom), ByClassName(nameof(DatePicker)));
public static Condition Frame { get; } = ByClassName(nameof(Frame));
public static Condition ControlTypeDocument { get; } = ByControlType(ControlType.Document);
public static AndCondition Expander { get; } = new AndCondition(ByControlType(ControlType.Group), ByClassName(nameof(Expander)));
public static Condition GridSplitter { get; } = ByClassName(nameof(GridSplitter));
public static Condition GridViewCell { get; } = new AndCondition(
new PropertyCondition(AutomationElement.IsTableItemPatternAvailableProperty, true),
new PropertyCondition(AutomationElement.IsGridItemPatternAvailableProperty, true));
public static Condition GridViewColumnHeader { get; } = ByClassName(nameof(GridViewColumnHeader));
public static Condition GridViewRowHeader { get; } = ByClassName(nameof(GridViewRowHeader));
public static Condition GridViewHeaderRowPresenter { get; } = ByClassName(nameof(GridViewHeaderRowPresenter));
public static Condition GroupBox { get; } = new AndCondition(ByControlType(ControlType.Group), ByClassName(nameof(GroupBox)));
public static Condition Header { get; } = ByControlType(ControlType.Header);
public static Condition HeaderItem { get; } = ByControlType(ControlType.HeaderItem);
public static Condition HeaderSite { get; } = new PropertyCondition(AutomationElement.AutomationIdProperty, nameof(HeaderSite));
public static Condition NotHeaderSite { get; } = new NotCondition(HeaderSite);
public static Condition HorizontalScrollBar { get; } = new AndCondition(ByControlType(ControlType.ScrollBar), new NotCondition(ByAutomationId(nameof(VerticalScrollBar))));
public static Condition VerticalScrollBar { get; } = new AndCondition(ByControlType(ControlType.ScrollBar), new NotCondition(ByAutomationId(nameof(HorizontalScrollBar))));
public static Condition Hyperlink { get; } = ByControlType(ControlType.Hyperlink);
public static Condition Image { get; } = ByControlType(ControlType.Image);
public static Condition Label { get; } = new AndCondition(
ByControlType(ControlType.Text),
new OrCondition(
ByClassName(nameof(Text)),
ByClassName("Static")));
public static Condition ListBox { get; } = ByClassName(nameof(ListBox));
public static Condition ListBoxItem { get; } = ByClassName(nameof(ListBoxItem));
public static Condition ListView { get; } = ByClassName(nameof(ListView));
public static Condition ListViewItem { get; } = ByClassName(nameof(ListViewItem));
public static Condition Menu { get; } = ByControlType(ControlType.Menu);
public static Condition MenuBar { get; } = ByControlType(ControlType.MenuBar);
public static Condition MenuItem { get; } = ByControlType(ControlType.MenuItem);
public static Condition MessageBox { get; } = ByClassName("#32770");
public static Condition OpenFileDialog { get; } = ByClassName("#32770");
public static Condition SaveFileDialog { get; } = ByClassName("#32770");
public static Condition ModalWindow { get; } = new AndCondition(
ByControlType(ControlType.Window),
new PropertyCondition(WindowPatternIdentifiers.IsModalProperty, true));
public static Condition Pane { get; } = ByControlType(ControlType.Pane);
public static Condition PasswordBox { get; } = ByClassName(nameof(PasswordBox));
public static Condition Popup { get; } = new AndCondition(
ByControlType(ControlType.Window),
Conditions.ByName(string.Empty),
Conditions.ByClassName("Popup"));
public static Condition ProgressBar { get; } = ByControlType(ControlType.ProgressBar);
public static Condition RadioButton { get; } = ByControlType(ControlType.RadioButton);
public static Condition RepeatButton { get; } = ByClassName(nameof(RepeatButton));
public static Condition RichTextBox { get; } = ByClassName(nameof(RichTextBox));
public static Condition ScrollBar { get; } = ByControlType(ControlType.ScrollBar);
public static Condition ScrollViewer { get; } = ByClassName(nameof(ScrollViewer));
public static Condition Separator { get; } = ByControlType(ControlType.Separator);
public static Condition Slider { get; } = ByControlType(ControlType.Slider);
public static Condition Spinner { get; } = ByControlType(ControlType.Spinner);
public static Condition SplitButton { get; } = ByControlType(ControlType.SplitButton);
public static Condition StatusBar { get; } = ByControlType(ControlType.StatusBar);
public static Condition TabControl { get; } = ByControlType(ControlType.Tab);
public static Condition TabItem { get; } = ByControlType(ControlType.TabItem);
public static Condition ControlTypeTable { get; } = ByControlType(ControlType.Table);
public static Condition TextBlock { get; } = new AndCondition(ByControlType(ControlType.Text), ByClassName(nameof(TextBlock)));
/// <summary>
/// For finding textblocks and labels.
/// </summary>
public static Condition Text { get; } = ByControlType(ControlType.Text);
public static Condition TextBox { get; } = ByClassName(nameof(TextBox));
public static Condition TextBoxBase { get; } = ByControlType(ControlType.Edit);
public static Condition Thumb { get; } = ByControlType(ControlType.Thumb);
public static Condition TitleBar { get; } = ByControlType(ControlType.TitleBar);
public static Condition ToggleButton { get; } = new AndCondition(
ByControlType(ControlType.Button),
new PropertyCondition(AutomationElement.IsTogglePatternAvailableProperty, true));
public static Condition ToolBar { get; } = ByControlType(ControlType.ToolBar);
public static Condition ToolTip { get; } = ByControlType(ControlType.ToolTip);
public static Condition TreeView { get; } = ByControlType(ControlType.Tree);
public static Condition TreeViewItem { get; } = ByControlType(ControlType.TreeItem);
public static Condition UserControl { get; } = new AndCondition(
ByControlType(ControlType.Custom),
new PropertyCondition(AutomationElement.IsContentElementProperty, true),
new PropertyCondition(AutomationElement.IsControlElementProperty, true));
public static Condition Window { get; } = ByControlType(ControlType.Window);
public static PropertyCondition IsKeyboardFocusable { get; } = new PropertyCondition(AutomationElement.IsKeyboardFocusableProperty, true);
public static PropertyCondition IsTableItemPatternAvailable { get; } = new PropertyCondition(AutomationElement.IsTableItemPatternAvailableProperty, true);
public static PropertyCondition IsScrollItemPatternAvailable { get; } = new PropertyCondition(AutomationElement.IsScrollItemPatternAvailableProperty, true);
public static PropertyCondition IsScrollPatternAvailable { get; } = new PropertyCondition(AutomationElement.IsScrollPatternAvailableProperty, true);
public static PropertyCondition ByAutomationId(string automationId)
{
return new PropertyCondition(AutomationElementIdentifiers.AutomationIdProperty, automationId);
}
public static PropertyCondition ByClassName(string className)
{
return new PropertyCondition(AutomationElementIdentifiers.ClassNameProperty, className);
}
public static PropertyCondition ByControlType(ControlType controlType)
{
return new PropertyCondition(AutomationElementIdentifiers.ControlTypeProperty, controlType);
}
public static PropertyCondition ByLocalizedControlType(string localizedControlType)
{
return new PropertyCondition(AutomationElementIdentifiers.LocalizedControlTypeProperty, localizedControlType);
}
public static PropertyCondition ByHelpTextProperty(string helpText)
{
return new PropertyCondition(AutomationElementIdentifiers.HelpTextProperty, helpText);
}
public static PropertyCondition ByName(string name)
{
return new PropertyCondition(AutomationElementIdentifiers.NameProperty, name);
}
public static OrCondition ByNameOrAutomationId(string key)
{
return new OrCondition(
ByName(key),
ByAutomationId(key));
}
public static PropertyCondition ByProcessId(int processId)
{
return new PropertyCondition(AutomationElementIdentifiers.ProcessIdProperty, processId);
}
public static PropertyCondition ByValue(string value)
{
return new PropertyCondition(ValuePatternIdentifiers.ValueProperty, value);
}
public static string Description(this Condition condition)
{
if (condition is null)
{
throw new ArgumentNullException(nameof(condition));
}
switch (condition)
{
case PropertyCondition propertyCondition:
{
if (Equals(propertyCondition.Property, AutomationElementIdentifiers.ControlTypeProperty))
{
// ReSharper disable once PossibleNullReferenceException
return $"ControlType == {ControlType.LookupById((int)propertyCondition.Value).ProgrammaticName.TrimStart("ControlType.")}";
}
return $"{propertyCondition.Property.ProgrammaticName.TrimStart("AutomationElementIdentifiers.").TrimEnd("Property")} == {propertyCondition.Value}";
}
case AndCondition andCondition:
return $"({string.Join(" && ", andCondition.GetConditions().Select(x => x.Description()))})";
case OrCondition orCondition:
return $"({string.Join(" || ", orCondition.GetConditions().Select(x => x.Description()))})";
case NotCondition notCondition:
return $"!{notCondition.Condition.Description()}";
case var c when c == Condition.TrueCondition:
return "Condition.TrueCondition";
case var c when c == Condition.FalseCondition:
return "Condition.FalseCondition";
default:
return condition.ToString()!;
}
}
internal static bool IsMatch(AutomationElement element, Condition condition)
{
switch (condition)
{
case PropertyCondition propertyCondition:
{
var value = element.GetCurrentPropertyValue(propertyCondition.Property);
if (Equals(propertyCondition.Property, AutomationElement.ControlTypeProperty) &&
value is ControlType controlType &&
propertyCondition.Value is int id)
{
return controlType.Id == id;
}
return propertyCondition.Flags switch
{
PropertyConditionFlags.None => Equals(value, propertyCondition.Value),
PropertyConditionFlags.IgnoreCase => string.Equals((string)value, (string)propertyCondition.Value, StringComparison.OrdinalIgnoreCase),
_ => throw new ArgumentOutOfRangeException(nameof(condition), propertyCondition.Flags, "Unknown flags."),
};
}
case AndCondition andCondition:
return andCondition.GetConditions().All(c => IsMatch(element, c));
case OrCondition orCondition:
return orCondition.GetConditions().Any(c => IsMatch(element, c));
case NotCondition notCondition:
return !IsMatch(element, notCondition.Condition);
case var c when c == Condition.TrueCondition:
return true;
case var c when c == Condition.FalseCondition:
return false;
default:
throw new ArgumentOutOfRangeException(nameof(condition), condition, "Condition not suported");
}
}
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections;
namespace Ctrip.Log4.Appender
{
/// <summary>
/// A strongly-typed collection of <see cref="IAppender"/> objects.
/// </summary>
/// <author>Nicko Cadell</author>
public class AppenderCollection : ICollection, IList, IEnumerable, ICloneable
{
#region Interfaces
/// <summary>
/// Supports type-safe iteration over a <see cref="AppenderCollection"/>.
/// </summary>
/// <exclude/>
public interface IAppenderCollectionEnumerator
{
/// <summary>
/// Gets the current element in the collection.
/// </summary>
IAppender Current { get; }
/// <summary>
/// Advances the enumerator to the next element in the collection.
/// </summary>
/// <returns>
/// <c>true</c> if the enumerator was successfully advanced to the next element;
/// <c>false</c> if the enumerator has passed the end of the collection.
/// </returns>
/// <exception cref="InvalidOperationException">
/// The collection was modified after the enumerator was created.
/// </exception>
bool MoveNext();
/// <summary>
/// Sets the enumerator to its initial position, before the first element in the collection.
/// </summary>
void Reset();
}
#endregion
private const int DEFAULT_CAPACITY = 16;
#region Implementation (data)
private IAppender[] m_array;
private int m_count = 0;
private int m_version = 0;
#endregion
#region Static Wrappers
/// <summary>
/// Creates a read-only wrapper for a <c>AppenderCollection</c> instance.
/// </summary>
/// <param name="list">list to create a readonly wrapper arround</param>
/// <returns>
/// An <c>AppenderCollection</c> wrapper that is read-only.
/// </returns>
public static AppenderCollection ReadOnly(AppenderCollection list)
{
if(list==null) throw new ArgumentNullException("list");
return new ReadOnlyAppenderCollection(list);
}
#endregion
#region Static Fields
/// <summary>
/// An empty readonly static AppenderCollection
/// </summary>
public static readonly AppenderCollection EmptyCollection = ReadOnly(new AppenderCollection(0));
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <c>AppenderCollection</c> class
/// that is empty and has the default initial capacity.
/// </summary>
public AppenderCollection()
{
m_array = new IAppender[DEFAULT_CAPACITY];
}
/// <summary>
/// Initializes a new instance of the <c>AppenderCollection</c> class
/// that has the specified initial capacity.
/// </summary>
/// <param name="capacity">
/// The number of elements that the new <c>AppenderCollection</c> is initially capable of storing.
/// </param>
public AppenderCollection(int capacity)
{
m_array = new IAppender[capacity];
}
/// <summary>
/// Initializes a new instance of the <c>AppenderCollection</c> class
/// that contains elements copied from the specified <c>AppenderCollection</c>.
/// </summary>
/// <param name="c">The <c>AppenderCollection</c> whose elements are copied to the new collection.</param>
public AppenderCollection(AppenderCollection c)
{
m_array = new IAppender[c.Count];
AddRange(c);
}
/// <summary>
/// Initializes a new instance of the <c>AppenderCollection</c> class
/// that contains elements copied from the specified <see cref="IAppender"/> array.
/// </summary>
/// <param name="a">The <see cref="IAppender"/> array whose elements are copied to the new list.</param>
public AppenderCollection(IAppender[] a)
{
m_array = new IAppender[a.Length];
AddRange(a);
}
/// <summary>
/// Initializes a new instance of the <c>AppenderCollection</c> class
/// that contains elements copied from the specified <see cref="IAppender"/> collection.
/// </summary>
/// <param name="col">The <see cref="IAppender"/> collection whose elements are copied to the new list.</param>
public AppenderCollection(ICollection col)
{
m_array = new IAppender[col.Count];
AddRange(col);
}
/// <summary>
/// Type visible only to our subclasses
/// Used to access protected constructor
/// </summary>
/// <exclude/>
internal protected enum Tag
{
/// <summary>
/// A value
/// </summary>
Default
}
/// <summary>
/// Allow subclasses to avoid our default constructors
/// </summary>
/// <param name="tag"></param>
/// <exclude/>
internal protected AppenderCollection(Tag tag)
{
m_array = null;
}
#endregion
#region Operations (type-safe ICollection)
/// <summary>
/// Gets the number of elements actually contained in the <c>AppenderCollection</c>.
/// </summary>
public virtual int Count
{
get { return m_count; }
}
/// <summary>
/// Copies the entire <c>AppenderCollection</c> to a one-dimensional
/// <see cref="IAppender"/> array.
/// </summary>
/// <param name="array">The one-dimensional <see cref="IAppender"/> array to copy to.</param>
public virtual void CopyTo(IAppender[] array)
{
this.CopyTo(array, 0);
}
/// <summary>
/// Copies the entire <c>AppenderCollection</c> to a one-dimensional
/// <see cref="IAppender"/> array, starting at the specified index of the target array.
/// </summary>
/// <param name="array">The one-dimensional <see cref="IAppender"/> array to copy to.</param>
/// <param name="start">The zero-based index in <paramref name="array"/> at which copying begins.</param>
public virtual void CopyTo(IAppender[] array, int start)
{
if (m_count > array.GetUpperBound(0) + 1 - start)
{
throw new System.ArgumentException("Destination array was not long enough.");
}
Array.Copy(m_array, 0, array, start, m_count);
}
/// <summary>
/// Gets a value indicating whether access to the collection is synchronized (thread-safe).
/// </summary>
/// <returns>true if access to the ICollection is synchronized (thread-safe); otherwise, false.</returns>
public virtual bool IsSynchronized
{
get { return m_array.IsSynchronized; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the collection.
/// </summary>
public virtual object SyncRoot
{
get { return m_array.SyncRoot; }
}
#endregion
#region Operations (type-safe IList)
/// <summary>
/// Gets or sets the <see cref="IAppender"/> at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the element to get or set.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="index"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="index"/> is equal to or greater than <see cref="AppenderCollection.Count"/>.</para>
/// </exception>
public virtual IAppender this[int index]
{
get
{
ValidateIndex(index); // throws
return m_array[index];
}
set
{
ValidateIndex(index); // throws
++m_version;
m_array[index] = value;
}
}
/// <summary>
/// Adds a <see cref="IAppender"/> to the end of the <c>AppenderCollection</c>.
/// </summary>
/// <param name="item">The <see cref="IAppender"/> to be added to the end of the <c>AppenderCollection</c>.</param>
/// <returns>The index at which the value has been added.</returns>
public virtual int Add(IAppender item)
{
if (m_count == m_array.Length)
{
EnsureCapacity(m_count + 1);
}
m_array[m_count] = item;
m_version++;
return m_count++;
}
/// <summary>
/// Removes all elements from the <c>AppenderCollection</c>.
/// </summary>
public virtual void Clear()
{
++m_version;
m_array = new IAppender[DEFAULT_CAPACITY];
m_count = 0;
}
/// <summary>
/// Creates a shallow copy of the <see cref="AppenderCollection"/>.
/// </summary>
/// <returns>A new <see cref="AppenderCollection"/> with a shallow copy of the collection data.</returns>
public virtual object Clone()
{
AppenderCollection newCol = new AppenderCollection(m_count);
Array.Copy(m_array, 0, newCol.m_array, 0, m_count);
newCol.m_count = m_count;
newCol.m_version = m_version;
return newCol;
}
/// <summary>
/// Determines whether a given <see cref="IAppender"/> is in the <c>AppenderCollection</c>.
/// </summary>
/// <param name="item">The <see cref="IAppender"/> to check for.</param>
/// <returns><c>true</c> if <paramref name="item"/> is found in the <c>AppenderCollection</c>; otherwise, <c>false</c>.</returns>
public virtual bool Contains(IAppender item)
{
for (int i=0; i != m_count; ++i)
{
if (m_array[i].Equals(item))
{
return true;
}
}
return false;
}
/// <summary>
/// Returns the zero-based index of the first occurrence of a <see cref="IAppender"/>
/// in the <c>AppenderCollection</c>.
/// </summary>
/// <param name="item">The <see cref="IAppender"/> to locate in the <c>AppenderCollection</c>.</param>
/// <returns>
/// The zero-based index of the first occurrence of <paramref name="item"/>
/// in the entire <c>AppenderCollection</c>, if found; otherwise, -1.
/// </returns>
public virtual int IndexOf(IAppender item)
{
for (int i=0; i != m_count; ++i)
{
if (m_array[i].Equals(item))
{
return i;
}
}
return -1;
}
/// <summary>
/// Inserts an element into the <c>AppenderCollection</c> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param>
/// <param name="item">The <see cref="IAppender"/> to insert.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="index"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="index"/> is equal to or greater than <see cref="AppenderCollection.Count"/>.</para>
/// </exception>
public virtual void Insert(int index, IAppender item)
{
ValidateIndex(index, true); // throws
if (m_count == m_array.Length)
{
EnsureCapacity(m_count + 1);
}
if (index < m_count)
{
Array.Copy(m_array, index, m_array, index + 1, m_count - index);
}
m_array[index] = item;
m_count++;
m_version++;
}
/// <summary>
/// Removes the first occurrence of a specific <see cref="IAppender"/> from the <c>AppenderCollection</c>.
/// </summary>
/// <param name="item">The <see cref="IAppender"/> to remove from the <c>AppenderCollection</c>.</param>
/// <exception cref="ArgumentException">
/// The specified <see cref="IAppender"/> was not found in the <c>AppenderCollection</c>.
/// </exception>
public virtual void Remove(IAppender item)
{
int i = IndexOf(item);
if (i < 0)
{
throw new System.ArgumentException("Cannot remove the specified item because it was not found in the specified Collection.");
}
++m_version;
RemoveAt(i);
}
/// <summary>
/// Removes the element at the specified index of the <c>AppenderCollection</c>.
/// </summary>
/// <param name="index">The zero-based index of the element to remove.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="index"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="index"/> is equal to or greater than <see cref="AppenderCollection.Count"/>.</para>
/// </exception>
public virtual void RemoveAt(int index)
{
ValidateIndex(index); // throws
m_count--;
if (index < m_count)
{
Array.Copy(m_array, index + 1, m_array, index, m_count - index);
}
// We can't set the deleted entry equal to null, because it might be a value type.
// Instead, we'll create an empty single-element array of the right type and copy it
// over the entry we want to erase.
IAppender[] temp = new IAppender[1];
Array.Copy(temp, 0, m_array, m_count, 1);
m_version++;
}
/// <summary>
/// Gets a value indicating whether the collection has a fixed size.
/// </summary>
/// <value>true if the collection has a fixed size; otherwise, false. The default is false</value>
public virtual bool IsFixedSize
{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether the IList is read-only.
/// </summary>
/// <value>true if the collection is read-only; otherwise, false. The default is false</value>
public virtual bool IsReadOnly
{
get { return false; }
}
#endregion
#region Operations (type-safe IEnumerable)
/// <summary>
/// Returns an enumerator that can iterate through the <c>AppenderCollection</c>.
/// </summary>
/// <returns>An <see cref="Enumerator"/> for the entire <c>AppenderCollection</c>.</returns>
public virtual IAppenderCollectionEnumerator GetEnumerator()
{
return new Enumerator(this);
}
#endregion
#region Public helpers (just to mimic some nice features of ArrayList)
/// <summary>
/// Gets or sets the number of elements the <c>AppenderCollection</c> can contain.
/// </summary>
public virtual int Capacity
{
get
{
return m_array.Length;
}
set
{
if (value < m_count)
{
value = m_count;
}
if (value != m_array.Length)
{
if (value > 0)
{
IAppender[] temp = new IAppender[value];
Array.Copy(m_array, 0, temp, 0, m_count);
m_array = temp;
}
else
{
m_array = new IAppender[DEFAULT_CAPACITY];
}
}
}
}
/// <summary>
/// Adds the elements of another <c>AppenderCollection</c> to the current <c>AppenderCollection</c>.
/// </summary>
/// <param name="x">The <c>AppenderCollection</c> whose elements should be added to the end of the current <c>AppenderCollection</c>.</param>
/// <returns>The new <see cref="AppenderCollection.Count"/> of the <c>AppenderCollection</c>.</returns>
public virtual int AddRange(AppenderCollection x)
{
if (m_count + x.Count >= m_array.Length)
{
EnsureCapacity(m_count + x.Count);
}
Array.Copy(x.m_array, 0, m_array, m_count, x.Count);
m_count += x.Count;
m_version++;
return m_count;
}
/// <summary>
/// Adds the elements of a <see cref="IAppender"/> array to the current <c>AppenderCollection</c>.
/// </summary>
/// <param name="x">The <see cref="IAppender"/> array whose elements should be added to the end of the <c>AppenderCollection</c>.</param>
/// <returns>The new <see cref="AppenderCollection.Count"/> of the <c>AppenderCollection</c>.</returns>
public virtual int AddRange(IAppender[] x)
{
if (m_count + x.Length >= m_array.Length)
{
EnsureCapacity(m_count + x.Length);
}
Array.Copy(x, 0, m_array, m_count, x.Length);
m_count += x.Length;
m_version++;
return m_count;
}
/// <summary>
/// Adds the elements of a <see cref="IAppender"/> collection to the current <c>AppenderCollection</c>.
/// </summary>
/// <param name="col">The <see cref="IAppender"/> collection whose elements should be added to the end of the <c>AppenderCollection</c>.</param>
/// <returns>The new <see cref="AppenderCollection.Count"/> of the <c>AppenderCollection</c>.</returns>
public virtual int AddRange(ICollection col)
{
if (m_count + col.Count >= m_array.Length)
{
EnsureCapacity(m_count + col.Count);
}
foreach(object item in col)
{
Add((IAppender)item);
}
return m_count;
}
/// <summary>
/// Sets the capacity to the actual number of elements.
/// </summary>
public virtual void TrimToSize()
{
this.Capacity = m_count;
}
/// <summary>
/// Return the collection elements as an array
/// </summary>
/// <returns>the array</returns>
public virtual IAppender[] ToArray()
{
IAppender[] resultArray = new IAppender[m_count];
if (m_count > 0)
{
Array.Copy(m_array, 0, resultArray, 0, m_count);
}
return resultArray;
}
#endregion
#region Implementation (helpers)
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="i"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="i"/> is equal to or greater than <see cref="AppenderCollection.Count"/>.</para>
/// </exception>
private void ValidateIndex(int i)
{
ValidateIndex(i, false);
}
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="i"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="i"/> is equal to or greater than <see cref="AppenderCollection.Count"/>.</para>
/// </exception>
private void ValidateIndex(int i, bool allowEqualEnd)
{
int max = (allowEqualEnd) ? (m_count) : (m_count-1);
if (i < 0 || i > max)
{
throw Ctrip.Log4.Util.SystemInfo.CreateArgumentOutOfRangeException("i", (object)i, "Index was out of range. Must be non-negative and less than the size of the collection. [" + (object)i + "] Specified argument was out of the range of valid values.");
}
}
private void EnsureCapacity(int min)
{
int newCapacity = ((m_array.Length == 0) ? DEFAULT_CAPACITY : m_array.Length * 2);
if (newCapacity < min)
{
newCapacity = min;
}
this.Capacity = newCapacity;
}
#endregion
#region Implementation (ICollection)
void ICollection.CopyTo(Array array, int start)
{
if (m_count > 0)
{
Array.Copy(m_array, 0, array, start, m_count);
}
}
#endregion
#region Implementation (IList)
object IList.this[int i]
{
get { return (object)this[i]; }
set { this[i] = (IAppender)value; }
}
int IList.Add(object x)
{
return this.Add((IAppender)x);
}
bool IList.Contains(object x)
{
return this.Contains((IAppender)x);
}
int IList.IndexOf(object x)
{
return this.IndexOf((IAppender)x);
}
void IList.Insert(int pos, object x)
{
this.Insert(pos, (IAppender)x);
}
void IList.Remove(object x)
{
this.Remove((IAppender)x);
}
void IList.RemoveAt(int pos)
{
this.RemoveAt(pos);
}
#endregion
#region Implementation (IEnumerable)
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator)(this.GetEnumerator());
}
#endregion
#region Nested enumerator class
/// <summary>
/// Supports simple iteration over a <see cref="AppenderCollection"/>.
/// </summary>
/// <exclude/>
private sealed class Enumerator : IEnumerator, IAppenderCollectionEnumerator
{
#region Implementation (data)
private readonly AppenderCollection m_collection;
private int m_index;
private int m_version;
#endregion
#region Construction
/// <summary>
/// Initializes a new instance of the <c>Enumerator</c> class.
/// </summary>
/// <param name="tc"></param>
internal Enumerator(AppenderCollection tc)
{
m_collection = tc;
m_index = -1;
m_version = tc.m_version;
}
#endregion
#region Operations (type-safe IEnumerator)
/// <summary>
/// Gets the current element in the collection.
/// </summary>
public IAppender Current
{
get { return m_collection[m_index]; }
}
/// <summary>
/// Advances the enumerator to the next element in the collection.
/// </summary>
/// <returns>
/// <c>true</c> if the enumerator was successfully advanced to the next element;
/// <c>false</c> if the enumerator has passed the end of the collection.
/// </returns>
/// <exception cref="InvalidOperationException">
/// The collection was modified after the enumerator was created.
/// </exception>
public bool MoveNext()
{
if (m_version != m_collection.m_version)
{
throw new System.InvalidOperationException("Collection was modified; enumeration operation may not execute.");
}
++m_index;
return (m_index < m_collection.Count);
}
/// <summary>
/// Sets the enumerator to its initial position, before the first element in the collection.
/// </summary>
public void Reset()
{
m_index = -1;
}
#endregion
#region Implementation (IEnumerator)
object IEnumerator.Current
{
get { return this.Current; }
}
#endregion
}
#endregion
#region Nested Read Only Wrapper class
/// <exclude/>
private sealed class ReadOnlyAppenderCollection : AppenderCollection, ICollection
{
#region Implementation (data)
private readonly AppenderCollection m_collection;
#endregion
#region Construction
internal ReadOnlyAppenderCollection(AppenderCollection list) : base(Tag.Default)
{
m_collection = list;
}
#endregion
#region Type-safe ICollection
public override void CopyTo(IAppender[] array)
{
m_collection.CopyTo(array);
}
public override void CopyTo(IAppender[] array, int start)
{
m_collection.CopyTo(array,start);
}
void ICollection.CopyTo(Array array, int start)
{
((ICollection)m_collection).CopyTo(array, start);
}
public override int Count
{
get { return m_collection.Count; }
}
public override bool IsSynchronized
{
get { return m_collection.IsSynchronized; }
}
public override object SyncRoot
{
get { return this.m_collection.SyncRoot; }
}
#endregion
#region Type-safe IList
public override IAppender this[int i]
{
get { return m_collection[i]; }
set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); }
}
public override int Add(IAppender x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override void Clear()
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override bool Contains(IAppender x)
{
return m_collection.Contains(x);
}
public override int IndexOf(IAppender x)
{
return m_collection.IndexOf(x);
}
public override void Insert(int pos, IAppender x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override void Remove(IAppender x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override void RemoveAt(int pos)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override bool IsFixedSize
{
get { return true; }
}
public override bool IsReadOnly
{
get { return true; }
}
#endregion
#region Type-safe IEnumerable
public override IAppenderCollectionEnumerator GetEnumerator()
{
return m_collection.GetEnumerator();
}
#endregion
#region Public Helpers
// (just to mimic some nice features of ArrayList)
public override int Capacity
{
get { return m_collection.Capacity; }
set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); }
}
public override int AddRange(AppenderCollection x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override int AddRange(IAppender[] x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
#endregion
}
#endregion
}
}
| |
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using Quartz;
using Spring.Objects.Factory;
using Spring.Objects.Factory.Config;
using Spring.Objects.Support;
namespace Spring.Scheduling.Quartz
{
/// <summary>
/// IFactoryObject that exposes a JobDetail object that delegates job execution
/// to a specified (static or non-static) method. Avoids the need to implement
/// a one-line Quartz Job that just invokes an existing service method.
/// </summary>
/// <remarks>
/// <p>
/// Derived from ArgumentConverting MethodInvoker to share common properties and behavior
/// with MethodInvokingFactoryObject.
/// </p>
/// <p>
/// Supports both concurrently running jobs and non-currently running
/// ones through the "concurrent" property. Jobs created by this
/// MethodInvokingJobDetailFactoryObject are by default volatile and durable
/// (according to Quartz terminology).
/// </p>
/// <p><b>NOTE: JobDetails created via this FactoryObject are <i>not</i>
/// serializable and thus not suitable for persistent job stores.</b>
/// You need to implement your own Quartz Job as a thin wrapper for each case
/// where you want a persistent job to delegate to a specific service method.
/// </p>
/// </remarks>
/// <author>Juergen Hoeller</author>
/// <author>Alef Arendsen</author>
/// <seealso cref="Concurrent" />
/// <seealso cref="MethodInvokingFactoryObject" />
public class MethodInvokingJobDetailFactoryObject : ArgumentConvertingMethodInvoker,
IObjectFactoryAware,
IFactoryObject,
IObjectNameAware,
IInitializingObject
{
private string name;
private string group;
private bool concurrent = true;
private string[] jobListenerNames;
private string targetObjectName;
private string objectName;
private JobDetail jobDetail;
private IObjectFactory objectFactory;
/// <summary>
/// Initializes a new instance of the <see cref="MethodInvokingJobDetailFactoryObject"/> class.
/// </summary>
public MethodInvokingJobDetailFactoryObject()
{
group = SchedulerConstants.DefaultGroup;
}
/// <summary>
/// Set the name of the job.
/// Default is the object name of this FactoryObject.
/// </summary>
/// <seealso cref="Name" />
public virtual string Name
{
set { name = value; }
}
/// <summary>
/// Set the group of the job.
/// Default is the default group of the Scheduler.
/// </summary>
/// <seealso cref="Group" />
/// <seealso cref="SchedulerConstants.DefaultGroup" />
public virtual string Group
{
set { group = value; }
}
/// <summary>
/// Specify whether or not multiple jobs should be run in a concurrent
/// fashion. The behavior when one does not want concurrent jobs to be
/// executed is realized through adding the <see cref="IStatefulJob" /> interface.
/// More information on stateful versus stateless jobs can be found
/// <a href="http://www.opensymphony.com/quartz/tutorial.html#jobsMore">here</a>.
/// <p>
/// The default setting is to run jobs concurrently.
/// </p>
/// </summary>
public virtual bool Concurrent
{
set { concurrent = value; }
}
/// <summary>
/// Gets the job detail.
/// </summary>
/// <value>The job detail.</value>
protected JobDetail JobDetail
{
get { return jobDetail; }
}
/// <summary>
/// Set a list of JobListener names for this job, referring to
/// non-global JobListeners registered with the Scheduler.
/// </summary>
/// <remarks>
/// A JobListener name always refers to the name returned
/// by the JobListener implementation.
/// </remarks>
/// <seealso cref="SchedulerAccessor.JobListeners" />
/// <seealso cref="IJobListener.Name" />
public virtual string[] JobListenerNames
{
set { jobListenerNames = value; }
}
/// <summary>
/// Set the name of the object in the object factory that created this object.
/// </summary>
/// <value>The name of the object in the factory.</value>
/// <remarks>
/// Invoked after population of normal object properties but before an init
/// callback like <see cref="Spring.Objects.Factory.IInitializingObject"/>'s
/// <see cref="Spring.Objects.Factory.IInitializingObject.AfterPropertiesSet"/>
/// method or a custom init-method.
/// </remarks>
public virtual string ObjectName
{
set { objectName = value; }
}
/// <summary>
/// Set the name of the target object in the Spring object factory.
/// </summary>
/// <remarks>
/// This is an alternative to specifying TargetObject
/// allowing for non-singleton objects to be invoked. Note that specified
/// "TargetObject" and "TargetType" values will
/// override the corresponding effect of this "TargetObjectName" setting
///(i.e. statically pre-define the object type or even the target object).
/// </remarks>
public string TargetObjectName
{
set { targetObjectName = value; }
}
/// <summary>
/// Sets the object factory.
/// </summary>
/// <value>The object factory.</value>
public IObjectFactory ObjectFactory
{
set { objectFactory = value; }
}
/// <summary>
/// Return an instance (possibly shared or independent) of the object
/// managed by this factory.
/// </summary>
/// <returns>
/// An instance (possibly shared or independent) of the object managed by
/// this factory.
/// </returns>
/// <remarks>
/// <note type="caution">
/// If this method is being called in the context of an enclosing IoC container and
/// returns <see langword="null"/>, the IoC container will consider this factory
/// object as not being fully initialized and throw a corresponding (and most
/// probably fatal) exception.
/// </note>
/// </remarks>
public virtual object GetObject()
{
return jobDetail;
}
/// <summary>
/// Return the <see cref="System.Type"/> of object that this
/// <see cref="Spring.Objects.Factory.IFactoryObject"/> creates, or
/// <see langword="null"/> if not known in advance.
/// </summary>
/// <value></value>
public virtual Type ObjectType
{
get
{
if (targetObjectName != null)
{
if (objectFactory == null)
{
throw new InvalidOperationException("ObjectFactory must be set when using 'TargetObjectName'");
}
return objectFactory.GetType(targetObjectName);
}
return typeof (JobDetail);
}
}
/// <summary>
/// Is the object managed by this factory a singleton or a prototype?
/// </summary>
/// <value></value>
public virtual bool IsSingleton
{
get { return true; }
}
/// <summary>
/// Invoked by an <see cref="Spring.Objects.Factory.IObjectFactory"/>
/// after it has injected all of an object's dependencies.
/// </summary>
/// <remarks>
/// <p>
/// This method allows the object instance to perform the kind of
/// initialization only possible when all of it's dependencies have
/// been injected (set), and to throw an appropriate exception in the
/// event of misconfiguration.
/// </p>
/// <p>
/// Please do consult the class level documentation for the
/// <see cref="Spring.Objects.Factory.IObjectFactory"/> interface for a
/// description of exactly <i>when</i> this method is invoked. In
/// particular, it is worth noting that the
/// <see cref="Spring.Objects.Factory.IObjectFactoryAware"/>
/// and <see cref="Spring.Context.IApplicationContextAware"/>
/// callbacks will have been invoked <i>prior</i> to this method being
/// called.
/// </p>
/// </remarks>
/// <exception cref="System.Exception">
/// In the event of misconfiguration (such as the failure to set a
/// required property) or if initialization fails.
/// </exception>
public virtual void AfterPropertiesSet()
{
Prepare();
// Use specific name if given, else fall back to object name.
string jobDetailName = (name != null ? name : objectName);
// Consider the concurrent flag to choose between stateful and stateless job.
Type jobType = (concurrent ? typeof (MethodInvokingJob) : typeof (StatefulMethodInvokingJob));
// Build JobDetail instance.
jobDetail = new JobDetail(jobDetailName, group, jobType);
jobDetail.JobDataMap.Put("methodInvoker", this);
jobDetail.Volatile = true;
jobDetail.Durable = true;
// Register job listener names.
if (jobListenerNames != null)
{
for (int i = 0; i < jobListenerNames.Length; i++)
{
jobDetail.AddJobListener(jobListenerNames[i]);
}
}
PostProcessJobDetail(jobDetail);
}
/// <summary>
/// Callback for post-processing the JobDetail to be exposed by this FactoryObject.
/// <p>
/// The default implementation is empty. Can be overridden in subclasses.
/// </p>
/// </summary>
/// <param name="detail">the JobDetail prepared by this FactoryObject</param>
protected virtual void PostProcessJobDetail(JobDetail detail)
{
}
}
}
| |
// 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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Scripting.Hosting
{
/// <summary>
/// Implements an assembly loader for interactive compiler and REPL.
/// </summary>
/// <remarks>
/// <para>
/// The class is thread-safe.
/// </para>
/// </remarks>
public sealed partial class InteractiveAssemblyLoader : IDisposable
{
private class LoadedAssembly
{
public bool LoadedExplicitly { get; set; }
/// <summary>
/// The original path of the assembly before it was shadow-copied.
/// For GAC'd assemblies, this is equal to Assembly.Location no matter what path was used to load them.
/// </summary>
public string OriginalPath { get; set; }
}
private readonly AssemblyLoaderImpl _runtimeAssemblyLoader;
private readonly MetadataShadowCopyProvider _shadowCopyProvider;
// Synchronizes assembly reference tracking.
// Needs to be thread-safe since assembly loading may be triggered at any time by CLR type loader.
private readonly object _referencesLock = new object();
// loaded assembly -> loaded assembly info
private readonly Dictionary<Assembly, LoadedAssembly> _assembliesLoadedFromLocation;
// { original full path -> assembly }
// Note, that there might be multiple entries for a single GAC'd assembly.
private readonly Dictionary<string, AssemblyAndLocation> _assembliesLoadedFromLocationByFullPath;
// simple name -> loaded assemblies
private readonly Dictionary<string, List<Assembly>> _loadedAssembliesBySimpleName;
// simple name -> identity and location of a known dependency
private readonly Dictionary<string, List<AssemblyIdentityAndLocation>> _dependenciesWithLocationBySimpleName;
[SuppressMessage("Performance", "RS0008", Justification = "Equality not actually implemented")]
private struct AssemblyIdentityAndLocation
{
public readonly AssemblyIdentity Identity;
public readonly string Location;
public AssemblyIdentityAndLocation(AssemblyIdentity identity, string location)
{
Debug.Assert(identity != null && location != null);
this.Identity = identity;
this.Location = location;
}
public override int GetHashCode()
{
throw ExceptionUtilities.Unreachable;
}
public override bool Equals(object obj)
{
throw ExceptionUtilities.Unreachable;
}
public override string ToString()
{
return Identity + " @ " + Location;
}
}
public InteractiveAssemblyLoader(MetadataShadowCopyProvider shadowCopyProvider = null)
{
_shadowCopyProvider = shadowCopyProvider;
_assembliesLoadedFromLocationByFullPath = new Dictionary<string, AssemblyAndLocation>();
_assembliesLoadedFromLocation = new Dictionary<Assembly, LoadedAssembly>();
_loadedAssembliesBySimpleName = new Dictionary<string, List<Assembly>>(AssemblyIdentityComparer.SimpleNameComparer);
_dependenciesWithLocationBySimpleName = new Dictionary<string, List<AssemblyIdentityAndLocation>>();
_runtimeAssemblyLoader = AssemblyLoaderImpl.Create(this);
}
public void Dispose()
{
_runtimeAssemblyLoader.Dispose();
}
internal Assembly LoadAssemblyFromStream(Stream peStream, Stream pdbStream)
{
Assembly assembly = _runtimeAssemblyLoader.LoadFromStream(peStream, pdbStream);
RegisterDependency(assembly);
return assembly;
}
private AssemblyAndLocation Load(string reference)
{
MetadataShadowCopy copy = null;
try
{
if (_shadowCopyProvider != null)
{
// All modules of the assembly has to be copied at once to keep the metadata consistent.
// This API copies the xml doc file and keeps the memory-maps of the metadata.
// We don't need that here but presumably the provider is shared with the compilation API that needs both.
// Ideally the CLR would expose API to load Assembly given a byte* and not create their own memory-map.
copy = _shadowCopyProvider.GetMetadataShadowCopy(reference, MetadataImageKind.Assembly);
}
var result = _runtimeAssemblyLoader.LoadFromPath((copy != null) ? copy.PrimaryModule.FullPath : reference);
if (_shadowCopyProvider != null && result.GlobalAssemblyCache)
{
_shadowCopyProvider.SuppressShadowCopy(reference);
}
return result;
}
catch (FileNotFoundException)
{
return default(AssemblyAndLocation);
}
finally
{
// copy holds on the file handle, we need to keep the handle
// open until the file is locked by the CLR assembly loader:
copy?.DisposeFileHandles();
}
}
/// <summary>
/// Loads an assembly from path.
/// </summary>
/// <param name="path">Absolute assembly file path.</param>
/// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="path"/> is not an existing path.</exception>
/// <exception cref="ArgumentException"><paramref name="path"/> is not an existing assembly file path.</exception>
/// <exception cref="TargetInvocationException">The assembly resolver threw an exception.</exception>
internal AssemblyLoadResult LoadFromPath(string path)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
if (!PathUtilities.IsAbsolute(path))
{
throw new ArgumentException(ScriptingResources.AbsolutePathExpected, nameof(path));
}
try
{
return LoadFromPathInternal(FileUtilities.NormalizeAbsolutePath(path));
}
catch (TargetInvocationException)
{
throw;
}
catch (Exception e)
{
throw new ArgumentException(e.Message, nameof(path), e);
}
}
/// <summary>
/// Notifies the assembly loader about a dependency that might be loaded in future.
/// </summary>
/// <param name="dependency">Assembly identity.</param>
/// <param name="path">Assembly location.</param>
/// <remarks>
/// Associates a full assembly name with its location. The association is used when an assembly
/// is being loaded and its name needs to be resolved to a location.
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="dependency"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="path"/> is not an existing path.</exception>
public void RegisterDependency(AssemblyIdentity dependency, string path)
{
if (dependency == null)
{
throw new ArgumentNullException(nameof(dependency));
}
if (!PathUtilities.IsAbsolute(path))
{
throw new ArgumentException(ScriptingResources.AbsolutePathExpected, nameof(path));
}
lock (_referencesLock)
{
RegisterDependencyNoLock(new AssemblyIdentityAndLocation(dependency, path));
}
}
/// <summary>
/// Notifies the assembly loader about an in-memory dependency that should be available within the resolution context.
/// </summary>
/// <param name="dependency">Assembly identity.</param>
/// <exception cref="ArgumentNullException"><paramref name="dependency"/> is null.</exception>
/// <remarks>
/// When another in-memory assembly references the <paramref name="dependency"/> the loader
/// responds with the specified dependency if the assembly identity matches the requested one.
/// </remarks>
public void RegisterDependency(Assembly dependency)
{
if (dependency == null)
{
throw new ArgumentNullException(nameof(dependency));
}
lock (_referencesLock)
{
RegisterLoadedAssemblySimpleNameNoLock(dependency);
}
}
private AssemblyLoadResult LoadFromPathInternal(string fullPath)
{
AssemblyAndLocation assembly;
lock (_referencesLock)
{
if (_assembliesLoadedFromLocationByFullPath.TryGetValue(fullPath, out assembly))
{
LoadedAssembly loadedAssembly = _assembliesLoadedFromLocation[assembly.Assembly];
if (loadedAssembly.LoadedExplicitly)
{
return AssemblyLoadResult.CreateAlreadyLoaded(assembly.Location, loadedAssembly.OriginalPath);
}
else
{
loadedAssembly.LoadedExplicitly = true;
return AssemblyLoadResult.CreateSuccessful(assembly.Location, loadedAssembly.OriginalPath);
}
}
}
AssemblyLoadResult result;
assembly = ShadowCopyAndLoadAssembly(fullPath, out result);
if (assembly.IsDefault)
{
throw new FileNotFoundException(message: null, fileName: fullPath);
}
return result;
}
private void RegisterLoadedAssemblySimpleNameNoLock(Assembly assembly)
{
List<Assembly> sameSimpleNameAssemblies;
string simpleName = assembly.GetName().Name;
if (_loadedAssembliesBySimpleName.TryGetValue(simpleName, out sameSimpleNameAssemblies))
{
sameSimpleNameAssemblies.Add(assembly);
}
else
{
_loadedAssembliesBySimpleName.Add(simpleName, new List<Assembly> { assembly });
}
}
private void RegisterDependencyNoLock(AssemblyIdentityAndLocation dependency)
{
List<AssemblyIdentityAndLocation> sameSimpleNameAssemblyIdentities;
string simpleName = dependency.Identity.Name;
if (_dependenciesWithLocationBySimpleName.TryGetValue(simpleName, out sameSimpleNameAssemblyIdentities))
{
sameSimpleNameAssemblyIdentities.Add(dependency);
}
else
{
_dependenciesWithLocationBySimpleName.Add(simpleName, new List<AssemblyIdentityAndLocation> { dependency });
}
}
internal Assembly ResolveAssembly(string assemblyDisplayName, Assembly requestingAssemblyOpt)
{
AssemblyIdentity identity;
if (!AssemblyIdentity.TryParseDisplayName(assemblyDisplayName, out identity))
{
return null;
}
string loadDirectoryOpt;
lock (_referencesLock)
{
LoadedAssembly loadedAssembly;
if (requestingAssemblyOpt != null &&
_assembliesLoadedFromLocation.TryGetValue(requestingAssemblyOpt, out loadedAssembly))
{
loadDirectoryOpt = Path.GetDirectoryName(loadedAssembly.OriginalPath);
}
else
{
loadDirectoryOpt = null;
}
}
return ResolveAssembly(identity, loadDirectoryOpt);
}
internal Assembly ResolveAssembly(AssemblyIdentity identity, string loadDirectoryOpt)
{
// if the referring assembly is already loaded by our loader, load from its directory:
if (loadDirectoryOpt != null)
{
string pathWithoutExtension = Path.Combine(loadDirectoryOpt, identity.Name);
string originalDllPath = pathWithoutExtension + ".dll";
string originalExePath = pathWithoutExtension + ".exe";
lock (_referencesLock)
{
AssemblyAndLocation assembly;
if (_assembliesLoadedFromLocationByFullPath.TryGetValue(originalDllPath, out assembly) ||
_assembliesLoadedFromLocationByFullPath.TryGetValue(originalExePath, out assembly))
{
return assembly.Assembly;
}
}
// Copy & load both .dll and .exe, this is not a common scenario we would need to optimize for.
// Remember both loaded assemblies for the next time, even though their versions might not match the current request
// they might match the next one and we don't want to load them again.
Assembly dll = ShadowCopyAndLoadDependency(originalDllPath).Assembly;
Assembly exe = ShadowCopyAndLoadDependency(originalExePath).Assembly;
if (dll == null ^ exe == null)
{
return dll ?? exe;
}
if (dll != null && exe != null)
{
// .dll and an .exe of the same name might have different versions,
// one of which might match the requested version.
// Prefer .dll if they are both the same.
return FindHighestVersionOrFirstMatchingIdentity(identity, new[] { dll, exe });
}
}
return GetOrLoadKnownAssembly(identity);
}
private Assembly GetOrLoadKnownAssembly(AssemblyIdentity identity)
{
Assembly assembly = null;
string assemblyFileToLoad = null;
// Try to find the assembly among assemblies that we loaded, comparing its identity with the requested one.
lock (_referencesLock)
{
// already loaded assemblies:
List<Assembly> sameSimpleNameAssemblies;
if (_loadedAssembliesBySimpleName.TryGetValue(identity.Name, out sameSimpleNameAssemblies))
{
assembly = FindHighestVersionOrFirstMatchingIdentity(identity, sameSimpleNameAssemblies);
if (assembly != null)
{
return assembly;
}
}
// names:
List<AssemblyIdentityAndLocation> sameSimpleNameIdentities;
if (_dependenciesWithLocationBySimpleName.TryGetValue(identity.Name, out sameSimpleNameIdentities))
{
var identityAndLocation = FindHighestVersionOrFirstMatchingIdentity(identity, sameSimpleNameIdentities);
if (identityAndLocation.Identity != null)
{
assemblyFileToLoad = identityAndLocation.Location;
AssemblyAndLocation assemblyAndLocation;
if (_assembliesLoadedFromLocationByFullPath.TryGetValue(assemblyFileToLoad, out assemblyAndLocation))
{
return assemblyAndLocation.Assembly;
}
}
}
}
if (assemblyFileToLoad != null)
{
assembly = ShadowCopyAndLoadDependency(assemblyFileToLoad).Assembly;
}
return assembly;
}
private AssemblyAndLocation ShadowCopyAndLoadAssembly(string originalPath, out AssemblyLoadResult result)
{
return ShadowCopyAndLoadAndAddEntry(originalPath, out result, explicitLoad: true);
}
private AssemblyAndLocation ShadowCopyAndLoadDependency(string originalPath)
{
AssemblyLoadResult result;
return ShadowCopyAndLoadAndAddEntry(originalPath, out result, explicitLoad: false);
}
private AssemblyAndLocation ShadowCopyAndLoadAndAddEntry(string originalPath, out AssemblyLoadResult result, bool explicitLoad)
{
AssemblyAndLocation assemblyAndLocation = Load(originalPath);
if (assemblyAndLocation.IsDefault)
{
result = default(AssemblyLoadResult);
return default(AssemblyAndLocation);
}
lock (_referencesLock)
{
// Always remember the path. The assembly might have been loaded from another path or not loaded yet.
_assembliesLoadedFromLocationByFullPath[originalPath] = assemblyAndLocation;
LoadedAssembly loadedAssembly;
if (_assembliesLoadedFromLocation.TryGetValue(assemblyAndLocation.Assembly, out loadedAssembly))
{
// The same assembly may have been loaded from a different path already,
// or the assembly has been loaded while we were copying the file and loading the copy;
// Use the existing assembly record.
if (loadedAssembly.LoadedExplicitly)
{
result = AssemblyLoadResult.CreateAlreadyLoaded(assemblyAndLocation.Location, loadedAssembly.OriginalPath);
}
else
{
loadedAssembly.LoadedExplicitly = explicitLoad;
result = AssemblyLoadResult.CreateSuccessful(assemblyAndLocation.Location, loadedAssembly.OriginalPath);
}
return assemblyAndLocation;
}
else
{
result = AssemblyLoadResult.CreateSuccessful(
assemblyAndLocation.Location,
assemblyAndLocation.GlobalAssemblyCache ? assemblyAndLocation.Location : originalPath);
_assembliesLoadedFromLocation.Add(
assemblyAndLocation.Assembly,
new LoadedAssembly { LoadedExplicitly = explicitLoad, OriginalPath = result.OriginalPath });
}
RegisterLoadedAssemblySimpleNameNoLock(assemblyAndLocation.Assembly);
}
return assemblyAndLocation;
}
private static Assembly FindHighestVersionOrFirstMatchingIdentity(AssemblyIdentity identity, IEnumerable<Assembly> assemblies)
{
Assembly candidate = null;
Version candidateVersion = null;
foreach (var assembly in assemblies)
{
var assemblyIdentity = AssemblyIdentity.FromAssemblyDefinition(assembly);
if (DesktopAssemblyIdentityComparer.Default.ReferenceMatchesDefinition(identity, assemblyIdentity))
{
if (candidate == null || candidateVersion < assemblyIdentity.Version)
{
candidate = assembly;
candidateVersion = assemblyIdentity.Version;
}
}
}
return candidate;
}
private static AssemblyIdentityAndLocation FindHighestVersionOrFirstMatchingIdentity(AssemblyIdentity identity, IEnumerable<AssemblyIdentityAndLocation> assemblies)
{
var candidate = default(AssemblyIdentityAndLocation);
foreach (var assembly in assemblies)
{
if (DesktopAssemblyIdentityComparer.Default.ReferenceMatchesDefinition(identity, assembly.Identity))
{
if (candidate.Identity == null || candidate.Identity.Version < assembly.Identity.Version)
{
candidate = assembly;
}
}
}
return candidate;
}
}
}
| |
using System;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using Csla;
using System.ComponentModel;
using System.Threading.Tasks;
namespace ProjectTracker.Library
{
[Serializable()]
public class ProjectEdit : CslaBaseTypes.BusinessBase<ProjectEdit>
{
public static readonly PropertyInfo<byte[]> TimeStampProperty =
RegisterProperty<byte[]>(nameof(TimeStamp));
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public byte[] TimeStamp
{
get { return GetProperty(TimeStampProperty); }
set { SetProperty(TimeStampProperty, value); }
}
public static readonly PropertyInfo<int> IdProperty =
RegisterProperty<int>(nameof(Id));
[Display(Name = "Project id")]
public int Id
{
get { return GetProperty(IdProperty); }
private set { LoadProperty(IdProperty, value); }
}
public static readonly PropertyInfo<string> NameProperty =
RegisterProperty<string>(nameof(Name));
[Display(Name = "Project name")]
[Required]
[StringLength(50)]
public string Name
{
get { return GetProperty(NameProperty); }
set { SetProperty(NameProperty, value); }
}
public static readonly PropertyInfo<DateTime?> StartedProperty =
RegisterProperty<DateTime?>(nameof(Started));
public DateTime? Started
{
get { return GetProperty(StartedProperty); }
set { SetProperty(StartedProperty, value); }
}
public static readonly PropertyInfo<DateTime?> EndedProperty =
RegisterProperty<DateTime?>(nameof(Ended));
public DateTime? Ended
{
get { return GetProperty(EndedProperty); }
set { SetProperty(EndedProperty, value); }
}
public static readonly PropertyInfo<string> DescriptionProperty =
RegisterProperty<string>(nameof(Description));
public string Description
{
get { return GetProperty(DescriptionProperty); }
set { SetProperty(DescriptionProperty, value); }
}
public static readonly PropertyInfo<ProjectResources> ResourcesProperty =
RegisterProperty<ProjectResources>(nameof(Resources));
public ProjectResources Resources
{
get { return GetProperty(ResourcesProperty); }
private set { LoadProperty(ResourcesProperty, value); }
}
public override string ToString()
{
return Id.ToString();
}
protected override void AddBusinessRules()
{
base.AddBusinessRules();
BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(NameProperty));
BusinessRules.AddRule(
new StartDateGTEndDate {
PrimaryProperty = StartedProperty,
AffectedProperties = { EndedProperty } });
BusinessRules.AddRule(
new StartDateGTEndDate {
PrimaryProperty = EndedProperty,
AffectedProperties = { StartedProperty } });
BusinessRules.AddRule(
new Csla.Rules.CommonRules.IsInRole(
Csla.Rules.AuthorizationActions.WriteProperty,
NameProperty,
"ProjectManager"));
BusinessRules.AddRule(new Csla.Rules.CommonRules.IsInRole(
Csla.Rules.AuthorizationActions.WriteProperty, StartedProperty, Security.Roles.ProjectManager));
BusinessRules.AddRule(new Csla.Rules.CommonRules.IsInRole(
Csla.Rules.AuthorizationActions.WriteProperty, EndedProperty, Security.Roles.ProjectManager));
BusinessRules.AddRule(new Csla.Rules.CommonRules.IsInRole(
Csla.Rules.AuthorizationActions.WriteProperty, DescriptionProperty, Security.Roles.ProjectManager));
BusinessRules.AddRule(new NoDuplicateResource { PrimaryProperty = ResourcesProperty });
}
[EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public static void AddObjectAuthorizationRules()
{
Csla.Rules.BusinessRules.AddRule(
typeof(ProjectEdit),
new Csla.Rules.CommonRules.IsInRole(
Csla.Rules.AuthorizationActions.CreateObject,
"ProjectManager"));
Csla.Rules.BusinessRules.AddRule(typeof(ProjectEdit),
new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.EditObject, Security.Roles.ProjectManager));
Csla.Rules.BusinessRules.AddRule(typeof(ProjectEdit),
new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.DeleteObject, Security.Roles.ProjectManager, Security.Roles.Administrator));
}
protected override void OnChildChanged(Csla.Core.ChildChangedEventArgs e)
{
if (e.ChildObject is ProjectResources)
{
BusinessRules.CheckRules(ResourcesProperty);
OnPropertyChanged(ResourcesProperty);
}
base.OnChildChanged(e);
}
private class NoDuplicateResource : Csla.Rules.BusinessRule
{
protected override void Execute(Csla.Rules.IRuleContext context)
{
var target = (ProjectEdit)context.Target;
foreach (var item in target.Resources)
{
var count = target.Resources.Count(r => r.ResourceId == item.ResourceId);
if (count > 1)
{
context.AddErrorResult("Duplicate resources not allowed");
return;
}
}
}
}
private class StartDateGTEndDate : Csla.Rules.BusinessRule
{
protected override void Execute(Csla.Rules.IRuleContext context)
{
var target = (ProjectEdit)context.Target;
var started = target.ReadProperty(StartedProperty);
var ended = target.ReadProperty(EndedProperty);
if (started.HasValue && ended.HasValue && started > ended || !started.HasValue && ended.HasValue)
context.AddErrorResult("Start date can't be after end date");
}
}
public async static Task<ProjectEdit> NewProjectAsync()
{
return await DataPortal.CreateAsync<ProjectEdit>();
}
public async static Task<ProjectEdit> GetProjectAsync(int id)
{
return await DataPortal.FetchAsync<ProjectEdit>(id);
}
public static ProjectEdit NewProject()
{
return DataPortal.Create<ProjectEdit>();
}
public static ProjectEdit GetProject(int id)
{
return DataPortal.Fetch<ProjectEdit>(id);
}
public static async Task DeleteProjectAsync(int id)
{
await DataPortal.DeleteAsync<ProjectEdit>(id);
}
public static async Task<bool> ExistsAsync(int id)
{
var cmd = await DataPortal.CreateAsync<ProjectExistsCommand>(id);
cmd = await DataPortal.ExecuteAsync(cmd);
return cmd.ProjectExists;
}
[Create]
[RunLocal]
protected override void DataPortal_Create()
{
LoadProperty(ResourcesProperty, DataPortal.CreateChild<ProjectResources>());
base.DataPortal_Create();
}
[Fetch]
private void DataPortal_Fetch(int id)
{
using (var ctx = ProjectTracker.Dal.DalFactory.GetManager())
{
var dal = ctx.GetProvider<ProjectTracker.Dal.IProjectDal>();
var data = dal.Fetch(id);
using (BypassPropertyChecks)
{
Id = data.Id;
Name = data.Name;
Description = data.Description;
Started = data.Started;
Ended = data.Ended;
TimeStamp = data.LastChanged;
Resources = DataPortal.FetchChild<ProjectResources>(id);
}
}
}
[Insert]
protected override void DataPortal_Insert()
{
using (var ctx = ProjectTracker.Dal.DalFactory.GetManager())
{
var dal = ctx.GetProvider<ProjectTracker.Dal.IProjectDal>();
using (BypassPropertyChecks)
{
var item = new ProjectTracker.Dal.ProjectDto
{
Name = this.Name,
Description = this.Description,
Started = this.Started,
Ended = this.Ended
};
dal.Insert(item);
Id = item.Id;
TimeStamp = item.LastChanged;
}
FieldManager.UpdateChildren(this);
}
}
[Update]
protected override void DataPortal_Update()
{
using (var ctx = ProjectTracker.Dal.DalFactory.GetManager())
{
var dal = ctx.GetProvider<ProjectTracker.Dal.IProjectDal>();
using (BypassPropertyChecks)
{
var item = new ProjectTracker.Dal.ProjectDto
{
Id = this.Id,
Name = this.Name,
Description = this.Description,
Started = this.Started,
Ended = this.Ended,
LastChanged = this.TimeStamp
};
dal.Update(item);
TimeStamp = item.LastChanged;
}
FieldManager.UpdateChildren(this.Id);
}
}
[DeleteSelf]
protected override void DataPortal_DeleteSelf()
{
using (BypassPropertyChecks)
DataPortal_Delete(this.Id);
}
[Delete]
private void DataPortal_Delete(int id)
{
using (var ctx = ProjectTracker.Dal.DalFactory.GetManager())
{
Resources.Clear();
FieldManager.UpdateChildren(this);
var dal = ctx.GetProvider<ProjectTracker.Dal.IProjectDal>();
dal.Delete(id);
}
}
}
}
| |
// 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.Security.Cryptography.X509Certificates
{
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Diagnostics.Contracts;
internal static class X509Constants {
internal const uint CRYPT_EXPORTABLE = 0x00000001;
internal const uint CRYPT_USER_PROTECTED = 0x00000002;
internal const uint CRYPT_MACHINE_KEYSET = 0x00000020;
internal const uint CRYPT_USER_KEYSET = 0x00001000;
internal const uint CERT_QUERY_CONTENT_CERT = 1;
internal const uint CERT_QUERY_CONTENT_CTL = 2;
internal const uint CERT_QUERY_CONTENT_CRL = 3;
internal const uint CERT_QUERY_CONTENT_SERIALIZED_STORE = 4;
internal const uint CERT_QUERY_CONTENT_SERIALIZED_CERT = 5;
internal const uint CERT_QUERY_CONTENT_SERIALIZED_CTL = 6;
internal const uint CERT_QUERY_CONTENT_SERIALIZED_CRL = 7;
internal const uint CERT_QUERY_CONTENT_PKCS7_SIGNED = 8;
internal const uint CERT_QUERY_CONTENT_PKCS7_UNSIGNED = 9;
internal const uint CERT_QUERY_CONTENT_PKCS7_SIGNED_EMBED = 10;
internal const uint CERT_QUERY_CONTENT_PKCS10 = 11;
internal const uint CERT_QUERY_CONTENT_PFX = 12;
internal const uint CERT_QUERY_CONTENT_CERT_PAIR = 13;
internal const uint CERT_STORE_PROV_MEMORY = 2;
internal const uint CERT_STORE_PROV_SYSTEM = 10;
// cert store flags
internal const uint CERT_STORE_NO_CRYPT_RELEASE_FLAG = 0x00000001;
internal const uint CERT_STORE_SET_LOCALIZED_NAME_FLAG = 0x00000002;
internal const uint CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG = 0x00000004;
internal const uint CERT_STORE_DELETE_FLAG = 0x00000010;
internal const uint CERT_STORE_SHARE_STORE_FLAG = 0x00000040;
internal const uint CERT_STORE_SHARE_CONTEXT_FLAG = 0x00000080;
internal const uint CERT_STORE_MANIFOLD_FLAG = 0x00000100;
internal const uint CERT_STORE_ENUM_ARCHIVED_FLAG = 0x00000200;
internal const uint CERT_STORE_UPDATE_KEYID_FLAG = 0x00000400;
internal const uint CERT_STORE_BACKUP_RESTORE_FLAG = 0x00000800;
internal const uint CERT_STORE_READONLY_FLAG = 0x00008000;
internal const uint CERT_STORE_OPEN_EXISTING_FLAG = 0x00004000;
internal const uint CERT_STORE_CREATE_NEW_FLAG = 0x00002000;
internal const uint CERT_STORE_MAXIMUM_ALLOWED_FLAG = 0x00001000;
internal const uint CERT_NAME_EMAIL_TYPE = 1;
internal const uint CERT_NAME_RDN_TYPE = 2;
internal const uint CERT_NAME_SIMPLE_DISPLAY_TYPE = 4;
internal const uint CERT_NAME_FRIENDLY_DISPLAY_TYPE = 5;
internal const uint CERT_NAME_DNS_TYPE = 6;
internal const uint CERT_NAME_URL_TYPE = 7;
internal const uint CERT_NAME_UPN_TYPE = 8;
}
/// <summary>
/// Groups of OIDs supported by CryptFindOIDInfo
/// </summary>
internal enum OidGroup {
AllGroups = 0,
HashAlgorithm = 1, // CRYPT_HASH_ALG_OID_GROUP_ID
EncryptionAlgorithm = 2, // CRYPT_ENCRYPT_ALG_OID_GROUP_ID
PublicKeyAlgorithm = 3, // CRYPT_PUBKEY_ALG_OID_GROUP_ID
SignatureAlgorithm = 4, // CRYPT_SIGN_ALG_OID_GROUP_ID
Attribute = 5, // CRYPT_RDN_ATTR_OID_GROUP_ID
ExtensionOrAttribute = 6, // CRYPT_EXT_OR_ATTR_OID_GROUP_ID
EnhancedKeyUsage = 7, // CRYPT_ENHKEY_USAGE_OID_GROUP_ID
Policy = 8, // CRYPT_POLICY_OID_GROUP_ID
Template = 9, // CRYPT_TEMPLATE_OID_GROUP_ID
KeyDerivationFunction = 10, // CRYPT_KDF_OID_GROUP_ID
// This can be ORed into the above groups to turn off an AD search
DisableSearchDS = unchecked((int)0x80000000) // CRYPT_OID_DISABLE_SEARCH_DS_FLAG
}
/// <summary>
/// Keys that can be used to query information on via CryptFindOIDInfo
/// </summary>
internal enum OidKeyType {
Oid = 1, // CRYPT_OID_INFO_OID_KEY
Name = 2, // CRYPT_OID_INFO_NAME_KEY
AlgorithmID = 3, // CRYPT_OID_INFO_ALGID_KEY
SignatureID = 4, // CRYPT_OID_INFO_SIGN_KEY
CngAlgorithmID = 5, // CRYPT_OID_INFO_CNG_ALGID_KEY
CngSignatureID = 6, // CRYPT_OID_INFO_CNG_SIGN_KEY
}
[StructLayout(LayoutKind.Sequential)]
internal struct CRYPT_OID_INFO {
internal int cbSize;
[MarshalAs(UnmanagedType.LPStr)]
internal string pszOID;
[MarshalAs(UnmanagedType.LPWStr)]
internal string pwszName;
internal OidGroup dwGroupId;
internal int AlgId;
internal int cbData;
internal IntPtr pbData;
}
internal static class X509Utils
{
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
private static bool OidGroupWillNotUseActiveDirectory(OidGroup group) {
// These groups will never cause an Active Directory query
return group == OidGroup.HashAlgorithm ||
group == OidGroup.EncryptionAlgorithm ||
group == OidGroup.PublicKeyAlgorithm ||
group == OidGroup.SignatureAlgorithm ||
group == OidGroup.Attribute ||
group == OidGroup.ExtensionOrAttribute ||
group == OidGroup.KeyDerivationFunction;
}
[SecurityCritical]
private static CRYPT_OID_INFO FindOidInfo(OidKeyType keyType, string key, OidGroup group) {
Contract.Requires(key != null);
IntPtr rawKey = IntPtr.Zero;
RuntimeHelpers.PrepareConstrainedRegions();
try {
if (keyType == OidKeyType.Oid) {
rawKey = Marshal.StringToCoTaskMemAnsi(key);
}
else {
rawKey = Marshal.StringToCoTaskMemUni(key);
}
// If the group alone isn't sufficient to suppress an active directory lookup, then our
// first attempt should also include the suppression flag
if (!OidGroupWillNotUseActiveDirectory(group)) {
OidGroup localGroup = group | OidGroup.DisableSearchDS;
IntPtr localOidInfo = CryptFindOIDInfo(keyType, rawKey, localGroup);
if (localOidInfo != IntPtr.Zero) {
return (CRYPT_OID_INFO)Marshal.PtrToStructure(localOidInfo, typeof(CRYPT_OID_INFO));
}
}
// Attempt to query with a specific group, to make try to avoid an AD lookup if possible
IntPtr fullOidInfo = CryptFindOIDInfo(keyType, rawKey, group);
if (fullOidInfo != IntPtr.Zero) {
return (CRYPT_OID_INFO)Marshal.PtrToStructure(fullOidInfo, typeof(CRYPT_OID_INFO));
}
// Finally, for compatibility with previous runtimes, if we have a group specified retry the
// query with no group
if (group != OidGroup.AllGroups) {
IntPtr allGroupOidInfo = CryptFindOIDInfo(keyType, rawKey, OidGroup.AllGroups);
if (allGroupOidInfo != IntPtr.Zero) {
return (CRYPT_OID_INFO)Marshal.PtrToStructure(fullOidInfo, typeof(CRYPT_OID_INFO));
}
}
// Otherwise the lookup failed
return new CRYPT_OID_INFO();
}
finally {
if (rawKey != IntPtr.Zero) {
Marshal.FreeCoTaskMem(rawKey);
}
}
}
[SecuritySafeCritical]
internal static int GetAlgIdFromOid(string oid, OidGroup oidGroup) {
Contract.Requires(oid != null);
// CAPI does not have ALGID mappings for all of the hash algorithms - see if we know the mapping
// first to avoid doing an AD lookup on these values
if (String.Equals(oid, Constants.OID_OIWSEC_SHA256, StringComparison.Ordinal)) {
return Constants.CALG_SHA_256;
}
else if (String.Equals(oid, Constants.OID_OIWSEC_SHA384, StringComparison.Ordinal)) {
return Constants.CALG_SHA_384;
}
else if (String.Equals(oid, Constants.OID_OIWSEC_SHA512, StringComparison.Ordinal)) {
return Constants.CALG_SHA_512;
}
else {
return FindOidInfo(OidKeyType.Oid, oid, oidGroup).AlgId;
}
}
[SecuritySafeCritical]
internal static string GetFriendlyNameFromOid(string oid, OidGroup oidGroup) {
Contract.Requires(oid != null);
CRYPT_OID_INFO oidInfo = FindOidInfo(OidKeyType.Oid, oid, oidGroup);
return oidInfo.pwszName;
}
[SecuritySafeCritical]
internal static string GetOidFromFriendlyName(string friendlyName, OidGroup oidGroup) {
Contract.Requires(friendlyName != null);
CRYPT_OID_INFO oidInfo = FindOidInfo(OidKeyType.Name, friendlyName, oidGroup);
return oidInfo.pszOID;
}
internal static int NameOrOidToAlgId (string oid, OidGroup oidGroup) {
// Default Algorithm Id is CALG_SHA1
if (oid == null)
return Constants.CALG_SHA1;
string oidValue = CryptoConfig.MapNameToOID(oid, oidGroup);
if (oidValue == null)
oidValue = oid; // we were probably passed an OID value directly
int algId = GetAlgIdFromOid(oidValue, oidGroup);
if (algId == 0 || algId == -1) {
throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidOID"));
}
return algId;
}
#endif // FEATURE_CRYPTO
// this method maps a cert content type returned from CryptQueryObject
// to a value in the managed X509ContentType enum
internal static X509ContentType MapContentType (uint contentType) {
switch (contentType) {
case X509Constants.CERT_QUERY_CONTENT_CERT:
return X509ContentType.Cert;
#if !FEATURE_CORECLR
case X509Constants.CERT_QUERY_CONTENT_SERIALIZED_STORE:
return X509ContentType.SerializedStore;
case X509Constants.CERT_QUERY_CONTENT_SERIALIZED_CERT:
return X509ContentType.SerializedCert;
case X509Constants.CERT_QUERY_CONTENT_PKCS7_SIGNED:
case X509Constants.CERT_QUERY_CONTENT_PKCS7_UNSIGNED:
return X509ContentType.Pkcs7;
case X509Constants.CERT_QUERY_CONTENT_PKCS7_SIGNED_EMBED:
return X509ContentType.Authenticode;
case X509Constants.CERT_QUERY_CONTENT_PFX:
return X509ContentType.Pkcs12;
#endif // !FEATURE_CORECLR
default:
return X509ContentType.Unknown;
}
}
// this method maps a X509KeyStorageFlags enum to a combination of crypto API flags
internal static uint MapKeyStorageFlags(X509KeyStorageFlags keyStorageFlags) {
#if FEATURE_LEGACYNETCF
if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
if (keyStorageFlags != X509KeyStorageFlags.DefaultKeySet)
throw new NotSupportedException(Environment.GetResourceString("Argument_InvalidFlag"),
new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), "keyStorageFlags"));
}
#endif
if ((keyStorageFlags & (X509KeyStorageFlags) ~0x1F) != 0)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), "keyStorageFlags");
#if !FEATURE_LEGACYNETCF // CompatibilitySwitches causes problems with CCRewrite
Contract.EndContractBlock();
#endif
uint dwFlags = 0;
#if FEATURE_CORECLR
if (keyStorageFlags != X509KeyStorageFlags.DefaultKeySet) {
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), "keyStorageFlags",
new NotSupportedException());
}
#else // FEATURE_CORECLR
if ((keyStorageFlags & X509KeyStorageFlags.UserKeySet) == X509KeyStorageFlags.UserKeySet)
dwFlags |= X509Constants.CRYPT_USER_KEYSET;
else if ((keyStorageFlags & X509KeyStorageFlags.MachineKeySet) == X509KeyStorageFlags.MachineKeySet)
dwFlags |= X509Constants.CRYPT_MACHINE_KEYSET;
if ((keyStorageFlags & X509KeyStorageFlags.Exportable) == X509KeyStorageFlags.Exportable)
dwFlags |= X509Constants.CRYPT_EXPORTABLE;
if ((keyStorageFlags & X509KeyStorageFlags.UserProtected) == X509KeyStorageFlags.UserProtected)
dwFlags |= X509Constants.CRYPT_USER_PROTECTED;
#endif // FEATURE_CORECLR else
return dwFlags;
}
#if !FEATURE_CORECLR
// this method creates a memory store from a certificate
[System.Security.SecurityCritical] // auto-generated
internal static SafeCertStoreHandle ExportCertToMemoryStore (X509Certificate certificate) {
SafeCertStoreHandle safeCertStoreHandle = SafeCertStoreHandle.InvalidHandle;
X509Utils._OpenX509Store(X509Constants.CERT_STORE_PROV_MEMORY,
X509Constants.CERT_STORE_ENUM_ARCHIVED_FLAG | X509Constants.CERT_STORE_CREATE_NEW_FLAG,
null,
ref safeCertStoreHandle);
X509Utils._AddCertificateToStore(safeCertStoreHandle, certificate.CertContext);
return safeCertStoreHandle;
}
#endif // !FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
internal static IntPtr PasswordToHGlobalUni (object password) {
if (password != null) {
string pwd = password as string;
if (pwd != null)
return Marshal.StringToHGlobalUni(pwd);
#if FEATURE_X509_SECURESTRINGS
SecureString securePwd = password as SecureString;
if (securePwd != null)
return Marshal.SecureStringToGlobalAllocUnicode(securePwd);
#endif // FEATURE_X509_SECURESTRINGS
}
return IntPtr.Zero;
}
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
[SecurityCritical]
[SuppressUnmanagedCodeSecurity]
[DllImport("crypt32")]
private static extern IntPtr CryptFindOIDInfo(OidKeyType dwKeyType, IntPtr pvKey, OidGroup dwGroupId);
#endif // FEATURE_CRYPTO
#if !FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void _AddCertificateToStore(SafeCertStoreHandle safeCertStoreHandle, SafeCertContextHandle safeCertContext);
#endif // !FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void _DuplicateCertContext(IntPtr handle, ref SafeCertContextHandle safeCertContext);
#if !FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern byte[] _ExportCertificatesToBlob(SafeCertStoreHandle safeCertStoreHandle, X509ContentType contentType, IntPtr password);
#endif // !FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern byte[] _GetCertRawData(SafeCertContextHandle safeCertContext);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void _GetDateNotAfter(SafeCertContextHandle safeCertContext, ref Win32Native.FILE_TIME fileTime);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void _GetDateNotBefore(SafeCertContextHandle safeCertContext, ref Win32Native.FILE_TIME fileTime);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern string _GetIssuerName(SafeCertContextHandle safeCertContext, bool legacyV1Mode);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern string _GetPublicKeyOid(SafeCertContextHandle safeCertContext);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern byte[] _GetPublicKeyParameters(SafeCertContextHandle safeCertContext);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern byte[] _GetPublicKeyValue(SafeCertContextHandle safeCertContext);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern string _GetSubjectInfo(SafeCertContextHandle safeCertContext, uint displayType, bool legacyV1Mode);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern byte[] _GetSerialNumber(SafeCertContextHandle safeCertContext);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern byte[] _GetThumbprint(SafeCertContextHandle safeCertContext);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void _LoadCertFromBlob(byte[] rawData, IntPtr password, uint dwFlags, bool persistKeySet, ref SafeCertContextHandle pCertCtx);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void _LoadCertFromFile(string fileName, IntPtr password, uint dwFlags, bool persistKeySet, ref SafeCertContextHandle pCertCtx);
#if !FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void _OpenX509Store(uint storeType, uint flags, string storeName, ref SafeCertStoreHandle safeCertStoreHandle);
#endif // !FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern uint _QueryCertBlobType(byte[] rawData);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern uint _QueryCertFileType(string fileName);
}
}
| |
using System;
using System.Collections.Generic;
using TileDraw;
using TileDraw.Map;
using UnityEngine;
[Serializable]
public class MapManager : MonoBehaviour
{
public List<Cell> Cells = new List<Cell>();
public string DefaultShader = "Diffuse";
public TileSet TileTextureSet;
public EntitySet EntitySet;
public int TextureResolution = 1024;
public int NumberOfTiles = 32;
public float SizeOfCell = 16;
public float HalfSizeOfCell
{
get { return SizeOfCell / 2f; }
}
public int TileResolution
{
get { return TextureResolution/NumberOfTiles; }
}
public float TileSize
{
get { return SizeOfCell/NumberOfTiles; }
}
public float HalfTileSize
{
get { return TileSize/2f; }
}
public void RebuildTextureFromTileSet()
{
var colors = new Color[TileTextureSet.Assets.Count][];
for (var index = 0; index < TileTextureSet.Assets.Count; index++)
{
colors[index] = Util.ResizeArray(TileTextureSet.Assets[index].GetAsset().GetPixels(), TileResolution);
}
foreach (var cell in Cells)
{
var texture = (Texture2D) cell.GetComponent<Renderer>().sharedMaterial.mainTexture;
var index = 0;
foreach (var t in cell.Tiles)
{
if (t.TextureIndex >= 0 && t.TextureIndex < colors.Length)
{
var color = colors[t.TextureIndex];
var x = (index%NumberOfTiles)*TileResolution;
var y = (index/NumberOfTiles)*TileResolution;
texture.SetPixels(x, y, TileResolution, TileResolution, color);
}
index++;
}
texture.Apply();
}
}
public Tile GetTile(Vector2 point)
{
var cell = GetCellOrCreate(point);
// pointInCell is the point in the cell you want to draw
var pointInCell = WorldToLocalTile(point);
return cell.GetTileFromPointInCell((int)pointInCell.x, (int)pointInCell.y);
}
public Cell GetCellOrCreate(Vector2 point)
{
// cellIndex is the index of the cell
var cellIndex = point;
cellIndex.x = Util.RoundTo(cellIndex.x + 0.5f, NumberOfTiles);
cellIndex.y = Util.RoundTo(cellIndex.y + 0.5f, NumberOfTiles);
cellIndex = cellIndex / NumberOfTiles;
var groupName = "(" + cellIndex.x + "," + cellIndex.y + ")";
var cell = Cells.Find(element => element.name == groupName);
// If it doesn't exist time to create it
if (cell == null)
{
cell = CellFactory.Create(cellIndex, this);
Cells.Add(cell);
}
return cell;
}
/// <summary>
/// Converts a position in the world to tile coords
/// </summary>
/// <param name="world">Point in the world</param>
/// <returns>World tile coords</returns>
public Vector2 PositionToWorldTile(Vector3 world)
{
var point = new Vector2(world.x, world.z);
point *= NumberOfTiles / SizeOfCell;
point.x = Util.RoundTo(point.x, 1);
point.y = Util.RoundTo(point.y, 1);
return point;
}
/// <summary>
/// Converts world tile coords to local tiles coords in relavent cell
/// </summary>
/// <param name="point">World tile coords</param>
/// <returns>Local tile coords</returns>
public Vector2 WorldToLocalTile(Vector2 point)
{
var pointInCell = point;
pointInCell.x = Util.RoundTo(pointInCell.x + NumberOfTiles / 2f, 1);
pointInCell.y = Util.RoundTo(pointInCell.y + NumberOfTiles / 2f, 1);
pointInCell.x = pointInCell.x % NumberOfTiles;
pointInCell.y = pointInCell.y % NumberOfTiles;
// Need to invert negative numbers
if (pointInCell.x < 0) pointInCell.x = NumberOfTiles + pointInCell.x;
if (pointInCell.y < 0) pointInCell.y = NumberOfTiles + pointInCell.y;
return pointInCell;
}
/// <summary>
/// Finds the local position of a tile anchored to the middle relative to the cell
/// </summary>
/// <param name="point">Local tile position</param>
/// <returns>Local position</returns>
public Vector2 LocalTileToLocalPosition(Vector2 point)
{
point.x = point.x * (SizeOfCell / NumberOfTiles) - SizeOfCell / 2f + HalfTileSize;
point.y = point.y * (SizeOfCell / NumberOfTiles) - SizeOfCell / 2f + HalfTileSize;
return point;
}
public Cell GetCell(Vector2 point)
{
// cellIndex is the index of the cell
var cellIndex = point;
cellIndex.x = Util.RoundTo(cellIndex.x + 0.5f, NumberOfTiles);
cellIndex.y = Util.RoundTo(cellIndex.y + 0.5f, NumberOfTiles);
cellIndex = cellIndex / NumberOfTiles;
var groupName = "(" + cellIndex.x + "," + cellIndex.y + ")";
// Find the cell
return Cells.Find(element => element.name == groupName);
}
public List<Cell> GetNeighbours(Cell c)
{
var neighbours = new [] {new Vector2(-1, -1),
new Vector2(-1, 0),
new Vector2(-1, 1),
new Vector2(0, -1),
new Vector2(0, 1),
new Vector2(1, -1),
new Vector2(1, 0),
new Vector2(1, 1)};
var cells = new List<Cell>();
foreach (var n in neighbours)
{
var cell = GetNeighbour(c, (int)n.x, (int)n.y);
if (cell != null)
cells.Add(cell);
}
return cells;
}
public Cell GetNeighbour(Cell c, int xDir, int yDir)
{
var split = c.name.Split(',');
if (split.Length != 2) throw new UnityException("Plane has been renamed");
var x = int.Parse(split[0].Substring(1, split[0].Length - 1));
var y = int.Parse(split[1].Substring(0, split[1].Length - 1));
var cellToFind = "(" + (x + xDir) + "," + (y + yDir) + ")";
// Find the cell
var cell = Cells.Find(element => element.name == cellToFind);
return cell;
}
#if UNITY_EDITOR
public bool IsDrawGizmo = true;
public void OnDrawGizmosSelected()
{
if (!IsDrawGizmo) return;
var range = SizeOfCell * 4;
var point = new Vector2(Screen.width / 2f, Screen.height / 2f);
var ray = Camera.current.ScreenPointToRay(point);
var layerMask = 1 << LayerMask.NameToLayer("LevelTerrain");
var hits = Physics.RaycastAll(ray, range, layerMask);
foreach (var hit in hits)
{
var mainCell = hit.transform.GetComponent<Cell>();
if (!Cells.Contains(mainCell)) continue;
DrawCellGrid(mainCell);
if (NumberOfTiles < 32)
{
var cells = GetNeighbours(mainCell);
foreach (var cell in cells)
{
DrawCellGrid(cell);
}
}
break;
}
}
private void DrawCellGrid(Cell cell)
{
if (!cell.GetComponent<Renderer>().isVisible) return; // if the renderer isn't visible continue
var mesh = cell.GetComponent<MeshFilter>().sharedMesh;
var numOfVerts = NumberOfTiles + 1;
var color = new Color(1, 1, 1, 0.5f);
Gizmos.color = color;
for (var j = 0; j < numOfVerts; j++)
{
for (var i = 0; i < numOfVerts; i++)
{
var z0 = mesh.vertices[j * numOfVerts + i] + cell.transform.position;
z0.y += 0.01f;
if (i < NumberOfTiles)
{
var x0 = mesh.vertices[j * numOfVerts + i + 1] + cell.transform.position;
x0.y += 0.01f;
Gizmos.DrawLine(z0, x0);
}
if (j < NumberOfTiles)
{
var y0 = mesh.vertices[(j + 1) * numOfVerts + i] + cell.transform.position;
y0.y += 0.01f;
Gizmos.DrawLine(z0, y0);
}
}
}
}
#endif
}
| |
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 Continuum.Master.Host.Areas.HelpPage.ModelDescriptions;
using Continuum.Master.Host.Areas.HelpPage.Models;
namespace Continuum.Master.Host.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);
}
}
}
}
| |
//
// DiscService.cs
//
// Author:
// Alex Launi <[email protected]>
//
// Copyright (C) 2010 Alex Launi
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Mono.Unix;
using Hyena;
using Banshee.ServiceStack;
using Banshee.Configuration;
using Banshee.Preferences;
using Banshee.Hardware;
using Banshee.Gui;
namespace Banshee.Discs
{
public abstract class DiscService : IExtensionService, IDisposable
{
private List<DeviceCommand> unhandled_device_commands;
public DiscService ()
{
}
public virtual void Initialize ()
{
Sources = new Dictionary<string, DiscSource> ();
lock (this) {
// This says Cdrom, but really it means Cdrom in the general Disc device sense.
foreach (ICdromDevice device in ServiceManager.HardwareManager.GetAllCdromDevices ()) {
MapDiscDevice (device);
}
ServiceManager.HardwareManager.DeviceAdded += OnHardwareDeviceAdded;
ServiceManager.HardwareManager.DeviceRemoved += OnHardwareDeviceRemoved;
ServiceManager.HardwareManager.DeviceCommand += OnDeviceCommand;
}
}
public virtual void Dispose ()
{
lock (this) {
ServiceManager.HardwareManager.DeviceAdded -= OnHardwareDeviceAdded;
ServiceManager.HardwareManager.DeviceRemoved -= OnHardwareDeviceRemoved;
ServiceManager.HardwareManager.DeviceCommand -= OnDeviceCommand;
foreach (DiscSource source in Sources.Values) {
ServiceManager.SourceManager.RemoveSource (source);
source.Dispose ();
}
Sources.Clear ();
Sources = null;
}
}
protected Dictionary<string, DiscSource> Sources {
get; private set;
}
protected virtual void MapDiscDevice (ICdromDevice device)
{
lock (this) {
foreach (IVolume volume in device) {
if (volume is IDiscVolume) {
MapDiscVolume ((IDiscVolume) volume);
}
}
}
}
protected virtual void MapDiscVolume (IDiscVolume volume)
{
DiscSource source = null;
lock (this) {
if (Sources.ContainsKey (volume.Uuid)) {
Log.Debug ("Already mapped");
return;
} else if (volume.HasAudio) {
Log.Debug ("Mapping audio cd");
source = new AudioCd.AudioCdSource (this as AudioCd.AudioCdService, new AudioCd.AudioCdDiscModel (volume));
} else if (volume.HasVideo) {
Log.Debug ("Mapping dvd");
source = new Dvd.DvdSource (this, new Dvd.DvdModel (volume));
} else {
Log.Debug ("Neither :(");
return;
}
Sources.Add (volume.Uuid, source);
ServiceManager.SourceManager.AddSource (source);
// If there are any queued device commands, see if they are to be
// handled by this new volume (e.g. --device-activate-play=cdda://sr0/)
try {
if (unhandled_device_commands != null) {
foreach (DeviceCommand command in unhandled_device_commands) {
if (DeviceCommandMatchesSource (source, command)) {
HandleDeviceCommand (source, command.Action);
unhandled_device_commands.Remove (command);
if (unhandled_device_commands.Count == 0) {
unhandled_device_commands = null;
}
break;
}
}
}
} catch (Exception e) {
Log.Exception (e);
}
Log.DebugFormat ("Mapping disc ({0})", volume.Uuid);
}
}
internal void UnmapDiscVolume (string uuid)
{
lock (this) {
if (Sources.ContainsKey (uuid)) {
DiscSource source = Sources[uuid];
source.StopPlayingDisc ();
ServiceManager.SourceManager.RemoveSource (source);
Sources.Remove (uuid);
Log.DebugFormat ("Unmapping disc ({0})", uuid);
}
}
}
private void OnHardwareDeviceAdded (object o, DeviceAddedArgs args)
{
lock (this) {
if (args.Device is ICdromDevice) {
MapDiscDevice ((ICdromDevice)args.Device);
} else if (args.Device is IDiscVolume) {
MapDiscVolume ((IDiscVolume)args.Device);
}
}
}
private void OnHardwareDeviceRemoved (object o, DeviceRemovedArgs args)
{
lock (this) {
UnmapDiscVolume (args.DeviceUuid);
}
}
#region DeviceCommand Handling
protected abstract bool DeviceCommandMatchesSource (DiscSource source, DeviceCommand command);
protected virtual void OnDeviceCommand (object o, DeviceCommand command)
{
lock (this) {
// Check to see if we have an already mapped disc volume that should
// handle this incoming command; if not, queue it for later discs
foreach (var source in Sources.Values) {
if (DeviceCommandMatchesSource (source, command)) {
HandleDeviceCommand (source, command.Action);
return;
}
}
if (unhandled_device_commands == null) {
unhandled_device_commands = new List<DeviceCommand> ();
}
unhandled_device_commands.Add (command);
}
}
protected virtual void HandleDeviceCommand (DiscSource source, DeviceCommandAction action)
{
if ((action & DeviceCommandAction.Activate) != 0) {
ServiceManager.SourceManager.SetActiveSource (source);
}
if ((action & DeviceCommandAction.Play) != 0) {
ServiceManager.PlaybackController.NextSource = source;
if (!ServiceManager.PlayerEngine.IsPlaying ()) {
ServiceManager.PlaybackController.Next ();
}
}
}
#endregion
string IService.ServiceName {
get { return "DiscService"; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace UnityEngine.Experimental.Rendering.LWRP
{
// TODO:
// Fix parametric mesh code so that the vertices, triangle, and color arrays are only recreated when number of sides change
// Change code to update mesh only when it is on screen. Maybe we can recreate a changed mesh if it was on screen last update (in the update), and if it wasn't set it dirty. If dirty, in the OnBecameVisible function create the mesh and clear the dirty flag.
[ExecuteAlways]
sealed public partial class Light2D : MonoBehaviour
{
public enum LightType
{
Parametric = 0,
Freeform = 1,
Sprite = 2,
Point = 3,
Global = 4
}
public enum LightOverlapMode
{
Additive,
AlphaBlend
}
//------------------------------------------------------------------------------------------
// Static/Constants
//------------------------------------------------------------------------------------------
const int k_LightOperationCount = 4; // This must match the array size of m_LightOperations in _2DRendererData.
static List<Light2D>[] s_Lights = SetupLightArray();
static CullingGroup s_CullingGroup;
static BoundingSphere[] s_BoundingSpheres;
static Dictionary<int, Color>[] s_GlobalClearColors = SetupGlobalClearColors();
internal static Dictionary<int, Color>[] globalClearColors { get { return s_GlobalClearColors; } }
//------------------------------------------------------------------------------------------
// Variables/Properties
//------------------------------------------------------------------------------------------
[SerializeField]
[Serialization.FormerlySerializedAs("m_LightProjectionType")]
LightType m_LightType = LightType.Parametric;
LightType m_PreviousLightType = (LightType)LightType.Parametric;
[SerializeField]
[Serialization.FormerlySerializedAs("m_ShapeLightType")]
[Serialization.FormerlySerializedAs("m_LightOperation")]
int m_LightOperationIndex = 0;
[SerializeField]
float m_FalloffCurve = 0.5f;
[ColorUsage(false, false)]
[SerializeField]
[Serialization.FormerlySerializedAs("m_LightColor")]
Color m_Color = Color.white;
Color m_PreviousColor = Color.white;
[SerializeField]
float m_Intensity = 1;
float m_PreviousIntensity = 1;
[SerializeField] float m_LightVolumeOpacity = 0.0f;
[SerializeField] int[] m_ApplyToSortingLayers = new int[1]; // These are sorting layer IDs. If we need to update this at runtime make sure we add code to update global lights
[SerializeField] Sprite m_LightCookieSprite = null;
int m_PreviousLightOperationIndex;
float m_PreviousLightVolumeOpacity;
Sprite m_PreviousLightCookieSprite = null;
Mesh m_Mesh;
int m_LightCullingIndex = -1;
Bounds m_LocalBounds;
public LightType lightType
{
get => m_LightType;
set => m_LightType = value;
}
public int lightOperationIndex => m_LightOperationIndex;
public Color color
{
get { return m_Color; }
set
{
AddGlobalLight(this, true);
m_Color = value;
}
}
public float intensity
{
get { return m_Intensity; }
set
{
AddGlobalLight(this, true);
m_Intensity = value;
}
}
public float volumeOpacity => m_LightVolumeOpacity;
public Sprite lightCookieSprite => m_LightCookieSprite;
public float falloffCurve => m_FalloffCurve;
public bool hasDirection { get { return m_LightType == LightType.Point; } }
//==========================================================================================
// Functions
//==========================================================================================
internal static Dictionary<int, Color>[] SetupGlobalClearColors()
{
Dictionary<int,Color>[] globalClearColors = new Dictionary<int, Color>[k_LightOperationCount];
for(int i=0;i<k_LightOperationCount;i++)
{
globalClearColors[i] = new Dictionary<int, Color>();
}
return globalClearColors;
}
internal static List<Light2D>[] SetupLightArray()
{
List<Light2D>[] retArray = new List<Light2D>[k_LightOperationCount];
for (int i = 0; i < retArray.Length; i++)
retArray[i] = new List<Light2D>();
return retArray;
}
internal static void SetupCulling(Camera camera)
{
if (s_CullingGroup == null)
return;
s_CullingGroup.targetCamera = camera;
int totalLights = 0;
for (int lightOpIndex = 0; lightOpIndex < s_Lights.Length; ++lightOpIndex)
totalLights += s_Lights[lightOpIndex].Count;
if (s_BoundingSpheres == null)
s_BoundingSpheres = new BoundingSphere[Mathf.Max(1024, 2 * totalLights)];
else if (totalLights > s_BoundingSpheres.Length)
s_BoundingSpheres = new BoundingSphere[2 * totalLights];
int currentLightCullingIndex = 0;
for (int lightOpIndex = 0; lightOpIndex < s_Lights.Length; ++lightOpIndex)
{
var lightsPerLightOp = s_Lights[lightOpIndex];
for (int lightIndex = 0; lightIndex < lightsPerLightOp.Count; ++lightIndex)
{
Light2D light = lightsPerLightOp[lightIndex];
if (light == null)
continue;
s_BoundingSpheres[currentLightCullingIndex] = light.GetBoundingSphere();
light.m_LightCullingIndex = currentLightCullingIndex++;
}
}
s_CullingGroup.SetBoundingSpheres(s_BoundingSpheres);
s_CullingGroup.SetBoundingSphereCount(currentLightCullingIndex);
}
internal static List<Light2D> GetLightsByLightOperation(int lightOpIndex)
{
return s_Lights[lightOpIndex];
}
internal int GetTopMostLitLayer()
{
int largestIndex = -1;
int largestLayer = 0;
// TODO: SortingLayer.layers allocates the memory for the returned array.
// An alternative to this is to keep m_ApplyToSortingLayers sorted by using SortingLayer.GetLayerValueFromID in the comparer.
SortingLayer[] layers = SortingLayer.layers;
for(int i = 0; i < m_ApplyToSortingLayers.Length; ++i)
{
for(int layer = layers.Length - 1; layer >= largestLayer; --layer)
{
if (layers[layer].id == m_ApplyToSortingLayers[i])
{
largestIndex = i;
largestLayer = layer;
}
}
}
if (largestIndex >= 0)
return m_ApplyToSortingLayers[largestIndex];
else
return -1;
}
internal void UpdateMesh()
{
GetMesh(true);
}
internal bool IsLitLayer(int layer)
{
return m_ApplyToSortingLayers != null ? Array.IndexOf(m_ApplyToSortingLayers, layer) >= 0 : false;
}
void InsertLight()
{
var lightList = s_Lights[m_LightOperationIndex];
int index = 0;
while (index < lightList.Count && m_ShapeLightOrder > lightList[index].m_ShapeLightOrder)
index++;
lightList.Insert(index, this);
}
void UpdateLightOperation()
{
if (m_LightOperationIndex == m_PreviousLightOperationIndex)
return;
s_Lights[m_PreviousLightOperationIndex].Remove(this);
m_PreviousLightOperationIndex = m_LightOperationIndex;
InsertLight();
}
BoundingSphere GetBoundingSphere()
{
return IsShapeLight() ? GetShapeLightBoundingSphere() : GetPointLightBoundingSphere();
}
internal Mesh GetMesh(bool forceUpdate = false)
{
if (m_Mesh != null && !forceUpdate)
return m_Mesh;
if (m_Mesh == null)
m_Mesh = new Mesh();
Color combinedColor = m_Intensity * m_Color;
switch (m_LightType)
{
case LightType.Freeform:
m_LocalBounds = LightUtility.GenerateShapeMesh(ref m_Mesh, combinedColor, m_ShapePath, m_ShapeLightFalloffOffset, m_LightVolumeOpacity, m_ShapeLightFalloffSize);
break;
case LightType.Parametric:
m_LocalBounds = LightUtility.GenerateParametricMesh(ref m_Mesh, m_ShapeLightRadius, m_ShapeLightFalloffOffset, m_ShapeLightParametricAngleOffset, m_ShapeLightParametricSides, m_ShapeLightFalloffSize, combinedColor, m_LightVolumeOpacity);
break;
case LightType.Sprite:
m_LocalBounds = LightUtility.GenerateSpriteMesh(ref m_Mesh, m_LightCookieSprite, combinedColor, m_LightVolumeOpacity, 1);
break;
case LightType.Point:
m_LocalBounds = LightUtility.GenerateParametricMesh(ref m_Mesh, 1.412135f, Vector2.zero, 0, 4, 0, combinedColor, m_LightVolumeOpacity);
break;
}
return m_Mesh;
}
internal bool IsLightVisible(Camera camera)
{
bool isVisible = (s_CullingGroup == null || s_CullingGroup.IsVisible(m_LightCullingIndex)) && isActiveAndEnabled;
#if UNITY_EDITOR
isVisible &= UnityEditor.SceneManagement.StageUtility.IsGameObjectRenderedByCamera(gameObject, camera);
#endif
return isVisible;
}
static internal void AddGlobalLight(Light2D light2D, bool overwriteColor = false)
{
for (int i = 0; i < light2D.m_ApplyToSortingLayers.Length; i++)
{
int sortingLayer = light2D.m_ApplyToSortingLayers[i];
Dictionary<int, Color> globalColorOp = s_GlobalClearColors[light2D.m_LightOperationIndex];
if (!globalColorOp.ContainsKey(sortingLayer))
{
globalColorOp.Add(sortingLayer, light2D.m_Intensity * light2D.m_Color);
}
else
{
globalColorOp[sortingLayer] = light2D.m_Intensity * light2D.m_Color;
if(!overwriteColor)
Debug.LogError("More than one global light on layer " + SortingLayer.IDToName(sortingLayer) + " for light operation index " + light2D.m_LightOperationIndex);
}
}
}
static internal void RemoveGlobalLight(Light2D light2D)
{
for (int i = 0; i < light2D.m_ApplyToSortingLayers.Length; i++)
{
int sortingLayer = light2D.m_ApplyToSortingLayers[i];
Dictionary<int, Color> globalColorOp = s_GlobalClearColors[light2D.m_LightOperationIndex];
if (globalColorOp.ContainsKey(sortingLayer))
globalColorOp.Remove(sortingLayer);
}
}
private void Awake()
{
if (m_ShapePath == null || m_ShapePath.Length == 0)
m_ShapePath = new Vector3[] { new Vector3(-0.5f, -0.5f), new Vector3(0.5f, -0.5f), new Vector3(0.5f, 0.5f), new Vector3(-0.5f, 0.5f) };
GetMesh();
}
private void OnEnable()
{
// This has to stay in OnEnable() because we need to re-initialize the static variables after a domain reload.
if (s_CullingGroup == null)
{
s_CullingGroup = new CullingGroup();
RenderPipeline.beginCameraRendering += SetupCulling;
}
if (!s_Lights[m_LightOperationIndex].Contains(this))
InsertLight();
m_PreviousLightOperationIndex = m_LightOperationIndex;
if (m_LightType == LightType.Global)
AddGlobalLight(this);
m_PreviousLightType = m_LightType;
}
private void OnDisable()
{
bool anyLightLeft = false;
for (int i = 0; i < s_Lights.Length; ++i)
{
s_Lights[i].Remove(this);
if (s_Lights[i].Count > 0)
anyLightLeft = true;
}
if (!anyLightLeft && s_CullingGroup != null)
{
s_CullingGroup.Dispose();
s_CullingGroup = null;
RenderPipeline.beginCameraRendering -= SetupCulling;
}
if (m_LightType == LightType.Global)
RemoveGlobalLight(this);
}
internal List<Vector2> GetFalloffShape()
{
List<Vector2> shape = LightUtility.GetFeatheredShape(m_ShapePath, m_ShapeLightFalloffSize);
return shape;
}
private void LateUpdate()
{
UpdateLightOperation();
bool rebuildMesh = false;
// Sorting. InsertLight() will make sure the lights are sorted.
if (LightUtility.CheckForChange(m_ShapeLightOrder, ref m_PreviousShapeLightOrder))
{
s_Lights[(int)m_LightOperationIndex].Remove(this);
InsertLight();
}
if (m_LightType != m_PreviousLightType)
{
if(m_PreviousLightType == LightType.Global)
RemoveGlobalLight(this);
if (m_LightType == LightType.Global)
AddGlobalLight(this);
else
rebuildMesh = true;
m_PreviousLightType = m_LightType;
}
// Mesh Rebuilding
rebuildMesh |= LightUtility.CheckForChange(m_Color, ref m_PreviousColor);
rebuildMesh |= LightUtility.CheckForChange(m_Intensity, ref m_PreviousIntensity);
rebuildMesh |= LightUtility.CheckForChange(m_ShapeLightFalloffSize, ref m_PreviousShapeLightFalloffSize);
rebuildMesh |= LightUtility.CheckForChange(m_ShapeLightRadius, ref m_PreviousShapeLightRadius);
rebuildMesh |= LightUtility.CheckForChange(m_ShapeLightParametricSides, ref m_PreviousShapeLightParametricSides);
rebuildMesh |= LightUtility.CheckForChange(m_LightVolumeOpacity, ref m_PreviousLightVolumeOpacity);
rebuildMesh |= LightUtility.CheckForChange(m_ShapeLightParametricAngleOffset, ref m_PreviousShapeLightParametricAngleOffset);
rebuildMesh |= LightUtility.CheckForChange(m_LightCookieSprite, ref m_PreviousLightCookieSprite);
#if UNITY_EDITOR
rebuildMesh |= LightUtility.CheckForChange(GetShapePathHash(), ref m_PreviousShapePathHash);
#endif
if (rebuildMesh)
UpdateMesh();
}
private void OnDrawGizmos()
{
Gizmos.DrawIcon(transform.position, "PointLight Gizmo", 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.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents a source code document that is part of a project.
/// It provides access to the source text, parsed syntax tree and the corresponding semantic model.
/// </summary>
[DebuggerDisplay("{GetDebuggerDisplay(),nq}")]
public partial class Document : TextDocument
{
private WeakReference<SemanticModel> _model;
private Task<SyntaxTree> _syntaxTreeResultTask;
internal Document(Project project, DocumentState state) :
base(project, state)
{
}
private DocumentState DocumentState => (DocumentState)State;
/// <summary>
/// The kind of source code this document contains.
/// </summary>
public SourceCodeKind SourceCodeKind
{
get
{
return DocumentState.SourceCodeKind;
}
}
/// <summary>
/// Get the current syntax tree for the document if the text is already loaded and the tree is already parsed.
/// In almost all cases, you should call <see cref="GetSyntaxTreeAsync"/> to fetch the tree, which will parse the tree
/// if it's not already parsed.
/// </summary>
public bool TryGetSyntaxTree(out SyntaxTree syntaxTree)
{
// if we already have cache, use it
if (_syntaxTreeResultTask != null)
{
syntaxTree = _syntaxTreeResultTask.Result;
}
if (!DocumentState.TryGetSyntaxTree(out syntaxTree))
{
return false;
}
// cache the result if it is not already cached
if (_syntaxTreeResultTask == null)
{
var result = Task.FromResult(syntaxTree);
Interlocked.CompareExchange(ref _syntaxTreeResultTask, result, null);
}
return true;
}
/// <summary>
/// Get the current syntax tree version for the document if the text is already loaded and the tree is already parsed.
/// In almost all cases, you should call <see cref="GetSyntaxVersionAsync"/> to fetch the version, which will load the tree
/// if it's not already available.
/// </summary>
public bool TryGetSyntaxVersion(out VersionStamp version)
{
version = default(VersionStamp);
VersionStamp textVersion;
if (!this.TryGetTextVersion(out textVersion))
{
return false;
}
var projectVersion = this.Project.Version;
version = textVersion.GetNewerVersion(projectVersion);
return true;
}
/// <summary>
/// Gets the version of the document's top level signature if it is already loaded and available.
/// </summary>
internal bool TryGetTopLevelChangeTextVersion(out VersionStamp version)
{
return DocumentState.TryGetTopLevelChangeTextVersion(out version);
}
/// <summary>
/// Gets the version of the syntax tree. This is generally the newer of the text version and the project's version.
/// </summary>
public async Task<VersionStamp> GetSyntaxVersionAsync(CancellationToken cancellationToken = default(CancellationToken))
{
var textVersion = await this.GetTextVersionAsync(cancellationToken).ConfigureAwait(false);
var projectVersion = this.Project.Version;
return textVersion.GetNewerVersion(projectVersion);
}
/// <summary>
/// <code>true</code> if this Document supports providing data through the
/// <see cref="GetSyntaxTreeAsync"/> and <see cref="GetSyntaxRootAsync"/> methods.
///
/// If <code>false</code> then these methods will return <code>null</code> instead.
/// </summary>
public bool SupportsSyntaxTree
{
get
{
return DocumentState.SupportsSyntaxTree;
}
}
/// <summary>
/// <code>true</code> if this Document supports providing data through the
/// <see cref="GetSemanticModelAsync"/> method.
///
/// If <code>false</code> then this method will return <code>null</code> instead.
/// </summary>
public bool SupportsSemanticModel
{
get
{
return this.SupportsSyntaxTree && this.Project.SupportsCompilation;
}
}
/// <summary>
/// Gets the <see cref="SyntaxTree" /> for this document asynchronously.
/// </summary>
public Task<SyntaxTree> GetSyntaxTreeAsync(CancellationToken cancellationToken = default(CancellationToken))
{
// If the language doesn't support getting syntax trees for a document, then bail out immediately.
if (!this.SupportsSyntaxTree)
{
return SpecializedTasks.Default<SyntaxTree>();
}
// if we have a cached result task use it
if (_syntaxTreeResultTask != null)
{
return _syntaxTreeResultTask;
}
// check to see if we already have the tree before actually going async
SyntaxTree tree;
if (TryGetSyntaxTree(out tree))
{
// stash a completed result task for this value for the next request (to reduce extraneous allocations of tasks)
// don't use the actual async task because it depends on a specific cancellation token
// its okay to cache the task and hold onto the SyntaxTree, because the DocumentState already keeps the SyntaxTree alive.
Interlocked.CompareExchange(ref _syntaxTreeResultTask, Task.FromResult(tree), null);
return _syntaxTreeResultTask;
}
// do it async for real.
return DocumentState.GetSyntaxTreeAsync(cancellationToken);
}
internal SyntaxTree GetSyntaxTreeSynchronously(CancellationToken cancellationToken)
{
if (!this.SupportsSyntaxTree)
{
return null;
}
return DocumentState.GetSyntaxTree(cancellationToken);
}
/// <summary>
/// Gets the root node of the current syntax tree if the syntax tree has already been parsed and the tree is still cached.
/// In almost all cases, you should call <see cref="GetSyntaxRootAsync"/> to fetch the root node, which will parse
/// the document if necessary.
/// </summary>
public bool TryGetSyntaxRoot(out SyntaxNode root)
{
root = null;
SyntaxTree tree;
return this.TryGetSyntaxTree(out tree) && tree.TryGetRoot(out root) && root != null;
}
/// <summary>
/// Gets the root node of the syntax tree asynchronously.
/// </summary>
public async Task<SyntaxNode> GetSyntaxRootAsync(CancellationToken cancellationToken = default(CancellationToken))
{
if (!this.SupportsSyntaxTree)
{
return null;
}
var tree = await this.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
return await tree.GetRootAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Only for features that absolutely must run synchronously (probably because they're
/// on the UI thread). Right now, the only feature this is for is Outlining as VS will
/// block on that feature from the UI thread when a document is opened.
/// </summary>
internal SyntaxNode GetSyntaxRootSynchronously(CancellationToken cancellationToken)
{
if (!this.SupportsSyntaxTree)
{
return null;
}
var tree = this.GetSyntaxTreeSynchronously(cancellationToken);
return tree.GetRoot(cancellationToken);
}
/// <summary>
/// Gets the current semantic model for this document if the model is already computed and still cached.
/// In almost all cases, you should call <see cref="GetSemanticModelAsync"/>, which will compute the semantic model
/// if necessary.
/// </summary>
public bool TryGetSemanticModel(out SemanticModel semanticModel)
{
semanticModel = null;
return _model != null && _model.TryGetTarget(out semanticModel);
}
/// <summary>
/// Gets the semantic model for this document asynchronously.
/// </summary>
public async Task<SemanticModel> GetSemanticModelAsync(CancellationToken cancellationToken = default(CancellationToken))
{
try
{
if (!this.SupportsSemanticModel)
{
return null;
}
SemanticModel semanticModel;
if (this.TryGetSemanticModel(out semanticModel))
{
return semanticModel;
}
var syntaxTree = await this.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var compilation = await this.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
var result = compilation.GetSemanticModel(syntaxTree);
Contract.ThrowIfNull(result);
// first try set the cache if it has not been set
var original = Interlocked.CompareExchange(ref _model, new WeakReference<SemanticModel>(result), null);
// okay, it is first time.
if (original == null)
{
return result;
}
// it looks like someone has set it. try to reuse same semantic model
if (original.TryGetTarget(out semanticModel))
{
return semanticModel;
}
// it looks like cache is gone. reset the cache.
original.SetTarget(result);
return result;
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
/// <summary>
/// Creates a new instance of this document updated to have the source code kind specified.
/// </summary>
public Document WithSourceCodeKind(SourceCodeKind kind)
{
return this.Project.Solution.WithDocumentSourceCodeKind(this.Id, kind).GetDocument(this.Id);
}
/// <summary>
/// Creates a new instance of this document updated to have the text specified.
/// </summary>
public Document WithText(SourceText text)
{
return this.Project.Solution.WithDocumentText(this.Id, text, PreservationMode.PreserveIdentity).GetDocument(this.Id);
}
/// <summary>
/// Creates a new instance of this document updated to have a syntax tree rooted by the specified syntax node.
/// </summary>
public Document WithSyntaxRoot(SyntaxNode root)
{
return this.Project.Solution.WithDocumentSyntaxRoot(this.Id, root, PreservationMode.PreserveIdentity).GetDocument(this.Id);
}
/// <summary>
/// Get the text changes between this document and a prior version of the same document.
/// The changes, when applied to the text of the old document, will produce the text of the current document.
/// </summary>
public async Task<IEnumerable<TextChange>> GetTextChangesAsync(Document oldDocument, CancellationToken cancellationToken = default(CancellationToken))
{
try
{
using (Logger.LogBlock(FunctionId.Workspace_Document_GetTextChanges, this.Name, cancellationToken))
{
if (oldDocument == this)
{
// no changes
return SpecializedCollections.EmptyEnumerable<TextChange>();
}
if (this.Id != oldDocument.Id)
{
throw new ArgumentException(WorkspacesResources.The_specified_document_is_not_a_version_of_this_document);
}
// first try to see if text already knows its changes
IList<TextChange> textChanges = null;
SourceText text;
SourceText oldText;
if (this.TryGetText(out text) && oldDocument.TryGetText(out oldText))
{
if (text == oldText)
{
return SpecializedCollections.EmptyEnumerable<TextChange>();
}
var container = text.Container;
if (container != null)
{
textChanges = text.GetTextChanges(oldText).ToList();
// if changes are significant (not the whole document being replaced) then use these changes
if (textChanges.Count > 1 || (textChanges.Count == 1 && textChanges[0].Span != new TextSpan(0, oldText.Length)))
{
return textChanges;
}
}
}
// get changes by diffing the trees
if (this.SupportsSyntaxTree)
{
var tree = await this.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var oldTree = await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
return tree.GetChanges(oldTree);
}
text = await this.GetTextAsync(cancellationToken).ConfigureAwait(false);
oldText = await oldDocument.GetTextAsync(cancellationToken).ConfigureAwait(false);
return text.GetTextChanges(oldText).ToList();
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
/// <summary>
/// Gets the list of <see cref="DocumentId"/>s that are linked to this
/// <see cref="Document" />. <see cref="Document"/>s are considered to be linked if they
/// share the same <see cref="TextDocument.FilePath" />. This <see cref="DocumentId"/> is excluded from the
/// result.
/// </summary>
public ImmutableArray<DocumentId> GetLinkedDocumentIds()
{
var documentIdsWithPath = this.Project.Solution.GetDocumentIdsWithFilePath(this.FilePath);
var filteredDocumentIds = this.Project.Solution.FilterDocumentIdsByLanguage(documentIdsWithPath, this.Project.Language).ToImmutableArray();
return filteredDocumentIds.Remove(this.Id);
}
/// <summary>
/// Creates a branched version of this document that has its semantic model frozen in whatever state it is available at the time,
/// assuming a background process is constructing the semantics asynchronously. Repeated calls to this method may return
/// documents with increasingly more complete semantics.
///
/// Use this method to gain access to potentially incomplete semantics quickly.
/// </summary>
internal async Task<Document> WithFrozenPartialSemanticsAsync(CancellationToken cancellationToken)
{
var solution = this.Project.Solution;
var workspace = solution.Workspace;
// only produce doc with frozen semantics if this document is part of the workspace's
// primary branch and there is actual background compilation going on, since w/o
// background compilation the semantics won't be moving toward completeness. Also,
// ensure that the project that this document is part of actually supports compilations,
// as partial semantics don't make sense otherwise.
if (solution.BranchId == workspace.PrimaryBranchId &&
workspace.PartialSemanticsEnabled &&
this.Project.SupportsCompilation)
{
var newSolution = await this.Project.Solution.WithFrozenPartialCompilationIncludingSpecificDocumentAsync(this.Id, cancellationToken).ConfigureAwait(false);
return newSolution.GetDocument(this.Id);
}
else
{
return this;
}
}
private string GetDebuggerDisplay()
{
return this.Name;
}
private AsyncLazy<DocumentOptionSet> _cachedOptions;
/// <summary>
/// Returns the options that should be applied to this document. This consists of global options from <see cref="Solution.Options"/>,
/// merged with any settings the user has specified at the document levels.
/// </summary>
/// <remarks>
/// This method is async because this may require reading other files. In files that are already open, this is expected to be cheap and complete synchronously.
/// </remarks>
public Task<DocumentOptionSet> GetOptionsAsync(CancellationToken cancellationToken = default(CancellationToken))
{
if (_cachedOptions == null)
{
var newAsyncLazy = new AsyncLazy<DocumentOptionSet>(async c =>
{
var optionsService = Project.Solution.Workspace.Services.GetRequiredService<IOptionService>();
var optionSet = await optionsService.GetUpdatedOptionSetForDocumentAsync(this, Project.Solution.Options, c).ConfigureAwait(false);
return new DocumentOptionSet(optionSet, Project.Language);
}, cacheResult: true);
Interlocked.CompareExchange(ref _cachedOptions, newAsyncLazy, comparand: null);
}
return _cachedOptions.GetValueAsync(cancellationToken);
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using FileHelpers;
namespace FileHelpersSamples
{
/// <summary>
/// Run the engine in Async mode to speed
/// the processing times of the file up.
/// </summary>
public class frmEasySampleAsync : frmFather
{
private TextBox txtClass;
private Button cmdRun;
private Label label2;
private Label label1;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.TextBox txtOut;
/// <summary>
/// Required designer variable.
/// </summary>
private Container components = null;
public frmEasySampleAsync()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing) {
if (components != null)
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources =
new System.ComponentModel.ComponentResourceManager(typeof (frmEasySampleAsync));
this.txtClass = new System.Windows.Forms.TextBox();
this.cmdRun = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.textBox1 = new System.Windows.Forms.TextBox();
this.txtOut = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// pictureBox3
//
//
// txtClass
//
this.txtClass.Font = new System.Drawing.Font("Courier New",
8.25F,
System.Drawing.FontStyle.Regular,
System.Drawing.GraphicsUnit.Point,
((byte) (0)));
this.txtClass.Location = new System.Drawing.Point(8, 288);
this.txtClass.Multiline = true;
this.txtClass.Name = "txtClass";
this.txtClass.ReadOnly = true;
this.txtClass.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtClass.Size = new System.Drawing.Size(328, 160);
this.txtClass.TabIndex = 0;
this.txtClass.Text = resources.GetString("txtClass.Text");
this.txtClass.WordWrap = false;
//
// cmdRun
//
this.cmdRun.BackColor = System.Drawing.Color.FromArgb(((int) (((byte) (0)))),
((int) (((byte) (0)))),
((int) (((byte) (110)))));
this.cmdRun.Font = new System.Drawing.Font("Tahoma",
9.75F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((byte) (0)));
this.cmdRun.ForeColor = System.Drawing.Color.White;
this.cmdRun.Location = new System.Drawing.Point(336, 8);
this.cmdRun.Name = "cmdRun";
this.cmdRun.Size = new System.Drawing.Size(152, 32);
this.cmdRun.TabIndex = 0;
this.cmdRun.Text = "RUN >>";
this.cmdRun.UseVisualStyleBackColor = false;
this.cmdRun.Click += new System.EventHandler(this.cmdRun_Click);
//
// label2
//
this.label2.BackColor = System.Drawing.Color.Transparent;
this.label2.Font = new System.Drawing.Font("Tahoma",
9F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((byte) (0)));
this.label2.ForeColor = System.Drawing.Color.White;
this.label2.Location = new System.Drawing.Point(8, 272);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(216, 16);
this.label2.TabIndex = 7;
this.label2.Text = "Code of the Mapping Class";
//
// label1
//
this.label1.BackColor = System.Drawing.Color.Transparent;
this.label1.Font = new System.Drawing.Font("Tahoma",
9F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((byte) (0)));
this.label1.ForeColor = System.Drawing.Color.White;
this.label1.Location = new System.Drawing.Point(344, 272);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(216, 16);
this.label1.TabIndex = 8;
this.label1.Text = "Console Output";
//
// label4
//
this.label4.BackColor = System.Drawing.Color.Transparent;
this.label4.Font = new System.Drawing.Font("Tahoma",
9F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((byte) (0)));
this.label4.ForeColor = System.Drawing.Color.White;
this.label4.Location = new System.Drawing.Point(8, 64);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(152, 16);
this.label4.TabIndex = 10;
this.label4.Text = "Code to Read the File";
//
// textBox1
//
this.textBox1.Font = new System.Drawing.Font("Courier New",
8.25F,
System.Drawing.FontStyle.Regular,
System.Drawing.GraphicsUnit.Point,
((byte) (0)));
this.textBox1.Location = new System.Drawing.Point(8, 80);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.ReadOnly = true;
this.textBox1.Size = new System.Drawing.Size(656, 184);
this.textBox1.TabIndex = 11;
this.textBox1.Text = resources.GetString("textBox1.Text");
this.textBox1.WordWrap = false;
//
// txtOut
//
this.txtOut.Font = new System.Drawing.Font("Courier New",
8.25F,
System.Drawing.FontStyle.Regular,
System.Drawing.GraphicsUnit.Point,
((byte) (0)));
this.txtOut.Location = new System.Drawing.Point(344, 288);
this.txtOut.Multiline = true;
this.txtOut.Name = "txtOut";
this.txtOut.ReadOnly = true;
this.txtOut.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtOut.Size = new System.Drawing.Size(328, 160);
this.txtOut.TabIndex = 12;
this.txtOut.WordWrap = false;
//
// frmEasySampleAsync
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
this.ClientSize = new System.Drawing.Size(680, 480);
this.Controls.Add(this.txtOut);
this.Controls.Add(this.label4);
this.Controls.Add(this.label1);
this.Controls.Add(this.label2);
this.Controls.Add(this.cmdRun);
this.Controls.Add(this.txtClass);
this.Controls.Add(this.textBox1);
this.Name = "frmEasySampleAsync";
this.Text = "FileHelpers - Easy Example";
this.Controls.SetChildIndex(this.textBox1, 0);
this.Controls.SetChildIndex(this.txtClass, 0);
this.Controls.SetChildIndex(this.cmdRun, 0);
this.Controls.SetChildIndex(this.label2, 0);
this.Controls.SetChildIndex(this.label1, 0);
this.Controls.SetChildIndex(this.label4, 0);
this.Controls.SetChildIndex(this.txtOut, 0);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
/// <summary>
/// Run the Async engine with a vertical bar file
/// </summary>
private void cmdRun_Click(object sender, EventArgs e)
{
txtOut.Text = string.Empty;
var engine = new FileHelperAsyncEngine<CustomersVerticalBar>();
engine.BeginReadString(TestData.mCustomersTest);
// The Async engines are IEnumerable
foreach (CustomersVerticalBar cust in engine) {
// your code here
txtOut.Text += cust.CustomerID + " - " + cust.ContactTitle + Environment.NewLine;
}
engine.Close();
}
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
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.Collections.Generic;
namespace System.Threading
{
/// <summary>
/// ReaderWriterLockExtensions
/// </summary>
public static class ReaderWriterLockExtensions
{
#if !SqlServer
#region THREADED
/// <summary>
/// Threadeds the atomic method.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TList">The type of the list.</typeparam>
/// <param name="rwLock">The reader writer lock.</param>
/// <param name="list">The list.</param>
/// <param name="key">The key.</param>
/// <param name="method">The method.</param>
public static void ThreadedAtomicMethod<TKey, TList>(this ReaderWriterLockSlim rwLock, TList list, TKey key, Action method)
where TList : IList<TKey>
{
// blocking calls
throw new NotImplementedException();
}
/// <summary>
/// Threadeds the atomic method.
/// </summary>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TList">The type of the list.</typeparam>
/// <param name="rwLock">The reader writer lock.</param>
/// <param name="list">The list.</param>
/// <param name="key">The key.</param>
/// <param name="method">The method.</param>
/// <returns></returns>
public static TValue ThreadedAtomicMethod<TValue, TKey, TList>(this ReaderWriterLockSlim rwLock, TList list, TKey key, Func<TValue> method)
where TList : IList<TKey>
{
// blocking calls
throw new NotImplementedException();
}
/// <summary>
/// Threadeds the atomic method async.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TList">The type of the list.</typeparam>
/// <param name="rwLock">The reader writer lock.</param>
/// <param name="list">The list.</param>
/// <param name="key">The key.</param>
/// <param name="method">The method.</param>
public static void ThreadedAtomicMethodAsync<TKey, TList>(this ReaderWriterLockSlim rwLock, TList list, TKey key, Action method)
where TList : IList<TKey>
{
rwLock.EnterUpgradeableReadLock();
try
{
if (!list.Contains(key))
{
// set to running
rwLock.EnterWriteLock();
try
{
if (list.Contains(key))
return;
list.Add(key);
}
finally { rwLock.ExitWriteLock(); }
// run queue
try { method(); }
catch
{
list.Remove(key);
throw;
}
// set to idle
rwLock.EnterWriteLock();
try
{
//if (!list.Contains(key))
// return default(TValue);
list.Remove(key);
}
finally { rwLock.ExitWriteLock(); }
return;
}
}
finally { rwLock.ExitUpgradeableReadLock(); }
return;
}
/// <summary>
/// Threadeds the atomic method async.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TList">The type of the list.</typeparam>
/// <param name="rwLock">The reader writer lock.</param>
/// <param name="list">The list.</param>
/// <param name="key">The key.</param>
/// <param name="method">The method.</param>
/// <param name="contention">The contention.</param>
public static void ThreadedAtomicMethodAsync<TKey, TList>(this ReaderWriterLockSlim rwLock, TList list, TKey key, Action method, Action contention)
where TList : IList<TKey>
{
rwLock.EnterUpgradeableReadLock();
try
{
if (!list.Contains(key))
{
// set to running
rwLock.EnterWriteLock();
try
{
if (list.Contains(key))
{
contention();
return;
}
list.Add(key);
}
finally { rwLock.ExitWriteLock(); }
// run queue
try { method(); }
catch
{
list.Remove(key);
throw;
}
// set to idle
rwLock.EnterWriteLock();
try
{
//if (!list.Contains(key))
// return default(TValue);
list.Remove(key);
}
finally { rwLock.ExitWriteLock(); }
return;
}
}
finally { rwLock.ExitUpgradeableReadLock(); }
contention();
}
/// <summary>
/// Threadeds the atomic method.
/// </summary>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TList">The type of the list.</typeparam>
/// <param name="rwLock">The reader writer lock.</param>
/// <param name="list">The list.</param>
/// <param name="key">The key.</param>
/// <param name="method">The method.</param>
/// <returns></returns>
public static TValue ThreadedAtomicMethodAsync<TValue, TKey, TList>(this ReaderWriterLockSlim rwLock, TList list, TKey key, Func<TValue> method)
where TList : IList<TKey>
{
rwLock.EnterUpgradeableReadLock();
try
{
if (!list.Contains(key))
{
// set to running
rwLock.EnterWriteLock();
try
{
if (list.Contains(key))
return default(TValue);
list.Add(key);
}
finally { rwLock.ExitWriteLock(); }
// run queue
TValue value;
try { value = method(); }
catch
{
list.Remove(key);
throw;
}
// set to idle
rwLock.EnterWriteLock();
try
{
//if (!list.Contains(key))
// return default(TValue);
list.Remove(key);
}
finally { rwLock.ExitWriteLock(); }
return value;
}
}
finally { rwLock.ExitUpgradeableReadLock(); }
return default(TValue);
}
/// <summary>
/// Threadeds the atomic method async.
/// </summary>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TList">The type of the list.</typeparam>
/// <param name="rwLock">The reader writer lock.</param>
/// <param name="list">The list.</param>
/// <param name="key">The key.</param>
/// <param name="method">The method.</param>
/// <param name="contention">The contention.</param>
/// <returns></returns>
public static TValue ThreadedAtomicMethodAsync<TValue, TKey, TList>(this ReaderWriterLockSlim rwLock, TList list, TKey key, Func<TValue> method, Func<TValue> contention)
where TList : IList<TKey>
{
rwLock.EnterUpgradeableReadLock();
try
{
if (!list.Contains(key))
{
// set to running
rwLock.EnterWriteLock();
try
{
if (list.Contains(key))
return contention();
list.Add(key);
}
finally { rwLock.ExitWriteLock(); }
// run queue
TValue value;
try { value = method(); }
catch
{
list.Remove(key);
throw;
}
// set to idle
rwLock.EnterWriteLock();
try
{
//if (!list.Contains(key))
// return default(TValue);
list.Remove(key);
}
finally { rwLock.ExitWriteLock(); }
return value;
}
}
finally { rwLock.ExitUpgradeableReadLock(); }
return contention();
}
/// <summary>
/// Threadeds the get with create.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="rwLock">The reader writer lock.</param>
/// <param name="value">The value.</param>
/// <param name="builder">The builder.</param>
/// <returns></returns>
public static T ThreadedGetWithCreate<T>(this ReaderWriterLockSlim rwLock, ref T value, Func<T> builder)
{
rwLock.EnterUpgradeableReadLock();
try
{
if (value == null)
{
rwLock.EnterWriteLock();
try
{
if (value == null)
// create
value = builder();
}
finally { rwLock.ExitWriteLock(); }
}
}
finally { rwLock.ExitUpgradeableReadLock(); }
return value;
}
/// <summary>
/// Threadeds the get with create.
/// </summary>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="THash">The type of the hash.</typeparam>
/// <param name="rwLock">The reader writer lock.</param>
/// <param name="hash">The hash.</param>
/// <param name="key">The key.</param>
/// <param name="builder">The builder.</param>
/// <returns></returns>
public static TValue ThreadedGetWithCreate<TValue, TKey, THash>(this ReaderWriterLockSlim rwLock, THash hash, TKey key, Func<TKey, TValue> builder)
where THash : IDictionary<TKey, TValue>
{
rwLock.EnterUpgradeableReadLock();
try
{
TValue value;
if (!hash.TryGetValue(key, out value))
{
rwLock.EnterWriteLock();
try
{
if (!hash.TryGetValue(key, out value))
{
// create
value = builder(key);
hash.Add(key, value);
}
}
finally { rwLock.ExitWriteLock(); }
}
return value;
}
finally { rwLock.ExitUpgradeableReadLock(); }
}
/// <summary>
/// Threadeds the remove.
/// </summary>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="THash">The type of the hash.</typeparam>
/// <param name="rwLock">The reader writer lock.</param>
/// <param name="hash">The hash.</param>
/// <param name="key">The key.</param>
public static void ThreadedRemove<TValue, TKey, THash>(this ReaderWriterLockSlim rwLock, THash hash, TKey key)
where THash : IDictionary<TKey, TValue>
{
rwLock.EnterUpgradeableReadLock();
try
{
if (hash.ContainsKey(key))
{
rwLock.EnterWriteLock();
try
{
if (hash.ContainsKey(key))
// remove
hash.Remove(key);
}
finally { rwLock.ExitWriteLock(); }
}
}
finally { rwLock.ExitUpgradeableReadLock(); }
}
#endregion
#else
#region SQL THREADED
/// <summary>
/// Threadeds the get with create.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="rwLock">The reader writer lock.</param>
/// <param name="value">The value.</param>
/// <param name="builder">The builder.</param>
/// <returns></returns>
public static T ThreadedGetWithCreate<T>(object rwLock, ref T value, Func<T> builder)
{
//readerWriterLock.AcquireReaderLock(System.Threading.Timeout.Infinite);
try
{
if (value == null)
{
//System.Threading.LockCookie lockCookie = readerWriterLock.UpgradeToWriterLock(System.Threading.Timeout.Infinite);
try
{
if (value == null)
{
// create
value = builder();
}
}
finally
{
//readerWriterLock.DowngradeFromWriterLock(ref lockCookie);
}
}
}
finally
{
//readerWriterLock.ReleaseReaderLock();
}
return value;
}
/// <summary>
/// Threadeds the get with create.
/// </summary>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="THash">The type of the hash.</typeparam>
/// <param name="rwLock">The reader writer lock.</param>
/// <param name="hash">The hash.</param>
/// <param name="key">The key.</param>
/// <param name="builder">The builder.</param>
/// <returns></returns>
public static TValue ThreadedGetWithCreate<TValue, TKey, THash>(object rwLock, THash hash, TKey key, Func<TKey, TValue> builder)
where THash : IDictionary<TKey, TValue>
{
//readerWriterLock.AcquireReaderLock(System.Threading.Timeout.Infinite);
try
{
TValue value;
if (!hash.TryGetValue(key, out value))
{
//System.Threading.LockCookie lockCookie = readerWriterLock.UpgradeToWriterLock(System.Threading.Timeout.Infinite);
try
{
if (!hash.TryGetValue(key, out value))
{
// create
value = builder(key);
hash.Add(key, value);
}
}
finally
{
//readerWriterLock.DowngradeFromWriterLock(ref lockCookie);
}
}
return value;
}
finally
{
//readerWriterLock.ReleaseReaderLock();
}
}
/// <summary>
/// Threadeds the remove.
/// </summary>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="THash">The type of the hash.</typeparam>
/// <param name="rwLock">The reader writer lock.</param>
/// <param name="hash">The hash.</param>
/// <param name="key">The key.</param>
public static void ThreadedRemove<TValue, TKey, THash>(object rwLock, THash hash, TKey key)
where THash : IDictionary<TKey, TValue>
{
//readerWriterLock.AcquireReaderLock(System.Threading.Timeout.Infinite);
try
{
if (hash.ContainsKey(key))
{
//System.Threading.LockCookie lockCookie = readerWriterLock.UpgradeToWriterLock(System.Threading.Timeout.Infinite);
try
{
if (hash.ContainsKey(key))
{
// remove
hash.Remove(key);
}
}
finally
{
//readerWriterLock.DowngradeFromWriterLock(ref lockCookie);
}
}
}
finally
{
//readerWriterLock.ReleaseReaderLock();
}
}
#endregion
#endif
}
}
| |
#region Header
// --------------------------------------------------------------------------
// Tethys.Silverlight
// ==========================================================================
//
// This library contains common code for Windows Forms applications.
//
// ===========================================================================
//
// <copyright file="CenteredMessageBox.cs" company="Tethys">
// Copyright 1998-2015 by Thomas Graf
// All rights reserved.
// Licensed under the Apache License, Version 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.
// </copyright>
//
// System ... Microsoft .Net Framework 4
// Tools .... Microsoft Visual Studio 2013
//
// ---------------------------------------------------------------------------
#endregion
namespace Tethys.Forms
{
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Tethys.Win32;
/// <summary>
/// CenteredMessageBox implements a message box that is always centered over
/// the parent window like the normal Win32 MessageBox.
/// </summary>
public static class CenteredMessageBox
{
#region SHOW() FUNCTIONS
/// <summary>
/// Displays a message box with specified text.
/// </summary>
/// <param name="owner">Window parent (owner).</param>
/// <param name="text">The text to display in the message box.</param>
/// <returns>One of the DialogResult values.</returns>
[SuppressMessage("Microsoft.Globalization",
"CA1300:SpecifyMessageBoxOptions",
Justification = "Not relevant here!")]
public static DialogResult Show(IWin32Window owner, string text)
{
Init(string.Empty, owner);
return MessageBox.Show(owner, text);
} // Show()
/// <summary>
/// Displays a message box with specified text and caption.
/// </summary>
/// <param name="owner">Window parent (owner).</param>
/// <param name="text">The text to display in the message box. </param>
/// <param name="caption">The text to display in the title bar of the
/// message box. </param>
/// <returns>One of the DialogResult values.</returns>
[SuppressMessage("Microsoft.Globalization",
"CA1300:SpecifyMessageBoxOptions",
Justification = "Not relevant here!")]
public static DialogResult Show(IWin32Window owner, string text,
string caption)
{
Init(caption, owner);
return MessageBox.Show(owner, text, caption);
} // Show()
/// <summary>
/// Displays a message box with specified text, caption, and buttons.
/// </summary>
/// <param name="owner">Window parent (owner).</param>
/// <param name="text">The text to display in the message box. </param>
/// <param name="caption">The text to display in the title bar of the
/// message box. </param>
/// <param name="buttons">One of the MessageBoxButtons that specifies
/// which buttons to display in the message box.</param>
/// <returns>One of the DialogResult values.</returns>
[SuppressMessage("Microsoft.Globalization",
"CA1300:SpecifyMessageBoxOptions",
Justification = "Not relevant here!")]
public static DialogResult Show(IWin32Window owner, string text,
string caption,
MessageBoxButtons buttons)
{
Init(caption, owner);
return MessageBox.Show(owner, text, caption, buttons);
} // Show()
/// <summary>
/// Displays a message box with specified text, caption, buttons, and
/// icon.
/// </summary>
/// <param name="owner">Window parent (owner).</param>
/// <param name="text">The text to display in the message box. </param>
/// <param name="caption">The text to display in the title bar of the
/// message box. </param>
/// <param name="buttons">One of the MessageBoxButtons that specifies
/// which buttons to display in the message box.</param>
/// <param name="icon">One of the MessageBoxIcon values that specifies
/// which icon to display in the message box. </param>
/// <returns>One of the DialogResult values.</returns>
[SuppressMessage("Microsoft.Globalization",
"CA1300:SpecifyMessageBoxOptions", Justification = "Not relevant here!")]
public static DialogResult Show(IWin32Window owner, string text,
string caption, MessageBoxButtons buttons, MessageBoxIcon icon)
{
Init(caption, owner);
return MessageBox.Show(owner, text, caption, buttons, icon);
} // Show()
/// <summary>
/// Displays a message box with the specified text, caption, buttons,
/// icon, and default button.
/// </summary>
/// <param name="owner">Window parent (owner).</param>
/// <param name="text">The text to display in the message box. </param>
/// <param name="caption">The text to display in the title bar of the
/// message box. </param>
/// <param name="buttons">One of the MessageBoxButtons that specifies
/// which buttons to display in the message box.</param>
/// <param name="icon">One of the MessageBoxIcon values that specifies
/// which icon to display in the message box.</param>
/// <param name="defButton">One for the MessageBoxDefaultButton values
/// which specifies which is the default button for the message box.
/// </param>
/// <returns>One of the DialogResult values.</returns>
[SuppressMessage("Microsoft.Globalization",
"CA1300:SpecifyMessageBoxOptions",
Justification = "Not relevant here!")]
public static DialogResult Show(IWin32Window owner, string text,
string caption, MessageBoxButtons buttons, MessageBoxIcon icon,
MessageBoxDefaultButton defButton)
{
Init(caption, owner);
return MessageBox.Show(owner, text, caption, buttons, icon,
defButton);
} // Show()
/// <summary>
/// Displays a message box with the specified text, caption, buttons,
/// icon, and default button.
/// </summary>
/// <param name="owner">Window parent (owner).</param>
/// <param name="text">The text to display in the message box. </param>
/// <param name="caption">The text to display in the title bar of the
/// message box. </param>
/// <param name="buttons">One of the MessageBoxButtons that specifies
/// which buttons to display in the message box.</param>
/// <param name="icon">One of the MessageBoxIcon values that specifies
/// which icon to display in the message box.</param>
/// <param name="defButton">One for the MessageBoxDefaultButton values
/// which specifies which is the default button for the message box.
/// </param>
/// <param name="options">Message box Options</param>
/// <returns>One of the DialogResult values.</returns>
[SuppressMessage("Microsoft.Globalization",
"CA1300:SpecifyMessageBoxOptions", Justification = "Not relevant here!")]
public static DialogResult Show(IWin32Window owner, string text,
string caption, MessageBoxButtons buttons, MessageBoxIcon icon,
MessageBoxDefaultButton defButton, MessageBoxOptions options)
{
Init(caption, owner);
return MessageBox.Show(owner, text, caption, buttons, icon,
defButton, options);
} // Show()
#endregion // SHOW() FUNCTIONS
//// --------------------------------------------------------------------
#region PRIVATE PROPERTIES
/// <summary>
/// The hook.
/// </summary>
private static readonly Win32Api.HookProc HookProc
= MessageBoxHookProc;
/// <summary>
/// Hook caption.
/// </summary>
private static string hookCaption = string.Empty;
/// <summary>
/// Hook handle.
/// </summary>
private static IntPtr handleHook = IntPtr.Zero;
/// <summary>
/// Parent window.
/// </summary>
private static IWin32Window parent;
#endregion // PRIVATE PROPERTIES
//// --------------------------------------------------------------------
#region CONTRUCTION
/// <summary>
/// Initialize hook management.
/// </summary>
/// <param name="caption">The caption.</param>
/// <param name="owner">The owner.</param>
/// <exception cref="System.NotSupportedException">multiple
/// calls are not supported</exception>
private static void Init(string caption, IWin32Window owner)
{
if (handleHook != IntPtr.Zero)
{
// prohibit reentrancy
throw new NotSupportedException(
"multiple calls are not supported");
} // if
// store parent (owner)
parent = owner;
// create hook
hookCaption = caption ?? string.Empty;
handleHook = Win32Api.SetWindowsHookEx(
(int)WindowsHookCodes.WH_CALLWNDPROCRET, HookProc, IntPtr.Zero,
Thread.CurrentThread.ManagedThreadId);
} // Init()
#endregion // CONTRUCTION
//// --------------------------------------------------------------------
#region HOOK
/// <summary>
/// This is the function called by the Windows hook management.
/// We assume, that when an WM_INITDIALOG message is sent and
/// the window text is the same like the one of our window that
/// the window to hook call comes from is indeed our window.
/// We start the timer and unhook ourselves.
/// </summary>
/// <param name="code">The code.</param>
/// <param name="wParam">The w parameter.</param>
/// <param name="lParam">The l parameter.</param>
/// <returns>The handle.</returns>
[SuppressMessage("StyleCop.CSharp.NamingRules",
"SA1305:FieldNamesMustNotUseHungarianNotation",
Justification = "Reviewed. Suppression is OK here.")]
private static IntPtr MessageBoxHookProc(int code, IntPtr wParam,
IntPtr lParam)
{
if (code < 0)
{
return Win32Api.CallNextHookEx(handleHook, code, wParam, lParam);
} // if
var msg = (CWPRETSTRUCT)Marshal.PtrToStructure(lParam,
typeof(CWPRETSTRUCT));
var hook = handleHook;
if ((hookCaption != null) && (msg.message == (uint)Msg.WM_INITDIALOG))
{
// get window text
int length = Win32Api.GetWindowTextLength(msg.hwnd);
var text = new StringBuilder(length + 1);
int result = Win32Api.GetWindowText(msg.hwnd, text,
text.Capacity);
Debug.Assert(result > 0, "GetWindowText reports error!");
// check whether this is the text we expect
if (hookCaption == text.ToString())
{
hookCaption = null;
// get size of the parent window
var rectParent = new RECT();
var rectClient = new RECT();
if (Win32Api.GetWindowRect(parent.Handle, ref rectParent))
{
// calculate center point
var centerParent = new Point((rectParent.left
+ rectParent.right) / 2,
(rectParent.top + rectParent.bottom) / 2);
if (Win32Api.GetWindowRect(msg.hwnd, ref rectClient))
{
var pt = new Point(centerParent.X -
((rectClient.right - rectClient.left) / 2),
centerParent.Y - ((rectClient.bottom
- rectClient.top) / 2));
if (pt.X < 0)
{
pt.X = 0;
} // if
if (pt.Y < 0)
{
pt.Y = 0;
} // if
// set new window position
const uint Flags = (uint)SetWindowPosFlags.SWP_NOOWNERZORDER
+ (uint)SetWindowPosFlags.SWP_NOSIZE
+ (uint)SetWindowPosFlags.SWP_NOZORDER;
Win32Api.SetWindowPos(msg.hwnd, IntPtr.Zero,
pt.X, pt.Y, 0, 0, Flags);
} // if
} // if
// unhook
Win32Api.UnhookWindowsHookEx(handleHook);
handleHook = IntPtr.Zero;
} // if
} // if
// default: call next hook
return Win32Api.CallNextHookEx(hook, code, wParam, lParam);
} // MessageBoxHookProc()
#endregion // HOOK
} // CenteredMessageBox
} // Tethys.Forms
// ==========================================
// Tethys.forms: end of centeredmessagebox.cs
// ==========================================
| |
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 CoursesSystem.Server.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;
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#region Using directives
using System;
using System.Management.Automation;
using System.Management.Automation.SecurityAccountsManager;
using System.Management.Automation.SecurityAccountsManager.Extensions;
using Microsoft.PowerShell.LocalAccounts;
#endregion
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// The Rename-LocalUser cmdlet renames a local user account in the Security
/// Accounts Manager.
/// </summary>
[Cmdlet(VerbsCommon.Rename, "LocalUser",
SupportsShouldProcess = true,
HelpUri = "https://go.microsoft.com/fwlink/?LinkID=717983")]
[Alias("rnlu")]
public class RenameLocalUserCommand : Cmdlet
{
#region Instance Data
private Sam sam = null;
#endregion Instance Data
#region Parameter Properties
/// <summary>
/// The following is the definition of the input parameter "InputObject".
/// Specifies the of the local user account to rename in the local Security
/// Accounts Manager.
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "InputObject")]
[ValidateNotNull]
public Microsoft.PowerShell.Commands.LocalUser InputObject
{
get { return this.inputobject;}
set { this.inputobject = value; }
}
private Microsoft.PowerShell.Commands.LocalUser inputobject;
/// <summary>
/// The following is the definition of the input parameter "Name".
/// Specifies the local user account to be renamed in the local Security
/// Accounts Manager.
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "Default")]
[ValidateNotNullOrEmpty]
public string Name
{
get { return this.name;}
set { this.name = value; }
}
private string name;
/// <summary>
/// The following is the definition of the input parameter "NewName".
/// Specifies the new name for the local user account in the Security Accounts
/// Manager.
/// </summary>
[Parameter(Mandatory = true,
Position = 1)]
[ValidateNotNullOrEmpty]
public string NewName
{
get { return this.newname;}
set { this.newname = value; }
}
private string newname;
/// <summary>
/// The following is the definition of the input parameter "SID".
/// Specifies the local user to rename.
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "SecurityIdentifier")]
[ValidateNotNull]
public System.Security.Principal.SecurityIdentifier SID
{
get { return this.sid;}
set { this.sid = value; }
}
private System.Security.Principal.SecurityIdentifier sid;
#endregion Parameter Properties
#region Cmdlet Overrides
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void BeginProcessing()
{
sam = new Sam();
}
/// <summary>
/// ProcessRecord method.
/// </summary>
protected override void ProcessRecord()
{
try
{
ProcessUser();
ProcessName();
ProcessSid();
}
catch (Exception ex)
{
WriteError(ex.MakeErrorRecord());
}
}
/// <summary>
/// EndProcessing method.
/// </summary>
protected override void EndProcessing()
{
if (sam != null)
{
sam.Dispose();
sam = null;
}
}
#endregion Cmdlet Overrides
#region Private Methods
/// <summary>
/// Process user requested by -Name.
/// </summary>
/// <remarks>
/// Arguments to -Name will be treated as names,
/// even if a name looks like a SID.
/// </remarks>
private void ProcessName()
{
if (Name != null)
{
try
{
if (CheckShouldProcess(Name, NewName))
sam.RenameLocalUser(sam.GetLocalUser(Name), NewName);
}
catch (Exception ex)
{
WriteError(ex.MakeErrorRecord());
}
}
}
/// <summary>
/// Process user requested by -SID.
/// </summary>
private void ProcessSid()
{
if (SID != null)
{
try
{
if (CheckShouldProcess(SID.ToString(), NewName))
sam.RenameLocalUser(SID, NewName);
}
catch (Exception ex)
{
WriteError(ex.MakeErrorRecord());
}
}
}
/// <summary>
/// Process group given through -InputObject.
/// </summary>
private void ProcessUser()
{
if (InputObject != null)
{
try
{
if (CheckShouldProcess(InputObject.Name, NewName))
sam.RenameLocalUser(InputObject, NewName);
}
catch (Exception ex)
{
WriteError(ex.MakeErrorRecord());
}
}
}
/// <summary>
/// Determine if a user should be processed.
/// Just a wrapper around Cmdlet.ShouldProcess, with localized string
/// formatting.
/// </summary>
/// <param name="userName">
/// Name of the user to rename.
/// </param>
/// <param name="newName">
/// New name for the user.
/// </param>
/// <returns>
/// True if the user should be processed, false otherwise.
/// </returns>
private bool CheckShouldProcess(string userName, string newName)
{
string msg = StringUtil.Format(Strings.ActionRenameUser, newName);
return ShouldProcess(userName, msg);
}
#endregion Private Methods
}
}
| |
// Provides a user-friendly folder chooser for VBSxript
// adapted from https://stackoverflow.com/questions/15368771/show-detailed-folder-browser-from-a-propertygrid#15386992
// by Simon Mourier https://stackoverflow.com/users/403671/simon-mourier
using System;
using System.Runtime.InteropServices;
using System.IO;
namespace VBScripting
{
/// <summary> COM interface for VBScripting.FolderChooser2 </summary>
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch),
Guid("2650C2AB-B3F8-495F-AB4D-6C61BD463EA4")]
public interface IFolderChooser2
{
/// <summary> </summary>
string InitialDirectory { get; set; }
/// <summary> </summary>
string Title { get; set; }
/// <summary> </summary>
string FolderName { get; }
}
/// <summary> Present the Windows Vista-style open file dialog to select a folder. </summary>
/// <remarks> Adapted from <a title="stackoverflow.com" href="https://stackoverflow.com/questions/15368771/show-detailed-folder-browser-from-a-propertygrid#15386992"> a stackoverflow post</a> by <a title="stackoverflow.com" href="https://stackoverflow.com/users/403671/simon-mourier"> Simon Mourier</a>. Uses <tt> System.Runtime.InteropServices</tt>. </remarks>
[ProgId("VBScripting.FolderChooser2"),
ClassInterface(ClassInterfaceType.None),
Guid("2650C2AB-B2F8-495F-AB4D-6C61BD463EA4")]
public class FolderChooser2 : IFolderChooser2
{
private string _initialDirectory;
private string _folderName;
private string _title;
/// <summary> Gets or sets the initial directory that the folder select dialog opens to. </summary>
/// <remarks> Environment variables are allowed. Relative paths are allowed. Optional. The default value is the current directory. </remarks>
public string InitialDirectory
{
get { return string.IsNullOrEmpty(_initialDirectory) ? Environment.CurrentDirectory : _initialDirectory; }
set { _initialDirectory = value; }
}
/// <summary> Sets the title/caption of the folder select dialog. Optional. The default value is "Select a folder". </summary>
public string Title
{
get
{
return string.IsNullOrEmpty(_title)
? "Select a folder"
: _title;
}
set { _title = value; }
}
/// <summary> Opens a dialog and returns the folder selected by the user. Returns an empty string if the user cancels. </summary>
/// <returns> a path </returns>
public string FolderName
{
get { return this.ShowDialog() ? _folderName : string.Empty; }
private set { _folderName = value; }
}
private bool ShowDialog()
{
return ShowDialog(IntPtr.Zero);
}
private bool ShowDialog(IntPtr hwndOwner)
{
IFileOpenDialog dialog = (IFileOpenDialog)new FileOpenDialog();
try
{
IShellItem item;
if (!string.IsNullOrEmpty(InitialDirectory))
{
var dir1 = InitialDirectory;
dir1 = Environment.ExpandEnvironmentVariables(dir1); // expand environment variables
dir1 = Path.GetFullPath(dir1); // resolve relative path
IntPtr idl;
uint atts = 0;
if (SHILCreateFromPath(dir1, out idl, ref atts) == 0)
{
if (SHCreateShellItem(IntPtr.Zero, IntPtr.Zero, idl, out item) == 0)
{
dialog.SetFolder(item);
}
}
}
dialog.SetOptions(FOS.FOS_PICKFOLDERS | FOS.FOS_FORCEFILESYSTEM);
dialog.SetTitle(Title);
uint hr = dialog.Show(hwndOwner);
if (hr == ERROR_CANCELLED)
{
_folderName = string.Empty;
return false;
}
if (hr != 0)
{
_folderName = string.Empty;
return false;
}
dialog.GetResult(out item);
string path;
item.GetDisplayName(SIGDN.SIGDN_FILESYSPATH, out path);
_folderName = path;
return true;
}
finally
{
Marshal.ReleaseComObject(dialog);
}
}
[DllImport("shell32.dll")]
private static extern int SHILCreateFromPath([MarshalAs(UnmanagedType.LPWStr)] string pszPath, out IntPtr ppIdl, ref uint rgflnOut);
[DllImport("shell32.dll")]
private static extern int SHCreateShellItem(IntPtr pidlParent, IntPtr psfParent, IntPtr pidl, out IShellItem ppsi);
[DllImport("user32.dll")]
private static extern IntPtr GetActiveWindow();
private const uint ERROR_CANCELLED = 0x800704C7;
[ComImport]
[Guid("DC1C5A9C-E88A-4dde-A5A1-60F82A20AEF7")]
private class FileOpenDialog
{
}
[ComImport]
[Guid("42f85136-db7e-439c-85f1-e4075d135fc8")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IFileOpenDialog
{
[PreserveSig]
uint Show([In] IntPtr parent); // IModalWindow
void SetFileTypes(); // not fully defined
void SetFileTypeIndex([In] uint iFileType);
void GetFileTypeIndex(out uint piFileType);
void Advise(); // not fully defined
void Unadvise();
void SetOptions([In] FOS fos);
void GetOptions(out FOS pfos);
void SetDefaultFolder(IShellItem psi);
void SetFolder(IShellItem psi);
void GetFolder(out IShellItem ppsi);
void GetCurrentSelection(out IShellItem ppsi);
void SetFileName([In, MarshalAs(UnmanagedType.LPWStr)] string pszName);
void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string pszName);
void SetTitle([In, MarshalAs(UnmanagedType.LPWStr)] string pszTitle);
void SetOkButtonLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszText);
void SetFileNameLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszLabel);
void GetResult(out IShellItem ppsi);
void AddPlace(IShellItem psi, int alignment);
void SetDefaultExtension([In, MarshalAs(UnmanagedType.LPWStr)] string pszDefaultExtension);
void Close(int hr);
void SetClientGuid(); // not fully defined
void ClearClientData();
void SetFilter([MarshalAs(UnmanagedType.Interface)] IntPtr pFilter);
void GetResults([MarshalAs(UnmanagedType.Interface)] out IntPtr ppenum); // not fully defined
void GetSelectedItems([MarshalAs(UnmanagedType.Interface)] out IntPtr ppsai); // not fully defined
}
[ComImport]
[Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IShellItem
{
void BindToHandler(); // not fully defined
void GetParent(); // not fully defined
void GetDisplayName([In] SIGDN sigdnName, [MarshalAs(UnmanagedType.LPWStr)] out string ppszName);
void GetAttributes(); // not fully defined
void Compare(); // not fully defined
}
private enum SIGDN : uint
{
SIGDN_DESKTOPABSOLUTEEDITING = 0x8004c000,
SIGDN_DESKTOPABSOLUTEPARSING = 0x80028000,
SIGDN_FILESYSPATH = 0x80058000,
SIGDN_NORMALDISPLAY = 0,
SIGDN_PARENTRELATIVE = 0x80080001,
SIGDN_PARENTRELATIVEEDITING = 0x80031001,
SIGDN_PARENTRELATIVEFORADDRESSBAR = 0x8007c001,
SIGDN_PARENTRELATIVEPARSING = 0x80018001,
SIGDN_URL = 0x80068000
}
[Flags]
private enum FOS
{
FOS_ALLNONSTORAGEITEMS = 0x80,
FOS_ALLOWMULTISELECT = 0x200,
FOS_CREATEPROMPT = 0x2000,
FOS_DEFAULTNOMINIMODE = 0x20000000,
FOS_DONTADDTORECENT = 0x2000000,
FOS_FILEMUSTEXIST = 0x1000,
FOS_FORCEFILESYSTEM = 0x40,
FOS_FORCESHOWHIDDEN = 0x10000000,
FOS_HIDEMRUPLACES = 0x20000,
FOS_HIDEPINNEDPLACES = 0x40000,
FOS_NOCHANGEDIR = 8,
FOS_NODEREFERENCELINKS = 0x100000,
FOS_NOREADONLYRETURN = 0x8000,
FOS_NOTESTFILECREATE = 0x10000,
FOS_NOVALIDATE = 0x100,
FOS_OVERWRITEPROMPT = 2,
FOS_PATHMUSTEXIST = 0x800,
FOS_PICKFOLDERS = 0x20,
FOS_SHAREAWARE = 0x4000,
FOS_STRICTFILETYPES = 4
}
}
}
| |
#if NETFX_CORE
using MarkerMetro.Unity.WinLegacy.Security.Cryptography;
using System.Threading.Tasks;
using System.Globalization;
#endif
using System;
using System.Collections.Generic;
using Facebook;
using MarkerMetro.Unity.WinIntegration;
#if NETFX_CORE
using Windows.Storage;
using MarkerMetro.Unity.WinIntegration.Storage;
using Windows.Security.Authentication.Web;
#endif
#if WINDOWS_UWP
using Facebook.Graph;
using Windows.Foundation.Collections;
#endif
namespace MarkerMetro.Unity.WinIntegration.Facebook
{
public delegate object FBReturnObjectFromJsonDelegate(string jsonText);
/// <summary>
/// Unity Facebook implementation
/// </summary>
public static class FBUWP
{
private const string EXPIRY_DATE_BIN = "FBEXPB";
// check whether facebook is initialized
public static bool IsInitialized
{
get
{
#if WINDOWS_UWP
FBSession session = FBSession.ActiveSession;
return session != null ? !string.IsNullOrEmpty(session.FBAppId) : false;
#else
throw new PlatformNotSupportedException("");
#endif
}
}
public static bool IsLoggedIn
{
get
{
#if WINDOWS_UWP
FBSession session = FBSession.ActiveSession;
return session != null ? session.LoggedIn : false;
#else
return false;
#endif
}
}
public static string AccessToken
{
get
{
#if WINDOWS_UWP
FBSession session = FBSession.ActiveSession;
if (session != null && session.AccessTokenData != null)
{
return session.AccessTokenData.AccessToken;
}
else
{
return null;
}
#else
throw new PlatformNotSupportedException("");
#endif
}
}
public static string UserId
{
get
{
#if WINDOWS_UWP
FBSession session = FBSession.ActiveSession;
if (session != null && session.LoggedIn && session.User != null)
{
return session.User.Id;
}
else
{
return null;
}
#else
throw new PlatformNotSupportedException("");
#endif
}
}
public static string UserName
{
get
{
#if WINDOWS_UWP
FBSession session = FBSession.ActiveSession;
if (session != null && session.LoggedIn && session.User != null)
{
return session.User.Name;
}
else
{
return null;
}
#else
throw new PlatformNotSupportedException("");
#endif
}
}
/// <summary>
/// FB.Init as per Unity SDK
/// </summary>
/// <remarks>
/// https://developers.facebook.com/docs/unity/reference/current/FB.Init
/// </remarks>
public static void Init(InitDelegate onInitComplete, string fbAppId, HideUnityDelegate onHideUnity)
{
#if WINDOWS_UWP
FBSession session = FBSession.ActiveSession;
session.FBAppId = fbAppId;
session.WinAppId = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString();
if (onInitComplete != null)
{
if (Settings.HasKey(EXPIRY_DATE_BIN))
{
long expDate = Settings.GetLong(EXPIRY_DATE_BIN);
DateTime expireDate = DateTime.FromBinary(expDate);
// verifies if the token has expired:
if (DateTime.Compare(DateTime.UtcNow, expireDate) > 0)
{
InvalidateData();
onInitComplete();
}
else
{
Login(null, (result) => { onInitComplete(); });
}
}
else
{
onInitComplete();
}
}
if (onHideUnity != null)
throw new NotSupportedException("onHideUnity is not currently supported at this time.");
#else
throw new PlatformNotSupportedException("");
#endif
}
#if WINDOWS_UWP
private static void InvalidateData()
{
Settings.DeleteKey(EXPIRY_DATE_BIN);
}
#endif
public static void Login(string permissions, FacebookDelegate callback)
{
#if WINDOWS_UWP
// Get active session
FBSession session = FBSession.ActiveSession;
if (!IsInitialized)
{
if (callback != null)
callback(new FBResult() { Error = "Not initialized." });
return;
}
Task.Run(async () =>
{
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
FBPermissions fbPermissions;
if (string.IsNullOrEmpty(permissions))
{
List<String> permissionList = new List<String>();
permissionList.Add("public_profile");
fbPermissions = new FBPermissions(permissionList);
}
else
{
var permissionsArray = permissions.Split(',');
fbPermissions = new FBPermissions(permissionsArray);
}
// Login to Facebook
global::Facebook.FBResult fbResult = await session.LoginAsync(fbPermissions);
var result = new FBResult(fbResult);
if (fbResult.Succeeded)
{
Settings.Set(EXPIRY_DATE_BIN, session.AccessTokenData.ExpirationDate.DateTime.ToUniversalTime().ToBinary());
}
if (callback != null)
{
Dispatcher.InvokeOnAppThread(() => { callback(result); });
}
});
});
#else
throw new PlatformNotSupportedException("");
#endif
}
public static void Logout()
{
#if WINDOWS_UWP
if (!IsLoggedIn)
return;
Task.Run(async () =>
{
FBSession session = FBSession.ActiveSession;
string appID = session.FBAppId;
await session.LogoutAsync();
InvalidateData();
session.FBAppId = appID;
session.WinAppId = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString();
});
#else
throw new PlatformNotSupportedException("");
#endif
}
public static void API(
string endpoint,
HttpMethod method,
FacebookDelegate callback,
object parameters = null,
FBReturnObjectFromJsonDelegate fbReturnObjectDelegate = null)
{
#if WINDOWS_UWP
if (!IsLoggedIn)
{
if (callback != null)
callback(new FBResult() { Error = "Not logged in" });
return;
}
// Get active session
FBSession session = FBSession.ActiveSession;
// If the user is logged in
if (session.LoggedIn)
{
Task.Run(async () =>
{
PropertySet param = new PropertySet();
if (parameters != null && parameters is ICollection<KeyValuePair<string, object>>)
{
foreach (KeyValuePair<string, object> pair in parameters as ICollection<KeyValuePair<string, object>>)
{
param.Add(pair);
}
}
FBSingleValue sval = new FBSingleValue(endpoint, param,
new FBJsonClassFactory(fbReturnObjectDelegate));
global::Facebook.FBResult fbResult;
if (method == HttpMethod.GET)
{
fbResult = await sval.GetAsync();
}
else if (method == HttpMethod.POST)
{
fbResult = await sval.PostAsync();
}
else
{
fbResult = await sval.DeleteAsync();
}
var result = new FBResult(fbResult);
if (callback != null)
{
Dispatcher.InvokeOnAppThread(() => { callback(result); });
}
});
}
#else
throw new PlatformNotSupportedException("");
#endif
}
/// <summary>
/// Show Request Dialog.
/// filters, excludeIds and maxRecipients are not currently supported at this time.
/// </summary>
public static void AppRequest(
string message,
string[] to = null,
string filters = "",
string[] excludeIds = null,
int? maxRecipients = null,
string data = "",
string title = "",
FacebookDelegate callback = null
)
{
#if WINDOWS_UWP
if (!IsLoggedIn)
{
if (callback != null)
callback(new FBResult() { Error = "Not logged in" });
return;
}
// Get active session
FBSession session = FBSession.ActiveSession;
if (session.LoggedIn)
{
Task.Run(async () =>
{
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
// Set parameters
PropertySet parameters = new PropertySet();
parameters.Add("message", message);
parameters.Add("to", to);
parameters.Add("data", data);
parameters.Add("title", title);
// Display feed dialog
global::Facebook.FBResult fbResult = await session.ShowRequestsDialogAsync(parameters);
var result = new FBResult(fbResult);
if (callback != null)
{
Dispatcher.InvokeOnAppThread(() => { callback(result); });
}
});
});
}
// throw not supported exception when user passed in parameters not supported currently
if (!string.IsNullOrWhiteSpace(filters) || excludeIds != null || maxRecipients != null)
throw new NotSupportedException("filters, excludeIds and maxRecipients are not currently supported at this time.");
#else
throw new PlatformNotSupportedException("");
#endif
}
/// <summary>
/// Show the Feed Dialog.
/// mediaSource, actionName, actionLink, reference and properties are not currently supported at this time.
/// </summary>
public static void Feed(
string toId = "",
string link = "",
string linkName = "",
string linkCaption = "",
string linkDescription = "",
string picture = "",
string mediaSource = "",
string actionName = "",
string actionLink = "",
string reference = "",
Dictionary<string, string[]> properties = null,
FacebookDelegate callback = null)
{
#if WINDOWS_UWP
if (!IsLoggedIn)
{
if (callback != null)
callback(new FBResult() { Error = "Not logged in" });
return;
}
// Get active session
FBSession session = FBSession.ActiveSession;
if (session.LoggedIn)
{
Task.Run(async () =>
{
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
// Set caption, link and description parameters
PropertySet parameters = new PropertySet();
parameters.Add("title", linkName);
parameters.Add("link", link);
parameters.Add("description", linkDescription);
parameters.Add("toId", toId);
parameters.Add("linkCaption", linkCaption);
parameters.Add("picture", picture);
// Display feed dialog
global::Facebook.FBResult fbResult = await session.ShowFeedDialogAsync(parameters);
var result = new FBResult(fbResult);
if (callback != null)
{
Dispatcher.InvokeOnAppThread(() => { callback(result); });
}
});
});
}
// throw not supported exception when user passed in parameters not supported currently
if (!string.IsNullOrWhiteSpace(mediaSource) || !string.IsNullOrWhiteSpace(actionName) || !string.IsNullOrWhiteSpace(actionLink) ||
!string.IsNullOrWhiteSpace(reference) || properties != null)
throw new NotSupportedException("mediaSource, actionName, actionLink, reference and properties are not currently supported at this time.");
#else
throw new PlatformNotSupportedException("");
#endif
}
}
}
| |
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Semmle.Extraction.CSharp.Populators;
using Semmle.Extraction.Kinds;
using System.Collections.Generic;
using System.Linq;
using System.Collections.Immutable;
namespace Semmle.Extraction.CSharp.Entities.Expressions
{
internal class VariableDeclaration : Expression
{
private VariableDeclaration(IExpressionInfo info) : base(info) { }
public static VariableDeclaration Create(Context cx, ISymbol symbol, AnnotatedTypeSymbol? type, TypeSyntax? optionalSyntax, Extraction.Entities.Location exprLocation, bool isVar, IExpressionParentEntity parent, int child)
{
var ret = new VariableDeclaration(new ExpressionInfo(cx, type, exprLocation, ExprKind.LOCAL_VAR_DECL, parent, child, false, null));
cx.Try(null, null, () =>
{
var l = LocalVariable.Create(cx, symbol);
l.PopulateManual(ret, isVar);
if (optionalSyntax is not null)
TypeMention.Create(cx, optionalSyntax, ret, type);
});
return ret;
}
private static VariableDeclaration CreateSingle(Context cx, DeclarationExpressionSyntax node, SingleVariableDesignationSyntax designation, IExpressionParentEntity parent, int child)
{
var variableSymbol = cx.GetModel(designation).GetDeclaredSymbol(designation) as ILocalSymbol;
if (variableSymbol is null)
{
cx.ModelError(node, "Failed to determine local variable");
return Create(cx, node, (AnnotatedTypeSymbol?)null, parent, child);
}
var type = variableSymbol.GetAnnotatedType();
var ret = Create(cx, designation, type, parent, child);
cx.Try(null, null, () =>
{
var l = LocalVariable.Create(cx, variableSymbol);
l.PopulateManual(ret, node.Type.IsVar);
});
return ret;
}
/// <summary>
/// Create a tuple expression representing a parenthesized variable declaration.
/// That is, we consider `var (x, y) = ...` to be equivalent to `(var x, var y) = ...`.
/// </summary>
public static Expression CreateParenthesized(Context cx, DeclarationExpressionSyntax node, ParenthesizedVariableDesignationSyntax designation, IExpressionParentEntity parent, int child, INamedTypeSymbol? t)
{
var type = t is null ? (AnnotatedTypeSymbol?)null : new AnnotatedTypeSymbol(t, t.NullableAnnotation);
var tuple = new Expression(new ExpressionInfo(cx, type, cx.CreateLocation(node.GetLocation()), ExprKind.TUPLE, parent, child, false, null));
cx.Try(null, null, () =>
{
for (var child0 = 0; child0 < designation.Variables.Count; child0++)
{
Create(cx, node, designation.Variables[child0], tuple, child0, t?.TypeArguments[child0] as INamedTypeSymbol);
}
});
return tuple;
}
public static Expression CreateParenthesized(Context cx, VarPatternSyntax varPattern, ParenthesizedVariableDesignationSyntax designation, IExpressionParentEntity parent, int child)
{
var tuple = new Expression(
new ExpressionInfo(cx, null, cx.CreateLocation(varPattern.GetLocation()), ExprKind.TUPLE, parent, child, false, null),
shouldPopulate: false);
var elementTypes = new List<ITypeSymbol?>();
cx.Try(null, null, () =>
{
var child0 = 0;
foreach (var variable in designation.Variables)
{
Expression sub;
switch (variable)
{
case ParenthesizedVariableDesignationSyntax paren:
sub = CreateParenthesized(cx, varPattern, paren, tuple, child0++);
break;
case SingleVariableDesignationSyntax single:
if (cx.GetModel(variable).GetDeclaredSymbol(single) is ILocalSymbol local)
{
var decl = Create(cx, variable, local.GetAnnotatedType(), tuple, child0++);
var l = LocalVariable.Create(cx, local);
l.PopulateManual(decl, true);
sub = decl;
}
else
{
throw new InternalError(single, "Failed to access local variable");
}
break;
case DiscardDesignationSyntax discard:
sub = new Discard(cx, discard, tuple, child0++);
if (!sub.Type.HasValue || sub.Type.Value.Symbol is null)
{
// The type is only updated in memory, it will not be written to the trap file.
sub.SetType(cx.Compilation.GetSpecialType(SpecialType.System_Object));
}
break;
default:
var type = variable.GetType().ToString() ?? "null";
throw new InternalError(variable, $"Unhandled designation type {type}");
}
elementTypes.Add(sub.Type.HasValue && sub.Type.Value.Symbol?.Kind != SymbolKind.ErrorType
? sub.Type.Value.Symbol
: null);
}
});
INamedTypeSymbol? tupleType = null;
if (!elementTypes.Any(et => et is null))
{
tupleType = cx.Compilation.CreateTupleTypeSymbol(elementTypes.ToImmutableArray()!);
}
tuple.SetType(tupleType);
tuple.TryPopulate();
return tuple;
}
private static Expression Create(Context cx, DeclarationExpressionSyntax node, VariableDesignationSyntax? designation, IExpressionParentEntity parent, int child, INamedTypeSymbol? declarationType)
{
switch (designation)
{
case SingleVariableDesignationSyntax single:
return CreateSingle(cx, node, single, parent, child);
case ParenthesizedVariableDesignationSyntax paren:
return CreateParenthesized(cx, node, paren, parent, child, declarationType);
case DiscardDesignationSyntax discard:
var type = cx.GetType(discard);
return Create(cx, node, type, parent, child);
default:
cx.ModelError(node, "Failed to determine designation type");
return Create(cx, node, null, parent, child);
}
}
public static Expression Create(Context cx, DeclarationExpressionSyntax node, IExpressionParentEntity parent, int child) =>
Create(cx, node, node.Designation, parent, child, cx.GetTypeInfo(node).Type.DisambiguateType() as INamedTypeSymbol);
public static VariableDeclaration Create(Context cx, CSharpSyntaxNode c, AnnotatedTypeSymbol? type, IExpressionParentEntity parent, int child) =>
new VariableDeclaration(new ExpressionInfo(cx, type, cx.CreateLocation(c.FixedLocation()), ExprKind.LOCAL_VAR_DECL, parent, child, false, null));
public static VariableDeclaration Create(Context cx, CatchDeclarationSyntax d, bool isVar, IExpressionParentEntity parent, int child)
{
var symbol = cx.GetModel(d).GetDeclaredSymbol(d)!;
var type = symbol.GetAnnotatedType();
var ret = Create(cx, d, type, parent, child);
cx.Try(d, null, () =>
{
var declSymbol = cx.GetModel(d).GetDeclaredSymbol(d)!;
var l = LocalVariable.Create(cx, declSymbol);
l.PopulateManual(ret, isVar);
TypeMention.Create(cx, d.Type, ret, type);
});
return ret;
}
public static VariableDeclaration CreateDeclarator(Context cx, VariableDeclaratorSyntax d, AnnotatedTypeSymbol type, bool isVar, IExpressionParentEntity parent, int child)
{
var ret = Create(cx, d, type, parent, child);
cx.Try(d, null, () =>
{
var declSymbol = cx.GetModel(d).GetDeclaredSymbol(d)!;
var localVar = LocalVariable.Create(cx, declSymbol);
localVar.PopulateManual(ret, isVar);
if (d.Initializer is not null)
{
Create(cx, d.Initializer.Value, ret, 0);
// Create an access
var access = new Expression(new ExpressionInfo(cx, type, localVar.Location, ExprKind.LOCAL_VARIABLE_ACCESS, ret, 1, false, null));
cx.TrapWriter.Writer.expr_access(access, localVar);
}
if (d.Parent is VariableDeclarationSyntax decl)
TypeMention.Create(cx, decl.Type, ret, type);
});
return ret;
}
}
internal static class VariableDeclarations
{
public static void Populate(Context cx, VariableDeclarationSyntax decl, IExpressionParentEntity parent, int child, int childIncrement = 1)
{
var type = cx.GetType(decl.Type);
foreach (var v in decl.Variables)
{
VariableDeclaration.CreateDeclarator(cx, v, type, decl.Type.IsVar, parent, child);
child += childIncrement;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using AllReady.Configuration;
using Xunit;
using Moq;
using AllReady.Features.Notifications;
using MediatR;
using Microsoft.Extensions.Logging;
using AllReady.Models;
namespace AllReady.UnitTest.Features.Notifications
{
using Event = AllReady.Models.Event;
public class NotifyAdminForSignupHandlerShould : InMemoryContextTest
{
protected override void LoadTestData()
{
var testOrg = new Organization
{
Name = "My Test Campaign",
LogoUrl = "http://www.htbox.org/testCampaign",
WebUrl = "http://www.htbox.org",
Campaigns = new List<Campaign>()
};
var testCampaign1 = new Campaign
{
Name = "Test Campaign 1",
ManagingOrganization = testOrg,
CampaignContacts = new List<CampaignContact>()
};
var testCampaign2 = new Campaign
{
Name = "Test Campaign 2",
ManagingOrganization = testOrg,
CampaignContacts = new List<CampaignContact>()
};
var primaryCampaignContact1 = new CampaignContact
{
ContactType = (int)ContactTypes.Primary,
Contact = new Contact
{
Email = "[email protected]"
}
};
var primaryCampaignContact2 = new CampaignContact
{
ContactType = (int)ContactTypes.Primary,
Contact = new Contact()
};
var testEvent1 = new Event
{
Id = 5,
Name = "Test Event Name",
Campaign = testCampaign1,
CampaignId = testCampaign1.Id,
StartDateTime = DateTime.UtcNow.AddDays(10),
EndDateTime = DateTime.UtcNow.AddDays(10).AddHours(8),
Location = new Location { Id = 2 },
RequiredSkills = new List<EventSkill>()
};
var testEvent2 = new Event
{
Id = 7,
Name = "Test Event 2",
Campaign = testCampaign2,
CampaignId = testCampaign2.Id,
StartDateTime = DateTime.UtcNow.AddDays(3),
EndDateTime = DateTime.UtcNow.AddDays(3).AddHours(4),
Location = new Location { Id = 5 },
RequiredSkills = new List<EventSkill>()
};
var username1 = $"[email protected]";
var user1 = new ApplicationUser { UserName = username1, Email = username1, EmailConfirmed = true };
Context.Users.Add(user1);
var username2 = $"[email protected]";
var user2 = new ApplicationUser { UserName = username2, Email = username2, EmailConfirmed = true };
Context.Users.Add(user2);
testCampaign1.CampaignContacts.Add(primaryCampaignContact1);
testCampaign2.CampaignContacts.Add(primaryCampaignContact2);
testOrg.Campaigns.Add(testCampaign1);
testOrg.Campaigns.Add(testCampaign2);
Context.Organizations.Add(testOrg);
Context.Events.Add(testEvent1);
Context.Events.Add(testEvent2);
var testTask1 = new VolunteerTask
{
Id = 7,
Event = testEvent1,
EventId = testEvent1.Id
// Required Skills?
};
var testTask2 = new VolunteerTask
{
Id = 9,
Event = testEvent2,
EventId = testEvent2.Id
// Required Skills?
};
Context.VolunteerTasks.Add(testTask1);
Context.VolunteerTasks.Add(testTask2);
Context.SaveChanges();
}
/// <summary>
/// Verifies that an object of type NotifyVolunteersCommand
/// is sent to the mediator
/// </summary>
[Fact]
public async void PassANotifyVolunteersCommandToTheMediator()
{
var taskDetailForNotificationModel = new VolunteerTaskDetailForNotificationModel
{
Volunteer = new ApplicationUser { Email = "VolunteerEmail", PhoneNumber = "VolunteerPhoneNumber" },
CampaignContacts = new List<CampaignContact>
{
new CampaignContact
{
ContactType = (int) ContactTypes.Primary,
Contact = new Contact {Email = "CampaignContactEmail"}
}
}
};
var mediator = new Mock<IMediator>();
mediator.Setup(x => x.SendAsync(It.IsAny<VolunteerTaskDetailForNotificationQuery>()))
.ReturnsAsync(taskDetailForNotificationModel);
var options = new TestOptions<GeneralSettings>();
options.Value.SiteBaseUrl = "localhost";
var notification = new VolunteerSignedUpNotification
{
UserId = Context.Users.First().Id,
VolunteerTaskId = Context.VolunteerTasks.First().Id
};
var target = new NotifyAdminForSignupHandler(Context, mediator.Object, options, null);
await target.Handle(notification);
mediator.Verify(x => x.SendAsync(It.IsAny<NotifyVolunteersCommand>()), Times.Once);
}
/// <summary>
/// Verifies that a non-empty subject is passed to the mediator
/// within the NotifyVolunteersCommand
/// </summary>
/// <remarks>We are only checking for a non-empty value here since
/// the actual content of the subject is not a requirement, just
/// that there be one. Adding a requirement for a specific subject
/// line can be done, but would likely make this test more fragile</remarks>
[Fact]
public async void PassAnEmailSubjectToTheMediator()
{
const string adminEmail = "AdminEmail";
var taskDetailForNotificationModel = new VolunteerTaskDetailForNotificationModel
{
Volunteer = new ApplicationUser { Email = "VolunteerEmail", PhoneNumber = "VolunteerPhoneNumber" },
CampaignContacts = new List<CampaignContact>
{
new CampaignContact
{
ContactType = (int) ContactTypes.Primary,
Contact = new Contact { Email = adminEmail }
}
}
};
var mediator = new Mock<IMediator>();
mediator.Setup(x => x.SendAsync(It.IsAny<VolunteerTaskDetailForNotificationQuery>()))
.ReturnsAsync(taskDetailForNotificationModel);
var options = new TestOptions<GeneralSettings>();
options.Value.SiteBaseUrl = "localhost";
var notification = new VolunteerSignedUpNotification
{
UserId = Context.Users.First().Id,
VolunteerTaskId = Context.VolunteerTasks.First().Id
};
var target = new NotifyAdminForSignupHandler(Context, mediator.Object, options, null);
await target.Handle(notification);
mediator.Verify(x => x.SendAsync(It.Is<NotifyVolunteersCommand>(y => !string.IsNullOrWhiteSpace(y.ViewModel.Subject))), Times.Once);
}
/// <summary>
/// Verifies that the correct admin email address is passed to
/// the mediator within the NotifyVolunteersCommand
/// </summary>
[Fact]
public async void SendToTheAdminEmail()
{
const string adminEmail = "AdminEmail";
var taskDetailForNotificationModel = new VolunteerTaskDetailForNotificationModel
{
Volunteer = new ApplicationUser { Email = "VolunteerEmail", PhoneNumber = "VolunteerPhoneNumber" },
CampaignContacts = new List<CampaignContact>
{
new CampaignContact
{
ContactType = (int) ContactTypes.Primary,
Contact = new Contact { Email = adminEmail }
}
}
};
var mediator = new Mock<IMediator>();
mediator.Setup(x => x.SendAsync(It.IsAny<VolunteerTaskDetailForNotificationQuery>()))
.ReturnsAsync(taskDetailForNotificationModel);
var options = new TestOptions<GeneralSettings>();
options.Value.SiteBaseUrl = "localhost";
var notification = new VolunteerSignedUpNotification
{
UserId = Context.Users.First().Id,
VolunteerTaskId = Context.VolunteerTasks.First().Id
};
var target = new NotifyAdminForSignupHandler(Context, mediator.Object, options, null);
await target.Handle(notification);
mediator.Verify(x => x.SendAsync(It.Is<NotifyVolunteersCommand>(y => y.ViewModel.EmailRecipients.Contains(adminEmail))), Times.Once);
}
/// <summary>
/// Verifies that a log entry is written if an error occurs during
/// the processing of a notification by the mediator
/// </summary>
/// <remarks>No verification of the content of the log entry is done
/// here. The few requirements that there are for logging will be
/// verified in other tests.</remarks>
[Fact]
public async void LogIfAnExceptionOccurs()
{
var mediator = new Mock<IMediator>();
mediator.Setup(x => x.SendAsync(It.IsAny<NotifyVolunteersCommand>()))
.Throws(new InvalidOperationException("Test Exception"));
var logger = new Mock<ILogger<NotifyAdminForUserUnenrollsHandler>>();
var options = new TestOptions<GeneralSettings>();
options.Value.SiteBaseUrl = "localhost";
var notification = new VolunteerSignedUpNotification
{
UserId = Context.Users.First().Id,
VolunteerTaskId = Context.VolunteerTasks.First().Id
};
var target = new NotifyAdminForSignupHandler(Context, mediator.Object, options, logger.Object);
await target.Handle(notification);
logger.Verify(x => x.Log(It.IsAny<LogLevel>(), It.IsAny<EventId>(),
It.IsAny<object>(), It.IsAny<Exception>(),
It.IsAny<Func<object, Exception, string>>()), Times.AtLeastOnce);
}
/// <summary>
/// Verifies that the log entry that is written when an error
/// occurs during notification processing is done at a LogLevel
/// of "Error".
/// </summary>
[Fact]
public async void LogAnErrorIfAnExceptionOccurs()
{
var mediator = new Mock<IMediator>();
mediator.Setup(x => x.SendAsync(It.IsAny<NotifyVolunteersCommand>()))
.Throws(new InvalidOperationException("Test Exception"));
var logger = new Mock<ILogger<NotifyAdminForUserUnenrollsHandler>>();
logger.Setup(x => x.Log(It.Is<LogLevel>(m => m == LogLevel.Error),
It.IsAny<EventId>(), It.IsAny<object>(), It.IsAny<Exception>(),
It.IsAny<Func<object, Exception, string>>()));
var options = new TestOptions<GeneralSettings>();
options.Value.SiteBaseUrl = "localhost";
var notification = new VolunteerSignedUpNotification
{
UserId = Context.Users.First().Id,
VolunteerTaskId = Context.VolunteerTasks.First().Id
};
var target = new NotifyAdminForSignupHandler(Context, mediator.Object, options, logger.Object);
await target.Handle(notification);
logger.VerifyAll();
}
/// <summary>
/// Verifies that the log entry that is written when an error
/// occurs during notification processing receives the correct
/// Exception type.
/// </summary>
[Fact]
public async void LogTheExceptionIfAnExceptionOccurs()
{
var mediator = new Mock<IMediator>();
mediator.Setup(x => x.SendAsync(It.IsAny<NotifyVolunteersCommand>()))
.Throws(new InvalidOperationException("Test Exception"));
var logger = new Mock<ILogger<NotifyAdminForUserUnenrollsHandler>>();
var options = new TestOptions<GeneralSettings>();
options.Value.SiteBaseUrl = "localhost";
var notification = new VolunteerSignedUpNotification
{
UserId = Context.Users.First().Id,
VolunteerTaskId = Context.VolunteerTasks.First().Id
};
var target = new NotifyAdminForSignupHandler(Context, mediator.Object, options, logger.Object);
await target.Handle(notification);
logger.Verify(x => x.Log(It.IsAny<LogLevel>(),
It.IsAny<EventId>(), It.IsAny<object>(),
It.IsAny<InvalidOperationException>(),
It.IsAny<Func<object, Exception, string>>()), Times.AtLeastOnce);
}
/// <summary>
/// Verifies that the send method is never called if
/// the admin email address has not been specified
/// </summary>
[Fact]
public async void SkipNotificationIfAdminEmailIsNotSpecified()
{
var mediator = new Mock<IMediator>();
var logger = Mock.Of<ILogger<NotifyAdminForUserUnenrollsHandler>>();
var options = new TestOptions<GeneralSettings>();
options.Value.SiteBaseUrl = "localhost";
var notification = new VolunteerSignedUpNotification
{
UserId = Context.Users.First().Id,
VolunteerTaskId = Context.VolunteerTasks.Skip(1).First().Id
};
var target = new NotifyAdminForSignupHandler(Context, mediator.Object, options, logger);
await target.Handle(notification);
mediator.Verify(x => x.SendAsync(It.IsAny<NotifyVolunteersCommand>()), Times.Never);
}
}
}
| |
// 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.Globalization;
using System.IO;
using System.Text;
namespace System.Net
{
[System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public enum CookieVariant
{
Unknown,
Plain,
Rfc2109,
Rfc2965,
Default = Rfc2109
}
// Cookie class
//
// Adheres to RFC 2965
//
// Currently, only represents client-side cookies. The cookie classes know
// how to parse a set-cookie format string, but not a cookie format string
// (e.g. "Cookie: $Version=1; name=value; $Path=/foo; $Secure")
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public sealed class Cookie
{
// NOTE: these two constants must change together.
internal const int MaxSupportedVersion = 1;
internal const string MaxSupportedVersionString = "1";
internal const string SeparatorLiteral = "; ";
internal const string EqualsLiteral = "=";
internal const string QuotesLiteral = "\"";
internal const string SpecialAttributeLiteral = "$";
internal static readonly char[] PortSplitDelimiters = new char[] { ' ', ',', '\"' };
// Space (' ') should be reserved as well per RFCs, but major web browsers support it and some web sites use it - so we support it too
internal static readonly char[] ReservedToName = new char[] { '\t', '\r', '\n', '=', ';', ',' };
internal static readonly char[] ReservedToValue = new char[] { ';', ',' };
private string m_comment = string.Empty; // Do not rename (binary serialization)
private Uri m_commentUri = null; // Do not rename (binary serialization)
private CookieVariant m_cookieVariant = CookieVariant.Plain; // Do not rename (binary serialization)
private bool m_discard = false; // Do not rename (binary serialization)
private string m_domain = string.Empty; // Do not rename (binary serialization)
private bool m_domain_implicit = true; // Do not rename (binary serialization)
private DateTime m_expires = DateTime.MinValue; // Do not rename (binary serialization)
private string m_name = string.Empty; // Do not rename (binary serialization)
private string m_path = string.Empty; // Do not rename (binary serialization)
private bool m_path_implicit = true; // Do not rename (binary serialization)
private string m_port = string.Empty; // Do not rename (binary serialization)
private bool m_port_implicit = true; // Do not rename (binary serialization)
private int[] m_port_list = null; // Do not rename (binary serialization)
private bool m_secure = false; // Do not rename (binary serialization)
[System.Runtime.Serialization.OptionalField]
private bool m_httpOnly = false; // Do not rename (binary serialization)
private DateTime m_timeStamp = DateTime.Now; // Do not rename (binary serialization)
private string m_value = string.Empty; // Do not rename (binary serialization)
private int m_version = 0; // Do not rename (binary serialization)
private string m_domainKey = string.Empty; // Do not rename (binary serialization)
internal bool IsQuotedVersion = false;
internal bool IsQuotedDomain = false;
#if DEBUG
static Cookie()
{
Debug.Assert(MaxSupportedVersion.ToString(NumberFormatInfo.InvariantInfo).Equals(MaxSupportedVersionString, StringComparison.Ordinal));
}
#endif
public Cookie()
{
}
public Cookie(string name, string value)
{
Name = name;
Value = value;
}
public Cookie(string name, string value, string path)
: this(name, value)
{
Path = path;
}
public Cookie(string name, string value, string path, string domain)
: this(name, value, path)
{
Domain = domain;
}
public string Comment
{
get
{
return m_comment;
}
set
{
m_comment = value ?? string.Empty;
}
}
public Uri CommentUri
{
get
{
return m_commentUri;
}
set
{
m_commentUri = value;
}
}
public bool HttpOnly
{
get
{
return m_httpOnly;
}
set
{
m_httpOnly = value;
}
}
public bool Discard
{
get
{
return m_discard;
}
set
{
m_discard = value;
}
}
public string Domain
{
get
{
return m_domain;
}
set
{
m_domain = value ?? string.Empty;
m_domain_implicit = false;
m_domainKey = string.Empty; // _domainKey will be set when adding this cookie to a container.
}
}
internal bool DomainImplicit
{
get
{
return m_domain_implicit;
}
set
{
m_domain_implicit = value;
}
}
public bool Expired
{
get
{
return (m_expires != DateTime.MinValue) && (m_expires.ToLocalTime() <= DateTime.Now);
}
set
{
if (value == true)
{
m_expires = DateTime.Now;
}
}
}
public DateTime Expires
{
get
{
return m_expires;
}
set
{
m_expires = value;
}
}
public string Name
{
get
{
return m_name;
}
set
{
if (string.IsNullOrEmpty(value) || !InternalSetName(value))
{
throw new CookieException(SR.Format(SR.net_cookie_attribute, "Name", value == null ? "<null>" : value));
}
}
}
internal bool InternalSetName(string value)
{
if (string.IsNullOrEmpty(value) || value[0] == '$' || value.IndexOfAny(ReservedToName) != -1 || value[0] == ' ' || value[value.Length - 1] == ' ')
{
m_name = string.Empty;
return false;
}
m_name = value;
return true;
}
public string Path
{
get
{
return m_path;
}
set
{
m_path = value ?? string.Empty;
m_path_implicit = false;
}
}
internal bool Plain
{
get
{
return Variant == CookieVariant.Plain;
}
}
internal Cookie Clone()
{
Cookie clonedCookie = new Cookie(m_name, m_value);
// Copy over all the properties from the original cookie
if (!m_port_implicit)
{
clonedCookie.Port = m_port;
}
if (!m_path_implicit)
{
clonedCookie.Path = m_path;
}
clonedCookie.Domain = m_domain;
// If the domain in the original cookie was implicit, we should preserve that property
clonedCookie.DomainImplicit = m_domain_implicit;
clonedCookie.m_timeStamp = m_timeStamp;
clonedCookie.Comment = m_comment;
clonedCookie.CommentUri = m_commentUri;
clonedCookie.HttpOnly = m_httpOnly;
clonedCookie.Discard = m_discard;
clonedCookie.Expires = m_expires;
clonedCookie.Version = m_version;
clonedCookie.Secure = m_secure;
// The variant is set when we set properties like port/version. So,
// we should copy over the variant from the original cookie after
// we set all other properties
clonedCookie.m_cookieVariant = m_cookieVariant;
return clonedCookie;
}
private static bool IsDomainEqualToHost(string domain, string host)
{
// +1 in the host length is to account for the leading dot in domain
return (host.Length + 1 == domain.Length) &&
(string.Compare(host, 0, domain, 1, host.Length, StringComparison.OrdinalIgnoreCase) == 0);
}
// According to spec we must assume default values for attributes but still
// keep in mind that we must not include them into the requests.
// We also check the validity of all attributes based on the version and variant (read RFC)
//
// To work properly this function must be called after cookie construction with
// default (response) URI AND setDefault == true
//
// Afterwards, the function can be called many times with other URIs and
// setDefault == false to check whether this cookie matches given uri
internal bool VerifySetDefaults(CookieVariant variant, Uri uri, bool isLocalDomain, string localDomain, bool setDefault, bool shouldThrow)
{
string host = uri.Host;
int port = uri.Port;
string path = uri.AbsolutePath;
bool valid = true;
if (setDefault)
{
// Set Variant. If version is zero => reset cookie to Version0 style
if (Version == 0)
{
variant = CookieVariant.Plain;
}
else if (Version == 1 && variant == CookieVariant.Unknown)
{
// Since we don't expose Variant to an app, set it to Default
variant = CookieVariant.Default;
}
m_cookieVariant = variant;
}
// Check the name
if (string.IsNullOrEmpty(m_name) || m_name[0] == '$' || m_name.IndexOfAny(ReservedToName) != -1 || m_name[0] == ' ' || m_name[m_name.Length - 1] == ' ')
{
if (shouldThrow)
{
throw new CookieException(SR.Format(SR.net_cookie_attribute, "Name", m_name == null ? "<null>" : m_name));
}
return false;
}
// Check the value
if (m_value == null ||
(!(m_value.Length > 2 && m_value[0] == '\"' && m_value[m_value.Length - 1] == '\"') && m_value.IndexOfAny(ReservedToValue) != -1))
{
if (shouldThrow)
{
throw new CookieException(SR.Format(SR.net_cookie_attribute, "Value", m_value == null ? "<null>" : m_value));
}
return false;
}
// Check Comment syntax
if (Comment != null && !(Comment.Length > 2 && Comment[0] == '\"' && Comment[Comment.Length - 1] == '\"')
&& (Comment.IndexOfAny(ReservedToValue) != -1))
{
if (shouldThrow)
{
throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.CommentAttributeName, Comment));
}
return false;
}
// Check Path syntax
if (Path != null && !(Path.Length > 2 && Path[0] == '\"' && Path[Path.Length - 1] == '\"')
&& (Path.IndexOfAny(ReservedToValue) != -1))
{
if (shouldThrow)
{
throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.PathAttributeName, Path));
}
return false;
}
// Check/set domain
//
// If domain is implicit => assume a) uri is valid, b) just set domain to uri hostname.
if (setDefault && m_domain_implicit == true)
{
m_domain = host;
}
else
{
if (!m_domain_implicit)
{
// Forwarding note: If Uri.Host is of IP address form then the only supported case
// is for IMPLICIT domain property of a cookie.
// The code below (explicit cookie.Domain value) will try to parse Uri.Host IP string
// as a fqdn and reject the cookie.
// Aliasing since we might need the KeyValue (but not the original one).
string domain = m_domain;
// Syntax check for Domain charset plus empty string.
if (!DomainCharsTest(domain))
{
if (shouldThrow)
{
throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.DomainAttributeName, domain == null ? "<null>" : domain));
}
return false;
}
// Domain must start with '.' if set explicitly.
if (domain[0] != '.')
{
if (!(variant == CookieVariant.Rfc2965 || variant == CookieVariant.Plain))
{
if (shouldThrow)
{
throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.DomainAttributeName, m_domain));
}
return false;
}
domain = '.' + domain;
}
int host_dot = host.IndexOf('.');
// First quick check is for pushing a cookie into the local domain.
if (isLocalDomain && string.Equals(localDomain, domain, StringComparison.OrdinalIgnoreCase))
{
valid = true;
}
else if (domain.IndexOf('.', 1, domain.Length - 2) == -1)
{
// A single label domain is valid only if the domain is exactly the same as the host specified in the URI.
if (!IsDomainEqualToHost(domain, host))
{
valid = false;
}
}
else if (variant == CookieVariant.Plain)
{
// We distinguish between Version0 cookie and other versions on domain issue.
// According to Version0 spec a domain must be just a substring of the hostname.
if (!IsDomainEqualToHost(domain, host))
{
if (host.Length <= domain.Length ||
(string.Compare(host, host.Length - domain.Length, domain, 0, domain.Length, StringComparison.OrdinalIgnoreCase) != 0))
{
valid = false;
}
}
}
else if (host_dot == -1 ||
domain.Length != host.Length - host_dot ||
(string.Compare(host, host_dot, domain, 0, domain.Length, StringComparison.OrdinalIgnoreCase) != 0))
{
// Starting from the first dot, the host must match the domain.
//
// For null hosts, the host must match the domain exactly.
if (!IsDomainEqualToHost(domain, host))
{
valid = false;
}
}
if (valid)
{
m_domainKey = domain.ToLowerInvariant();
}
}
else
{
// For implicitly set domain AND at the set_default == false time
// we simply need to match uri.Host against m_domain.
if (!string.Equals(host, m_domain, StringComparison.OrdinalIgnoreCase))
{
valid = false;
}
}
if (!valid)
{
if (shouldThrow)
{
throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.DomainAttributeName, m_domain));
}
return false;
}
}
// Check/Set Path
if (setDefault && m_path_implicit == true)
{
// This code assumes that the URI path is always valid and contains at least one '/'.
switch (m_cookieVariant)
{
case CookieVariant.Plain:
m_path = path;
break;
case CookieVariant.Rfc2109:
m_path = path.Substring(0, path.LastIndexOf('/')); // May be empty
break;
case CookieVariant.Rfc2965:
default:
// NOTE: this code is not resilient against future versions with different 'Path' semantics.
m_path = path.Substring(0, path.LastIndexOf('/') + 1);
break;
}
}
else
{
// Check current path (implicit/explicit) against given URI.
if (!path.StartsWith(CookieParser.CheckQuoted(m_path)))
{
if (shouldThrow)
{
throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.PathAttributeName, m_path));
}
return false;
}
}
// Set the default port if Port attribute was present but had no value.
if (setDefault && (m_port_implicit == false && m_port.Length == 0))
{
m_port_list = new int[1] { port };
}
if (m_port_implicit == false)
{
// Port must match against the one from the uri.
valid = false;
foreach (int p in m_port_list)
{
if (p == port)
{
valid = true;
break;
}
}
if (!valid)
{
if (shouldThrow)
{
throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.PortAttributeName, m_port));
}
return false;
}
}
return true;
}
// Very primitive test to make sure that the name does not have illegal characters
// as per RFC 952 (relaxed on first char could be a digit and string can have '_').
private static bool DomainCharsTest(string name)
{
if (name == null || name.Length == 0)
{
return false;
}
for (int i = 0; i < name.Length; ++i)
{
char ch = name[i];
if (!((ch >= '0' && ch <= '9') ||
(ch == '.' || ch == '-') ||
(ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z') ||
(ch == '_')))
{
return false;
}
}
return true;
}
public string Port
{
get
{
return m_port;
}
set
{
m_port_implicit = false;
if (string.IsNullOrEmpty(value))
{
// "Port" is present but has no value.
m_port = string.Empty;
}
else
{
// Parse port list
if (value[0] != '\"' || value[value.Length - 1] != '\"')
{
throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.PortAttributeName, value));
}
string[] ports = value.Split(PortSplitDelimiters);
List<int> portList = new List<int>();
int port;
for (int i = 0; i < ports.Length; ++i)
{
// Skip spaces
if (ports[i] != string.Empty)
{
if (!int.TryParse(ports[i], out port))
{
throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.PortAttributeName, value));
}
// valid values for port 0 - 0xFFFF
if ((port < 0) || (port > 0xFFFF))
{
throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.PortAttributeName, value));
}
portList.Add(port);
}
}
m_port_list = portList.ToArray();
m_port = value;
m_version = MaxSupportedVersion;
m_cookieVariant = CookieVariant.Rfc2965;
}
}
}
internal int[] PortList
{
get
{
// PortList will be null if Port Attribute was omitted in the response.
return m_port_list;
}
}
public bool Secure
{
get
{
return m_secure;
}
set
{
m_secure = value;
}
}
public DateTime TimeStamp
{
get
{
return m_timeStamp;
}
}
public string Value
{
get
{
return m_value;
}
set
{
m_value = value ?? string.Empty;
}
}
internal CookieVariant Variant
{
get
{
return m_cookieVariant;
}
set
{
// Only set by HttpListenerRequest::Cookies_get()
if (value != CookieVariant.Rfc2965)
{
NetEventSource.Fail(this, $"value != Rfc2965:{value}");
}
m_cookieVariant = value;
}
}
// _domainKey member is set internally in VerifySetDefaults().
// If it is not set then verification function was not called;
// this should never happen.
internal string DomainKey
{
get
{
return m_domain_implicit ? Domain : m_domainKey;
}
}
public int Version
{
get
{
return m_version;
}
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
m_version = value;
if (value > 0 && m_cookieVariant < CookieVariant.Rfc2109)
{
m_cookieVariant = CookieVariant.Rfc2109;
}
}
}
public override bool Equals(object comparand)
{
Cookie other = comparand as Cookie;
return other != null
&& string.Equals(Name, other.Name, StringComparison.OrdinalIgnoreCase)
&& string.Equals(Value, other.Value, StringComparison.Ordinal)
&& string.Equals(Path, other.Path, StringComparison.Ordinal)
&& string.Equals(Domain, other.Domain, StringComparison.OrdinalIgnoreCase)
&& (Version == other.Version);
}
public override int GetHashCode()
{
return (Name + "=" + Value + ";" + Path + "; " + Domain + "; " + Version).GetHashCode();
}
public override string ToString()
{
StringBuilder sb = StringBuilderCache.Acquire();
ToString(sb);
return StringBuilderCache.GetStringAndRelease(sb);
}
internal void ToString(StringBuilder sb)
{
int beforeLength = sb.Length;
// Add the Cookie version if necessary.
if (Version != 0)
{
sb.Append(SpecialAttributeLiteral + CookieFields.VersionAttributeName + EqualsLiteral); // const strings
if (IsQuotedVersion) sb.Append('"');
sb.Append(m_version.ToString(NumberFormatInfo.InvariantInfo));
if (IsQuotedVersion) sb.Append('"');
sb.Append(SeparatorLiteral);
}
// Add the Cookie Name=Value pair.
sb.Append(Name).Append(EqualsLiteral).Append(Value);
if (!Plain)
{
// Add the Path if necessary.
if (!m_path_implicit && m_path.Length > 0)
{
sb.Append(SeparatorLiteral + SpecialAttributeLiteral + CookieFields.PathAttributeName + EqualsLiteral); // const strings
sb.Append(m_path);
}
// Add the Domain if necessary.
if (!m_domain_implicit && m_domain.Length > 0)
{
sb.Append(SeparatorLiteral + SpecialAttributeLiteral + CookieFields.DomainAttributeName + EqualsLiteral); // const strings
if (IsQuotedDomain) sb.Append('"');
sb.Append(m_domain);
if (IsQuotedDomain) sb.Append('"');
}
}
// Add the Port if necessary.
if (!m_port_implicit)
{
sb.Append(SeparatorLiteral + SpecialAttributeLiteral + CookieFields.PortAttributeName); // const strings
if (m_port.Length > 0)
{
sb.Append(EqualsLiteral);
sb.Append(m_port);
}
}
// Check to see whether the only thing we added was "=", and if so,
// remove it so that we leave the StringBuilder unchanged in contents.
int afterLength = sb.Length;
if (afterLength == (1 + beforeLength) && sb[beforeLength] == '=')
{
sb.Length = beforeLength;
}
}
internal string ToServerString()
{
string result = Name + EqualsLiteral + Value;
if (m_comment != null && m_comment.Length > 0)
{
result += SeparatorLiteral + CookieFields.CommentAttributeName + EqualsLiteral + m_comment;
}
if (m_commentUri != null)
{
result += SeparatorLiteral + CookieFields.CommentUrlAttributeName + EqualsLiteral + QuotesLiteral + m_commentUri.ToString() + QuotesLiteral;
}
if (m_discard)
{
result += SeparatorLiteral + CookieFields.DiscardAttributeName;
}
if (!m_domain_implicit && m_domain != null && m_domain.Length > 0)
{
result += SeparatorLiteral + CookieFields.DomainAttributeName + EqualsLiteral + m_domain;
}
if (Expires != DateTime.MinValue)
{
int seconds = (int)(Expires.ToLocalTime() - DateTime.Now).TotalSeconds;
if (seconds < 0)
{
// This means that the cookie has already expired. Set Max-Age to 0
// so that the client will discard the cookie immediately.
seconds = 0;
}
result += SeparatorLiteral + CookieFields.MaxAgeAttributeName + EqualsLiteral + seconds.ToString(NumberFormatInfo.InvariantInfo);
}
if (!m_path_implicit && m_path != null && m_path.Length > 0)
{
result += SeparatorLiteral + CookieFields.PathAttributeName + EqualsLiteral + m_path;
}
if (!Plain && !m_port_implicit && m_port != null && m_port.Length > 0)
{
// QuotesLiteral are included in _port.
result += SeparatorLiteral + CookieFields.PortAttributeName + EqualsLiteral + m_port;
}
if (m_version > 0)
{
result += SeparatorLiteral + CookieFields.VersionAttributeName + EqualsLiteral + m_version.ToString(NumberFormatInfo.InvariantInfo);
}
return result == EqualsLiteral ? null : result;
}
}
}
| |
using System;
using System.Text;
using System.Xml;
using System.Text.RegularExpressions;
using System.Collections;
namespace NLipsum.Core {
/// <summary>
/// Represents a utility that generates Lipsum from a source.
/// </summary>
public class LipsumGenerator {
private StringBuilder _lipsumText = null;
private string[] _preparedWords = new string[] { };
#region Constructors
/// <summary>
/// Instantiates a LipsumGenerator using the <see cref="Lipsums.LoremIpsum"/> text corpus.
/// </summary>
public LipsumGenerator()
{
this.LipsumText = new StringBuilder(Lipsums.LoremIpsum);
}
/// <summary>
/// Instantiates a LipsumGenerator with the passed data.
/// </summary>
/// <param name="rawData">The data to be used as LipsumText.</param>
/// <param name="isXml">Whether the data is in an Xml format and should be parsed for the LipsumText.</param>
public LipsumGenerator(string rawData, bool isXml) {
/*
* If we're receiving an XML string we need to do some
* parsing to retrieve the lipsum text.
*/
this.LipsumText = isXml ?
LipsumUtilities.GetTextFromRawXml(rawData) : new StringBuilder(rawData);
}
#endregion
#region General/TopLevel Generators
/// <summary>
/// Generates 'count' medium length paragraphs separated by environment linebreaks.
/// </summary>
/// <param name="count">The number of paragraphs desired.</param>
/// <returns></returns>
public string GenerateLipsum(int count) {
return GenerateLipsum(count, Features.Paragraphs, FormatStrings.Paragraph.LineBreaks);
}
/// <summary>
/// Generates 'count' medium length paragraphs surrounded by html paragraph tags.
/// </summary>
/// <param name="count">The number of paragraphs desired.</param>
/// <returns></returns>
public string GenerateLipsumHtml(int count) {
return GenerateLipsum(count, Features.Paragraphs, FormatStrings.Paragraph.Html);
}
/// <summary>
/// Generates 'count' features. The format string will be applied to the feature not the result.
/// </summary>
/// <param name="count">How many features are desired.</param>
/// <param name="feature">The desired feature, such as Paragraph or Sentence.</param>
/// <param name="formatString">The formatting to apply to each feature.</param>
/// <returns></returns>
public string GenerateLipsum(int count, Features part, string formatString) {
StringBuilder results = new StringBuilder();
string[] data = new string[] { };
if (part == Features.Paragraphs) {
data = GenerateParagraphs(count, formatString);
} else if (part == Features.Sentences) {
data = GenerateSentences(count, formatString);
} else if (part == Features.Words) {
data = GenerateWords(count);
} else if (part == Features.Characters) {
data = GenerateCharacters(count);
} else {
throw new NotImplementedException("Sorry, this is not yet implemented.");
}
int length = data.Length;
for (int i = 0; i < length; i++) {
results.Append(data[i]);
}
return results.ToString();
}
#endregion
#region Static Generators
/// <summary>
/// Generates 'count' medium length paragraphs separated by environment linebreaks.
/// Standard Lorem Ipsum text will be used.
/// </summary>
/// <param name="count">The number of paragraphs desired.</param>
/// <returns></returns>
public static string Generate(int count) {
return Generate(count, Lipsums.LoremIpsum);
}
/// <summary>
/// Generates 'count' medium length paragraphs surrounded by Html paragraph tags.
/// Standard Lorem Ipsum text will be used.
/// </summary>
/// <param name="count">The number of paragraphs desired.</param>
/// <returns></returns>
public static string GenerateHtml(int count) {
return Generate(count, FormatStrings.Paragraph.Html, Lipsums.LoremIpsum);
}
/// <summary>
/// Generates 'count' medium length paragraphs separated by environment linebreaks.
/// </summary>
/// <param name="count">The number of paragraphs desired.</param>
/// <param name="rawText">The text from which to generate the Lipsum.</param>
/// <returns></returns>
public static string Generate(int count, string rawText) {
return Generate(count, FormatStrings.Paragraph.LineBreaks, rawText);
}
/// <summary>
/// Generates 'count' medium length paragraphs.
/// </summary>
/// <param name="count">The number of paragraphs desired.</param>
/// <param name="formatString">The string with which to format the feature.</param>
/// <param name="rawText">The text from which to generate the Lipsum.</param>
/// <returns></returns>
public static string Generate(int count, string formatString, string rawText) {
return Generate(count, Features.Paragraphs, formatString, rawText);
}
/// <summary>
/// Generates 'count' features.
/// </summary>
/// <param name="count">The number of features desired.</param>
/// <param name="feature">The type of feature desired.</param>
/// <param name="formatString">The string with which to format the feature.</param>
/// <param name="rawText">The text from which to generate the Lipsum.</param>
/// <returns></returns>
public static string Generate(int count, Features feature, string formatString, string rawText) {
LipsumGenerator generator = new LipsumGenerator(rawText, false);
return generator.GenerateLipsum(count, feature, formatString);
}
#endregion
#region Characters
/// <summary>
/// Generates a single string (in an array with only this as an element)
/// by getting the first 'count' characters from LipsumText.
/// </summary>
/// <param name="count"></param>
/// <param name="formatString"></param>
/// <returns></returns>
public string[] GenerateCharacters(int count) {
string[] result = new string[1];
/* This whole method needs some thought.
* Right now it just grabs 'count' amount
* of characters from the beginning of the
* LipsumText. It'd be nice if it could
* generate sentences and then truncate them
* but I can't think of an elegant way to
* do that at the moment. TODO. */
if (count >= LipsumText.Length) {
count = LipsumText.Length - 1;
}
char[] chars = LipsumText.ToString().Substring(0, count).ToCharArray();
result[0] = new String(chars);
return result;
}
#endregion
#region Paragraphs
/// <summary>
/// Generates 'count' medium-sized paragraphs of lipsum text.
/// </summary>
/// <param name="count">The number of paragraphs desired.</param>
public string[] GenerateParagraphs(int count) {
return GenerateParagraphs(count, "");
}
/// <summary>
/// Generates 'count' medium-sized paragraphs of lipsum text.
/// </summary>
/// <param name="count">The number of paragraphs desired.</param>
/// <param name="formatString">The string used to format the paragraphs. Will not perform formatting if null or empty.</param>
public string[] GenerateParagraphs(int count, string formatString) {
Paragraph options = Paragraph.Medium;
options.FormatString = formatString;
return GenerateParagraphs(count, options);
}
/// <summary>
/// Generates 'count' paragraphs of lipsum text.
/// </summary>
/// <param name="count">The number of paragraphs desired.</param>
/// <param name="options">Used to determine the minimum and maximum sentences per paragraphs, and format string if applicable.</param>
/// <returns></returns>
public string[] GenerateParagraphs(int count, Paragraph options) {
/*
* TODO: These generate methods could probably be
* refactored into one method that takes a count
* and a TextFeature. */
string[] paragraphs = new string[count];
string[] sentences = new string[] { };
for (int i = 0; i < count; i++) {
/* Get a random amount of sentences based on the
* min and max from the paragraph options */
sentences = GenerateSentences(LipsumUtilities.
RandomInt((int)options.GetMinimum(), (int)options.GetMaximum()));
// Shove them all together in sentence fashion.
string joined = String.Join(options.Delimiter, sentences);
// Format if allowed.
paragraphs[i] = String.IsNullOrEmpty(options.FormatString) ?
joined : options.Format(joined);
}
return paragraphs;
}
#endregion
#region Sentences
/// <summary>
/// Generates 'count' sentences of lipsum text, using a Medium length sentence. Will use Phase formatting.
/// </summary>
/// <param name="count">The number of sentences desired.</param>
public string[] GenerateSentences(int count) {
return GenerateSentences(count, FormatStrings.Sentence.Phrase);
}
/// <summary>
/// Generates 'count' sentences of lipsum text, using a Medium length sentence.
/// </summary>
/// <param name="count">The number of sentences desired.</param>
/// <param name="formatString">The string used to format the sentences. Will not perform formatting if null or empty.</param>
/// <returns></returns>
public string[] GenerateSentences(int count, string formatString) {
Sentence options = Sentence.Medium;
options.FormatString = formatString;
return GenerateSentences(count, options);
}
/// <summary>
/// Generates 'count' sentences of lipsum text.
/// If options.FormatString is not null or empty that string used to format the sentences.
/// </summary>
/// <param name="count">The number of sentences desired.</param>
/// <param name="options">Used to determine the minimum and maximum words per sentence, and format string if applicable.</param>
/// <returns></returns>
public string[] GenerateSentences(int count, Sentence options) {
string[] sentences = new string[count];
string[] words = new string[] { };
for (int i = 0; i < count; i++) {
/* Get a random amount of words based on the
* min and max from the Sentence options */
words = GenerateWords(LipsumUtilities.
RandomInt((int)options.MinimumWords, (int)options.MaximumWords));
// Shove them all together in sentence fashion.
string joined = String.Join(options.Delimiter, words);
// Format if allowed.
sentences[i] = String.IsNullOrEmpty(options.FormatString) ?
joined : options.Format(joined);
}
return sentences;
}
#endregion
#region Words
/// <summary>
/// Generates the amount of lipsum words.
/// </summary>
/// <param name="count">The amount of words to generate.</param>
/// <returns></returns>
public string[] GenerateWords(int count) {
string[] words = new string[count];
for (int i = 0; i < count; i++) {
words[i] = LipsumUtilities.RandomElement(PreparedWords);
}
return words;
}
/// <summary>
/// Retreives all of the words in the LipsumText as an array.
/// </summary>
/// <returns></returns>
public string[] PrepareWords() {
return LipsumUtilities.RemoveEmptyElements(
Regex.Split(this.LipsumText.ToString(), @"\s"));
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the text used to generate lipsum.
/// </summary>
public StringBuilder LipsumText {
get { return _lipsumText; }
set {
_lipsumText = value;
PreparedWords = PrepareWords();
}
}
/// <summary>
/// Gets the words prepared from the LipsumText.
/// </summary>
public string[] PreparedWords {
get { return _preparedWords; }
protected set { _preparedWords = value; }
}
#endregion
public string RandomWord() {
return LipsumUtilities.RandomElement(PreparedWords);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="UpdatePanel.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.UI {
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Drawing.Design;
using System.Globalization;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.Resources;
using System.Web.Util;
using Debug = System.Diagnostics.Debug;
[
DefaultProperty("Triggers"),
Designer("System.Web.UI.Design.UpdatePanelDesigner, " + AssemblyRef.SystemWebExtensionsDesign),
ParseChildren(true),
PersistChildren(false),
ToolboxBitmap(typeof(EmbeddedResourceFinder), "System.Web.Resources.UpdatePanel.bmp")
]
public class UpdatePanel : Control, IAttributeAccessor, IUpdatePanel {
private const string UpdatePanelToken = "updatePanel";
private new IPage _page;
private IScriptManagerInternal _scriptManager;
private AttributeCollection _attributes;
private bool _childrenAsTriggers = true;
private ITemplate _contentTemplate;
private Control _contentTemplateContainer;
private bool _asyncPostBackMode;
private bool _asyncPostBackModeInitialized;
private UpdatePanelUpdateMode _updateMode = UpdatePanelUpdateMode.Always;
private bool _rendered;
private bool _explicitUpdate;
private UpdatePanelRenderMode _renderMode = UpdatePanelRenderMode.Block;
private UpdatePanelTriggerCollection _triggers;
// Keep an explicit check whether the panel registered with ScriptManager. Sometimes
// OnInit is not called on the panel, so then OnUnload gets called and you get an
// exception. This can happen if an unhandled exception happened on the page before Init
// and the page unloads.
private bool _panelRegistered;
public UpdatePanel() {
}
internal UpdatePanel(IScriptManagerInternal scriptManager, IPage page) {
_scriptManager = scriptManager;
_page = page;
}
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
WebSysDescription(SR.WebControl_Attributes)
]
public AttributeCollection Attributes {
get {
if (_attributes == null) {
StateBag bag = new StateBag(true /* ignoreCase */);
_attributes = new AttributeCollection(bag);
}
return _attributes;
}
}
[
ResourceDescription("UpdatePanel_ChildrenAsTriggers"),
Category("Behavior"),
DefaultValue(true),
]
public bool ChildrenAsTriggers {
get {
return _childrenAsTriggers;
}
set {
_childrenAsTriggers = value;
}
}
[
Browsable(false),
PersistenceMode(PersistenceMode.InnerProperty),
TemplateInstance(TemplateInstance.Single),
]
public ITemplate ContentTemplate {
get {
return _contentTemplate;
}
set {
if (!DesignMode && _contentTemplate != null) {
throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.UpdatePanel_CannotSetContentTemplate, ID));
}
_contentTemplate = value;
if (_contentTemplate != null) {
// DevDiv 79989: Instantiate the template immediately so that the controls are available as soon as possible
CreateContents();
}
}
}
public sealed override ControlCollection Controls {
get {
// We override and seal this property because we have very special semantics
// on the behavior of this property and the type of ControlCollection we create.
return base.Controls;
}
}
[
Browsable(false),
]
public Control ContentTemplateContainer {
get {
if (_contentTemplateContainer == null) {
_contentTemplateContainer = CreateContentTemplateContainer();
AddContentTemplateContainer();
}
return _contentTemplateContainer;
}
}
[
Browsable(false),
]
public bool IsInPartialRendering {
get {
return _asyncPostBackMode;
}
}
private IPage IPage {
get {
if (_page != null) {
return _page;
}
else {
Page page = Page;
if (page == null) {
throw new InvalidOperationException(AtlasWeb.Common_PageCannotBeNull);
}
return new PageWrapper(page);
}
}
}
protected internal virtual bool RequiresUpdate {
get {
if (_explicitUpdate || (UpdateMode == UpdatePanelUpdateMode.Always)) {
return true;
}
if ((_triggers == null) || (_triggers.Count == 0)) {
return false;
}
return _triggers.HasTriggered();
}
}
[
ResourceDescription("UpdatePanel_RenderMode"),
Category("Layout"),
DefaultValue(UpdatePanelRenderMode.Block),
]
public UpdatePanelRenderMode RenderMode {
get {
return _renderMode;
}
set {
if (value < UpdatePanelRenderMode.Block || value > UpdatePanelRenderMode.Inline) {
throw new ArgumentOutOfRangeException("value");
}
_renderMode = value;
}
}
internal IScriptManagerInternal ScriptManager {
get {
if (_scriptManager == null) {
Page page = Page;
if (page == null) {
throw new InvalidOperationException(AtlasWeb.Common_PageCannotBeNull);
}
_scriptManager = UI.ScriptManager.GetCurrent(page);
if (_scriptManager == null) {
throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.Common_ScriptManagerRequired, ID));
}
}
return _scriptManager;
}
}
[
Category("Behavior"),
DefaultValue(null),
Editor("System.Web.UI.Design.UpdatePanelTriggerCollectionEditor, " +
AssemblyRef.SystemWebExtensionsDesign, typeof(UITypeEditor)),
ResourceDescription("UpdatePanel_Triggers"),
PersistenceMode(PersistenceMode.InnerProperty),
MergableProperty(false),
]
public UpdatePanelTriggerCollection Triggers {
get {
if (_triggers == null) {
// NOTE: This is not view state managed, because the update panel trigger
// collection needs to be ready by InitComplete (so that
// Initialize of all triggers gets called at init time), which
// implies that the trigger collection cannot be modified
// beyond what was set up declaratively.
_triggers = new UpdatePanelTriggerCollection(this);
}
return _triggers;
}
}
[
ResourceDescription("UpdatePanel_UpdateMode"),
Category("Behavior"),
DefaultValue(UpdatePanelUpdateMode.Always),
]
public UpdatePanelUpdateMode UpdateMode {
get {
return _updateMode;
}
set {
if (value < UpdatePanelUpdateMode.Always || value > UpdatePanelUpdateMode.Conditional) {
throw new ArgumentOutOfRangeException("value");
}
_updateMode = value;
}
}
private SingleChildControlCollection ChildControls {
get {
SingleChildControlCollection singleChildCollection = Controls as SingleChildControlCollection;
Debug.Assert(singleChildCollection != null, "The Controls property did not return the expected control collection instance.");
return singleChildCollection;
}
}
private void AddContentTemplateContainer() {
// This will call an internal method to specially add the
// ContentTemplateContainer to the control tree safely.
ChildControls.AddSingleChild(_contentTemplateContainer);
}
internal void ClearContent() {
Debug.Assert(DesignMode, "ClearContent should only be used in DesignMode.");
// DevDiv Bugs 135848:
// Called from UpdatePanelDesigner to clear control tree when
// GetDesignTimeHtml(DesignerRegionCollection regions) is called, necessary to avoid
// duplicate controls being created at design time. See comment in UpdatePanelDesigner.
ContentTemplateContainer.Controls.Clear();
_contentTemplateContainer = null;
ChildControls.ClearInternal();
}
private void CreateContents() {
if (DesignMode) {
// Clear out old stuff
ClearContent();
}
// The ContentTemplateContainer may have already been created by someone due to
// some dynamic access. If the container already exists and there is a ContentTemplate,
// we will instantiate into it.
if (_contentTemplateContainer == null) {
_contentTemplateContainer = CreateContentTemplateContainer();
// The controls inside the template are instantiated into
// a dummy container to ensure that they all do lifecycle catchup
// at the same time (i.e. Init1, Init2, Load1, Load2) as opposed to
// one after another (i.e. Init1, Load1, Init2, Load2).
if (_contentTemplate != null) {
_contentTemplate.InstantiateIn(_contentTemplateContainer);
}
AddContentTemplateContainer();
}
else if (_contentTemplate != null) {
// Someone already created a ContentTemplateContainer, instantiate into it
_contentTemplate.InstantiateIn(_contentTemplateContainer);
}
}
protected virtual Control CreateContentTemplateContainer() {
return new Control();
}
protected sealed override ControlCollection CreateControlCollection() {
// We override and seal this method because we have very special semantics
// on the behavior of this method and the type of ControlCollection we create.
return new SingleChildControlCollection(this);
}
protected internal virtual void Initialize() {
if (_triggers != null) {
if (ScriptManager.SupportsPartialRendering) {
// Triggers need to be initialized in initial requests as well as all postbacks,
// however only if partial rendering is enabled.
_triggers.Initialize();
}
}
}
[SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")]
protected internal override void OnInit(EventArgs e) {
base.OnInit(e);
RegisterPanel();
// DevDiv 79989: Whether the template has been set or not we need to ensure
// the template container is created by Init to remain consistent with 1.0.
if (_contentTemplateContainer == null) {
_contentTemplateContainer = CreateContentTemplateContainer();
AddContentTemplateContainer();
}
}
[SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")]
protected internal override void OnLoad(EventArgs e) {
base.OnLoad(e);
if (!DesignMode) {
if (!ScriptManager.IsInAsyncPostBack) {
// In partial rendering mode, ScriptManager calls Initialize.
// In all other cases we have to initialize here.
// This will cause things like AsyncPostBackTrigger to
// register event handlers for control events, which in turn
// will lead controls to track property values in view state
// and appropriately detect changes on the subsequent postbacks.
Initialize();
}
}
}
[SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")]
protected internal override void OnPreRender(EventArgs e) {
base.OnPreRender(e);
if (!ChildrenAsTriggers && UpdateMode == UpdatePanelUpdateMode.Always) {
throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.UpdatePanel_ChildrenTriggersAndUpdateAlways, ID));
}
}
[SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")]
protected internal override void OnUnload(EventArgs e) {
if (!DesignMode && _panelRegistered) {
ScriptManager.UnregisterUpdatePanel(this);
}
base.OnUnload(e);
}
private void RegisterPanel() {
// Safeguard against registering in design mode, and against registering twice
if (!DesignMode && !_panelRegistered) {
// Before we can register we need to make sure all our parent panel (if any) has
// registered already. This is critical since the ScriptManager assumes that
// the panels are registered in a specific order.
Control parent = Parent;
while (parent != null) {
UpdatePanel parentUpdatePanel = parent as UpdatePanel;
if (parentUpdatePanel != null) {
parentUpdatePanel.RegisterPanel();
break;
}
parent = parent.Parent;
}
// Now we can register ourselves
ScriptManager.RegisterUpdatePanel(this);
_panelRegistered = true;
}
}
protected internal override void Render(HtmlTextWriter writer) {
IPage.VerifyRenderingInServerForm(this);
base.Render(writer);
}
protected internal override void RenderChildren(HtmlTextWriter writer) {
if (_asyncPostBackMode) {
Debug.Assert(!DesignMode, "Shouldn't be in DesignMode");
// Render might sometimes be called twice instead of just once if we are forcing
// all controls to render to ensure EventValidation is valid.
if (_rendered) {
return;
}
HtmlTextWriter childWriter = new HtmlTextWriter(new StringWriter(CultureInfo.CurrentCulture));
base.RenderChildren(childWriter);
PageRequestManager.EncodeString(writer, UpdatePanelToken, ClientID, childWriter.InnerWriter.ToString());
}
else {
Debug.Assert(!_rendered);
writer.AddAttribute(HtmlTextWriterAttribute.Id, ClientID);
if (_attributes != null) {
_attributes.AddAttributes(writer);
}
if (RenderMode == UpdatePanelRenderMode.Block) {
writer.RenderBeginTag(HtmlTextWriterTag.Div);
}
else {
writer.RenderBeginTag(HtmlTextWriterTag.Span);
}
base.RenderChildren(writer);
writer.RenderEndTag();
}
_rendered = true;
}
internal void SetAsyncPostBackMode(bool asyncPostBackMode) {
if (_asyncPostBackModeInitialized) {
throw new InvalidOperationException(AtlasWeb.UpdatePanel_SetPartialRenderingModeCalledOnce);
}
_asyncPostBackMode = asyncPostBackMode;
_asyncPostBackModeInitialized = true;
}
public void Update() {
if (UpdateMode == UpdatePanelUpdateMode.Always) {
throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.UpdatePanel_UpdateConditional, ID));
}
if (_asyncPostBackModeInitialized) {
throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.UpdatePanel_UpdateTooLate, ID));
}
_explicitUpdate = true;
}
string IAttributeAccessor.GetAttribute(string key) {
return (_attributes != null) ? _attributes[key] : null;
}
void IAttributeAccessor.SetAttribute(string key, string value) {
Attributes[key] = value;
}
private sealed class SingleChildControlCollection : ControlCollection {
private bool _allowClear;
public SingleChildControlCollection(Control owner)
: base(owner) {
}
internal void AddSingleChild(Control child) {
Debug.Assert(Count == 0, "The collection must be empty if this is called");
base.Add(child);
}
public override void Add(Control child) {
throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.UpdatePanel_CannotModifyControlCollection, Owner.ID));
}
public override void AddAt(int index, Control child) {
throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.UpdatePanel_CannotModifyControlCollection, Owner.ID));
}
public override void Clear() {
throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.UpdatePanel_CannotModifyControlCollection, Owner.ID));
}
internal void ClearInternal() {
try {
_allowClear = true;
base.Clear();
}
finally {
_allowClear = false;
}
}
public override void Remove(Control value) {
if (!_allowClear) {
throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.UpdatePanel_CannotModifyControlCollection, Owner.ID));
}
base.Remove(value);
}
public override void RemoveAt(int index) {
if (!_allowClear) {
throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.UpdatePanel_CannotModifyControlCollection, Owner.ID));
}
base.RemoveAt(index);
}
}
}
}
| |
/*
* BvhImporter.cs
* Copyright (c) 2006, 2007 Michael Nikonov, David Astle
*
* 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.
*/
#region Using Statements
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline;
using Microsoft.Xna.Framework;
using System.Xml.Serialization;
using System.Xml;
using System.Globalization;
#endregion
namespace FlatRedBall.Graphics.Model.Animation.Content
{
/// <summary>
/// Imports BVH (Biovision hierarchical) animation data.
/// </summary>
[ContentImporter(".BVH", CacheImportedData = true, DefaultProcessor = "AnimationProcessor",
DisplayName = "BVH - Animation Library")]
internal sealed class BvhImporter : ContentImporter<BoneContent>
{
private char[] whiteSpace = { ' ', '\t', '\r', '\n' };
private ContentImporterContext context;
private StreamReader reader;
private List<BoneInfo> bones;
private ContentIdentity contentId;
private int currentLine = 0;
private BoneContent root;
int frames = 0;
double frameTime = 0.0;
private ContentIdentity cId
{
get
{
contentId.FragmentIdentifier = "line " + currentLine.ToString();
return contentId;
}
}
public static float ParseFloat(string data)
{
return float.Parse(data, NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat);
}
/// <summary>
/// Imports BVH (Biovision hierarchical) animation data.
/// Stores animation data in root bone.
/// </summary>
public override BoneContent Import(string filename, ContentImporterContext context)
{
this.context = context;
contentId = new ContentIdentity(filename, GetType().ToString());
AnimationContent animation = new AnimationContent();
animation.Name = Path.GetFileNameWithoutExtension(filename);
animation.Identity = contentId;
bones = new List<BoneInfo>();
reader = new StreamReader(filename);
String line;
if ((line = readLine()) != "HIERARCHY")
{
throw new InvalidContentException("no HIERARCHY found", cId);
}
BoneContent bone = root;
while ((line = readLine()) != "MOTION")
{
if (line == null)
throw new InvalidContentException("premature end of file", cId);
string keyword = line.Split(whiteSpace)[0];
if (keyword == "ROOT" || keyword == "JOINT" || line == "End Site")
{
BoneInfo boneInfo = new BoneInfo();
BoneContent newBone = new BoneContent();
if (keyword == "JOINT" || line == "End Site")
{
bone.Children.Add(newBone);
}
if (keyword == "ROOT")
{
root = newBone;
}
if (keyword == "ROOT" || keyword == "JOINT")
{
newBone.Name = line.Split(whiteSpace)[1];
boneInfo.bone = newBone;
bones.Add(boneInfo);
}
else
{
newBone.Name = bone.Name + "End";
}
if ((line = readLine()) != "{")
{
throw new InvalidContentException("expected '{' but found " + line, cId);
}
line = readLine();
if (line!=null && line.StartsWith("OFFSET"))
{
string[] data = line.Split(whiteSpace);
//couldn't get the .NET 2.0 version of Split() working,
//therefore this ugly hack
List<string> coords = new List<string>();
foreach (string s in data)
{
if (s != "OFFSET" && s != "" && s != null)
{
coords.Add(s);
}
}
Vector3 v = new Vector3();
v.X = ParseFloat(coords[0]);
v.Y = ParseFloat(coords[1]);
v.Z = ParseFloat(coords[2]);
Matrix offset = Matrix.CreateTranslation(v);
newBone.Transform = offset;
}
else
{
throw new InvalidContentException("expected 'OFFSET' but found " + line, cId);
}
if (keyword == "ROOT" || keyword == "JOINT")
{
line = readLine();
if (line != null && line.StartsWith("CHANNELS"))
{
string[] channels = line.Split(whiteSpace);
for (int i = 2; i < channels.Length; i++)
{
if (channels[i]!=null && channels[i]!="")
boneInfo.Add(channels[i]);
}
}
else
{
throw new InvalidContentException("expected 'CHANNELS' but found " + line, cId);
}
}
bone = newBone;
}
if (line == "}")
{
bone = (BoneContent)bone.Parent;
}
}
if ((line = readLine()) != null)
{
string[] data = line.Split(':');
if (data[0] == "Frames")
{
frames = int.Parse(data[1].Trim());
}
}
if ((line = readLine()) != null)
{
string[] data = line.Split(':');
if (data[0] == "Frame Time")
{
frameTime = double.Parse(data[1].Trim());
}
}
animation.Duration = TimeSpan.FromSeconds(frameTime * frames);
root.Animations.Add(animation.Name, animation);
foreach (BoneInfo b in bones)
{
animation.Channels.Add(b.bone.Name, new AnimationChannel());
}
int frameNumber = 0;
while ((line = readLine()) != null)
{
string[] ss = line.Split(whiteSpace);
//couldn't get the .NET 2.0 version of Split() working,
//therefore this ugly hack
List<string> data = new List<string>();
foreach (string s in ss)
{
if (s != "" && s != null)
{
data.Add(s);
}
}
int i = 0;
foreach (BoneInfo b in bones)
{
foreach (string channel in b.channels)
{
b.channelValues[channel] = ParseFloat(data[i]);
++i;
}
}
foreach (BoneInfo b in bones)
{
// Many applications export BVH in such a way that bone translation
// needs to be aplied in every frame.
Matrix translation = b.bone.Transform;
Vector3 t = new Vector3();
t.X = b["Xposition"];
t.Y = b["Yposition"];
t.Z = b["Zposition"];
if (t.Length() != 0.0f)
{
// Some applications export BVH with translation channels for every bone.
// In this case, bone translation should not be applied.
translation = Matrix.CreateTranslation(t);
}
Quaternion r = Quaternion.Identity;
// get rotations in correct order
foreach (string channel in b.channels)
{
float angle = MathHelper.ToRadians(b[channel]);
if (channel.Equals("Xrotation", StringComparison.InvariantCultureIgnoreCase))
r = r * Quaternion.CreateFromAxisAngle(Vector3.UnitX, angle);
if (channel.Equals("Yrotation", StringComparison.InvariantCultureIgnoreCase))
r = r * Quaternion.CreateFromAxisAngle(Vector3.UnitY, angle);
if (channel.Equals("Zrotation", StringComparison.InvariantCultureIgnoreCase))
r = r * Quaternion.CreateFromAxisAngle(Vector3.UnitZ, angle);
}
Matrix m = Matrix.CreateFromQuaternion(r) * translation;
TimeSpan time = TimeSpan.FromSeconds(frameTime * frameNumber);
AnimationKeyframe keyframe = new AnimationKeyframe(time, m);
animation.Channels[b.bone.Name].Add(keyframe);
++i;
}
++frameNumber;
}
root.Identity = contentId;
return root;
}
private string readLine()
{
string line = reader.ReadLine();
++currentLine;
if (line != null)
line = line.Trim();
return line;
}
}
internal class BoneInfo
{
public BoneContent bone;
public Dictionary<string, float> channelValues=new Dictionary<string, float>();
public List<string> channels = new List<string>();
public void Add(string channel)
{
channels.Add(channel.ToLower());
channelValues.Add(channel.ToLower(), 0.0f);
}
public float this[string channel]
{
get
{
if (channelValues.ContainsKey(channel.ToLower()))
return channelValues[channel.ToLower()];
else
return 0.0f;
}
}
}
}
| |
// 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 OrUInt64()
{
var test = new SimpleBinaryOpTest__OrUInt64();
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();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// 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 class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
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 SimpleBinaryOpTest__OrUInt64
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(UInt64[] inArray1, UInt64[] inArray2, UInt64[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt64>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt64>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt64>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt64, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt64, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<UInt64> _fld1;
public Vector128<UInt64> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__OrUInt64 testClass)
{
var result = Sse2.Or(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__OrUInt64 testClass)
{
fixed (Vector128<UInt64>* pFld1 = &_fld1)
fixed (Vector128<UInt64>* pFld2 = &_fld2)
{
var result = Sse2.Or(
Sse2.LoadVector128((UInt64*)(pFld1)),
Sse2.LoadVector128((UInt64*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static UInt64[] _data1 = new UInt64[Op1ElementCount];
private static UInt64[] _data2 = new UInt64[Op2ElementCount];
private static Vector128<UInt64> _clsVar1;
private static Vector128<UInt64> _clsVar2;
private Vector128<UInt64> _fld1;
private Vector128<UInt64> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__OrUInt64()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
}
public SimpleBinaryOpTest__OrUInt64()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
_dataTable = new DataTable(_data1, _data2, new UInt64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.Or(
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.Or(
Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.Or(
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Or), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Or), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Or), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.Or(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<UInt64>* pClsVar1 = &_clsVar1)
fixed (Vector128<UInt64>* pClsVar2 = &_clsVar2)
{
var result = Sse2.Or(
Sse2.LoadVector128((UInt64*)(pClsVar1)),
Sse2.LoadVector128((UInt64*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr);
var result = Sse2.Or(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr));
var result = Sse2.Or(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr));
var result = Sse2.Or(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__OrUInt64();
var result = Sse2.Or(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__OrUInt64();
fixed (Vector128<UInt64>* pFld1 = &test._fld1)
fixed (Vector128<UInt64>* pFld2 = &test._fld2)
{
var result = Sse2.Or(
Sse2.LoadVector128((UInt64*)(pFld1)),
Sse2.LoadVector128((UInt64*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.Or(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<UInt64>* pFld1 = &_fld1)
fixed (Vector128<UInt64>* pFld2 = &_fld2)
{
var result = Sse2.Or(
Sse2.LoadVector128((UInt64*)(pFld1)),
Sse2.LoadVector128((UInt64*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.Or(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse2.Or(
Sse2.LoadVector128((UInt64*)(&test._fld1)),
Sse2.LoadVector128((UInt64*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(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<UInt64> op1, Vector128<UInt64> op2, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt64[] left, UInt64[] right, UInt64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((ulong)(left[0] | right[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((ulong)(left[i] | right[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.Or)}<UInt64>(Vector128<UInt64>, Vector128<UInt64>): {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;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.StreamAnalytics
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Operations operations.
/// </summary>
internal partial class Operations : IServiceOperations<StreamAnalyticsManagementClient>, IOperations
{
/// <summary>
/// Initializes a new instance of the Operations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal Operations(StreamAnalyticsManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the StreamAnalyticsManagementClient
/// </summary>
public StreamAnalyticsManagementClient Client { get; private set; }
/// <summary>
/// Lists all of the available Stream Analytics related operations.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Operation>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.StreamAnalytics/operations").ToString();
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Operation>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Operation>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists all of the available Stream Analytics related operations.
/// </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<Operation>>> 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 = 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<Operation>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Operation>>(_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;
}
}
}
| |
// 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 AddSaturateByte()
{
var test = new SimpleBinaryOpTest__AddSaturateByte();
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();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// 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 class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
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 SimpleBinaryOpTest__AddSaturateByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Byte> _fld1;
public Vector128<Byte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__AddSaturateByte testClass)
{
var result = Sse2.AddSaturate(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddSaturateByte testClass)
{
fixed (Vector128<Byte>* pFld1 = &_fld1)
fixed (Vector128<Byte>* pFld2 = &_fld2)
{
var result = Sse2.AddSaturate(
Sse2.LoadVector128((Byte*)(pFld1)),
Sse2.LoadVector128((Byte*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static Byte[] _data1 = new Byte[Op1ElementCount];
private static Byte[] _data2 = new Byte[Op2ElementCount];
private static Vector128<Byte> _clsVar1;
private static Vector128<Byte> _clsVar2;
private Vector128<Byte> _fld1;
private Vector128<Byte> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__AddSaturateByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
}
public SimpleBinaryOpTest__AddSaturateByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
_dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.AddSaturate(
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.AddSaturate(
Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.AddSaturate(
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.AddSaturate), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.AddSaturate), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.AddSaturate), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.AddSaturate(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Byte>* pClsVar1 = &_clsVar1)
fixed (Vector128<Byte>* pClsVar2 = &_clsVar2)
{
var result = Sse2.AddSaturate(
Sse2.LoadVector128((Byte*)(pClsVar1)),
Sse2.LoadVector128((Byte*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr);
var result = Sse2.AddSaturate(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr));
var result = Sse2.AddSaturate(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr));
var result = Sse2.AddSaturate(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__AddSaturateByte();
var result = Sse2.AddSaturate(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__AddSaturateByte();
fixed (Vector128<Byte>* pFld1 = &test._fld1)
fixed (Vector128<Byte>* pFld2 = &test._fld2)
{
var result = Sse2.AddSaturate(
Sse2.LoadVector128((Byte*)(pFld1)),
Sse2.LoadVector128((Byte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.AddSaturate(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Byte>* pFld1 = &_fld1)
fixed (Vector128<Byte>* pFld2 = &_fld2)
{
var result = Sse2.AddSaturate(
Sse2.LoadVector128((Byte*)(pFld1)),
Sse2.LoadVector128((Byte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.AddSaturate(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse2.AddSaturate(
Sse2.LoadVector128((Byte*)(&test._fld1)),
Sse2.LoadVector128((Byte*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(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<Byte> op1, Vector128<Byte> op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (Sse2Verify.AddSaturate(left[0], right[0], result[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (Sse2Verify.AddSaturate(left[i], right[i], result[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.AddSaturate)}<Byte>(Vector128<Byte>, Vector128<Byte>): {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;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
namespace Neo.Compiler.MSIL
{
class DefLogger : ILogger
{
public void Log(string log)
{
Console.WriteLine(log);
}
}
/// <summary>
/// Convert IL to NeoVM opcode
/// </summary>
public partial class ModuleConverter
{
public ModuleConverter(ILogger logger)
{
if (logger == null)
{
logger = new DefLogger();
}
this.logger = logger;
}
private const int MAX_STATIC_FIELDS_COUNT = 255;
private const int MAX_PARAMS_COUNT = 255;
private const int MAX_LOCAL_VARIABLES_COUNT = 255;
private readonly ILogger logger;
public NeoModule outModule;
private ILModule inModule;
public Dictionary<ILMethod, NeoMethod> methodLink = new Dictionary<ILMethod, NeoMethod>();
public NeoModule Convert(ILModule _in, ConvOption option = null)
{
this.inModule = _in;
this.outModule = new NeoModule(this.logger)
{
option = option ?? ConvOption.Default
};
foreach (var t in _in.mapType)
{
if (t.Key.Contains("<")) continue; //skip system type
if (t.Key.Contains("_API_")) continue; // skip api
if (t.Key.Contains(".My.")) continue; //vb system
foreach (var m in t.Value.methods)
{
if (m.Value.method == null) continue;
if (m.Value.method.IsAddOn || m.Value.method.IsRemoveOn) continue; // skip the code generated by event
if (m.Value.method.Is_ctor()) continue;
if (m.Value.method.Is_cctor())
{
//if cctor contains sth can not be as a const value.
// then need 1.record these cctor's code.
// 2.insert them to main function
CctorSubVM.Parse(m.Value, this.outModule);
continue;
}
NeoMethod nm = new NeoMethod(m.Value);
this.methodLink[m.Value] = nm;
outModule.mapMethods[nm.name] = nm;
}
foreach (var e in t.Value.fields)
{
if (e.Value.isEvent)
{
NeoEvent ae = new NeoEvent(e.Value);
outModule.mapEvents[ae.name] = ae;
}
else if (e.Value.field.IsStatic)
{
var _fieldindex = outModule.mapFields.Count;
var field = new NeoField(e.Key, e.Value.type, _fieldindex);
outModule.mapFields[e.Value.field.FullName] = field;
}
}
}
var keys = new List<string>(_in.mapType.Keys);
foreach (var key in keys)
{
var value = _in.mapType[key];
if (key.Contains("<")) continue; // skip system typee
if (key.Contains("_API_")) continue; // skip api
if (key.Contains(".My.")) continue; //vb system
foreach (var m in value.methods)
{
if (m.Value.method == null) continue;
if (m.Value.method.Is_cctor()) continue;
if (m.Value.method.IsAddOn || m.Value.method.IsRemoveOn) continue; // skip the code generated by event
var nm = this.methodLink[m.Value];
//try
{
nm.returntype = m.Value.returntype;
foreach (var src in m.Value.paramtypes)
{
nm.paramtypes.Add(new NeoParam(src.name, src.type));
}
if (IsContractCall(m.Value.method, out byte[] outcall))
continue;
if (IsNonCall(m.Value.method))
continue;
if (IsMixAttribute(m.Value.method, out VM.OpCode[] opcodes, out string[] opdata))
continue;
if (m.Key.Contains("::Main("))
{
NeoMethod _m = outModule.mapMethods[m.Key];
}
this.ConvertMethod(m.Value, nm);
}
}
}
if (this.outModule.mapFields.Count > MAX_STATIC_FIELDS_COUNT)
throw new Exception("too much static fields");
if (this.outModule.mapFields.Count > 0)
{
InsertInitializeMethod();
logger.Log("Insert _initialize().");
}
var attr = outModule.mapMethods.Values.Where(u => u.inSmartContract).Select(u => u.type?.attributes.ToArray()).FirstOrDefault();
if (attr?.Length > 0)
{
outModule.attributes.AddRange(attr);
}
this.LinkCode();
// this.findFirstFunc();// Need to find the first method
// Assign func addr for each method
// Then convert the call address
return outModule;
}
private string InsertInitializeMethod()
{
string name = "::initializemethod";
NeoMethod initialize = new NeoMethod
{
_namespace = "",
name = "Initialize",
displayName = "_initialize",
inSmartContract = true
};
initialize.returntype = FuncExport.Void;
initialize.funcaddr = 0;
if (!FillInitializeMethod(initialize))
{
return "";
}
outModule.mapMethods[name] = initialize;
return name;
}
private bool FillInitializeMethod(NeoMethod to)
{
this.addr = 0;
this.addrconv.Clear();
#if DEBUG
Insert1(VM.OpCode.NOP, "this is a debug code.", to);
#endif
InsertSharedStaticVarCode(to);
#if DEBUG
Insert1(VM.OpCode.NOP, "this is a end debug code.", to);
#endif
Insert1(VM.OpCode.RET, "", to);
ConvertAddrInMethod(to);
return true;
}
private void LinkCode()
{
this.outModule.totalCodes.Clear();
int addr = 0;
foreach (var m in this.outModule.mapMethods)
{
m.Value.funcaddr = addr;
foreach (var c in m.Value.body_Codes)
{
this.outModule.totalCodes[addr] = c.Value;
addr += 1;
if (c.Value.bytes != null)
addr += c.Value.bytes.Length;
// address offset
c.Value.addr += m.Value.funcaddr;
}
}
foreach (var c in this.outModule.totalCodes.Values)
{
if (c.needfixfunc)
{ // Address convert required
var addrfunc = this.outModule.mapMethods[c.srcfunc].funcaddr;
if (c.bytes.Length > 4)
{
var len = c.bytes.Length - 4;
long wantaddr = (long)addrfunc - c.addr - len;
if (wantaddr < Int32.MinValue || wantaddr > Int32.MaxValue)
{
throw new Exception("addr jump is too far.");
}
var bts = BitConverter.GetBytes((int)wantaddr);
c.bytes[^4] = bts[0];
c.bytes[^3] = bts[1];
c.bytes[^2] = bts[2];
c.bytes[^1] = bts[3];
}
else if (c.bytes.Length == 4)
{
long wantaddr = (long)addrfunc - c.addr;
if (wantaddr < Int32.MinValue || wantaddr > Int32.MaxValue)
{
throw new Exception("addr jump is too far.");
}
c.bytes = BitConverter.GetBytes((int)wantaddr);
}
else
{
throw new Exception("not have right fill bytes");
}
c.needfixfunc = false;
}
}
}
private void FillMethod(ILMethod from, NeoMethod to, bool withReturn)
{
int skipcount = 0;
foreach (var src in from.body_Codes.Values)
{
if (skipcount > 0)
{
skipcount--;
}
else
{
//Need clear arguments before return
if (src.code == CodeEx.Ret)//before return
{
if (!withReturn) break;
}
try
{
skipcount = ConvertCode(from, src, to);
}
catch (Exception err)
{
throw new Exception("error:" + from.method.FullName + "::" + src, err);
}
}
}
ConvertAddrInMethod(to);
}
private void ConvertMethod(ILMethod from, NeoMethod to)
{
this.addr = 0;
this.addrconv.Clear();
// Insert a code that record the depth
InsertBeginCode(from, to);
FillMethod(from, to, true);
}
private readonly Dictionary<int, int> addrconv = new Dictionary<int, int>();
private int addr = 0;
private int ldloca_slot = -1;
static int GetNumber(NeoCode code)
{
if (code.code <= VM.OpCode.PUSHINT256)
return (int)new BigInteger(code.bytes);
else if (code.code == VM.OpCode.PUSHM1) return -1;
else if (code.code == VM.OpCode.PUSH0) return 0;
else if (code.code == VM.OpCode.PUSH1) return 1;
else if (code.code == VM.OpCode.PUSH2) return 2;
else if (code.code == VM.OpCode.PUSH3) return 3;
else if (code.code == VM.OpCode.PUSH4) return 4;
else if (code.code == VM.OpCode.PUSH5) return 5;
else if (code.code == VM.OpCode.PUSH6) return 6;
else if (code.code == VM.OpCode.PUSH7) return 7;
else if (code.code == VM.OpCode.PUSH8) return 8;
else if (code.code == VM.OpCode.PUSH9) return 9;
else if (code.code == VM.OpCode.PUSH10) return 10;
else if (code.code == VM.OpCode.PUSH11) return 11;
else if (code.code == VM.OpCode.PUSH12) return 12;
else if (code.code == VM.OpCode.PUSH13) return 13;
else if (code.code == VM.OpCode.PUSH14) return 14;
else if (code.code == VM.OpCode.PUSH15) return 15;
else if (code.code == VM.OpCode.PUSH16) return 16;
else if (code.code == VM.OpCode.PUSHDATA1) return Pushdata1bytes2int(code.bytes);
else
throw new Exception("not support getNumber From this:" + code.ToString());
}
static int Pushdata1bytes2int(byte[] data)
{
byte[] target = new byte[4];
for (var i = 1; i < data.Length; i++)
target[i - 1] = data[i];
var n = BitConverter.ToInt32(target, 0);
return n;
}
private void ConvertAddrInMethod(NeoMethod to)
{
foreach (var c in to.body_Codes.Values)
{
if (c.needfix)
{
if (c.code == VM.OpCode.TRY_L)
{
var srcCatch = BitConverter.ToInt32(c.bytes, 0);
var srcFinal = BitConverter.ToInt32(c.bytes, 4);
if (srcCatch == -1)
{
var bytesCatch = new byte[] { 0, 0, 0, 0 };
Array.Copy(bytesCatch, 0, c.bytes, 0, 4);
}
else
{
var _addrCatch = addrconv[srcCatch];
Int32 addroffCatch = (Int32)(_addrCatch - c.addr);
var bytesCatch = BitConverter.GetBytes(addroffCatch);
Array.Copy(bytesCatch, 0, c.bytes, 0, 4);
}
if (srcFinal == -1)
{
var bytesFinal = new byte[] { 0, 0, 0, 0 };
Array.Copy(bytesFinal, 0, c.bytes, 4, 4);
}
else
{
var _addrFinal = addrconv[srcFinal];
int addroffFinal = (int)(_addrFinal - c.addr);
var bytesFinal = BitConverter.GetBytes(addroffFinal);
Array.Copy(bytesFinal, 0, c.bytes, 4, 4);
}
}
else
{
try
{
var _addr = addrconv[c.srcaddr];
int addroff = (int)(_addr - c.addr);
c.bytes = BitConverter.GetBytes(addroff);
c.needfix = false;
}
catch
{
throw new Exception("cannot convert addr in: " + to.name + "\r\n");
}
}
}
}
}
private int ConvertCode(ILMethod method, OpCode src, NeoMethod to)
{
//add try code
if (method.tryPositions.Contains(src.addr))
{
foreach (var info in method.tryInfos)
{
if (info.addr_Try_Begin == src.addr)
{
if (info.catch_Infos.Count > 1)
throw new Exception("only support one catch for now.");
var buf = new byte[8];
var catchAddr = -1;
if (info.catch_Infos.Count == 1)
{
var first = info.catch_Infos.First().Value;
catchAddr = first.addrBegin;
}
var bytesCatch = BitConverter.GetBytes(catchAddr);
var bytesFinally = BitConverter.GetBytes(info.addr_Finally_Begin);
Array.Copy(bytesCatch, 0, buf, 0, 4);
Array.Copy(bytesFinally, 0, buf, 4, 4);
var trycode = Convert1by1(VM.OpCode.TRY_L, src, to, buf);
trycode.needfix = true;
break;
}
}
}
int skipcount = 0;
switch (src.code)
{
case CodeEx.Nop:
Convert1by1(VM.OpCode.NOP, src, to);
break;
case CodeEx.Ret:
// return was handled outside
Convert1by1(VM.OpCode.RET, src, to);
break;
case CodeEx.Pop:
Convert1by1(VM.OpCode.DROP, src, to);
break;
case CodeEx.Ldnull:
Convert1by1(VM.OpCode.PUSHNULL, src, to);
break;
case CodeEx.Ldc_I4:
case CodeEx.Ldc_I4_S:
skipcount = ConvertPushI4WithConv(method, src.tokenI32, src, to);
break;
case CodeEx.Ldc_I4_0:
ConvertPushNumber(0, src, to);
break;
case CodeEx.Ldc_I4_1:
ConvertPushNumber(1, src, to);
break;
case CodeEx.Ldc_I4_2:
ConvertPushNumber(2, src, to);
break;
case CodeEx.Ldc_I4_3:
ConvertPushNumber(3, src, to);
break;
case CodeEx.Ldc_I4_4:
ConvertPushNumber(4, src, to);
break;
case CodeEx.Ldc_I4_5:
ConvertPushNumber(5, src, to);
break;
case CodeEx.Ldc_I4_6:
ConvertPushNumber(6, src, to);
break;
case CodeEx.Ldc_I4_7:
ConvertPushNumber(7, src, to);
break;
case CodeEx.Ldc_I4_8:
ConvertPushNumber(8, src, to);
break;
case CodeEx.Ldc_I4_M1:
skipcount = ConvertPushI4WithConv(method, -1, src, to);
break;
case CodeEx.Ldc_I8:
skipcount = ConvertPushI8WithConv(method, src.tokenI64, src, to);
break;
case CodeEx.Ldstr:
ConvertPushString(src.tokenStr, src, to);
break;
case CodeEx.Stloc_0:
ConvertStLoc(src, to, 0);
break;
case CodeEx.Stloc_1:
ConvertStLoc(src, to, 1);
break;
case CodeEx.Stloc_2:
ConvertStLoc(src, to, 2);
break;
case CodeEx.Stloc_3:
ConvertStLoc(src, to, 3);
break;
case CodeEx.Stloc_S:
ConvertStLoc(src, to, src.tokenI32);
break;
case CodeEx.Ldloc_0:
ConvertLdLoc(src, to, 0);
break;
case CodeEx.Ldloc_1:
ConvertLdLoc(src, to, 1);
break;
case CodeEx.Ldloc_2:
ConvertLdLoc(src, to, 2);
break;
case CodeEx.Ldloc_3:
ConvertLdLoc(src, to, 3);
break;
case CodeEx.Ldloc_S:
ConvertLdLoc(src, to, src.tokenI32);
break;
case CodeEx.Ldarg_0:
ConvertLdArg(method, src, to, 0);
break;
case CodeEx.Ldarg_1:
ConvertLdArg(method, src, to, 1);
break;
case CodeEx.Ldarg_2:
ConvertLdArg(method, src, to, 2);
break;
case CodeEx.Ldarg_3:
ConvertLdArg(method, src, to, 3);
break;
case CodeEx.Ldarg_S:
case CodeEx.Ldarg:
case CodeEx.Ldarga:
case CodeEx.Ldarga_S:
ConvertLdArg(method, src, to, src.tokenI32);
break;
case CodeEx.Starg_S:
case CodeEx.Starg:
ConvertStArg(src, to, src.tokenI32);
break;
// Address convert required
case CodeEx.Br:
case CodeEx.Br_S:
{
var code = Convert1by1(VM.OpCode.JMP_L, src, to, new byte[] { 0, 0, 0, 0 });
code.needfix = true;
code.srcaddr = src.tokenAddr_Index;
}
break;
case CodeEx.Leave:
case CodeEx.Leave_S:
{//will support try catch
var tryinfo = method.GetTryInfo(src.addr, out ILMethod.TryCodeType type);
//leaves in try
//leaves in catch
if (type == ILMethod.TryCodeType.Try || type == ILMethod.TryCodeType.Catch)
{
var code = Convert1by1(VM.OpCode.ENDTRY_L, src, to, new byte[] { 0, 0, 0, 0 });
code.needfix = true;
code.srcaddr = src.tokenAddr_Index;
}
else //or else just jmp
{
var code = Convert1by1(VM.OpCode.JMP_L, src, to, new byte[] { 0, 0, 0, 0 });
code.needfix = true;
code.srcaddr = src.tokenAddr_Index;
}
}
break;
case CodeEx.Endfinally:
{
//need vm add these opcodes
var code = Convert1by1(VM.OpCode.ENDFINALLY, src, to);
}
break;
case CodeEx.Switch:
{
// Insert a set of IF-JMP code here to replace the support of the Switch statement.
// For Switch(int), the compiler will subtract the smallest case value from the input,
// then compare the result with 0,1,2... to get the address to jump to.
Convert1by1(VM.OpCode.NOP, src, to);//nop tag
Insert1(VM.OpCode.CONVERT, "", to, new byte[] { (byte)VM.Types.StackItemType.Integer });
for (var i = 0; i < src.tokenAddr_Switch.Length; i++)
{
Insert1(VM.OpCode.DUP, "", to);
ConvertPushNumber(i, null, to);
Insert1(VM.OpCode.NUMEQUAL, "", to);
var addroff = BitConverter.GetBytes((int)11);
var codenext = Insert1(VM.OpCode.JMPIFNOT_L, "jmp next", to, addroff);
codenext.needfix = false;
Insert1(VM.OpCode.DROP, "", to);
var codeswitch = Insert1(VM.OpCode.JMP_L, "", to, BitConverter.GetBytes((int)src.tokenAddr_Switch[i]));
codeswitch.srcaddr = src.tokenAddr_Switch[i];
codeswitch.needfix = true;
}
Insert1(VM.OpCode.DROP, "switch end", to);
}
break;
case CodeEx.Brtrue:
case CodeEx.Brtrue_S:
{
var code = Convert1by1(VM.OpCode.JMPIF_L, src, to, new byte[] { 0, 0, 0, 0 });
code.needfix = true;
code.srcaddr = src.tokenAddr_Index;
}
break;
case CodeEx.Brfalse:
case CodeEx.Brfalse_S:
{
var code = Convert1by1(VM.OpCode.JMPIFNOT_L, src, to, new byte[] { 0, 0, 0, 0 });
code.needfix = true;
code.srcaddr = src.tokenAddr_Index;
}
break;
case CodeEx.Beq:
case CodeEx.Beq_S:
{
Convert1by1(VM.OpCode.NUMEQUAL, src, to);
var code = Convert1by1(VM.OpCode.JMPIF_L, null, to, new byte[] { 0, 0, 0, 0 });
code.needfix = true;
code.srcaddr = src.tokenAddr_Index;
}
break;
case CodeEx.Bne_Un:
case CodeEx.Bne_Un_S:
{
Convert1by1(VM.OpCode.ABS, src, to);
Convert1by1(VM.OpCode.SWAP, null, to);
Convert1by1(VM.OpCode.ABS, null, to);
Convert1by1(VM.OpCode.SWAP, null, to);
Convert1by1(VM.OpCode.NUMNOTEQUAL, null, to);
var code = Convert1by1(VM.OpCode.JMPIF_L, null, to, new byte[] { 0, 0, 0, 0 });
code.needfix = true;
code.srcaddr = src.tokenAddr_Index;
}
break;
case CodeEx.Blt:
case CodeEx.Blt_S:
{
Convert1by1(VM.OpCode.LT, src, to);
var code = Convert1by1(VM.OpCode.JMPIF_L, null, to, new byte[] { 0, 0, 0, 0 });
code.needfix = true;
code.srcaddr = src.tokenAddr_Index;
}
break;
case CodeEx.Blt_Un:
case CodeEx.Blt_Un_S:
{
Convert1by1(VM.OpCode.ABS, src, to);
Convert1by1(VM.OpCode.SWAP, null, to);
Convert1by1(VM.OpCode.ABS, null, to);
Convert1by1(VM.OpCode.SWAP, null, to);
Convert1by1(VM.OpCode.LT, null, to);
var code = Convert1by1(VM.OpCode.JMPIF_L, null, to, new byte[] { 0, 0, 0, 0 });
code.needfix = true;
code.srcaddr = src.tokenAddr_Index;
}
break;
case CodeEx.Ble:
case CodeEx.Ble_S:
{
Convert1by1(VM.OpCode.LE, src, to);
var code = Convert1by1(VM.OpCode.JMPIF_L, null, to, new byte[] { 0, 0, 0, 0 });
code.needfix = true;
code.srcaddr = src.tokenAddr_Index;
}
break;
case CodeEx.Ble_Un:
case CodeEx.Ble_Un_S:
{
Convert1by1(VM.OpCode.ABS, src, to);
Convert1by1(VM.OpCode.SWAP, null, to);
Convert1by1(VM.OpCode.ABS, null, to);
Convert1by1(VM.OpCode.SWAP, null, to);
Convert1by1(VM.OpCode.LE, null, to);
var code = Convert1by1(VM.OpCode.JMPIF_L, null, to, new byte[] { 0, 0, 0, 0 });
code.needfix = true;
code.srcaddr = src.tokenAddr_Index;
}
break;
case CodeEx.Bgt:
case CodeEx.Bgt_S:
{
Convert1by1(VM.OpCode.GT, src, to);
var code = Convert1by1(VM.OpCode.JMPIF_L, null, to, new byte[] { 0, 0, 0, 0 });
code.needfix = true;
code.srcaddr = src.tokenAddr_Index;
}
break;
case CodeEx.Bgt_Un:
case CodeEx.Bgt_Un_S:
{
Convert1by1(VM.OpCode.ABS, src, to);
Convert1by1(VM.OpCode.SWAP, null, to);
Convert1by1(VM.OpCode.ABS, null, to);
Convert1by1(VM.OpCode.SWAP, null, to);
Convert1by1(VM.OpCode.GT, null, to);
var code = Convert1by1(VM.OpCode.JMPIF_L, null, to, new byte[] { 0, 0, 0, 0 });
code.needfix = true;
code.srcaddr = src.tokenAddr_Index;
}
break;
case CodeEx.Bge:
case CodeEx.Bge_S:
{
Convert1by1(VM.OpCode.GE, src, to);
var code = Convert1by1(VM.OpCode.JMPIF_L, null, to, new byte[] { 0, 0, 0, 0 });
code.needfix = true;
code.srcaddr = src.tokenAddr_Index;
}
break;
case CodeEx.Bge_Un:
case CodeEx.Bge_Un_S:
{
Convert1by1(VM.OpCode.ABS, src, to);
Convert1by1(VM.OpCode.SWAP, null, to);
Convert1by1(VM.OpCode.ABS, null, to);
Convert1by1(VM.OpCode.SWAP, null, to);
Convert1by1(VM.OpCode.GE, null, to);
var code = Convert1by1(VM.OpCode.JMPIF_L, null, to, new byte[] { 0, 0, 0, 0 });
code.needfix = true;
code.srcaddr = src.tokenAddr_Index;
}
break;
//Stack
case CodeEx.Dup:
Convert1by1(VM.OpCode.DUP, src, to);
break;
//Bitwise logic
case CodeEx.And:
Convert1by1(VM.OpCode.AND, src, to);
break;
case CodeEx.Or:
Convert1by1(VM.OpCode.OR, src, to);
break;
case CodeEx.Xor:
Convert1by1(VM.OpCode.XOR, src, to);
break;
case CodeEx.Not:
Convert1by1(VM.OpCode.INVERT, src, to);
break;
//math
case CodeEx.Add:
case CodeEx.Add_Ovf:
case CodeEx.Add_Ovf_Un:
Convert1by1(VM.OpCode.ADD, src, to);
break;
case CodeEx.Sub:
case CodeEx.Sub_Ovf:
case CodeEx.Sub_Ovf_Un:
Convert1by1(VM.OpCode.SUB, src, to);
break;
case CodeEx.Mul:
case CodeEx.Mul_Ovf:
case CodeEx.Mul_Ovf_Un:
Convert1by1(VM.OpCode.MUL, src, to);
break;
case CodeEx.Div:
case CodeEx.Div_Un:
Convert1by1(VM.OpCode.DIV, src, to);
break;
case CodeEx.Rem:
case CodeEx.Rem_Un:
Convert1by1(VM.OpCode.MOD, src, to);
break;
case CodeEx.Neg:
Convert1by1(VM.OpCode.NEGATE, src, to);
break;
case CodeEx.Shl:
Convert1by1(VM.OpCode.SHL, src, to);
break;
case CodeEx.Shr:
case CodeEx.Shr_Un:
Convert1by1(VM.OpCode.SHR, src, to);
break;
//logic
case CodeEx.Clt:
case CodeEx.Clt_Un:
Convert1by1(VM.OpCode.LT, src, to);
break;
case CodeEx.Cgt:
case CodeEx.Cgt_Un:
skipcount = ConvertCgt(src, to);
break;
case CodeEx.Ceq:
skipcount = ConvertCeq(src, to);
break;
//call
case CodeEx.Call:
case CodeEx.Callvirt:
{
if (src.tokenMethod == "System.UInt32 <PrivateImplementationDetails>::ComputeStringHash(System.String)")
{
// this method maybe is a tag of switch
skipcount = ConvertStringSwitch(method, src, to);
}
else
{
ConvertCall(src, to);
}
}
break;
// Use the previous argument as the array size, then new a array
case CodeEx.Newarr:
skipcount = ConvertNewArr(method, src, to);
break;
//array
//Intent to use byte[] as array.....
case CodeEx.Ldelem_U1:
case CodeEx.Ldelem_I1:
//_ConvertPush(1, src, to);
//_Convert1by1(VM.OpCode.SUBSTR, null, to);
//break;
//now we can use pickitem for byte[]
case CodeEx.Ldelem_Any:
case CodeEx.Ldelem_I:
//case CodeEx.Ldelem_I1:
case CodeEx.Ldelem_I2:
case CodeEx.Ldelem_I4:
case CodeEx.Ldelem_I8:
case CodeEx.Ldelem_R4:
case CodeEx.Ldelem_R8:
case CodeEx.Ldelem_Ref:
case CodeEx.Ldelem_U2:
case CodeEx.Ldelem_U4:
Convert1by1(VM.OpCode.PICKITEM, src, to);
break;
case CodeEx.Ldlen:
Convert1by1(VM.OpCode.SIZE, src, to);
break;
case CodeEx.Stelem_Any:
case CodeEx.Stelem_I:
case CodeEx.Stelem_I1:
case CodeEx.Stelem_I2:
case CodeEx.Stelem_I4:
case CodeEx.Stelem_I8:
case CodeEx.Stelem_R4:
case CodeEx.Stelem_R8:
case CodeEx.Stelem_Ref:
Convert1by1(VM.OpCode.SETITEM, src, to);
break;
case CodeEx.Isinst://Support `as` expression
break;
case CodeEx.Castclass:
ConvertCastclass(src, to);
break;
case CodeEx.Box:
case CodeEx.Unbox:
case CodeEx.Unbox_Any:
case CodeEx.Break:
//Maybe we can use these for breakpoint debug
case CodeEx.Conv_I:
case CodeEx.Conv_I1:
case CodeEx.Conv_I2:
case CodeEx.Conv_I4:
case CodeEx.Conv_I8:
case CodeEx.Conv_Ovf_I:
case CodeEx.Conv_Ovf_I_Un:
case CodeEx.Conv_Ovf_I1:
case CodeEx.Conv_Ovf_I1_Un:
case CodeEx.Conv_Ovf_I2:
case CodeEx.Conv_Ovf_I2_Un:
case CodeEx.Conv_Ovf_I4:
case CodeEx.Conv_Ovf_I4_Un:
case CodeEx.Conv_Ovf_I8:
case CodeEx.Conv_Ovf_I8_Un:
case CodeEx.Conv_Ovf_U:
case CodeEx.Conv_Ovf_U_Un:
case CodeEx.Conv_Ovf_U1:
case CodeEx.Conv_Ovf_U1_Un:
case CodeEx.Conv_Ovf_U2:
case CodeEx.Conv_Ovf_U2_Un:
case CodeEx.Conv_Ovf_U4:
case CodeEx.Conv_Ovf_U4_Un:
case CodeEx.Conv_Ovf_U8:
case CodeEx.Conv_Ovf_U8_Un:
case CodeEx.Conv_U:
case CodeEx.Conv_U1:
case CodeEx.Conv_U2:
case CodeEx.Conv_U4:
case CodeEx.Conv_U8:
this.addrconv[src.addr] = addr;
break;
///////////////////////////////////////////////
// Support for structure
// Load a reference, but we change to load the value of `pos` position
case CodeEx.Ldloca:
case CodeEx.Ldloca_S:
ConvertLdLocA(method, src, to, src.tokenI32);
break;
case CodeEx.Initobj:
ConvertInitObj(src, to);
break;
case CodeEx.Newobj:
ConvertNewObj(method, src, to);
break;
case CodeEx.Stfld:
ConvertStfld(src, to);
break;
case CodeEx.Ldfld:
ConvertLdfld(src, to);
break;
case CodeEx.Ldsfld:
{
Convert1by1(VM.OpCode.NOP, src, to);
var d = src.tokenUnknown as Mono.Cecil.FieldDefinition;
// If readonly, pull a const value
if (
((d.Attributes & Mono.Cecil.FieldAttributes.InitOnly) > 0) &&
((d.Attributes & Mono.Cecil.FieldAttributes.Static) > 0) &&
// For a readonly Framework.Services, it can't be a const value,
// we should handle in initializemethod.
(!d.FieldType.FullName.Contains("Neo.SmartContract.Framework.Services"))
)
{
var fname = d.FullName;// d.DeclaringType.FullName + "::" + d.Name;
var _src = outModule.staticfieldsWithConstValue[fname];
if (_src is byte[])
{
ConvertPushDataArray((byte[])_src, src, to);
}
else if (_src is int intsrc)
{
ConvertPushNumber(intsrc, src, to);
}
else if (_src is long longsrc)
{
ConvertPushNumber(longsrc, src, to);
}
else if (_src is bool bsrc)
{
ConvertPushBoolean(bsrc, src, to);
}
else if (_src is string strsrc)
{
ConvertPushString(strsrc, src, to);
}
else if (_src is BigInteger bisrc)
{
ConvertPushNumber(bisrc, src, to);
}
else if (_src is string[] strArray)
{
ConvertPushStringArray(strArray, src, to);
}
else
{
throw new Exception("not support type Ldsfld\r\n in: " + to.name + "\r\n");
}
break;
}
//If this code was called by event, just find its name
var findEventFlag = false;
if (d.DeclaringType.HasEvents)
{
foreach (var ev in d.DeclaringType.Events)
{
if (ev.FullName == d.FullName && ev.EventType.FullName == d.FieldType.FullName)
{
findEventFlag = true;
Mono.Collections.Generic.Collection<Mono.Cecil.CustomAttribute> ca = ev.CustomAttributes;
to.lastsfieldname = d.Name;
foreach (var attr in ca)
{
if (attr.AttributeType.FullName == "System.ComponentModel.DisplayNameAttribute")
{
to.lastsfieldname = (string)attr.ConstructorArguments[0].Value;
}
}
break;
}
}
}
if (!findEventFlag)
{
var field = this.outModule.mapFields[d.FullName];
Convert1by1(VM.OpCode.LDSFLD, src, to, new byte[] { (byte)field.index });
}
}
break;
case CodeEx.Stsfld:
{
var d = src.tokenUnknown as Mono.Cecil.FieldDefinition;
var field = this.outModule.mapFields[d.FullName];
Convert1by1(VM.OpCode.STSFLD, src, to, new byte[] { (byte)field.index });
}
break;
case CodeEx.Throw:
{
Convert1by1(VM.OpCode.THROW, src, to);// throw suspends the vm
break;
}
case CodeEx.Ldftn:
{
Insert1(VM.OpCode.DROP, "", to); // drop null
var c = Convert1by1(VM.OpCode.PUSHA, null, to, new byte[] { 5, 0, 0, 0 });
c.needfixfunc = true;
c.srcfunc = src.tokenMethod;
return 1; // skip create object
}
default:
logger.Log("unsupported instruction " + src.code + "\r\n in: " + to.name + "\r\n");
throw new Exception("unsupported instruction " + src.code + "\r\n in: " + to.name + "\r\n");
}
return skipcount;
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// Specialist Subjects per Home Group Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class SSHGDataSet : EduHubDataSet<SSHG>
{
/// <inheritdoc />
public override string Name { get { return "SSHG"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal SSHGDataSet(EduHubContext Context)
: base(Context)
{
Index_HOMEGROUP = new Lazy<NullDictionary<string, IReadOnlyList<SSHG>>>(() => this.ToGroupedNullDictionary(i => i.HOMEGROUP));
Index_LW_DATE = new Lazy<NullDictionary<DateTime?, IReadOnlyList<SSHG>>>(() => this.ToGroupedNullDictionary(i => i.LW_DATE));
Index_STUDENT = new Lazy<NullDictionary<string, IReadOnlyList<SSHG>>>(() => this.ToGroupedNullDictionary(i => i.STUDENT));
Index_SUBJECT = new Lazy<Dictionary<string, IReadOnlyList<SSHG>>>(() => this.ToGroupedDictionary(i => i.SUBJECT));
Index_TEACHER = new Lazy<NullDictionary<string, IReadOnlyList<SSHG>>>(() => this.ToGroupedNullDictionary(i => i.TEACHER));
Index_TEACHING_HG = new Lazy<NullDictionary<string, IReadOnlyList<SSHG>>>(() => this.ToGroupedNullDictionary(i => i.TEACHING_HG));
Index_TID = new Lazy<Dictionary<int, SSHG>>(() => this.ToDictionary(i => i.TID));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="SSHG" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="SSHG" /> fields for each CSV column header</returns>
internal override Action<SSHG, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<SSHG, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "TID":
mapper[i] = (e, v) => e.TID = int.Parse(v);
break;
case "HOMEGROUP":
mapper[i] = (e, v) => e.HOMEGROUP = v;
break;
case "SUBJECT":
mapper[i] = (e, v) => e.SUBJECT = v;
break;
case "TEACHER":
mapper[i] = (e, v) => e.TEACHER = v;
break;
case "STUDENT":
mapper[i] = (e, v) => e.STUDENT = v;
break;
case "VARIATION":
mapper[i] = (e, v) => e.VARIATION = v;
break;
case "TEACHING_HG":
mapper[i] = (e, v) => e.TEACHING_HG = v;
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="SSHG" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="SSHG" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="SSHG" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{SSHG}"/> of entities</returns>
internal override IEnumerable<SSHG> ApplyDeltaEntities(IEnumerable<SSHG> Entities, List<SSHG> DeltaEntities)
{
HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.SUBJECT;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_TID.Remove(entity.TID);
if (entity.SUBJECT.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<NullDictionary<string, IReadOnlyList<SSHG>>> Index_HOMEGROUP;
private Lazy<NullDictionary<DateTime?, IReadOnlyList<SSHG>>> Index_LW_DATE;
private Lazy<NullDictionary<string, IReadOnlyList<SSHG>>> Index_STUDENT;
private Lazy<Dictionary<string, IReadOnlyList<SSHG>>> Index_SUBJECT;
private Lazy<NullDictionary<string, IReadOnlyList<SSHG>>> Index_TEACHER;
private Lazy<NullDictionary<string, IReadOnlyList<SSHG>>> Index_TEACHING_HG;
private Lazy<Dictionary<int, SSHG>> Index_TID;
#endregion
#region Index Methods
/// <summary>
/// Find SSHG by HOMEGROUP field
/// </summary>
/// <param name="HOMEGROUP">HOMEGROUP value used to find SSHG</param>
/// <returns>List of related SSHG entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<SSHG> FindByHOMEGROUP(string HOMEGROUP)
{
return Index_HOMEGROUP.Value[HOMEGROUP];
}
/// <summary>
/// Attempt to find SSHG by HOMEGROUP field
/// </summary>
/// <param name="HOMEGROUP">HOMEGROUP value used to find SSHG</param>
/// <param name="Value">List of related SSHG entities</param>
/// <returns>True if the list of related SSHG entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByHOMEGROUP(string HOMEGROUP, out IReadOnlyList<SSHG> Value)
{
return Index_HOMEGROUP.Value.TryGetValue(HOMEGROUP, out Value);
}
/// <summary>
/// Attempt to find SSHG by HOMEGROUP field
/// </summary>
/// <param name="HOMEGROUP">HOMEGROUP value used to find SSHG</param>
/// <returns>List of related SSHG entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<SSHG> TryFindByHOMEGROUP(string HOMEGROUP)
{
IReadOnlyList<SSHG> value;
if (Index_HOMEGROUP.Value.TryGetValue(HOMEGROUP, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find SSHG by LW_DATE field
/// </summary>
/// <param name="LW_DATE">LW_DATE value used to find SSHG</param>
/// <returns>List of related SSHG entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<SSHG> FindByLW_DATE(DateTime? LW_DATE)
{
return Index_LW_DATE.Value[LW_DATE];
}
/// <summary>
/// Attempt to find SSHG by LW_DATE field
/// </summary>
/// <param name="LW_DATE">LW_DATE value used to find SSHG</param>
/// <param name="Value">List of related SSHG entities</param>
/// <returns>True if the list of related SSHG entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByLW_DATE(DateTime? LW_DATE, out IReadOnlyList<SSHG> Value)
{
return Index_LW_DATE.Value.TryGetValue(LW_DATE, out Value);
}
/// <summary>
/// Attempt to find SSHG by LW_DATE field
/// </summary>
/// <param name="LW_DATE">LW_DATE value used to find SSHG</param>
/// <returns>List of related SSHG entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<SSHG> TryFindByLW_DATE(DateTime? LW_DATE)
{
IReadOnlyList<SSHG> value;
if (Index_LW_DATE.Value.TryGetValue(LW_DATE, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find SSHG by STUDENT field
/// </summary>
/// <param name="STUDENT">STUDENT value used to find SSHG</param>
/// <returns>List of related SSHG entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<SSHG> FindBySTUDENT(string STUDENT)
{
return Index_STUDENT.Value[STUDENT];
}
/// <summary>
/// Attempt to find SSHG by STUDENT field
/// </summary>
/// <param name="STUDENT">STUDENT value used to find SSHG</param>
/// <param name="Value">List of related SSHG entities</param>
/// <returns>True if the list of related SSHG entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindBySTUDENT(string STUDENT, out IReadOnlyList<SSHG> Value)
{
return Index_STUDENT.Value.TryGetValue(STUDENT, out Value);
}
/// <summary>
/// Attempt to find SSHG by STUDENT field
/// </summary>
/// <param name="STUDENT">STUDENT value used to find SSHG</param>
/// <returns>List of related SSHG entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<SSHG> TryFindBySTUDENT(string STUDENT)
{
IReadOnlyList<SSHG> value;
if (Index_STUDENT.Value.TryGetValue(STUDENT, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find SSHG by SUBJECT field
/// </summary>
/// <param name="SUBJECT">SUBJECT value used to find SSHG</param>
/// <returns>List of related SSHG entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<SSHG> FindBySUBJECT(string SUBJECT)
{
return Index_SUBJECT.Value[SUBJECT];
}
/// <summary>
/// Attempt to find SSHG by SUBJECT field
/// </summary>
/// <param name="SUBJECT">SUBJECT value used to find SSHG</param>
/// <param name="Value">List of related SSHG entities</param>
/// <returns>True if the list of related SSHG entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindBySUBJECT(string SUBJECT, out IReadOnlyList<SSHG> Value)
{
return Index_SUBJECT.Value.TryGetValue(SUBJECT, out Value);
}
/// <summary>
/// Attempt to find SSHG by SUBJECT field
/// </summary>
/// <param name="SUBJECT">SUBJECT value used to find SSHG</param>
/// <returns>List of related SSHG entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<SSHG> TryFindBySUBJECT(string SUBJECT)
{
IReadOnlyList<SSHG> value;
if (Index_SUBJECT.Value.TryGetValue(SUBJECT, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find SSHG by TEACHER field
/// </summary>
/// <param name="TEACHER">TEACHER value used to find SSHG</param>
/// <returns>List of related SSHG entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<SSHG> FindByTEACHER(string TEACHER)
{
return Index_TEACHER.Value[TEACHER];
}
/// <summary>
/// Attempt to find SSHG by TEACHER field
/// </summary>
/// <param name="TEACHER">TEACHER value used to find SSHG</param>
/// <param name="Value">List of related SSHG entities</param>
/// <returns>True if the list of related SSHG entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTEACHER(string TEACHER, out IReadOnlyList<SSHG> Value)
{
return Index_TEACHER.Value.TryGetValue(TEACHER, out Value);
}
/// <summary>
/// Attempt to find SSHG by TEACHER field
/// </summary>
/// <param name="TEACHER">TEACHER value used to find SSHG</param>
/// <returns>List of related SSHG entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<SSHG> TryFindByTEACHER(string TEACHER)
{
IReadOnlyList<SSHG> value;
if (Index_TEACHER.Value.TryGetValue(TEACHER, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find SSHG by TEACHING_HG field
/// </summary>
/// <param name="TEACHING_HG">TEACHING_HG value used to find SSHG</param>
/// <returns>List of related SSHG entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<SSHG> FindByTEACHING_HG(string TEACHING_HG)
{
return Index_TEACHING_HG.Value[TEACHING_HG];
}
/// <summary>
/// Attempt to find SSHG by TEACHING_HG field
/// </summary>
/// <param name="TEACHING_HG">TEACHING_HG value used to find SSHG</param>
/// <param name="Value">List of related SSHG entities</param>
/// <returns>True if the list of related SSHG entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTEACHING_HG(string TEACHING_HG, out IReadOnlyList<SSHG> Value)
{
return Index_TEACHING_HG.Value.TryGetValue(TEACHING_HG, out Value);
}
/// <summary>
/// Attempt to find SSHG by TEACHING_HG field
/// </summary>
/// <param name="TEACHING_HG">TEACHING_HG value used to find SSHG</param>
/// <returns>List of related SSHG entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<SSHG> TryFindByTEACHING_HG(string TEACHING_HG)
{
IReadOnlyList<SSHG> value;
if (Index_TEACHING_HG.Value.TryGetValue(TEACHING_HG, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find SSHG by TID field
/// </summary>
/// <param name="TID">TID value used to find SSHG</param>
/// <returns>Related SSHG entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public SSHG FindByTID(int TID)
{
return Index_TID.Value[TID];
}
/// <summary>
/// Attempt to find SSHG by TID field
/// </summary>
/// <param name="TID">TID value used to find SSHG</param>
/// <param name="Value">Related SSHG entity</param>
/// <returns>True if the related SSHG entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTID(int TID, out SSHG Value)
{
return Index_TID.Value.TryGetValue(TID, out Value);
}
/// <summary>
/// Attempt to find SSHG by TID field
/// </summary>
/// <param name="TID">TID value used to find SSHG</param>
/// <returns>Related SSHG entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public SSHG TryFindByTID(int TID)
{
SSHG value;
if (Index_TID.Value.TryGetValue(TID, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a SSHG table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[SSHG]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[SSHG](
[TID] int IDENTITY NOT NULL,
[HOMEGROUP] varchar(3) NULL,
[SUBJECT] varchar(10) NOT NULL,
[TEACHER] varchar(4) NULL,
[STUDENT] varchar(10) NULL,
[VARIATION] varchar(3) NULL,
[TEACHING_HG] varchar(3) NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [SSHG_Index_TID] PRIMARY KEY NONCLUSTERED (
[TID] ASC
)
);
CREATE NONCLUSTERED INDEX [SSHG_Index_HOMEGROUP] ON [dbo].[SSHG]
(
[HOMEGROUP] ASC
);
CREATE NONCLUSTERED INDEX [SSHG_Index_LW_DATE] ON [dbo].[SSHG]
(
[LW_DATE] ASC
);
CREATE NONCLUSTERED INDEX [SSHG_Index_STUDENT] ON [dbo].[SSHG]
(
[STUDENT] ASC
);
CREATE CLUSTERED INDEX [SSHG_Index_SUBJECT] ON [dbo].[SSHG]
(
[SUBJECT] ASC
);
CREATE NONCLUSTERED INDEX [SSHG_Index_TEACHER] ON [dbo].[SSHG]
(
[TEACHER] ASC
);
CREATE NONCLUSTERED INDEX [SSHG_Index_TEACHING_HG] ON [dbo].[SSHG]
(
[TEACHING_HG] ASC
);
END");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes.
/// Typically called before <see cref="SqlBulkCopy"/> to improve performance.
/// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SSHG]') AND name = N'SSHG_Index_HOMEGROUP')
ALTER INDEX [SSHG_Index_HOMEGROUP] ON [dbo].[SSHG] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SSHG]') AND name = N'SSHG_Index_LW_DATE')
ALTER INDEX [SSHG_Index_LW_DATE] ON [dbo].[SSHG] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SSHG]') AND name = N'SSHG_Index_STUDENT')
ALTER INDEX [SSHG_Index_STUDENT] ON [dbo].[SSHG] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SSHG]') AND name = N'SSHG_Index_TEACHER')
ALTER INDEX [SSHG_Index_TEACHER] ON [dbo].[SSHG] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SSHG]') AND name = N'SSHG_Index_TEACHING_HG')
ALTER INDEX [SSHG_Index_TEACHING_HG] ON [dbo].[SSHG] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SSHG]') AND name = N'SSHG_Index_TID')
ALTER INDEX [SSHG_Index_TID] ON [dbo].[SSHG] DISABLE;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SSHG]') AND name = N'SSHG_Index_HOMEGROUP')
ALTER INDEX [SSHG_Index_HOMEGROUP] ON [dbo].[SSHG] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SSHG]') AND name = N'SSHG_Index_LW_DATE')
ALTER INDEX [SSHG_Index_LW_DATE] ON [dbo].[SSHG] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SSHG]') AND name = N'SSHG_Index_STUDENT')
ALTER INDEX [SSHG_Index_STUDENT] ON [dbo].[SSHG] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SSHG]') AND name = N'SSHG_Index_TEACHER')
ALTER INDEX [SSHG_Index_TEACHER] ON [dbo].[SSHG] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SSHG]') AND name = N'SSHG_Index_TEACHING_HG')
ALTER INDEX [SSHG_Index_TEACHING_HG] ON [dbo].[SSHG] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SSHG]') AND name = N'SSHG_Index_TID')
ALTER INDEX [SSHG_Index_TID] ON [dbo].[SSHG] REBUILD PARTITION = ALL;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="SSHG"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="SSHG"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<SSHG> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<int> Index_TID = new List<int>();
foreach (var entity in Entities)
{
Index_TID.Add(entity.TID);
}
builder.AppendLine("DELETE [dbo].[SSHG] WHERE");
// Index_TID
builder.Append("[TID] IN (");
for (int index = 0; index < Index_TID.Count; index++)
{
if (index != 0)
builder.Append(", ");
// TID
var parameterTID = $"@p{parameterIndex++}";
builder.Append(parameterTID);
command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the SSHG data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the SSHG data set</returns>
public override EduHubDataSetDataReader<SSHG> GetDataSetDataReader()
{
return new SSHGDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the SSHG data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the SSHG data set</returns>
public override EduHubDataSetDataReader<SSHG> GetDataSetDataReader(List<SSHG> Entities)
{
return new SSHGDataReader(new EduHubDataSetLoadedReader<SSHG>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class SSHGDataReader : EduHubDataSetDataReader<SSHG>
{
public SSHGDataReader(IEduHubDataSetReader<SSHG> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 10; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // TID
return Current.TID;
case 1: // HOMEGROUP
return Current.HOMEGROUP;
case 2: // SUBJECT
return Current.SUBJECT;
case 3: // TEACHER
return Current.TEACHER;
case 4: // STUDENT
return Current.STUDENT;
case 5: // VARIATION
return Current.VARIATION;
case 6: // TEACHING_HG
return Current.TEACHING_HG;
case 7: // LW_DATE
return Current.LW_DATE;
case 8: // LW_TIME
return Current.LW_TIME;
case 9: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 1: // HOMEGROUP
return Current.HOMEGROUP == null;
case 3: // TEACHER
return Current.TEACHER == null;
case 4: // STUDENT
return Current.STUDENT == null;
case 5: // VARIATION
return Current.VARIATION == null;
case 6: // TEACHING_HG
return Current.TEACHING_HG == null;
case 7: // LW_DATE
return Current.LW_DATE == null;
case 8: // LW_TIME
return Current.LW_TIME == null;
case 9: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // TID
return "TID";
case 1: // HOMEGROUP
return "HOMEGROUP";
case 2: // SUBJECT
return "SUBJECT";
case 3: // TEACHER
return "TEACHER";
case 4: // STUDENT
return "STUDENT";
case 5: // VARIATION
return "VARIATION";
case 6: // TEACHING_HG
return "TEACHING_HG";
case 7: // LW_DATE
return "LW_DATE";
case 8: // LW_TIME
return "LW_TIME";
case 9: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "TID":
return 0;
case "HOMEGROUP":
return 1;
case "SUBJECT":
return 2;
case "TEACHER":
return 3;
case "STUDENT":
return 4;
case "VARIATION":
return 5;
case "TEACHING_HG":
return 6;
case "LW_DATE":
return 7;
case "LW_TIME":
return 8;
case "LW_USER":
return 9;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
// ZipConstants.cs
//
// Copyright (C) 2001 Mike Krueger
// Copyright (C) 2004 John Reilly
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
// HISTORY
// 22-12-2009 DavidPierson Added AES support
using System;
using System.Text;
using System.Threading;
#if NETCF_1_0 || NETCF_2_0
using System.Globalization;
#endif
namespace GitHub.ICSharpCode.SharpZipLib.Zip
{
#region Enumerations
/// <summary>
/// Determines how entries are tested to see if they should use Zip64 extensions or not.
/// </summary>
public enum UseZip64
{
/// <summary>
/// Zip64 will not be forced on entries during processing.
/// </summary>
/// <remarks>An entry can have this overridden if required <see cref="ZipEntry.ForceZip64"></see></remarks>
Off,
/// <summary>
/// Zip64 should always be used.
/// </summary>
On,
/// <summary>
/// #ZipLib will determine use based on entry values when added to archive.
/// </summary>
Dynamic,
}
/// <summary>
/// The kind of compression used for an entry in an archive
/// </summary>
public enum CompressionMethod
{
/// <summary>
/// A direct copy of the file contents is held in the archive
/// </summary>
Stored = 0,
/// <summary>
/// Common Zip compression method using a sliding dictionary
/// of up to 32KB and secondary compression from Huffman/Shannon-Fano trees
/// </summary>
Deflated = 8,
/// <summary>
/// An extension to deflate with a 64KB window. Not supported by #Zip currently
/// </summary>
Deflate64 = 9,
/// <summary>
/// BZip2 compression. Not supported by #Zip.
/// </summary>
BZip2 = 11,
/// <summary>
/// WinZip special for AES encryption, Now supported by #Zip.
/// </summary>
WinZipAES = 99,
}
/// <summary>
/// Identifies the encryption algorithm used for an entry
/// </summary>
public enum EncryptionAlgorithm
{
/// <summary>
/// No encryption has been used.
/// </summary>
None = 0,
/// <summary>
/// Encrypted using PKZIP 2.0 or 'classic' encryption.
/// </summary>
PkzipClassic = 1,
/// <summary>
/// DES encryption has been used.
/// </summary>
Des = 0x6601,
/// <summary>
/// RCS encryption has been used for encryption.
/// </summary>
RC2 = 0x6602,
/// <summary>
/// Triple DES encryption with 168 bit keys has been used for this entry.
/// </summary>
TripleDes168 = 0x6603,
/// <summary>
/// Triple DES with 112 bit keys has been used for this entry.
/// </summary>
TripleDes112 = 0x6609,
/// <summary>
/// AES 128 has been used for encryption.
/// </summary>
Aes128 = 0x660e,
/// <summary>
/// AES 192 has been used for encryption.
/// </summary>
Aes192 = 0x660f,
/// <summary>
/// AES 256 has been used for encryption.
/// </summary>
Aes256 = 0x6610,
/// <summary>
/// RC2 corrected has been used for encryption.
/// </summary>
RC2Corrected = 0x6702,
/// <summary>
/// Blowfish has been used for encryption.
/// </summary>
Blowfish = 0x6720,
/// <summary>
/// Twofish has been used for encryption.
/// </summary>
Twofish = 0x6721,
/// <summary>
/// RC4 has been used for encryption.
/// </summary>
RC4 = 0x6801,
/// <summary>
/// An unknown algorithm has been used for encryption.
/// </summary>
Unknown = 0xffff
}
/// <summary>
/// Defines the contents of the general bit flags field for an archive entry.
/// </summary>
[Flags]
public enum GeneralBitFlags : int
{
/// <summary>
/// Bit 0 if set indicates that the file is encrypted
/// </summary>
Encrypted = 0x0001,
/// <summary>
/// Bits 1 and 2 - Two bits defining the compression method (only for Method 6 Imploding and 8,9 Deflating)
/// </summary>
Method = 0x0006,
/// <summary>
/// Bit 3 if set indicates a trailing data desciptor is appended to the entry data
/// </summary>
Descriptor = 0x0008,
/// <summary>
/// Bit 4 is reserved for use with method 8 for enhanced deflation
/// </summary>
ReservedPKware4 = 0x0010,
/// <summary>
/// Bit 5 if set indicates the file contains Pkzip compressed patched data.
/// Requires version 2.7 or greater.
/// </summary>
Patched = 0x0020,
/// <summary>
/// Bit 6 if set indicates strong encryption has been used for this entry.
/// </summary>
StrongEncryption = 0x0040,
/// <summary>
/// Bit 7 is currently unused
/// </summary>
Unused7 = 0x0080,
/// <summary>
/// Bit 8 is currently unused
/// </summary>
Unused8 = 0x0100,
/// <summary>
/// Bit 9 is currently unused
/// </summary>
Unused9 = 0x0200,
/// <summary>
/// Bit 10 is currently unused
/// </summary>
Unused10 = 0x0400,
/// <summary>
/// Bit 11 if set indicates the filename and
/// comment fields for this file must be encoded using UTF-8.
/// </summary>
UnicodeText = 0x0800,
/// <summary>
/// Bit 12 is documented as being reserved by PKware for enhanced compression.
/// </summary>
EnhancedCompress = 0x1000,
/// <summary>
/// Bit 13 if set indicates that values in the local header are masked to hide
/// their actual values, and the central directory is encrypted.
/// </summary>
/// <remarks>
/// Used when encrypting the central directory contents.
/// </remarks>
HeaderMasked = 0x2000,
/// <summary>
/// Bit 14 is documented as being reserved for use by PKware
/// </summary>
ReservedPkware14 = 0x4000,
/// <summary>
/// Bit 15 is documented as being reserved for use by PKware
/// </summary>
ReservedPkware15 = 0x8000
}
#endregion
/// <summary>
/// This class contains constants used for Zip format files
/// </summary>
public sealed class ZipConstants
{
#region Versions
/// <summary>
/// The version made by field for entries in the central header when created by this library
/// </summary>
/// <remarks>
/// This is also the Zip version for the library when comparing against the version required to extract
/// for an entry. See <see cref="ZipEntry.CanDecompress"/>.
/// </remarks>
public const int VersionMadeBy = 51; // was 45 before AES
/// <summary>
/// The version made by field for entries in the central header when created by this library
/// </summary>
/// <remarks>
/// This is also the Zip version for the library when comparing against the version required to extract
/// for an entry. See <see cref="ZipInputStream.CanDecompressEntry">ZipInputStream.CanDecompressEntry</see>.
/// </remarks>
[Obsolete("Use VersionMadeBy instead")]
public const int VERSION_MADE_BY = 51;
/// <summary>
/// The minimum version required to support strong encryption
/// </summary>
public const int VersionStrongEncryption = 50;
/// <summary>
/// The minimum version required to support strong encryption
/// </summary>
[Obsolete("Use VersionStrongEncryption instead")]
public const int VERSION_STRONG_ENCRYPTION = 50;
/// <summary>
/// Version indicating AES encryption
/// </summary>
public const int VERSION_AES = 51;
/// <summary>
/// The version required for Zip64 extensions (4.5 or higher)
/// </summary>
public const int VersionZip64 = 45;
#endregion
#region Header Sizes
/// <summary>
/// Size of local entry header (excluding variable length fields at end)
/// </summary>
public const int LocalHeaderBaseSize = 30;
/// <summary>
/// Size of local entry header (excluding variable length fields at end)
/// </summary>
[Obsolete("Use LocalHeaderBaseSize instead")]
public const int LOCHDR = 30;
/// <summary>
/// Size of Zip64 data descriptor
/// </summary>
public const int Zip64DataDescriptorSize = 24;
/// <summary>
/// Size of data descriptor
/// </summary>
public const int DataDescriptorSize = 16;
/// <summary>
/// Size of data descriptor
/// </summary>
[Obsolete("Use DataDescriptorSize instead")]
public const int EXTHDR = 16;
/// <summary>
/// Size of central header entry (excluding variable fields)
/// </summary>
public const int CentralHeaderBaseSize = 46;
/// <summary>
/// Size of central header entry
/// </summary>
[Obsolete("Use CentralHeaderBaseSize instead")]
public const int CENHDR = 46;
/// <summary>
/// Size of end of central record (excluding variable fields)
/// </summary>
public const int EndOfCentralRecordBaseSize = 22;
/// <summary>
/// Size of end of central record (excluding variable fields)
/// </summary>
[Obsolete("Use EndOfCentralRecordBaseSize instead")]
public const int ENDHDR = 22;
/// <summary>
/// Size of 'classic' cryptographic header stored before any entry data
/// </summary>
public const int CryptoHeaderSize = 12;
/// <summary>
/// Size of cryptographic header stored before entry data
/// </summary>
[Obsolete("Use CryptoHeaderSize instead")]
public const int CRYPTO_HEADER_SIZE = 12;
#endregion
#region Header Signatures
/// <summary>
/// Signature for local entry header
/// </summary>
public const int LocalHeaderSignature = 'P' | ('K' << 8) | (3 << 16) | (4 << 24);
/// <summary>
/// Signature for local entry header
/// </summary>
[Obsolete("Use LocalHeaderSignature instead")]
public const int LOCSIG = 'P' | ('K' << 8) | (3 << 16) | (4 << 24);
/// <summary>
/// Signature for spanning entry
/// </summary>
public const int SpanningSignature = 'P' | ('K' << 8) | (7 << 16) | (8 << 24);
/// <summary>
/// Signature for spanning entry
/// </summary>
[Obsolete("Use SpanningSignature instead")]
public const int SPANNINGSIG = 'P' | ('K' << 8) | (7 << 16) | (8 << 24);
/// <summary>
/// Signature for temporary spanning entry
/// </summary>
public const int SpanningTempSignature = 'P' | ('K' << 8) | ('0' << 16) | ('0' << 24);
/// <summary>
/// Signature for temporary spanning entry
/// </summary>
[Obsolete("Use SpanningTempSignature instead")]
public const int SPANTEMPSIG = 'P' | ('K' << 8) | ('0' << 16) | ('0' << 24);
/// <summary>
/// Signature for data descriptor
/// </summary>
/// <remarks>
/// This is only used where the length, Crc, or compressed size isnt known when the
/// entry is created and the output stream doesnt support seeking.
/// The local entry cannot be 'patched' with the correct values in this case
/// so the values are recorded after the data prefixed by this header, as well as in the central directory.
/// </remarks>
public const int DataDescriptorSignature = 'P' | ('K' << 8) | (7 << 16) | (8 << 24);
/// <summary>
/// Signature for data descriptor
/// </summary>
/// <remarks>
/// This is only used where the length, Crc, or compressed size isnt known when the
/// entry is created and the output stream doesnt support seeking.
/// The local entry cannot be 'patched' with the correct values in this case
/// so the values are recorded after the data prefixed by this header, as well as in the central directory.
/// </remarks>
[Obsolete("Use DataDescriptorSignature instead")]
public const int EXTSIG = 'P' | ('K' << 8) | (7 << 16) | (8 << 24);
/// <summary>
/// Signature for central header
/// </summary>
[Obsolete("Use CentralHeaderSignature instead")]
public const int CENSIG = 'P' | ('K' << 8) | (1 << 16) | (2 << 24);
/// <summary>
/// Signature for central header
/// </summary>
public const int CentralHeaderSignature = 'P' | ('K' << 8) | (1 << 16) | (2 << 24);
/// <summary>
/// Signature for Zip64 central file header
/// </summary>
public const int Zip64CentralFileHeaderSignature = 'P' | ('K' << 8) | (6 << 16) | (6 << 24);
/// <summary>
/// Signature for Zip64 central file header
/// </summary>
[Obsolete("Use Zip64CentralFileHeaderSignature instead")]
public const int CENSIG64 = 'P' | ('K' << 8) | (6 << 16) | (6 << 24);
/// <summary>
/// Signature for Zip64 central directory locator
/// </summary>
public const int Zip64CentralDirLocatorSignature = 'P' | ('K' << 8) | (6 << 16) | (7 << 24);
/// <summary>
/// Signature for archive extra data signature (were headers are encrypted).
/// </summary>
public const int ArchiveExtraDataSignature = 'P' | ('K' << 8) | (6 << 16) | (7 << 24);
/// <summary>
/// Central header digitial signature
/// </summary>
public const int CentralHeaderDigitalSignature = 'P' | ('K' << 8) | (5 << 16) | (5 << 24);
/// <summary>
/// Central header digitial signature
/// </summary>
[Obsolete("Use CentralHeaderDigitalSignaure instead")]
public const int CENDIGITALSIG = 'P' | ('K' << 8) | (5 << 16) | (5 << 24);
/// <summary>
/// End of central directory record signature
/// </summary>
public const int EndOfCentralDirectorySignature = 'P' | ('K' << 8) | (5 << 16) | (6 << 24);
/// <summary>
/// End of central directory record signature
/// </summary>
[Obsolete("Use EndOfCentralDirectorySignature instead")]
public const int ENDSIG = 'P' | ('K' << 8) | (5 << 16) | (6 << 24);
#endregion
#if NETCF_1_0 || NETCF_2_0
// This isnt so great but is better than nothing.
// Trying to work out an appropriate OEM code page would be good.
// 850 is a good default for english speakers particularly in Europe.
static int defaultCodePage = CultureInfo.CurrentCulture.TextInfo.ANSICodePage;
#else
static int defaultCodePage = Thread.CurrentThread.CurrentCulture.TextInfo.OEMCodePage;
#endif
/// <summary>
/// Default encoding used for string conversion. 0 gives the default system OEM code page.
/// Dont use unicode encodings if you want to be Zip compatible!
/// Using the default code page isnt the full solution neccessarily
/// there are many variable factors, codepage 850 is often a good choice for
/// European users, however be careful about compatability.
/// </summary>
public static int DefaultCodePage {
get {
return defaultCodePage;
}
set {
defaultCodePage = value;
}
}
/// <summary>
/// Convert a portion of a byte array to a string.
/// </summary>
/// <param name="data">
/// Data to convert to string
/// </param>
/// <param name="count">
/// Number of bytes to convert starting from index 0
/// </param>
/// <returns>
/// data[0]..data[length - 1] converted to a string
/// </returns>
public static string ConvertToString(byte[] data, int count)
{
if ( data == null ) {
return string.Empty;
}
return Encoding.GetEncoding(DefaultCodePage).GetString(data, 0, count);
}
/// <summary>
/// Convert a byte array to string
/// </summary>
/// <param name="data">
/// Byte array to convert
/// </param>
/// <returns>
/// <paramref name="data">data</paramref>converted to a string
/// </returns>
public static string ConvertToString(byte[] data)
{
if ( data == null ) {
return string.Empty;
}
return ConvertToString(data, data.Length);
}
/// <summary>
/// Convert a byte array to string
/// </summary>
/// <param name="flags">The applicable general purpose bits flags</param>
/// <param name="data">
/// Byte array to convert
/// </param>
/// <param name="count">The number of bytes to convert.</param>
/// <returns>
/// <paramref name="data">data</paramref>converted to a string
/// </returns>
public static string ConvertToStringExt(int flags, byte[] data, int count)
{
if ( data == null ) {
return string.Empty;
}
if ( (flags & (int)GeneralBitFlags.UnicodeText) != 0 ) {
return Encoding.UTF8.GetString(data, 0, count);
}
else {
return ConvertToString(data, count);
}
}
/// <summary>
/// Convert a byte array to string
/// </summary>
/// <param name="data">
/// Byte array to convert
/// </param>
/// <param name="flags">The applicable general purpose bits flags</param>
/// <returns>
/// <paramref name="data">data</paramref>converted to a string
/// </returns>
public static string ConvertToStringExt(int flags, byte[] data)
{
if ( data == null ) {
return string.Empty;
}
if ( (flags & (int)GeneralBitFlags.UnicodeText) != 0 ) {
return Encoding.UTF8.GetString(data, 0, data.Length);
}
else {
return ConvertToString(data, data.Length);
}
}
/// <summary>
/// Convert a string to a byte array
/// </summary>
/// <param name="str">
/// String to convert to an array
/// </param>
/// <returns>Converted array</returns>
public static byte[] ConvertToArray(string str)
{
if ( str == null ) {
return new byte[0];
}
return Encoding.GetEncoding(DefaultCodePage).GetBytes(str);
}
/// <summary>
/// Convert a string to a byte array
/// </summary>
/// <param name="flags">The applicable <see cref="GeneralBitFlags">general purpose bits flags</see></param>
/// <param name="str">
/// String to convert to an array
/// </param>
/// <returns>Converted array</returns>
public static byte[] ConvertToArray(int flags, string str)
{
if (str == null) {
return new byte[0];
}
if ((flags & (int)GeneralBitFlags.UnicodeText) != 0) {
return Encoding.UTF8.GetBytes(str);
}
else {
return ConvertToArray(str);
}
}
/// <summary>
/// Initialise default instance of <see cref="ZipConstants">ZipConstants</see>
/// </summary>
/// <remarks>
/// Private to prevent instances being created.
/// </remarks>
ZipConstants()
{
// Do nothing
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// 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.IO;
using System.Reflection;
using System.Threading;
using DiscUtils.CoreCompat;
namespace DiscUtils.Iscsi
{
/// <summary>
/// Represents a connection to a particular Target.
/// </summary>
public sealed class Session : IDisposable
{
private static int _nextInitiatorSessionId = new Random().Next();
private readonly IList<TargetAddress> _addresses;
/// <summary>
/// The set of all 'parameters' we've negotiated.
/// </summary>
private readonly Dictionary<string, string> _negotiatedParameters;
private ushort _nextConnectionId;
internal Session(SessionType type, string targetName, params TargetAddress[] addresses)
: this(type, targetName, null, null, addresses) {}
internal Session(SessionType type, string targetName, string userName, string password, IList<TargetAddress> addresses)
{
InitiatorSessionId = (uint)Interlocked.Increment(ref _nextInitiatorSessionId);
_addresses = addresses;
SessionType = type;
TargetName = targetName;
CommandSequenceNumber = 1;
CurrentTaskTag = 1;
// Default negotiated values...
MaxConnections = 1;
InitialR2T = true;
ImmediateData = true;
MaxBurstLength = 262144;
FirstBurstLength = 65536;
DefaultTime2Wait = 0;
DefaultTime2Retain = 60;
MaxOutstandingR2T = 1;
DataPDUInOrder = true;
DataSequenceInOrder = true;
_negotiatedParameters = new Dictionary<string, string>();
if (string.IsNullOrEmpty(userName))
{
ActiveConnection = new Connection(this, _addresses[0], new Authenticator[] { new NullAuthenticator() });
}
else
{
ActiveConnection = new Connection(this, _addresses[0], new Authenticator[] { new NullAuthenticator(), new ChapAuthenticator(userName, password) });
}
}
internal Connection ActiveConnection { get; private set; }
internal uint CommandSequenceNumber { get; private set; }
internal uint CurrentTaskTag { get; private set; }
internal uint InitiatorSessionId { get; }
internal ushort TargetSessionId { get; set; }
/// <summary>
/// Disposes of this instance, closing the session with the Target.
/// </summary>
public void Dispose()
{
if (ActiveConnection != null)
{
ActiveConnection.Close(LogoutReason.CloseSession);
}
ActiveConnection = null;
}
/// <summary>
/// Enumerates all of the Targets.
/// </summary>
/// <returns>The list of Targets.</returns>
/// <remarks>In practice, for an established session, this just returns details of
/// the connected Target.</remarks>
public TargetInfo[] EnumerateTargets()
{
return ActiveConnection.EnumerateTargets();
}
/// <summary>
/// Gets information about the LUNs available from the Target.
/// </summary>
/// <returns>The LUNs available.</returns>
public LunInfo[] GetLuns()
{
ScsiReportLunsCommand cmd = new ScsiReportLunsCommand(ScsiReportLunsCommand.InitialResponseSize);
ScsiReportLunsResponse resp = Send<ScsiReportLunsResponse>(cmd, null, 0, 0, ScsiReportLunsCommand.InitialResponseSize);
if (resp.Truncated)
{
cmd = new ScsiReportLunsCommand(resp.NeededDataLength);
resp = Send<ScsiReportLunsResponse>(cmd, null, 0, 0, (int)resp.NeededDataLength);
}
if (resp.Truncated)
{
throw new InvalidProtocolException("Truncated response");
}
LunInfo[] result = new LunInfo[resp.Luns.Count];
for (int i = 0; i < resp.Luns.Count; ++i)
{
result[i] = GetInfo((long)resp.Luns[i]);
}
return result;
}
/// <summary>
/// Gets all the block-device LUNs available from the Target.
/// </summary>
/// <returns>The block-device LUNs.</returns>
public long[] GetBlockDeviceLuns()
{
List<long> luns = new List<long>();
foreach (LunInfo info in GetLuns())
{
if (info.DeviceType == LunClass.BlockStorage)
{
luns.Add(info.Lun);
}
}
return luns.ToArray();
}
/// <summary>
/// Gets information about a particular LUN.
/// </summary>
/// <param name="lun">The LUN to query.</param>
/// <returns>Information about the LUN.</returns>
public LunInfo GetInfo(long lun)
{
ScsiInquiryCommand cmd = new ScsiInquiryCommand((ulong)lun, ScsiInquiryCommand.InitialResponseDataLength);
ScsiInquiryStandardResponse resp = Send<ScsiInquiryStandardResponse>(cmd, null, 0, 0, ScsiInquiryCommand.InitialResponseDataLength);
TargetInfo targetInfo = new TargetInfo(TargetName, new List<TargetAddress>(_addresses).ToArray());
return new LunInfo(targetInfo, lun, resp.DeviceType, resp.Removable, resp.VendorId, resp.ProductId, resp.ProductRevision);
}
/// <summary>
/// Gets the capacity of a particular LUN.
/// </summary>
/// <param name="lun">The LUN to query.</param>
/// <returns>The LUN's capacity.</returns>
public LunCapacity GetCapacity(long lun)
{
ScsiReadCapacityCommand cmd = new ScsiReadCapacityCommand((ulong)lun);
ScsiReadCapacityResponse resp = Send<ScsiReadCapacityResponse>(cmd, null, 0, 0, ScsiReadCapacityCommand.ResponseDataLength);
if (resp.Truncated)
{
throw new InvalidProtocolException("Truncated response");
}
return new LunCapacity(resp.NumLogicalBlocks, (int)resp.LogicalBlockSize);
}
/// <summary>
/// Provides read-write access to a LUN as a VirtualDisk.
/// </summary>
/// <param name="lun">The LUN to access.</param>
/// <returns>The new VirtualDisk instance.</returns>
public Disk OpenDisk(long lun)
{
return OpenDisk(lun, FileAccess.ReadWrite);
}
/// <summary>
/// Provides access to a LUN as a VirtualDisk.
/// </summary>
/// <param name="lun">The LUN to access.</param>
/// <param name="access">The type of access desired.</param>
/// <returns>The new VirtualDisk instance.</returns>
public Disk OpenDisk(long lun, FileAccess access)
{
return new Disk(this, lun, access);
}
/// <summary>
/// Reads some data from a LUN.
/// </summary>
/// <param name="lun">The LUN to read from.</param>
/// <param name="startBlock">The first block to read.</param>
/// <param name="blockCount">The number of blocks to read.</param>
/// <param name="buffer">The buffer to fill.</param>
/// <param name="offset">The offset of the first byte to fill.</param>
/// <returns>The number of bytes read.</returns>
public int Read(long lun, long startBlock, short blockCount, byte[] buffer, int offset)
{
ScsiReadCommand cmd = new ScsiReadCommand((ulong)lun, (uint)startBlock, (ushort)blockCount);
return Send(cmd, null, 0, 0, buffer, offset, buffer.Length - offset);
}
/// <summary>
/// Writes some data to a LUN.
/// </summary>
/// <param name="lun">The LUN to write to.</param>
/// <param name="startBlock">The first block to write.</param>
/// <param name="blockCount">The number of blocks to write.</param>
/// <param name="blockSize">The size of each block (must match the actual LUN geometry).</param>
/// <param name="buffer">The data to write.</param>
/// <param name="offset">The offset of the first byte to write in buffer.</param>
public void Write(long lun, long startBlock, short blockCount, int blockSize, byte[] buffer, int offset)
{
ScsiWriteCommand cmd = new ScsiWriteCommand((ulong)lun, (uint)startBlock, (ushort)blockCount);
Send(cmd, buffer, offset, blockCount * blockSize, null, 0, 0);
}
/// <summary>
/// Performs a raw SCSI command.
/// </summary>
/// <param name="lun">The target LUN for the command.</param>
/// <param name="command">The command (a SCSI Command Descriptor Block, aka CDB).</param>
/// <param name="outBuffer">Buffer of data to send with the command (or <c>null</c>).</param>
/// <param name="outBufferOffset">Offset of first byte of data to send with the command.</param>
/// <param name="outBufferLength">Amount of data to send with the command.</param>
/// <param name="inBuffer">Buffer to receive data from the command (or <c>null</c>).</param>
/// <param name="inBufferOffset">Offset of the first byte position to fill with received data.</param>
/// <param name="inBufferLength">The expected amount of data to receive.</param>
/// <returns>The number of bytes of data received.</returns>
/// <remarks>
/// <para>This method permits the caller to send raw SCSI commands to a LUN.</para>
/// <para>The command .</para>
/// </remarks>
public int RawCommand(long lun, byte[] command, byte[] outBuffer, int outBufferOffset, int outBufferLength, byte[] inBuffer, int inBufferOffset, int inBufferLength)
{
if (outBuffer == null && outBufferLength != 0)
{
throw new ArgumentException("outBufferLength must be 0 if outBuffer null", nameof(outBufferLength));
}
if (inBuffer == null && inBufferLength != 0)
{
throw new ArgumentException("inBufferLength must be 0 if inBuffer null", nameof(inBufferLength));
}
ScsiRawCommand cmd = new ScsiRawCommand((ulong)lun, command, 0, command.Length);
return Send(cmd, outBuffer, outBufferOffset, outBufferLength, inBuffer, inBufferOffset, inBufferLength);
}
internal uint NextCommandSequenceNumber()
{
return ++CommandSequenceNumber;
}
internal uint NextTaskTag()
{
return ++CurrentTaskTag;
}
internal ushort NextConnectionId()
{
return ++_nextConnectionId;
}
internal void GetParametersToNegotiate(TextBuffer parameters, KeyUsagePhase phase)
{
PropertyInfo[] properties = GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach (PropertyInfo propInfo in properties)
{
ProtocolKeyAttribute attr = (ProtocolKeyAttribute)ReflectionHelper.GetCustomAttribute(propInfo, typeof(ProtocolKeyAttribute));
if (attr != null)
{
object value = propInfo.GetGetMethod(true).Invoke(this, null);
if (attr.ShouldTransmit(value, propInfo.PropertyType, phase, SessionType == SessionType.Discovery))
{
parameters.Add(attr.Name, ProtocolKeyAttribute.GetValueAsString(value, propInfo.PropertyType));
_negotiatedParameters.Add(attr.Name, string.Empty);
}
}
}
}
internal void ConsumeParameters(TextBuffer inParameters, TextBuffer outParameters)
{
PropertyInfo[] properties = GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach (PropertyInfo propInfo in properties)
{
ProtocolKeyAttribute attr = (ProtocolKeyAttribute)ReflectionHelper.GetCustomAttribute(propInfo, typeof(ProtocolKeyAttribute));
if (attr != null)
{
if (inParameters[attr.Name] != null)
{
object value = ProtocolKeyAttribute.GetValueAsObject(inParameters[attr.Name], propInfo.PropertyType);
propInfo.GetSetMethod(true).Invoke(this, new[] { value });
inParameters.Remove(attr.Name);
if (attr.Type == KeyType.Negotiated && !_negotiatedParameters.ContainsKey(attr.Name))
{
value = propInfo.GetGetMethod(true).Invoke(this, null);
outParameters.Add(attr.Name, ProtocolKeyAttribute.GetValueAsString(value, propInfo.PropertyType));
_negotiatedParameters.Add(attr.Name, string.Empty);
}
}
}
}
}
#region Protocol Features
/// <summary>
/// Gets the name of the iSCSI target this session is connected to.
/// </summary>
[ProtocolKey("TargetName", null, KeyUsagePhase.SecurityNegotiation, KeySender.Initiator, KeyType.Declarative, UsedForDiscovery = true)]
public string TargetName { get; internal set; }
/// <summary>
/// Gets the name of the iSCSI initiator seen by the target for this session.
/// </summary>
[ProtocolKey("InitiatorName", null, KeyUsagePhase.SecurityNegotiation, KeySender.Initiator, KeyType.Declarative, UsedForDiscovery = true)]
public string InitiatorName
{
get { return "iqn.2008-2010-04.discutils.codeplex.com"; }
}
/// <summary>
/// Gets the friendly name of the iSCSI target this session is connected to.
/// </summary>
[ProtocolKey("TargetAlias", "", KeyUsagePhase.All, KeySender.Target, KeyType.Declarative)]
public string TargetAlias { get; internal set; }
[ProtocolKey("SessionType", null, KeyUsagePhase.SecurityNegotiation, KeySender.Initiator, KeyType.Declarative, UsedForDiscovery = true)]
internal SessionType SessionType { get; set; }
[ProtocolKey("MaxConnections", "1", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, LeadingConnectionOnly = true)]
internal int MaxConnections { get; set; }
[ProtocolKey("InitiatorAlias", "", KeyUsagePhase.All, KeySender.Initiator, KeyType.Declarative)]
internal string InitiatorAlias { get; set; }
[ProtocolKey("TargetPortalGroupTag", null, KeyUsagePhase.SecurityNegotiation, KeySender.Target, KeyType.Declarative)]
internal int TargetPortalGroupTag { get; set; }
[ProtocolKey("InitialR2T", "Yes", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, LeadingConnectionOnly = true)]
internal bool InitialR2T { get; set; }
[ProtocolKey("ImmediateData", "Yes", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, LeadingConnectionOnly = true)]
internal bool ImmediateData { get; set; }
[ProtocolKey("MaxBurstLength", "262144", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, LeadingConnectionOnly = true)]
internal int MaxBurstLength { get; set; }
[ProtocolKey("FirstBurstLength", "65536", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, LeadingConnectionOnly = true)]
internal int FirstBurstLength { get; set; }
[ProtocolKey("DefaultTime2Wait", "2", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, LeadingConnectionOnly = true)]
internal int DefaultTime2Wait { get; set; }
[ProtocolKey("DefaultTime2Retain", "20", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, LeadingConnectionOnly = true)]
internal int DefaultTime2Retain { get; set; }
[ProtocolKey("MaxOutstandingR2T", "1", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, LeadingConnectionOnly = true)]
internal int MaxOutstandingR2T { get; set; }
[ProtocolKey("DataPDUInOrder", "Yes", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, LeadingConnectionOnly = true)]
internal bool DataPDUInOrder { get; set; }
[ProtocolKey("DataSequenceInOrder", "Yes", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, LeadingConnectionOnly = true)]
internal bool DataSequenceInOrder { get; set; }
[ProtocolKey("ErrorRecoveryLevel", "0", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, LeadingConnectionOnly = true)]
internal int ErrorRecoveryLevel { get; set; }
#endregion
#region Scsi Bus
/// <summary>
/// Sends an SCSI command (aka task) to a LUN via the connected target.
/// </summary>
/// <param name="cmd">The command to send.</param>
/// <param name="outBuffer">The data to send with the command.</param>
/// <param name="outBufferOffset">The offset of the first byte to send.</param>
/// <param name="outBufferCount">The number of bytes to send, if any.</param>
/// <param name="inBuffer">The buffer to fill with returned data.</param>
/// <param name="inBufferOffset">The first byte to fill with returned data.</param>
/// <param name="inBufferMax">The maximum amount of data to receive.</param>
/// <returns>The number of bytes received.</returns>
private int Send(ScsiCommand cmd, byte[] outBuffer, int outBufferOffset, int outBufferCount, byte[] inBuffer, int inBufferOffset, int inBufferMax)
{
return ActiveConnection.Send(cmd, outBuffer, outBufferOffset, outBufferCount, inBuffer, inBufferOffset, inBufferMax);
}
private T Send<T>(ScsiCommand cmd, byte[] buffer, int offset, int count, int expected)
where T : ScsiResponse, new()
{
return ActiveConnection.Send<T>(cmd, buffer, offset, count, expected);
}
#endregion
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ListOperator.cs" company="PropertyTools">
// Copyright (c) 2014 PropertyTools contributors
// </copyright>
// <summary>
// Represents an operator for DataGrid when its ItemsSource is of IList.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace PropertyTools.Wpf
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Data;
/// <summary>
/// Represents an operator for <see cref="DataGrid" /> when its ItemsSource is of type <see cref="IList" />.
/// </summary>
public class ListOperator : DataGridOperator
{
/// <summary>
/// Generate column definitions based on a list of items.
/// </summary>
/// <param name="list">The list of items.</param>
/// <returns>A sequence of column definitions.</returns>
/// <remarks>The constraint is that all the items in the ItemsSource's should be of the same type.
/// For non built in type, a
/// <code>public static T Parse(string s, IFormatProvider formatProvider)</code> and
/// <code>public string ToString(string format, IFormatProvider formatProvider)</code> should be defined.
/// interface type is not acceptable for no object instance can be created based on it.</remarks>
protected override IEnumerable<ColumnDefinition> GenerateColumnDefinitions(IList list)
{
if (list == null)
{
yield break;
}
// Strategy 1: get properties from IItemProperties
var view = CollectionViewSource.GetDefaultView(list);
var itemPropertiesView = view as IItemProperties;
if (itemPropertiesView?.ItemProperties != null && itemPropertiesView.ItemProperties.Count > 0)
{
foreach (var info in itemPropertiesView.ItemProperties)
{
var descriptor = info.Descriptor as PropertyDescriptor;
if (descriptor == null || !descriptor.IsBrowsable)
{
continue;
}
var cd = new ColumnDefinition
{
PropertyName = descriptor.Name,
Header = info.Name,
HorizontalAlignment = this.DefaultHorizontalAlignment,
Width = this.DefaultColumnWidth
};
yield return cd;
}
yield break;
}
// Strategy 2: get properties from type descriptor
var itemType = TypeHelper.FindBiggestCommonType(list);
var properties = TypeDescriptor.GetProperties(itemType);
if (properties.Count == 0)
{
// Otherwise try to get the property descriptors from an instance
properties = GetPropertiesFromInstance(list, itemType);
}
if (properties.Count > 0)
{
foreach (PropertyDescriptor descriptor in properties)
{
if (!descriptor.IsBrowsable)
{
continue;
}
var cd = new ColumnDefinition
{
PropertyName = descriptor.Name,
Header = descriptor.Name,
HorizontalAlignment = this.DefaultHorizontalAlignment,
Width = this.DefaultColumnWidth
};
yield return cd;
}
yield break;
}
// Strategy 3: create a single column
var itemsType = TypeHelper.GetItemType(list);
yield return
new ColumnDefinition
{
Header = itemsType.Name,
HorizontalAlignment = this.DefaultHorizontalAlignment,
Width = this.DefaultColumnWidth
};
}
/// <summary>
/// Gets the item in cell.
/// </summary>
/// <param name="owner">The owner.</param>
/// <param name="cell">The cell reference.</param>
/// <returns>
/// The item <see cref="object" />.
/// </returns>
public override object GetItem(DataGrid owner, CellRef cell)
{
var list = owner.ItemsSource;
if (list == null)
{
return null;
}
var index = this.GetItemIndex(owner, cell);
if (index >= 0 && index < list.Count)
{
return list[index];
}
return null;
}
/// <summary>
/// Inserts item to <see cref="DataGrid" />.
/// </summary>
/// <param name="owner">The owner.</param>
/// <param name="index">The index.</param>
/// <returns>
/// <c>true</c> if insertion is successful, <c>false</c> otherwise.
/// </returns>
public override bool InsertItem(DataGrid owner, int index)
{
var list = owner.ItemsSource;
if (list == null)
{
return false;
}
var itemType = TypeHelper.GetItemType(list);
object newItem = null;
if (itemType == typeof(string))
{
newItem = string.Empty;
}
if (itemType == typeof(double))
{
newItem = 0.0;
}
if (itemType == typeof(int))
{
newItem = 0;
}
try
{
if (newItem == null)
{
newItem = this.CreateItem(owner, itemType);
}
}
catch
{
return false;
}
if (index < 0)
{
list.Add(newItem);
}
else
{
list.Insert(index, newItem);
}
return true;
}
/// <summary>
/// Sets value to item in cell.
/// </summary>
/// <param name="owner">The owner.</param>
/// <param name="cell">The cell reference.</param>
/// <param name="value">The value.</param>
public override void SetValue(DataGrid owner, CellRef cell, object value)
{
var list = owner.ItemsSource;
if (list == null || cell.Column < 0 || cell.Row < 0)
{
return;
}
var index = this.GetItemIndex(owner, cell);
list[index] = value;
}
/// <summary>
/// Gets the item index for the specified cell.
/// </summary>
/// <param name="owner">The owner.</param>
/// <param name="cell">The cell.</param>
/// <returns>
/// The get item index.
/// </returns>
protected virtual int GetItemIndex(DataGrid owner, CellRef cell)
{
if (owner.WrapItems)
{
return owner.ItemsInRows ? (cell.Row * owner.Columns) + cell.Column : (cell.Column * owner.Rows) + cell.Row;
}
return owner.ItemsInRows ? cell.Row : cell.Column;
}
/// <summary>
/// Gets the binding path for the specified cell.
/// </summary>
/// <param name="owner">The owner.</param>
/// <param name="cell">The cell.</param>
/// <returns>
/// The binding path
/// </returns>
public override string GetBindingPath(DataGrid owner, CellRef cell)
{
var pd = owner.GetPropertyDefinition(cell);
if (pd?.PropertyName != null)
{
return pd.PropertyName;
}
var index = this.GetItemIndex(owner, cell);
return $"[{index}]";
}
/// <summary>
/// Gets property descriptors from one instance.
/// </summary>
/// <param name="items">The items.</param>
/// <param name="itemType">The target item type.</param>
/// <returns>
/// The <see cref="PropertyDescriptorCollection" />.
/// </returns>
private static PropertyDescriptorCollection GetPropertiesFromInstance(IList items, Type itemType)
{
foreach (var item in items)
{
if (item != null && item.GetType() == itemType)
{
return TypeDescriptor.GetProperties(item);
}
}
return new PropertyDescriptorCollection(new PropertyDescriptor[0]);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing.Text;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Drawing
{
/// <summary>
/// Abstracts a group of type faces having a similar basic design but having certain variation in styles.
/// </summary>
public sealed class FontFamily : MarshalByRefObject, IDisposable
{
private const int NeutralLanguage = 0;
private IntPtr _nativeFamily;
private bool _createDefaultOnFail;
#if DEBUG
private static object s_lockObj = new object();
private static int s_idCount = 0;
private int _id;
#endif
[SuppressMessage("Microsoft.Security", "CA2106:SecureAsserts")]
private void SetNativeFamily(IntPtr family)
{
Debug.Assert(_nativeFamily == IntPtr.Zero, "Setting GDI+ native font family when already initialized.");
Debug.Assert(family != IntPtr.Zero, "Setting GDI+ native font family to null.");
_nativeFamily = family;
#if DEBUG
lock (s_lockObj)
{
_id = ++s_idCount;
}
#endif
}
internal FontFamily(IntPtr family) => SetNativeFamily(family);
/// <summary>
/// Initializes a new instance of the <see cref='FontFamily'/> class with the specified name.
///
/// The <paramref name="createDefaultOnFail"/> parameter determines how errors are handled when creating a
/// font based on a font family that does not exist on the end user's system at run time. If this parameter is
/// true, then a fall-back fontwill always be used instead. If this parameter is false, an exception will be thrown.
/// </summary>
internal FontFamily(string name, bool createDefaultOnFail)
{
_createDefaultOnFail = createDefaultOnFail;
CreateFontFamily(name, null);
}
/// <summary>
/// Initializes a new instance of the <see cref='FontFamily'/> class with the specified name.
/// </summary>
public FontFamily(string name) => CreateFontFamily(name, null);
/// <summary>
/// Initializes a new instance of the <see cref='FontFamily'/> class in the specified
/// <see cref='FontCollection'/> and with the specified name.
/// </summary>
public FontFamily(string name, FontCollection fontCollection) => CreateFontFamily(name, fontCollection);
// Creates the native font family object.
// Note: GDI+ creates singleton font family objects (from the corresponding font file) and reference count them.
private void CreateFontFamily(string name, FontCollection fontCollection)
{
IntPtr fontfamily = IntPtr.Zero;
IntPtr nativeFontCollection = (fontCollection == null) ? IntPtr.Zero : fontCollection._nativeFontCollection;
int status = SafeNativeMethods.Gdip.GdipCreateFontFamilyFromName(name, new HandleRef(fontCollection, nativeFontCollection), out fontfamily);
if (status != SafeNativeMethods.Gdip.Ok)
{
if (_createDefaultOnFail)
{
fontfamily = GetGdipGenericSansSerif(); // This throws if failed.
}
else
{
// Special case this incredibly common error message to give more information.
if (status == SafeNativeMethods.Gdip.FontFamilyNotFound)
{
throw new ArgumentException(SR.Format(SR.GdiplusFontFamilyNotFound, name));
}
else if (status == SafeNativeMethods.Gdip.NotTrueTypeFont)
{
throw new ArgumentException(SR.Format(SR.GdiplusNotTrueTypeFont, name));
}
else
{
throw SafeNativeMethods.Gdip.StatusException(status);
}
}
}
SetNativeFamily(fontfamily);
}
/// <summary>
/// Initializes a new instance of the <see cref='FontFamily'/> class from the specified generic font family.
/// </summary>
public FontFamily(GenericFontFamilies genericFamily)
{
IntPtr nativeFamily = IntPtr.Zero;
int status;
switch (genericFamily)
{
case GenericFontFamilies.Serif:
status = SafeNativeMethods.Gdip.GdipGetGenericFontFamilySerif(out nativeFamily);
break;
case GenericFontFamilies.SansSerif:
status = SafeNativeMethods.Gdip.GdipGetGenericFontFamilySansSerif(out nativeFamily);
break;
case GenericFontFamilies.Monospace:
default:
status = SafeNativeMethods.Gdip.GdipGetGenericFontFamilyMonospace(out nativeFamily);
break;
}
SafeNativeMethods.Gdip.CheckStatus(status);
SetNativeFamily(nativeFamily);
}
~FontFamily() => Dispose(false);
internal IntPtr NativeFamily => _nativeFamily;
public override bool Equals(object obj)
{
if (obj == this)
{
return true;
}
if (!(obj is FontFamily otherFamily))
{
return false;
}
// We can safely use the ptr to the native GDI+ FontFamily because it is common to
// all objects of the same family (singleton RO object).
return otherFamily.NativeFamily == NativeFamily;
}
/// <summary>
/// Converts this <see cref='FontFamily'/> to a human-readable string.
/// </summary>
public override string ToString() => $"[{GetType().Name}: Name={Name}]";
/// <summary>
/// Gets a hash code for this <see cref='FontFamily'/>.
/// </summary>
public override int GetHashCode() => GetName(NeutralLanguage).GetHashCode();
private static int CurrentLanguage => CultureInfo.CurrentUICulture.LCID;
/// <summary>
/// Disposes of this <see cref='FontFamily'/>.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (_nativeFamily != IntPtr.Zero)
{
try
{
#if DEBUG
int status =
#endif
SafeNativeMethods.Gdip.GdipDeleteFontFamily(new HandleRef(this, _nativeFamily));
#if DEBUG
Debug.Assert(status == SafeNativeMethods.Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture));
#endif
}
catch (Exception ex) when (!ClientUtils.IsCriticalException(ex))
{
}
finally
{
_nativeFamily = IntPtr.Zero;
}
}
}
/// <summary>
/// Gets the name of this <see cref='FontFamily'/>.
/// </summary>
public string Name => GetName(CurrentLanguage);
/// <summary>
/// Retuns the name of this <see cref='FontFamily'/> in the specified language.
/// </summary>
public string GetName(int language)
{
// LF_FACESIZE is 32
var name = new StringBuilder(32);
int status = SafeNativeMethods.Gdip.GdipGetFamilyName(new HandleRef(this, NativeFamily), name, language);
SafeNativeMethods.Gdip.CheckStatus(status);
return name.ToString();
}
/// <summary>
/// Returns an array that contains all of the <see cref='FontFamily'/> objects associated with the current
/// graphics context.
/// </summary>
public static FontFamily[] Families => new InstalledFontCollection().Families;
/// <summary>
/// Gets a generic SansSerif <see cref='FontFamily'/>.
/// </summary>
public static FontFamily GenericSansSerif => new FontFamily(GetGdipGenericSansSerif());
private static IntPtr GetGdipGenericSansSerif()
{
IntPtr nativeFamily = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipGetGenericFontFamilySansSerif(out nativeFamily);
SafeNativeMethods.Gdip.CheckStatus(status);
return nativeFamily;
}
/// <summary>
/// Gets a generic Serif <see cref='FontFamily'/>.
/// </summary>
public static FontFamily GenericSerif => new FontFamily(GenericFontFamilies.Serif);
/// <summary>
/// Gets a generic monospace <see cref='FontFamily'/>.
/// </summary>
public static FontFamily GenericMonospace => new FontFamily(GenericFontFamilies.Monospace);
/// <summary>
/// Returns an array that contains all of the <see cref='FontFamily'/> objects associated with the specified
/// graphics context.
[Obsolete("Do not use method GetFamilies, use property Families instead")]
public static FontFamily[] GetFamilies(Graphics graphics)
{
if (graphics == null)
{
throw new ArgumentNullException(nameof(graphics));
}
return new InstalledFontCollection().Families;
}
/// <summary>
/// Indicates whether the specified <see cref='FontStyle'/> is available.
/// </summary>
public bool IsStyleAvailable(FontStyle style)
{
int bresult;
int status = SafeNativeMethods.Gdip.GdipIsStyleAvailable(new HandleRef(this, NativeFamily), style, out bresult);
SafeNativeMethods.Gdip.CheckStatus(status);
return bresult != 0;
}
/// <summary>
/// Gets the size of the Em square for the specified style in font design units.
/// </summary>
public int GetEmHeight(FontStyle style)
{
int result = 0;
int status = SafeNativeMethods.Gdip.GdipGetEmHeight(new HandleRef(this, NativeFamily), style, out result);
SafeNativeMethods.Gdip.CheckStatus(status);
return result;
}
/// <summary>
/// Returns the ascender metric for Windows.
/// </summary>
public int GetCellAscent(FontStyle style)
{
int result = 0;
int status = SafeNativeMethods.Gdip.GdipGetCellAscent(new HandleRef(this, NativeFamily), style, out result);
SafeNativeMethods.Gdip.CheckStatus(status);
return result;
}
/// <summary>
/// Returns the descender metric for Windows.
/// </summary>
public int GetCellDescent(FontStyle style)
{
int result = 0;
int status = SafeNativeMethods.Gdip.GdipGetCellDescent(new HandleRef(this, NativeFamily), style, out result);
SafeNativeMethods.Gdip.CheckStatus(status);
return result;
}
/// <summary>
/// Returns the distance between two consecutive lines of text for this <see cref='FontFamily'/> with the
/// specified <see cref='FontStyle'/>.
/// </summary>
public int GetLineSpacing(FontStyle style)
{
int result = 0;
int status = SafeNativeMethods.Gdip.GdipGetLineSpacing(new HandleRef(this, NativeFamily), style, out result);
SafeNativeMethods.Gdip.CheckStatus(status);
return result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\Arm\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.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void LoadVector128_UInt16()
{
var test = new LoadUnaryOpTest__LoadVector128_UInt16();
if (test.IsSupported)
{
// Validates basic functionality works
test.RunBasicScenario_Load();
// Validates calling via reflection works
test.RunReflectionScenario_Load();
}
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 LoadUnaryOpTest__LoadVector128_UInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(UInt16[] inArray1, UInt16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16);
private static UInt16[] _data = new UInt16[Op1ElementCount];
private DataTable _dataTable;
public LoadUnaryOpTest__LoadVector128_UInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); }
_dataTable = new DataTable(_data, new UInt16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.LoadVector128(
(UInt16*)(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.LoadVector128), new Type[] { typeof(UInt16*) })
.Invoke(null, new object[] {
Pointer.Box(_dataTable.inArray1Ptr, typeof(UInt16*))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
Succeeded = false;
try
{
RunBasicScenario_Load();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<UInt16> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray = new UInt16[Op1ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray = new UInt16[Op1ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt16[] firstOp, UInt16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (firstOp[0] != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (firstOp[i] != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.LoadVector128)}<UInt16>(Vector128<UInt16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.CoreModules.Framework.InterfaceCommander;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Timers;
using System.Xml;
using System.Xml.Serialization;
namespace OpenSim.Region.OptionalModules.World.TreePopulator
{
/// <summary>
/// Version 2.02 - Still hacky
/// </summary>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "TreePopulatorModule")]
public class TreePopulatorModule : INonSharedRegionModule, ICommandableModule, IVegetationModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private readonly Commander m_commander = new Commander("tree");
private Scene m_scene;
[XmlRootAttribute(ElementName = "Copse", IsNullable = false)]
public class Copse
{
public string m_name;
public Boolean m_frozen;
public Tree m_tree_type;
public int m_tree_quantity;
public float m_treeline_low;
public float m_treeline_high;
public Vector3 m_seed_point;
public double m_range;
public Vector3 m_initial_scale;
public Vector3 m_maximum_scale;
public Vector3 m_rate;
[XmlIgnore]
public Boolean m_planted;
[XmlIgnore]
public List<UUID> m_trees;
public Copse()
{
}
public Copse(string fileName, Boolean planted)
{
Copse cp = (Copse)DeserializeObject(fileName);
this.m_name = cp.m_name;
this.m_frozen = cp.m_frozen;
this.m_tree_quantity = cp.m_tree_quantity;
this.m_treeline_high = cp.m_treeline_high;
this.m_treeline_low = cp.m_treeline_low;
this.m_range = cp.m_range;
this.m_tree_type = cp.m_tree_type;
this.m_seed_point = cp.m_seed_point;
this.m_initial_scale = cp.m_initial_scale;
this.m_maximum_scale = cp.m_maximum_scale;
this.m_initial_scale = cp.m_initial_scale;
this.m_rate = cp.m_rate;
this.m_planted = planted;
this.m_trees = new List<UUID>();
}
public Copse(string copsedef)
{
char[] delimiterChars = {':', ';'};
string[] field = copsedef.Split(delimiterChars);
this.m_name = field[1].Trim();
this.m_frozen = (copsedef[0] == 'F');
this.m_tree_quantity = int.Parse(field[2]);
this.m_treeline_high = float.Parse(field[3], Culture.NumberFormatInfo);
this.m_treeline_low = float.Parse(field[4], Culture.NumberFormatInfo);
this.m_range = double.Parse(field[5], Culture.NumberFormatInfo);
this.m_tree_type = (Tree) Enum.Parse(typeof(Tree),field[6]);
this.m_seed_point = Vector3.Parse(field[7]);
this.m_initial_scale = Vector3.Parse(field[8]);
this.m_maximum_scale = Vector3.Parse(field[9]);
this.m_rate = Vector3.Parse(field[10]);
this.m_planted = true;
this.m_trees = new List<UUID>();
}
public Copse(string name, int quantity, float high, float low, double range, Vector3 point, Tree type, Vector3 scale, Vector3 max_scale, Vector3 rate, List<UUID> trees)
{
this.m_name = name;
this.m_frozen = false;
this.m_tree_quantity = quantity;
this.m_treeline_high = high;
this.m_treeline_low = low;
this.m_range = range;
this.m_tree_type = type;
this.m_seed_point = point;
this.m_initial_scale = scale;
this.m_maximum_scale = max_scale;
this.m_rate = rate;
this.m_planted = false;
this.m_trees = trees;
}
public override string ToString()
{
string frozen = (this.m_frozen ? "F" : "A");
return string.Format("{0}TPM: {1}; {2}; {3:0.0}; {4:0.0}; {5:0.0}; {6}; {7:0.0}; {8:0.0}; {9:0.0}; {10:0.00};",
frozen,
this.m_name,
this.m_tree_quantity,
this.m_treeline_high,
this.m_treeline_low,
this.m_range,
this.m_tree_type,
this.m_seed_point.ToString(),
this.m_initial_scale.ToString(),
this.m_maximum_scale.ToString(),
this.m_rate.ToString());
}
}
private List<Copse> m_copse;
private double m_update_ms = 1000.0; // msec between updates
private bool m_active_trees = false;
Timer CalculateTrees;
#region ICommandableModule Members
public ICommander CommandInterface
{
get { return m_commander; }
}
#endregion
#region Region Module interface
public void Initialise(IConfigSource config)
{
// ini file settings
try
{
m_active_trees = config.Configs["Trees"].GetBoolean("active_trees", m_active_trees);
}
catch (Exception)
{
m_log.Debug("[TREES]: ini failure for active_trees - using default");
}
try
{
m_update_ms = config.Configs["Trees"].GetDouble("update_rate", m_update_ms);
}
catch (Exception)
{
m_log.Debug("[TREES]: ini failure for update_rate - using default");
}
InstallCommands();
m_log.Debug("[TREES]: Initialised tree module");
}
public void AddRegion(Scene scene)
{
m_scene = scene;
m_scene.RegisterModuleCommander(m_commander);
m_scene.EventManager.OnPluginConsole += EventManager_OnPluginConsole;
}
public void RemoveRegion(Scene scene)
{
}
public void RegionLoaded(Scene scene)
{
ReloadCopse();
if (m_copse.Count > 0)
m_log.Info("[TREES]: Copse load complete");
if (m_active_trees)
activeizeTreeze(true);
}
public void Close()
{
}
public string Name
{
get { return "TreePopulatorModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
//--------------------------------------------------------------
#region ICommandableModule Members
private void HandleTreeActive(Object[] args)
{
if ((Boolean)args[0] && !m_active_trees)
{
m_log.InfoFormat("[TREES]: Activating Trees");
m_active_trees = true;
activeizeTreeze(m_active_trees);
}
else if (!(Boolean)args[0] && m_active_trees)
{
m_log.InfoFormat("[TREES]: Trees module is no longer active");
m_active_trees = false;
activeizeTreeze(m_active_trees);
}
else
{
m_log.InfoFormat("[TREES]: Trees module is already in the required state");
}
}
private void HandleTreeFreeze(Object[] args)
{
string copsename = ((string)args[0]).Trim();
Boolean freezeState = (Boolean) args[1];
foreach (Copse cp in m_copse)
{
if (cp.m_name == copsename && (!cp.m_frozen && freezeState || cp.m_frozen && !freezeState))
{
cp.m_frozen = freezeState;
foreach (UUID tree in cp.m_trees)
{
SceneObjectPart sop = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
sop.Name = (freezeState ? sop.Name.Replace("ATPM", "FTPM") : sop.Name.Replace("FTPM", "ATPM"));
sop.ParentGroup.HasGroupChanged = true;
}
m_log.InfoFormat("[TREES]: Activity for copse {0} is frozen {1}", copsename, freezeState);
return;
}
else if (cp.m_name == copsename && (cp.m_frozen && freezeState || !cp.m_frozen && !freezeState))
{
m_log.InfoFormat("[TREES]: Copse {0} is already in the requested freeze state", copsename);
return;
}
}
m_log.InfoFormat("[TREES]: Copse {0} was not found - command failed", copsename);
}
private void HandleTreeLoad(Object[] args)
{
Copse copse;
m_log.InfoFormat("[TREES]: Loading copse definition....");
copse = new Copse(((string)args[0]), false);
foreach (Copse cp in m_copse)
{
if (cp.m_name == copse.m_name)
{
m_log.InfoFormat("[TREES]: Copse: {0} is already defined - command failed", copse.m_name);
return;
}
}
m_copse.Add(copse);
m_log.InfoFormat("[TREES]: Loaded copse: {0}", copse.ToString());
}
private void HandleTreePlant(Object[] args)
{
string copsename = ((string)args[0]).Trim();
m_log.InfoFormat("[TREES]: New tree planting for copse {0}", copsename);
UUID uuid = m_scene.RegionInfo.EstateSettings.EstateOwner;
foreach (Copse copse in m_copse)
{
if (copse.m_name == copsename)
{
if (!copse.m_planted)
{
// The first tree for a copse is created here
CreateTree(uuid, copse, copse.m_seed_point);
copse.m_planted = true;
return;
}
else
{
m_log.InfoFormat("[TREES]: Copse {0} has already been planted", copsename);
}
}
}
m_log.InfoFormat("[TREES]: Copse {0} not found for planting", copsename);
}
private void HandleTreeRate(Object[] args)
{
m_update_ms = (double)args[0];
if (m_update_ms >= 1000.0)
{
if (m_active_trees)
{
activeizeTreeze(false);
activeizeTreeze(true);
}
m_log.InfoFormat("[TREES]: Update rate set to {0} mSec", m_update_ms);
}
else
{
m_log.InfoFormat("[TREES]: minimum rate is 1000.0 mSec - command failed");
}
}
private void HandleTreeReload(Object[] args)
{
if (m_active_trees)
{
CalculateTrees.Stop();
}
ReloadCopse();
if (m_active_trees)
{
CalculateTrees.Start();
}
}
private void HandleTreeRemove(Object[] args)
{
string copsename = ((string)args[0]).Trim();
Copse copseIdentity = null;
foreach (Copse cp in m_copse)
{
if (cp.m_name == copsename)
{
copseIdentity = cp;
}
}
if (copseIdentity != null)
{
foreach (UUID tree in copseIdentity.m_trees)
{
if (m_scene.Entities.ContainsKey(tree))
{
SceneObjectPart selectedTree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
// Delete tree and alert clients (not silent)
m_scene.DeleteSceneObject(selectedTree.ParentGroup, false);
}
else
{
m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
}
}
copseIdentity.m_trees = new List<UUID>();
m_copse.Remove(copseIdentity);
m_log.InfoFormat("[TREES]: Copse {0} has been removed", copsename);
}
else
{
m_log.InfoFormat("[TREES]: Copse {0} was not found - command failed", copsename);
}
}
private void HandleTreeStatistics(Object[] args)
{
m_log.InfoFormat("[TREES]: Activity State: {0}; Update Rate: {1}", m_active_trees, m_update_ms);
foreach (Copse cp in m_copse)
{
m_log.InfoFormat("[TREES]: Copse {0}; {1} trees; frozen {2}", cp.m_name, cp.m_trees.Count, cp.m_frozen);
}
}
private void InstallCommands()
{
Command treeActiveCommand =
new Command("active", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeActive, "Change activity state for the trees module");
treeActiveCommand.AddArgument("activeTF", "The required activity state", "Boolean");
Command treeFreezeCommand =
new Command("freeze", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeFreeze, "Freeze/Unfreeze activity for a defined copse");
treeFreezeCommand.AddArgument("copse", "The required copse", "String");
treeFreezeCommand.AddArgument("freezeTF", "The required freeze state", "Boolean");
Command treeLoadCommand =
new Command("load", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeLoad, "Load a copse definition from an xml file");
treeLoadCommand.AddArgument("filename", "The (xml) file you wish to load", "String");
Command treePlantCommand =
new Command("plant", CommandIntentions.COMMAND_HAZARDOUS, HandleTreePlant, "Start the planting on a copse");
treePlantCommand.AddArgument("copse", "The required copse", "String");
Command treeRateCommand =
new Command("rate", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeRate, "Reset the tree update rate (mSec)");
treeRateCommand.AddArgument("updateRate", "The required update rate (minimum 1000.0)", "Double");
Command treeReloadCommand =
new Command("reload", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeReload, "Reload copse definitions from the in-scene trees");
Command treeRemoveCommand =
new Command("remove", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeRemove, "Remove a copse definition and all its in-scene trees");
treeRemoveCommand.AddArgument("copse", "The required copse", "String");
Command treeStatisticsCommand =
new Command("statistics", CommandIntentions.COMMAND_STATISTICAL, HandleTreeStatistics, "Log statistics about the trees");
m_commander.RegisterCommand("active", treeActiveCommand);
m_commander.RegisterCommand("freeze", treeFreezeCommand);
m_commander.RegisterCommand("load", treeLoadCommand);
m_commander.RegisterCommand("plant", treePlantCommand);
m_commander.RegisterCommand("rate", treeRateCommand);
m_commander.RegisterCommand("reload", treeReloadCommand);
m_commander.RegisterCommand("remove", treeRemoveCommand);
m_commander.RegisterCommand("statistics", treeStatisticsCommand);
}
/// <summary>
/// Processes commandline input. Do not call directly.
/// </summary>
/// <param name="args">Commandline arguments</param>
private void EventManager_OnPluginConsole(string[] args)
{
if (args[0] == "tree")
{
if (args.Length == 1)
{
m_commander.ProcessConsoleCommand("help", new string[0]);
return;
}
string[] tmpArgs = new string[args.Length - 2];
int i;
for (i = 2; i < args.Length; i++)
{
tmpArgs[i - 2] = args[i];
}
m_commander.ProcessConsoleCommand(args[1], tmpArgs);
}
}
#endregion
#region IVegetationModule Members
public SceneObjectGroup AddTree(
UUID uuid, UUID groupID, Vector3 scale, Quaternion rotation, Vector3 position, Tree treeType, bool newTree)
{
PrimitiveBaseShape treeShape = new PrimitiveBaseShape();
treeShape.PathCurve = 16;
treeShape.PathEnd = 49900;
treeShape.PCode = newTree ? (byte)PCode.NewTree : (byte)PCode.Tree;
treeShape.Scale = scale;
treeShape.State = (byte)treeType;
return m_scene.AddNewPrim(uuid, groupID, position, rotation, treeShape);
}
#endregion
#region IEntityCreator Members
protected static readonly PCode[] creationCapabilities = new PCode[] { PCode.NewTree, PCode.Tree };
public PCode[] CreationCapabilities { get { return creationCapabilities; } }
public SceneObjectGroup CreateEntity(
UUID ownerID, UUID groupID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape)
{
if (Array.IndexOf(creationCapabilities, (PCode)shape.PCode) < 0)
{
m_log.DebugFormat("[VEGETATION]: PCode {0} not handled by {1}", shape.PCode, Name);
return null;
}
SceneObjectGroup sceneObject = new SceneObjectGroup(ownerID, pos, rot, shape);
SceneObjectPart rootPart = sceneObject.GetPart(sceneObject.UUID);
rootPart.AddFlag(PrimFlags.Phantom);
m_scene.AddNewSceneObject(sceneObject, true);
sceneObject.SetGroup(groupID, null);
return sceneObject;
}
#endregion
//--------------------------------------------------------------
#region Tree Utilities
static public void SerializeObject(string fileName, Object obj)
{
try
{
XmlSerializer xs = new XmlSerializer(typeof(Copse));
using (XmlTextWriter writer = new XmlTextWriter(fileName, Util.UTF8))
{
writer.Formatting = Formatting.Indented;
xs.Serialize(writer, obj);
}
}
catch (SystemException ex)
{
throw new ApplicationException("Unexpected failure in Tree serialization", ex);
}
}
static public object DeserializeObject(string fileName)
{
try
{
XmlSerializer xs = new XmlSerializer(typeof(Copse));
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
return xs.Deserialize(fs);
}
catch (SystemException ex)
{
throw new ApplicationException("Unexpected failure in Tree de-serialization", ex);
}
}
private void ReloadCopse()
{
m_copse = new List<Copse>();
EntityBase[] objs = m_scene.GetEntities();
foreach (EntityBase obj in objs)
{
if (obj is SceneObjectGroup)
{
SceneObjectGroup grp = (SceneObjectGroup)obj;
if (grp.Name.Length > 5 && (grp.Name.Substring(0, 5) == "ATPM:" || grp.Name.Substring(0, 5) == "FTPM:"))
{
// Create a new copse definition or add uuid to an existing definition
try
{
Boolean copsefound = false;
Copse copse = new Copse(grp.Name);
foreach (Copse cp in m_copse)
{
if (cp.m_name == copse.m_name)
{
copsefound = true;
cp.m_trees.Add(grp.UUID);
//m_log.DebugFormat("[TREES]: Found tree {0}", grp.UUID);
}
}
if (!copsefound)
{
m_log.InfoFormat("[TREES]: Found copse {0}", grp.Name);
m_copse.Add(copse);
copse.m_trees.Add(grp.UUID);
}
}
catch
{
m_log.InfoFormat("[TREES]: Ill formed copse definition {0} - ignoring", grp.Name);
}
}
}
}
}
#endregion
private void activeizeTreeze(bool activeYN)
{
if (activeYN)
{
CalculateTrees = new Timer(m_update_ms);
CalculateTrees.Elapsed += CalculateTrees_Elapsed;
CalculateTrees.Start();
}
else
{
CalculateTrees.Stop();
}
}
private void growTrees()
{
foreach (Copse copse in m_copse)
{
if (!copse.m_frozen)
{
foreach (UUID tree in copse.m_trees)
{
if (m_scene.Entities.ContainsKey(tree))
{
SceneObjectPart s_tree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
if (s_tree.Scale.X < copse.m_maximum_scale.X && s_tree.Scale.Y < copse.m_maximum_scale.Y && s_tree.Scale.Z < copse.m_maximum_scale.Z)
{
s_tree.Scale += copse.m_rate;
s_tree.ParentGroup.HasGroupChanged = true;
s_tree.ScheduleFullUpdate();
}
}
else
{
m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
}
}
}
}
}
private void seedTrees()
{
foreach (Copse copse in m_copse)
{
if (!copse.m_frozen)
{
foreach (UUID tree in copse.m_trees)
{
if (m_scene.Entities.ContainsKey(tree))
{
SceneObjectPart s_tree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
if (copse.m_trees.Count < copse.m_tree_quantity)
{
// Tree has grown enough to seed if it has grown by at least 25% of seeded to full grown height
if (s_tree.Scale.Z > copse.m_initial_scale.Z + (copse.m_maximum_scale.Z - copse.m_initial_scale.Z) / 4.0)
{
if (Util.RandomClass.NextDouble() > 0.75)
{
SpawnChild(copse, s_tree);
}
}
}
}
else
{
m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
}
}
}
}
}
private void killTrees()
{
foreach (Copse copse in m_copse)
{
if (!copse.m_frozen && copse.m_trees.Count >= copse.m_tree_quantity)
{
foreach (UUID tree in copse.m_trees)
{
double killLikelyhood = 0.0;
if (m_scene.Entities.ContainsKey(tree))
{
SceneObjectPart selectedTree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
double selectedTreeScale = Math.Sqrt(Math.Pow(selectedTree.Scale.X, 2) +
Math.Pow(selectedTree.Scale.Y, 2) +
Math.Pow(selectedTree.Scale.Z, 2));
foreach (UUID picktree in copse.m_trees)
{
if (picktree != tree)
{
SceneObjectPart pickedTree = ((SceneObjectGroup)m_scene.Entities[picktree]).RootPart;
double pickedTreeScale = Math.Sqrt(Math.Pow(pickedTree.Scale.X, 2) +
Math.Pow(pickedTree.Scale.Y, 2) +
Math.Pow(pickedTree.Scale.Z, 2));
double pickedTreeDistance = Vector3.Distance(pickedTree.AbsolutePosition, selectedTree.AbsolutePosition);
killLikelyhood += (selectedTreeScale / (pickedTreeScale * pickedTreeDistance)) * 0.1;
}
}
if (Util.RandomClass.NextDouble() < killLikelyhood)
{
// Delete tree and alert clients (not silent)
m_scene.DeleteSceneObject(selectedTree.ParentGroup, false);
copse.m_trees.Remove(selectedTree.ParentGroup.UUID);
break;
}
}
else
{
m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
}
}
}
}
}
private void SpawnChild(Copse copse, SceneObjectPart s_tree)
{
Vector3 position = new Vector3();
double randX = ((Util.RandomClass.NextDouble() * 2.0) - 1.0) * (s_tree.Scale.X * 3);
double randY = ((Util.RandomClass.NextDouble() * 2.0) - 1.0) * (s_tree.Scale.X * 3);
position.X = s_tree.AbsolutePosition.X + (float)randX;
position.Y = s_tree.AbsolutePosition.Y + (float)randY;
if (position.X <= (m_scene.RegionInfo.RegionSizeX - 1) && position.X >= 0 &&
position.Y <= (m_scene.RegionInfo.RegionSizeY - 1) && position.Y >= 0 &&
Util.GetDistanceTo(position, copse.m_seed_point) <= copse.m_range)
{
UUID uuid = m_scene.RegionInfo.EstateSettings.EstateOwner;
CreateTree(uuid, copse, position);
}
}
private void CreateTree(UUID uuid, Copse copse, Vector3 position)
{
position.Z = (float)m_scene.Heightmap[(int)position.X, (int)position.Y];
if (position.Z >= copse.m_treeline_low && position.Z <= copse.m_treeline_high)
{
SceneObjectGroup tree = AddTree(uuid, UUID.Zero, copse.m_initial_scale, Quaternion.Identity, position, copse.m_tree_type, false);
tree.Name = copse.ToString();
copse.m_trees.Add(tree.UUID);
tree.SendGroupFullUpdate();
}
}
private void CalculateTrees_Elapsed(object sender, ElapsedEventArgs e)
{
growTrees();
seedTrees();
killTrees();
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* [email protected]. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Text;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Runtime.Operations;
[module: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Scope = "member", Target = "IronPython.Runtime.Exceptions.TraceBackFrame..ctor(System.Object,System.Object,System.Object)", MessageId = "0#globals")]
[module: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Scope = "member", Target = "IronPython.Runtime.Exceptions.TraceBackFrame.Globals", MessageId = "Globals")]
namespace IronPython.Runtime.Exceptions {
[PythonType("traceback")]
[Serializable]
public class TraceBack {
private readonly TraceBack _next;
private readonly TraceBackFrame _frame;
private int _line;
public TraceBack(TraceBack nextTraceBack, TraceBackFrame fromFrame) {
_next = nextTraceBack;
_frame = fromFrame;
}
public TraceBack tb_next {
get {
return _next;
}
}
public TraceBackFrame tb_frame {
get {
return _frame;
}
}
public int tb_lineno {
get {
return _line;
}
}
public int tb_lasti {
get {
return 0; // not presently tracked
}
}
internal void SetLine(int lineNumber) {
_line = lineNumber;
}
/// <summary>
/// returns string containing human readable representation of traceback
/// </summary>
internal string Extract() {
var sb = new StringBuilder();
var tb = this;
while (tb != null) {
var f = tb._frame;
var lineno = tb._line;
var co = f.f_code;
var filename = co.co_filename;
var name = co.co_name;
sb.AppendFormat(" File \"{0}\", line {1}, in {2}{3}", filename, lineno, name, Environment.NewLine);
tb = tb._next;
}
return sb.ToString();
}
}
[PythonType("frame")]
[Serializable]
public class TraceBackFrame {
private readonly PythonTracebackListener _traceAdapter;
private TracebackDelegate _trace;
private object _traceObject;
internal int _lineNo;
private readonly PythonDebuggingPayload _debugProperties;
private readonly Func<IDictionary<object, object>> _scopeCallback;
private readonly PythonDictionary _globals;
private readonly object _locals;
private readonly FunctionCode _code;
private readonly CodeContext/*!*/ _context;
private readonly TraceBackFrame _back;
internal TraceBackFrame(CodeContext/*!*/ context, PythonDictionary globals, object locals, FunctionCode code) {
_globals = globals;
_locals = locals;
_code = code;
_context = context;
}
internal TraceBackFrame(CodeContext/*!*/ context, PythonDictionary globals, object locals, FunctionCode code, TraceBackFrame back) {
_globals = globals;
_locals = locals;
_code = code;
_context = context;
_back = back;
}
internal TraceBackFrame(PythonTracebackListener traceAdapter, FunctionCode code, TraceBackFrame back, PythonDebuggingPayload debugProperties, Func<IDictionary<object, object>> scopeCallback) {
_traceAdapter = traceAdapter;
_code = code;
_back = back;
_debugProperties = debugProperties;
_scopeCallback = scopeCallback;
}
[SpecialName, PropertyMethod]
public object Getf_trace() {
if (_traceAdapter != null) {
return _traceObject;
} else {
return null;
}
}
[SpecialName, PropertyMethod]
public void Setf_trace(object value) {
_traceObject = value;
_trace = (TracebackDelegate)Converter.ConvertToDelegate(value, typeof(TracebackDelegate));
}
[SpecialName, PropertyMethod]
public void Deletef_trace() {
Setf_trace(null);
}
internal CodeContext Context {
get {
return _context;
}
}
internal TracebackDelegate TraceDelegate {
get {
if (_traceAdapter != null) {
return _trace;
} else {
return null;
}
}
}
public PythonDictionary f_globals {
get {
object context;
if (_scopeCallback != null &&
_scopeCallback().TryGetValue(Compiler.Ast.PythonAst.GlobalContextName, out context) && context != null) {
return ((CodeContext)context).GlobalDict;
} else {
return _globals;
}
}
}
public object f_locals {
get {
if (_traceAdapter != null && _scopeCallback != null) {
if (_code.IsModule) {
// don't use the scope callback for locals in a module, use our globals dictionary instead
return f_globals;
}
return new PythonDictionary(new DebuggerDictionaryStorage(_scopeCallback()));
} else {
return _locals;
}
}
}
public FunctionCode f_code {
get {
return _code;
}
}
public object f_builtins {
get {
return PythonContext.GetContext(_context).BuiltinModuleDict;
}
}
public TraceBackFrame f_back {
get {
return _back;
}
}
public object f_exc_traceback {
get {
return null;
}
}
public object f_exc_type {
get {
return null;
}
}
public bool f_restricted {
get {
return false;
}
}
public object f_lineno {
get {
if (_traceAdapter != null) {
return _lineNo;
} else {
return 1;
}
}
set {
if (!(value is int)) {
throw PythonOps.ValueError("lineno must be an integer");
}
int newLineNum = (int)value;
if (_traceAdapter != null) {
SetLineNumber(newLineNum);
} else {
throw PythonOps.ValueError("f_lineno can only be set by a trace function");
}
}
}
private void SetLineNumber(int newLineNum) {
var pyThread = PythonOps.GetFunctionStackNoCreate();
if (!IsTopMostFrame(pyThread)) {
if (!TracingThisFrame(pyThread)) {
throw PythonOps.ValueError("f_lineno can only be set by a trace function");
} else {
return;
}
}
FunctionCode funcCode = _debugProperties.Code;
Dictionary<int, Dictionary<int, bool>> loopAndFinallyLocations = _debugProperties.LoopAndFinallyLocations;
Dictionary<int, bool> handlerLocations = _debugProperties.HandlerLocations;
Dictionary<int, bool> currentLoopIds = null;
bool inForLoopOrFinally = loopAndFinallyLocations != null && loopAndFinallyLocations.TryGetValue(_lineNo, out currentLoopIds);
int originalNewLine = newLineNum;
if (newLineNum < funcCode.Span.Start.Line) {
throw PythonOps.ValueError("line {0} comes before the current code block", newLineNum);
} else if (newLineNum > funcCode.Span.End.Line) {
throw PythonOps.ValueError("line {0} comes after the current code block", newLineNum);
}
while (newLineNum <= funcCode.Span.End.Line) {
var span = new SourceSpan(new SourceLocation(0, newLineNum, 1), new SourceLocation(0, newLineNum, Int32.MaxValue));
// Check if we're jumping onto a handler
bool handlerIsFinally;
if (handlerLocations != null && handlerLocations.TryGetValue(newLineNum, out handlerIsFinally)) {
throw PythonOps.ValueError("can't jump to 'except' line");
}
// Check if we're jumping into a for-loop
Dictionary<int, bool> jumpIntoLoopIds;
if (loopAndFinallyLocations != null && loopAndFinallyLocations.TryGetValue(newLineNum, out jumpIntoLoopIds)) {
// If we're not in any loop already - then we can't jump into a loop
if (!inForLoopOrFinally) {
throw BadForOrFinallyJump(newLineNum, jumpIntoLoopIds);
}
// If we're in loops - we can only jump if we're not entering a new loop
foreach (int jumpIntoLoopId in jumpIntoLoopIds.Keys) {
if (!currentLoopIds.ContainsKey(jumpIntoLoopId)) {
throw BadForOrFinallyJump(newLineNum, currentLoopIds);
}
}
} else if (currentLoopIds != null) {
foreach (bool isFinally in currentLoopIds.Values) {
if (isFinally) {
throw PythonOps.ValueError("can't jump out of 'finally block'");
}
}
}
if (_traceAdapter.PythonContext.TracePipeline.TrySetNextStatement((string)((FunctionCode)_code).co_filename, span)) {
_lineNo = newLineNum;
return;
}
++newLineNum;
}
throw PythonOps.ValueError("line {0} is invalid jump location ({1} - {2} are valid)", originalNewLine, funcCode.Span.Start.Line, funcCode.Span.End.Line);
}
private bool TracingThisFrame(List<FunctionStack> pyThread) {
return pyThread != null &&
pyThread.FindIndex(x => x.Frame == this) != -1;
}
private bool IsTopMostFrame(List<FunctionStack> pyThread) {
return pyThread != null && pyThread.Count != 0 && Type.ReferenceEquals(this, pyThread[pyThread.Count - 1].Frame);
}
private static Exception BadForOrFinallyJump(int newLineNum, Dictionary<int, bool> jumpIntoLoopIds) {
foreach (bool isFinally in jumpIntoLoopIds.Values) {
if (isFinally) {
return PythonOps.ValueError("can't jump into 'finally block'", newLineNum);
}
}
return PythonOps.ValueError("can't jump into 'for loop'", newLineNum);
}
}
public delegate TracebackDelegate TracebackDelegate(TraceBackFrame frame, string result, object payload);
}
| |
using System;
using NBitcoin.BouncyCastle.Crypto;
using NBitcoin.BouncyCastle.Crypto.Parameters;
using NBitcoin.BouncyCastle.Security;
namespace NBitcoin.BouncyCastle.Crypto.Paddings
{
/**
* A wrapper class that allows block ciphers to be used to process data in
* a piecemeal fashion with padding. The PaddedBufferedBlockCipher
* outputs a block only when the buffer is full and more data is being added,
* or on a doFinal (unless the current block in the buffer is a pad block).
* The default padding mechanism used is the one outlined in Pkcs5/Pkcs7.
*/
public class PaddedBufferedBlockCipher
: BufferedBlockCipher
{
private readonly IBlockCipherPadding padding;
/**
* Create a buffered block cipher with the desired padding.
*
* @param cipher the underlying block cipher this buffering object wraps.
* @param padding the padding type.
*/
public PaddedBufferedBlockCipher(
IBlockCipher cipher,
IBlockCipherPadding padding)
{
this.cipher = cipher;
this.padding = padding;
buf = new byte[cipher.GetBlockSize()];
bufOff = 0;
}
/**
* Create a buffered block cipher Pkcs7 padding
*
* @param cipher the underlying block cipher this buffering object wraps.
*/
public PaddedBufferedBlockCipher(
IBlockCipher cipher)
: this(cipher, new Pkcs7Padding()) { }
/**
* initialise the cipher.
*
* @param forEncryption if true the cipher is initialised for
* encryption, if false for decryption.
* @param param the key and other data required by the cipher.
* @exception ArgumentException if the parameters argument is
* inappropriate.
*/
public override void Init(
bool forEncryption,
ICipherParameters parameters)
{
this.forEncryption = forEncryption;
SecureRandom initRandom = null;
if (parameters is ParametersWithRandom)
{
ParametersWithRandom p = (ParametersWithRandom)parameters;
initRandom = p.Random;
parameters = p.Parameters;
}
Reset();
padding.Init(initRandom);
cipher.Init(forEncryption, parameters);
}
/**
* return the minimum size of the output buffer required for an update
* plus a doFinal with an input of len bytes.
*
* @param len the length of the input.
* @return the space required to accommodate a call to update and doFinal
* with len bytes of input.
*/
public override int GetOutputSize(
int length)
{
int total = length + bufOff;
int leftOver = total % buf.Length;
if (leftOver == 0)
{
if (forEncryption)
{
return total + buf.Length;
}
return total;
}
return total - leftOver + buf.Length;
}
/**
* return the size of the output buffer required for an update
* an input of len bytes.
*
* @param len the length of the input.
* @return the space required to accommodate a call to update
* with len bytes of input.
*/
public override int GetUpdateOutputSize(
int length)
{
int total = length + bufOff;
int leftOver = total % buf.Length;
if (leftOver == 0)
{
return total - buf.Length;
}
return total - leftOver;
}
/**
* process a single byte, producing an output block if neccessary.
*
* @param in the input byte.
* @param out the space for any output that might be produced.
* @param outOff the offset from which the output will be copied.
* @return the number of output bytes copied to out.
* @exception DataLengthException if there isn't enough space in out.
* @exception InvalidOperationException if the cipher isn't initialised.
*/
public override int ProcessByte(
byte input,
byte[] output,
int outOff)
{
int resultLen = 0;
if (bufOff == buf.Length)
{
resultLen = cipher.ProcessBlock(buf, 0, output, outOff);
bufOff = 0;
}
buf[bufOff++] = input;
return resultLen;
}
/**
* process an array of bytes, producing output if necessary.
*
* @param in the input byte array.
* @param inOff the offset at which the input data starts.
* @param len the number of bytes to be copied out of the input array.
* @param out the space for any output that might be produced.
* @param outOff the offset from which the output will be copied.
* @return the number of output bytes copied to out.
* @exception DataLengthException if there isn't enough space in out.
* @exception InvalidOperationException if the cipher isn't initialised.
*/
public override int ProcessBytes(
byte[] input,
int inOff,
int length,
byte[] output,
int outOff)
{
if (length < 0)
{
throw new ArgumentException("Can't have a negative input length!");
}
int blockSize = GetBlockSize();
int outLength = GetUpdateOutputSize(length);
if (outLength > 0)
{
if ((outOff + outLength) > output.Length)
{
throw new DataLengthException("output buffer too short");
}
}
int resultLen = 0;
int gapLen = buf.Length - bufOff;
if (length > gapLen)
{
Array.Copy(input, inOff, buf, bufOff, gapLen);
resultLen += cipher.ProcessBlock(buf, 0, output, outOff);
bufOff = 0;
length -= gapLen;
inOff += gapLen;
while (length > buf.Length)
{
resultLen += cipher.ProcessBlock(input, inOff, output, outOff + resultLen);
length -= blockSize;
inOff += blockSize;
}
}
Array.Copy(input, inOff, buf, bufOff, length);
bufOff += length;
return resultLen;
}
/**
* Process the last block in the buffer. If the buffer is currently
* full and padding needs to be added a call to doFinal will produce
* 2 * GetBlockSize() bytes.
*
* @param out the array the block currently being held is copied into.
* @param outOff the offset at which the copying starts.
* @return the number of output bytes copied to out.
* @exception DataLengthException if there is insufficient space in out for
* the output or we are decrypting and the input is not block size aligned.
* @exception InvalidOperationException if the underlying cipher is not
* initialised.
* @exception InvalidCipherTextException if padding is expected and not found.
*/
public override int DoFinal(
byte[] output,
int outOff)
{
int blockSize = cipher.GetBlockSize();
int resultLen = 0;
if (forEncryption)
{
if (bufOff == blockSize)
{
if ((outOff + 2 * blockSize) > output.Length)
{
Reset();
throw new DataLengthException("output buffer too short");
}
resultLen = cipher.ProcessBlock(buf, 0, output, outOff);
bufOff = 0;
}
padding.AddPadding(buf, bufOff);
resultLen += cipher.ProcessBlock(buf, 0, output, outOff + resultLen);
Reset();
}
else
{
if (bufOff == blockSize)
{
resultLen = cipher.ProcessBlock(buf, 0, buf, 0);
bufOff = 0;
}
else
{
Reset();
throw new DataLengthException("last block incomplete in decryption");
}
try
{
resultLen -= padding.PadCount(buf);
Array.Copy(buf, 0, output, outOff, resultLen);
}
finally
{
Reset();
}
}
return resultLen;
}
}
}
| |
/*
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.Diagnostics;
using System.IO;
using System.IO.IsolatedStorage;
using System.Runtime.Serialization;
using System.Security;
using System.Text;
using System.Windows;
using System.Windows.Resources;
namespace WPCordovaClassLib.Cordova.Commands
{
/// <summary>
/// Provides access to isolated storage
/// </summary>
public class File : BaseCommand
{
// Error codes
public const int NOT_FOUND_ERR = 1;
public const int SECURITY_ERR = 2;
public const int ABORT_ERR = 3;
public const int NOT_READABLE_ERR = 4;
public const int ENCODING_ERR = 5;
public const int NO_MODIFICATION_ALLOWED_ERR = 6;
public const int INVALID_STATE_ERR = 7;
public const int SYNTAX_ERR = 8;
public const int INVALID_MODIFICATION_ERR = 9;
public const int QUOTA_EXCEEDED_ERR = 10;
public const int TYPE_MISMATCH_ERR = 11;
public const int PATH_EXISTS_ERR = 12;
// File system options
public const int TEMPORARY = 0;
public const int PERSISTENT = 1;
public const int RESOURCE = 2;
public const int APPLICATION = 3;
/// <summary>
/// Temporary directory name
/// </summary>
private readonly string TMP_DIRECTORY_NAME = "tmp";
/// <summary>
/// Represents error code for callback
/// </summary>
[DataContract]
public class ErrorCode
{
/// <summary>
/// Error code
/// </summary>
[DataMember(IsRequired = true, Name = "code")]
public int Code { get; set; }
/// <summary>
/// Creates ErrorCode object
/// </summary>
public ErrorCode(int code)
{
this.Code = code;
}
}
/// <summary>
/// Represents File action options.
/// </summary>
[DataContract]
public class FileOptions
{
/// <summary>
/// File path
/// </summary>
///
private string _fileName;
[DataMember(Name = "fileName")]
public string FilePath
{
get
{
return this._fileName;
}
set
{
int index = value.IndexOfAny(new char[] { '#', '?' });
this._fileName = index > -1 ? value.Substring(0, index) : value;
}
}
/// <summary>
/// Full entryPath
/// </summary>
[DataMember(Name = "fullPath")]
public string FullPath { get; set; }
/// <summary>
/// Directory name
/// </summary>
[DataMember(Name = "dirName")]
public string DirectoryName { get; set; }
/// <summary>
/// Path to create file/directory
/// </summary>
[DataMember(Name = "path")]
public string Path { get; set; }
/// <summary>
/// The encoding to use to encode the file's content. Default is UTF8.
/// </summary>
[DataMember(Name = "encoding")]
public string Encoding { get; set; }
/// <summary>
/// Uri to get file
/// </summary>
///
private string _uri;
[DataMember(Name = "uri")]
public string Uri
{
get
{
return this._uri;
}
set
{
int index = value.IndexOfAny(new char[] { '#', '?' });
this._uri = index > -1 ? value.Substring(0, index) : value;
}
}
/// <summary>
/// Size to truncate file
/// </summary>
[DataMember(Name = "size")]
public long Size { get; set; }
/// <summary>
/// Data to write in file
/// </summary>
[DataMember(Name = "data")]
public string Data { get; set; }
/// <summary>
/// Position the writing starts with
/// </summary>
[DataMember(Name = "position")]
public int Position { get; set; }
/// <summary>
/// Type of file system requested
/// </summary>
[DataMember(Name = "type")]
public int FileSystemType { get; set; }
/// <summary>
/// New file/directory name
/// </summary>
[DataMember(Name = "newName")]
public string NewName { get; set; }
/// <summary>
/// Destination directory to copy/move file/directory
/// </summary>
[DataMember(Name = "parent")]
public string Parent { get; set; }
/// <summary>
/// Options for getFile/getDirectory methods
/// </summary>
[DataMember(Name = "options")]
public CreatingOptions CreatingOpt { get; set; }
/// <summary>
/// Creates options object with default parameters
/// </summary>
public FileOptions()
{
this.SetDefaultValues(new StreamingContext());
}
/// <summary>
/// Initializes default values for class fields.
/// Implemented in separate method because default constructor is not invoked during deserialization.
/// </summary>
/// <param name="context"></param>
[OnDeserializing()]
public void SetDefaultValues(StreamingContext context)
{
this.Encoding = "UTF-8";
this.FilePath = "";
this.FileSystemType = -1;
}
}
/// <summary>
/// Stores image info
/// </summary>
[DataContract]
public class FileMetadata
{
[DataMember(Name = "fileName")]
public string FileName { get; set; }
[DataMember(Name = "fullPath")]
public string FullPath { get; set; }
[DataMember(Name = "type")]
public string Type { get; set; }
[DataMember(Name = "lastModifiedDate")]
public string LastModifiedDate { get; set; }
[DataMember(Name = "size")]
public long Size { get; set; }
public FileMetadata(string filePath)
{
if (string.IsNullOrEmpty(filePath))
{
throw new FileNotFoundException("File doesn't exist");
}
this.FullPath = filePath;
this.Size = 0;
this.FileName = string.Empty;
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
bool IsFile = isoFile.FileExists(filePath);
bool IsDirectory = isoFile.DirectoryExists(filePath);
if (!IsDirectory)
{
if (!IsFile) // special case, if isoFile cannot find it, it might still be part of the app-package
{
// attempt to get it from the resources
Uri fileUri = new Uri(filePath, UriKind.Relative);
StreamResourceInfo streamInfo = Application.GetResourceStream(fileUri);
if (streamInfo != null)
{
this.Size = streamInfo.Stream.Length;
this.FileName = filePath.Substring(filePath.LastIndexOf("/") + 1);
}
else
{
throw new FileNotFoundException("File doesn't exist");
}
}
else
{
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, FileAccess.Read, isoFile))
{
this.Size = stream.Length;
}
this.FileName = System.IO.Path.GetFileName(filePath);
this.LastModifiedDate = isoFile.GetLastWriteTime(filePath).DateTime.ToString();
}
}
this.Type = MimeTypeMapper.GetMimeType(this.FileName);
}
}
}
/// <summary>
/// Represents file or directory modification metadata
/// </summary>
[DataContract]
public class ModificationMetadata
{
/// <summary>
/// Modification time
/// </summary>
[DataMember]
public string modificationTime { get; set; }
}
/// <summary>
/// Represents file or directory entry
/// </summary>
[DataContract]
public class FileEntry
{
/// <summary>
/// File type
/// </summary>
[DataMember(Name = "isFile")]
public bool IsFile { get; set; }
/// <summary>
/// Directory type
/// </summary>
[DataMember(Name = "isDirectory")]
public bool IsDirectory { get; set; }
/// <summary>
/// File/directory name
/// </summary>
[DataMember(Name = "name")]
public string Name { get; set; }
/// <summary>
/// Full path to file/directory
/// </summary>
[DataMember(Name = "fullPath")]
public string FullPath { get; set; }
/// <summary>
/// URI encoded fullpath
/// </summary>
[DataMember(Name = "nativeURL")]
public string NativeURL
{
set { }
get
{
string escaped = Uri.EscapeUriString(this.FullPath);
escaped = escaped.Replace("//", "/");
if (escaped.StartsWith("/"))
{
escaped = escaped.Insert(0, "/");
}
return escaped;
}
}
public bool IsResource { get; set; }
public static FileEntry GetEntry(string filePath, bool bIsRes=false)
{
FileEntry entry = null;
try
{
entry = new FileEntry(filePath, bIsRes);
}
catch (Exception ex)
{
Debug.WriteLine("Exception in GetEntry for filePath :: " + filePath + " " + ex.Message);
}
return entry;
}
/// <summary>
/// Creates object and sets necessary properties
/// </summary>
/// <param name="filePath"></param>
public FileEntry(string filePath, bool bIsRes = false)
{
if (string.IsNullOrEmpty(filePath))
{
throw new ArgumentException();
}
if(filePath.Contains(" "))
{
Debug.WriteLine("FilePath with spaces :: " + filePath);
}
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
IsResource = bIsRes;
IsFile = isoFile.FileExists(filePath);
IsDirectory = isoFile.DirectoryExists(filePath);
if (IsFile)
{
this.Name = Path.GetFileName(filePath);
}
else if (IsDirectory)
{
this.Name = this.GetDirectoryName(filePath);
if (string.IsNullOrEmpty(Name))
{
this.Name = "/";
}
}
else
{
if (IsResource)
{
this.Name = Path.GetFileName(filePath);
}
else
{
throw new FileNotFoundException();
}
}
try
{
this.FullPath = filePath.Replace('\\', '/'); // new Uri(filePath).LocalPath;
}
catch (Exception)
{
this.FullPath = filePath;
}
}
}
/// <summary>
/// Extracts directory name from path string
/// Path should refer to a directory, for example \foo\ or /foo.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
private string GetDirectoryName(string path)
{
if (String.IsNullOrEmpty(path))
{
return path;
}
string[] split = path.Split(new char[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
if (split.Length < 1)
{
return null;
}
else
{
return split[split.Length - 1];
}
}
}
/// <summary>
/// Represents info about requested file system
/// </summary>
[DataContract]
public class FileSystemInfo
{
/// <summary>
/// file system type
/// </summary>
[DataMember(Name = "name", IsRequired = true)]
public string Name { get; set; }
/// <summary>
/// Root directory entry
/// </summary>
[DataMember(Name = "root", EmitDefaultValue = false)]
public FileEntry Root { get; set; }
/// <summary>
/// Creates class instance
/// </summary>
/// <param name="name"></param>
/// <param name="rootEntry"> Root directory</param>
public FileSystemInfo(string name, FileEntry rootEntry = null)
{
Name = name;
Root = rootEntry;
}
}
[DataContract]
public class CreatingOptions
{
/// <summary>
/// Create file/directory if is doesn't exist
/// </summary>
[DataMember(Name = "create")]
public bool Create { get; set; }
/// <summary>
/// Generate an exception if create=true and file/directory already exists
/// </summary>
[DataMember(Name = "exclusive")]
public bool Exclusive { get; set; }
}
// returns null value if it fails.
private string[] getOptionStrings(string options)
{
string[] optStings = null;
try
{
optStings = JSON.JsonHelper.Deserialize<string[]>(options);
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), CurrentCommandCallbackId);
}
return optStings;
}
/// <summary>
/// Gets amount of free space available for Isolated Storage
/// </summary>
/// <param name="options">No options is needed for this method</param>
public void getFreeDiskSpace(string options)
{
string callbackId = getOptionStrings(options)[0];
try
{
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, isoFile.AvailableFreeSpace), callbackId);
}
}
catch (IsolatedStorageException)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId);
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId);
}
}
}
/// <summary>
/// Check if file exists
/// </summary>
/// <param name="options">File path</param>
public void testFileExists(string options)
{
IsDirectoryOrFileExist(options, false);
}
/// <summary>
/// Check if directory exists
/// </summary>
/// <param name="options">directory name</param>
public void testDirectoryExists(string options)
{
IsDirectoryOrFileExist(options, true);
}
/// <summary>
/// Check if file or directory exist
/// </summary>
/// <param name="options">File path/Directory name</param>
/// <param name="isDirectory">Flag to recognize what we should check</param>
public void IsDirectoryOrFileExist(string options, bool isDirectory)
{
string[] args = getOptionStrings(options);
string callbackId = args[1];
FileOptions fileOptions = JSON.JsonHelper.Deserialize<FileOptions>(args[0]);
string filePath = args[0];
if (fileOptions == null)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), callbackId);
}
try
{
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
bool isExist;
if (isDirectory)
{
isExist = isoFile.DirectoryExists(fileOptions.DirectoryName);
}
else
{
isExist = isoFile.FileExists(fileOptions.FilePath);
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, isExist), callbackId);
}
}
catch (IsolatedStorageException) // default handler throws INVALID_MODIFICATION_ERR
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId);
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId);
}
}
}
public void readAsDataURL(string options)
{
string[] optStrings = getOptionStrings(options);
string filePath = optStrings[0];
int startPos = int.Parse(optStrings[1]);
int endPos = int.Parse(optStrings[2]);
string callbackId = optStrings[3];
if (filePath != null)
{
try
{
string base64URL = null;
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isoFile.FileExists(filePath))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId);
return;
}
string mimeType = MimeTypeMapper.GetMimeType(filePath);
using (IsolatedStorageFileStream stream = isoFile.OpenFile(filePath, FileMode.Open, FileAccess.Read))
{
string base64String = GetFileContent(stream);
base64URL = "data:" + mimeType + ";base64," + base64String;
}
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, base64URL), callbackId);
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId);
}
}
}
}
private byte[] readFileBytes(string filePath,int startPos,int endPos, IsolatedStorageFile isoFile)
{
byte[] buffer;
using (IsolatedStorageFileStream reader = isoFile.OpenFile(filePath, FileMode.Open, FileAccess.Read))
{
if (startPos < 0)
{
startPos = Math.Max((int)reader.Length + startPos, 0);
}
else if (startPos > 0)
{
startPos = Math.Min((int)reader.Length, startPos);
}
if (endPos > 0)
{
endPos = Math.Min((int)reader.Length, endPos);
}
else if (endPos < 0)
{
endPos = Math.Max(endPos + (int)reader.Length, 0);
}
buffer = new byte[endPos - startPos];
reader.Seek(startPos, SeekOrigin.Begin);
reader.Read(buffer, 0, buffer.Length);
}
return buffer;
}
public void readAsArrayBuffer(string options)
{
string[] optStrings = getOptionStrings(options);
string filePath = optStrings[0];
int startPos = int.Parse(optStrings[1]);
int endPos = int.Parse(optStrings[2]);
string callbackId = optStrings[3];
try
{
byte[] buffer;
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isoFile.FileExists(filePath))
{
readResourceAsText(options);
return;
}
buffer = readFileBytes(filePath, startPos, endPos, isoFile);
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, buffer), callbackId);
}
catch (Exception ex)
{
if (!this.HandleException(ex, callbackId))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId);
}
}
}
public void readAsBinaryString(string options)
{
string[] optStrings = getOptionStrings(options);
string filePath = optStrings[0];
int startPos = int.Parse(optStrings[1]);
int endPos = int.Parse(optStrings[2]);
string callbackId = optStrings[3];
try
{
string result;
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isoFile.FileExists(filePath))
{
readResourceAsText(options);
return;
}
byte[] buffer = readFileBytes(filePath, startPos, endPos, isoFile);
result = System.Text.Encoding.GetEncoding("iso-8859-1").GetString(buffer, 0, buffer.Length);
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, result), callbackId);
}
catch (Exception ex)
{
if (!this.HandleException(ex, callbackId))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId);
}
}
}
public void readAsText(string options)
{
string[] optStrings = getOptionStrings(options);
string filePath = optStrings[0];
string encStr = optStrings[1];
int startPos = int.Parse(optStrings[2]);
int endPos = int.Parse(optStrings[3]);
string callbackId = optStrings[4];
try
{
string text = "";
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isoFile.FileExists(filePath))
{
readResourceAsText(options);
return;
}
Encoding encoding = Encoding.GetEncoding(encStr);
byte[] buffer = this.readFileBytes(filePath, startPos, endPos, isoFile);
text = encoding.GetString(buffer, 0, buffer.Length);
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, text), callbackId);
}
catch (Exception ex)
{
if (!this.HandleException(ex, callbackId))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId);
}
}
}
/// <summary>
/// Reads application resource as a text
/// </summary>
/// <param name="options">Path to a resource</param>
public void readResourceAsText(string options)
{
string[] optStrings = getOptionStrings(options);
string pathToResource = optStrings[0];
string encStr = optStrings[1];
int start = int.Parse(optStrings[2]);
int endMarker = int.Parse(optStrings[3]);
string callbackId = optStrings[4];
try
{
if (pathToResource.StartsWith("/"))
{
pathToResource = pathToResource.Remove(0, 1);
}
var resource = Application.GetResourceStream(new Uri(pathToResource, UriKind.Relative));
if (resource == null)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId);
return;
}
string text;
StreamReader streamReader = new StreamReader(resource.Stream);
text = streamReader.ReadToEnd();
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, text), callbackId);
}
catch (Exception ex)
{
if (!this.HandleException(ex, callbackId))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId);
}
}
}
public void truncate(string options)
{
string[] optStrings = getOptionStrings(options);
string filePath = optStrings[0];
int size = int.Parse(optStrings[1]);
string callbackId = optStrings[2];
try
{
long streamLength = 0;
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isoFile.FileExists(filePath))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId);
return;
}
using (FileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, FileAccess.ReadWrite, isoFile))
{
if (0 <= size && size <= stream.Length)
{
stream.SetLength(size);
}
streamLength = stream.Length;
}
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, streamLength), callbackId);
}
catch (Exception ex)
{
if (!this.HandleException(ex, callbackId))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId);
}
}
}
//write:[filePath,data,position,isBinary,callbackId]
public void write(string options)
{
string[] optStrings = getOptionStrings(options);
string filePath = optStrings[0];
string data = optStrings[1];
int position = int.Parse(optStrings[2]);
bool isBinary = bool.Parse(optStrings[3]);
string callbackId = optStrings[4];
try
{
if (string.IsNullOrEmpty(data))
{
Debug.WriteLine("Expected some data to be send in the write command to {0}", filePath);
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), callbackId);
return;
}
byte[] dataToWrite = isBinary ? JSON.JsonHelper.Deserialize<byte[]>(data) :
System.Text.Encoding.UTF8.GetBytes(data);
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
// create the file if not exists
if (!isoFile.FileExists(filePath))
{
var file = isoFile.CreateFile(filePath);
file.Close();
}
using (FileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, FileAccess.ReadWrite, isoFile))
{
if (0 <= position && position <= stream.Length)
{
stream.SetLength(position);
}
using (BinaryWriter writer = new BinaryWriter(stream))
{
writer.Seek(0, SeekOrigin.End);
writer.Write(dataToWrite);
}
}
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, dataToWrite.Length), callbackId);
}
catch (Exception ex)
{
if (!this.HandleException(ex, callbackId))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId);
}
}
}
/// <summary>
/// Look up metadata about this entry.
/// </summary>
/// <param name="options">filePath to entry</param>
public void getMetadata(string options)
{
string[] optStings = getOptionStrings(options);
string filePath = optStings[0];
string callbackId = optStings[1];
if (filePath != null)
{
try
{
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isoFile.FileExists(filePath))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK,
new ModificationMetadata() { modificationTime = isoFile.GetLastWriteTime(filePath).DateTime.ToString() }), callbackId);
}
else if (isoFile.DirectoryExists(filePath))
{
string modTime = isoFile.GetLastWriteTime(filePath).DateTime.ToString();
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new ModificationMetadata() { modificationTime = modTime }), callbackId);
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId);
}
}
}
catch (IsolatedStorageException)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId);
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId);
}
}
}
}
/// <summary>
/// Returns a File that represents the current state of the file that this FileEntry represents.
/// </summary>
/// <param name="filePath">filePath to entry</param>
/// <returns></returns>
public void getFileMetadata(string options)
{
string[] optStings = getOptionStrings(options);
string filePath = optStings[0];
string callbackId = optStings[1];
if (!string.IsNullOrEmpty(filePath))
{
try
{
FileMetadata metaData = new FileMetadata(filePath);
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, metaData), callbackId);
}
catch (IsolatedStorageException)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId);
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId);
}
}
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId);
}
}
/// <summary>
/// Look up the parent DirectoryEntry containing this Entry.
/// If this Entry is the root of IsolatedStorage, its parent is itself.
/// </summary>
/// <param name="options"></param>
public void getParent(string options)
{
string[] optStings = getOptionStrings(options);
string filePath = optStings[0];
string callbackId = optStings[1];
if (filePath != null)
{
try
{
if (string.IsNullOrEmpty(filePath))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION),callbackId);
return;
}
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
FileEntry entry;
if (isoFile.FileExists(filePath) || isoFile.DirectoryExists(filePath))
{
string path = this.GetParentDirectory(filePath);
entry = FileEntry.GetEntry(path);
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry),callbackId);
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR),callbackId);
}
}
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR),callbackId);
}
}
}
}
public void remove(string options)
{
string[] args = getOptionStrings(options);
string filePath = args[0];
string callbackId = args[1];
if (filePath != null)
{
try
{
if (filePath == "/" || filePath == "" || filePath == @"\")
{
throw new Exception("Cannot delete root file system") ;
}
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isoFile.FileExists(filePath))
{
isoFile.DeleteFile(filePath);
}
else
{
if (isoFile.DirectoryExists(filePath))
{
isoFile.DeleteDirectory(filePath);
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR),callbackId);
return;
}
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK),callbackId);
}
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR),callbackId);
}
}
}
}
public void removeRecursively(string options)
{
string[] args = getOptionStrings(options);
string filePath = args[0];
string callbackId = args[1];
if (filePath != null)
{
if (string.IsNullOrEmpty(filePath))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION),callbackId);
}
else
{
if (removeDirRecursively(filePath, callbackId))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId);
}
}
}
}
public void readEntries(string options)
{
string[] args = getOptionStrings(options);
string filePath = args[0];
string callbackId = args[1];
if (filePath != null)
{
try
{
if (string.IsNullOrEmpty(filePath))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION),callbackId);
return;
}
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isoFile.DirectoryExists(filePath))
{
string path = File.AddSlashToDirectory(filePath);
List<FileEntry> entries = new List<FileEntry>();
string[] files = isoFile.GetFileNames(path + "*");
string[] dirs = isoFile.GetDirectoryNames(path + "*");
foreach (string file in files)
{
entries.Add(FileEntry.GetEntry(path + file));
}
foreach (string dir in dirs)
{
entries.Add(FileEntry.GetEntry(path + dir + "/"));
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entries),callbackId);
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR),callbackId);
}
}
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR),callbackId);
}
}
}
}
public void requestFileSystem(string options)
{
// TODO: try/catch
string[] optVals = getOptionStrings(options);
//FileOptions fileOptions = new FileOptions();
int fileSystemType = int.Parse(optVals[0]);
double size = double.Parse(optVals[1]);
string callbackId = optVals[2];
IsolatedStorageFile.GetUserStoreForApplication();
if (size > (10 * 1024 * 1024)) // 10 MB, compier will clean this up!
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, QUOTA_EXCEEDED_ERR), callbackId);
return;
}
try
{
if (size != 0)
{
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
long availableSize = isoFile.AvailableFreeSpace;
if (size > availableSize)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, QUOTA_EXCEEDED_ERR), callbackId);
return;
}
}
}
if (fileSystemType == PERSISTENT)
{
// TODO: this should be in it's own folder to prevent overwriting of the app assets, which are also in ISO
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("persistent", FileEntry.GetEntry("/"))), callbackId);
}
else if (fileSystemType == TEMPORARY)
{
using (IsolatedStorageFile isoStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isoStorage.FileExists(TMP_DIRECTORY_NAME))
{
isoStorage.CreateDirectory(TMP_DIRECTORY_NAME);
}
}
string tmpFolder = "/" + TMP_DIRECTORY_NAME + "/";
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("temporary", FileEntry.GetEntry(tmpFolder))), callbackId);
}
else if (fileSystemType == RESOURCE)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("resource")), callbackId);
}
else if (fileSystemType == APPLICATION)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("application")), callbackId);
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId);
}
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId);
}
}
}
public void resolveLocalFileSystemURI(string options)
{
string[] optVals = getOptionStrings(options);
string uri = optVals[0].Split('?')[0];
string callbackId = optVals[1];
if (uri != null)
{
// a single '/' is valid, however, '/someDir' is not, but '/tmp//somedir' and '///someDir' are valid
if (uri.StartsWith("/") && uri.IndexOf("//") < 0 && uri != "/")
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR), callbackId);
return;
}
try
{
// fix encoded spaces
string path = Uri.UnescapeDataString(uri);
FileEntry uriEntry = FileEntry.GetEntry(path);
if (uriEntry != null)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, uriEntry), callbackId);
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId);
}
}
catch (Exception ex)
{
if (!this.HandleException(ex, callbackId))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId);
}
}
}
}
public void copyTo(string options)
{
TransferTo(options, false);
}
public void moveTo(string options)
{
TransferTo(options, true);
}
public void getFile(string options)
{
GetFileOrDirectory(options, false);
}
public void getDirectory(string options)
{
GetFileOrDirectory(options, true);
}
#region internal functionality
/// <summary>
/// Retrieves the parent directory name of the specified path,
/// </summary>
/// <param name="path">Path</param>
/// <returns>Parent directory name</returns>
private string GetParentDirectory(string path)
{
if (String.IsNullOrEmpty(path) || path == "/")
{
return "/";
}
if (path.EndsWith(@"/") || path.EndsWith(@"\"))
{
return this.GetParentDirectory(Path.GetDirectoryName(path));
}
string result = Path.GetDirectoryName(path);
if (result == null)
{
result = "/";
}
return result;
}
private bool removeDirRecursively(string fullPath,string callbackId)
{
try
{
if (fullPath == "/")
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR),callbackId);
return false;
}
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isoFile.DirectoryExists(fullPath))
{
string tempPath = File.AddSlashToDirectory(fullPath);
string[] files = isoFile.GetFileNames(tempPath + "*");
if (files.Length > 0)
{
foreach (string file in files)
{
isoFile.DeleteFile(tempPath + file);
}
}
string[] dirs = isoFile.GetDirectoryNames(tempPath + "*");
if (dirs.Length > 0)
{
foreach (string dir in dirs)
{
if (!removeDirRecursively(tempPath + dir, callbackId))
{
return false;
}
}
}
isoFile.DeleteDirectory(fullPath);
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR),callbackId);
}
}
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR),callbackId);
return false;
}
}
return true;
}
private bool CanonicalCompare(string pathA, string pathB)
{
string a = pathA.Replace("//", "/");
string b = pathB.Replace("//", "/");
return a.Equals(b, StringComparison.OrdinalIgnoreCase);
}
/*
* copyTo:["fullPath","parent", "newName"],
* moveTo:["fullPath","parent", "newName"],
*/
private void TransferTo(string options, bool move)
{
// TODO: try/catch
string[] optStrings = getOptionStrings(options);
string fullPath = optStrings[0];
string parent = optStrings[1];
string newFileName = optStrings[2];
string callbackId = optStrings[3];
char[] invalids = Path.GetInvalidPathChars();
if (newFileName.IndexOfAny(invalids) > -1 || newFileName.IndexOf(":") > -1 )
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR), callbackId);
return;
}
try
{
if ((parent == null) || (string.IsNullOrEmpty(parent)) || (string.IsNullOrEmpty(fullPath)))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId);
return;
}
string parentPath = File.AddSlashToDirectory(parent);
string currentPath = fullPath;
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
bool isFileExist = isoFile.FileExists(currentPath);
bool isDirectoryExist = isoFile.DirectoryExists(currentPath);
bool isParentExist = isoFile.DirectoryExists(parentPath);
if ( ( !isFileExist && !isDirectoryExist ) || !isParentExist )
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId);
return;
}
string newName;
string newPath;
if (isFileExist)
{
newName = (string.IsNullOrEmpty(newFileName))
? Path.GetFileName(currentPath)
: newFileName;
newPath = Path.Combine(parentPath, newName);
// sanity check ..
// cannot copy file onto itself
if (CanonicalCompare(newPath,currentPath)) //(parent + newFileName))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, INVALID_MODIFICATION_ERR), callbackId);
return;
}
else if (isoFile.DirectoryExists(newPath))
{
// there is already a folder with the same name, operation is not allowed
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, INVALID_MODIFICATION_ERR), callbackId);
return;
}
else if (isoFile.FileExists(newPath))
{ // remove destination file if exists, in other case there will be exception
isoFile.DeleteFile(newPath);
}
if (move)
{
isoFile.MoveFile(currentPath, newPath);
}
else
{
isoFile.CopyFile(currentPath, newPath, true);
}
}
else
{
newName = (string.IsNullOrEmpty(newFileName))
? currentPath
: newFileName;
newPath = Path.Combine(parentPath, newName);
if (move)
{
// remove destination directory if exists, in other case there will be exception
// target directory should be empty
if (!newPath.Equals(currentPath) && isoFile.DirectoryExists(newPath))
{
isoFile.DeleteDirectory(newPath);
}
isoFile.MoveDirectory(currentPath, newPath);
}
else
{
CopyDirectory(currentPath, newPath, isoFile);
}
}
FileEntry entry = FileEntry.GetEntry(newPath);
if (entry != null)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId);
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId);
}
}
}
catch (Exception ex)
{
if (!this.HandleException(ex, callbackId))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId);
}
}
}
private bool HandleException(Exception ex, string cbId="")
{
bool handled = false;
string callbackId = String.IsNullOrEmpty(cbId) ? this.CurrentCommandCallbackId : cbId;
if (ex is SecurityException)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, SECURITY_ERR), callbackId);
handled = true;
}
else if (ex is FileNotFoundException)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId);
handled = true;
}
else if (ex is ArgumentException)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR), callbackId);
handled = true;
}
else if (ex is IsolatedStorageException)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, INVALID_MODIFICATION_ERR), callbackId);
handled = true;
}
else if (ex is DirectoryNotFoundException)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId);
handled = true;
}
return handled;
}
private void CopyDirectory(string sourceDir, string destDir, IsolatedStorageFile isoFile)
{
string path = File.AddSlashToDirectory(sourceDir);
bool bExists = isoFile.DirectoryExists(destDir);
if (!bExists)
{
isoFile.CreateDirectory(destDir);
}
destDir = File.AddSlashToDirectory(destDir);
string[] files = isoFile.GetFileNames(path + "*");
if (files.Length > 0)
{
foreach (string file in files)
{
isoFile.CopyFile(path + file, destDir + file,true);
}
}
string[] dirs = isoFile.GetDirectoryNames(path + "*");
if (dirs.Length > 0)
{
foreach (string dir in dirs)
{
CopyDirectory(path + dir, destDir + dir, isoFile);
}
}
}
private string RemoveExtraSlash(string path) {
if (path.StartsWith("//")) {
path = path.Remove(0, 1);
path = RemoveExtraSlash(path);
}
return path;
}
private string ResolvePath(string parentPath, string path)
{
string absolutePath = null;
if (path.Contains(".."))
{
if (parentPath.Length > 1 && parentPath.StartsWith("/") && parentPath !="/")
{
parentPath = RemoveExtraSlash(parentPath);
}
string fullPath = Path.GetFullPath(Path.Combine(parentPath, path));
absolutePath = fullPath.Replace(Path.GetPathRoot(fullPath), @"//");
}
else
{
absolutePath = Path.Combine(parentPath + "/", path);
}
return absolutePath;
}
private void GetFileOrDirectory(string options, bool getDirectory)
{
FileOptions fOptions = new FileOptions();
string[] args = getOptionStrings(options);
fOptions.FullPath = args[0];
fOptions.Path = args[1];
string callbackId = args[3];
try
{
fOptions.CreatingOpt = JSON.JsonHelper.Deserialize<CreatingOptions>(args[2]);
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), callbackId);
return;
}
try
{
if ((string.IsNullOrEmpty(fOptions.Path)) || (string.IsNullOrEmpty(fOptions.FullPath)))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId);
return;
}
string path;
if (fOptions.Path.Split(':').Length > 2)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR), callbackId);
return;
}
try
{
path = ResolvePath(fOptions.FullPath, fOptions.Path);
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR), callbackId);
return;
}
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
bool isFile = isoFile.FileExists(path);
bool isDirectory = isoFile.DirectoryExists(path);
bool create = (fOptions.CreatingOpt == null) ? false : fOptions.CreatingOpt.Create;
bool exclusive = (fOptions.CreatingOpt == null) ? false : fOptions.CreatingOpt.Exclusive;
if (create)
{
if (exclusive && (isoFile.FileExists(path) || isoFile.DirectoryExists(path)))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, PATH_EXISTS_ERR), callbackId);
return;
}
// need to make sure the parent exists
// it is an error to create a directory whose immediate parent does not yet exist
// see issue: https://issues.apache.org/jira/browse/CB-339
string[] pathParts = path.Split('/');
string builtPath = pathParts[0];
for (int n = 1; n < pathParts.Length - 1; n++)
{
builtPath += "/" + pathParts[n];
if (!isoFile.DirectoryExists(builtPath))
{
Debug.WriteLine(String.Format("Error :: Parent folder \"{0}\" does not exist, when attempting to create \"{1}\"",builtPath,path));
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId);
return;
}
}
if ((getDirectory) && (!isDirectory))
{
isoFile.CreateDirectory(path);
}
else
{
if ((!getDirectory) && (!isFile))
{
IsolatedStorageFileStream fileStream = isoFile.CreateFile(path);
fileStream.Close();
}
}
}
else // (not create)
{
if ((!isFile) && (!isDirectory))
{
if (path.IndexOf("//www") == 0)
{
Uri fileUri = new Uri(path.Remove(0,2), UriKind.Relative);
StreamResourceInfo streamInfo = Application.GetResourceStream(fileUri);
if (streamInfo != null)
{
FileEntry _entry = FileEntry.GetEntry(fileUri.OriginalString,true);
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, _entry), callbackId);
//using (BinaryReader br = new BinaryReader(streamInfo.Stream))
//{
// byte[] data = br.ReadBytes((int)streamInfo.Stream.Length);
//}
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId);
}
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId);
}
return;
}
if (((getDirectory) && (!isDirectory)) || ((!getDirectory) && (!isFile)))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, TYPE_MISMATCH_ERR), callbackId);
return;
}
}
FileEntry entry = FileEntry.GetEntry(path);
if (entry != null)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId);
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId);
}
}
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId);
}
}
}
private static string AddSlashToDirectory(string dirPath)
{
if (dirPath.EndsWith("/"))
{
return dirPath;
}
else
{
return dirPath + "/";
}
}
/// <summary>
/// Returns file content in a form of base64 string
/// </summary>
/// <param name="stream">File stream</param>
/// <returns>Base64 representation of the file</returns>
private string GetFileContent(Stream stream)
{
int streamLength = (int)stream.Length;
byte[] fileData = new byte[streamLength + 1];
stream.Read(fileData, 0, streamLength);
stream.Close();
return Convert.ToBase64String(fileData);
}
#endregion
}
}
| |
namespace CompactMovieManager
{
partial class frmCompactMovieManager
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmCompactMovieManager));
this.lstMovies = new System.Windows.Forms.ListBox();
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.stslblLastPickedCap = new System.Windows.Forms.ToolStripStatusLabel();
this.stslblLastPicked = new System.Windows.Forms.ToolStripStatusLabel();
this.stsprgRandomPick = new System.Windows.Forms.ToolStripProgressBar();
this.stslblError = new System.Windows.Forms.ToolStripStatusLabel();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.mnuConnectTo = new System.Windows.Forms.ToolStripMenuItem();
this.mniPathMode = new System.Windows.Forms.ToolStripMenuItem();
this.mniDatabase = new System.Windows.Forms.ToolStripMenuItem();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.mnuHelp = new System.Windows.Forms.ToolStripMenuItem();
this.mniAbout = new System.Windows.Forms.ToolStripMenuItem();
this.grpMovieList = new System.Windows.Forms.GroupBox();
this.btnSave = new System.Windows.Forms.Button();
this.imageList = new System.Windows.Forms.ImageList(this.components);
this.grpDetails = new System.Windows.Forms.GroupBox();
this.chkSubtitles = new System.Windows.Forms.CheckBox();
this.lblTotalMovies = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.btnRefresh = new System.Windows.Forms.Button();
this.btnPick = new System.Windows.Forms.Button();
this.grpMoviesPath = new System.Windows.Forms.GroupBox();
this.btnBrowse = new System.Windows.Forms.Button();
this.txtPath = new System.Windows.Forms.TextBox();
this.ttpMain = new System.Windows.Forms.ToolTip(this.components);
this.dlgFolderBrowser = new System.Windows.Forms.FolderBrowserDialog();
this.bkgPicker = new System.ComponentModel.BackgroundWorker();
this.fswFileWatcher = new System.IO.FileSystemWatcher();
this.grpSearch = new System.Windows.Forms.GroupBox();
this.txtTitleSearch = new System.Windows.Forms.TextBox();
this.btnSearch = new System.Windows.Forms.Button();
this.cmbSearch = new System.Windows.Forms.ComboBox();
this.cxtSave = new System.Windows.Forms.ContextMenuStrip(this.components);
this.saveTotextFileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveToDatabaseToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.statusStrip1.SuspendLayout();
this.menuStrip1.SuspendLayout();
this.grpMovieList.SuspendLayout();
this.grpDetails.SuspendLayout();
this.grpMoviesPath.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.fswFileWatcher)).BeginInit();
this.grpSearch.SuspendLayout();
this.cxtSave.SuspendLayout();
this.SuspendLayout();
//
// lstMovies
//
this.lstMovies.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lstMovies.FormattingEnabled = true;
this.lstMovies.Location = new System.Drawing.Point(48, 19);
this.lstMovies.Name = "lstMovies";
this.lstMovies.ScrollAlwaysVisible = true;
this.lstMovies.Size = new System.Drawing.Size(227, 212);
this.lstMovies.TabIndex = 0;
this.lstMovies.SelectedIndexChanged += new System.EventHandler(this.lstMovies_SelectedIndexChanged);
this.lstMovies.DoubleClick += new System.EventHandler(this.lstMovies_DoubleClick);
//
// statusStrip1
//
this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.stslblLastPickedCap,
this.stslblLastPicked,
this.stsprgRandomPick,
this.stslblError});
this.statusStrip1.Location = new System.Drawing.Point(0, 401);
this.statusStrip1.Name = "statusStrip1";
this.statusStrip1.Size = new System.Drawing.Size(466, 22);
this.statusStrip1.TabIndex = 1;
this.statusStrip1.Text = "statusStrip1";
//
// stslblLastPickedCap
//
this.stslblLastPickedCap.AutoSize = false;
this.stslblLastPickedCap.Name = "stslblLastPickedCap";
this.stslblLastPickedCap.Size = new System.Drawing.Size(109, 17);
this.stslblLastPickedCap.Text = "Last Random Pick: ";
//
// stslblLastPicked
//
this.stslblLastPicked.AutoSize = false;
this.stslblLastPicked.Font = new System.Drawing.Font("Tahoma", 6.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.stslblLastPicked.Name = "stslblLastPicked";
this.stslblLastPicked.Size = new System.Drawing.Size(170, 17);
this.stslblLastPicked.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// stsprgRandomPick
//
this.stsprgRandomPick.MarqueeAnimationSpeed = 150;
this.stsprgRandomPick.Maximum = 20;
this.stsprgRandomPick.Name = "stsprgRandomPick";
this.stsprgRandomPick.Size = new System.Drawing.Size(100, 16);
this.stsprgRandomPick.Step = 1;
this.stsprgRandomPick.Style = System.Windows.Forms.ProgressBarStyle.Continuous;
//
// stslblError
//
this.stslblError.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.stslblError.ForeColor = System.Drawing.Color.Red;
this.stslblError.IsLink = true;
this.stslblError.LinkColor = System.Drawing.Color.Red;
this.stslblError.Name = "stslblError";
this.stslblError.Size = new System.Drawing.Size(70, 17);
this.stslblError.Spring = true;
this.stslblError.Text = "Error";
this.stslblError.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.stslblError.Click += new System.EventHandler(this.toolStripStatusLabel1_Click);
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.mnuHelp});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(466, 24);
this.menuStrip1.TabIndex = 3;
this.menuStrip1.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuConnectTo,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(40, 20);
this.fileToolStripMenuItem.Text = "&File";
//
// mnuConnectTo
//
this.mnuConnectTo.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mniPathMode,
this.mniDatabase});
this.mnuConnectTo.Name = "mnuConnectTo";
this.mnuConnectTo.Size = new System.Drawing.Size(166, 22);
this.mnuConnectTo.Text = "Connect to ...";
//
// mniPathMode
//
this.mniPathMode.Checked = true;
this.mniPathMode.CheckOnClick = true;
this.mniPathMode.CheckState = System.Windows.Forms.CheckState.Checked;
this.mniPathMode.Name = "mniPathMode";
this.mniPathMode.Size = new System.Drawing.Size(142, 22);
this.mniPathMode.Text = "Path";
this.mniPathMode.CheckedChanged += new System.EventHandler(this.mniPathMode_CheckedChanged);
//
// mniDatabase
//
this.mniDatabase.CheckOnClick = true;
this.mniDatabase.Name = "mniDatabase";
this.mniDatabase.Size = new System.Drawing.Size(142, 22);
this.mniDatabase.Text = "Database";
this.mniDatabase.CheckedChanged += new System.EventHandler(this.mniDatabase_CheckedChanged);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(166, 22);
this.exitToolStripMenuItem.Text = "E&xit";
//
// mnuHelp
//
this.mnuHelp.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mniAbout});
this.mnuHelp.Name = "mnuHelp";
this.mnuHelp.Size = new System.Drawing.Size(45, 20);
this.mnuHelp.Text = "&Help";
//
// mniAbout
//
this.mniAbout.Name = "mniAbout";
this.mniAbout.Size = new System.Drawing.Size(122, 22);
this.mniAbout.Text = "&About";
this.mniAbout.Click += new System.EventHandler(this.mniAbout_Click);
//
// grpMovieList
//
this.grpMovieList.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.grpMovieList.Controls.Add(this.btnSave);
this.grpMovieList.Controls.Add(this.grpDetails);
this.grpMovieList.Controls.Add(this.btnRefresh);
this.grpMovieList.Controls.Add(this.btnPick);
this.grpMovieList.Controls.Add(this.lstMovies);
this.grpMovieList.Location = new System.Drawing.Point(8, 149);
this.grpMovieList.Name = "grpMovieList";
this.grpMovieList.Size = new System.Drawing.Size(450, 242);
this.grpMovieList.TabIndex = 5;
this.grpMovieList.TabStop = false;
this.grpMovieList.Text = "Movies";
this.grpMovieList.Enter += new System.EventHandler(this.grpMovieList_Enter);
//
// btnSave
//
this.btnSave.BackgroundImage = global::CompactMovieManager.Properties.Resources.save;
this.btnSave.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center;
this.btnSave.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnSave.ImageKey = "(none)";
this.btnSave.ImageList = this.imageList;
this.btnSave.Location = new System.Drawing.Point(7, 99);
this.btnSave.Name = "btnSave";
this.btnSave.Size = new System.Drawing.Size(39, 40);
this.btnSave.TabIndex = 9;
this.btnSave.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
this.ttpMain.SetToolTip(this.btnSave, "Save to Text File");
this.btnSave.UseVisualStyleBackColor = true;
this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
//
// imageList
//
this.imageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList.ImageStream")));
this.imageList.TransparentColor = System.Drawing.Color.Transparent;
this.imageList.Images.SetKeyName(0, "Dice.png");
this.imageList.Images.SetKeyName(1, "Refresh.png");
//
// grpDetails
//
this.grpDetails.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Right)));
this.grpDetails.Controls.Add(this.chkSubtitles);
this.grpDetails.Controls.Add(this.lblTotalMovies);
this.grpDetails.Controls.Add(this.label1);
this.grpDetails.Location = new System.Drawing.Point(281, 13);
this.grpDetails.Name = "grpDetails";
this.grpDetails.Size = new System.Drawing.Size(161, 219);
this.grpDetails.TabIndex = 8;
this.grpDetails.TabStop = false;
this.grpDetails.Text = "Details";
//
// chkSubtitles
//
this.chkSubtitles.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this.chkSubtitles.Location = new System.Drawing.Point(4, 20);
this.chkSubtitles.Name = "chkSubtitles";
this.chkSubtitles.Size = new System.Drawing.Size(150, 17);
this.chkSubtitles.TabIndex = 11;
this.chkSubtitles.Text = "Subtitles";
this.chkSubtitles.UseVisualStyleBackColor = true;
//
// lblTotalMovies
//
this.lblTotalMovies.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.lblTotalMovies.AutoSize = true;
this.lblTotalMovies.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblTotalMovies.Location = new System.Drawing.Point(130, 200);
this.lblTotalMovies.Name = "lblTotalMovies";
this.lblTotalMovies.Size = new System.Drawing.Size(0, 13);
this.lblTotalMovies.TabIndex = 10;
//
// label1
//
this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(93, 200);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(34, 13);
this.label1.TabIndex = 9;
this.label1.Text = "Total:";
//
// btnRefresh
//
this.btnRefresh.BackgroundImage = global::CompactMovieManager.Properties.Resources.Refresh;
this.btnRefresh.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center;
this.btnRefresh.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnRefresh.ImageKey = "(none)";
this.btnRefresh.ImageList = this.imageList;
this.btnRefresh.Location = new System.Drawing.Point(7, 59);
this.btnRefresh.Name = "btnRefresh";
this.btnRefresh.Size = new System.Drawing.Size(39, 40);
this.btnRefresh.TabIndex = 7;
this.btnRefresh.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
this.ttpMain.SetToolTip(this.btnRefresh, "Refresh");
this.btnRefresh.UseVisualStyleBackColor = true;
this.btnRefresh.Click += new System.EventHandler(this.button1_Click);
//
// btnPick
//
this.btnPick.BackgroundImage = global::CompactMovieManager.Properties.Resources.Dice;
this.btnPick.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center;
this.btnPick.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnPick.ImageKey = "(none)";
this.btnPick.ImageList = this.imageList;
this.btnPick.Location = new System.Drawing.Point(7, 19);
this.btnPick.Name = "btnPick";
this.btnPick.Size = new System.Drawing.Size(39, 40);
this.btnPick.TabIndex = 6;
this.btnPick.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
this.ttpMain.SetToolTip(this.btnPick, "Random Pick");
this.btnPick.UseVisualStyleBackColor = true;
this.btnPick.Click += new System.EventHandler(this.btnPick_Click);
//
// grpMoviesPath
//
this.grpMoviesPath.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.grpMoviesPath.Controls.Add(this.btnBrowse);
this.grpMoviesPath.Controls.Add(this.txtPath);
this.grpMoviesPath.Location = new System.Drawing.Point(8, 28);
this.grpMoviesPath.Name = "grpMoviesPath";
this.grpMoviesPath.Size = new System.Drawing.Size(450, 43);
this.grpMoviesPath.TabIndex = 6;
this.grpMoviesPath.TabStop = false;
this.grpMoviesPath.Text = "Path";
//
// btnBrowse
//
this.btnBrowse.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnBrowse.BackgroundImage = global::CompactMovieManager.Properties.Resources.Folder;
this.btnBrowse.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.btnBrowse.Location = new System.Drawing.Point(419, 15);
this.btnBrowse.Name = "btnBrowse";
this.btnBrowse.Size = new System.Drawing.Size(26, 22);
this.btnBrowse.TabIndex = 8;
this.btnBrowse.UseVisualStyleBackColor = true;
this.btnBrowse.Click += new System.EventHandler(this.btnBrowse_Click);
//
// txtPath
//
this.txtPath.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtPath.Location = new System.Drawing.Point(6, 16);
this.txtPath.Name = "txtPath";
this.txtPath.Size = new System.Drawing.Size(410, 20);
this.txtPath.TabIndex = 7;
//
// ttpMain
//
this.ttpMain.AutoPopDelay = 5000;
this.ttpMain.InitialDelay = 300;
this.ttpMain.ReshowDelay = 100;
//
// dlgFolderBrowser
//
this.dlgFolderBrowser.RootFolder = System.Environment.SpecialFolder.MyComputer;
//
// bkgPicker
//
this.bkgPicker.WorkerSupportsCancellation = true;
this.bkgPicker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.bkgPicker_DoWork);
this.bkgPicker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.bkgPicker_RunWorkerCompleted);
//
// fswFileWatcher
//
this.fswFileWatcher.EnableRaisingEvents = true;
this.fswFileWatcher.SynchronizingObject = this;
this.fswFileWatcher.Renamed += new System.IO.RenamedEventHandler(this.fswFileWatcher_Renamed);
this.fswFileWatcher.Created += new System.IO.FileSystemEventHandler(this.fswFileWatcher_Created);
this.fswFileWatcher.Changed += new System.IO.FileSystemEventHandler(this.fswFileWatcher_Changed);
//
// grpSearch
//
this.grpSearch.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.grpSearch.Controls.Add(this.txtTitleSearch);
this.grpSearch.Controls.Add(this.btnSearch);
this.grpSearch.Controls.Add(this.cmbSearch);
this.grpSearch.Location = new System.Drawing.Point(8, 87);
this.grpSearch.Name = "grpSearch";
this.grpSearch.Size = new System.Drawing.Size(450, 43);
this.grpSearch.TabIndex = 9;
this.grpSearch.TabStop = false;
this.grpSearch.Text = "Search by";
//
// txtTitleSearch
//
this.txtTitleSearch.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtTitleSearch.Location = new System.Drawing.Point(129, 17);
this.txtTitleSearch.Name = "txtTitleSearch";
this.txtTitleSearch.Size = new System.Drawing.Size(287, 20);
this.txtTitleSearch.TabIndex = 9;
//
// btnSearch
//
this.btnSearch.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnSearch.BackgroundImage = global::CompactMovieManager.Properties.Resources.Search;
this.btnSearch.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.btnSearch.Location = new System.Drawing.Point(419, 16);
this.btnSearch.Name = "btnSearch";
this.btnSearch.Size = new System.Drawing.Size(26, 22);
this.btnSearch.TabIndex = 9;
this.btnSearch.UseVisualStyleBackColor = true;
this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click);
//
// cmbSearch
//
this.cmbSearch.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbSearch.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.cmbSearch.FormattingEnabled = true;
this.cmbSearch.Items.AddRange(new object[] {
"Title",
"Duration",
"Subtitles"});
this.cmbSearch.Location = new System.Drawing.Point(6, 16);
this.cmbSearch.Name = "cmbSearch";
this.cmbSearch.Size = new System.Drawing.Size(119, 21);
this.cmbSearch.TabIndex = 8;
//
// cxtSave
//
this.cxtSave.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.saveTotextFileToolStripMenuItem,
this.saveToDatabaseToolStripMenuItem});
this.cxtSave.Name = "cxtSave";
this.cxtSave.Size = new System.Drawing.Size(189, 48);
//
// saveTotextFileToolStripMenuItem
//
this.saveTotextFileToolStripMenuItem.Name = "saveTotextFileToolStripMenuItem";
this.saveTotextFileToolStripMenuItem.Size = new System.Drawing.Size(188, 22);
this.saveTotextFileToolStripMenuItem.Text = "Save to &text file";
this.saveTotextFileToolStripMenuItem.Click += new System.EventHandler(this.saveTotextFileToolStripMenuItem_Click);
//
// saveToDatabaseToolStripMenuItem
//
this.saveToDatabaseToolStripMenuItem.Name = "saveToDatabaseToolStripMenuItem";
this.saveToDatabaseToolStripMenuItem.Size = new System.Drawing.Size(188, 22);
this.saveToDatabaseToolStripMenuItem.Text = "Save to database";
this.saveToDatabaseToolStripMenuItem.Click += new System.EventHandler(this.saveToDatabaseToolStripMenuItem_Click);
//
// frmCompactMovieManager
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(466, 423);
this.Controls.Add(this.grpSearch);
this.Controls.Add(this.grpMoviesPath);
this.Controls.Add(this.grpMovieList);
this.Controls.Add(this.statusStrip1);
this.Controls.Add(this.menuStrip1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MainMenuStrip = this.menuStrip1;
this.MinimumSize = new System.Drawing.Size(407, 353);
this.Name = "frmCompactMovieManager";
this.Text = "Compact Movie Manager";
this.Load += new System.EventHandler(this.frmCompactMovieManager_Load);
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.frmCompactMovieManager_FormClosed);
this.statusStrip1.ResumeLayout(false);
this.statusStrip1.PerformLayout();
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.grpMovieList.ResumeLayout(false);
this.grpDetails.ResumeLayout(false);
this.grpDetails.PerformLayout();
this.grpMoviesPath.ResumeLayout(false);
this.grpMoviesPath.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.fswFileWatcher)).EndInit();
this.grpSearch.ResumeLayout(false);
this.grpSearch.PerformLayout();
this.cxtSave.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ListBox lstMovies;
private System.Windows.Forms.StatusStrip statusStrip1;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.GroupBox grpMovieList;
private System.Windows.Forms.Button btnPick;
private System.Windows.Forms.ToolStripStatusLabel stslblLastPickedCap;
private System.Windows.Forms.ToolStripStatusLabel stslblLastPicked;
private System.Windows.Forms.GroupBox grpMoviesPath;
private System.Windows.Forms.Button btnBrowse;
private System.Windows.Forms.TextBox txtPath;
private System.Windows.Forms.ImageList imageList;
private System.Windows.Forms.Button btnRefresh;
private System.Windows.Forms.ToolTip ttpMain;
private System.Windows.Forms.FolderBrowserDialog dlgFolderBrowser;
private System.ComponentModel.BackgroundWorker bkgPicker;
private System.Windows.Forms.ToolStripStatusLabel stslblError;
private System.Windows.Forms.ToolStripProgressBar stsprgRandomPick;
private System.Windows.Forms.GroupBox grpDetails;
private System.IO.FileSystemWatcher fswFileWatcher;
private System.Windows.Forms.Label lblTotalMovies;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button btnSave;
private System.Windows.Forms.ToolStripMenuItem mnuHelp;
private System.Windows.Forms.ToolStripMenuItem mniAbout;
private System.Windows.Forms.CheckBox chkSubtitles;
private System.Windows.Forms.GroupBox grpSearch;
private System.Windows.Forms.Button btnSearch;
private System.Windows.Forms.ComboBox cmbSearch;
private System.Windows.Forms.TextBox txtTitleSearch;
private System.Windows.Forms.ToolStripMenuItem mnuConnectTo;
private System.Windows.Forms.ToolStripMenuItem mniPathMode;
private System.Windows.Forms.ToolStripMenuItem mniDatabase;
private System.Windows.Forms.ContextMenuStrip cxtSave;
private System.Windows.Forms.ToolStripMenuItem saveTotextFileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveToDatabaseToolStripMenuItem;
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gagr = Google.Api.Gax.ResourceNames;
using gcdv = Google.Cloud.Dataproc.V1;
using sys = System;
namespace Google.Cloud.Dataproc.V1
{
/// <summary>Resource name for the <c>AutoscalingPolicy</c> resource.</summary>
public sealed partial class AutoscalingPolicyName : gax::IResourceName, sys::IEquatable<AutoscalingPolicyName>
{
/// <summary>The possible contents of <see cref="AutoscalingPolicyName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/autoscalingPolicies/{autoscaling_policy}</c>.
/// </summary>
ProjectLocationAutoscalingPolicy = 1,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/regions/{region}/autoscalingPolicies/{autoscaling_policy}</c>.
/// </summary>
ProjectRegionAutoscalingPolicy = 2,
}
private static gax::PathTemplate s_projectLocationAutoscalingPolicy = new gax::PathTemplate("projects/{project}/locations/{location}/autoscalingPolicies/{autoscaling_policy}");
private static gax::PathTemplate s_projectRegionAutoscalingPolicy = new gax::PathTemplate("projects/{project}/regions/{region}/autoscalingPolicies/{autoscaling_policy}");
/// <summary>Creates a <see cref="AutoscalingPolicyName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="AutoscalingPolicyName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static AutoscalingPolicyName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new AutoscalingPolicyName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="AutoscalingPolicyName"/> with the pattern
/// <c>projects/{project}/locations/{location}/autoscalingPolicies/{autoscaling_policy}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="autoscalingPolicyId">The <c>AutoscalingPolicy</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="AutoscalingPolicyName"/> constructed from the provided ids.</returns>
public static AutoscalingPolicyName FromProjectLocationAutoscalingPolicy(string projectId, string locationId, string autoscalingPolicyId) =>
new AutoscalingPolicyName(ResourceNameType.ProjectLocationAutoscalingPolicy, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), autoscalingPolicyId: gax::GaxPreconditions.CheckNotNullOrEmpty(autoscalingPolicyId, nameof(autoscalingPolicyId)));
/// <summary>
/// Creates a <see cref="AutoscalingPolicyName"/> with the pattern
/// <c>projects/{project}/regions/{region}/autoscalingPolicies/{autoscaling_policy}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="regionId">The <c>Region</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="autoscalingPolicyId">The <c>AutoscalingPolicy</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="AutoscalingPolicyName"/> constructed from the provided ids.</returns>
public static AutoscalingPolicyName FromProjectRegionAutoscalingPolicy(string projectId, string regionId, string autoscalingPolicyId) =>
new AutoscalingPolicyName(ResourceNameType.ProjectRegionAutoscalingPolicy, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), regionId: gax::GaxPreconditions.CheckNotNullOrEmpty(regionId, nameof(regionId)), autoscalingPolicyId: gax::GaxPreconditions.CheckNotNullOrEmpty(autoscalingPolicyId, nameof(autoscalingPolicyId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AutoscalingPolicyName"/> with pattern
/// <c>projects/{project}/locations/{location}/autoscalingPolicies/{autoscaling_policy}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="autoscalingPolicyId">The <c>AutoscalingPolicy</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AutoscalingPolicyName"/> with pattern
/// <c>projects/{project}/locations/{location}/autoscalingPolicies/{autoscaling_policy}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string autoscalingPolicyId) =>
FormatProjectLocationAutoscalingPolicy(projectId, locationId, autoscalingPolicyId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AutoscalingPolicyName"/> with pattern
/// <c>projects/{project}/locations/{location}/autoscalingPolicies/{autoscaling_policy}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="autoscalingPolicyId">The <c>AutoscalingPolicy</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AutoscalingPolicyName"/> with pattern
/// <c>projects/{project}/locations/{location}/autoscalingPolicies/{autoscaling_policy}</c>.
/// </returns>
public static string FormatProjectLocationAutoscalingPolicy(string projectId, string locationId, string autoscalingPolicyId) =>
s_projectLocationAutoscalingPolicy.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(autoscalingPolicyId, nameof(autoscalingPolicyId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AutoscalingPolicyName"/> with pattern
/// <c>projects/{project}/regions/{region}/autoscalingPolicies/{autoscaling_policy}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="regionId">The <c>Region</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="autoscalingPolicyId">The <c>AutoscalingPolicy</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AutoscalingPolicyName"/> with pattern
/// <c>projects/{project}/regions/{region}/autoscalingPolicies/{autoscaling_policy}</c>.
/// </returns>
public static string FormatProjectRegionAutoscalingPolicy(string projectId, string regionId, string autoscalingPolicyId) =>
s_projectRegionAutoscalingPolicy.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(regionId, nameof(regionId)), gax::GaxPreconditions.CheckNotNullOrEmpty(autoscalingPolicyId, nameof(autoscalingPolicyId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="AutoscalingPolicyName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/autoscalingPolicies/{autoscaling_policy}</c>
/// </description>
/// </item>
/// <item>
/// <description>
/// <c>projects/{project}/regions/{region}/autoscalingPolicies/{autoscaling_policy}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="autoscalingPolicyName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="AutoscalingPolicyName"/> if successful.</returns>
public static AutoscalingPolicyName Parse(string autoscalingPolicyName) => Parse(autoscalingPolicyName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="AutoscalingPolicyName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/autoscalingPolicies/{autoscaling_policy}</c>
/// </description>
/// </item>
/// <item>
/// <description>
/// <c>projects/{project}/regions/{region}/autoscalingPolicies/{autoscaling_policy}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="autoscalingPolicyName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="AutoscalingPolicyName"/> if successful.</returns>
public static AutoscalingPolicyName Parse(string autoscalingPolicyName, bool allowUnparsed) =>
TryParse(autoscalingPolicyName, allowUnparsed, out AutoscalingPolicyName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AutoscalingPolicyName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/autoscalingPolicies/{autoscaling_policy}</c>
/// </description>
/// </item>
/// <item>
/// <description>
/// <c>projects/{project}/regions/{region}/autoscalingPolicies/{autoscaling_policy}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="autoscalingPolicyName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AutoscalingPolicyName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string autoscalingPolicyName, out AutoscalingPolicyName result) =>
TryParse(autoscalingPolicyName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AutoscalingPolicyName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/autoscalingPolicies/{autoscaling_policy}</c>
/// </description>
/// </item>
/// <item>
/// <description>
/// <c>projects/{project}/regions/{region}/autoscalingPolicies/{autoscaling_policy}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="autoscalingPolicyName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AutoscalingPolicyName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string autoscalingPolicyName, bool allowUnparsed, out AutoscalingPolicyName result)
{
gax::GaxPreconditions.CheckNotNull(autoscalingPolicyName, nameof(autoscalingPolicyName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationAutoscalingPolicy.TryParseName(autoscalingPolicyName, out resourceName))
{
result = FromProjectLocationAutoscalingPolicy(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (s_projectRegionAutoscalingPolicy.TryParseName(autoscalingPolicyName, out resourceName))
{
result = FromProjectRegionAutoscalingPolicy(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(autoscalingPolicyName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private AutoscalingPolicyName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string autoscalingPolicyId = null, string locationId = null, string projectId = null, string regionId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
AutoscalingPolicyId = autoscalingPolicyId;
LocationId = locationId;
ProjectId = projectId;
RegionId = regionId;
}
/// <summary>
/// Constructs a new instance of a <see cref="AutoscalingPolicyName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/autoscalingPolicies/{autoscaling_policy}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="autoscalingPolicyId">The <c>AutoscalingPolicy</c> ID. Must not be <c>null</c> or empty.</param>
public AutoscalingPolicyName(string projectId, string locationId, string autoscalingPolicyId) : this(ResourceNameType.ProjectLocationAutoscalingPolicy, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), autoscalingPolicyId: gax::GaxPreconditions.CheckNotNullOrEmpty(autoscalingPolicyId, nameof(autoscalingPolicyId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>AutoscalingPolicy</c> ID. May be <c>null</c>, depending on which resource name is contained by this
/// instance.
/// </summary>
public string AutoscalingPolicyId { get; }
/// <summary>
/// The <c>Location</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Region</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string RegionId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationAutoscalingPolicy: return s_projectLocationAutoscalingPolicy.Expand(ProjectId, LocationId, AutoscalingPolicyId);
case ResourceNameType.ProjectRegionAutoscalingPolicy: return s_projectRegionAutoscalingPolicy.Expand(ProjectId, RegionId, AutoscalingPolicyId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as AutoscalingPolicyName);
/// <inheritdoc/>
public bool Equals(AutoscalingPolicyName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(AutoscalingPolicyName a, AutoscalingPolicyName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(AutoscalingPolicyName a, AutoscalingPolicyName b) => !(a == b);
}
/// <summary>Resource name for the <c>Region</c> resource.</summary>
public sealed partial class RegionName : gax::IResourceName, sys::IEquatable<RegionName>
{
/// <summary>The possible contents of <see cref="RegionName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>projects/{project}/regions/{region}</c>.</summary>
ProjectRegion = 1,
}
private static gax::PathTemplate s_projectRegion = new gax::PathTemplate("projects/{project}/regions/{region}");
/// <summary>Creates a <see cref="RegionName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="RegionName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static RegionName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new RegionName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="RegionName"/> with the pattern <c>projects/{project}/regions/{region}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="regionId">The <c>Region</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="RegionName"/> constructed from the provided ids.</returns>
public static RegionName FromProjectRegion(string projectId, string regionId) =>
new RegionName(ResourceNameType.ProjectRegion, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), regionId: gax::GaxPreconditions.CheckNotNullOrEmpty(regionId, nameof(regionId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="RegionName"/> with pattern
/// <c>projects/{project}/regions/{region}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="regionId">The <c>Region</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="RegionName"/> with pattern
/// <c>projects/{project}/regions/{region}</c>.
/// </returns>
public static string Format(string projectId, string regionId) => FormatProjectRegion(projectId, regionId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="RegionName"/> with pattern
/// <c>projects/{project}/regions/{region}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="regionId">The <c>Region</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="RegionName"/> with pattern
/// <c>projects/{project}/regions/{region}</c>.
/// </returns>
public static string FormatProjectRegion(string projectId, string regionId) =>
s_projectRegion.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(regionId, nameof(regionId)));
/// <summary>Parses the given resource name string into a new <see cref="RegionName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/regions/{region}</c></description></item>
/// </list>
/// </remarks>
/// <param name="regionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="RegionName"/> if successful.</returns>
public static RegionName Parse(string regionName) => Parse(regionName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="RegionName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/regions/{region}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="regionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="RegionName"/> if successful.</returns>
public static RegionName Parse(string regionName, bool allowUnparsed) =>
TryParse(regionName, allowUnparsed, out RegionName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="RegionName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/regions/{region}</c></description></item>
/// </list>
/// </remarks>
/// <param name="regionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="RegionName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string regionName, out RegionName result) => TryParse(regionName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="RegionName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/regions/{region}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="regionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="RegionName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string regionName, bool allowUnparsed, out RegionName result)
{
gax::GaxPreconditions.CheckNotNull(regionName, nameof(regionName));
gax::TemplatedResourceName resourceName;
if (s_projectRegion.TryParseName(regionName, out resourceName))
{
result = FromProjectRegion(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(regionName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private RegionName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string projectId = null, string regionId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
ProjectId = projectId;
RegionId = regionId;
}
/// <summary>
/// Constructs a new instance of a <see cref="RegionName"/> class from the component parts of pattern
/// <c>projects/{project}/regions/{region}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="regionId">The <c>Region</c> ID. Must not be <c>null</c> or empty.</param>
public RegionName(string projectId, string regionId) : this(ResourceNameType.ProjectRegion, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), regionId: gax::GaxPreconditions.CheckNotNullOrEmpty(regionId, nameof(regionId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Region</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string RegionId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectRegion: return s_projectRegion.Expand(ProjectId, RegionId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as RegionName);
/// <inheritdoc/>
public bool Equals(RegionName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(RegionName a, RegionName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(RegionName a, RegionName b) => !(a == b);
}
public partial class AutoscalingPolicy
{
/// <summary>
/// <see cref="gcdv::AutoscalingPolicyName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdv::AutoscalingPolicyName AutoscalingPolicyName
{
get => string.IsNullOrEmpty(Name) ? null : gcdv::AutoscalingPolicyName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class CreateAutoscalingPolicyRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary><see cref="RegionName"/>-typed view over the <see cref="Parent"/> resource name property.</summary>
public RegionName ParentAsRegionName
{
get => string.IsNullOrEmpty(Parent) ? null : RegionName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gax::IResourceName ParentAsResourceName
{
get
{
if (string.IsNullOrEmpty(Parent))
{
return null;
}
if (gagr::LocationName.TryParse(Parent, out gagr::LocationName location))
{
return location;
}
if (RegionName.TryParse(Parent, out RegionName region))
{
return region;
}
return gax::UnparsedResourceName.Parse(Parent);
}
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetAutoscalingPolicyRequest
{
/// <summary>
/// <see cref="gcdv::AutoscalingPolicyName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdv::AutoscalingPolicyName AutoscalingPolicyName
{
get => string.IsNullOrEmpty(Name) ? null : gcdv::AutoscalingPolicyName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class DeleteAutoscalingPolicyRequest
{
/// <summary>
/// <see cref="gcdv::AutoscalingPolicyName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdv::AutoscalingPolicyName AutoscalingPolicyName
{
get => string.IsNullOrEmpty(Name) ? null : gcdv::AutoscalingPolicyName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListAutoscalingPoliciesRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary><see cref="RegionName"/>-typed view over the <see cref="Parent"/> resource name property.</summary>
public RegionName ParentAsRegionName
{
get => string.IsNullOrEmpty(Parent) ? null : RegionName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gax::IResourceName ParentAsResourceName
{
get
{
if (string.IsNullOrEmpty(Parent))
{
return null;
}
if (gagr::LocationName.TryParse(Parent, out gagr::LocationName location))
{
return location;
}
if (RegionName.TryParse(Parent, out RegionName region))
{
return region;
}
return gax::UnparsedResourceName.Parse(Parent);
}
set => Parent = value?.ToString() ?? "";
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureSpecials
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// SkipUrlEncodingOperations operations.
/// </summary>
internal partial class SkipUrlEncodingOperations : IServiceOperations<AutoRestAzureSpecialParametersTestClient>, ISkipUrlEncodingOperations
{
/// <summary>
/// Initializes a new instance of the SkipUrlEncodingOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal SkipUrlEncodingOperations(AutoRestAzureSpecialParametersTestClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestAzureSpecialParametersTestClient
/// </summary>
public AutoRestAzureSpecialParametersTestClient Client { get; private set; }
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='unencodedPathParam'>
/// Unencoded path parameter with value 'path1/path2/path3'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> GetMethodPathValidWithHttpMessagesAsync(string unencodedPathParam, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (unencodedPathParam == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "unencodedPathParam");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("unencodedPathParam", unencodedPathParam);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetMethodPathValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/skipUrlEncoding/method/path/valid/{unencodedPathParam}").ToString();
_url = _url.Replace("{unencodedPathParam}", unencodedPathParam);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
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>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='unencodedPathParam'>
/// Unencoded path parameter with value 'path1/path2/path3'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> GetPathPathValidWithHttpMessagesAsync(string unencodedPathParam, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (unencodedPathParam == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "unencodedPathParam");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("unencodedPathParam", unencodedPathParam);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetPathPathValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/skipUrlEncoding/path/path/valid/{unencodedPathParam}").ToString();
_url = _url.Replace("{unencodedPathParam}", unencodedPathParam);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
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>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> GetSwaggerPathValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
string unencodedPathParam = "path1/path2/path3";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("unencodedPathParam", unencodedPathParam);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetSwaggerPathValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/skipUrlEncoding/swagger/path/valid/{unencodedPathParam}").ToString();
_url = _url.Replace("{unencodedPathParam}", unencodedPathParam);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
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>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='q1'>
/// Unencoded query parameter with value 'value1&q2=value2&q3=value3'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> GetMethodQueryValidWithHttpMessagesAsync(string q1, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (q1 == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "q1");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("q1", q1);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetMethodQueryValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/skipUrlEncoding/method/query/valid").ToString();
List<string> _queryParameters = new List<string>();
if (q1 != null)
{
_queryParameters.Add(string.Format("q1={0}", q1));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
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>
/// Get method with unencoded query parameter with value null
/// </summary>
/// <param name='q1'>
/// Unencoded query parameter with value null
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> GetMethodQueryNullWithHttpMessagesAsync(string q1 = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("q1", q1);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetMethodQueryNull", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/skipUrlEncoding/method/query/null").ToString();
List<string> _queryParameters = new List<string>();
if (q1 != null)
{
_queryParameters.Add(string.Format("q1={0}", q1));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
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>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='q1'>
/// Unencoded query parameter with value 'value1&q2=value2&q3=value3'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> GetPathQueryValidWithHttpMessagesAsync(string q1, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (q1 == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "q1");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("q1", q1);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetPathQueryValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/skipUrlEncoding/path/query/valid").ToString();
List<string> _queryParameters = new List<string>();
if (q1 != null)
{
_queryParameters.Add(string.Format("q1={0}", q1));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
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>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> GetSwaggerQueryValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
string q1 = "value1&q2=value2&q3=value3";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("q1", q1);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetSwaggerQueryValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/skipUrlEncoding/swagger/query/valid").ToString();
List<string> _queryParameters = new List<string>();
if (q1 != null)
{
_queryParameters.Add(string.Format("q1={0}", q1));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
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;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
//Joshua Saxton
namespace Boys_vs.Girls
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
SpriteFont font;
public static Random jen = new Random();
public static Player p1;
public static Player p2;
private List<Enemy> enemylist = new List<Enemy>();
public static List<Weapon> onscreenWeapons = new List<Weapon>(3);
private Texture2D player_texture;
public Texture2D bulletHeart;
public Texture2D missilePod;
public Texture2D lipstick;
public Texture2D currbullet;
public Texture2D sword;
public Texture2D lollipop;
private Texture2D Spring;
public enum ScreenState
{
startScreen,
playingScreen,
highScore,
endGame
}
ScreenState currstate;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
graphics.PreferredBackBufferHeight = 600;
graphics.PreferredBackBufferWidth = 800;
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
currstate = ScreenState.startScreen;
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// TODO: use this.Content to load your game content here
player_texture = Content.Load<Texture2D>("Girl");
p1 = new Player("Sweetie", 0, player_texture, new Vector2(100.0f, 100.0f), this, 1);
p2 = new Player("Honey", 0, player_texture, new Vector2(500.0f, 500.0f), this, 2);
font = Content.Load<SpriteFont>("font");
for (int i = 0; i < 20; i++)
{
enemylist.Add(new Spider(Content.Load<Texture2D>("Spider"), this));
enemylist.Add(new Boy(Content.Load<Texture2D>("Boy"), this));
enemylist.Add(new Monkey(Content.Load<Texture2D>("monkey"), this));
}
//Bullet loading
bulletHeart = Content.Load<Texture2D>("BulletHeart");
missilePod = Content.Load<Texture2D>("Missilepod");
lipstick = Content.Load<Texture2D>("Lipstick");
//Weapon loading
sword = Content.Load<Texture2D>("Sword");
onscreenWeapons.Add(new Sword(sword, this, 10.0f));
lollipop = Content.Load<Texture2D>("Lollipop");
onscreenWeapons.Add(new Lollipop(lollipop, this, 30.0f));
Spring = Content.Load<Texture2D>("Spring room");
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the Room,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
switch (currstate)
{
case ScreenState.playingScreen:
if (p1.Health <= 0 && p2.Health <= 0 || enemylist.Count == 0)
{
currstate = ScreenState.endGame;
}
p1.Update();
p2.Update();
foreach (Enemy e in enemylist)
{
e.Update(p1.Position);
e.Update(p2.Position);
e.Attack(p1);
e.Attack(p2);
}
Collisions(p1.Bulletlist, enemylist, p1);
Collisions(p2.Bulletlist, enemylist, p2);
break;
case ScreenState.startScreen:
if (Keyboard.GetState().IsKeyDown(Keys.Enter))
{
currstate = ScreenState.playingScreen;
}
break;
case ScreenState.highScore:
case ScreenState.endGame:
break;
}
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// TODO: Add your drawing code here
spriteBatch.Begin();
switch (currstate)
{
case ScreenState.playingScreen:
spriteBatch.Draw(Spring, new Vector2(0.0f, 0.0f), Color.White);
if (p1.Health >= 0)
p1.Draw(spriteBatch);
if (p2.Health >= 0)
p2.Draw(spriteBatch);
foreach (Enemy e in enemylist)
{
e.Draw(spriteBatch);
}
foreach (Weapon w in onscreenWeapons)
{
w.Draw(spriteBatch);
}
spriteBatch.DrawString(font, "Player 1 Health : " + p1.Health, Vector2.Zero, Color.LavenderBlush);
spriteBatch.DrawString(font, "Player 2 Score: " + p1.Score, new Vector2(0, 15), Color.LavenderBlush);
spriteBatch.DrawString(font, "Player 2 Health : " + p2.Health, new Vector2(600, 0), Color.Pink);
spriteBatch.DrawString(font, "Player 2 Score : " + p2.Score, new Vector2(600, 15), Color.Pink);
break;
case ScreenState.startScreen:
spriteBatch.Draw(Content.Load<Texture2D>("StartScreen"), Vector2.Zero, Color.White);
spriteBatch.DrawString(font, "Enter = Begin Game", new Vector2(0, 600), Color.White);
spriteBatch.DrawString(font, "F1 to enter fullscreen", new Vector2(0, 550), Color.White);
break;
}
spriteBatch.End();
base.Draw(gameTime);
}
private void Collisions(List<Bullet> bulletlist, List<Enemy> enemylist, Player p)
{
for (int i = enemylist.Count - 1; i >= 0; i--)
{
Enemy e = enemylist[i];
for (int j = bulletlist.Count - 1; j >= 0; j--)
{
Bullet b = bulletlist[j];
if (b.X >= 800 || b.X <= 0 || b.Y >= 600 || b.Y <= 0)
{
bulletlist.RemoveAt(j);
continue;
}
if (b.Spriterect.Intersects(e.Spriterect))
{
e.Health -= .005f;
if (e.Health <= 0)
{
enemylist.RemoveAt(i);
bulletlist.RemoveAt(j);
p.Score += 10;
break;
}
}
}
}
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Compute.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedZoneOperationsClientTest
{
[xunit::FactAttribute]
public void DeleteRequestObject()
{
moq::Mock<ZoneOperations.ZoneOperationsClient> mockGrpcClient = new moq::Mock<ZoneOperations.ZoneOperationsClient>(moq::MockBehavior.Strict);
DeleteZoneOperationRequest request = new DeleteZoneOperationRequest
{
Zone = "zone255f4ea8",
Operation = "operation615a23f7",
Project = "projectaa6ff846",
};
DeleteZoneOperationResponse expectedResponse = new DeleteZoneOperationResponse { };
mockGrpcClient.Setup(x => x.Delete(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ZoneOperationsClient client = new ZoneOperationsClientImpl(mockGrpcClient.Object, null);
DeleteZoneOperationResponse response = client.Delete(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteRequestObjectAsync()
{
moq::Mock<ZoneOperations.ZoneOperationsClient> mockGrpcClient = new moq::Mock<ZoneOperations.ZoneOperationsClient>(moq::MockBehavior.Strict);
DeleteZoneOperationRequest request = new DeleteZoneOperationRequest
{
Zone = "zone255f4ea8",
Operation = "operation615a23f7",
Project = "projectaa6ff846",
};
DeleteZoneOperationResponse expectedResponse = new DeleteZoneOperationResponse { };
mockGrpcClient.Setup(x => x.DeleteAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<DeleteZoneOperationResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ZoneOperationsClient client = new ZoneOperationsClientImpl(mockGrpcClient.Object, null);
DeleteZoneOperationResponse responseCallSettings = await client.DeleteAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
DeleteZoneOperationResponse responseCancellationToken = await client.DeleteAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Delete()
{
moq::Mock<ZoneOperations.ZoneOperationsClient> mockGrpcClient = new moq::Mock<ZoneOperations.ZoneOperationsClient>(moq::MockBehavior.Strict);
DeleteZoneOperationRequest request = new DeleteZoneOperationRequest
{
Zone = "zone255f4ea8",
Operation = "operation615a23f7",
Project = "projectaa6ff846",
};
DeleteZoneOperationResponse expectedResponse = new DeleteZoneOperationResponse { };
mockGrpcClient.Setup(x => x.Delete(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ZoneOperationsClient client = new ZoneOperationsClientImpl(mockGrpcClient.Object, null);
DeleteZoneOperationResponse response = client.Delete(request.Project, request.Zone, request.Operation);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteAsync()
{
moq::Mock<ZoneOperations.ZoneOperationsClient> mockGrpcClient = new moq::Mock<ZoneOperations.ZoneOperationsClient>(moq::MockBehavior.Strict);
DeleteZoneOperationRequest request = new DeleteZoneOperationRequest
{
Zone = "zone255f4ea8",
Operation = "operation615a23f7",
Project = "projectaa6ff846",
};
DeleteZoneOperationResponse expectedResponse = new DeleteZoneOperationResponse { };
mockGrpcClient.Setup(x => x.DeleteAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<DeleteZoneOperationResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ZoneOperationsClient client = new ZoneOperationsClientImpl(mockGrpcClient.Object, null);
DeleteZoneOperationResponse responseCallSettings = await client.DeleteAsync(request.Project, request.Zone, request.Operation, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
DeleteZoneOperationResponse responseCancellationToken = await client.DeleteAsync(request.Project, request.Zone, request.Operation, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetRequestObject()
{
moq::Mock<ZoneOperations.ZoneOperationsClient> mockGrpcClient = new moq::Mock<ZoneOperations.ZoneOperationsClient>(moq::MockBehavior.Strict);
GetZoneOperationRequest request = new GetZoneOperationRequest
{
Zone = "zone255f4ea8",
Operation = "operation615a23f7",
Project = "projectaa6ff846",
};
Operation expectedResponse = new Operation
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
User = "userb1cb11ee",
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
StartTime = "start_timebd8dd9c4",
OperationGroupId = "operation_group_idd2040cf0",
TargetLink = "target_link9b435dc0",
Progress = 278622268,
Error = new Error(),
EndTime = "end_time89285d30",
Region = "regionedb20d96",
OperationType = "operation_typeece9e153",
Status = Operation.Types.Status.Pending,
HttpErrorMessage = "http_error_messageb5ef3c7f",
TargetId = 6263187990225347157UL,
ClientOperationId = "client_operation_id4e51b631",
StatusMessage = "status_message2c618f86",
HttpErrorStatusCode = 1766362655,
Description = "description2cf9da67",
InsertTime = "insert_time7467185a",
SelfLink = "self_link7e87f12d",
Warnings = { new Warnings(), },
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ZoneOperationsClient client = new ZoneOperationsClientImpl(mockGrpcClient.Object, null);
Operation response = client.Get(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRequestObjectAsync()
{
moq::Mock<ZoneOperations.ZoneOperationsClient> mockGrpcClient = new moq::Mock<ZoneOperations.ZoneOperationsClient>(moq::MockBehavior.Strict);
GetZoneOperationRequest request = new GetZoneOperationRequest
{
Zone = "zone255f4ea8",
Operation = "operation615a23f7",
Project = "projectaa6ff846",
};
Operation expectedResponse = new Operation
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
User = "userb1cb11ee",
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
StartTime = "start_timebd8dd9c4",
OperationGroupId = "operation_group_idd2040cf0",
TargetLink = "target_link9b435dc0",
Progress = 278622268,
Error = new Error(),
EndTime = "end_time89285d30",
Region = "regionedb20d96",
OperationType = "operation_typeece9e153",
Status = Operation.Types.Status.Pending,
HttpErrorMessage = "http_error_messageb5ef3c7f",
TargetId = 6263187990225347157UL,
ClientOperationId = "client_operation_id4e51b631",
StatusMessage = "status_message2c618f86",
HttpErrorStatusCode = 1766362655,
Description = "description2cf9da67",
InsertTime = "insert_time7467185a",
SelfLink = "self_link7e87f12d",
Warnings = { new Warnings(), },
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Operation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ZoneOperationsClient client = new ZoneOperationsClientImpl(mockGrpcClient.Object, null);
Operation responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Operation responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Get()
{
moq::Mock<ZoneOperations.ZoneOperationsClient> mockGrpcClient = new moq::Mock<ZoneOperations.ZoneOperationsClient>(moq::MockBehavior.Strict);
GetZoneOperationRequest request = new GetZoneOperationRequest
{
Zone = "zone255f4ea8",
Operation = "operation615a23f7",
Project = "projectaa6ff846",
};
Operation expectedResponse = new Operation
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
User = "userb1cb11ee",
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
StartTime = "start_timebd8dd9c4",
OperationGroupId = "operation_group_idd2040cf0",
TargetLink = "target_link9b435dc0",
Progress = 278622268,
Error = new Error(),
EndTime = "end_time89285d30",
Region = "regionedb20d96",
OperationType = "operation_typeece9e153",
Status = Operation.Types.Status.Pending,
HttpErrorMessage = "http_error_messageb5ef3c7f",
TargetId = 6263187990225347157UL,
ClientOperationId = "client_operation_id4e51b631",
StatusMessage = "status_message2c618f86",
HttpErrorStatusCode = 1766362655,
Description = "description2cf9da67",
InsertTime = "insert_time7467185a",
SelfLink = "self_link7e87f12d",
Warnings = { new Warnings(), },
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ZoneOperationsClient client = new ZoneOperationsClientImpl(mockGrpcClient.Object, null);
Operation response = client.Get(request.Project, request.Zone, request.Operation);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAsync()
{
moq::Mock<ZoneOperations.ZoneOperationsClient> mockGrpcClient = new moq::Mock<ZoneOperations.ZoneOperationsClient>(moq::MockBehavior.Strict);
GetZoneOperationRequest request = new GetZoneOperationRequest
{
Zone = "zone255f4ea8",
Operation = "operation615a23f7",
Project = "projectaa6ff846",
};
Operation expectedResponse = new Operation
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
User = "userb1cb11ee",
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
StartTime = "start_timebd8dd9c4",
OperationGroupId = "operation_group_idd2040cf0",
TargetLink = "target_link9b435dc0",
Progress = 278622268,
Error = new Error(),
EndTime = "end_time89285d30",
Region = "regionedb20d96",
OperationType = "operation_typeece9e153",
Status = Operation.Types.Status.Pending,
HttpErrorMessage = "http_error_messageb5ef3c7f",
TargetId = 6263187990225347157UL,
ClientOperationId = "client_operation_id4e51b631",
StatusMessage = "status_message2c618f86",
HttpErrorStatusCode = 1766362655,
Description = "description2cf9da67",
InsertTime = "insert_time7467185a",
SelfLink = "self_link7e87f12d",
Warnings = { new Warnings(), },
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Operation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ZoneOperationsClient client = new ZoneOperationsClientImpl(mockGrpcClient.Object, null);
Operation responseCallSettings = await client.GetAsync(request.Project, request.Zone, request.Operation, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Operation responseCancellationToken = await client.GetAsync(request.Project, request.Zone, request.Operation, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void WaitRequestObject()
{
moq::Mock<ZoneOperations.ZoneOperationsClient> mockGrpcClient = new moq::Mock<ZoneOperations.ZoneOperationsClient>(moq::MockBehavior.Strict);
WaitZoneOperationRequest request = new WaitZoneOperationRequest
{
Zone = "zone255f4ea8",
Operation = "operation615a23f7",
Project = "projectaa6ff846",
};
Operation expectedResponse = new Operation
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
User = "userb1cb11ee",
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
StartTime = "start_timebd8dd9c4",
OperationGroupId = "operation_group_idd2040cf0",
TargetLink = "target_link9b435dc0",
Progress = 278622268,
Error = new Error(),
EndTime = "end_time89285d30",
Region = "regionedb20d96",
OperationType = "operation_typeece9e153",
Status = Operation.Types.Status.Pending,
HttpErrorMessage = "http_error_messageb5ef3c7f",
TargetId = 6263187990225347157UL,
ClientOperationId = "client_operation_id4e51b631",
StatusMessage = "status_message2c618f86",
HttpErrorStatusCode = 1766362655,
Description = "description2cf9da67",
InsertTime = "insert_time7467185a",
SelfLink = "self_link7e87f12d",
Warnings = { new Warnings(), },
};
mockGrpcClient.Setup(x => x.Wait(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ZoneOperationsClient client = new ZoneOperationsClientImpl(mockGrpcClient.Object, null);
Operation response = client.Wait(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task WaitRequestObjectAsync()
{
moq::Mock<ZoneOperations.ZoneOperationsClient> mockGrpcClient = new moq::Mock<ZoneOperations.ZoneOperationsClient>(moq::MockBehavior.Strict);
WaitZoneOperationRequest request = new WaitZoneOperationRequest
{
Zone = "zone255f4ea8",
Operation = "operation615a23f7",
Project = "projectaa6ff846",
};
Operation expectedResponse = new Operation
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
User = "userb1cb11ee",
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
StartTime = "start_timebd8dd9c4",
OperationGroupId = "operation_group_idd2040cf0",
TargetLink = "target_link9b435dc0",
Progress = 278622268,
Error = new Error(),
EndTime = "end_time89285d30",
Region = "regionedb20d96",
OperationType = "operation_typeece9e153",
Status = Operation.Types.Status.Pending,
HttpErrorMessage = "http_error_messageb5ef3c7f",
TargetId = 6263187990225347157UL,
ClientOperationId = "client_operation_id4e51b631",
StatusMessage = "status_message2c618f86",
HttpErrorStatusCode = 1766362655,
Description = "description2cf9da67",
InsertTime = "insert_time7467185a",
SelfLink = "self_link7e87f12d",
Warnings = { new Warnings(), },
};
mockGrpcClient.Setup(x => x.WaitAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Operation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ZoneOperationsClient client = new ZoneOperationsClientImpl(mockGrpcClient.Object, null);
Operation responseCallSettings = await client.WaitAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Operation responseCancellationToken = await client.WaitAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Wait()
{
moq::Mock<ZoneOperations.ZoneOperationsClient> mockGrpcClient = new moq::Mock<ZoneOperations.ZoneOperationsClient>(moq::MockBehavior.Strict);
WaitZoneOperationRequest request = new WaitZoneOperationRequest
{
Zone = "zone255f4ea8",
Operation = "operation615a23f7",
Project = "projectaa6ff846",
};
Operation expectedResponse = new Operation
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
User = "userb1cb11ee",
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
StartTime = "start_timebd8dd9c4",
OperationGroupId = "operation_group_idd2040cf0",
TargetLink = "target_link9b435dc0",
Progress = 278622268,
Error = new Error(),
EndTime = "end_time89285d30",
Region = "regionedb20d96",
OperationType = "operation_typeece9e153",
Status = Operation.Types.Status.Pending,
HttpErrorMessage = "http_error_messageb5ef3c7f",
TargetId = 6263187990225347157UL,
ClientOperationId = "client_operation_id4e51b631",
StatusMessage = "status_message2c618f86",
HttpErrorStatusCode = 1766362655,
Description = "description2cf9da67",
InsertTime = "insert_time7467185a",
SelfLink = "self_link7e87f12d",
Warnings = { new Warnings(), },
};
mockGrpcClient.Setup(x => x.Wait(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ZoneOperationsClient client = new ZoneOperationsClientImpl(mockGrpcClient.Object, null);
Operation response = client.Wait(request.Project, request.Zone, request.Operation);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task WaitAsync()
{
moq::Mock<ZoneOperations.ZoneOperationsClient> mockGrpcClient = new moq::Mock<ZoneOperations.ZoneOperationsClient>(moq::MockBehavior.Strict);
WaitZoneOperationRequest request = new WaitZoneOperationRequest
{
Zone = "zone255f4ea8",
Operation = "operation615a23f7",
Project = "projectaa6ff846",
};
Operation expectedResponse = new Operation
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
User = "userb1cb11ee",
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
StartTime = "start_timebd8dd9c4",
OperationGroupId = "operation_group_idd2040cf0",
TargetLink = "target_link9b435dc0",
Progress = 278622268,
Error = new Error(),
EndTime = "end_time89285d30",
Region = "regionedb20d96",
OperationType = "operation_typeece9e153",
Status = Operation.Types.Status.Pending,
HttpErrorMessage = "http_error_messageb5ef3c7f",
TargetId = 6263187990225347157UL,
ClientOperationId = "client_operation_id4e51b631",
StatusMessage = "status_message2c618f86",
HttpErrorStatusCode = 1766362655,
Description = "description2cf9da67",
InsertTime = "insert_time7467185a",
SelfLink = "self_link7e87f12d",
Warnings = { new Warnings(), },
};
mockGrpcClient.Setup(x => x.WaitAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Operation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ZoneOperationsClient client = new ZoneOperationsClientImpl(mockGrpcClient.Object, null);
Operation responseCallSettings = await client.WaitAsync(request.Project, request.Zone, request.Operation, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Operation responseCancellationToken = await client.WaitAsync(request.Project, request.Zone, request.Operation, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
/*
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 *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.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using Microsoft.Research.DryadLinq.Internal;
namespace Microsoft.Research.DryadLinq
{
/// <summary>
/// DryadLinqBinaryReader is the main interface for user provided custom serializers.
/// It is also used for DryadLINQ internal autoserialization to read primitive types.
/// </summary>
public unsafe sealed class DryadLinqBinaryReader
{
private NativeBlockStream m_nativeStream;
private Encoding m_encoding;
private Decoder m_decoder;
private DataBlockInfo m_curDataBlockInfo;
private byte* m_curDataBlock; // The current read buffer. This is requested from the native stream as it depletes,
// and individual ReadXXX methods deserialize primitives out of this buffer
private Int32 m_curBlockSize; // Size of the current read buffer.
private Int32 m_curBlockPos; // Current position on the read buffer. This is updated by individual
// ReadXXX methods as they pull bytes for primitives they are reading
private bool m_isClosed;
internal DryadLinqBinaryReader(NativeBlockStream stream)
: this(stream, Encoding.UTF8)
{
}
internal DryadLinqBinaryReader(NativeBlockStream stream, Encoding encoding)
{
this.m_nativeStream = stream;
this.m_encoding = encoding;
this.m_decoder = encoding.GetDecoder();
this.m_curDataBlockInfo.DataBlock = null;
this.m_curDataBlockInfo.BlockSize = -1;
this.m_curDataBlockInfo.ItemHandle = IntPtr.Zero;
this.m_curDataBlock = this.m_curDataBlockInfo.DataBlock;
this.m_curBlockSize = this.m_curDataBlockInfo.BlockSize;
this.m_curBlockPos = -1;
this.m_isClosed = false;
}
internal DryadLinqBinaryReader(IntPtr vertexInfo, UInt32 portNum)
: this(new DryadLinqChannel(vertexInfo, portNum, true), Encoding.UTF8)
{
}
internal DryadLinqBinaryReader(IntPtr vertexInfo, UInt32 portNum, Encoding encoding)
: this(new DryadLinqChannel(vertexInfo, portNum, true), encoding)
{
}
/// <summary>
/// The finalizer that frees native resources.
/// </summary>
~DryadLinqBinaryReader()
{
// Only release native resoure here
if (this.m_curDataBlockInfo.ItemHandle != IntPtr.Zero)
{
this.m_nativeStream.ReleaseDataBlock(this.m_curDataBlockInfo.ItemHandle);
this.m_curDataBlockInfo.ItemHandle = IntPtr.Zero;
}
}
////////////////////////////////////////////////////////////////////////////////
//
// Internal methods
//
internal Int64 GetTotalLength()
{
return this.m_nativeStream.GetTotalLength();
}
internal long Length
{
get { return this.m_curBlockSize; }
}
internal void Close()
{
if (!this.m_isClosed)
{
this.m_isClosed = true;
this.m_nativeStream.ReleaseDataBlock(this.m_curDataBlockInfo.ItemHandle);
this.m_nativeStream.Close();
}
GC.SuppressFinalize(this);
}
/// <summary>
/// Private helper to request a new data block from the native stream.
/// - it releases the current data block back to the native stream code
/// (which owns the lifecycle of read buffers),
/// - then requests a new buffer from the native stream
/// - and updates the internal read buffer pointer (m_curDataBlock), size (m_curDataSize)
/// and position, all of which are needed by subsequent Read*() calls coming from the user
/// </summary>
private unsafe void GetNextDataBlock()
{
this.m_nativeStream.ReleaseDataBlock(this.m_curDataBlockInfo.ItemHandle);
this.m_curDataBlockInfo.ItemHandle = IntPtr.Zero;
this.m_curDataBlockInfo = this.m_nativeStream.ReadDataBlock();
this.m_curDataBlock = this.m_curDataBlockInfo.DataBlock;
this.m_curBlockSize = this.m_curDataBlockInfo.BlockSize;
this.m_curBlockPos = 0;
}
internal string GetChannelURI()
{
return this.m_nativeStream.GetURI();
}
////////////////////////////////////////////////////////////////////////////////
//
// Public methods
//
/// <summary>
/// Returns a string that represents this DryadLinqBinaryReader object.
/// </summary>
/// <returns>The string representation of this reader</returns>
public override string ToString()
{
return this.m_nativeStream.ToString();
}
/// <summary>
/// Helper used by DryadLinqRecordReader and generated vertex code to check whether the
/// reader reached the end of stream.
/// Returns true if the reader is at the end of the stream, and false is there is
/// more data to read.
/// This check may cause a new data block to be fetched if the call happens while
/// we're at the end of the current read buffer.
/// </summary>
internal bool EndOfStream()
{
if (this.m_curBlockPos < this.m_curBlockSize)
{
return false;
}
if (this.m_curBlockSize == 0)
{
return true;
}
this.GetNextDataBlock();
return (this.m_curBlockSize <= 0);
}
/// <summary>
/// Reads a byte from the current reader and advances the current position of the
/// reader by one byte.
/// </summary>
/// <returns>The next byte read from the current reader.</returns>
public byte ReadUByte()
{
if (this.m_curBlockPos == this.m_curBlockSize)
{
this.GetNextDataBlock();
if (this.m_curBlockSize <= 0)
{
throw new DryadLinqException(DryadLinqErrorCode.EndOfStreamEncountered,
String.Format(SR.EndOfStreamEncountered,
GetChannelURI()));
}
}
return this.m_curDataBlock[this.m_curBlockPos++];
}
/// <summary>
/// Reads a signed byte from the current reader and advances the current
/// position of the reader by one byte.
/// </summary>
/// <returns>The next signed byte read from the current reader.</returns>
public sbyte ReadSByte()
{
if (this.m_curBlockPos == this.m_curBlockSize)
{
this.GetNextDataBlock();
if (this.m_curBlockSize <= 0)
{
throw new DryadLinqException(DryadLinqErrorCode.EndOfStreamEncountered,
String.Format(SR.EndOfStreamEncountered,
GetChannelURI()));
}
}
return (sbyte)this.m_curDataBlock[this.m_curBlockPos++];
}
/// <summary>
/// Reads a boolean value from the current reader and advances the current
/// position of the reader by one byte.
/// </summary>
/// <returns>true iff the byte is nonzero.</returns>
public unsafe bool ReadBool()
{
if (this.m_curBlockPos == this.m_curBlockSize)
{
this.GetNextDataBlock();
if (this.m_curBlockSize <= 0)
{
throw new DryadLinqException(DryadLinqErrorCode.EndOfStreamEncountered,
String.Format(SR.EndOfStreamEncountered,
GetChannelURI()));
}
}
byte res = this.m_curDataBlock[this.m_curBlockPos++];
return (res == 0) ? false : true;
}
/// <summary>
/// Reads a character from the current reader and advances the current position of the reader
/// according to the encoding and the character.
/// </summary>
/// <returns>A character read from the current reader.</returns>
public char ReadChar()
{
char ch;
char *pCh = &ch;
while (true)
{
// request a new buffer from the native stream if we're at the end of the current one
if (this.m_curBlockPos == this.m_curBlockSize)
{
this.GetNextDataBlock();
if (this.m_curBlockSize <= 0)
{
throw new DryadLinqException(DryadLinqErrorCode.EndOfStreamEncountered,
String.Format(SR.EndOfStreamEncountered,
GetChannelURI()));
}
}
// decode a character and update current position
int numChars = this.m_decoder.GetChars(this.m_curDataBlock + this.m_curBlockPos, 1, pCh, 1, false);
this.m_curBlockPos++;
if (numChars == 1) return ch;
}
}
/// <summary>
/// Reads a 16-bit signed integer from the current reader.
/// </summary>
/// <returns>A 16-bit signed integer.</returns>
public short ReadInt16()
{
ushort low, high;
if (this.m_curBlockSize < this.m_curBlockPos + 2)
{
low = this.ReadUByte();
high = this.ReadUByte();
}
else
{
low = this.m_curDataBlock[this.m_curBlockPos++];
high = this.m_curDataBlock[this.m_curBlockPos++];
}
return (short)(low | (high << 8));
}
/// <summary>
/// Reads a 16-bit unsigned integer from the current reader.
/// </summary>
/// <returns>A 16-bit unsigned integer.</returns>
public ushort ReadUInt16()
{
ushort low, high;
if (this.m_curBlockSize < this.m_curBlockPos + 2)
{
low = this.ReadUByte();
high = this.ReadUByte();
}
else
{
low = this.m_curDataBlock[this.m_curBlockPos++];
high = this.m_curDataBlock[this.m_curBlockPos++];
}
return (ushort)(low | (high << 8));
}
/// <summary>
/// Reads a 32-bit signed integer from the current reader.
/// </summary>
/// <returns>A 32-bit signed integer.</returns>
public int ReadInt32()
{
int b1, b2, b3, b4;
if (this.m_curBlockSize < this.m_curBlockPos + 4)
{
b1 = this.ReadUByte();
b2 = this.ReadUByte() << 8;
b3 = this.ReadUByte() << 16;
b4 = this.ReadUByte() << 24;
}
else
{
b1 = this.m_curDataBlock[this.m_curBlockPos++];
b2 = this.m_curDataBlock[this.m_curBlockPos++] << 8;
b3 = this.m_curDataBlock[this.m_curBlockPos++] << 16;
b4 = this.m_curDataBlock[this.m_curBlockPos++] << 24;
}
return (int)(b1 | b2 | b3 | b4);
}
/// <summary>
/// Reads a 32-bit signed integer from the current reader. Assumes that the integer
/// is represented in the compact format as written by WriteCompact of a DryadLinqBinaryWriter.
/// </summary>
/// <returns>A 32-bit signed integer.</returns>
public unsafe int ReadCompactInt32()
{
int b1, b2, b3, b4;
b1 = this.ReadUByte();
if (b1 < 0x80)
{
return b1;
}
else
{
b1 = (b1 & 0x7F) << 24;
if (this.m_curBlockSize < this.m_curBlockPos + 3)
{
b2 = this.ReadUByte() << 16;
b3 = this.ReadUByte() << 8;
b4 = this.ReadUByte();
}
else
{
b2 = this.m_curDataBlock[this.m_curBlockPos++] << 16;
b3 = this.m_curDataBlock[this.m_curBlockPos++] << 8;
b4 = this.m_curDataBlock[this.m_curBlockPos++];
}
return (int)(b1 | b2 | b3 | b4);
}
}
/// <summary>
/// Reads a 32-bit unsigned integer from the current reader.
/// </summary>
/// <returns>A 32-bit unsigned integer.</returns>
public uint ReadUInt32()
{
int b1, b2, b3, b4;
if (this.m_curBlockSize < this.m_curBlockPos + 4)
{
b1 = this.ReadUByte();
b2 = this.ReadUByte() << 8;
b3 = this.ReadUByte() << 16;
b4 = this.ReadUByte() << 24;
}
else
{
b1 = this.m_curDataBlock[this.m_curBlockPos++];
b2 = this.m_curDataBlock[this.m_curBlockPos++] << 8;
b3 = this.m_curDataBlock[this.m_curBlockPos++] << 16;
b4 = this.m_curDataBlock[this.m_curBlockPos++] << 24;
}
return (uint)(b1 | b2 | b3 | b4);
}
/// <summary>
/// Reads a 64-bit signed integer from the current reader.
/// </summary>
/// <returns>A 64-bit signed integer.</returns>
public long ReadInt64()
{
uint lo, hi;
if (this.m_curBlockSize < this.m_curBlockPos + 8)
{
lo = this.ReadUInt32();
hi = this.ReadUInt32();
}
else
{
lo = (uint)(this.m_curDataBlock[this.m_curBlockPos++] |
this.m_curDataBlock[this.m_curBlockPos++] << 8 |
this.m_curDataBlock[this.m_curBlockPos++] << 16 |
this.m_curDataBlock[this.m_curBlockPos++] << 24);
hi = (uint)(this.m_curDataBlock[this.m_curBlockPos++] |
this.m_curDataBlock[this.m_curBlockPos++] << 8 |
this.m_curDataBlock[this.m_curBlockPos++] << 16 |
this.m_curDataBlock[this.m_curBlockPos++] << 24);
}
return (long)(((ulong)hi) << 32 | lo);
}
/// <summary>
/// Reads a 64-bit unsigned integer from the current reader.
/// </summary>
/// <returns>A 64-bit unsigned integer.</returns>
public ulong ReadUInt64()
{
uint lo, hi;
if (this.m_curBlockSize < this.m_curBlockPos + 8)
{
lo = this.ReadUInt32();
hi = this.ReadUInt32();
}
else
{
lo = (uint)(this.m_curDataBlock[this.m_curBlockPos++] |
this.m_curDataBlock[this.m_curBlockPos++] << 8 |
this.m_curDataBlock[this.m_curBlockPos++] << 16 |
this.m_curDataBlock[this.m_curBlockPos++] << 24);
hi = (uint)(this.m_curDataBlock[this.m_curBlockPos++] |
this.m_curDataBlock[this.m_curBlockPos++] << 8 |
this.m_curDataBlock[this.m_curBlockPos++] << 16 |
this.m_curDataBlock[this.m_curBlockPos++] << 24);
}
return ((ulong)hi) << 32 | lo;
}
/// <summary>
/// Reads a 32-bit floating point number from the current reader.
/// </summary>
/// <returns>A 32-bit floating point number.</returns>
public float ReadSingle()
{
int tmp = this.ReadInt32();
return *((float*)&tmp);
}
/// <summary>
/// Reads a decimal number from the current reader.
/// </summary>
/// <returns>A decimal number.</returns>
public decimal ReadDecimal()
{
decimal val;
this.ReadRawBytes((byte*)&val, sizeof(decimal));
return val;
}
/// <summary>
/// Reads a 64-bit floating point number from the current reader.
/// </summary>
/// <returns>A 64-bit floating point number.</returns>
public double ReadDouble()
{
ulong tmp = this.ReadUInt64();
return *((double*)&tmp);
}
private const Int64 TicksMask = 0x3FFFFFFFFFFFFFFF;
private const Int32 KindShift = 62;
/// <summary>
/// Reads a value of DateTime from the current reader.
/// </summary>
/// <returns>A value of DateTime.</returns>
public DateTime ReadDateTime()
{
UInt64 value = this.ReadUInt64();
return new DateTime((Int64)(value & TicksMask), (DateTimeKind)(value >> KindShift));
}
/// <summary>
/// Reads a value of SqlDateTime from the current reader.
/// </summary>
/// <returns>A value of SqlDateTime.</returns>
public SqlDateTime ReadSqlDateTime()
{
int dayTicks = this.ReadInt32();
int timeTicks = this.ReadInt32();
return new SqlDateTime(dayTicks, timeTicks);
}
/// <summary>
/// Reads a value of Guid from the current reader.
/// </summary>
/// <returns>A value of Guid.</returns>
public Guid ReadGuid()
{
Guid guid;
ReadRawBytes((byte*)&guid, sizeof(Guid));
return guid;
}
/// <summary>
/// Reads <paramref name="charCount"/> chars into <paramref name="destBuffer"/> starting at <paramref name="offset"/>.
/// </summary>
/// <param name="destBuffer">The pre-allocated char array to read data into.</param>
/// <param name="offset">The starting offset at which to begin reading chars into <paramref name="destBuffer"/>.</param>
/// <param name="charCount">The maximum number of chars to read. </param>
/// <returns>The number of chars that was actually read.</returns>
public unsafe int ReadChars(char[] destBuffer, int offset, int charCount)
{
if (destBuffer == null)
{
throw new ArgumentNullException("destBuffer");
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset");
}
if (charCount < 0)
{
throw new ArgumentOutOfRangeException("charCount");
}
if (destBuffer.Length < (offset + charCount))
{
throw new ArgumentOutOfRangeException("destBuffer",
String.Format(SR.ArrayLengthVsCountAndOffset,
"destBuffer", offset + charCount,
"offset", "charCount"));
}
Int32 numChars = charCount;
Int32 numMaxBytes = m_encoding.GetMaxByteCount(charCount); // note numMaxBytes may not always equal the actual bytes consumed in the conversion
int numCharsDecoded = 0;
while (numChars > 0)
{
// check if there's enough data in the read buffer to finish the conversion
// if so do it in a single step, adjust read buffer location and return
int numAvailBytes = this.m_curBlockSize - this.m_curBlockPos;
if (numAvailBytes >= numMaxBytes)
{
int bytesUsed;
int charsConverted;
bool completed;
fixed (char *pChars = destBuffer)
{
this.m_decoder.Convert(this.m_curDataBlock + this.m_curBlockPos,
numMaxBytes,
pChars + offset + numCharsDecoded,
numChars,
false,
out bytesUsed,
out charsConverted,
out completed);
}
this.m_curBlockPos += bytesUsed;
numCharsDecoded = charCount;
return numCharsDecoded;
}
// The remaining bytes in the read buffer don't *seem to be* enough to satisfy
// the request, but attempt to convert all the remaining bytes, and adjust
// current pos etc. before requesting a new buffer
if (numAvailBytes != 0)
{
int bytesUsed;
int charsConverted;
bool completed;
fixed (char *pChars = destBuffer)
{
this.m_decoder.Convert(this.m_curDataBlock + this.m_curBlockPos,
numAvailBytes,
pChars + offset + numCharsDecoded,
numChars,
false,
out bytesUsed,
out charsConverted,
out completed);
}
numChars -= charsConverted; // update the number of remaining chars to convert
numMaxBytes -= bytesUsed; // adjust the max bytes estimate
numAvailBytes -= bytesUsed;
numCharsDecoded += charsConverted;
// Even though it seemed like the remaining # of bytes wouldn't be enough,
// there's still a chance we decoded all the chars we needed
// (this can happen if the decoding used less bytes / char than the max estimate)
// So we need to check for this and return if it's indeed the case
if (numChars == 0)
{
this.m_curBlockPos += bytesUsed;
break;
}
}
// if we've reached this line there must be 0 bytes remaining, if not there's a mismatch in the math above
Debug.Assert(numAvailBytes == 0);
// if we are here it means we've depleted all the bytes
this.GetNextDataBlock();
if (this.m_curBlockSize <= 0)
{
// this means we're at the end of the file. simply break so that we
// return the number of chars read so far
break;
}
}
return numCharsDecoded;
}
/// <summary>
/// Reads a string value from the current reader.
/// </summary>
/// <returns>A string.</returns>
public string ReadString()
{
// First read the length of the string and the number of bytes needed
Int32 numChars = this.ReadCompactInt32();
Int32 numBytes = this.ReadCompactInt32();
// allocate the string
string str = new String('a', numChars);
int numCharsDecoded = 0;
while (numChars > 0)
{
int numAvailBytes = this.m_curBlockSize - this.m_curBlockPos;
// Check whether current read buffer has enough data to fill the string
// buffer to the end. If so, invoke decoder to copy from bytes to the
// destination chars, update m_curBlockPos and return
if (numAvailBytes >= numBytes)
{
fixed (char *pChars = str)
{
this.m_decoder.GetChars(this.m_curDataBlock + this.m_curBlockPos,
numBytes,
pChars + numCharsDecoded,
numChars,
false);
}
this.m_curBlockPos += numBytes;
break;
}
// If there wasn't enough data in the read buffer convert the remaining bytes to chars
// and request a new data block from the stream.
if (numAvailBytes != 0)
{
Int32 num = 0;
fixed (char *pChars = str)
{
num = this.m_decoder.GetChars(this.m_curDataBlock + this.m_curBlockPos,
numAvailBytes,
pChars + numCharsDecoded,
numChars,
false);
}
numChars -= num;
numBytes -= numAvailBytes;
numCharsDecoded += num;
}
this.GetNextDataBlock();
if (this.m_curBlockSize <= 0)
{
throw new DryadLinqException(DryadLinqErrorCode.EndOfStreamEncountered,
String.Format(SR.EndOfStreamEncountered,
GetChannelURI()));
}
}
return str;
}
/// <summary>
/// Reads <paramref name="byteCount"/> bytes into <paramref name="destBuffer"/> starting at <paramref name="offset"/>.
/// </summary>
/// <param name="destBuffer">The pre-allocated byte array to read data into.</param>
/// <param name="offset">The starting offset at which to begin reading bytes into <paramref name="destBuffer"/>.</param>
/// <param name="byteCount">The maximum number of bytes to read. </param>
/// <returns>The number of bytes that was actually read.</returns>
public int ReadBytes(byte[] destBuffer, int offset, int byteCount)
{
if (destBuffer == null)
{
throw new ArgumentNullException("destBuffer");
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset");
}
if (byteCount < 0)
{
throw new ArgumentOutOfRangeException("byteCount");
}
if (destBuffer.Length < (offset + byteCount))
{
throw new ArgumentOutOfRangeException("destBuffer",
String.Format(SR.ArrayLengthVsCountAndOffset,
"destBuffer", offset + byteCount,
"offset", "byteCount"));
}
int numBytes = byteCount;
int numBytesRead = 0;
fixed (byte *pBytes = &destBuffer[offset])
{
while (numBytes > 0)
{
int numAvailBytes = this.m_curBlockSize - this.m_curBlockPos;
// Check if there are enough bytes in the read buffer to satisfy the
// caller's request. If so, do the copy, update m_curBlockPos and return
if (numAvailBytes >= numBytes)
{
DryadLinqUtil.memcpy(this.m_curDataBlock + this.m_curBlockPos,
pBytes + numBytesRead,
numBytes);
this.m_curBlockPos += numBytes;
numBytesRead = byteCount;
break;
}
// The remaining data in the read buffer isn't enough to fill the user's request...
// Copy the all the remaining bytes to the destination buffer, and request a
// new read buffer from the stream.
// Note that we don't need to update m_curBlockPos here because the
// GetNextDataBlock call will reset it.
DryadLinqUtil.memcpy(this.m_curDataBlock + this.m_curBlockPos,
pBytes + numBytesRead,
numAvailBytes);
// update numBytes/numBytesRead
numBytes -= numAvailBytes;
numBytesRead += numAvailBytes;
this.GetNextDataBlock();
if (this.m_curBlockSize <= 0)
{
// if the file stream returned an empty buffer it means we are at the
// end of the file. Just return the total number of bytes read, and the
// caller will decide how to handle it.
break;
}
// continue with the loop to keep filling the remaining parts of the
// destination buffer
}
}
return numBytesRead;
}
/// <summary>
/// public helper to read into a byte*, mainly used to read preallocated fixed size,
/// non-integer types (Array, Guid, decimal etc)
/// </summary>
/// <param name="pBytes">The pointer to the pre-allocated byte array to read data into</param>
/// <param name="numBytes">The number of bytes to read</param>
public void ReadRawBytes(byte* pBytes, int numBytes)
{
int numBytesRead = 0;
while (numBytes > 0)
{
int numAvailBytes = this.m_curBlockSize - this.m_curBlockPos;
// if m_curDataBlock has enough bytes to fill the remainder of the user's request,
// simply copy and exit.
if (numAvailBytes >= numBytes)
{
DryadLinqUtil.memcpy(this.m_curDataBlock + this.m_curBlockPos,
pBytes + numBytesRead,
numBytes);
this.m_curBlockPos += numBytes;
break;
}
// if m_curDataBlock has less data than required, copy all the remaining bytes
// to user's buffer, update BytesRead counter, and request a new data block from
// the native stream now that m_curDataBlock is depleted
// Note that we don't need to update m_curBlockPos after memcpy() becase the
// subsequent GetNextDataBlock() call will reset it
DryadLinqUtil.memcpy(this.m_curDataBlock + this.m_curBlockPos,
pBytes + numBytesRead,
numAvailBytes);
this.GetNextDataBlock();
if (this.m_curBlockSize <= 0)
{
throw new DryadLinqException(DryadLinqErrorCode.EndOfStreamEncountered,
String.Format(SR.EndOfStreamEncountered,
GetChannelURI()));
}
numBytes -= numAvailBytes;
numBytesRead += numAvailBytes;
// here we go on to do another loop, as we can only reach when the user's request
// isn't fulfilled.
}
}
}
}
| |
using UnityEngine;
using UnityEngine.Networking;
#if UNITY_EDITOR
using UnityEditor;
#endif
using System;
//we need System.IO now aswell to load cached bundleIndexes
using System.IO;
using System.Collections;
using System.Collections.Generic;
/* The AssetBundle Manager provides a High-Level API for working with AssetBundles.
The AssetBundle Manager will take care of loading AssetBundles and their associated
Asset Dependencies.
Initialize()
Initializes the AssetBundle index object. This contains the standard Unity AssetBundleIndex data as well as an index of what assets are in what asset bundles
LoadAssetAsync()
Loads a given asset from a given AssetBundle and handles all the dependencies.
LoadLevelAsync()
Loads a given scene from a given AssetBundle and handles all the dependencies.
LoadDependencies()
Loads all the dependent AssetBundles for a given AssetBundle.
BaseDownloadingURL
Sets the base downloading url which is used for automatic downloading dependencies.
SimulateAssetBundleInEditor
Sets Simulation Mode in the Editor.
Variants
Sets the active variant.
RemapVariantName()
Resolves the correct AssetBundle according to the active variant.
*/
namespace UMA.AssetBundles
{
/// <summary>
/// After an asset bundles download or cache retrieval opertaion is complete a LoadaedAssetBundle object is created for it.
/// Loaded assetBundle contains the references count which can be used to unload dependent assetBundles automatically.
/// </summary>
public class LoadedAssetBundle
{
public AssetBundle m_AssetBundle;
public int m_ReferencedCount;
//to enable a json index we need to have a string/data field here
public string m_data;
internal event Action unload;
//Added a bool here to make it possible to unload loaded assets from the bundle too
internal void OnUnload(bool unloadAllLoadedObjects = false)
{
m_AssetBundle.Unload(unloadAllLoadedObjects);
if (unload != null)
unload();
}
public LoadedAssetBundle(AssetBundle assetBundle)
{
m_AssetBundle = assetBundle;
m_ReferencedCount = 1;
}
public LoadedAssetBundle(string data)
{
m_AssetBundle = null;
m_data = data;
m_ReferencedCount = 1;
}
}
/// <summary>
/// Class takes care of loading assetBundle and its dependencies automatically, loading variants automatically.
/// </summary>
public class AssetBundleManager : MonoBehaviour
{
public enum LogMode { All, JustErrors };
public enum LogType { Info, Warning, Error };
static LogMode m_LogMode = LogMode.All;
static string m_BaseDownloadingURL = "";
//If we are using Encrypted Bundles DynamicAssetLoader will set the encryption key here.
static string m_BundleEncryptionKey = "";
static string[] m_ActiveVariants = { };
static AssetBundleIndex m_AssetBundleIndex = null;
#if UNITY_EDITOR
static int m_SimulateAssetBundleInEditor = -1;
const string kSimulateAssetBundles = "SimulateAssetBundles";
static SimpleWebServer webserver;
#endif
static Dictionary<string, LoadedAssetBundle> m_LoadedAssetBundles = new Dictionary<string, LoadedAssetBundle>();
static Dictionary<string, string> m_DownloadingErrors = new Dictionary<string, string>();
static List<string> m_DownloadingBundles = new List<string>();
static List<AssetBundleLoadOperation> m_InProgressOperations = new List<AssetBundleLoadOperation>();
static Dictionary<string, string[]> m_Dependencies = new Dictionary<string, string[]>();
//a list of bundles that failed to download because we had no internet connection
//when we get a connection again we can restart them
static List<string> m_FailedBundleDownloads = new List<string>();
//made this static so re-initializing this does not cause multiples to be created
static GameObject generatedGO = null;
//the IConnectionChecker is an interface that can be used to tell us if there is an Internet connection and provides some methods we can trigger when things go wrong
static IConnectionChecker m_ConnectionChecker = null;
public static IConnectionChecker ConnectionChecker
{
get { return m_ConnectionChecker; }
set { m_ConnectionChecker = value; }
}
static bool m_UsingCachedIndex = false;
/// <summary>
/// Is the AssetBundleManager using a cached index (because its offline)?
/// </summary>
public static bool UsingCachedIndex { get { return m_UsingCachedIndex; } }
//these are used to store the values sent to the Initialize method when we started offline,
//so that if/when we go online we can download and cache the live index
static string m_SessionIndexAssetBundleName = "";
static bool m_SessionUseJsonIndex;
static string m_SessionJsonIndexUrl = "";
public static bool SimulateOverride;
public static LogMode logMode
{
get { return m_LogMode; }
set { m_LogMode = value; }
}
/// <summary>
/// The base downloading url which is used to generate the full
/// downloading url with the assetBundle names.
/// </summary>
public static string BaseDownloadingURL
{
get { return m_BaseDownloadingURL; }
set { m_BaseDownloadingURL = value; }
}
public static string BundleEncryptionKey
{
get { return m_BundleEncryptionKey; }
set { m_BundleEncryptionKey = value; }
}
public delegate string OverrideBaseDownloadingURLDelegate(string bundleName);
/// <summary>
/// Implements per-bundle base downloading URL override.
/// The subscribers must return null values for unknown bundle names;
/// </summary>
public static event OverrideBaseDownloadingURLDelegate overrideBaseDownloadingURL;
/// <summary>
/// Variants which is used to define the active variants.
/// </summary>
public static string[] ActiveVariants
{
get { return m_ActiveVariants; }
set { m_ActiveVariants = value; }
}
/// <summary>
/// AssetBundleIndex object which can be used to check the contents of
/// any asset bundle without having to download it first.
/// </summary>
public static AssetBundleIndex AssetBundleIndexObject
{
get { return m_AssetBundleIndex; }
set {
m_UsingCachedIndex = false;
m_AssetBundleIndex = value;
}
}
private static void Log(LogType logType, string text)
{
if (Debug.isDebugBuild)
{
if (logType == LogType.Error)
Debug.LogError("[AssetBundleManager] " + text);
else if (m_LogMode == LogMode.All)
Debug.Log("[AssetBundleManager] " + text);
}
}
#if UNITY_EDITOR
// Flag to indicate if we want to simulate assetBundles in Editor without building them actually.
//we dont want an editorPrefs for this now because there is no way of changing it!
public static bool SimulateAssetBundleInEditor
{
get
{
if (SimulateOverride)
return true;
if (Application.isPlaying == false) // always simulate when out of play mode
return true;
if (m_SimulateAssetBundleInEditor == -1)
m_SimulateAssetBundleInEditor = 0;
return m_SimulateAssetBundleInEditor != 0;
}
set
{
int newValue = value ? 1 : 0;
if (newValue != m_SimulateAssetBundleInEditor)
{
m_SimulateAssetBundleInEditor = newValue;
}
}
}
#else
public static bool SimulateAssetBundleInEditor
{
get { return false;}
}
#endif
private static string GetStreamingAssetsPath()
{
if (Application.isEditor)
return "file://" + System.Environment.CurrentDirectory.Replace("\\", "/"); // Use the build output folder directly.
#if !UNITY_2017_2_OR_NEWER
if (Application.isWebPlayer)
return System.IO.Path.GetDirectoryName(Application.absoluteURL).Replace("\\", "/") + "/StreamingAssets";
#endif
if (Application.isMobilePlatform || Application.isConsolePlatform)
return Application.streamingAssetsPath;
// For standalone player.
return "file://" + Application.streamingAssetsPath;
}
/// <summary>
/// Sets base downloading URL to a directory relative to the streaming assets directory.Asset bundles are loaded from a local directory.
/// </summary>
public static void SetSourceAssetBundleDirectory(string relativePath)
{
BaseDownloadingURL = GetStreamingAssetsPath() + relativePath;
}
/// <summary>
/// Sets base downloading URL to a web URL. The directory pointed to by this URL
/// on the web-server should have the same structure as the AssetBundles directory
/// in the demo project root. For example, AssetBundles/iOS/xyz-scene must map to
/// absolutePath/iOS/xyz-scene.
/// If you are using assetBundle encryption this should be absolutePath/Encrypted/iOS/xyz-scene
/// </summary>
/// <param name="absolutePath"></param>
public static void SetSourceAssetBundleURL(string absolutePath)
{
string encryptedSuffix = m_BundleEncryptionKey != "" ? "Encrypted/" : "";
if (absolutePath != "")
{
if (!absolutePath.EndsWith("/"))
absolutePath += "/";
if (Debug.isDebugBuild)
Debug.Log("[AssetBundleManager] SetSourceAssetBundleURL to " + absolutePath + encryptedSuffix + Utility.GetPlatformName() + "/");
BaseDownloadingURL = absolutePath + encryptedSuffix + Utility.GetPlatformName() + "/";
}
}
/// <summary>
/// Retrieves an asset bundle that has previously been requested via LoadAssetBundle.
/// Returns null if the asset bundle or one of its dependencies have not been downloaded yet.
/// </summary>
/// <param name="assetBundleName"></param>
/// <param name="error"></param>
/// <returns></returns>
static public LoadedAssetBundle GetLoadedAssetBundle(string assetBundleName, out string error)
{
if (m_DownloadingErrors.TryGetValue(assetBundleName, out error))
{
if (!error.StartsWith("-"))
{
m_DownloadingErrors[assetBundleName] = "-" + error;
error = m_DownloadingErrors[assetBundleName];
#if UNITY_EDITOR
if (assetBundleName == Utility.GetPlatformName().ToLower() + "index")
{
if (EditorPrefs.GetBool(Application.dataPath+"LocalAssetBundleServerEnabled") == false || SimpleWebServer.serverStarted == false)//when the user restarts Unity this might be true even if the server has not actually been started
{
if (SimulateAssetBundleInEditor)
{
//we already outputted a message in DynamicAssetloader
SimulateOverride = true;
}
else
{
//I think here we dont have an internet connection and we need one to download this bundle
if (Debug.isDebugBuild)
Debug.LogWarning("AssetBundleManager could not download the AssetBundleIndex from the Remote Server URL you have set in DynamicAssetLoader. Have you set the URL correctly and uploaded your AssetBundles?");
error = "AssetBundleManager could not download the AssetBundleIndex from the Remote Server URL you have set in DynamicAssetLoader. Have you set the URL correctly and uploaded your AssetBundles?";
}
}
else
{
//Otherwise the AssetBundles themselves will not have been built.
if (Debug.isDebugBuild)
Debug.LogWarning("Switched to Simulation mode because no AssetBundles were found. Have you build them? (Go to 'Assets/AssetBundles/Build AssetBundles').");
error = "Switched to Simulation mode because no AssetBundles were found.Have you build them? (Go to 'Assets/AssetBundles/Build AssetBundles').";
//this needs to hide the loading infobox- or something needs too..
SimulateOverride = true;
}
}
else
#endif
if (Debug.isDebugBuild)
Debug.LogWarning("Could not return " + assetBundleName + " because of error:" + error);
}
return null;
}
LoadedAssetBundle bundle = null;
m_LoadedAssetBundles.TryGetValue(assetBundleName, out bundle);
if (bundle == null)
return null;
// No dependencies are recorded, only the bundle itself is required.
string[] dependencies = null;
if (!m_Dependencies.TryGetValue(assetBundleName, out dependencies))
return bundle;
// Otherwise Make sure all dependencies are loaded
foreach (var dependency in dependencies)
{
if (m_DownloadingErrors.TryGetValue(dependency, out error))
return null;
// Wait all the dependent assetBundles being loaded.
LoadedAssetBundle dependentBundle = null;
m_LoadedAssetBundles.TryGetValue(dependency, out dependentBundle);
if (dependentBundle == null)
return null;
}
return bundle;
}
/// <summary>
/// Returns the download progress of an assetbundle, optionally including any bundles it is dependent on
/// </summary>
static public float GetBundleDownloadProgress(string assetBundleName, bool andDependencies)
{
float overallProgress = 0;
string error;
if (m_DownloadingErrors.TryGetValue(assetBundleName, out error))
{
return 0;
}
if (m_LoadedAssetBundles.ContainsKey(assetBundleName))
{
overallProgress = 1f;
}
else
{
//find out its progress
foreach (AssetBundleLoadOperation operation in m_InProgressOperations)
{
if (operation.GetType() == typeof(AssetBundleDownloadOperation) || operation.GetType().IsSubclassOf(typeof(AssetBundleDownloadOperation)))
{
AssetBundleDownloadOperation typedOperation = (AssetBundleDownloadOperation)operation;
if (typedOperation.assetBundleName == assetBundleName)
overallProgress = typedOperation.downloadProgress == 1f ? 0.99f : typedOperation.downloadProgress;
}
}
}
//deal with dependencies if necessary
if (andDependencies)
{
string[] dependencies = null;
m_Dependencies.TryGetValue(assetBundleName, out dependencies);
if (dependencies != null)
{
if (dependencies.Length > 0)
{
foreach (string dependency in dependencies)
{
if (m_LoadedAssetBundles.ContainsKey(dependency))
{
overallProgress += 1;
}
else //It must be in progress
{
foreach (AssetBundleLoadOperation operation in m_InProgressOperations)
{
if (operation.GetType() == typeof(AssetBundleDownloadOperation) || operation.GetType().IsSubclassOf(typeof(AssetBundleDownloadOperation)))
{
AssetBundleDownloadOperation typedOperation = (AssetBundleDownloadOperation)operation;
if (typedOperation.assetBundleName == dependency)
overallProgress += typedOperation.downloadProgress == 1f ? 0.99f : typedOperation.downloadProgress;
}
}
}
}
//divide by num dependencies +1
overallProgress = overallProgress / (dependencies.Length + 1);
}
}
}
return overallProgress;
}
/// <summary>
/// Returns the current LoadedAssetBundlesDictionary
/// </summary>
static public Dictionary<string, LoadedAssetBundle> GetLoadedAssetBundles()
{
return m_LoadedAssetBundles;
}
/// <summary>
/// Returns true if certain asset bundle has been downloaded regardless of whether its
/// whether it's dependencies have been loaded.
/// </summary>
static public bool IsAssetBundleDownloaded(string assetBundleName)
{
return m_LoadedAssetBundles.ContainsKey(assetBundleName);
}
/// <summary>
/// Returns true if any asset bundles are still downloading optionally filtered by name.
/// </summary>
static public bool AreBundlesDownloading(string assetBundleName = "")
{
if (assetBundleName == "")
{
return (m_DownloadingBundles.Count > 0 && m_InProgressOperations.Count > 0);
}
else
{
if (m_DownloadingBundles.Contains(assetBundleName))
{
return true;
}
else
{
foreach (string key in m_DownloadingBundles)
{
if (key.IndexOf(assetBundleName + "/") > -1)
{
return true;
}
}
return false;
}
}
}
static public bool IsOperationInProgress(AssetBundleLoadOperation operation)
{
if (m_InProgressOperations.Contains(operation))
return true;
else
return false;
}
/// <summary>
/// Initializes asset bundle namager and starts download of index asset bundle
/// </summary>
/// <returns>Returns the index asset bundle download operation object.</returns>
static public AssetBundleLoadIndexOperation Initialize()
{
return Initialize(Utility.GetPlatformName(), false, "");
}
static public AssetBundleLoadIndexOperation Initialize(bool useJsonIndex)
{
return Initialize(Utility.GetPlatformName(), useJsonIndex, "");
}
static public AssetBundleLoadIndexOperation Initialize(bool useJsonIndex, string jsonIndexUrl)
{
return Initialize(Utility.GetPlatformName(), useJsonIndex, jsonIndexUrl);
}
static public AssetBundleLoadIndexOperation Initialize(string indexAssetBundleName, bool useJsonIndex, string jsonIndexUrl)
{
if (!SimulateAssetBundleInEditor)//dont show the indicator if we are not using asset bundles - TODO we need a more comprehensive solution for this scenerio
{
if(AssetBundleLoadingIndicator.Instance)
AssetBundleLoadingIndicator.Instance.Show(indexAssetBundleName.ToLower() + "index", "Initializing...", "", "Initialized");
}
#if UNITY_EDITOR
Log(LogType.Info, "Simulation Mode: " + (SimulateAssetBundleInEditor ? "Enabled" : "Disabled"));
#endif
//Dont make another one if we are 're-initializing'
if (generatedGO == null)
{
generatedGO = new GameObject("AssetBundleManager", typeof(AssetBundleManager));
DontDestroyOnLoad(generatedGO);
}
else
{
//
}
#if UNITY_EDITOR
// If we're in Editor simulation mode, we don't need the index assetBundle.
if (SimulateAssetBundleInEditor)
return null;
#endif
//if we have a connectionChecker use it to check we have a connection- otherwise assume we do
bool connected = m_ConnectionChecker != null ? m_ConnectionChecker.InternetAvailable : true;
if (connected)
{
//as of 05/08/2016 we dont use Unitys AssetBundleManifest at all we just use our AssetBundleIndex
LoadAssetBundle(indexAssetBundleName.ToLower() + "index", true, useJsonIndex, jsonIndexUrl);
var operation = new AssetBundleLoadIndexOperation(indexAssetBundleName.ToLower() + "index", indexAssetBundleName + "Index", typeof(AssetBundleIndex), useJsonIndex);
m_InProgressOperations.Add(operation);
return operation;
}
else //if we dont have a connection try to load a cached index otherwise trigger m_ConnectionChecker.ShowConnectionRequiredUI()
{
m_SessionIndexAssetBundleName = indexAssetBundleName;
m_SessionUseJsonIndex = useJsonIndex;
m_SessionJsonIndexUrl = jsonIndexUrl;
//if we are not using index caching always trigger the ShowConnectionRequiredUI because we cant do anything without an index.
if (!m_ConnectionChecker.UseBundleIndexCaching)
{
if (Debug.isDebugBuild)
Debug.LogWarning("[AssetBundleManager] Could not load the bundle index because there was no connection, and UseBundleIndexCaching was off");
m_ConnectionChecker.ShowConnectionRequiredUI();
return null;
}
else
{
//this operation will load the cached index if there is one
var operation = new AssetBundleLoadCachedIndexOperation(indexAssetBundleName.ToLower() + "index", indexAssetBundleName + "Index", typeof(AssetBundleIndex), useJsonIndex);
//so if(m_AssetBundleIndex == null) after that we need to call m_ConnectionChecker.ShowConnectionRequiredUI() because we cant do anything without an index
if (m_AssetBundleIndex == null)
{
if (Debug.isDebugBuild)
Debug.LogWarning("[AssetBundleManager] Could not load the bundle index because there was no connection, and there was no cached index");
m_ConnectionChecker.ShowConnectionRequiredUI();
}
else
{
m_UsingCachedIndex = true;
m_LoadedAssetBundles.Add(indexAssetBundleName.ToLower() + "index", new LoadedAssetBundle("CachedIndex"));
}
m_InProgressOperations.Add(operation);
return operation;
}
}
}
// Temporarily work around a il2cpp bug
static protected void LoadAssetBundle(string assetBundleName)
{
LoadAssetBundle(assetBundleName, false);
}
/// <summary>
/// Starts the download of the asset bundle identified by the given name. Also downloads any asset bundles the given asset bundle is dependent on.
/// </summary>
/// <param name="assetBundleName">The bundle to load- if bundles are encrypted this should be the name of the UNENCRYPTED bundle.</param>
/// <param name="isLoadingAssetBundleIndex">If true does not check for the existance of the assetBundleIndex. This should be false unless you ARE downloading the index</param>
/// <param name="useJsonIndex">if true will attempt to download an asset called [platformname]index.json unless a specific json Url is supplied in the following param</param>
/// <param name="jsonIndexUrl">provides a specific url to download a json index from</param>
public static void LoadAssetBundle(string assetBundleName, bool isLoadingAssetBundleIndex = false, bool useJsonIndex = false, string jsonIndexUrl = "")
{
#if UNITY_EDITOR
string fromLocalServer = (EditorPrefs.GetBool(Application.dataPath+"LocalAssetBundleServerEnabled") && SimpleWebServer.serverStarted) ? "from LocalServer " : "";
string encrypted = BundleEncryptionKey != "" ? " (Encrypted)" : "";
Log(LogType.Info, "Loading Asset Bundle " + fromLocalServer + (isLoadingAssetBundleIndex ? "Index: " : ": ") + assetBundleName + encrypted);
// If we're in Editor simulation mode, we don't have to really load the assetBundle and its dependencies.
if (SimulateAssetBundleInEditor)
return;
#endif
if (!isLoadingAssetBundleIndex)
{
if (m_AssetBundleIndex == null)
{
if (Debug.isDebugBuild)
Debug.LogError("Please initialize AssetBundleIndex by calling AssetBundleManager.Initialize()");
return;
}
}
// Check if the assetBundle has already been processed.
bool isAlreadyProcessed = LoadAssetBundleInternal(assetBundleName, isLoadingAssetBundleIndex, useJsonIndex, jsonIndexUrl);
// Load dependencies.
if (!isAlreadyProcessed && !isLoadingAssetBundleIndex)
LoadDependencies(assetBundleName);
}
/// <summary>
/// Returns base downloading URL for the given asset bundle.
/// This URL may be overridden on per-bundle basis via overrideBaseDownloadingURL event.
/// </summary>
protected static string GetAssetBundleBaseDownloadingURL(string bundleName)
{
if (overrideBaseDownloadingURL != null)
{
foreach (OverrideBaseDownloadingURLDelegate method in overrideBaseDownloadingURL.GetInvocationList())
{
string res = method(bundleName);
if (!String.IsNullOrEmpty(res))
return res;
}
}
return m_BaseDownloadingURL;
}
/// <summary>
/// Checks who is responsible for determination of the correct asset bundle variant that should be loaded on this platform.
///
/// On most platforms, this is done by the AssetBundleManager itself. However, on
/// certain platforms (iOS at the moment) it's possible that an external asset bundle
/// variant resolution mechanism is used. In these cases, we use base asset bundle
/// name (without the variant tag) as the bundle identifier. The platform-specific
/// code is responsible for correctly loading the bundle.
/// </summary>
static protected bool UsesExternalBundleVariantResolutionMechanism(string baseAssetBundleName)
{
#if ENABLE_IOS_APP_SLICING
var url = GetAssetBundleBaseDownloadingURL(baseAssetBundleName);
if (url.ToLower().StartsWith("res://") ||
url.ToLower().StartsWith("odr://"))
return true;
#endif
return false;
}
/// <summary>
/// Remaps the asset bundle name to the best fitting asset bundle variant.
/// </summary>
static protected string RemapVariantName(string assetBundleName)
{
string[] bundlesWithVariant = m_AssetBundleIndex.GetAllAssetBundlesWithVariant();
// Get base bundle name
string baseName = assetBundleName.Split('.')[0];
if (UsesExternalBundleVariantResolutionMechanism(baseName))
return baseName;
int bestFit = int.MaxValue;
int bestFitIndex = -1;
// Loop all the assetBundles with variant to find the best fit variant assetBundle.
for (int i = 0; i < bundlesWithVariant.Length; i++)
{
string[] curSplit = bundlesWithVariant[i].Split('.');
string curBaseName = curSplit[0];
string curVariant = curSplit[1];
if (curBaseName != baseName)
continue;
int found = System.Array.IndexOf(m_ActiveVariants, curVariant);
// If there is no active variant found. We still want to use the first
if (found == -1)
found = int.MaxValue - 1;
if (found < bestFit)
{
bestFit = found;
bestFitIndex = i;
}
}
if (bestFit == int.MaxValue - 1)
{
Log(LogType.Warning, "Ambigious asset bundle variant chosen because there was no matching active variant: " + bundlesWithVariant[bestFitIndex]);
}
if (bestFitIndex != -1)
{
return bundlesWithVariant[bestFitIndex];
}
else
{
return assetBundleName;
}
}
/// <summary>
/// Sets up download operation for the given asset bundle if it's not downloaded already.
/// </summary>
static protected bool LoadAssetBundleInternal(string assetBundleToFind, bool isLoadingAssetBundleIndex = false, bool useJsonIndex = false, string jsonIndexUrl = "")
{
//encrypted bundles have the suffix 'encrypted' appended to the name TODO this should probably go in the index though and be settable in the UMAAssetBundleManagerSettings window
string assetBundleToGet = assetBundleToFind;
if(BundleEncryptionKey != "" && isLoadingAssetBundleIndex == false)
{
assetBundleToGet = m_AssetBundleIndex.GetAssetBundleEncryptedName(assetBundleToFind);
if (Debug.isDebugBuild)
Debug.Log("assetBundleToFind was " + assetBundleToFind + " assetBundleToGet was " + assetBundleToGet);
}
else if(BundleEncryptionKey != "" && isLoadingAssetBundleIndex == true)
{
assetBundleToGet = assetBundleToFind + "encrypted";
}
// Already loaded.
LoadedAssetBundle bundle = null;
m_LoadedAssetBundles.TryGetValue(assetBundleToFind, out bundle);//encrypted or not this will have the assetbundlename without the 'encrypted' suffix
if (bundle != null && bundle.m_AssetBundle != null)
{
if (Debug.isDebugBuild)
Debug.Log("[AssetBundleManager] " + assetBundleToFind + " was already loaded");
bundle.m_ReferencedCount++;
return true;
}
// @TODO: Do we need to consider the referenced count of WWWs?
// users can call LoadAssetAsync()/LoadLevelAsync() several times then wait them to be finished which might have duplicate WWWs.
if (m_DownloadingBundles.Contains(assetBundleToFind))
{
if (Debug.isDebugBuild)
Debug.Log("[AssetBundleManager] " + assetBundleToFind + " was already downloading");
return true;
}
string bundleBaseDownloadingURL = GetAssetBundleBaseDownloadingURL(assetBundleToFind);
//TODO These dont support encrypted bundles yet
if (bundleBaseDownloadingURL.ToLower().StartsWith("odr://"))
{
#if ENABLE_IOS_ON_DEMAND_RESOURCES
Log(LogType.Info, "Requesting bundle " + assetBundleToGet + " through ODR");
m_InProgressOperations.Add(new AssetBundleDownloadFromODROperation(assetBundleToGet));
#else
new ApplicationException("Can't load bundle " + assetBundleToFind + " through ODR: this Unity version or build target doesn't support it.");
#endif
}
else if (bundleBaseDownloadingURL.ToLower().StartsWith("res://"))
{
#if ENABLE_IOS_APP_SLICING
Log(LogType.Info, "Requesting bundle " + assetBundleToGet + " through asset catalog");
m_InProgressOperations.Add(new AssetBundleOpenFromAssetCatalogOperation(assetBundleToGet));
#else
new ApplicationException("Can't load bundle " + assetBundleToFind + " through asset catalog: this Unity version or build target doesn't support it.");
#endif
}
else
{
if (!bundleBaseDownloadingURL.EndsWith("/"))
bundleBaseDownloadingURL += "/";
string url = bundleBaseDownloadingURL + assetBundleToGet;
UnityWebRequest download = null;
// For index assetbundle, always download it as we don't have hash for it.
if (isLoadingAssetBundleIndex)
{
if (useJsonIndex && jsonIndexUrl != "")
{
url = jsonIndexUrl.Replace("[PLATFORM]", Utility.GetPlatformName());
}
else if (useJsonIndex)
{
url = url+ ".json";
}
#if UNITY_2018_1_OR_NEWER
download = UnityWebRequestAssetBundle.GetAssetBundle(url);
#else
download = UnityWebRequest.GetAssetBundle(url);
#endif
if (!String.IsNullOrEmpty(download.error) || download == null)
{
if (!String.IsNullOrEmpty(download.error))
Log(LogType.Warning, download.error);
else
Log(LogType.Warning, " index new WWW(url) was NULL");
}
}
else
{
#if UNITY_2018_1_OR_NEWER
download = UnityWebRequestAssetBundle.GetAssetBundle(url, m_AssetBundleIndex.GetAssetBundleHash(assetBundleToFind), 0);
#else
download = UnityWebRequest.GetAssetBundle(url, m_AssetBundleIndex.GetAssetBundleHash(assetBundleToFind), 0);
#endif
}
#if UNITY_2017_2_OR_NEWER
download.SendWebRequest();
#else
download.Send();
#endif
m_InProgressOperations.Add(new AssetBundleDownloadFromWebOperation(assetBundleToFind/* + encryptedSuffix*/, download, useJsonIndex));
}
m_DownloadingBundles.Add(assetBundleToFind);
return false;
}
/// <summary>
/// Where we get all the dependencies from the index for the given asset bundle and load them all.
/// </summary>
/// <param name="assetBundleName"></param>
static protected void LoadDependencies(string assetBundleName)
{
if (m_AssetBundleIndex == null)
{
Log(LogType.Error, "Please initialize AssetBundleIndex by calling AssetBundleManager.Initialize()");
return;
}
// Get dependecies from the AssetBundleIndex object..
string[] dependencies = m_AssetBundleIndex.GetAllDependencies(assetBundleName);
if (dependencies.Length == 0)
return;
for (int i = 0; i < dependencies.Length; i++)
dependencies[i] = RemapVariantName(dependencies[i]);
// Record and load all dependencies.
//If a failed download is added again this dictionary will already have an entry for it so check for that
if (m_Dependencies.ContainsKey(assetBundleName))
{
m_Dependencies[assetBundleName] = dependencies;
}
else
{
m_Dependencies.Add(assetBundleName, dependencies);
}
for (int i = 0; i < dependencies.Length; i++)
LoadAssetBundleInternal(dependencies[i], false);
}
//This was not working with DynamicAssetloader is that still the case?
/// <summary>
/// Unloads all unused AssetBundles compressed data to free up memory.
/// </summary>
static public void UnloadAllAssetBundles()
{
#if UNITY_EDITOR
// If we're in Editor simulation mode, we wont have actually loaded and bundles
if (SimulateAssetBundleInEditor)
return;
#endif
List<string> bundlesToUnload = new List<string>();
foreach (KeyValuePair<string, LoadedAssetBundle> kp in m_LoadedAssetBundles)
{
if (kp.Key.IndexOf(Utility.GetPlatformName().ToLower() + "index") == -1)//dont try to unload the index...
bundlesToUnload.Add(kp.Key);
}
foreach (string bundleName in bundlesToUnload)
{
UnloadAssetBundleInternal(bundleName);
UnloadDependencies(bundleName);//I think its unloading dependencies thats causing an issue with UMA
}
}
/// <summary>
/// Unloads assetbundle and its dependencies
/// </summary>
/// <param name="assetBundleName"></param>
static public void UnloadAssetBundle(string assetBundleName)
{
#if UNITY_EDITOR
// If we're in Editor simulation mode, we have actually loaded any asset bundles
if (SimulateAssetBundleInEditor)
return;
#endif
UnloadAssetBundleInternal(assetBundleName);
UnloadDependencies(assetBundleName);
}
static protected void UnloadDependencies(string assetBundleName)
{
string[] dependencies = null;
if (!m_Dependencies.TryGetValue(assetBundleName, out dependencies))
return;
// Loop dependencies.
foreach (var dependency in dependencies)
{
UnloadAssetBundleInternal(dependency);
}
//This may not actually get unloaded if its actually referenced so check that
if(!m_LoadedAssetBundles.ContainsKey(assetBundleName))
m_Dependencies.Remove(assetBundleName);
}
//Added a bool here to make it possible to unload loaded assets from the bundle too
static protected void UnloadAssetBundleInternal(string assetBundleName, bool disregardRefrencedStatus = false, bool unloadAllLoadedObjects = false)
{
string error;
LoadedAssetBundle bundle = GetLoadedAssetBundle(assetBundleName, out error);
if (bundle == null)
return;
if (--bundle.m_ReferencedCount == 0 || disregardRefrencedStatus)
{
bundle.OnUnload(unloadAllLoadedObjects);
m_LoadedAssetBundles.Remove(assetBundleName);
Log(LogType.Info, assetBundleName + " has been unloaded successfully");
}
}
void Update()
{
// Update all in progress operations
for (int i = 0; i < m_InProgressOperations.Count;)
{
var operation = m_InProgressOperations[i];
if (operation.Update())
{
i++;
}
else
{
m_InProgressOperations.RemoveAt(i);
ProcessFinishedOperation(operation);
}
}
if(m_AssetBundleIndex == null)
{
RedownloadAssetBundleIndex();
}
//if we have a connection now and FailedDownloads has stuff in it (which only happens if downloads fail because there is no connection)
//we can start those downloads again
if (m_FailedBundleDownloads.Count > 0 && m_ConnectionChecker != null && m_ConnectionChecker.InternetAvailable && m_ConnectionChecker.RestartFailedDownloads)
{
RestartFailedDownloads();
}
}
/// <summary>
/// If a cached assetBundleIndex was used because the application was running off line, call this method when a connection is
/// established, to make AssetBundleManager download a live version. If the ConnectionChecker.UseBundleIndexCaching is true
/// the downloaded version will be cached.
/// </summary>
public static void RedownloadAssetBundleIndex()
{
#if UNITY_EDITOR
// If we're in Editor simulation mode, we wont have actually loaded any bundles
if (SimulateAssetBundleInEditor)
return;
#endif
//there is no point in doing this unless we have a connection
if (ConnectionChecker == null || ConnectionChecker.InternetAvailable)
{
bool alreadyLoading = false;
for (int i = 0; i < m_InProgressOperations.Count; i++)
{
if (m_InProgressOperations[i].GetType() == typeof(AssetBundleLoadIndexOperation))
alreadyLoading = true;
}
if (!alreadyLoading)
{
//we are also going to need to remove it from downloaded bundles otherwise it will get skipped
m_LoadedAssetBundles.Remove(m_SessionIndexAssetBundleName.ToLower() + "index");
//the operation does not update if the index is not null- can we get away with making it null?
m_AssetBundleIndex = null;
//
//do we do anything if we dont actually have an index right now? Or are we in fact calling Init anyway?
LoadAssetBundle(m_SessionIndexAssetBundleName.ToLower() + "index", true, m_SessionUseJsonIndex, m_SessionJsonIndexUrl);
var operation = new AssetBundleLoadIndexOperation(m_SessionIndexAssetBundleName.ToLower() + "index", m_SessionIndexAssetBundleName + "Index", typeof(AssetBundleIndex), m_SessionUseJsonIndex);
m_InProgressOperations.Add(operation);
}
}
else if (ConnectionChecker != null && !ConnectionChecker.InternetAvailable)
{
//If we dont have an index at all Update will have called this- in that case dont log
if (m_AssetBundleIndex != null)
{
if (Debug.isDebugBuild)
Debug.LogWarning("[AssetbundleManager] RedownloadAssetBundleIndex aborted because there was no Internet Connection!");
}
}
}
/// <summary>
/// Restarts any downloads that failed because there was no cached version and no Internet Connection was available.
/// Requires that the AssetBundleManager has an IConnectionChecker object assigned to check the connection.
/// </summary>
public static void RestartFailedDownloads()
{
if (m_FailedBundleDownloads.Count > 0 && m_ConnectionChecker != null && m_ConnectionChecker.InternetAvailable)
{
if (m_AssetBundleIndex == null)
{
//Update will do this automatically now
}
else
{
for (int i = 0; i < m_FailedBundleDownloads.Count; i++)
{
var assetBundleName = m_FailedBundleDownloads[i];
//remove the bundle from download errors
//remove it from failedDownloads
//start it again
if (m_DownloadingErrors.ContainsKey(assetBundleName))
m_DownloadingErrors.Remove(assetBundleName);
m_FailedBundleDownloads.Remove(assetBundleName);
//we need to remove any dependencies from failedDownloads and errors too
string[] dependencies = null;
m_Dependencies.TryGetValue(assetBundleName, out dependencies);
if (dependencies != null && dependencies.Length > 0)
{
for (int di = 0; di < dependencies.Length; di++)
{
if (m_DownloadingErrors.ContainsKey(dependencies[di]))
m_DownloadingErrors.Remove(dependencies[di]);
if (m_FailedBundleDownloads.Contains(dependencies[di]))
m_FailedBundleDownloads.Remove(dependencies[di]);
}
}
if (Debug.isDebugBuild)
Debug.LogWarning("RELOADING " + assetBundleName + " after connection established");
LoadAssetBundle(assetBundleName);//this will create a new operation which I dont want really
}
}
}
}
/// <summary>
/// CAUTION Only call this method when the active scene is not using any assetBundle assets! Unloads all currently loaded assetBundles and any assets loaded
/// from them and redownloads them if the current index finds that the cached versions are not uptodate.
/// Use this when the user has been offline and a cached index/assetbundles were used, and the user has now gone online.
/// </summary>
public static void RedownloadActiveBundles()
{
//if there is no index we cant do anything
if (m_AssetBundleIndex == null)
return;
//there is no point in doing this unless we have a connection
if (ConnectionChecker == null || ConnectionChecker.InternetAvailable)
{
//if we are using a cached index do we need to update it? Or do we leave it to the dev to do that?
//
List<string> assetBundlesToReload = new List<string>();
foreach (KeyValuePair<string, LoadedAssetBundle> kp in m_LoadedAssetBundles)
{
if (kp.Key.IndexOf(Utility.GetPlatformName().ToLower() + "index") == -1)//dont try to unload the index...
assetBundlesToReload.Add(kp.Key);
}
//Unload them all
for (int i = 0; i < assetBundlesToReload.Count; i++)
{
if (m_Dependencies.ContainsKey(assetBundlesToReload[i]))
m_Dependencies.Remove(assetBundlesToReload[i]);
UnloadAssetBundleInternal(assetBundlesToReload[i], true, true);
}
for (int i = 0; i < assetBundlesToReload.Count; i++)
{
LoadAssetBundle(assetBundlesToReload[i]);
}
}
else if(ConnectionChecker != null && !ConnectionChecker.InternetAvailable)
{
if (Debug.isDebugBuild)
Debug.LogWarning("[AssetbundleManager] RedownloadActiveBundles aborted because there was no Internet Connection!");
}
}
/// <summary>
/// Unloads all assetBundles and any loaded content. CAUTION This will probably break a running game! Should only be used when you want
/// to enable the user to clear their cache of downloaded data and to do that you need to 'unlock' any used asset bundles by unloading them first.
/// </summary>
//TODO Make this work- as soon as they get deleted they get loaded again...
/*public static void ForcefullyUnloadAllAssetBundles()
{
List<string> assetBundlesToUnload = new List<string>();
foreach (KeyValuePair<string, LoadedAssetBundle> kp in m_LoadedAssetBundles)
{
if (kp.Key.IndexOf(Utility.GetPlatformName().ToLower() + "index") == -1)//dont try to unload the index...
assetBundlesToUnload.Add(kp.Key);
}
//Unload them all
for (int i = 0; i < assetBundlesToUnload.Count; i++)
{
if (m_Dependencies.ContainsKey(assetBundlesToUnload[i]))
m_Dependencies.Remove(assetBundlesToUnload[i]);
UnloadAssetBundleInternal(assetBundlesToUnload[i], true, true);
}
}*/
void ProcessFinishedOperation(AssetBundleLoadOperation operation)
{
AssetBundleDownloadOperation download = operation as AssetBundleDownloadOperation;
if (download == null)
return;
if (String.IsNullOrEmpty(download.error))
{
//Debug.Log("[AssetBundleManager] processed downloaded bundle " + download.assetBundleName);
m_LoadedAssetBundles.Add(download.assetBundleName, download.assetBundle);
}
else
{
string msg = string.Format("Failed downloading bundle {0} from {1}: {2}",
download.assetBundleName, download.GetSourceURL(), download.error);
m_DownloadingErrors.Add(download.assetBundleName, msg);
//if this failed and we have no internet connection we can probably assume thats the reason...
//in that case add it to the failedDownloads list so that if we do get an internet connection we can start it again.
if (m_ConnectionChecker != null /*&& !m_ConnectionChecker.InternetAvailable*/)
{
if (!m_ConnectionChecker.InternetAvailable)
//show the user that an internet connection was required to get this bundle
//Its up to the devloper how they use this interface method...
m_ConnectionChecker.ShowConnectionRequiredUI();
else
{
//This will happen when there is an internet connection, that is working (i.e. the connection check passes)
//but for some reason the download is still failing- like if there is a storm and very small amounts of data
//download fine but large amounts fail
if (Debug.isDebugBuild)
Debug.LogError("SHOW DOWNLOAD FAILED UI");
m_ConnectionChecker.ShowDownloadFailedUI(download.assetBundleName);
}
//add it to failed downloads
if (!m_FailedBundleDownloads.Contains(download.assetBundleName))
{
//Debug.LogWarning(msg);//dont think we need to show the warning because it will get shown
//when progress for the bundle is requested- but then maybe ShowConnectionRequiredUI() should only happen when progress is requested
//but then the requesting code might not know which bundle was not cached and caused the error?
//So maybe we should show the warning LOL
m_FailedBundleDownloads.Add(download.assetBundleName);
}
//Dependencies will have failed too
string[] dependencies = null;
m_Dependencies.TryGetValue(download.assetBundleName, out dependencies);
if (dependencies != null && dependencies.Length > 0)
{
for (int i = 0; i < dependencies.Length; i++)
{
if (!m_FailedBundleDownloads.Contains(dependencies[i]))
m_FailedBundleDownloads.Add(dependencies[i]);
}
}
}
}
m_DownloadingBundles.Remove(download.assetBundleName);
}
/// <summary>
/// Starts a load operation for an asset from the given asset bundle.
/// </summary>
static public AssetBundleLoadAssetOperation LoadAssetAsync(string assetBundleName, string assetName, System.Type type)
{
Log(LogType.Info, "Loading " + assetName + " from " + assetBundleName + " bundle");
AssetBundleLoadAssetOperation operation = null;
#if UNITY_EDITOR
if (SimulateAssetBundleInEditor)
{
string[] assetPaths = AssetDatabase.GetAssetPathsFromAssetBundleAndAssetName(assetBundleName, assetName);
if (assetPaths.Length == 0)
{
if (Debug.isDebugBuild)
Debug.LogError("There is no asset with name \"" + assetName + "\" in " + assetBundleName);
return null;
}
// @TODO: Now we only get the main object from the first asset. Should consider type also.
UnityEngine.Object target = AssetDatabase.LoadMainAssetAtPath(assetPaths[0]);
operation = new AssetBundleLoadAssetOperationSimulation(target);
}
else
#endif
{
assetBundleName = RemapVariantName(assetBundleName);
LoadAssetBundle(assetBundleName, false);
operation = new AssetBundleLoadAssetOperationFull(assetBundleName, assetName, type);
m_InProgressOperations.Add(operation);
}
return operation;
}
/// <summary>
/// Starts a load operation for a level from the given asset bundle.
/// </summary>
static public AssetBundleLoadOperation LoadLevelAsync(string assetBundleName, string levelName, bool isAdditive)
{
Log(LogType.Info, "Loading " + levelName + " from " + assetBundleName + " bundle");
AssetBundleLoadOperation operation = null;
#if UNITY_EDITOR
if (SimulateAssetBundleInEditor)
{
operation = new AssetBundleLoadLevelSimulationOperation(assetBundleName, levelName, isAdditive);
}
else
#endif
{
assetBundleName = RemapVariantName(assetBundleName);
LoadAssetBundle(assetBundleName, false);
operation = new AssetBundleLoadLevelOperation(assetBundleName, levelName, isAdditive);
m_InProgressOperations.Add(operation);
}
return operation;
}
#if UNITY_EDITOR
//We can have an EditorHelper so we can see what is actually going on with this thing in the inspector...
public class EditorHelper
{
public List<string> loadedBundles = new List<string>();
public List<string> downloadingBundles = new List<string>();
public List<string> inProgressOperations = new List<string>();
public List<string> failedDownloads = new List<string>();
public bool isUsingCachedIndex;
public string bundleIndexPlayerversion = "0.0";
public EditorHelper()
{
}
public void Update()
{
loadedBundles.Clear();
foreach (KeyValuePair<string, LoadedAssetBundle> kp in m_LoadedAssetBundles)
{
loadedBundles.Add(kp.Key);
}
downloadingBundles.Clear();
downloadingBundles.AddRange(m_DownloadingBundles);//be nice if these showed progress
inProgressOperations.Clear();
for (int i = 0; i < m_InProgressOperations.Count; i++)
{
try
{
inProgressOperations.Add(
((AssetBundleDownloadOperation)m_InProgressOperations[i]).assetBundleName + " : " +
((AssetBundleDownloadOperation)m_InProgressOperations[i]).downloadProgress);
}
catch
{
inProgressOperations.Add("unknown operation");
}
}
failedDownloads.Clear();
failedDownloads.AddRange(m_FailedBundleDownloads);//maybe these could show the error
isUsingCachedIndex = m_UsingCachedIndex;
bundleIndexPlayerversion = m_AssetBundleIndex != null && !string.IsNullOrEmpty(m_AssetBundleIndex.bundlesPlayerVersion) ? m_AssetBundleIndex.bundlesPlayerVersion : "0.0";
}
}
#endif
} // End of AssetBundleManager.
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Core;
using Core.Models;
using Core.Repositories;
using Core.Services;
using Core.Services.Posting;
using Core.Web;
using DAL;
using Microsoft.Extensions.Logging;
using WebSite.ViewModels;
using X.PagedList;
namespace WebSite.AppCode
{
public interface IWebAppPublicationService
{
Task<PublicationViewModel> CreatePublication(NewPostRequest request, User user);
Task<IReadOnlyCollection<Category>> GetCategories();
Task<StaticPagedList<PublicationViewModel>> GetPublications(int? categoryId = null, int page = 1);
Task<IReadOnlyCollection<PublicationViewModel>> FindPublications(params string[] keywords);
Task<PublicationViewModel> GetPublication(int id);
Task<IReadOnlyCollection<VacancyViewModel>> LoadHotVacancies();
Task<IPagedList<VacancyViewModel>> GetVacancies(int page = 1);
Task<VacancyViewModel> GetVacancy(int id);
Task<PlatformViewModel> GetPlatformInformation();
Task<HomePageViewModel> GetHomePageInformation();
}
public class WebAppPublicationService : IWebAppPublicationService
{
private readonly ILocalizationService _localizationService;
private readonly IPublicationService _publicationService;
private readonly ISocialRepository _socialRepository;
private readonly ILanguageAnalyzerService _languageAnalyzer;
private readonly PostingServiceFactory _factory;
private readonly IVacancyService _vacancyService;
private readonly Settings _settings;
private readonly ILogger _logger;
private IReadOnlyCollection<Category> _categories;
public WebAppPublicationService(
ILocalizationService localizationService,
IPublicationService publicationService,
ISocialRepository socialRepository,
PostingServiceFactory factory,
Settings settings,
ILanguageAnalyzerService languageAnalyzer,
IVacancyService vacancyService,
ILogger<WebAppPublicationService> logger)
{
_logger = logger;
_languageAnalyzer = languageAnalyzer;
_vacancyService = vacancyService;
_factory = factory;
_settings = settings;
_socialRepository = socialRepository;
_localizationService = localizationService;
_publicationService = publicationService;
}
public async Task<PublicationViewModel> CreatePublication(NewPostRequest request, User user)
{
var extractor = new X.Web.MetaExtractor.Extractor();
var metadata = await extractor.ExtractAsync(request.Link);
var existingPublication = await _publicationService.Get(new Uri(metadata.Url));
if (existingPublication != null)
{
throw new DuplicateNameException("Publication with this URL already exist");
}
var languageCode = _languageAnalyzer.GetTextLanguage(metadata.Description);
var languageId = await _localizationService.GetLanguageId(languageCode) ?? Core.Language.EnglishId;
var player = EmbeddedPlayerFactory.CreatePlayer(request.Link);
var playerCode = player != null ? await player.GetEmbeddedPlayerUrl(request.Link) : null;
var publication = await _publicationService.CreatePublication(
metadata,
user.Id,
languageId,
playerCode,
request.CategoryId,
request.Comment);
if (publication != null)
{
var model = new PublicationViewModel(publication, _settings.WebSiteUrl);
//If we can embed main content into site page, so we can share this page.
var url = string.IsNullOrEmpty(model.EmbededPlayerCode) ? model.Url : model.ShareUrl;
var services = await GetServices(publication);
foreach (var service in services)
{
await service.Send(request.Comment, url, GetTags(request));
}
return model;
}
throw new Exception("Can't save publication to database");
}
public async Task<IReadOnlyCollection<IPostingService>> GetServices(Publication publication)
{
var categoryId = publication.CategoryId;
var telegramChannels = await _socialRepository.GetTelegramChannels(categoryId);
var facebookPages = await _socialRepository.GetFacebookPages(categoryId);
var twitterAccounts = await _socialRepository.GetTwitterAccounts();
var slackApplications = await _socialRepository.GetSlackApplications();
var services = new List<IPostingService>();
foreach (var telegramChannel in telegramChannels)
{
services.Add(_factory.CreateTelegramService(
telegramChannel.Token,
telegramChannel.Name));
}
foreach (var facebookPage in facebookPages)
{
services.Add(_factory.CreateFacebookService(
facebookPage.Token,
facebookPage.Name));
}
foreach (var twitterAccount in twitterAccounts)
{
services.Add(_factory.CreateTwitterService(
twitterAccount.ConsumerKey,
twitterAccount.ConsumerSecret,
twitterAccount.AccessToken,
twitterAccount.AccessTokenSecret,
twitterAccount.Name,
await _publicationService.GetCategoryTags(categoryId)));
}
foreach (var slack in slackApplications)
{
services.Add(_factory.CreateSlackService(slack.WebHookUrl));
}
return services.ToImmutableList();
}
private static IReadOnlyCollection<string> GetTags(NewPostRequest request)
{
if (request == null || string.IsNullOrWhiteSpace(request.Tags))
{
return ImmutableList<string>.Empty;
}
return request.Tags
.Split(' ')
.Where(o => !string.IsNullOrWhiteSpace(o))
.Select(o => o.Trim())
.ToImmutableList();
}
public async Task<IReadOnlyCollection<Category>> GetCategories()
{
return _categories ??= await _publicationService.GetCategories();
}
private async Task<IReadOnlyCollection<SocialAccount>> GetTelegramChannels() =>
(await _socialRepository.GetTelegramChannels())
.Select(o => new SocialAccount
{
Description = o.Description,
Logo = o.Logo,
Title = o.Title,
Url = $"https://t.me/{o.Name.Replace("@", "")}"
})
.ToImmutableList();
private async Task<IReadOnlyCollection<SocialAccount>> GetFacebookPages() =>
(await _socialRepository.GetFacebookPages())
.Select(o => new SocialAccount
{
Description = o.Description,
Logo = o.Logo,
Title = o.Name,
Url = o.Url
})
.ToImmutableList();
private async Task<IReadOnlyCollection<SocialAccount>> GetTwitterAccounts() =>
(await _socialRepository.GetTwitterAccounts())
.Select(o => new SocialAccount
{
Description = o.Description,
Logo = o.Logo,
Title = o.Name,
Url = o.Url
})
.ToImmutableList();
public async Task<IReadOnlyCollection<PublicationViewModel>> GetTopPublications()
{
var publications = await _publicationService.GetTopPublications();
var categories = await GetCategories();
return publications
.Select(o => new PublicationViewModel(o, _settings.WebSiteUrl, categories))
.ToImmutableList();
}
public async Task<IReadOnlyCollection<PublicationViewModel>> FindPublications(params string[] keywords)
{
var publications = await _publicationService.FindPublications(keywords);
var categories = await GetCategories();
return publications
.Select(o => new PublicationViewModel(o, _settings.WebSiteUrl, categories))
.ToImmutableList();
}
public async Task<PublicationViewModel> GetPublication(int id)
{
var publication = await _publicationService.Get(id);
var categories = await GetCategories();
if (publication != null)
{
await _publicationService.IncreaseViewCount(id);
return new PublicationViewModel(publication, _settings.WebSiteUrl, categories);
}
return null;
}
public Task IncreaseViewCount(int publicationId)
{
return _publicationService.IncreaseViewCount(publicationId);
}
public async Task<IReadOnlyCollection<VacancyViewModel>> LoadHotVacancies()
{
var vacancies = (await _vacancyService.GetHotVacancies())
.Select(o => new VacancyViewModel(o, _settings.WebSiteUrl))
.ToImmutableList();
return vacancies;
}
public async Task<IPagedList<VacancyViewModel>> GetVacancies(int page)
{
var vacancies = await _vacancyService.GetVacancies(page);
var subset = vacancies.Select(o => new VacancyViewModel(o, _settings.WebSiteUrl));
return new StaticPagedList<VacancyViewModel>(subset, vacancies);
}
public async Task<VacancyViewModel> GetVacancy(int id)
{
var vacancy = await _vacancyService.Get(id);
await _vacancyService.IncreaseViewCount(id);
var image = _vacancyService.GetVacancyImage();
return new VacancyViewModel(vacancy, _settings.WebSiteUrl, image);
}
public async Task<PlatformViewModel> GetPlatformInformation()
{
return new PlatformViewModel
{
Telegram = await GetTelegramChannels(),
Facebook = await GetFacebookPages(),
Twitter = await GetTwitterAccounts()
};
}
public async Task<HomePageViewModel> GetHomePageInformation()
{
return new HomePageViewModel
{
Publications = await GetPublications(),
TopPublications = await GetTopPublications()
};
}
public async Task<StaticPagedList<PublicationViewModel>> GetPublications(int? categoryId = null, int page = 1)
{
var categories = await GetCategories();
var pagedResult = await _publicationService.GetPublications(categoryId, page);
var publications = pagedResult
.Select(o => new PublicationViewModel(o, _settings.WebSiteUrl, categories))
.ToImmutableList();
return new StaticPagedList<PublicationViewModel>(publications, pagedResult);
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Targets
{
using System;
using System.Collections.Generic;
using System.Threading;
using NUnit.Framework;
#if !NUNIT
using SetUp = Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
using TearDown = Microsoft.VisualStudio.TestTools.UnitTesting.TestCleanupAttribute;
#endif
using NLog.Common;
using NLog.Internal;
using NLog.Targets;
[TestFixture]
public class TargetTests : NLogTestBase
{
[Test]
public void InitializeTest()
{
var target = new MyTarget();
target.Initialize(null);
// initialize was called once
Assert.AreEqual(1, target.InitializeCount);
Assert.AreEqual(1, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
}
[Test]
public void InitializeFailedTest()
{
var target = new MyTarget();
target.ThrowOnInitialize = true;
try
{
target.Initialize(null);
Assert.Fail("Expected exception.");
}
catch (InvalidOperationException)
{
}
// after exception in Initialize(), the target becomes non-functional and all Write() operations
var exceptions = new List<Exception>();
target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
Assert.AreEqual(0, target.WriteCount);
Assert.AreEqual(1, exceptions.Count);
Assert.IsNotNull(exceptions[0]);
Assert.AreEqual("Target " + target + " failed to initialize.", exceptions[0].Message);
Assert.AreEqual("Init error.", exceptions[0].InnerException.Message);
}
[Test]
public void DoubleInitializeTest()
{
var target = new MyTarget();
target.Initialize(null);
target.Initialize(null);
// initialize was called once
Assert.AreEqual(1, target.InitializeCount);
Assert.AreEqual(1, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
}
[Test]
public void DoubleCloseTest()
{
var target = new MyTarget();
target.Initialize(null);
target.Close();
target.Close();
// initialize and close were called once each
Assert.AreEqual(1, target.InitializeCount);
Assert.AreEqual(1, target.CloseCount);
Assert.AreEqual(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
}
[Test]
public void CloseWithoutInitializeTest()
{
var target = new MyTarget();
target.Close();
// nothing was called
Assert.AreEqual(0, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
}
[Test]
public void WriteWithoutInitializeTest()
{
var target = new MyTarget();
List<Exception> exceptions = new List<Exception>();
target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
target.WriteAsyncLogEvents(new[]
{
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
});
// write was not called
Assert.AreEqual(0, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
Assert.AreEqual(4, exceptions.Count);
exceptions.ForEach(Assert.IsNull);
}
[Test]
public void WriteOnClosedTargetTest()
{
var target = new MyTarget();
target.Initialize(null);
target.Close();
var exceptions = new List<Exception>();
target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
target.WriteAsyncLogEvents(
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
Assert.AreEqual(1, target.InitializeCount);
Assert.AreEqual(1, target.CloseCount);
// write was not called
Assert.AreEqual(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
// but all callbacks were invoked with null values
Assert.AreEqual(4, exceptions.Count);
exceptions.ForEach(Assert.IsNull);
}
[Test]
public void FlushTest()
{
var target = new MyTarget();
List<Exception> exceptions = new List<Exception>();
target.Initialize(null);
target.Flush(exceptions.Add);
// flush was called
Assert.AreEqual(1, target.FlushCount);
Assert.AreEqual(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
Assert.AreEqual(1, exceptions.Count);
exceptions.ForEach(Assert.IsNull);
}
[Test]
public void FlushWithoutInitializeTest()
{
var target = new MyTarget();
List<Exception> exceptions = new List<Exception>();
target.Flush(exceptions.Add);
Assert.AreEqual(1, exceptions.Count);
exceptions.ForEach(Assert.IsNull);
// flush was not called
Assert.AreEqual(0, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
}
[Test]
public void FlushOnClosedTargetTest()
{
var target = new MyTarget();
target.Initialize(null);
target.Close();
Assert.AreEqual(1, target.InitializeCount);
Assert.AreEqual(1, target.CloseCount);
List<Exception> exceptions = new List<Exception>();
target.Flush(exceptions.Add);
Assert.AreEqual(1, exceptions.Count);
exceptions.ForEach(Assert.IsNull);
// flush was not called
Assert.AreEqual(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
}
[Test]
public void LockingTest()
{
var target = new MyTarget();
target.Initialize(null);
var mre = new ManualResetEvent(false);
Exception backgroundThreadException = null;
Thread t = new Thread(() =>
{
try
{
target.BlockingOperation(1000);
}
catch (Exception ex)
{
backgroundThreadException = ex;
}
finally
{
mre.Set();
}
});
target.Initialize(null);
t.Start();
Thread.Sleep(50);
List<Exception> exceptions = new List<Exception>();
target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
target.WriteAsyncLogEvents(new[]
{
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
});
target.Flush(exceptions.Add);
target.Close();
exceptions.ForEach(Assert.IsNull);
mre.WaitOne();
if (backgroundThreadException != null)
{
Assert.Fail(backgroundThreadException.ToString());
}
}
public class MyTarget : Target
{
private int inBlockingOperation;
public int InitializeCount { get; set; }
public int CloseCount { get; set; }
public int FlushCount { get; set; }
public int WriteCount { get; set; }
public int WriteCount2 { get; set; }
public bool ThrowOnInitialize { get; set; }
public int WriteCount3 { get; set; }
protected override void InitializeTarget()
{
if (this.ThrowOnInitialize)
{
throw new InvalidOperationException("Init error.");
}
Assert.AreEqual(0, this.inBlockingOperation);
this.InitializeCount++;
base.InitializeTarget();
}
protected override void CloseTarget()
{
Assert.AreEqual(0, this.inBlockingOperation);
this.CloseCount++;
base.CloseTarget();
}
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
Assert.AreEqual(0, this.inBlockingOperation);
this.FlushCount++;
base.FlushAsync(asyncContinuation);
}
protected override void Write(LogEventInfo logEvent)
{
Assert.AreEqual(0, this.inBlockingOperation);
this.WriteCount++;
}
protected override void Write(AsyncLogEventInfo logEvent)
{
Assert.AreEqual(0, this.inBlockingOperation);
this.WriteCount2++;
base.Write(logEvent);
}
protected override void Write(AsyncLogEventInfo[] logEvents)
{
Assert.AreEqual(0, this.inBlockingOperation);
this.WriteCount3++;
base.Write(logEvents);
}
public void BlockingOperation(int millisecondsTimeout)
{
lock (this.SyncRoot)
{
this.inBlockingOperation++;
Thread.Sleep(millisecondsTimeout);
this.inBlockingOperation--;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using gView.Framework.system.UI;
using gView.Framework.UI;
using gView.Framework.Db.UI;
using gView.Framework.Db;
using gView.Framework.IO;
using System.Windows.Forms;
using gView.DataSources.EventTable;
using gView.Framework.Data;
using gView.Framework.Globalisation;
namespace gView.DataSources.EventTable.UI
{
[gView.Framework.system.RegisterPlugIn("653DA8F8-D321-4701-861F-23317E9FEC4D")]
public class EventTableGroupObject : ExplorerParentObject, IExplorerGroupObject
{
private EventTableConnectionsIcon _icon = new EventTableConnectionsIcon();
public EventTableGroupObject()
: base(null, null, 0)
{
}
#region IExplorerObject Member
public string Name
{
get { return "Eventtable Connections"; }
}
public string FullName
{
get { return "EventTableConnections"; }
}
public string Type
{
get { return "Eventtable Connections"; }
}
public IExplorerIcon Icon
{
get { return _icon; }
}
public new object Object
{
get { return null; }
}
#endregion
#region ISerializableExplorerObject Member
public IExplorerObject CreateInstanceByFullName(string FullName, ISerializableExplorerObjectCache cache)
{
if (cache.Contains(FullName)) return cache[FullName];
if (this.FullName == FullName)
{
EventTableGroupObject exObject = new EventTableGroupObject();
cache.Append(exObject);
return exObject;
}
return null;
}
#endregion
#region IExplorerParentObject Members
public override void Refresh()
{
base.Refresh();
base.AddChildObject(new EventTableNewConnectionObject(this));
ConfigConnections conStream = new ConfigConnections("eventtable", "546B0513-D71D-4490-9E27-94CD5D72C64A");
Dictionary<string, string> DbConnectionStrings = conStream.Connections;
foreach (string DbConnName in DbConnectionStrings.Keys)
{
EventTableConnection dbConn = new EventTableConnection();
dbConn.FromXmlString(DbConnectionStrings[DbConnName]);
base.AddChildObject(new EventTableObject(this, DbConnName, dbConn));
}
}
#endregion
}
[gView.Framework.system.RegisterPlugIn("F45B7E98-B20A-47bf-A45D-E78D52F36314")]
public class EventTableNewConnectionObject : ExplorerObjectCls, IExplorerSimpleObject, IExplorerObjectDoubleClick, IExplorerObjectCreatable
{
private IExplorerIcon _icon = new EventTableNewConnectionIcon();
public EventTableNewConnectionObject()
: base(null, null, 1)
{
}
public EventTableNewConnectionObject(IExplorerObject parent)
: base(parent, null, 1)
{
}
#region IExplorerSimpleObject Members
public IExplorerIcon Icon
{
get { return _icon; }
}
#endregion
#region IExplorerObject Members
public string Name
{
get { return "New Connection..."; }
}
public string FullName
{
get { return ""; }
}
public string Type
{
get { return "New OracleSDO Connection"; }
}
public void Dispose()
{
}
public new object Object
{
get { return null; }
}
public IExplorerObject CreateInstanceByFullName(string FullName)
{
return null;
}
#endregion
#region IExplorerObjectDoubleClick Members
public void ExplorerObjectDoubleClick(ExplorerObjectEventArgs e)
{
FormEventTableConnection dlg = new FormEventTableConnection();
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
ConfigConnections connStream = new ConfigConnections("eventtable", "546B0513-D71D-4490-9E27-94CD5D72C64A");
EventTableConnection etconn = new EventTableConnection(
dlg.DbConnectionString,
dlg.TableName,
dlg.IdField, dlg.XField, dlg.YField,
dlg.SpatialReference);
string id = connStream.GetName(dlg.TableName);
connStream.Add(id, etconn.ToXmlString());
e.NewExplorerObject = new EventTableObject(this.ParentExplorerObject, id, etconn);
}
}
#endregion
#region ISerializableExplorerObject Member
public IExplorerObject CreateInstanceByFullName(string FullName, ISerializableExplorerObjectCache cache)
{
if (cache.Contains(FullName)) return cache[FullName];
return null;
}
#endregion
#region IExplorerObjectCreatable Member
public bool CanCreate(IExplorerObject parentExObject)
{
return (parentExObject is EventTableGroupObject);
}
public IExplorerObject CreateExplorerObject(IExplorerObject parentExObject)
{
ExplorerObjectEventArgs e = new ExplorerObjectEventArgs();
ExplorerObjectDoubleClick(e);
return e.NewExplorerObject;
}
#endregion
}
[gView.Framework.system.RegisterPlugIn("B498C801-D7F2-4e1d-AA09-7A3599549DD8")]
public class EventTableObject : ExplorerObjectCls, IExplorerSimpleObject, IExplorerObjectContextMenu, IExplorerObjectDeletable, IExplorerObjectRenamable
{
private EventTableConnection _etconn = null;
private EventTableIcon _icon = new EventTableIcon();
private ToolStripItem[] _contextItems = null;
private string _name = String.Empty;
private IFeatureClass _fc = null;
public EventTableObject() : base(null, typeof(IFeatureClass), 1) { }
public EventTableObject(IExplorerObject parent, string name, EventTableConnection etconn)
: base(parent, typeof(IFeatureClass), 1)
{
_name = name;
_etconn = etconn;
List<ToolStripMenuItem> items = new List<ToolStripMenuItem>();
ToolStripMenuItem item = new ToolStripMenuItem(LocalizedResources.GetResString("Menu.ConnectionProperties", "Connection Properties..."));
item.Click += new EventHandler(ConnectionProperties_Click);
items.Add(item);
_contextItems = items.ToArray();
}
void ConnectionProperties_Click(object sender, EventArgs e)
{
if (_etconn == null) return;
FormEventTableConnection dlg = new FormEventTableConnection();
dlg.DbConnectionString = _etconn.DbConnectionString;
dlg.TableName = _etconn.TableName;
dlg.IdField = _etconn.IdFieldName;
dlg.XField = _etconn.XFieldName;
dlg.YField = _etconn.YFieldName;
dlg.SpatialReference = _etconn.SpatialReference;
if (dlg.ShowDialog() == DialogResult.OK)
{
EventTableConnection etcon = new EventTableConnection(
dlg.DbConnectionString,
dlg.TableName,
dlg.IdField, dlg.XField, dlg.YField,
dlg.SpatialReference);
ConfigConnections connStream = new ConfigConnections("eventtable", "546B0513-D71D-4490-9E27-94CD5D72C64A");
connStream.Add(dlg.TableName, etcon.ToXmlString());
_etconn = etcon;
}
}
#region IExplorerObject Member
public string Name
{
get
{
if (_etconn == null)
return "???";
return _name;
}
}
public string FullName
{
get
{
if (_etconn == null)
return "???";
return @"EventTableConnections\" + _name;
}
}
public string Type
{
get { return "Database Event Table"; ; }
}
public IExplorerIcon Icon
{
get { return _icon; }
}
public object Object
{
get
{
if (_fc != null) return _fc;
if (_etconn != null)
{
try
{
Dataset ds = new Dataset();
ds.ConnectionString = _etconn.ToXmlString();
ds.Open();
_fc = ds.Elements[0].Class as IFeatureClass;
return _fc;
}
catch
{
_fc = null;
}
}
return null;
}
}
#endregion
#region IDisposable Member
public void Dispose()
{
}
#endregion
#region ISerializableExplorerObject Member
public IExplorerObject CreateInstanceByFullName(string FullName, ISerializableExplorerObjectCache cache)
{
if (cache.Contains(FullName)) return cache[FullName];
EventTableGroupObject group = new EventTableGroupObject();
if (FullName.StartsWith(group.FullName))
{
foreach (IExplorerObject exObject in group.ChildObjects)
{
if (exObject.FullName == FullName)
{
cache.Append(exObject);
return exObject;
}
}
}
return null;
}
#endregion
#region IExplorerObjectContextMenu Member
public System.Windows.Forms.ToolStripItem[] ContextMenuItems
{
get { return _contextItems; }
}
#endregion
#region IExplorerObjectDeletable Member
public event ExplorerObjectDeletedEvent ExplorerObjectDeleted = null;
public bool DeleteExplorerObject(ExplorerObjectEventArgs e)
{
ConfigConnections stream = new ConfigConnections("eventtable", "546B0513-D71D-4490-9E27-94CD5D72C64A");
bool ret = stream.Remove(_name);
if (ret)
{
if (ExplorerObjectDeleted != null)
ExplorerObjectDeleted(this);
}
return ret;
}
#endregion
#region IExplorerObjectRenamable Member
public event ExplorerObjectRenamedEvent ExplorerObjectRenamed;
public bool RenameExplorerObject(string newName)
{
ConfigConnections stream = new ConfigConnections("eventtable", "546B0513-D71D-4490-9E27-94CD5D72C64A");
bool ret = stream.Rename(_name, newName);
if (ret == true)
{
_name = newName;
if (ExplorerObjectRenamed != null) ExplorerObjectRenamed(this);
}
return ret;
}
#endregion
}
class EventTableConnectionsIcon : IExplorerIcon
{
#region IExplorerIcon Members
public Guid GUID
{
get
{
return new Guid("10B98A8C-6E8E-4e92-B1F6-D9C923AF3151");
}
}
public System.Drawing.Image Image
{
get
{
return global::gView.DataSources.EventTable.UI.Properties.Resources.cat6;
}
}
#endregion
}
class EventTableNewConnectionIcon : IExplorerIcon
{
#region IExplorerIcon Members
public Guid GUID
{
get
{
return new Guid("BA81F595-A40D-45d0-9731-A2DC5D6B67BC");
}
}
public System.Drawing.Image Image
{
get
{
return global::gView.DataSources.EventTable.UI.Properties.Resources.gps_point;
}
}
#endregion
}
class EventTableIcon : IExplorerIcon
{
#region IExplorerIcon Members
public Guid GUID
{
get
{
return new Guid("C49DE671-C109-4e36-86D0-B9F4A1A75CC9");
}
}
public System.Drawing.Image Image
{
get
{
return global::gView.DataSources.EventTable.UI.Properties.Resources.table_base;
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Reflection;
using System.Reflection.Emit;
using Xunit;
namespace System.Reflection.Emit.Tests
{
public class TypeBuilderCreateType2
{
private const int MinAsmName = 1;
private const int MaxAsmName = 260;
private const int MinModName = 1;
private const int MaxModName = 260;
private const int MinTypName = 1;
private const int MaxTypName = 1024;
private const int NumLoops = 5;
private readonly RandomDataGenerator _generator = new RandomDataGenerator();
private TypeAttributes[] _typesPos = new TypeAttributes[17] {
TypeAttributes.Abstract | TypeAttributes.NestedPublic,
TypeAttributes.AnsiClass | TypeAttributes.NestedPublic,
TypeAttributes.AutoClass | TypeAttributes.NestedPublic,
TypeAttributes.AutoLayout | TypeAttributes.NestedPublic,
TypeAttributes.BeforeFieldInit | TypeAttributes.NestedPublic,
TypeAttributes.Class | TypeAttributes.NestedPublic,
TypeAttributes.ClassSemanticsMask | TypeAttributes.Abstract | TypeAttributes.NestedPublic,
TypeAttributes.ExplicitLayout | TypeAttributes.NestedPublic,
TypeAttributes.Import | TypeAttributes.NestedPublic,
TypeAttributes.Interface | TypeAttributes.Abstract | TypeAttributes.NestedPublic,
TypeAttributes.Sealed | TypeAttributes.NestedPublic,
TypeAttributes.SequentialLayout | TypeAttributes.NestedPublic,
TypeAttributes.Serializable | TypeAttributes.NestedPublic,
TypeAttributes.SpecialName | TypeAttributes.NestedPublic,
TypeAttributes.StringFormatMask | TypeAttributes.NestedPublic,
TypeAttributes.UnicodeClass | TypeAttributes.NestedPublic,
TypeAttributes.VisibilityMask,
};
[Fact]
public void TestDefineNestedType()
{
ModuleBuilder modBuilder;
TypeBuilder typeBuilder;
TypeBuilder nestedType = null;
Type newType;
string typeName = "";
string nestedTypeName = "";
modBuilder = CreateModule(
_generator.GetString(true, MinAsmName, MaxAsmName),
_generator.GetString(false, MinModName, MaxModName));
typeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls
typeBuilder = modBuilder.DefineType(typeName);
for (int i = 0; i < NumLoops; i++)
{
nestedTypeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls
// create nested type
if (null != nestedType && 0 == (_generator.GetInt32() % 2))
{
nestedType.DefineNestedType(nestedTypeName, TypeAttributes.Abstract | TypeAttributes.NestedPublic);
}
else
{
nestedType = typeBuilder.DefineNestedType(nestedTypeName, TypeAttributes.Abstract | TypeAttributes.NestedPublic);
}
}
newType = typeBuilder.CreateTypeInfo().AsType();
Assert.True(newType.Name.Equals(typeName));
}
[Fact]
public void TestDefineNestedTypeWithEmbeddedNullsInName()
{
ModuleBuilder modBuilder;
TypeBuilder typeBuilder;
Type newType;
string typeName = "";
string nestedTypeName = "";
for (int i = 0; i < NumLoops; i++)
{
modBuilder = CreateModule(
_generator.GetString(true, MinAsmName, MaxAsmName),
_generator.GetString(false, MinModName, MaxModName));
typeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls
nestedTypeName = _generator.GetString(true, MinTypName, MaxTypName / 4)
+ '\0'
+ _generator.GetString(true, MinTypName, MaxTypName / 4)
+ '\0'
+ _generator.GetString(true, MinTypName, MaxTypName / 4);
typeBuilder = modBuilder.DefineType(typeName);
// create nested type
typeBuilder.DefineNestedType(nestedTypeName, TypeAttributes.Abstract | TypeAttributes.NestedPublic);
newType = typeBuilder.CreateTypeInfo().AsType();
Assert.True(newType.Name.Equals(typeName));
}
}
[Fact]
public void TestDefineNestedTypeWithTypeAttributes()
{
ModuleBuilder modBuilder;
TypeBuilder typeBuilder;
TypeBuilder nestedType = null;
Type newType;
string typeName = "";
string nestedTypeName = "";
TypeAttributes typeAttrib = (TypeAttributes)0;
int i = 0;
modBuilder = CreateModule(
_generator.GetString(true, MinAsmName, MaxAsmName),
_generator.GetString(false, MinModName, MaxModName));
typeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls
typeBuilder = modBuilder.DefineType(typeName, typeAttrib);
for (i = 0; i < _typesPos.Length; i++)
{
typeAttrib = _typesPos[i];
nestedTypeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls
// create nested type
if (null != nestedType && 0 == (_generator.GetInt32() % 2))
{
nestedType.DefineNestedType(nestedTypeName, _typesPos[i]);
}
else
{
nestedType = typeBuilder.DefineNestedType(nestedTypeName, _typesPos[i]);
}
}
newType = typeBuilder.CreateTypeInfo().AsType();
Assert.True(newType.Name.Equals(typeName));
}
[Fact]
public void TestThrowsExceptionForNullName()
{
ModuleBuilder modBuilder;
TypeBuilder typeBuilder;
Type newType;
string typeName = "";
string nestedTypeName = "";
modBuilder = CreateModule(
_generator.GetString(true, MinAsmName, MaxAsmName),
_generator.GetString(false, MinModName, MaxModName));
typeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls
nestedTypeName = null;
typeBuilder = modBuilder.DefineType(typeName);
Assert.Throws<ArgumentNullException>(() =>
{
// create nested type
typeBuilder.DefineNestedType(nestedTypeName, TypeAttributes.NestedPublic | TypeAttributes.Class);
newType = typeBuilder.CreateTypeInfo().AsType();
});
}
[Fact]
public void TestThrowsExceptionForEmptyName()
{
ModuleBuilder modBuilder;
TypeBuilder typeBuilder;
Type newType;
string typeName = "";
string nestedTypeName = "";
modBuilder = CreateModule(
_generator.GetString(true, MinAsmName, MaxAsmName),
_generator.GetString(false, MinModName, MaxModName));
typeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls
nestedTypeName = string.Empty;
typeBuilder = modBuilder.DefineType(typeName);
Assert.Throws<ArgumentException>(() =>
{
// create nested type
typeBuilder.DefineNestedType(nestedTypeName, TypeAttributes.NestedPublic | TypeAttributes.Class);
newType = typeBuilder.CreateTypeInfo().AsType();
});
}
public ModuleBuilder CreateModule(string assemblyName, string modName)
{
AssemblyName asmName;
AssemblyBuilder asmBuilder;
ModuleBuilder modBuilder;
// create the dynamic module
asmName = new AssemblyName(assemblyName);
asmBuilder = AssemblyBuilder.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run);
modBuilder = TestLibrary.Utilities.GetModuleBuilder(asmBuilder, "Module1");
return modBuilder;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass001.regclass001;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Reflection;
public class MyClass
{
public int Field = 0;
}
public struct MyStruct
{
public int Number;
}
public enum MyEnum
{
First = 1,
Second = 2,
Third = 3
}
public class MemberClass
{
/*
Example of calling it:
MemberClass staticMC =new MemberClass();
dynamic mc = staticMC;
bool myBool;
//This test the getter for the property
myBool = true;
staticMC.myBool = myBool; //We set the inner field
myBool = mc.Property_bool; //We use the property to get the field
if (myBool != true)
return 1;
//This tests the setter for the property
myBool = true;
mc.Property_bool = myBool; //We set the property
myBool = statMc.myBool; // We get the inner field
if (myBool != true)
return 1;
*/
public bool myBool = true;
public bool? myBoolNull = true;
public bool?[] myBoolNullArr = new bool?[2];
public bool[] myBoolArr = new bool[2];
public char myChar = 'a';
public char? myCharNull = 'a';
public char?[] myCharNullArr = new char?[2];
public char[] myCharArr = new char[2];
public decimal myDecimal = 1m;
public decimal? myDecimalNull = 1m;
public decimal?[] myDecimalNullArr = new decimal?[2];
public decimal[] myDecimalArr = new decimal[2];
public dynamic myDynamic = new object();
public float myFloat = 3f;
public float?[] myFloatNullArr = new float?[]
{
}
;
public MyClass myClass = new MyClass()
{
Field = 2
}
;
public MyClass[] myClassArr = new MyClass[3];
public MyEnum myEnum = MyEnum.First;
public MyEnum? myEnumNull = MyEnum.First;
public MyEnum?[] myEnumNullArr = new MyEnum?[3];
public MyEnum[] myEnumArr = new MyEnum[3];
public MyStruct myStruct = new MyStruct()
{
Number = 3
}
;
public MyStruct? myStructNull = new MyStruct()
{
Number = 3
}
;
public MyStruct?[] myStructNullArr = new MyStruct?[3];
public MyStruct[] myStructArr = new MyStruct[3];
public short myShort = 1;
public short? myShortNull = 1;
public short?[] myShortNullArr = new short?[2];
public short[] myShortArr = new short[2];
public string myString = string.Empty;
public string[] myStringArr = new string[2];
public ulong myUlong = 1;
public ulong? myUlongNull = 1;
public ulong?[] myUlongNullArr = new ulong?[2];
public ulong[] myUlongArr = new ulong[2];
public bool Property_bool
{
protected set
{
myBool = value;
}
get
{
return false;
}
}
public bool? Property_boolNull
{
protected set
{
myBoolNull = value;
}
get
{
return null;
}
}
public bool?[] Property_boolNullArr
{
protected set
{
myBoolNullArr = value;
}
get
{
return new bool?[]
{
true, null, false
}
;
}
}
public bool[] Property_boolArr
{
protected set
{
myBoolArr = value;
}
get
{
return new bool[]
{
true, false
}
;
}
}
public char Property_char
{
private set
{
myChar = value;
}
get
{
return myChar;
}
}
public char? Property_charNull
{
private set
{
myCharNull = value;
}
get
{
return myCharNull;
}
}
public char?[] Property_charNullArr
{
private set
{
myCharNullArr = value;
}
get
{
return myCharNullArr;
}
}
public char[] Property_charArr
{
private set
{
myCharArr = value;
}
get
{
return myCharArr;
}
}
public decimal Property_decimal
{
internal set
{
myDecimal = value;
}
get
{
return myDecimal;
}
}
public decimal? Property_decimalNull
{
internal set
{
myDecimalNull = value;
}
get
{
return myDecimalNull;
}
}
public decimal?[] Property_decimalNullArr
{
protected internal set
{
myDecimalNullArr = value;
}
get
{
return myDecimalNullArr;
}
}
public decimal[] Property_decimalArr
{
protected internal set
{
myDecimalArr = value;
}
get
{
return myDecimalArr;
}
}
public dynamic Property_dynamic
{
get
{
return myDynamic;
}
set
{
myDynamic = value;
}
}
public float Property_Float
{
get
{
return myFloat;
}
set
{
myFloat = value;
}
}
public float?[] Property_FloatNullArr
{
get
{
return myFloatNullArr;
}
set
{
myFloatNullArr = value;
}
}
public MyClass Property_MyClass
{
set
{
myClass = value;
}
}
public MyClass[] Property_MyClassArr
{
set
{
myClassArr = value;
}
}
public MyEnum Property_MyEnum
{
set
{
myEnum = value;
}
get
{
return myEnum;
}
}
public MyEnum? Property_MyEnumNull
{
set
{
myEnumNull = value;
}
private get
{
return myEnumNull;
}
}
public MyEnum?[] Property_MyEnumNullArr
{
set
{
myEnumNullArr = value;
}
private get
{
return myEnumNullArr;
}
}
public MyEnum[] Property_MyEnumArr
{
set
{
myEnumArr = value;
}
private get
{
return myEnumArr;
}
}
public MyStruct Property_MyStruct
{
get
{
return myStruct;
}
set
{
myStruct = value;
}
}
public MyStruct? Property_MyStructNull
{
get
{
return myStructNull;
}
}
public MyStruct?[] Property_MyStructNullArr
{
get
{
return myStructNullArr;
}
}
public MyStruct[] Property_MyStructArr
{
get
{
return myStructArr;
}
}
public short Property_short
{
set
{
myShort = value;
}
protected get
{
return myShort;
}
}
public short? Property_shortNull
{
set
{
myShortNull = value;
}
protected get
{
return myShortNull;
}
}
public short?[] Property_shortNullArr
{
set
{
myShortNullArr = value;
}
protected get
{
return myShortNullArr;
}
}
public short[] Property_shortArr
{
set
{
myShortArr = value;
}
protected get
{
return myShortArr;
}
}
public string Property_string
{
set
{
myString = value;
}
get
{
return myString;
}
}
public string[] Property_stringArr
{
set
{
myStringArr = value;
}
get
{
return myStringArr;
}
}
public ulong Property_ulong
{
set
{
myUlong = value;
}
protected internal get
{
return myUlong;
}
}
public ulong? Property_ulongNull
{
set
{
myUlongNull = value;
}
protected internal get
{
return myUlongNull;
}
}
public ulong?[] Property_ulongNullArr
{
set
{
myUlongNullArr = value;
}
protected internal get
{
return myUlongNullArr;
}
}
public ulong[] Property_ulongArr
{
set
{
myUlongArr = value;
}
protected internal get
{
return myUlongArr;
}
}
public static bool myBoolStatic;
public static MyClass myClassStatic = new MyClass();
public static bool Property_boolStatic
{
protected set
{
myBoolStatic = value;
}
get
{
return myBoolStatic;
}
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass001.regclass001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass001.regclass001;
// <Title> Tests regular class regular property used in static method body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
return Test.TestGetMethod(new MemberClass()) + Test.TestSetMethod(new MemberClass()) == 0 ? 0 : 1;
}
public static int TestGetMethod(MemberClass mc)
{
dynamic dy = mc;
dy.myBool = true;
if (dy.Property_bool) //always return false
return 1;
else
return 0;
}
public static int TestSetMethod(MemberClass mc)
{
dynamic dy = mc;
try
{
dy.Property_bool = true;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.InaccessibleSetter, e.Message, "MemberClass.Property_bool", "set"))
return 0;
}
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass002.regclass002
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass002.regclass002;
// <Title> Tests regular class regular property used in argements of method invocation.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
private delegate int TestDec(char[] c);
private static char[] s_charArray = new char[]
{
'0', 'a'
};
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t = new Test();
TestDec td = t.TestMethod;
MemberClass mc = new MemberClass();
mc.myCharArr = s_charArray;
dynamic dy = mc;
return td((char[])dy.Property_charArr);
}
public int TestMethod(char[] c)
{
if (ReferenceEquals(c, s_charArray) && c[0] == '0' && c[1] == 'a')
return 0;
else
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass003.regclass003
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass003.regclass003;
// <Title> Tests regular class regular property used in property-set body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
private static dynamic s_mc = new MemberClass();
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Dec = new short?[]
{
null, 0, -1
}
;
if (s_mc.myShortNullArr[0] == null && s_mc.myShortNullArr[1] == 0 && s_mc.myShortNullArr[2] == -1)
return 0;
return 1;
}
public static short?[] Dec
{
set
{
s_mc.Property_shortNullArr = value;
}
get
{
return null;
}
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass004.regclass004
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass004.regclass004;
// <Title> Tests regular class regular property used in short-circuit boolean expression and ternary operator expression.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact(Skip = "875112")]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = new MemberClass();
int loopCount = 0;
dy.Property_decimal = 0M;
while (dy.Property_decimal < 10)
{
System.Console.WriteLine((object)dy.Property_decimal);
dy.Property_decimal++;
loopCount++;
}
return (dy.Property_decimal == 10 && loopCount == 10) ? 0 : 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass005.regclass005
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass005.regclass005;
// <Title> Tests regular class regular property used in property set.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t = new Test();
try
{
t.TestProperty = null; //protected, should have exception
return 1;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.InaccessibleSetter, e.Message, "MemberClass.Property_boolNull"))
return 0;
}
return 1;
}
public bool? TestProperty
{
set
{
dynamic dy = new MemberClass();
dy.Property_boolNull = value;
}
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass006.regclass006
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass006.regclass006;
// <Title> Tests regular class regular property used in property get body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t = new Test();
bool?[] array = t.TestProperty;
if (array.Length == 3 && array[0] == true && array[1] == null && array[2] == false)
return 0;
return 1;
}
public bool?[] TestProperty
{
get
{
dynamic dy = new MemberClass();
return dy.Property_boolNullArr;
}
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass007.regclass007
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass007.regclass007;
// <Title> Tests regular class regular property used in static method body.</Title>
// <Description>
// Derived class call protected parent property.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test : MemberClass
{
[Fact(Skip = "875112")]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test mc = new Test();
dynamic dy = mc;
dy.Property_boolArr = new bool[3];
bool[] result = dy.Property_boolArr;
if (result.Length != 2 || result[0] != true || result[1] != false)
return 1;
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass008.regclass008
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass008.regclass008;
// <Title> Tests regular class regular property used in indexer.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Collections.Generic;
public class Test
{
private Dictionary<string, int> _dic = new Dictionary<string, int>();
private MemberClass _mc = new MemberClass();
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
if (TestSet() == 0 && TestGet() == 0)
return 0;
else
return 1;
}
private static int TestSet()
{
Test t = new Test();
t["a"] = 10;
t[string.Empty] = -1;
if (t._dic["a"] == 10 && t._dic[string.Empty] == -1 && (string)t._mc.Property_string == string.Empty)
return 0;
else
return 1;
}
private static int TestGet()
{
Test t = new Test();
t._dic["Test0"] = 2;
if (t["Test0"] == 2)
return 0;
else
return 1;
}
public int this[string i]
{
set
{
dynamic dy = _mc;
dy.Property_string = i;
_dic.Add((string)dy.Property_string, value);
_mc = dy; //this is to circumvent the boxing of the struct
}
get
{
_mc.Property_string = i;
dynamic dy = _mc;
return _dic[(string)dy.Property_string];
}
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass010.regclass010
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass010.regclass010;
// <Title> Tests regular class regular property used in try/catch/finally.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
dynamic dy = mc;
dy.myChar = 'a';
try
{
dy.Property_char = 'x'; //private, should have exception.
return 1;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (!ErrorVerifier.Verify(ErrorMessageId.InaccessibleSetter, e.Message, "MemberClass.Property_char"))
return 1;
if ((char)dy.Property_char != 'a')
return 1;
}
finally
{
dy.myChar = 'b';
}
if ((char)dy.Property_char != 'b')
return 1;
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass011.regclass011
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass011.regclass011;
// <Title> Tests regular class regular property used in anonymous method.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
dynamic dy = mc;
Func<char, char?> func = delegate (char arg)
{
mc.myCharNull = arg;
dy = mc; // struct need to re-assign the value.
return dy.Property_charNull;
}
;
char? result = func('a');
if (result == 'a')
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass012.regclass012
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass012.regclass012;
// <Title> Tests regular class regular property used in lambda expression.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Linq;
public class Test
{
[Fact(Skip = "875112")]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
return TestGet() + TestSet();
}
private static int TestSet()
{
MemberClass mc = new MemberClass();
dynamic dy = mc;
dy.Property_ulongArr = new ulong[]
{
1, 2, 3, 4, 3, 4
}
;
dy.Property_ulong = (ulong)4;
var list = mc.Property_ulongArr.Where(p => p == (ulong)mc.Property_ulong).ToList();
return list.Count - 2;
}
private static int TestGet()
{
MemberClass mc = new MemberClass();
dynamic dy = mc;
mc.Property_ulongArr = new ulong[]
{
1, 2, 3, 4, 3, 4
}
;
mc.Property_ulong = 4;
var list = ((ulong[])dy.Property_ulongArr).Where(p => p == (ulong)dy.Property_ulong).ToList();
return list.Count - 2;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass013.regclass013
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass013.regclass013;
// <Title> Tests regular class regular property used in the foreach loop body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
dynamic dy = mc;
char result = default(char);
char[] LoopArray = new char[]
{
'a', 'b'
}
;
foreach (char c in LoopArray)
{
mc.myCharNullArr = new char?[]
{
c
}
;
dy = mc;
result = ((char?[])dy.myCharNullArr)[0].Value;
}
if (result == 'b')
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass014.regclass014
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass014.regclass014;
// <Title> Tests regular class regular property used in do/while expression.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
mc.Property_decimalNull = -10.1M;
dynamic dy = mc;
do
{
mc.Property_decimalNull += 1;
dy = mc; // for struct we should re-assign.
}
while ((decimal?)dy.Property_decimalNull < 0M);
if ((decimal?)mc.Property_decimalNull == 0.9M)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass017.regclass017
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass017.regclass017;
// <Title> Tests regular class regular property used in using expression.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.IO;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
mc.myChar = (char)256;
dynamic dy = mc;
using (MemoryStream ms = new MemoryStream((int)dy.Property_char))
{
if (ms.Capacity != 256)
return 1;
}
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass018.regclass018
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass018.regclass018;
// <Title> Tests regular class regular property used in try/catch/finally.</Title>
// <Description>
// try/catch/finally that uses an anonymous method and refer two dynamic parameters.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
mc.Property_decimalNullArr = new decimal?[]
{
0M, 1M, 1.3M
}
;
mc.myStruct = new MyStruct()
{
Number = 3
}
;
dynamic dy = mc;
int result = -1;
try
{
Func<decimal?[], MyStruct, int> func = delegate (decimal?[] x, MyStruct y)
{
int tmp = 0;
foreach (decimal? d in x)
{
tmp += (int)d.Value;
}
tmp += y.Number;
return tmp;
}
;
result = func((decimal?[])dy.Property_decimalNullArr, (MyStruct)dy.Property_MyStruct);
}
finally
{
result += (int)dy.Property_MyStruct.Number;
}
if (result != 8)
return 1;
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass019.regclass019
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass019.regclass019;
// <Title> Tests regular class regular property used in foreach.</Title>
// <Description>
// foreach inside a using statement that uses the dynamic introduced by the using statement.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.IO;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
int[] array = new int[]
{
1, 2
}
;
MemoryStream ms = new MemoryStream(new byte[]
{
84, 101, 115, 116
}
); //Test
MemberClass mc = new MemberClass();
mc.Property_dynamic = true;
dynamic dy = mc;
string result = string.Empty;
using (dynamic sr = new StreamReader(ms, (bool)dy.Property_dynamic))
{
foreach (int s in array)
{
ms.Position = 0;
string m = ((StreamReader)sr).ReadToEnd();
result += m + s.ToString();
}
}
//Test1Test2
if (result == "Test1Test2")
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass020.regclass020
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass020.regclass020;
// <Title> Tests regular class regular property used in iterator that calls to a lambda expression.</Title>
// <Description>
// foreach inside a using statement that uses the dynamic introduced by the using statement.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Collections;
public class Test
{
private static MemberClass s_mc;
private static dynamic s_dy;
static Test()
{
s_mc = new MemberClass();
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
decimal index = 1M;
s_mc.Property_decimalArr = new decimal[]
{
1M, 2M, 3M
}
;
s_dy = s_mc;
Test t = new Test();
foreach (decimal i in t.Increment(0))
{
if (i != index)
return 1;
index = index + 1;
}
if (index != 4)
return 1;
return 0;
}
public IEnumerable Increment(int number)
{
while (number < s_mc.Property_decimalArr.Length)
{
Func<decimal[], decimal> func = (decimal[] x) => x[number++];
yield return func(s_dy.Property_decimalArr);
}
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass021.regclass021
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass021.regclass021;
// <Title> Tests regular class regular property used in object initializer inside a collection initializer.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Collections.Generic;
public class Test
{
private float _field1;
private float?[] _field2;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
mc.Property_Float = 1.23f;
mc.Property_FloatNullArr = new float?[]
{
null, 1.33f
}
;
dynamic dy = mc;
List<Test> list = new List<Test>()
{
new Test()
{
_field1 = dy.Property_Float, _field2 = dy.Property_FloatNullArr
}
}
;
if (list.Count == 1 && list[0]._field1 == 1.23f && list[0]._field2.Length == 2 && list[0]._field2[0] == null && list[0]._field2[1] == 1.33f)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass022.regclass022
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass022.regclass022;
// <Title> Tests regular class regular property used in static method body.</Title>
// <Description>
// set only property access.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Collections.Generic;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
dynamic dy = mc;
dy.Property_MyClass = new MyClass()
{
Field = -1
}
;
mc = dy; //to circumvent the boxing of the struct
if (mc.myClass.Field == -1)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass023.regclass023
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass023.regclass023;
// <Title> Tests regular class regular property used in static method body.</Title>
// <Description>
// Negative: set only property access
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
using System.Collections.Generic;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
dynamic dy = mc;
dy.Property_MyClass = new MyClass()
{
Field = -1
}
;
mc = dy; //to circumvent the boxing of the struct
if (mc.myClass.Field != -1)
return 1;
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass024.regclass024
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass024.regclass024;
// <Title> Tests regular class regular property used in throws.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
dynamic dy = mc;
dy.Property_string = "Test Message";
try
{
throw new ArithmeticException((string)dy.Property_string);
}
catch (ArithmeticException ae)
{
if (ae.Message == "Test Message")
return 0;
}
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass025.regclass025
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass025.regclass025;
// <Title> Tests regular class regular property used in field initializer.</Title>
// <Description>
// Negative
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
private static MemberClass s_mc;
private static dynamic s_dy;
private MyEnum _me = s_dy.Property_MyEnum;
static Test()
{
s_mc = new MemberClass();
s_dy = s_mc;
s_dy.Property_MyEnum = MyEnum.Third;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t = new Test();
if (t._me != MyEnum.Third)
return 1;
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass026.regclass026
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass026.regclass026;
// <Title> Tests regular class regular property used in set only property body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
private MemberClass _mc;
private MyEnum? MyProp
{
set
{
_mc = new MemberClass();
dynamic dy = _mc;
dy.Property_MyEnumNull = value;
_mc = dy; // for struct.
}
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t = new Test();
t.MyProp = MyEnum.Second;
if (t._mc.myEnumNull == MyEnum.Second)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass027.regclass027
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass027.regclass027;
// <Title> Tests regular class regular property used in read only property body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
private MyEnum MyProp
{
get
{
dynamic dy = new MemberClass();
dy.Property_MyEnumArr = new MyEnum[]
{
MyEnum.Second, default (MyEnum)}
;
return dy.myEnumArr[0];
}
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t = new Test();
if (t.MyProp == MyEnum.Second)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass028.regclass028
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass028.regclass028;
// <Title> Tests regular class regular property used in static read only property body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
private static MyEnum? MyProp
{
get
{
dynamic dy = new MemberClass();
dy.Property_MyEnumNullArr = new MyEnum?[]
{
null, MyEnum.Second, default (MyEnum)}
;
return dy.myEnumNullArr[0];
}
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
if (Test.MyProp == null)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass029.regclass029
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass029.regclass029;
// <Title> Tests regular class regular property used in static method body.</Title>
// <Description>
// get only property access.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
mc.myStructNull = new MyStruct()
{
Number = int.MinValue
}
;
dynamic dy = mc;
MyStruct? result = dy.Property_MyStructNull;
if (result.Value.Number == int.MinValue)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass030.regclass030
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass030.regclass030;
// <Title> Tests regular class regular property used in method call argument.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
mc.myStructArr = new MyStruct[]
{
new MyStruct()
{
Number = 1
}
, new MyStruct()
{
Number = -1
}
}
;
dynamic dy = mc;
bool result = TestMethod(1, string.Empty, (MyStruct[])dy.Property_MyStructArr);
if (result)
return 0;
return 1;
}
private static bool TestMethod<V, U>(V v, U u, params MyStruct[] ms)
{
if (v.GetType() != typeof(int))
return false;
if (u.GetType() != typeof(string))
return false;
if (ms.Length != 2 || ms[0].Number != 1 || ms[1].Number != -1)
return false;
return true;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass031.regclass031
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass031.regclass031;
// <Title> Tests regular class regular property used in static method body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
dynamic dy = mc;
mc.myStructNullArr = new MyStruct?[]
{
null, new MyStruct()
{
Number = -1
}
}
;
if (((MyStruct?[])dy.Property_MyStructNullArr)[0] == null)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass032.regclass032
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass032.regclass032;
// <Title> Tests regular class regular property used in lock expression.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test : MemberClass
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
dynamic dy = mc;
dy.Property_shortNull = (short)-1;
try
{
lock (dy.Property_shortNull)
{
}
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.BadProtectedAccess, e.Message, "MemberClass.Property_shortNull", "MemberClass", "Test"))
return 0;
}
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass034.regclass034
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass034.regclass034;
// <Title> Tests regular class regular property used in foreach loop.</Title>
// <Description>
// Negative
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
mc.Property_shortArr = new short[]
{
1, 2, 3, 4, 5
}
;
dynamic dy = mc;
short i = 1;
try
{
foreach (var x in dy.Property_shortArr) //protected
{
if (i++ != (short)x)
return 1;
}
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.InaccessibleGetter, e.Message, "MemberClass.Property_shortArr"))
return 0;
}
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass035.regclass035
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass035.regclass035;
// <Title> Tests regular class regular property used in method body.</Title>
// <Description>
// Negative
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact(Skip = "875112")]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
return Test.TestGetMethod(new MemberClass()) + Test.TestSetMethod(new MemberClass()) == 0 ? 0 : 1;
}
public static int TestGetMethod(MemberClass mc)
{
dynamic dy = mc;
mc.Property_ulongNullArr = new ulong?[]
{
null, 1
}
;
if (dy.Property_ulongNullArr.Length == 2 && dy.Property_ulongNullArr[0] == null && dy.Property_ulongNullArr[1] == 1)
return 0;
else
return 1;
}
public static int TestSetMethod(MemberClass mc)
{
dynamic dy = mc;
dy.Property_ulongNullArr = new ulong?[]
{
null, 1
}
;
if (mc.Property_ulongNullArr.Length == 2 && mc.Property_ulongNullArr[0] == null && mc.Property_ulongNullArr[1] == 1)
return 0;
else
return 1;
}
}
//</Code>
}
| |
// 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.Globalization {
using System.Text;
using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
internal static class TimeSpanFormat {
private static String IntToString(int n, int digits) {
return ParseNumbers.IntToString(n, 10, digits, '0', 0);
}
internal static readonly FormatLiterals PositiveInvariantFormatLiterals = TimeSpanFormat.FormatLiterals.InitInvariant(false /*isNegative*/);
internal static readonly FormatLiterals NegativeInvariantFormatLiterals = TimeSpanFormat.FormatLiterals.InitInvariant(true /*isNegative*/);
internal enum Pattern {
None = 0,
Minimum = 1,
Full = 2,
}
//
// Format
//
// Actions: Main method called from TimeSpan.ToString
//
internal static String Format(TimeSpan value, String format, IFormatProvider formatProvider) {
if (format == null || format.Length == 0)
format = "c";
// standard formats
if (format.Length == 1) {
char f = format[0];
if (f == 'c' || f == 't' || f == 'T')
return FormatStandard(value, true, format, Pattern.Minimum);
if (f == 'g' || f == 'G') {
Pattern pattern;
DateTimeFormatInfo dtfi = DateTimeFormatInfo.GetInstance(formatProvider);
if (value._ticks < 0)
format = dtfi.FullTimeSpanNegativePattern;
else
format = dtfi.FullTimeSpanPositivePattern;
if (f == 'g')
pattern = Pattern.Minimum;
else
pattern = Pattern.Full;
return FormatStandard(value, false, format, pattern);
}
throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
}
return FormatCustomized(value, format, DateTimeFormatInfo.GetInstance(formatProvider));
}
//
// FormatStandard
//
// Actions: Format the TimeSpan instance using the specified format.
//
private static String FormatStandard(TimeSpan value, bool isInvariant, String format, Pattern pattern) {
StringBuilder sb = StringBuilderCache.Acquire();
int day = (int)(value._ticks / TimeSpan.TicksPerDay);
long time = value._ticks % TimeSpan.TicksPerDay;
if (value._ticks < 0) {
day = -day;
time = -time;
}
int hours = (int)(time / TimeSpan.TicksPerHour % 24);
int minutes = (int)(time / TimeSpan.TicksPerMinute % 60);
int seconds = (int)(time / TimeSpan.TicksPerSecond % 60);
int fraction = (int)(time % TimeSpan.TicksPerSecond);
FormatLiterals literal;
if (isInvariant) {
if (value._ticks < 0)
literal = NegativeInvariantFormatLiterals;
else
literal = PositiveInvariantFormatLiterals;
}
else {
literal = new FormatLiterals();
literal.Init(format, pattern == Pattern.Full);
}
if (fraction != 0) { // truncate the partial second to the specified length
fraction = (int)((long)fraction / (long)Math.Pow(10, DateTimeFormat.MaxSecondsFractionDigits - literal.ff));
}
// Pattern.Full: [-]dd.hh:mm:ss.fffffff
// Pattern.Minimum: [-][d.]hh:mm:ss[.fffffff]
sb.Append(literal.Start); // [-]
if (pattern == Pattern.Full || day != 0) { //
sb.Append(day); // [dd]
sb.Append(literal.DayHourSep); // [.]
} //
sb.Append(IntToString(hours, literal.hh)); // hh
sb.Append(literal.HourMinuteSep); // :
sb.Append(IntToString(minutes, literal.mm)); // mm
sb.Append(literal.MinuteSecondSep); // :
sb.Append(IntToString(seconds, literal.ss)); // ss
if (!isInvariant && pattern == Pattern.Minimum) {
int effectiveDigits = literal.ff;
while (effectiveDigits > 0) {
if (fraction % 10 == 0) {
fraction = fraction / 10;
effectiveDigits--;
}
else {
break;
}
}
if (effectiveDigits > 0) {
sb.Append(literal.SecondFractionSep); // [.FFFFFFF]
sb.Append((fraction).ToString(DateTimeFormat.fixedNumberFormats[effectiveDigits - 1], CultureInfo.InvariantCulture));
}
}
else if (pattern == Pattern.Full || fraction != 0) {
sb.Append(literal.SecondFractionSep); // [.]
sb.Append(IntToString(fraction, literal.ff)); // [fffffff]
} //
sb.Append(literal.End); //
return StringBuilderCache.GetStringAndRelease(sb);
}
//
// FormatCustomized
//
// Actions: Format the TimeSpan instance using the specified format.
//
internal static String FormatCustomized(TimeSpan value, String format, DateTimeFormatInfo dtfi) {
Debug.Assert(dtfi != null, "dtfi == null");
int day = (int)(value._ticks / TimeSpan.TicksPerDay);
long time = value._ticks % TimeSpan.TicksPerDay;
if (value._ticks < 0) {
day = -day;
time = -time;
}
int hours = (int)(time / TimeSpan.TicksPerHour % 24);
int minutes = (int)(time / TimeSpan.TicksPerMinute % 60);
int seconds = (int)(time / TimeSpan.TicksPerSecond % 60);
int fraction = (int)(time % TimeSpan.TicksPerSecond);
long tmp = 0;
int i = 0;
int tokenLen;
StringBuilder result = StringBuilderCache.Acquire();
while (i < format.Length) {
char ch = format[i];
int nextChar;
switch (ch) {
case 'h':
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > 2)
throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
DateTimeFormat.FormatDigits(result, hours, tokenLen);
break;
case 'm':
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > 2)
throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
DateTimeFormat.FormatDigits(result, minutes, tokenLen);
break;
case 's':
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > 2)
throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
DateTimeFormat.FormatDigits(result, seconds, tokenLen);
break;
case 'f':
//
// The fraction of a second in single-digit precision. The remaining digits are truncated.
//
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits)
throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
tmp = (long)fraction;
tmp /= (long)Math.Pow(10, DateTimeFormat.MaxSecondsFractionDigits - tokenLen);
result.Append((tmp).ToString(DateTimeFormat.fixedNumberFormats[tokenLen - 1], CultureInfo.InvariantCulture));
break;
case 'F':
//
// Displays the most significant digit of the seconds fraction. Nothing is displayed if the digit is zero.
//
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits)
throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
tmp = (long)fraction;
tmp /= (long)Math.Pow(10, DateTimeFormat.MaxSecondsFractionDigits - tokenLen);
int effectiveDigits = tokenLen;
while (effectiveDigits > 0) {
if (tmp % 10 == 0) {
tmp = tmp / 10;
effectiveDigits--;
}
else {
break;
}
}
if (effectiveDigits > 0) {
result.Append((tmp).ToString(DateTimeFormat.fixedNumberFormats[effectiveDigits - 1], CultureInfo.InvariantCulture));
}
break;
case 'd':
//
// tokenLen == 1 : Day as digits with no leading zero.
// tokenLen == 2+: Day as digits with leading zero for single-digit days.
//
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > 8)
throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
DateTimeFormat.FormatDigits(result, day, tokenLen, true);
break;
case '\'':
case '\"':
tokenLen = DateTimeFormat.ParseQuoteString(format, i, result);
break;
case '%':
// Optional format character.
// For example, format string "%d" will print day
// Most of the cases, "%" can be ignored.
nextChar = DateTimeFormat.ParseNextChar(format, i);
// nextChar will be -1 if we already reach the end of the format string.
// Besides, we will not allow "%%" appear in the pattern.
if (nextChar >= 0 && nextChar != (int)'%') {
result.Append(TimeSpanFormat.FormatCustomized(value, ((char)nextChar).ToString(), dtfi));
tokenLen = 2;
}
else
{
//
// This means that '%' is at the end of the format string or
// "%%" appears in the format string.
//
throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
}
break;
case '\\':
// Escaped character. Can be used to insert character into the format string.
// For example, "\d" will insert the character 'd' into the string.
//
nextChar = DateTimeFormat.ParseNextChar(format, i);
if (nextChar >= 0)
{
result.Append(((char)nextChar));
tokenLen = 2;
}
else
{
//
// This means that '\' is at the end of the formatting string.
//
throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
}
break;
default:
throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
}
i += tokenLen;
}
return StringBuilderCache.GetStringAndRelease(result);
}
internal struct FormatLiterals {
internal String Start {
get {
return literals[0];
}
}
internal String DayHourSep {
get {
return literals[1];
}
}
internal String HourMinuteSep {
get {
return literals[2];
}
}
internal String MinuteSecondSep {
get {
return literals[3];
}
}
internal String SecondFractionSep {
get {
return literals[4];
}
}
internal String End {
get {
return literals[5];
}
}
internal String AppCompatLiteral;
internal int dd;
internal int hh;
internal int mm;
internal int ss;
internal int ff;
private String[] literals;
/* factory method for static invariant FormatLiterals */
internal static FormatLiterals InitInvariant(bool isNegative) {
FormatLiterals x = new FormatLiterals();
x.literals = new String[6];
x.literals[0] = isNegative ? "-" : String.Empty;
x.literals[1] = ".";
x.literals[2] = ":";
x.literals[3] = ":";
x.literals[4] = ".";
x.literals[5] = String.Empty;
x.AppCompatLiteral = ":."; // MinuteSecondSep+SecondFractionSep;
x.dd = 2;
x.hh = 2;
x.mm = 2;
x.ss = 2;
x.ff = DateTimeFormat.MaxSecondsFractionDigits;
return x;
}
// For the "v1" TimeSpan localized patterns, the data is simply literal field separators with
// the constants guaranteed to include DHMSF ordered greatest to least significant.
// Once the data becomes more complex than this we will need to write a proper tokenizer for
// parsing and formatting
internal void Init(String format, bool useInvariantFieldLengths) {
literals = new String[6];
for (int i = 0; i < literals.Length; i++)
literals[i] = String.Empty;
dd = 0;
hh = 0;
mm = 0;
ss = 0;
ff = 0;
StringBuilder sb = StringBuilderCache.Acquire();
bool inQuote = false;
char quote = '\'';
int field = 0;
for (int i = 0; i < format.Length; i++) {
switch (format[i]) {
case '\'':
case '\"':
if (inQuote && (quote == format[i])) {
/* we were in a quote and found a matching exit quote, so we are outside a quote now */
Debug.Assert(field >= 0 && field <= 5, "field >= 0 && field <= 5");
if (field >= 0 && field <= 5) {
literals[field] = sb.ToString();
sb.Length = 0;
inQuote = false;
}
else {
return; // how did we get here?
}
}
else if (!inQuote) {
/* we are at the start of a new quote block */
quote = format[i];
inQuote = true;
}
else {
/* we were in a quote and saw the other type of quote character, so we are still in a quote */
}
break;
case '%':
Debug.Assert(false, "Unexpected special token '%', Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
goto default;
case '\\':
if (!inQuote) {
i++; /* skip next character that is escaped by this backslash or percent sign */
break;
}
goto default;
case 'd':
if (!inQuote) {
Debug.Assert((field == 0 && sb.Length == 0) || field == 1,
"field == 0 || field == 1, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 1; // DayHourSep
dd++;
}
break;
case 'h':
if (!inQuote) {
Debug.Assert((field == 1 && sb.Length == 0) || field == 2,
"field == 1 || field == 2, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 2; // HourMinuteSep
hh++;
}
break;
case 'm':
if (!inQuote) {
Debug.Assert((field == 2 && sb.Length == 0) || field == 3,
"field == 2 || field == 3, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 3; // MinuteSecondSep
mm++;
}
break;
case 's':
if (!inQuote) {
Debug.Assert((field == 3 && sb.Length == 0) || field == 4,
"field == 3 || field == 4, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 4; // SecondFractionSep
ss++;
}
break;
case 'f':
case 'F':
if (!inQuote) {
Debug.Assert((field == 4 && sb.Length == 0) || field == 5,
"field == 4 || field == 5, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 5; // End
ff++;
}
break;
default:
sb.Append(format[i]);
break;
}
}
Debug.Assert(field == 5);
AppCompatLiteral = MinuteSecondSep + SecondFractionSep;
Debug.Assert(0 < dd && dd < 3, "0 < dd && dd < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
Debug.Assert(0 < hh && hh < 3, "0 < hh && hh < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
Debug.Assert(0 < mm && mm < 3, "0 < mm && mm < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
Debug.Assert(0 < ss && ss < 3, "0 < ss && ss < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
Debug.Assert(0 < ff && ff < 8, "0 < ff && ff < 8, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
if (useInvariantFieldLengths) {
dd = 2;
hh = 2;
mm = 2;
ss = 2;
ff = DateTimeFormat.MaxSecondsFractionDigits;
}
else {
if (dd < 1 || dd > 2) dd = 2; // The DTFI property has a problem. let's try to make the best of the situation.
if (hh < 1 || hh > 2) hh = 2;
if (mm < 1 || mm > 2) mm = 2;
if (ss < 1 || ss > 2) ss = 2;
if (ff < 1 || ff > 7) ff = 7;
}
StringBuilderCache.Release(sb);
}
} //end of struct FormatLiterals
}
}
| |
using System;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.IO;
using CamBam;
using CamBam.UI;
using CamBam.CAD;
using CamBam.Util;
namespace Matmill
{
// Insert logger into the matmill namespace to be bound in compile-time
class Logger
{
static public void log(int level, string s, params object[] args)
{
ThisApplication.AddLogMessage(level, s, args);
}
static public void log(string s, params object[] args)
{
ThisApplication.AddLogMessage(4, s, args);
}
static public void warn(string s, params object[] args)
{
ThisApplication.AddLogMessage("Trocho warning: " + s, args);
}
static public void err(string s, params object[] args)
{
ThisApplication.AddLogMessage("Trocho error: " + s, args);
}
}
}
namespace Trochomops
{
// alias for compatibility with the old name of trochoidal pocket
[Serializable]
public class Mop_matmill : MOPTrochopock
{
}
public static class Plug
{
const string pocket_mop_name = "Trochoidal Pocket";
const string profile_mop_name = "Trochoidal Profile";
private static void pocket_mop_onclick(object sender, EventArgs ars)
{
if (!PolylineUtils.ConfirmSelected(CamBamUI.MainUI.ActiveView))
{
return;
}
MOPTrochopock mop = new MOPTrochopock(CamBamUI.MainUI.ActiveView.CADFile, CamBamUI.MainUI.ActiveView.Selection);
CamBamUI.MainUI.InsertMOP(mop);
}
private static void profile_mop_onclick(object sender, EventArgs ars)
{
if (!PolylineUtils.ConfirmSelected(CamBamUI.MainUI.ActiveView))
{
return;
}
MOPTrochoprof mop = new MOPTrochoprof(CamBamUI.MainUI.ActiveView.CADFile, CamBamUI.MainUI.ActiveView.Selection);
CamBamUI.MainUI.InsertMOP(mop);
}
private static void insert_in_top_menu(CamBamUI ui, ToolStripMenuItem entry)
{
for (int i = 0; i < ui.Menus.mnuMachining.DropDownItems.Count; ++i)
{
ToolStripItem tsi = ui.Menus.mnuMachining.DropDownItems[i];
if (tsi is ToolStripSeparator || i == ui.Menus.mnuMachining.DropDownItems.Count - 1)
{
ui.Menus.mnuMachining.DropDownItems.Insert(i, entry);
return;
}
}
}
private static void insert_in_context_menu(CamBamUI ui, ToolStripMenuItem entry)
{
foreach (ToolStripItem tsi in ui.ViewContextMenus.ViewContextMenu.Items)
{
if (tsi is ToolStripMenuItem && tsi.Name == "machineToolStripMenuItem")
{
ToolStripMenuItem tsmi = (ToolStripMenuItem)tsi;
for (int i = 0; i < tsmi.DropDownItems.Count; ++i)
{
if (tsmi.DropDownItems[i] is ToolStripSeparator || i == tsmi.DropDownItems.Count - 1)
{
tsmi.DropDownItems.Insert(i, entry);
return;
}
}
}
}
}
private static void insert_in_toolbar(ToolStripButton button)
{
foreach (Control c in ThisApplication.TopWindow.Controls)
{
if (c is ToolStripContainer)
{
foreach (Control cc in ((ToolStripContainer)c).TopToolStripPanel.Controls)
{
if (cc is CAMToolStrip)
{
CAMToolStrip strip = (CAMToolStrip)cc;
// check if 'Custom CAMToolbar plugin' already iserted us
foreach (ToolStripButton b in strip.Items)
{
if (b.ToolTipText == button.ToolTipText)
return;
}
strip.Items.Add(button);
return;
}
}
}
}
}
private static void on_window_shown(object sender, EventArgs e)
{
ThisApplication.TopWindow.Shown -= on_window_shown;
ToolStripButton button;
button = new ToolStripButton();
button.ToolTipText = TextTranslation.Translate(profile_mop_name);
button.Click += profile_mop_onclick;
button.Image = resources.cam_trochoprof1;
insert_in_toolbar(button);
button = new ToolStripButton();
button.ToolTipText = TextTranslation.Translate(pocket_mop_name);
button.Click += pocket_mop_onclick;
button.Image = resources.cam_trochopock1;
insert_in_toolbar(button);
}
public static void InitPlugin(CamBamUI ui)
{
ToolStripMenuItem menu_entry;
menu_entry = new ToolStripMenuItem();
menu_entry.Text = profile_mop_name;
menu_entry.Click += profile_mop_onclick;
menu_entry.Image = resources.cam_trochoprof1;
insert_in_top_menu(ui, menu_entry);
menu_entry = new ToolStripMenuItem();
menu_entry.Text = profile_mop_name;
menu_entry.Click += profile_mop_onclick;
menu_entry.Image = resources.cam_trochoprof1;
insert_in_context_menu(ui, menu_entry);
menu_entry = new ToolStripMenuItem();
menu_entry.Text = pocket_mop_name;
menu_entry.Click += pocket_mop_onclick;
menu_entry.Image = resources.cam_trochopock1;
insert_in_top_menu(ui, menu_entry);
menu_entry = new ToolStripMenuItem();
menu_entry.Text = pocket_mop_name;
menu_entry.Click += pocket_mop_onclick;
menu_entry.Image = resources.cam_trochopock1;
insert_in_context_menu(ui, menu_entry);
// defer attachment to toolbar until the first show.
// Custom CAM Toolbar plugin (if installed) may already attached us after Load event, so we react on later Shown event
ThisApplication.TopWindow.Shown += on_window_shown;
if (CADFile.ExtraTypes == null)
CADFile.ExtraTypes = new List<Type>();
CADFile.ExtraTypes.Add(typeof(MOPTrochopock));
CADFile.ExtraTypes.Add(typeof(Mop_matmill));
CADFile.ExtraTypes.Add(typeof(MOPTrochoprof));
{
MOPTrochopock o = new MOPTrochopock();
XmlSerializer xmlSerializer = new XmlSerializer(typeof(MOPTrochopock));
MemoryStream stream = new MemoryStream();
xmlSerializer.Serialize(stream, o);
}
{
MOPTrochoprof o = new MOPTrochoprof();
XmlSerializer xmlSerializer = new XmlSerializer(typeof(MOPTrochoprof));
MemoryStream stream = new MemoryStream();
xmlSerializer.Serialize(stream, o);
}
}
}
}
| |
// 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.ServiceModel.Syndication
{
using System.ServiceModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
// NOTE: This class implements Clone so if you add any members, please update the copy ctor
public class SyndicationFeed : IExtensibleSyndicationObject
{
private Collection<SyndicationPerson> _authors;
private Uri _baseUri;
private Collection<SyndicationCategory> _categories;
private Collection<SyndicationPerson> _contributors;
private TextSyndicationContent _copyright;
private TextSyndicationContent _description;
private ExtensibleSyndicationObject _extensions = new ExtensibleSyndicationObject();
private string _generator;
private string _id;
private Uri _imageUrl;
private TextSyndicationContent _imageTitle;
private Uri _imageLink;
private IEnumerable<SyndicationItem> _items;
private string _language;
private DateTimeOffset _lastUpdatedTime;
private Collection<SyndicationLink> _links;
private TextSyndicationContent _title;
// optional RSS tags
private SyndicationLink _documentation;
private int _timeToLive;
private Collection<int> _skipHours;
private Collection<string> _skipDays;
private SyndicationTextInput _textInput;
private Uri _iconImage;
public Uri IconImage
{
get
{
return _iconImage;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
_iconImage = value;
}
}
public SyndicationTextInput TextInput
{
get
{
return _textInput;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
_textInput = value;
}
}
public SyndicationLink Documentation
{
get
{
return _documentation;
}
set
{
_documentation = value;
}
}
public int TimeToLive
{
get
{
return _timeToLive;
}
set
{
_timeToLive = value;
}
}
public Collection<int> SkipHours
{
get
{
if (_skipHours == null)
_skipHours = new Collection<int>();
return _skipHours;
}
}
public Collection<string> SkipDays
{
get
{
if (_skipDays == null)
_skipDays = new Collection<string>();
return _skipDays;
}
}
//======================================
public SyndicationFeed()
: this((IEnumerable<SyndicationItem>)null)
{
}
public SyndicationFeed(IEnumerable<SyndicationItem> items)
: this(null, null, null, items)
{
}
public SyndicationFeed(string title, string description, Uri feedAlternateLink)
: this(title, description, feedAlternateLink, null)
{
}
public SyndicationFeed(string title, string description, Uri feedAlternateLink, IEnumerable<SyndicationItem> items)
: this(title, description, feedAlternateLink, null, DateTimeOffset.MinValue, items)
{
}
public SyndicationFeed(string title, string description, Uri feedAlternateLink, string id, DateTimeOffset lastUpdatedTime)
: this(title, description, feedAlternateLink, id, lastUpdatedTime, null)
{
}
public SyndicationFeed(string title, string description, Uri feedAlternateLink, string id, DateTimeOffset lastUpdatedTime, IEnumerable<SyndicationItem> items)
{
if (title != null)
{
_title = new TextSyndicationContent(title);
}
if (description != null)
{
_description = new TextSyndicationContent(description);
}
if (feedAlternateLink != null)
{
this.Links.Add(SyndicationLink.CreateAlternateLink(feedAlternateLink));
}
_id = id;
_lastUpdatedTime = lastUpdatedTime;
_items = items;
}
protected SyndicationFeed(SyndicationFeed source, bool cloneItems)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
_authors = FeedUtils.ClonePersons(source._authors);
_categories = FeedUtils.CloneCategories(source._categories);
_contributors = FeedUtils.ClonePersons(source._contributors);
_copyright = FeedUtils.CloneTextContent(source._copyright);
_description = FeedUtils.CloneTextContent(source._description);
_extensions = source._extensions.Clone();
_generator = source._generator;
_id = source._id;
_imageUrl = source._imageUrl;
_language = source._language;
_lastUpdatedTime = source._lastUpdatedTime;
_links = FeedUtils.CloneLinks(source._links);
_title = FeedUtils.CloneTextContent(source._title);
_baseUri = source._baseUri;
IList<SyndicationItem> srcList = source._items as IList<SyndicationItem>;
if (srcList != null)
{
Collection<SyndicationItem> tmp = new NullNotAllowedCollection<SyndicationItem>();
for (int i = 0; i < srcList.Count; ++i)
{
tmp.Add((cloneItems) ? srcList[i].Clone() : srcList[i]);
}
_items = tmp;
}
else
{
if (cloneItems)
{
throw new InvalidOperationException(SR.UnbufferedItemsCannotBeCloned);
}
_items = source._items;
}
}
public Dictionary<XmlQualifiedName, string> AttributeExtensions
{
get { return _extensions.AttributeExtensions; }
}
public Collection<SyndicationPerson> Authors
{
get
{
if (_authors == null)
{
_authors = new NullNotAllowedCollection<SyndicationPerson>();
}
return _authors;
}
}
public Uri BaseUri
{
get { return _baseUri; }
set { _baseUri = value; }
}
public Collection<SyndicationCategory> Categories
{
get
{
if (_categories == null)
{
_categories = new NullNotAllowedCollection<SyndicationCategory>();
}
return _categories;
}
}
public Collection<SyndicationPerson> Contributors
{
get
{
if (_contributors == null)
{
_contributors = new NullNotAllowedCollection<SyndicationPerson>();
}
return _contributors;
}
}
public TextSyndicationContent Copyright
{
get { return _copyright; }
set { _copyright = value; }
}
public TextSyndicationContent Description
{
get { return _description; }
set { _description = value; }
}
public SyndicationElementExtensionCollection ElementExtensions
{
get { return _extensions.ElementExtensions; }
}
public string Generator
{
get { return _generator; }
set { _generator = value; }
}
public string Id
{
get { return _id; }
set { _id = value; }
}
public Uri ImageUrl
{
get { return _imageUrl; }
set { _imageUrl = value; }
}
public TextSyndicationContent ImageTitle
{
get { return _imageTitle; }
set { _imageTitle = value; }
}
public Uri ImageLink
{
get { return _imageLink; }
set { _imageLink = value; }
}
public IEnumerable<SyndicationItem> Items
{
get
{
if (_items == null)
{
_items = new NullNotAllowedCollection<SyndicationItem>();
}
return _items;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_items = value;
}
}
public string Language
{
get { return _language; }
set { _language = value; }
}
public DateTimeOffset LastUpdatedTime
{
get { return _lastUpdatedTime; }
set { _lastUpdatedTime = value; }
}
public Collection<SyndicationLink> Links
{
get
{
if (_links == null)
{
_links = new NullNotAllowedCollection<SyndicationLink>();
}
return _links;
}
}
public TextSyndicationContent Title
{
get { return _title; }
set { _title = value; }
}
//// Custom Parsing
public static async Task<SyndicationFeed> LoadAsync(XmlReader reader, Rss20FeedFormatter formatter, CancellationToken ct)
{
return await LoadAsync(reader, formatter, new Atom10FeedFormatter(), ct);
}
public static async Task<SyndicationFeed> LoadAsync(XmlReader reader, Atom10FeedFormatter formatter, CancellationToken ct)
{
return await LoadAsync(reader, new Rss20FeedFormatter(), formatter, ct);
}
public static async Task<SyndicationFeed> LoadAsync(XmlReader reader, Rss20FeedFormatter Rssformatter, Atom10FeedFormatter Atomformatter, CancellationToken ct)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
XmlReaderWrapper wrappedReader = XmlReaderWrapper.CreateFromReader(reader);
Atom10FeedFormatter atomSerializer = Atomformatter;
if (atomSerializer.CanRead(wrappedReader))
{
await atomSerializer.ReadFromAsync(wrappedReader, new CancellationToken());
return atomSerializer.Feed;
}
Rss20FeedFormatter rssSerializer = Rssformatter;
if (rssSerializer.CanRead(wrappedReader))
{
await rssSerializer.ReadFromAsync(wrappedReader, new CancellationToken());
return rssSerializer.Feed;
}
throw new XmlException(string.Format(SR.UnknownFeedXml, wrappedReader.LocalName, wrappedReader.NamespaceURI));
}
//=================================
public static SyndicationFeed Load(XmlReader reader)
{
return Load<SyndicationFeed>(reader);
}
public static TSyndicationFeed Load<TSyndicationFeed>(XmlReader reader)
where TSyndicationFeed : SyndicationFeed, new()
{
CancellationToken ct = new CancellationToken();
return LoadAsync<TSyndicationFeed>(reader, ct).GetAwaiter().GetResult();
}
public static async Task<SyndicationFeed> LoadAsync(XmlReader reader, CancellationToken ct)
{
return await LoadAsync<SyndicationFeed>(reader, ct);
}
public static async Task<TSyndicationFeed> LoadAsync<TSyndicationFeed>(XmlReader reader, CancellationToken ct)
where TSyndicationFeed : SyndicationFeed, new()
{
Atom10FeedFormatter<TSyndicationFeed> atomSerializer = new Atom10FeedFormatter<TSyndicationFeed>();
if (atomSerializer.CanRead(reader))
{
await atomSerializer.ReadFromAsync(reader, ct);
return atomSerializer.Feed as TSyndicationFeed;
}
Rss20FeedFormatter<TSyndicationFeed> rssSerializer = new Rss20FeedFormatter<TSyndicationFeed>();
if (rssSerializer.CanRead(reader))
{
await rssSerializer.ReadFromAsync(reader, ct);
return rssSerializer.Feed as TSyndicationFeed;
}
throw new XmlException(string.Format(SR.UnknownFeedXml, reader.LocalName, reader.NamespaceURI));
}
public virtual SyndicationFeed Clone(bool cloneItems)
{
return new SyndicationFeed(this, cloneItems);
}
public Atom10FeedFormatter GetAtom10Formatter()
{
return new Atom10FeedFormatter(this);
}
public Rss20FeedFormatter GetRss20Formatter()
{
return GetRss20Formatter(true);
}
public Rss20FeedFormatter GetRss20Formatter(bool serializeExtensionsAsAtom)
{
return new Rss20FeedFormatter(this, serializeExtensionsAsAtom);
}
public Task SaveAsAtom10Async(XmlWriter writer, CancellationToken ct)
{
return GetAtom10Formatter().WriteToAsync(writer, ct);
}
public Task SaveAsRss20Async(XmlWriter writer, CancellationToken ct)
{
return GetRss20Formatter().WriteToAsync(writer, ct);
}
protected internal virtual SyndicationCategory CreateCategory()
{
return new SyndicationCategory();
}
protected internal virtual SyndicationItem CreateItem()
{
return new SyndicationItem();
}
protected internal virtual SyndicationLink CreateLink()
{
return new SyndicationLink();
}
protected internal virtual SyndicationPerson CreatePerson()
{
return new SyndicationPerson();
}
protected internal virtual bool TryParseAttribute(string name, string ns, string value, string version)
{
return false;
}
protected internal virtual bool TryParseElement(XmlReader reader, string version)
{
return false;
}
protected internal virtual Task WriteAttributeExtensionsAsync(XmlWriter writer, string version)
{
return _extensions.WriteAttributeExtensionsAsync(writer);
}
protected internal virtual Task WriteElementExtensionsAsync(XmlWriter writer, string version)
{
return _extensions.WriteElementExtensionsAsync(writer);
}
internal void LoadElementExtensions(XmlReader readerOverUnparsedExtensions, int maxExtensionSize)
{
_extensions.LoadElementExtensions(readerOverUnparsedExtensions, maxExtensionSize);
}
internal void LoadElementExtensions(XmlBuffer buffer)
{
_extensions.LoadElementExtensions(buffer);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using StructureMap.Building;
using StructureMap.Building.Interception;
using StructureMap.Diagnostics;
using StructureMap.Graph;
using StructureMap.TypeRules;
namespace StructureMap.Pipeline
{
public abstract class Instance : HasLifecycle, IDescribed
{
private readonly string _originalName;
private string _name;
private readonly IList<IInterceptor> _interceptors = new List<IInterceptor>();
/// <summary>
/// Add an interceptor to only this Instance
/// </summary>
/// <param name="interceptor"></param>
public void AddInterceptor(IInterceptor interceptor)
{
if (ReturnedType != null && !ReturnedType.CanBeCastTo(interceptor.Accepts))
{
throw new ArgumentOutOfRangeException(
"ReturnedType {0} cannot be cast to the Interceptor Accepts type {1}".ToFormat(
ReturnedType.GetFullName(), interceptor.Accepts.GetFullName()));
}
_interceptors.Add(interceptor);
}
protected Instance()
{
Id = Guid.NewGuid();
_originalName = _name = Id.ToString();
}
/// <summary>
/// Strategy for how this Instance would be built as
/// an inline dependency in the parent Instance's
/// "Build Plan"
/// </summary>
/// <param name="pluginType"></param>
/// <returns></returns>
public abstract IDependencySource ToDependencySource(Type pluginType);
/// <summary>
/// Creates an IDependencySource that can be used to build the object
/// represented by this Instance
/// </summary>
/// <param name="pluginType"></param>
/// <param name="policies"></param>
/// <returns></returns>
public virtual IDependencySource ToBuilder(Type pluginType, Policies policies)
{
return ToDependencySource(pluginType);
}
public IEnumerable<IInterceptor> Interceptors
{
get { return _interceptors; }
}
public virtual string Name
{
get { return _name; }
set { _name = value; }
}
public abstract string Description { get; }
public InstanceToken CreateToken()
{
return new InstanceToken(Name, Description);
}
/// <summary>
/// The known .Net Type built by this Instance. May be null when indeterminate.
/// </summary>
public abstract Type ReturnedType { get; }
/// <summary>
/// Does this Instance have a user-defined name?
/// </summary>
/// <returns></returns>
public bool HasExplicitName()
{
return _name != _originalName;
}
/// <summary>
/// Return the closed type value for this Instance
/// when starting from an open generic type
/// </summary>
/// <param name="types"></param>
/// <returns></returns>
public virtual Instance CloseType(Type[] types)
{
return this;
}
private readonly object _buildLock = new object();
private IBuildPlan _plan;
/// <summary>
/// Resolves the IBuildPlan for this Instance. The result is remembered
/// for subsequent requests
/// </summary>
/// <param name="pluginType"></param>
/// <param name="policies"></param>
/// <returns></returns>
public IBuildPlan ResolveBuildPlan(Type pluginType, Policies policies)
{
lock (_buildLock)
{
return _plan ?? (_plan = buildPlan(pluginType, policies));
}
}
/// <summary>
/// Clears out any remembered IBuildPlan for this Instance
/// </summary>
public void ClearBuildPlan()
{
lock (_buildLock)
{
_plan = null;
}
}
private string toDescription(Type pluginType)
{
var typeName = (pluginType ?? ReturnedType).GetFullName();
if (HasExplicitName())
{
return "Instance of {0} ({1}) -- {2}".ToFormat(typeName, Name, Description);
}
return "Instance of {0} -- {1}".ToFormat(typeName, Description);
}
protected virtual IBuildPlan buildPlan(Type pluginType, Policies policies)
{
try
{
var builderSource = ToBuilder(pluginType, policies);
var interceptors = determineInterceptors(pluginType, policies);
return new BuildPlan(pluginType, this, builderSource, policies, interceptors);
}
catch (StructureMapException e)
{
e.Push("Attempting to create a BuildPlan for " + toDescription(pluginType));
throw;
}
catch (Exception e)
{
throw new StructureMapBuildPlanException(
"Error while trying to create the BuildPlan for {0}.\nPlease check the inner exception".ToFormat(
toDescription(pluginType)), e);
}
}
protected IEnumerable<IInterceptor> determineInterceptors(Type pluginType, Policies policies)
{
var interceptors =
policies.Interceptors.SelectInterceptors(pluginType, this).Union(_interceptors);
return interceptors;
}
/// <summary>
/// Creates a hash that is unique for this Instance and PluginType combination
/// </summary>
/// <param name="pluginType"></param>
/// <returns></returns>
public int InstanceKey(Type pluginType)
{
unchecked
{
return ((_originalName != null ? _originalName.GetHashCode() : 0)*397) ^
(pluginType != null ? pluginType.AssemblyQualifiedName.GetHashCode() : 0);
}
}
public ILifecycle DetermineLifecycle(ILifecycle parent)
{
return Lifecycle ?? parent ?? Lifecycles.Transient;
}
protected bool Equals(Instance other)
{
return string.Equals(_originalName, other._originalName);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Instance) obj);
}
public override int GetHashCode()
{
return (_originalName != null ? _originalName.GetHashCode() : 0);
}
public Guid Id { get; private set; }
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
namespace PiHexScreensaver
{
class PiHex
{
private static double[] tp = new double[25];
private static int tp1 = 0;
private static bool firstCheck = false;
private static char[] previousSequence = new char[16];
//private static bool fileExists = false;
//private static int currentDigit = 0;
private static bool firstResume = true;
private static string ihex(double x, int nhx, char[] chx)
{
//This returns, in chx, the first nhx hex digits of the fraction of x.
int i = 0;
double y = 0;
char[] hx = "0123456789ABCDEF".ToCharArray();
y = Math.Abs(x);
string temp = "";
for (i = 0; i < nhx; i++)
{
y = 16 * (y - Math.Floor(y));
//chx[i] = hx[(int) y];
temp += hx[(int)y];
}
return temp;
}
private static double series(int m, int id)
{
//This routine evaluates the series sum_k 16^(id-k)/(8*k+m)
//using the modular exponentiation technique.
int k = 0;
double ak = 0;
double eps = 0;
double p = 0;
double s = 0;
double t = 0;
//double expm(double x, double y);
//#define eps 1e-17
s = 0;
//Sum the series up to id.
for (k = 0; k < id; k++)
{
ak = 8 * k + m;
p = id - k;
t = expm(p, ak);
s = s + t / ak;
s = s - (int)s;
}
//Compute a few terms where k >= id.
for (k = id; k <= id + 100; k++)
{
ak = 8 * k + m;
t = Math.Pow(16, (double)(id - k)) / ak;
if (t < eps) break;
s = s + t;
s = s - (int)s;
}
return s;
}
private static double expm(double p, double ak)
{
//expm = 16^p mod ak. This routine uses the left-to-right binary
//exponentiation scheme.
int i = 0;
int j = 0;
double p1 = 0;
double pt = 0;
double r = 0;
//If this is the first call to expm, fill the power of two table tp.
if (tp1 == 0)
{
tp1 = 1;
tp[0] = 1;
for (i = 1; i < 25; i++) { tp[i] = 2 * tp[i - 1]; }
}
if (ak == 1) return 0;
//Find the greatest power of two less than or equal to p.
for (i = 0; i < 25; i++) if (tp[i] > p) break;
pt = tp[i - 1];
p1 = p;
r = 1;
//Perform binary exponentiation algorithm modulo ak.
for (j = 1; j <= i; j++)
{
if (p1 >= pt)
{
r = 16 * r;
r = r - (int)(r / ak) * ak;
p1 = p1 - pt;
}
pt = 0.5 * pt;
if (pt >= 1)
{
r = r * r;
r = r - (int)(r / ak) * ak;
}
}
return r;
}
public static string hexToIntegerString(char[] hexChars)
{
string hexStringOut = "";
for (int i = 0; i < hexChars.Length; i++)
{
char hexCharTemp = hexChars[i];
if (i == 0)
{
switch (hexCharTemp)
{
case 'A':
hexStringOut += "10";
break;
case 'B':
hexStringOut += "11";
break;
case 'C':
hexStringOut += "12";
break;
case 'D':
hexStringOut += "13";
break;
case 'E':
hexStringOut += "14";
break;
case 'F':
hexStringOut += "15";
break;
default:
hexStringOut += hexCharTemp;
break;
}
}
else
{
switch (hexCharTemp)
{
case 'A':
hexStringOut += ", 10";
break;
case 'B':
hexStringOut += ", 11";
break;
case 'C':
hexStringOut += ", 12";
break;
case 'D':
hexStringOut += ", 13";
break;
case 'E':
hexStringOut += ", 14";
break;
case 'F':
hexStringOut += ", 15";
break;
default:
hexStringOut += ", " + hexCharTemp;
break;
}
}
}
return hexStringOut;
}
public static string nthHexDigitOfPi(int id)
{
double pid = 0;
double s1 = 0;
double s2 = 0;
double s3 = 0;
double s4 = 0;
char[] chx = new char[16];
s1 = series(1, id);
s2 = series(4, id);
s3 = series(5, id);
s4 = series(6, id);
pid = 4 * s1 - 2 * s2 - s3 - s4;
pid = pid - (int)pid;
if (pid < 0.0) pid = pid + 1.0;
string hexString = ihex(pid, 16, chx);
if (PiHexSession.isErrorChecking() == true)
{
String tempHex = errorCheck(hexString.ToCharArray()).ToString();
if (PiHexSession.isLogging()) { saveDigitToTempFile(tempHex); }
return tempHex;
}
if (PiHexSession.isLogging()) { saveDigitToTempFile(hexString.Substring(0, 1)); }
return hexString.Substring(0, 1);
}
private static char errorCheck(char[] hexStringCheck)
{
if (firstCheck == false)
{
char charOut = hexStringCheck[0];
previousSequence = hexStringCheck;
firstCheck = true;
return charOut;
}
for (int i = 0; i < 4; i++)
{
if (!hexStringCheck[i].Equals(previousSequence[i + 1]))
{
previousSequence = hexStringCheck;
return '?';
}
}
char charOut2 = hexStringCheck[0];
previousSequence = hexStringCheck;
return charOut2;
}
private static void saveDigitToTempFile(string digit)
{
if (!(File.Exists(PiHexSession.localTempFile)))
{
StreamWriter SW = File.CreateText(PiHexSession.localTempFile);
SW.Write(digit);
SW.Close();
}
else
{
StreamWriter SW = File.AppendText(PiHexSession.localTempFile);
SW.Write(digit);
SW.Close();
}
}
//private static void log(string data)
//{
// if (logging == true)
// {
// if (File.Exists(logFile) == false)
// {
// StreamWriter SW4;
// SW4 = File.CreateText("C:\\WINDOWS\\system32\\PiHexSpacingSettings.dat");
// SW4.WriteLine("0");
// SW4.WriteLine("0");
// SW4.WriteLine("0");
// SW4.Close();
// StreamWriter SW;
// SW = File.CreateText(logFile);
// SW.Write("3.");
// SW.Close();
// }
// StreamWriter SW6;
// SW6 = File.AppendText(logFile);
// if (currentDigit == 10000000) { SW6.Write("\n\n--------------------------------------------------------------------------\nAccuracy of Pi cannot be gaureenteed past 10000000 digits on this machine.\n--------------------------------------------------------------------------\n"); spacing = 0; spacingSet = 0; }
// if (spacing % 5 == 0) { SW6.Write(" "); spacing = 0; }
// if (spacingSet % 50 == 0) { SW6.Write("\n"); spacing = 0; spacingSet = 0; }
// if (spacingSet % 25 == 0) { SW6.Write(" "); }
// SW6.Write(data);
// SW6.Close();
// spacing++;
// spacingSet++;
// StreamWriter SW2;
// SW2 = File.CreateText(logSettings);
// SW2.WriteLine(currentDigit + 1);
// SW2.WriteLine(spacing);
// SW2.WriteLine(spacingSet);
// SW2.Close();
// }
//}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.Serialization;
using System.Text;
// This HttpHandlerDiagnosticListener class is applicable only for .NET 4.6, and not for .NET core.
namespace System.Diagnostics
{
/// <summary>
/// A HttpHandlerDiagnosticListener is a DiagnosticListener for .NET 4.6 and above where
/// HttpClient doesn't have a DiagnosticListener built in. This class is not used for .NET Core
/// because HttpClient in .NET Core already emits DiagnosticSource events. This class compensates for
/// that in .NET 4.6 and above. HttpHandlerDiagnosticListener has no public constructor. To use this,
/// the application just needs to call <see cref="DiagnosticListener.AllListeners" /> and
/// <see cref="DiagnosticListener.AllListenerObservable.Subscribe(IObserver{DiagnosticListener})"/>,
/// then in the <see cref="IObserver{DiagnosticListener}.OnNext(DiagnosticListener)"/> method,
/// when it sees the System.Net.Http.Desktop source, subscribe to it. This will trigger the
/// initialization of this DiagnosticListener.
/// </summary>
internal sealed class HttpHandlerDiagnosticListener : DiagnosticListener
{
/// <summary>
/// Overriding base class implementation just to give us a chance to initialize.
/// </summary>
public override IDisposable Subscribe(IObserver<KeyValuePair<string, object>> observer, Predicate<string> isEnabled)
{
IDisposable result = base.Subscribe(observer, isEnabled);
Initialize();
return result;
}
/// <summary>
/// Overriding base class implementation just to give us a chance to initialize.
/// </summary>
public override IDisposable Subscribe(IObserver<KeyValuePair<string, object>> observer, Func<string, object, object, bool> isEnabled)
{
IDisposable result = base.Subscribe(observer, isEnabled);
Initialize();
return result;
}
/// <summary>
/// Overriding base class implementation just to give us a chance to initialize.
/// </summary>
public override IDisposable Subscribe(IObserver<KeyValuePair<string, object>> observer)
{
IDisposable result = base.Subscribe(observer);
Initialize();
return result;
}
/// <summary>
/// Initializes all the reflection objects it will ever need. Reflection is costly, but it's better to take
/// this one time performance hit than to get it multiple times later, or do it lazily and have to worry about
/// threading issues. If Initialize has been called before, it will not doing anything.
/// </summary>
private void Initialize()
{
lock (this)
{
if (!this.initialized)
{
try
{
// This flag makes sure we only do this once. Even if we failed to initialize in an
// earlier time, we should not retry because this initialization is not cheap and
// the likelihood it will succeed the second time is very small.
this.initialized = true;
PrepareReflectionObjects();
PerformInjection();
}
catch (Exception ex)
{
// If anything went wrong, just no-op. Write an event so at least we can find out.
this.Write(InitializationFailed, new { Exception = ex });
}
}
}
}
#region private helper classes
private class HashtableWrapper : Hashtable, IEnumerable
{
protected Hashtable _table;
public override int Count
{
get
{
return this._table.Count;
}
}
public override bool IsReadOnly
{
get
{
return this._table.IsReadOnly;
}
}
public override bool IsFixedSize
{
get
{
return this._table.IsFixedSize;
}
}
public override bool IsSynchronized
{
get
{
return this._table.IsSynchronized;
}
}
public override object this[object key]
{
get
{
return this._table[key];
}
set
{
this._table[key] = value;
}
}
public override object SyncRoot
{
get
{
return this._table.SyncRoot;
}
}
public override ICollection Keys
{
get
{
return this._table.Keys;
}
}
public override ICollection Values
{
get
{
return this._table.Values;
}
}
internal HashtableWrapper(Hashtable table) : base()
{
this._table = table;
}
public override void Add(object key, object value)
{
this._table.Add(key, value);
}
public override void Clear()
{
this._table.Clear();
}
public override bool Contains(object key)
{
return this._table.Contains(key);
}
public override bool ContainsKey(object key)
{
return this._table.ContainsKey(key);
}
public override bool ContainsValue(object key)
{
return this._table.ContainsValue(key);
}
public override void CopyTo(Array array, int arrayIndex)
{
this._table.CopyTo(array, arrayIndex);
}
public override object Clone()
{
return new HashtableWrapper((Hashtable)this._table.Clone());
}
IEnumerator IEnumerable.GetEnumerator()
{
return this._table.GetEnumerator();
}
public override IDictionaryEnumerator GetEnumerator()
{
return this._table.GetEnumerator();
}
public override void Remove(object key)
{
this._table.Remove(key);
}
}
/// <summary>
/// Helper class used for ServicePointManager.s_ServicePointTable. The goal here is to
/// intercept each new ServicePoint object being added to ServicePointManager.s_ServicePointTable
/// and replace its ConnectionGroupList hashtable field.
/// </summary>
private sealed class ServicePointHashtable : HashtableWrapper
{
public ServicePointHashtable(Hashtable table) : base(table)
{
}
public override object this[object key]
{
get
{
return base[key];
}
set
{
WeakReference weakRef = value as WeakReference;
if (weakRef != null && weakRef.IsAlive)
{
ServicePoint servicePoint = weakRef.Target as ServicePoint;
if (servicePoint != null)
{
// Replace the ConnectionGroup hashtable inside this ServicePoint object,
// which allows us to intercept each new ConnectionGroup object added under
// this ServicePoint.
Hashtable originalTable = s_connectionGroupListField.GetValue(servicePoint) as Hashtable;
ConnectionGroupHashtable newTable = new ConnectionGroupHashtable(originalTable ?? new Hashtable());
s_connectionGroupListField.SetValue(servicePoint, newTable);
}
}
base[key] = value;
}
}
}
/// <summary>
/// Helper class used for ServicePoint.m_ConnectionGroupList. The goal here is to
/// intercept each new ConnectionGroup object being added to ServicePoint.m_ConnectionGroupList
/// and replace its m_ConnectionList arraylist field.
/// </summary>
private sealed class ConnectionGroupHashtable : HashtableWrapper
{
public ConnectionGroupHashtable(Hashtable table) : base(table)
{
}
public override object this[object key]
{
get
{
return base[key];
}
set
{
if (s_connectionGroupType.IsInstanceOfType(value))
{
// Replace the Connection arraylist inside this ConnectionGroup object,
// which allows us to intercept each new Connection object added under
// this ConnectionGroup.
ArrayList originalArrayList = s_connectionListField.GetValue(value) as ArrayList;
ConnectionArrayList newArrayList = new ConnectionArrayList(originalArrayList ?? new ArrayList());
s_connectionListField.SetValue(value, newArrayList);
}
base[key] = value;
}
}
}
/// <summary>
/// Helper class used to wrap the array list object. This class itself doesn't actually
/// have the array elements, but rather access another array list that's given at
/// construction time.
/// </summary>
private class ArrayListWrapper : ArrayList
{
private ArrayList _list;
public override int Capacity
{
get
{
return this._list.Capacity;
}
set
{
this._list.Capacity = value;
}
}
public override int Count
{
get
{
return this._list.Count;
}
}
public override bool IsReadOnly
{
get
{
return this._list.IsReadOnly;
}
}
public override bool IsFixedSize
{
get
{
return this._list.IsFixedSize;
}
}
public override bool IsSynchronized
{
get
{
return this._list.IsSynchronized;
}
}
public override object this[int index]
{
get
{
return this._list[index];
}
set
{
this._list[index] = value;
}
}
public override object SyncRoot
{
get
{
return this._list.SyncRoot;
}
}
internal ArrayListWrapper(ArrayList list) : base()
{
this._list = list;
}
public override int Add(object value)
{
return this._list.Add(value);
}
public override void AddRange(ICollection c)
{
this._list.AddRange(c);
}
public override int BinarySearch(object value)
{
return this._list.BinarySearch(value);
}
public override int BinarySearch(object value, IComparer comparer)
{
return this._list.BinarySearch(value, comparer);
}
public override int BinarySearch(int index, int count, object value, IComparer comparer)
{
return this._list.BinarySearch(index, count, value, comparer);
}
public override void Clear()
{
this._list.Clear();
}
public override object Clone()
{
return new ArrayListWrapper((ArrayList)this._list.Clone());
}
public override bool Contains(object item)
{
return this._list.Contains(item);
}
public override void CopyTo(Array array)
{
this._list.CopyTo(array);
}
public override void CopyTo(Array array, int index)
{
this._list.CopyTo(array, index);
}
public override void CopyTo(int index, Array array, int arrayIndex, int count)
{
this._list.CopyTo(index, array, arrayIndex, count);
}
public override IEnumerator GetEnumerator()
{
return this._list.GetEnumerator();
}
public override IEnumerator GetEnumerator(int index, int count)
{
return this._list.GetEnumerator(index, count);
}
public override int IndexOf(object value)
{
return this._list.IndexOf(value);
}
public override int IndexOf(object value, int startIndex)
{
return this._list.IndexOf(value, startIndex);
}
public override int IndexOf(object value, int startIndex, int count)
{
return this._list.IndexOf(value, startIndex, count);
}
public override void Insert(int index, object value)
{
this._list.Insert(index, value);
}
public override void InsertRange(int index, ICollection c)
{
this._list.InsertRange(index, c);
}
public override int LastIndexOf(object value)
{
return this._list.LastIndexOf(value);
}
public override int LastIndexOf(object value, int startIndex)
{
return this._list.LastIndexOf(value, startIndex);
}
public override int LastIndexOf(object value, int startIndex, int count)
{
return this._list.LastIndexOf(value, startIndex, count);
}
public override void Remove(object value)
{
this._list.Remove(value);
}
public override void RemoveAt(int index)
{
this._list.RemoveAt(index);
}
public override void RemoveRange(int index, int count)
{
this._list.RemoveRange(index, count);
}
public override void Reverse(int index, int count)
{
this._list.Reverse(index, count);
}
public override void SetRange(int index, ICollection c)
{
this._list.SetRange(index, c);
}
public override ArrayList GetRange(int index, int count)
{
return this._list.GetRange(index, count);
}
public override void Sort()
{
this._list.Sort();
}
public override void Sort(IComparer comparer)
{
this._list.Sort(comparer);
}
public override void Sort(int index, int count, IComparer comparer)
{
this._list.Sort(index, count, comparer);
}
public override object[] ToArray()
{
return this._list.ToArray();
}
public override Array ToArray(Type type)
{
return this._list.ToArray(type);
}
public override void TrimToSize()
{
this._list.TrimToSize();
}
}
/// <summary>
/// Helper class used for ConnectionGroup.m_ConnectionList. The goal here is to
/// intercept each new Connection object being added to ConnectionGroup.m_ConnectionList
/// and replace its m_WriteList arraylist field.
/// </summary>
private sealed class ConnectionArrayList : ArrayListWrapper
{
public ConnectionArrayList(ArrayList list) : base(list)
{
}
public override int Add(object value)
{
if (s_connectionType.IsInstanceOfType(value))
{
// Replace the HttpWebRequest arraylist inside this Connection object,
// which allows us to intercept each new HttpWebRequest object added under
// this Connection.
ArrayList originalArrayList = s_writeListField.GetValue(value) as ArrayList;
HttpWebRequestArrayList newArrayList = new HttpWebRequestArrayList(originalArrayList ?? new ArrayList());
s_writeListField.SetValue(value, newArrayList);
}
return base.Add(value);
}
}
/// <summary>
/// Helper class used for Connection.m_WriteList. The goal here is to
/// intercept all new HttpWebRequest objects being added to Connection.m_WriteList
/// and notify the listener about the HttpWebRequest that's about to send a request.
/// It also intercepts all HttpWebRequest objects that are about to get removed from
/// Connection.m_WriteList as they have completed the request.
/// </summary>
private sealed class HttpWebRequestArrayList : ArrayListWrapper
{
public HttpWebRequestArrayList(ArrayList list) : base(list)
{
}
public override int Add(object value)
{
HttpWebRequest request = value as HttpWebRequest;
if (request != null)
{
s_instance.RaiseRequestEvent(request);
}
return base.Add(value);
}
public override void RemoveAt(int index)
{
HttpWebRequest request = base[index] as HttpWebRequest;
if (request != null)
{
HttpWebResponse response = s_httpResponseAccessor(request);
if (response != null)
{
s_instance.RaiseResponseEvent(request, response);
}
else
{
// In case reponse content length is 0 and request is async,
// we won't have a HttpWebResponse set on request object when this method is called
// http://referencesource.microsoft.com/#System/net/System/Net/HttpWebResponse.cs,525
// But we there will be CoreResponseData object that is either exception
// or the internal HTTP reponse representation having status, content and headers
var coreResponse = s_coreResponseAccessor(request);
if (coreResponse != null && s_coreResponseDataType.IsInstanceOfType(coreResponse))
{
HttpStatusCode status = s_coreStatusCodeAccessor(coreResponse);
WebHeaderCollection headers = s_coreHeadersAccessor(coreResponse);
// Manual creation of HttpWebResponse here is not possible as this method is eventually called from the
// HttpWebResponse ctor. So we will send Stop event with the Status and Headers payload
// to notify listeners about response;
// We use two different names for Stop events since one event with payload type that varies creates
// complications for efficient payload parsing and is not supported by DiagnosicSource helper
// libraries (e.g. Microsoft.Extensions.DiagnosticAdapter)
s_instance.RaiseResponseEvent(request, status, headers);
}
}
}
base.RemoveAt(index);
}
}
#endregion
#region private methods
/// <summary>
/// Private constructor. This class implements a singleton pattern and only this class is allowed to create an instance.
/// </summary>
private HttpHandlerDiagnosticListener() : base(DiagnosticListenerName)
{
}
private void RaiseRequestEvent(HttpWebRequest request)
{
if (request.Headers.Get(RequestIdHeaderName) != null)
{
// this request was instrumented by previous RaiseRequestEvent
return;
}
if (this.IsEnabled(ActivityName, request))
{
var activity = new Activity(ActivityName);
// Only send start event to users who subscribed for it, but start activity anyway
if (this.IsEnabled(RequestStartName))
{
this.StartActivity(activity, new { Request = request });
}
else
{
activity.Start();
}
request.Headers.Add(RequestIdHeaderName, activity.Id);
// we expect baggage to be empty or contain a few items
using (IEnumerator<KeyValuePair<string, string>> e = activity.Baggage.GetEnumerator())
{
if (e.MoveNext())
{
StringBuilder baggage = new StringBuilder();
do
{
KeyValuePair<string, string> item = e.Current;
baggage.Append(item.Key).Append('=').Append(item.Value).Append(',');
}
while (e.MoveNext());
baggage.Remove(baggage.Length - 1, 1);
request.Headers.Add(CorrelationContextHeaderName, baggage.ToString());
}
}
// There is no gurantee that Activity.Current will flow to the Response, so let's stop it here
activity.Stop();
}
}
private void RaiseResponseEvent(HttpWebRequest request, HttpWebResponse response)
{
// Response event could be received several times for the same request in case it was redirected
// IsLastResponse checks if response is the last one (no more redirects will happen)
// based on response StatusCode and number or redirects done so far
if (request.Headers[RequestIdHeaderName] != null && IsLastResponse(request, response.StatusCode))
{
// only send Stop if request was instrumented
this.Write(RequestStopName, new { Request = request, Response = response });
}
}
private void RaiseResponseEvent(HttpWebRequest request, HttpStatusCode statusCode, WebHeaderCollection headers)
{
// Response event could be received several times for the same request in case it was redirected
// IsLastResponse checks if response is the last one (no more redirects will happen)
// based on response StatusCode and number or redirects done so far
if (request.Headers[RequestIdHeaderName] != null && IsLastResponse(request, statusCode))
{
this.Write(RequestStopExName, new { Request = request, StatusCode = statusCode, Headers = headers });
}
}
private bool IsLastResponse(HttpWebRequest request, HttpStatusCode statusCode)
{
if (request.AllowAutoRedirect)
{
if (statusCode == HttpStatusCode.Ambiguous || // 300
statusCode == HttpStatusCode.Moved || // 301
statusCode == HttpStatusCode.Redirect || // 302
statusCode == HttpStatusCode.RedirectMethod || // 303
statusCode == HttpStatusCode.RedirectKeepVerb || // 307
(int)statusCode == 308) // 308 Permanent Redirect is not in netfx yet, and so has to be specified this way.
{
return s_autoRedirectsAccessor(request) >= request.MaximumAutomaticRedirections;
}
}
return true;
}
private static void PrepareReflectionObjects()
{
// At any point, if the operation failed, it should just throw. The caller should catch all exceptions and swallow.
// First step: Get all the reflection objects we will ever need.
Assembly systemNetHttpAssembly = typeof(ServicePoint).Assembly;
s_connectionGroupListField = typeof(ServicePoint).GetField("m_ConnectionGroupList", BindingFlags.Instance | BindingFlags.NonPublic);
s_connectionGroupType = systemNetHttpAssembly?.GetType("System.Net.ConnectionGroup");
s_connectionListField = s_connectionGroupType?.GetField("m_ConnectionList", BindingFlags.Instance | BindingFlags.NonPublic);
s_connectionType = systemNetHttpAssembly?.GetType("System.Net.Connection");
s_writeListField = s_connectionType?.GetField("m_WriteList", BindingFlags.Instance | BindingFlags.NonPublic);
s_httpResponseAccessor = CreateFieldGetter<HttpWebRequest, HttpWebResponse>("_HttpResponse", BindingFlags.NonPublic | BindingFlags.Instance);
s_autoRedirectsAccessor = CreateFieldGetter<HttpWebRequest, int>("_AutoRedirects", BindingFlags.NonPublic | BindingFlags.Instance);
s_coreResponseAccessor = CreateFieldGetter<HttpWebRequest, object>("_CoreResponse", BindingFlags.NonPublic | BindingFlags.Instance);
s_coreResponseDataType = systemNetHttpAssembly?.GetType("System.Net.CoreResponseData");
if (s_coreResponseDataType != null)
{
s_coreStatusCodeAccessor = CreateFieldGetter<HttpStatusCode>(s_coreResponseDataType, "m_StatusCode", BindingFlags.Public | BindingFlags.Instance);
s_coreHeadersAccessor = CreateFieldGetter<WebHeaderCollection>(s_coreResponseDataType, "m_ResponseHeaders", BindingFlags.Public | BindingFlags.Instance);
}
// Double checking to make sure we have all the pieces initialized
if (s_connectionGroupListField == null ||
s_connectionGroupType == null ||
s_connectionListField == null ||
s_connectionType == null ||
s_writeListField == null ||
s_httpResponseAccessor == null ||
s_autoRedirectsAccessor == null ||
s_coreResponseDataType == null ||
s_coreStatusCodeAccessor == null ||
s_coreHeadersAccessor == null)
{
// If anything went wrong here, just return false. There is nothing we can do.
throw new InvalidOperationException("Unable to initialize all required reflection objects");
}
}
private static void PerformInjection()
{
FieldInfo servicePointTableField = typeof(ServicePointManager).GetField("s_ServicePointTable", BindingFlags.Static | BindingFlags.NonPublic);
if (servicePointTableField == null)
{
// If anything went wrong here, just return false. There is nothing we can do.
throw new InvalidOperationException("Unable to access the ServicePointTable field");
}
Hashtable originalTable = servicePointTableField.GetValue(null) as Hashtable;
ServicePointHashtable newTable = new ServicePointHashtable(originalTable ?? new Hashtable());
servicePointTableField.SetValue(null, newTable);
}
private static Func<TClass, TField> CreateFieldGetter<TClass, TField>(string fieldName, BindingFlags flags) where TClass : class
{
FieldInfo field = typeof(TClass).GetField(fieldName, flags);
if (field != null)
{
string methodName = field.ReflectedType.FullName + ".get_" + field.Name;
DynamicMethod getterMethod = new DynamicMethod(methodName, typeof(TField), new [] { typeof(TClass) }, true);
ILGenerator generator = getterMethod.GetILGenerator();
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Ldfld, field);
generator.Emit(OpCodes.Ret);
return (Func<TClass, TField>)getterMethod.CreateDelegate(typeof(Func<TClass, TField>));
}
return null;
}
/// <summary>
/// Creates getter for a field defined in private or internal type
/// repesented with classType variable
/// </summary>
private static Func<object, TField> CreateFieldGetter<TField>(Type classType, string fieldName, BindingFlags flags)
{
FieldInfo field = classType.GetField(fieldName, flags);
if (field != null)
{
string methodName = classType.FullName + ".get_" + field.Name;
DynamicMethod getterMethod = new DynamicMethod(methodName, typeof(TField), new [] { typeof(object) }, true);
ILGenerator generator = getterMethod.GetILGenerator();
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Castclass, classType);
generator.Emit(OpCodes.Ldfld, field);
generator.Emit(OpCodes.Ret);
return (Func<object, TField>)getterMethod.CreateDelegate(typeof(Func<object, TField>));
}
return null;
}
#endregion
internal static HttpHandlerDiagnosticListener s_instance = new HttpHandlerDiagnosticListener();
#region private fields
private const string DiagnosticListenerName = "System.Net.Http.Desktop";
private const string ActivityName = "System.Net.Http.Desktop.HttpRequestOut";
private const string RequestStartName = "System.Net.Http.Desktop.HttpRequestOut.Start";
private const string RequestStopName = "System.Net.Http.Desktop.HttpRequestOut.Stop";
private const string RequestStopExName = "System.Net.Http.Desktop.HttpRequestOut.Ex.Stop";
private const string InitializationFailed = "System.Net.Http.InitializationFailed";
private const string RequestIdHeaderName = "Request-Id";
private const string CorrelationContextHeaderName = "Correlation-Context";
// Fields for controlling initialization of the HttpHandlerDiagnosticListener singleton
private bool initialized = false;
// Fields for reflection
private static FieldInfo s_connectionGroupListField;
private static Type s_connectionGroupType;
private static FieldInfo s_connectionListField;
private static Type s_connectionType;
private static FieldInfo s_writeListField;
private static Func<HttpWebRequest, HttpWebResponse> s_httpResponseAccessor;
private static Func<HttpWebRequest, int> s_autoRedirectsAccessor;
private static Func<HttpWebRequest, object> s_coreResponseAccessor;
private static Func<object, HttpStatusCode> s_coreStatusCodeAccessor;
private static Func<object, WebHeaderCollection> s_coreHeadersAccessor;
private static Type s_coreResponseDataType;
#endregion
}
}
| |
//==============================================================================
// TorqueLab -> Editor Gui General Scripts
// Copyright (c) 2015 All Right Reserved, http://nordiklab.com/
//------------------------------------------------------------------------------
//==============================================================================
function SceneInspectorBase::onAdd( %this ) {
Lab.baseInspectors = strAddWord(Lab.baseInspectors,%this.getId(),true);
}
//==============================================================================
function SceneInspectorBase::inspect( %this, %obj ) {
//echo( "inspecting: " @ %obj );
%name = "";
if ( isObject( %obj ) )
%name = %obj.getName();
else
SceneFieldInfoControl.setText( "" );
//InspectorNameEdit.setValue( %name );
Parent::inspect( %this, %obj );
}
//------------------------------------------------------------------------------
//==============================================================================
// Inspector Compound Callbacks
//==============================================================================
//==============================================================================
function SceneInspectorBase::onFieldAdded( %this, %object, %fieldName ) {
logd("SceneInspectorBase::onFieldAdded( %this, %object, %fieldName )",%this, %object, %fieldName );
}
//------------------------------------------------------------------------------
//==============================================================================
function SceneInspectorBase::onFieldRemoved( %this, %object, %fieldName ) {
logd("SceneInspectorBase::onFieldRemoved( %this, %object, %fieldName )",%this, %object, %fieldName );
}
//------------------------------------------------------------------------------
//==============================================================================
function SceneInspectorBase::onFieldRenamed( %this, %object, %fieldName ,%newName) {
logd("SceneInspectorBase::onFieldRenamed( %this, %object, %fieldName,%newName )",%this, %object, %fieldName,%newName );
}
//------------------------------------------------------------------------------
//==============================================================================
//==============================================================================
function SceneInspectorBase::onFieldSelected( %this, %fieldName, %fieldTypeStr, %fieldDoc ) {
logd("SceneInspectorBase::onFieldSelected( %this, %fieldName, %fieldTypeStr, %fieldDoc )",%this, %fieldName, %fieldTypeStr, %fieldDoc );
SceneFieldInfoControl.setText( "<font:ArialBold:14>" @ %fieldName @ "<font:ArialItalic:14> (" @ %fieldTypeStr @ ") " NL "<font:Arial:14>" @ %fieldDoc );
}
//------------------------------------------------------------------------------
//==============================================================================
function SceneInspectorBase::onFieldRightClick( %this, %object, %fieldName ,%newName) {
logd("SceneInspectorBase::onFieldRightClick( %this, %object, %fieldName,%newName )",%this, %object, %fieldName,%newName );
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//==============================================================================
function SceneInspectorBase::onInspectorFieldModified( %this, %object, %fieldName, %arrayIndex, %oldValue, %newValue ) {
logd("SceneInspectorBase::onInspectorFieldModified( %this, %object, %fieldName, %arrayIndex, %oldValue, %newValue )",%this, %object, %fieldName, %arrayIndex, %oldValue, %newValue );
// The instant group will try to add our
// UndoAction if we don't disable it.
pushInstantGroup();
%nameOrClass = %object.getName();
if ( %nameOrClass $= "" )
%nameOrClass = %object.getClassname();
%action = new InspectorFieldUndoAction() {
actionName = %nameOrClass @ "." @ %fieldName @ " Change";
objectId = %object.getId();
fieldName = %fieldName;
fieldValue = %oldValue;
arrayIndex = %arrayIndex;
inspectorGui = %this;
};
// If it's a datablock, initiate a retransmit. Don't do so
// immediately so as the actual field value will only be set
// by the inspector code after this method has returned.
// Restore the instant group.
popInstantGroup();
%action.addToManager( Editor.getUndoManager() );
if( %object.isMemberOfClass( "SimDataBlock" ) )
{
// %this.onDatablockFieldModified(%object, %fieldName, %arrayIndex, %oldValue, %newValue );
return;
}
EWorldEditor.isDirty = true;
// Update the selection
if(EWorldEditor.getSelectionSize() > 0 && (%fieldName $= "position" || %fieldName $= "rotation" || %fieldName $= "scale")) {
EWorldEditor.invalidateSelectionCentroid();
}
if (%object.getClassName() $= "LevelInfo") {
devLog("onInspectorFieldModified LevelInfo",%fieldName);
if (%fieldName $= "LevelEnvMap")
SceneInspectorBase.schedule(500,"envHack",true);
}
}
//------------------------------------------------------------------------------
//==============================================================================
function SceneInspectorBase::onDatablockFieldModified( %this, %object, %fieldName, %arrayIndex, %oldValue, %newValue ) {
logd("SceneInspectorBase::onDatablockFieldModified( %this, %object, %fieldName, %arrayIndex, %oldValue, %newValue )",%this, %object, %fieldName, %arrayIndex, %oldValue, %newValue );
%object.schedule( 1, "reloadOnLocalClient" );
//Tell SceneEditor Datablock Page
SEP_DatablockPage.datablockFieldModified(%object, %fieldName, %arrayIndex, %oldValue, %newValue );
}
//------------------------------------------------------------------------------
//==============================================================================
// The following three methods are for fields that edit field value live and thus cannot record
// undo information during edits. For these fields, undo information is recorded in advance and
// then either queued or disarded when the field edit is finished.
function SceneInspectorBase::onInspectorPreFieldModification( %this, %fieldName, %arrayIndex ) {
logd("SceneInspectorBase::onInspectorPreFieldModification( %this, %fieldName, %arrayIndex )",%this, %fieldName, %arrayIndex );
pushInstantGroup();
%undoManager = Editor.getUndoManager();
%numObjects = %this.getNumInspectObjects();
if( %numObjects > 1 )
%action = %undoManager.pushCompound( "Multiple Field Edit" );
for( %i = 0; %i < %numObjects; %i ++ ) {
%object = %this.getInspectObject( %i );
%nameOrClass = %object.getName();
if ( %nameOrClass $= "" )
%nameOrClass = %object.getClassname();
%undo = new InspectorFieldUndoAction() {
actionName = %nameOrClass @ "." @ %fieldName @ " Change";
objectId = %object.getId();
fieldName = %fieldName;
fieldValue = %object.getFieldValue( %fieldName, %arrayIndex );
arrayIndex = %arrayIndex;
inspectorGui = %this;
};
if( %numObjects > 1 )
%undo.addToManager( %undoManager );
else {
%action = %undo;
break;
}
}
%this.currentFieldEditAction = %action;
popInstantGroup();
}
//------------------------------------------------------------------------------
//==============================================================================
function SceneInspectorBase::onInspectorPostFieldModification( %this ) {
logd("SceneInspectorBase::onInspectorPostFieldModification( %this)",%this, %fieldName, %arrayIndex );
if( %this.currentFieldEditAction.isMemberOfClass( "CompoundUndoAction" ) ) {
// Finish multiple field edit.
Editor.getUndoManager().popCompound();
} else {
// Queue single field undo.
%this.currentFieldEditAction.addToManager( Editor.getUndoManager() );
}
%this.currentFieldEditAction = "";
EWorldEditor.isDirty = true;
%obj = %this.getInspectObject( 0 );
if (%obj.getClassName() $= "LevelInfo") {
devLog("onInspectorPostFieldModification LevelInfo");
%tmpObj = new EnvVolume("TmpEnvVolume");
delObj(%tmpObj);
}
}
//------------------------------------------------------------------------------
//==============================================================================
//==============================================================================
function SceneInspectorBase::onInspectorDiscardFieldModification( %this ) {
logd("SceneInspectorBase::onInspectorDiscardFieldModification( %this)",%this, %fieldName, %arrayIndex );
%this.currentFieldEditAction.undo();
if( %this.currentFieldEditAction.isMemberOfClass( "CompoundUndoAction" ) ) {
// Multiple field editor. Pop and discard.
Editor.getUndoManager().popCompound( true );
} else {
// Single field edit. Just kill undo action.
%this.currentFieldEditAction.delete();
}
%this.currentFieldEditAction = "";
}
//------------------------------------------------------------------------------
//==============================================================================
// Inspector Compound Callbacks
//==============================================================================
//==============================================================================
function SceneInspectorBase::onBeginCompoundEdit( %this ) {
Editor.getUndoManager().pushCompound( "Multiple Field Edit" );
}
//------------------------------------------------------------------------------
//==============================================================================
function SceneInspectorBase::onEndCompoundEdit( %this ) {
Editor.getUndoManager().popCompound();
}
//------------------------------------------------------------------------------
//==============================================================================
function SceneInspectorBase::onCancelCompoundEdit( %this ) {
Editor.getUndoManager().popCompound( true );
}
//------------------------------------------------------------------------------
| |
// 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.IO;
using SuppressMessageAttribute = System.Diagnostics.CodeAnalysis.SuppressMessageAttribute;
using Encoding = System.Text.Encoding;
namespace System.Xml.Linq
{
/// <summary>
/// Represents an XML document.
/// </summary>
/// <remarks>
/// An <see cref="XDocument"/> can contain:
/// <list>
/// <item>
/// A Document Type Declaration (DTD), see <see cref="XDocumentType"/>
/// </item>
/// <item>One root element.</item>
/// <item>Zero or more <see cref="XComment"/> objects.</item>
/// <item>Zero or more <see cref="XProcessingInstruction"/> objects.</item>
/// </list>
/// </remarks>
public class XDocument : XContainer
{
private XDeclaration _declaration;
///<overloads>
/// Initializes a new instance of the <see cref="XDocument"/> class.
/// Overloaded constructors are provided for creating a new empty
/// <see cref="XDocument"/>, creating an <see cref="XDocument"/> with
/// a parameter list of initial content, and as a copy of another
/// <see cref="XDocument"/> object.
/// </overloads>
/// <summary>
/// Initializes a new instance of the <see cref="XDocument"/> class.
/// </summary>
public XDocument()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="XDocument"/> class with the specified content.
/// </summary>
/// <param name="content">
/// A parameter list of content objects to add to this document.
/// </param>
/// <remarks>
/// Valid content includes:
/// <list>
/// <item>Zero or one <see cref="XDocumentType"/> objects</item>
/// <item>Zero or one elements</item>
/// <item>Zero or more comments</item>
/// <item>Zero or more processing instructions</item>
/// </list>
/// See <see cref="XContainer.Add(object)"/> for details about the content that can be added
/// using this method.
/// </remarks>
public XDocument(params object[] content)
: this()
{
AddContentSkipNotify(content);
}
/// <summary>
/// Initializes a new instance of the <see cref="XDocument"/> class
/// with the specified <see cref="XDeclaration"/> and content.
/// </summary>
/// <param name="declaration">
/// The XML declaration for the document.
/// </param>
/// <param name="content">
/// The contents of the document.
/// </param>
/// <remarks>
/// Valid content includes:
/// <list>
/// <item>Zero or one <see cref="XDocumentType"/> objects</item>
/// <item>Zero or one elements</item>
/// <item>Zero or more comments</item>
/// <item>Zero or more processing instructions</item>
/// <item></item>
/// </list>
/// See <see cref="XContainer.Add(object)"/> for details about the content that can be added
/// using this method.
/// </remarks>
public XDocument(XDeclaration declaration, params object[] content)
: this(content)
{
_declaration = declaration;
}
/// <summary>
/// Initializes a new instance of the <see cref="XDocument"/> class from an
/// existing XDocument object.
/// </summary>
/// <param name="other">
/// The <see cref="XDocument"/> object that will be copied.
/// </param>
public XDocument(XDocument other)
: base(other)
{
if (other._declaration != null)
{
_declaration = new XDeclaration(other._declaration);
}
}
/// <summary>
/// Gets the XML declaration for this document.
/// </summary>
public XDeclaration Declaration
{
get { return _declaration; }
set { _declaration = value; }
}
/// <summary>
/// Gets the Document Type Definition (DTD) for this document.
/// </summary>
public XDocumentType DocumentType
{
get
{
return GetFirstNode<XDocumentType>();
}
}
/// <summary>
/// Gets the node type for this node.
/// </summary>
/// <remarks>
/// This property will always return XmlNodeType.Document.
/// </remarks>
public override XmlNodeType NodeType
{
get
{
return XmlNodeType.Document;
}
}
/// <summary>
/// Gets the root element of the XML Tree for this document.
/// </summary>
public XElement Root
{
get
{
return GetFirstNode<XElement>();
}
}
/// <overloads>
/// The Load method provides multiple strategies for creating a new
/// <see cref="XDocument"/> and initializing it from a data source containing
/// raw XML. Load from a file (passing in a URI to the file), a
/// <see cref="Stream"/>, a <see cref="TextReader"/>, or an
/// <see cref="XmlReader"/>. Note: Use <see cref="XDocument.Parse(string)"/>
/// to create an <see cref="XDocument"/> from a string containing XML.
/// <seealso cref="XDocument.Parse(string)"/>
/// </overloads>
/// <summary>
/// Create a new <see cref="XDocument"/> based on the contents of the file
/// referenced by the URI parameter passed in. Note: Use
/// <see cref="XDocument.Parse(string)"/> to create an <see cref="XDocument"/> from
/// a string containing XML.
/// <seealso cref="XmlReader.Create(string)"/>
/// <seealso cref="XDocument.Parse(string)"/>
/// </summary>
/// <remarks>
/// This method uses the <see cref="XmlReader.Create(string)"/> method to create
/// an <see cref="XmlReader"/> to read the raw XML into the underlying
/// XML tree.
/// </remarks>
/// <param name="uri">
/// A URI string referencing the file to load into a new <see cref="XDocument"/>.
/// </param>
/// <returns>
/// An <see cref="XDocument"/> initialized with the contents of the file referenced
/// in the passed in uri parameter.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#", Justification = "Back-compat with System.Xml.")]
public static XDocument Load(string uri)
{
return Load(uri, LoadOptions.None);
}
/// <summary>
/// Create a new <see cref="XDocument"/> based on the contents of the file
/// referenced by the URI parameter passed in. Optionally, whitespace can be preserved.
/// <see cref="XmlReader.Create(string)"/>
/// </summary>
/// <remarks>
/// This method uses the <see cref="XmlReader.Create(string)"/> method to create
/// an <see cref="XmlReader"/> to read the raw XML into an underlying
/// XML tree. If LoadOptions.PreserveWhitespace is enabled then
/// the <see cref="XmlReaderSettings"/> property <see cref="XmlReaderSettings.IgnoreWhitespace"/>
/// is set to false.
/// </remarks>
/// <param name="uri">
/// A string representing the URI of the file to be loaded into a new <see cref="XDocument"/>.
/// </param>
/// <param name="options">
/// A set of <see cref="LoadOptions"/>.
/// </param>
/// <returns>
/// An <see cref="XDocument"/> initialized with the contents of the file referenced
/// in the passed uri parameter. If LoadOptions.PreserveWhitespace is enabled then
/// all whitespace will be preserved.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#", Justification = "Back-compat with System.Xml.")]
public static XDocument Load(string uri, LoadOptions options)
{
XmlReaderSettings rs = GetXmlReaderSettings(options);
using (XmlReader r = XmlReader.Create(uri, rs))
{
return Load(r, options);
}
}
/// <summary>
/// Create a new <see cref="XDocument"/> and initialize its underlying XML tree using
/// the passed <see cref="Stream"/> parameter.
/// </summary>
/// <param name="stream">
/// A <see cref="Stream"/> containing the raw XML to read into the newly
/// created <see cref="XDocument"/>.
/// </param>
/// <returns>
/// A new <see cref="XDocument"/> containing the contents of the passed in
/// <see cref="Stream"/>.
/// </returns>
public static XDocument Load(Stream stream)
{
return Load(stream, LoadOptions.None);
}
/// <summary>
/// Create a new <see cref="XDocument"/> and initialize its underlying XML tree using
/// the passed <see cref="Stream"/> parameter. Optionally whitespace handling
/// can be preserved.
/// </summary>
/// <remarks>
/// If LoadOptions.PreserveWhitespace is enabled then
/// the underlying <see cref="XmlReaderSettings"/> property <see cref="XmlReaderSettings.IgnoreWhitespace"/>
/// is set to false.
/// </remarks>
/// <param name="stream">
/// A <see cref="Stream"/> containing the raw XML to read into the newly
/// created <see cref="XDocument"/>.
/// </param>
/// <param name="options">
/// A set of <see cref="LoadOptions"/>.
/// </param>
/// <returns>
/// A new <see cref="XDocument"/> containing the contents of the passed in
/// <see cref="Stream"/>.
/// </returns>
public static XDocument Load(Stream stream, LoadOptions options)
{
XmlReaderSettings rs = GetXmlReaderSettings(options);
using (XmlReader r = XmlReader.Create(stream, rs))
{
return Load(r, options);
}
}
/// <summary>
/// Create a new <see cref="XDocument"/> and initialize its underlying XML tree using
/// the passed <see cref="TextReader"/> parameter.
/// </summary>
/// <param name="textReader">
/// A <see cref="TextReader"/> containing the raw XML to read into the newly
/// created <see cref="XDocument"/>.
/// </param>
/// <returns>
/// A new <see cref="XDocument"/> containing the contents of the passed in
/// <see cref="TextReader"/>.
/// </returns>
public static XDocument Load(TextReader textReader)
{
return Load(textReader, LoadOptions.None);
}
/// <summary>
/// Create a new <see cref="XDocument"/> and initialize its underlying XML tree using
/// the passed <see cref="TextReader"/> parameter. Optionally whitespace handling
/// can be preserved.
/// </summary>
/// <remarks>
/// If LoadOptions.PreserveWhitespace is enabled then
/// the <see cref="XmlReaderSettings"/> property <see cref="XmlReaderSettings.IgnoreWhitespace"/>
/// is set to false.
/// </remarks>
/// <param name="textReader">
/// A <see cref="TextReader"/> containing the raw XML to read into the newly
/// created <see cref="XDocument"/>.
/// </param>
/// <param name="options">
/// A set of <see cref="LoadOptions"/>.
/// </param>
/// <returns>
/// A new <see cref="XDocument"/> containing the contents of the passed in
/// <see cref="TextReader"/>.
/// </returns>
public static XDocument Load(TextReader textReader, LoadOptions options)
{
XmlReaderSettings rs = GetXmlReaderSettings(options);
using (XmlReader r = XmlReader.Create(textReader, rs))
{
return Load(r, options);
}
}
/// <summary>
/// Create a new <see cref="XDocument"/> containing the contents of the
/// passed in <see cref="XmlReader"/>.
/// </summary>
/// <param name="reader">
/// An <see cref="XmlReader"/> containing the XML to be read into the new
/// <see cref="XDocument"/>.
/// </param>
/// <returns>
/// A new <see cref="XDocument"/> containing the contents of the passed
/// in <see cref="XmlReader"/>.
/// </returns>
public static XDocument Load(XmlReader reader)
{
return Load(reader, LoadOptions.None);
}
/// <summary>
/// Create a new <see cref="XDocument"/> containing the contents of the
/// passed in <see cref="XmlReader"/>.
/// </summary>
/// <param name="reader">
/// An <see cref="XmlReader"/> containing the XML to be read into the new
/// <see cref="XDocument"/>.
/// </param>
/// <param name="options">
/// A set of <see cref="LoadOptions"/>.
/// </param>
/// <returns>
/// A new <see cref="XDocument"/> containing the contents of the passed
/// in <see cref="XmlReader"/>.
/// </returns>
public static XDocument Load(XmlReader reader, LoadOptions options)
{
if (reader == null) throw new ArgumentNullException(nameof(reader));
if (reader.ReadState == ReadState.Initial) reader.Read();
XDocument d = new XDocument();
if ((options & LoadOptions.SetBaseUri) != 0)
{
string baseUri = reader.BaseURI;
if (!string.IsNullOrEmpty(baseUri))
{
d.SetBaseUri(baseUri);
}
}
if ((options & LoadOptions.SetLineInfo) != 0)
{
IXmlLineInfo li = reader as IXmlLineInfo;
if (li != null && li.HasLineInfo())
{
d.SetLineInfo(li.LineNumber, li.LinePosition);
}
}
if (reader.NodeType == XmlNodeType.XmlDeclaration)
{
d.Declaration = new XDeclaration(reader);
}
d.ReadContentFrom(reader, options);
if (!reader.EOF) throw new InvalidOperationException(SR.InvalidOperation_ExpectedEndOfFile);
if (d.Root == null) throw new InvalidOperationException(SR.InvalidOperation_MissingRoot);
return d;
}
/// <overloads>
/// Create a new <see cref="XDocument"/> from a string containing
/// XML. Optionally whitespace can be preserved.
/// </overloads>
/// <summary>
/// Create a new <see cref="XDocument"/> from a string containing
/// XML.
/// </summary>
/// <param name="text">
/// A string containing XML.
/// </param>
/// <returns>
/// An <see cref="XDocument"/> containing an XML tree initialized from the
/// passed in XML string.
/// </returns>
public static XDocument Parse(string text)
{
return Parse(text, LoadOptions.None);
}
/// <summary>
/// Create a new <see cref="XDocument"/> from a string containing
/// XML. Optionally whitespace can be preserved.
/// </summary>
/// <remarks>
/// This method uses <see cref="XmlReader.Create(TextReader, XmlReaderSettings)"/>,
/// passing it a StringReader constructed from the passed in XML String. If
/// <see cref="LoadOptions.PreserveWhitespace"/> is enabled then
/// <see cref="XmlReaderSettings.IgnoreWhitespace"/> is set to false. See
/// <see cref="XmlReaderSettings.IgnoreWhitespace"/> for more information on
/// whitespace handling.
/// </remarks>
/// <param name="text">
/// A string containing XML.
/// </param>
/// <param name="options">
/// A set of <see cref="LoadOptions"/>.
/// </param>
/// <returns>
/// An <see cref="XDocument"/> containing an XML tree initialized from the
/// passed in XML string.
/// </returns>
public static XDocument Parse(string text, LoadOptions options)
{
using (StringReader sr = new StringReader(text))
{
XmlReaderSettings rs = GetXmlReaderSettings(options);
using (XmlReader r = XmlReader.Create(sr, rs))
{
return Load(r, options);
}
}
}
/// <summary>
/// Output this <see cref="XDocument"/> to the passed in <see cref="Stream"/>.
/// </summary>
/// <remarks>
/// The format will be indented by default. If you want
/// no indenting then use the SaveOptions version of Save (see
/// <see cref="XDocument.Save(Stream, SaveOptions)"/>) enabling
/// SaveOptions.DisableFormatting
/// There is also an option SaveOptions.OmitDuplicateNamespaces for removing duplicate namespace declarations.
/// Or instead use the SaveOptions as an annotation on this node or its ancestors, then this method will use those options.
/// </remarks>
/// <param name="stream">
/// The <see cref="Stream"/> to output this <see cref="XDocument"/> to.
/// </param>
public void Save(Stream stream)
{
Save(stream, GetSaveOptionsFromAnnotations());
}
/// <summary>
/// Output this <see cref="XDocument"/> to a <see cref="Stream"/>.
/// </summary>
/// <param name="stream">
/// The <see cref="Stream"/> to output the XML to.
/// </param>
/// <param name="options">
/// If SaveOptions.DisableFormatting is enabled the output is not indented.
/// If SaveOptions.OmitDuplicateNamespaces is enabled duplicate namespace declarations will be removed.
/// </param>
public void Save(Stream stream, SaveOptions options)
{
XmlWriterSettings ws = GetXmlWriterSettings(options);
if (_declaration != null && !string.IsNullOrEmpty(_declaration.Encoding))
{
try
{
ws.Encoding = Encoding.GetEncoding(_declaration.Encoding);
}
catch (ArgumentException)
{
}
}
using (XmlWriter w = XmlWriter.Create(stream, ws))
{
Save(w);
}
}
/// <summary>
/// Output this <see cref="XDocument"/> to the passed in <see cref="TextWriter"/>.
/// </summary>
/// <remarks>
/// The format will be indented by default. If you want
/// no indenting then use the SaveOptions version of Save (see
/// <see cref="XDocument.Save(TextWriter, SaveOptions)"/>) enabling
/// SaveOptions.DisableFormatting
/// There is also an option SaveOptions.OmitDuplicateNamespaces for removing duplicate namespace declarations.
/// Or instead use the SaveOptions as an annotation on this node or its ancestors, then this method will use those options.
/// </remarks>
/// <param name="textWriter">
/// The <see cref="TextWriter"/> to output this <see cref="XDocument"/> to.
/// </param>
public void Save(TextWriter textWriter)
{
Save(textWriter, GetSaveOptionsFromAnnotations());
}
/// <summary>
/// Output this <see cref="XDocument"/> to a <see cref="TextWriter"/>.
/// </summary>
/// <param name="textWriter">
/// The <see cref="TextWriter"/> to output the XML to.
/// </param>
/// <param name="options">
/// If SaveOptions.DisableFormatting is enabled the output is not indented.
/// If SaveOptions.OmitDuplicateNamespaces is enabled duplicate namespace declarations will be removed.
/// </param>
public void Save(TextWriter textWriter, SaveOptions options)
{
XmlWriterSettings ws = GetXmlWriterSettings(options);
using (XmlWriter w = XmlWriter.Create(textWriter, ws))
{
Save(w);
}
}
/// <summary>
/// Output this <see cref="XDocument"/> to an <see cref="XmlWriter"/>.
/// </summary>
/// <param name="writer">
/// The <see cref="XmlWriter"/> to output the XML to.
/// </param>
public void Save(XmlWriter writer)
{
WriteTo(writer);
}
///<overloads>
/// Outputs this <see cref="XDocument"/>'s underlying XML tree. The output can
/// be saved to a file, a <see cref="Stream"/>, a <see cref="TextWriter"/>,
/// or an <see cref="XmlWriter"/>. Optionally whitespace can be preserved.
/// </overloads>
/// <summary>
/// Output this <see cref="XDocument"/> to a file.
/// </summary>
/// <remarks>
/// The format will be indented by default. If you want
/// no indenting then use the SaveOptions version of Save (see
/// <see cref="XDocument.Save(string, SaveOptions)"/>) enabling
/// SaveOptions.DisableFormatting.
/// There is also an option SaveOptions.OmitDuplicateNamespaces for removing duplicate namespace declarations.
/// Or instead use the SaveOptions as an annotation on this node or its ancestors, then this method will use those options.
/// </remarks>
/// <param name="fileName">
/// The name of the file to output the XML to.
/// </param>
public void Save(string fileName)
{
Save(fileName, GetSaveOptionsFromAnnotations());
}
/// <summary>
/// Output this <see cref="XDocument"/> to a file.
/// </summary>
/// <param name="fileName">
/// The name of the file to output the XML to.
/// </param>
/// <param name="options">
/// If SaveOptions.DisableFormatting is enabled the output is not indented.
/// If SaveOptions.OmitDuplicateNamespaces is enabled duplicate namespace declarations will be removed.
/// </param>
public void Save(string fileName, SaveOptions options)
{
XmlWriterSettings ws = GetXmlWriterSettings(options);
if (_declaration != null && !string.IsNullOrEmpty(_declaration.Encoding))
{
try
{
ws.Encoding = Encoding.GetEncoding(_declaration.Encoding);
}
catch (ArgumentException)
{
}
}
using (XmlWriter w = XmlWriter.Create(fileName, ws))
{
Save(w);
}
}
/// <summary>
/// Output this <see cref="XDocument"/>'s underlying XML tree to the
/// passed in <see cref="XmlWriter"/>.
/// <seealso cref="XDocument.Save(XmlWriter)"/>
/// </summary>
/// <param name="writer">
/// The <see cref="XmlWriter"/> to output the content of this
/// <see cref="XDocument"/>.
/// </param>
public override void WriteTo(XmlWriter writer)
{
if (writer == null) throw new ArgumentNullException(nameof(writer));
if (_declaration != null && _declaration.Standalone == "yes")
{
writer.WriteStartDocument(true);
}
else if (_declaration != null && _declaration.Standalone == "no")
{
writer.WriteStartDocument(false);
}
else
{
writer.WriteStartDocument();
}
WriteContentTo(writer);
writer.WriteEndDocument();
}
internal override void AddAttribute(XAttribute a)
{
throw new ArgumentException(SR.Argument_AddAttribute);
}
internal override void AddAttributeSkipNotify(XAttribute a)
{
throw new ArgumentException(SR.Argument_AddAttribute);
}
internal override XNode CloneNode()
{
return new XDocument(this);
}
internal override bool DeepEquals(XNode node)
{
XDocument other = node as XDocument;
return other != null && ContentsEqual(other);
}
internal override int GetDeepHashCode()
{
return ContentsHashCode();
}
private T GetFirstNode<T>() where T : XNode
{
XNode n = content as XNode;
if (n != null)
{
do
{
n = n.next;
T e = n as T;
if (e != null) return e;
} while (n != content);
}
return null;
}
internal static bool IsWhitespace(string s)
{
foreach (char ch in s)
{
if (ch != ' ' && ch != '\t' && ch != '\r' && ch != '\n') return false;
}
return true;
}
internal override void ValidateNode(XNode node, XNode previous)
{
switch (node.NodeType)
{
case XmlNodeType.Text:
ValidateString(((XText)node).Value);
break;
case XmlNodeType.Element:
ValidateDocument(previous, XmlNodeType.DocumentType, XmlNodeType.None);
break;
case XmlNodeType.DocumentType:
ValidateDocument(previous, XmlNodeType.None, XmlNodeType.Element);
break;
case XmlNodeType.CDATA:
throw new ArgumentException(SR.Format(SR.Argument_AddNode, XmlNodeType.CDATA));
case XmlNodeType.Document:
throw new ArgumentException(SR.Format(SR.Argument_AddNode, XmlNodeType.Document));
}
}
private void ValidateDocument(XNode previous, XmlNodeType allowBefore, XmlNodeType allowAfter)
{
XNode n = content as XNode;
if (n != null)
{
if (previous == null) allowBefore = allowAfter;
do
{
n = n.next;
XmlNodeType nt = n.NodeType;
if (nt == XmlNodeType.Element || nt == XmlNodeType.DocumentType)
{
if (nt != allowBefore) throw new InvalidOperationException(SR.InvalidOperation_DocumentStructure);
allowBefore = XmlNodeType.None;
}
if (n == previous) allowBefore = allowAfter;
} while (n != content);
}
}
internal override void ValidateString(string s)
{
if (!IsWhitespace(s)) throw new ArgumentException(SR.Argument_AddNonWhitespace);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using NSubstitute;
using Octokit.Tests.Helpers;
using Xunit;
namespace Octokit.Tests.Clients
{
/// <summary>
/// Client tests mostly just need to make sure they call the IApiConnection with the correct
/// relative Uri. No need to fake up the response. All *those* tests are in ApiConnectionTests.cs.
/// </summary>
public class RepositoriesClientTests
{
public class TheConstructor
{
[Fact]
public void EnsuresNonNullArguments()
{
Assert.Throws<ArgumentNullException>(() => new RepositoriesClient(null));
}
}
public class TheCreateMethodForUser
{
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoriesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Create(null));
}
[Fact]
public void UsesTheUserReposUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
client.Create(new NewRepository("aName"));
connection.Received().Post<Repository>(Arg.Is<Uri>(u => u.ToString() == "user/repos"), Arg.Any<NewRepository>());
}
[Fact]
public void TheNewRepositoryDescription()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
var newRepository = new NewRepository("aName");
client.Create(newRepository);
connection.Received().Post<Repository>(Args.Uri, newRepository);
}
[Fact]
public async Task ThrowsRepositoryExistsExceptionWhenRepositoryExistsForCurrentUser()
{
var newRepository = new NewRepository("aName");
var response = Substitute.For<IResponse>();
response.StatusCode.Returns((HttpStatusCode)422);
response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":"
+ @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository"","
+ @"""code"":""custom"",""field"":""name"",""message"":""name already exists on this account""}]}");
var credentials = new Credentials("haacked", "pwd");
var connection = Substitute.For<IApiConnection>();
connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl);
connection.Connection.Credentials.Returns(credentials);
connection.Post<Repository>(Args.Uri, newRepository)
.Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); });
var client = new RepositoriesClient(connection);
var exception = await Assert.ThrowsAsync<RepositoryExistsException>(
() => client.Create(newRepository));
Assert.False(exception.OwnerIsOrganization);
Assert.Null(exception.Organization);
Assert.Equal("aName", exception.RepositoryName);
Assert.Null(exception.ExistingRepositoryWebUrl);
}
[Fact]
public async Task ThrowsExceptionWhenPrivateRepositoryQuotaExceeded()
{
var newRepository = new NewRepository("aName") { Private = true };
var response = Substitute.For<IResponse>();
response.StatusCode.Returns((HttpStatusCode)422);
response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":"
+ @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository"","
+ @"""code"":""custom"",""field"":""name"",""message"":"
+ @"""name can't be private. You are over your quota.""}]}");
var credentials = new Credentials("haacked", "pwd");
var connection = Substitute.For<IApiConnection>();
connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl);
connection.Connection.Credentials.Returns(credentials);
connection.Post<Repository>(Args.Uri, newRepository)
.Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); });
var client = new RepositoriesClient(connection);
var exception = await Assert.ThrowsAsync<PrivateRepositoryQuotaExceededException>(
() => client.Create(newRepository));
Assert.NotNull(exception);
}
}
public class TheCreateMethodForOrganization
{
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoriesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Create(null, new NewRepository("aName")));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Create("aLogin", null));
}
[Fact]
public async Task UsesTheOrganizatinosReposUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
await client.Create("theLogin", new NewRepository("aName"));
connection.Received().Post<Repository>(
Arg.Is<Uri>(u => u.ToString() == "orgs/theLogin/repos"),
Args.NewRepository);
}
[Fact]
public async Task TheNewRepositoryDescription()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
var newRepository = new NewRepository("aName");
await client.Create("aLogin", newRepository);
connection.Received().Post<Repository>(Args.Uri, newRepository);
}
[Fact]
public async Task ThrowsRepositoryExistsExceptionWhenRepositoryExistsForSpecifiedOrg()
{
var newRepository = new NewRepository("aName");
var response = Substitute.For<IResponse>();
response.StatusCode.Returns((HttpStatusCode)422);
response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":"
+ @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository"","
+ @"""code"":""custom"",""field"":""name"",""message"":""name already exists on this account""}]}");
var connection = Substitute.For<IApiConnection>();
connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl);
connection.Post<Repository>(Args.Uri, newRepository)
.Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); });
var client = new RepositoriesClient(connection);
var exception = await Assert.ThrowsAsync<RepositoryExistsException>(
() => client.Create("illuminati", newRepository));
Assert.True(exception.OwnerIsOrganization);
Assert.Equal("illuminati", exception.Organization);
Assert.Equal("aName", exception.RepositoryName);
Assert.Equal(new Uri("https://github.com/illuminati/aName"), exception.ExistingRepositoryWebUrl);
Assert.Equal("There is already a repository named 'aName' in the organization 'illuminati'.",
exception.Message);
}
[Fact]
public async Task ThrowsValidationException()
{
var newRepository = new NewRepository("aName");
var response = Substitute.For<IResponse>();
response.StatusCode.Returns((HttpStatusCode)422);
response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":"
+ @"""http://developer.github.com/v3/repos/#create"",""errors"":[]}");
var connection = Substitute.For<IApiConnection>();
connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl);
connection.Post<Repository>(Args.Uri, newRepository)
.Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); });
var client = new RepositoriesClient(connection);
var exception = await Assert.ThrowsAsync<ApiValidationException>(
() => client.Create("illuminati", newRepository));
Assert.Null(exception as RepositoryExistsException);
}
[Fact]
public async Task ThrowsRepositoryExistsExceptionForEnterpriseInstance()
{
var newRepository = new NewRepository("aName");
var response = Substitute.For<IResponse>();
response.StatusCode.Returns((HttpStatusCode)422);
response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":"
+ @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository"","
+ @"""code"":""custom"",""field"":""name"",""message"":""name already exists on this account""}]}");
var connection = Substitute.For<IApiConnection>();
connection.Connection.BaseAddress.Returns(new Uri("https://example.com"));
connection.Post<Repository>(Args.Uri, newRepository)
.Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); });
var client = new RepositoriesClient(connection);
var exception = await Assert.ThrowsAsync<RepositoryExistsException>(
() => client.Create("illuminati", newRepository));
Assert.Equal("aName", exception.RepositoryName);
Assert.Equal(new Uri("https://example.com/illuminati/aName"), exception.ExistingRepositoryWebUrl);
}
}
public class TheDeleteMethod
{
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoriesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Delete(null, "aRepoName"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Delete("anOwner", null));
}
[Fact]
public async Task RequestsCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
await client.Delete("theOwner", "theRepoName");
connection.Received().Delete(Arg.Is<Uri>(u => u.ToString() == "repos/theOwner/theRepoName"));
}
}
public class TheGetMethod
{
[Fact]
public void RequestsCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
client.Get("fake", "repo");
connection.Received().Get<Repository>(Arg.Is<Uri>(u => u.ToString() == "repos/fake/repo"), null);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoriesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get(null, "name"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get("owner", null));
}
}
public class TheGetAllPublicMethod
{
[Fact]
public void RequestsTheCorrectUrlAndReturnsRepositories()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
client.GetAllPublic();
connection.Received()
.GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "/repositories"));
}
}
public class TheGetAllPublicSinceMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
client.GetAllPublic(new PublicRepositoryRequest(364));
connection.Received()
.GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "/repositories?since=364"));
}
[Fact]
public void SendsTheCorrectParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
client.GetAllPublic(new PublicRepositoryRequest(364));
connection.Received()
.GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "/repositories?since=364"));
}
}
public class TheGetAllForCurrentMethod
{
[Fact]
public void RequestsTheCorrectUrlAndReturnsRepositories()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
client.GetAllForCurrent();
connection.Received()
.GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "user/repos"));
}
[Fact]
public void CanFilterByType()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
var request = new RepositoryRequest
{
Type = RepositoryType.All
};
client.GetAllForCurrent(request);
connection.Received()
.GetAll<Repository>(
Arg.Is<Uri>(u => u.ToString() == "user/repos"),
Arg.Is<Dictionary<string,string>>(d => d["type"] == "all"));
}
[Fact]
public void CanFilterBySort()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
var request = new RepositoryRequest
{
Type = RepositoryType.Private,
Sort = RepositorySort.FullName
};
client.GetAllForCurrent(request);
connection.Received()
.GetAll<Repository>(
Arg.Is<Uri>(u => u.ToString() == "user/repos"),
Arg.Is<Dictionary<string, string>>(d =>
d["type"] == "private" && d["sort"] == "full_name"));
}
[Fact]
public void CanFilterBySortDirection()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
var request = new RepositoryRequest
{
Type = RepositoryType.Member,
Sort = RepositorySort.Updated,
Direction = SortDirection.Ascending
};
client.GetAllForCurrent(request);
connection.Received()
.GetAll<Repository>(
Arg.Is<Uri>(u => u.ToString() == "user/repos"),
Arg.Is<Dictionary<string, string>>(d =>
d["type"] == "member" && d["sort"] == "updated" && d["direction"] == "asc"));
}
}
public class TheGetAllForUserMethod
{
[Fact]
public void RequestsTheCorrectUrlAndReturnsRepositories()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
client.GetAllForUser("username");
connection.Received()
.GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "users/username/repos"));
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var reposEndpoint = new RepositoriesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => reposEndpoint.GetAllForUser(null));
}
}
public class TheGetAllForOrgMethod
{
[Fact]
public void RequestsTheCorrectUrlAndReturnsRepositories()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
client.GetAllForOrg("orgname");
connection.Received()
.GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "orgs/orgname/repos"));
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var reposEndpoint = new RepositoriesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => reposEndpoint.GetAllForOrg(null));
}
}
public class TheGetAllBranchesMethod
{
[Fact]
public void ReturnsBranches()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
client.GetAllBranches("owner", "name");
connection.Received()
.GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/branches"));
}
[Fact]
public async Task EnsuresArguments()
{
var client = new RepositoriesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllBranches(null, "repo"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllBranches("owner", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllBranches("", "repo"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllBranches("owner", ""));
}
}
public class TheGetAllContributorsMethod
{
[Fact]
public void GetsCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
client.GetAllContributors("owner", "name");
connection.Received()
.GetAll<RepositoryContributor>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/contributors"), Arg.Any<IDictionary<string, string>>());
}
[Fact]
public async Task EnsuresArguments()
{
var client = new RepositoriesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllContributors(null, "repo"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllContributors("owner", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllContributors("", "repo"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllContributors("owner", ""));
}
}
public class TheGetAllLanguagesMethod
{
[Fact]
public void GetsCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
client.GetAllLanguages("owner", "name");
connection.Received()
.Get<Dictionary<string, long>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/languages"), null);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoriesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllLanguages(null, "repo"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllLanguages("owner", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllLanguages("", "repo"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllLanguages("owner", ""));
}
}
public class TheGetAllTeamsMethod
{
[Fact]
public void GetsCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
client.GetAllTeams("owner", "name");
connection.Received()
.GetAll<Team>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/teams"));
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoriesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTeams(null, "repo"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTeams("owner", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllTeams("", "repo"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllTeams("owner", ""));
}
}
public class TheGetAllTagsMethod
{
[Fact]
public void GetsCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
client.GetAllTags("owner", "name");
connection.Received()
.GetAll<RepositoryTag>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/tags"));
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoriesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTags(null, "repo"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTags("owner", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllTags("", "repo"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllTags("owner", ""));
}
}
public class TheGetBranchMethod
{
[Fact]
public void GetsCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
client.GetBranch("owner", "repo", "branch");
connection.Received()
.Get<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch"), null);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoriesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranch(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranch("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranch("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranch("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranch("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranch("owner", "repo", ""));
}
}
public class TheEditMethod
{
[Fact]
public void PatchesCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
var update = new RepositoryUpdate();
client.Edit("owner", "repo", update);
connection.Received()
.Patch<Repository>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo"), Arg.Any<RepositoryUpdate>());
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoriesClient(Substitute.For<IApiConnection>());
var update = new RepositoryUpdate();
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Edit(null, "repo", update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Edit("owner", null, update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Edit("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.Edit("", "repo", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.Edit("owner", "", update));
}
}
public class TheCompareMethod
{
[Fact]
public async Task EnsureNonNullArguments()
{
var client = new RepositoryCommitsClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Compare(null, "repo", "base", "head"));
await Assert.ThrowsAsync<ArgumentException>(() => client.Compare("", "repo", "base", "head"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Compare("owner", null, "base", "head"));
await Assert.ThrowsAsync<ArgumentException>(() => client.Compare("owner", "", "base", "head"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Compare("owner", "repo", null, "head"));
await Assert.ThrowsAsync<ArgumentException>(() => client.Compare("owner", "repo", "", "head"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Compare("owner", "repo", "base", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.Compare("owner", "repo", "base", ""));
}
[Fact]
public void GetsCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryCommitsClient(connection);
client.Compare("owner", "repo", "base", "head");
connection.Received()
.Get<CompareResult>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/compare/base...head"), null);
}
[Fact]
public void EncodesUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryCommitsClient(connection);
client.Compare("owner", "repo", "base", "shiftkey/my-cool-branch");
connection.Received()
.Get<CompareResult>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/compare/base...shiftkey%2Fmy-cool-branch"), null);
}
}
public class TheGetCommitMethod
{
[Fact]
public async Task EnsureNonNullArguments()
{
var client = new RepositoryCommitsClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get(null, "repo", "reference"));
await Assert.ThrowsAsync<ArgumentException>(() => client.Get("", "repo", "reference"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get("owner", null, "reference"));
await Assert.ThrowsAsync<ArgumentException>(() => client.Get("owner", "", "reference"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.Get("owner", "repo", ""));
}
[Fact]
public void GetsCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryCommitsClient(connection);
client.Get("owner", "name", "reference");
connection.Received()
.Get<GitHubCommit>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/commits/reference"), null);
}
}
public class TheGetAllCommitsMethod
{
[Fact]
public async Task EnsureNonNullArguments()
{
var client = new RepositoryCommitsClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll(null, "repo"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAll("", "repo"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll("owner", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAll("owner", ""));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll("owner", "repo", null));
}
[Fact]
public void GetsCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryCommitsClient(connection);
client.GetAll("owner", "name");
connection.Received()
.GetAll<GitHubCommit>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/commits"),
Arg.Any<Dictionary<string, string>>());
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using PlayFab;
using PlayFab.AuthenticationModels;
using PlayFab.AdminModels;
using PlayFab.Json;
namespace UB_Uploader
{
public static class Program
{
// shared variables
private static string defaultCatalog = null; // Determined by TitleSettings.json
private static bool hitErrors;
// data file locations
private const string currencyPath = "./PlayFabData/Currency.json";
private const string titleSettingsPath = "./PlayFabData/TitleSettings.json";
private const string titleDataPath = "./PlayFabData/TitleData.json";
private const string catalogPath = "./PlayFabData/Catalog.json";
private const string catalogPathEvents = "./PlayFabData/CatalogEvents.json";
private const string dropTablesPath = "./PlayFabData/DropTables.json";
private const string cloudScriptPath = "./PlayFabData/CloudScript.js";
private const string titleNewsPath = "./PlayFabData/TitleNews.json";
private const string statsDefPath = "./PlayFabData/StatisticsDefinitions.json";
private const string storesPath = "./PlayFabData/Stores.json";
private const string storesPathEvents = "./PlayFabData/StoresEvents.json";
private const string cdnAssetsPath = "./PlayFabData/CdnData.json";
private const string permissionPath = "./PlayFabData/Permissions.json";
// authentication tokens
private static string authToken;
// log file details
private static FileInfo logFile;
private static StreamWriter logStream;
// CDN
public enum CdnPlatform { Desktop, iOS, Android }
public static readonly Dictionary<CdnPlatform, string> cdnPlatformSubfolder = new Dictionary<CdnPlatform, string> {
{ CdnPlatform.Desktop, "" },
{ CdnPlatform.iOS, "iOS/" },
{ CdnPlatform.Android, "Android/" },
};
public static string cdnPath = "./PlayFabData/AssetBundles/";
/// <summary>
/// This app parses the textfiles(defined above) and uploads the contents into a PlayFab title (defined in titleSettingsPath);
/// </summary>
/// <param name="args"></param>
public static void Main(string[] args)
{
try
{
// setup the log file
logFile = new FileInfo("PreviousUploadLog.txt");
logStream = logFile.CreateText();
// get the destination title settings
if (!GetTitleSettings())
throw new Exception("\tFailed to load Title Settings");
if (!GetAuthToken())
throw new Exception("\tFailed to retrieve Auth Token");
// start uploading
if (!UploadTitleData())
throw new Exception("\tFailed to upload TitleData.");
if (!UploadEconomyData())
throw new Exception("\tFailed to upload Economy Data.");
if (!UploadEventData())
throw new Exception("\tFailed to upload Event Data.");
if (!UploadCloudScript())
throw new Exception("\tFailed to upload CloudScript.");
if (!UploadTitleNews())
throw new Exception("\tFailed to upload TitleNews.");
if (!UploadStatisticDefinitions())
throw new Exception("\tFailed to upload Statistics Definitions.");
if (!UploadCdnAssets())
throw new Exception("\tFailed to upload CDN Assets.");
if (!UploadPolicy(permissionPath))
throw new Exception("\tFailed to upload permissions policy.");
}
catch (Exception ex)
{
hitErrors = true;
LogToFile("\tAn unexpected error occurred: " + ex.Message, ConsoleColor.Red);
}
finally
{
var status = hitErrors ? "ended with errors. See PreviousUploadLog.txt for details" : "ended successfully!";
var color = hitErrors ? ConsoleColor.Red : ConsoleColor.White;
LogToFile("UB_Uploader.exe " + status, color);
logStream.Close();
Console.WriteLine("Press return to exit.");
Console.ReadLine();
}
}
private static bool GetTitleSettings()
{
var parsedFile = ParseFile(titleSettingsPath);
var titleSettings = JsonWrapper.DeserializeObject<Dictionary<string, string>>(parsedFile);
if (titleSettings != null &&
titleSettings.TryGetValue("TitleId", out PlayFabSettings.staticSettings.TitleId) && !string.IsNullOrEmpty(PlayFabSettings.staticSettings.TitleId) &&
titleSettings.TryGetValue("DeveloperSecretKey", out PlayFabSettings.staticSettings.DeveloperSecretKey) && !string.IsNullOrEmpty(PlayFabSettings.staticSettings.DeveloperSecretKey) &&
titleSettings.TryGetValue("CatalogName", out defaultCatalog))
{
LogToFile("Setting Destination TitleId to: " + PlayFabSettings.staticSettings.TitleId);
LogToFile("Setting DeveloperSecretKey to: " + PlayFabSettings.staticSettings.DeveloperSecretKey);
LogToFile("Setting defaultCatalog name to: " + defaultCatalog);
return true;
}
LogToFile("An error occurred when trying to parse TitleSettings.json", ConsoleColor.Red);
return false;
}
#region Uploading Functions -- these are straightforward calls that push the data to the backend
private static bool UploadEconomyData()
{
////MUST upload these in this order so that the economy data is properly imported: VC -> Catalogs -> DropTables -> Catalogs part 2 -> Stores
if (!UploadVc())
return false;
if (string.IsNullOrEmpty(catalogPath))
return false;
LogToFile("Uploading CatalogItems...");
// now go through the catalog; split into two parts.
var reUploadList = new List<CatalogItem>();
var parsedFile = ParseFile(catalogPath);
var catalogWrapper = JsonWrapper.DeserializeObject<CatalogWrapper>(parsedFile);
if (catalogWrapper == null)
{
LogToFile("\tAn error occurred deserializing the Catalog.json file.", ConsoleColor.Red);
return false;
}
for (var z = 0; z < catalogWrapper.Catalog.Count; z++)
{
if (catalogWrapper.Catalog[z].Bundle != null || catalogWrapper.Catalog[z].Container != null)
{
var original = catalogWrapper.Catalog[z];
var strippedClone = CloneCatalogItemAndStripTables(original);
reUploadList.Add(original);
catalogWrapper.Catalog.Remove(original);
catalogWrapper.Catalog.Add(strippedClone);
}
}
if (!UpdateCatalog(catalogWrapper.Catalog, defaultCatalog, true))
return false;
if (!UploadDropTables())
return false;
if (!UploadStores(storesPath, defaultCatalog))
return false;
// workaround for the DropTable conflict
if (reUploadList.Count > 0)
{
LogToFile("Re-uploading [" + reUploadList.Count + "] CatalogItems due to DropTable conflicts...");
if (!UpdateCatalog(reUploadList, defaultCatalog, true))
return false;
}
return true;
}
private static bool UploadEventData()
{
if (string.IsNullOrEmpty(catalogPathEvents))
return false;
LogToFile("Uploading Event Items...");
var parsedFile = ParseFile(catalogPathEvents);
var catalogWrapper = JsonWrapper.DeserializeObject<CatalogWrapper>(parsedFile);
if (catalogWrapper == null)
{
LogToFile("\tAn error occurred deserializing the CatalogEvents.json file.", ConsoleColor.Red);
return false;
}
if (!UpdateCatalog(catalogWrapper.Catalog, "Events", false))
return false;
LogToFile("\tUploaded Event Catalog!", ConsoleColor.Green);
if (!UploadStores(storesPathEvents, "Events"))
return false;
return true;
}
private static bool UploadStatisticDefinitions()
{
if (string.IsNullOrEmpty(statsDefPath))
return false;
LogToFile("Updating Player Statistics Definitions ...");
var parsedFile = ParseFile(statsDefPath);
var statisticDefinitions = JsonWrapper.DeserializeObject<List<PlayerStatisticDefinition>>(parsedFile);
foreach (var item in statisticDefinitions)
{
LogToFile("\tUploading: " + item.StatisticName);
var request = new CreatePlayerStatisticDefinitionRequest()
{
StatisticName = item.StatisticName,
VersionChangeInterval = item.VersionChangeInterval,
AggregationMethod = item.AggregationMethod
};
var createStatTask = PlayFabAdminAPI.CreatePlayerStatisticDefinitionAsync(request);
createStatTask.Wait();
if (createStatTask.Result.Error != null)
{
if (createStatTask.Result.Error.Error == PlayFabErrorCode.StatisticNameConflict)
{
LogToFile("\tStatistic Already Exists, Updating values: " + item.StatisticName, ConsoleColor.DarkYellow);
var updateRequest = new UpdatePlayerStatisticDefinitionRequest()
{
StatisticName = item.StatisticName,
VersionChangeInterval = item.VersionChangeInterval,
AggregationMethod = item.AggregationMethod
};
var updateStatTask = PlayFabAdminAPI.UpdatePlayerStatisticDefinitionAsync(updateRequest);
updateStatTask.Wait();
if (updateStatTask.Result.Error != null)
OutputPlayFabError("\t\tStatistics Definition Error: " + item.StatisticName, updateStatTask.Result.Error);
else
LogToFile("\t\tStatistics Definition:" + item.StatisticName + " Updated", ConsoleColor.Green);
}
else
{
OutputPlayFabError("\t\tStatistics Definition Error: " + item.StatisticName, createStatTask.Result.Error);
}
}
else
{
LogToFile("\t\tStatistics Definition: " + item.StatisticName + " Created", ConsoleColor.Green);
}
}
return true;
}
private static bool UploadTitleNews()
{
if (string.IsNullOrEmpty(titleNewsPath))
return false;
LogToFile("Uploading TitleNews...");
var parsedFile = ParseFile(titleNewsPath);
var titleNewsItems = JsonWrapper.DeserializeObject<List<PlayFab.ServerModels.TitleNewsItem>>(parsedFile);
foreach (var item in titleNewsItems)
{
LogToFile("\tUploading: " + item.Title);
var request = new AddNewsRequest()
{
Title = item.Title,
Body = item.Body
};
var addNewsTask = PlayFabAdminAPI.AddNewsAsync(request);
addNewsTask.Wait();
if (addNewsTask.Result.Error != null)
OutputPlayFabError("\t\tTitleNews Upload: " + item.Title, addNewsTask.Result.Error);
else
LogToFile("\t\t" + item.Title + " Uploaded.", ConsoleColor.Green);
}
return true;
}
// retrieves and stores an auth token
// returns false if it fails
private static bool GetAuthToken()
{
var entityTokenRequest = new GetEntityTokenRequest();
var authTask = PlayFabAuthenticationAPI.GetEntityTokenAsync(entityTokenRequest);
authTask.Wait();
if (authTask.Result.Error != null)
{
OutputPlayFabError("\t\tError retrieving auth token: ", authTask.Result.Error);
return false;
}
else
{
authToken = authTask.Result.Result.EntityToken;
LogToFile("\t\tAuth token retrieved.", ConsoleColor.Green);
}
return true;
}
private static bool UploadCloudScript()
{
if (string.IsNullOrEmpty(cloudScriptPath))
return false;
LogToFile("Uploading CloudScript...");
var parsedFile = ParseFile(cloudScriptPath);
if (parsedFile == null)
{
LogToFile("\tAn error occurred deserializing the CloudScript.js file.", ConsoleColor.Red);
return false;
}
var files = new List<CloudScriptFile> {
new CloudScriptFile
{
Filename = "CloudScript.js",
FileContents = parsedFile
}
};
var request = new UpdateCloudScriptRequest()
{
Publish = true,
Files = files
};
var updateCloudScriptTask = PlayFabAdminAPI.UpdateCloudScriptAsync(request);
updateCloudScriptTask.Wait();
if (updateCloudScriptTask.Result.Error != null)
{
OutputPlayFabError("\tCloudScript Upload Error: ", updateCloudScriptTask.Result.Error);
return false;
}
LogToFile("\tUploaded CloudScript!", ConsoleColor.Green);
return true;
}
private static bool UploadTitleData()
{
if (string.IsNullOrEmpty(titleDataPath))
return false;
LogToFile("Uploading Title Data Keys & Values...");
var parsedFile = ParseFile(titleDataPath);
var titleDataDict = JsonWrapper.DeserializeObject<Dictionary<string, string>>(parsedFile);
foreach (var kvp in titleDataDict)
{
LogToFile("\tUploading: " + kvp.Key);
var request = new SetTitleDataRequest()
{
Key = kvp.Key,
Value = kvp.Value
};
var setTitleDataTask = PlayFabAdminAPI.SetTitleDataAsync(request);
setTitleDataTask.Wait();
if (setTitleDataTask.Result.Error != null)
OutputPlayFabError("\t\tTitleData Upload: " + kvp.Key, setTitleDataTask.Result.Error);
else
LogToFile("\t\t" + kvp.Key + " Uploaded.", ConsoleColor.Green);
}
return true;
}
private static bool UploadVc()
{
LogToFile("Uploading Virtual Currency Settings...");
var parsedFile = ParseFile(currencyPath);
var vcData = JsonWrapper.DeserializeObject<List<VirtualCurrencyData>>(parsedFile);
var request = new AddVirtualCurrencyTypesRequest
{
VirtualCurrencies = vcData
};
var updateVcTask = PlayFabAdminAPI.AddVirtualCurrencyTypesAsync(request);
updateVcTask.Wait();
if (updateVcTask.Result.Error != null)
{
OutputPlayFabError("\tVC Upload Error: ", updateVcTask.Result.Error);
return false;
}
LogToFile("\tUploaded VC!", ConsoleColor.Green);
return true;
}
private static bool UploadDropTables()
{
if (string.IsNullOrEmpty(dropTablesPath))
return false;
LogToFile("Uploading DropTables...");
var parsedFile = ParseFile(dropTablesPath);
var dtDict = JsonWrapper.DeserializeObject<Dictionary<string, RandomResultTableListing>>(parsedFile);
if (dtDict == null)
{
LogToFile("\tAn error occurred deserializing the DropTables.json file.", ConsoleColor.Red);
return false;
}
var dropTables = new List<RandomResultTable>();
foreach (var kvp in dtDict)
{
dropTables.Add(new RandomResultTable()
{
TableId = kvp.Value.TableId,
Nodes = kvp.Value.Nodes
});
}
var request = new UpdateRandomResultTablesRequest()
{
CatalogVersion = defaultCatalog,
Tables = dropTables
};
var updateResultTableTask = PlayFabAdminAPI.UpdateRandomResultTablesAsync(request);
updateResultTableTask.Wait();
if (updateResultTableTask.Result.Error != null)
{
OutputPlayFabError("\tDropTable Upload Error: ", updateResultTableTask.Result.Error);
return false;
}
LogToFile("\tUploaded DropTables!", ConsoleColor.Green);
return true;
}
private static bool UploadStores(string filePath, string catalogName)
{
if (string.IsNullOrEmpty(filePath))
return false;
LogToFile("Uploading Stores...");
var parsedFile = ParseFile(filePath);
var storesList = JsonWrapper.DeserializeObject<List<StoreWrapper>>(parsedFile);
foreach (var eachStore in storesList)
{
LogToFile("\tUploading: " + eachStore.StoreId);
var request = new UpdateStoreItemsRequest
{
CatalogVersion = catalogName,
StoreId = eachStore.StoreId,
Store = eachStore.Store,
MarketingData = eachStore.MarketingData
};
var updateStoresTask = PlayFabAdminAPI.SetStoreItemsAsync(request);
updateStoresTask.Wait();
if (updateStoresTask.Result.Error != null)
OutputPlayFabError("\t\tStore Upload: " + eachStore.StoreId, updateStoresTask.Result.Error);
else
LogToFile("\t\tStore: " + eachStore.StoreId + " Uploaded. ", ConsoleColor.Green);
}
return true;
}
private static bool UploadPolicy(string filePath)
{
if (string.IsNullOrEmpty(filePath))
return false;
LogToFile("Uploading Policy...");
var parsedFile = ParseFile(filePath);
var permissionList = JsonWrapper.DeserializeObject<List<PlayFab.ProfilesModels.EntityPermissionStatement>>(parsedFile);
var request = new PlayFab.ProfilesModels.SetGlobalPolicyRequest
{
Permissions = permissionList
};
var setPermissionTask = PlayFab.PlayFabProfilesAPI.SetGlobalPolicyAsync(request);
setPermissionTask.Wait();
if (setPermissionTask.Result.Error != null)
OutputPlayFabError("\t\tSet Permissions: ", setPermissionTask.Result.Error);
else
LogToFile("\t\tPermissions uploaded... ", ConsoleColor.Green);
return true;
}
private static bool UploadCdnAssets()
{
var tdParsedFile = ParseFile(titleDataPath);
var titleDataDict = JsonWrapper.DeserializeObject<Dictionary<string, string>>(tdParsedFile);
var useCDN = titleDataDict.ContainsKey("UseCDN") && int.Parse(titleDataDict["UseCDN"]) == 1;
if (!useCDN)
{
LogToFile("\tSkipping CDN Upload, because UseCDN is set to 0");
return true;
}
if (string.IsNullOrEmpty(cdnAssetsPath))
return false;
LogToFile("Uploading CDN AssetBundles...");
var parsedFile = ParseFile(cdnAssetsPath);
var bundleNames = JsonWrapper.DeserializeObject<List<string>>(parsedFile); // TODO: This could probably just read the list of files from the directory
if (bundleNames != null)
{
foreach (var bundleName in bundleNames)
{
foreach (CdnPlatform eachPlatform in Enum.GetValues(typeof(CdnPlatform)))
{
var key = cdnPlatformSubfolder[eachPlatform] + bundleName;
var path = cdnPath + key;
UploadAsset(key, path);
}
}
}
else
{
LogToFile("\tAn error occurred deserializing CDN Assets: ", ConsoleColor.Red);
return false;
}
return true;
}
#endregion
#region Helper Functions -- these functions help the main uploading functions
static void LogToFile(string content, ConsoleColor color = ConsoleColor.White)
{
Console.ForegroundColor = color;
Console.WriteLine(content);
logStream.WriteLine(content);
Console.ForegroundColor = ConsoleColor.White;
}
static void OutputPlayFabError(string context, PlayFabError err)
{
hitErrors = true;
LogToFile("\tAn error occurred during: " + context, ConsoleColor.Red);
var details = string.Empty;
if (err.ErrorDetails != null)
{
foreach (var kvp in err.ErrorDetails)
{
details += (kvp.Key + ": ");
foreach (var eachIssue in kvp.Value)
details += (eachIssue + ", ");
details += "\n";
}
}
LogToFile(string.Format("\t\t[{0}] -- {1}: {2} ", err.Error, err.ErrorMessage, details), ConsoleColor.Red);
}
static string ParseFile(string path)
{
var s = File.OpenText(path);
var contents = s.ReadToEnd();
s.Close();
return contents;
}
static CatalogItem CloneCatalogItemAndStripTables(CatalogItem strip)
{
if (strip == null)
return null;
return new CatalogItem
{
ItemId = strip.ItemId,
ItemClass = strip.ItemClass,
CatalogVersion = strip.CatalogVersion,
DisplayName = strip.DisplayName,
Description = strip.Description,
VirtualCurrencyPrices = strip.VirtualCurrencyPrices,
RealCurrencyPrices = strip.RealCurrencyPrices,
Tags = strip.Tags,
CustomData = strip.CustomData,
Consumable = strip.Consumable,
Container = null,//strip.Container, // Clearing this is the point
Bundle = null,//strip.Bundle, // Clearing this is the point
CanBecomeCharacter = strip.CanBecomeCharacter,
IsStackable = strip.CanBecomeCharacter,
IsTradable = strip.IsTradable,
ItemImageUrl = strip.ItemImageUrl
};
}
private static bool UpdateCatalog(List<CatalogItem> catalog, string catalogName, bool isDefault)
{
var request = new UpdateCatalogItemsRequest
{
CatalogVersion = catalogName,
Catalog = catalog,
SetAsDefaultCatalog = isDefault
};
var updateCatalogItemsTask = PlayFabAdminAPI.UpdateCatalogItemsAsync(request);
updateCatalogItemsTask.Wait();
if (updateCatalogItemsTask.Result.Error != null)
{
OutputPlayFabError("\tCatalog Upload Error: ", updateCatalogItemsTask.Result.Error);
return false;
}
LogToFile("\tUploaded Catalog!", ConsoleColor.Green);
return true;
}
private static bool UploadAsset(string key, string path)
{
var request = new GetContentUploadUrlRequest()
{
Key = key,
ContentType = "application/x-gzip"
};
LogToFile("\tFetching CDN endpoint for " + key);
var getContentUploadTask = PlayFabAdminAPI.GetContentUploadUrlAsync(request);
getContentUploadTask.Wait();
if (getContentUploadTask.Result.Error != null)
{
OutputPlayFabError("\t\tAcquire CDN URL Error: ", getContentUploadTask.Result.Error);
return false;
}
var destUrl = getContentUploadTask.Result.Result.URL;
LogToFile("\t\tAcquired CDN Address: " + key, ConsoleColor.Green);
byte[] fileContents = File.ReadAllBytes(path);
return PutFile(key, destUrl, fileContents);
}
private static bool PutFile(string key, string url, byte[] payload)
{
LogToFile("\t\tStarting HTTP PUT for: " + key);
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "PUT";
request.ContentType = "application/x-gzip";
if (payload != null)
{
var dataStream = request.GetRequestStream();
dataStream.Write(payload, 0, payload.Length);
dataStream.Close();
}
else
{
LogToFile("\t\t\tERROR: Byte array was empty or null", ConsoleColor.Red);
return false;
}
var response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
LogToFile("\t\t\tHTTP PUT Successful:" + key, ConsoleColor.Green);
return true;
}
else
{
LogToFile(string.Format("\t\t\tERROR: Asset:{0} -- Code:[{1}] -- Msg:{2}", url, response.StatusCode, response.StatusDescription), ConsoleColor.Red);
return false;
}
}
#endregion
}
}
public class CatalogWrapper
{
public string CatalogVersion;
public List<CatalogItem> Catalog;
}
public class StoreWrapper
{
public string StoreId;
public List<StoreItem> Store;
public StoreMarketingModel MarketingData;
}
| |
// Copyright (c) Microsoft. All rights reserved.
using System;
using System.Collections.ObjectModel;
using Windows.Devices.Enumeration;
using Windows.Foundation;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using SDKTemplate;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace DeviceEnumeration
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class Scenario8 : Page
{
private MainPage rootPage;
private DeviceWatcher deviceWatcher = null;
private TypedEventHandler<DeviceWatcher, DeviceInformation> handlerAdded = null;
private TypedEventHandler<DeviceWatcher, DeviceInformationUpdate> handlerUpdated = null;
private TypedEventHandler<DeviceWatcher, DeviceInformationUpdate> handlerRemoved = null;
private TypedEventHandler<DeviceWatcher, Object> handlerEnumCompleted = null;
private TypedEventHandler<DeviceWatcher, Object> handlerStopped = null;
public ObservableCollection<DeviceInformationDisplay> ResultCollection
{
get;
private set;
}
public Scenario8()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
rootPage = MainPage.Current;
ResultCollection = new ObservableCollection<DeviceInformationDisplay>();
selectorComboBox.ItemsSource = ProtocolSelectorChoices.Selectors;
selectorComboBox.SelectedIndex = 0;
DataContext = this;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
StopWatcher();
}
private void StartWatcherButton_Click(object sender, RoutedEventArgs e)
{
StartWatcher();
}
private void StopWatcherButton_Click(object sender, RoutedEventArgs e)
{
StopWatcher();
}
private void StartWatcher()
{
ProtocolSelectorInfo protocolSelectorInfo;
string aqsFilter;
startWatcherButton.IsEnabled = false;
ResultCollection.Clear();
// Request the IsPaired property so we can display the paired status in the UI
string[] requestedProperties = {"System.Devices.Aep.IsPaired"};
// Get the device selector chosen by the UI, then 'AND' it with the 'CanPair' property
protocolSelectorInfo = (ProtocolSelectorInfo)selectorComboBox.SelectedItem;
aqsFilter = protocolSelectorInfo.Selector + " AND System.Devices.Aep.CanPair:=System.StructuredQueryType.Boolean#True";
deviceWatcher = DeviceInformation.CreateWatcher(
aqsFilter,
requestedProperties,
DeviceInformationKind.AssociationEndpoint
);
// Hook up handlers for the watcher events before starting the watcher
handlerAdded = new TypedEventHandler<DeviceWatcher, DeviceInformation>(async (watcher, deviceInfo) =>
{
// Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
{
ResultCollection.Add(new DeviceInformationDisplay(deviceInfo));
rootPage.NotifyUser(
String.Format("{0} devices found.", ResultCollection.Count),
NotifyType.StatusMessage);
});
});
deviceWatcher.Added += handlerAdded;
handlerUpdated = new TypedEventHandler<DeviceWatcher, DeviceInformationUpdate>(async (watcher, deviceInfoUpdate) =>
{
// Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
{
// Find the corresponding updated DeviceInformation in the collection and pass the update object
// to the Update method of the existing DeviceInformation. This automatically updates the object
// for us.
foreach (DeviceInformationDisplay deviceInfoDisp in ResultCollection)
{
if (deviceInfoDisp.Id == deviceInfoUpdate.Id)
{
deviceInfoDisp.Update(deviceInfoUpdate);
break;
}
}
});
});
deviceWatcher.Updated += handlerUpdated;
handlerRemoved = new TypedEventHandler<DeviceWatcher, DeviceInformationUpdate>(async (watcher, deviceInfoUpdate) =>
{
// Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
{
// Find the corresponding DeviceInformation in the collection and remove it
foreach (DeviceInformationDisplay deviceInfoDisp in ResultCollection)
{
if (deviceInfoDisp.Id == deviceInfoUpdate.Id)
{
ResultCollection.Remove(deviceInfoDisp);
break;
}
}
rootPage.NotifyUser(
String.Format("{0} devices found.", ResultCollection.Count),
NotifyType.StatusMessage);
});
});
deviceWatcher.Removed += handlerRemoved;
handlerEnumCompleted = new TypedEventHandler<DeviceWatcher, Object>(async (watcher, obj) =>
{
await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
{
rootPage.NotifyUser(
String.Format("{0} devices found. Enumeration completed. Watching for updates...", ResultCollection.Count),
NotifyType.StatusMessage);
});
});
deviceWatcher.EnumerationCompleted += handlerEnumCompleted;
handlerStopped = new TypedEventHandler<DeviceWatcher, Object>(async (watcher, obj) =>
{
await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
{
rootPage.NotifyUser(
String.Format("{0} devices found. Watcher {1}.",
ResultCollection.Count,
DeviceWatcherStatus.Aborted == watcher.Status ? "aborted" : "stopped"),
NotifyType.StatusMessage);
});
});
deviceWatcher.Stopped += handlerStopped;
rootPage.NotifyUser("Starting Watcher...", NotifyType.StatusMessage);
deviceWatcher.Start();
stopWatcherButton.IsEnabled = true;
}
private void StopWatcher()
{
stopWatcherButton.IsEnabled = false;
if (null != deviceWatcher)
{
// First unhook all event handlers except the stopped handler. This ensures our
// event handlers don't get called after stop, as stop won't block for any "in flight"
// event handler calls. We leave the stopped handler as it's guaranteed to only be called
// once and we'll use it to know when the query is completely stopped.
deviceWatcher.Added -= handlerAdded;
deviceWatcher.Updated -= handlerUpdated;
deviceWatcher.Removed -= handlerRemoved;
deviceWatcher.EnumerationCompleted -= handlerEnumCompleted;
if (DeviceWatcherStatus.Started == deviceWatcher.Status ||
DeviceWatcherStatus.EnumerationCompleted == deviceWatcher.Status)
{
deviceWatcher.Stop();
}
}
startWatcherButton.IsEnabled = true;
}
private async void PairButton_Click(object sender, RoutedEventArgs e)
{
DeviceInformationDisplay deviceInfoDisp = resultsListView.SelectedItem as DeviceInformationDisplay;
pairButton.IsEnabled = false;
DevicePairingResult dpr = await deviceInfoDisp.DeviceInformation.Pairing.PairAsync();
rootPage.NotifyUser(
"Pairing result = " + dpr.Status.ToString(),
dpr.Status == DevicePairingResultStatus.Paired ? NotifyType.StatusMessage : NotifyType.ErrorMessage);
}
private void ResultsListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DeviceInformationDisplay deviceInfoDisp = (DeviceInformationDisplay)resultsListView.SelectedItem;
if (null != deviceInfoDisp &&
true == deviceInfoDisp.DeviceInformation.Pairing.CanPair &&
false == deviceInfoDisp.DeviceInformation.Pairing.IsPaired)
{
pairButton.IsEnabled = true;
}
else
{
pairButton.IsEnabled = false;
}
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia.Collections;
namespace Avalonia.Controls
{
/// <summary>
/// Holds a collection of style classes for an <see cref="IControl"/>.
/// </summary>
/// <remarks>
/// Similar to CSS, each control may have any number of styling classes applied.
/// </remarks>
public class Classes : AvaloniaList<string>, IPseudoClasses
{
/// <summary>
/// Initializes a new instance of the <see cref="Classes"/> class.
/// </summary>
public Classes()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Classes"/> class.
/// </summary>
/// <param name="items">The initial items.</param>
public Classes(IEnumerable<string> items)
: base(items)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Classes"/> class.
/// </summary>
/// <param name="items">The initial items.</param>
public Classes(params string[] items)
: base(items)
{
}
/// <summary>
/// Adds a style class to the collection.
/// </summary>
/// <param name="name">The class name.</param>
/// <remarks>
/// Only standard classes may be added via this method. To add pseudoclasses (classes
/// beginning with a ':' character) use the protected <see cref="Control.PseudoClasses"/>
/// property.
/// </remarks>
public override void Add(string name)
{
ThrowIfPseudoclass(name, "added");
if (!Contains(name))
{
base.Add(name);
}
}
/// <summary>
/// Adds a style classes to the collection.
/// </summary>
/// <param name="names">The class names.</param>
/// <remarks>
/// Only standard classes may be added via this method. To add pseudoclasses (classes
/// beginning with a ':' character) use the protected <see cref="Control.PseudoClasses"/>
/// property.
/// </remarks>
public override void AddRange(IEnumerable<string> names)
{
var c = new List<string>();
foreach (var name in names)
{
ThrowIfPseudoclass(name, "added");
if (!Contains(name))
{
c.Add(name);
}
}
base.AddRange(c);
}
/// <summary>
/// Inserts a style class into the collection.
/// </summary>
/// <param name="index">The index to insert the class at.</param>
/// <param name="name">The class name.</param>
/// <remarks>
/// Only standard classes may be added via this method. To add pseudoclasses (classes
/// beginning with a ':' character) use the protected <see cref="Control.PseudoClasses"/>
/// property.
/// </remarks>
public override void Insert(int index, string name)
{
ThrowIfPseudoclass(name, "added");
if (!Contains(name))
{
base.Insert(index, name);
}
}
/// <summary>
/// Inserts style classes into the collection.
/// </summary>
/// <param name="index">The index to insert the class at.</param>
/// <param name="names">The class names.</param>
/// <remarks>
/// Only standard classes may be added via this method. To add pseudoclasses (classes
/// beginning with a ':' character) use the protected <see cref="Control.PseudoClasses"/>
/// property.
/// </remarks>
public override void InsertRange(int index, IEnumerable<string> names)
{
var c = new List<string>();
foreach (var name in names)
{
ThrowIfPseudoclass(name, "added");
if (!Contains(name))
{
c.Add(name);
}
}
base.InsertRange(index, c);
}
/// <summary>
/// Removes a style class from the collection.
/// </summary>
/// <param name="name">The class name.</param>
/// <remarks>
/// Only standard classes may be removed via this method. To remove pseudoclasses (classes
/// beginning with a ':' character) use the protected <see cref="Control.PseudoClasses"/>
/// property.
/// </remarks>
public override bool Remove(string name)
{
ThrowIfPseudoclass(name, "removed");
return base.Remove(name);
}
/// <summary>
/// Removes style classes from the collection.
/// </summary>
/// <param name="names">The class name.</param>
/// <remarks>
/// Only standard classes may be removed via this method. To remove pseudoclasses (classes
/// beginning with a ':' character) use the protected <see cref="Control.PseudoClasses"/>
/// property.
/// </remarks>
public override void RemoveAll(IEnumerable<string> names)
{
var c = new List<string>();
foreach (var name in names)
{
ThrowIfPseudoclass(name, "removed");
if (!Contains(name))
{
c.Add(name);
}
}
base.RemoveAll(c);
}
/// <summary>
/// Removes a style class from the collection.
/// </summary>
/// <param name="index">The index of the class in the collection.</param>
/// <remarks>
/// Only standard classes may be removed via this method. To remove pseudoclasses (classes
/// beginning with a ':' character) use the protected <see cref="Control.PseudoClasses"/>
/// property.
/// </remarks>
public override void RemoveAt(int index)
{
var name = this[index];
ThrowIfPseudoclass(name, "removed");
base.RemoveAt(index);
}
/// <summary>
/// Removes style classes from the collection.
/// </summary>
/// <param name="index">The first index to remove.</param>
/// <param name="count">The number of items to remove.</param>
public override void RemoveRange(int index, int count)
{
var names = GetRange(index, count);
base.RemoveRange(index, count);
}
/// <summary>
/// Removes all non-pseudoclasses in the collection and adds a new set.
/// </summary>
/// <param name="source">The new contents of the collection.</param>
public void Replace(IList<string> source)
{
var toRemove = new List<string>();
foreach (var name in source)
{
ThrowIfPseudoclass(name, "added");
}
foreach (var name in this)
{
if (!name.StartsWith(":"))
{
toRemove.Add(name);
}
}
base.RemoveAll(toRemove);
base.AddRange(source);
}
/// <inheritdoc/>
void IPseudoClasses.Add(string name)
{
if (!Contains(name))
{
base.Add(name);
}
}
/// <inheritdoc/>
bool IPseudoClasses.Remove(string name)
{
return base.Remove(name);
}
private void ThrowIfPseudoclass(string name, string operation)
{
if (name.StartsWith(":"))
{
throw new ArgumentException(
$"The pseudoclass '{name}' may only be {operation} by the control itself.");
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;
namespace Steering {
[ExecuteInEditMode]
public class Path : MonoBehaviour {
#region Stations list
[SerializeField]
private List<Station> stations = new List<Station>();
public int StationsCount {
get { return stations.Count; }
}
public GameObject GetStation(int index) {
return stations[index].gameObject;
}
public ReadOnlyCollection<Station> GetAllStations() {
return stations.AsReadOnly();
}
/// <summary>
/// THIS SHOULD NEVER EVER BE USED BY ANYTHING ELSE THAN THE REORDERABLELIST
/// </summary>
/// <returns></returns>
public List<Station> GetAllStationWARNING() {
return stations;
}
public void AddStation(GameObject station) {
stations.Add(new Station(station));
ReCalculateStationWeights();
}
public void RemoveStationAt(int index) {
stations.RemoveAt(index);
ReCalculateStationWeights();
}
internal void ReCalculateStationWeights() {
// calculate distances and the sum
float sum = 0f;
for (int i = (isCircle ? 0 : 1); i < stations.Count; i++) {
stations[i].distanceToHere = Vector3.Distance(stations[i].gameObject.transform.position, stations[GetPreviousStationIndex(i)].gameObject.transform.position);
sum += stations[i].distanceToHere;
}
// calcuate weights
for (int i = (isCircle ? 0 : 1); i < stations.Count; i++) {
stations[i].weight = stations[i].distanceToHere / sum;
}
}
#endregion
[SerializeField]
internal bool isCircle = false;
/// <summary>
/// Returns position of station with the given index
/// </summary>
public Vector3 GetStationPosition(int index) {
if (index >= stations.Count || index < 0)
throw new ArgumentException(index + " is not a valid station index for this method!");
return stations[index].gameObject.transform.position;
}
/// <summary>
/// Returns the index of the next station. Takes the circle into consideration
/// </summary>
public int GetNextStationIndex(int current) {
if (current >= stations.Count || current < 0)
throw new ArgumentException(current + " is not a valid station index for this method!");
if (current < stations.Count - 1)
return current + 1;
else { // it is the last station that has been given
if (isCircle) return 0;
else return stations.Count - 1;
}
}
/// <summary>
/// Returns the index of the previous station. Takes the circle into consideration
/// </summary>
public int GetPreviousStationIndex(int current) {
if (current >= stations.Count || current < 0)
throw new ArgumentException(current + " is not a valid station index for this method!");
if (current > 0)
return current - 1;
else { // current is 0
if (isCircle) return stations.Count - 1;
else return 0;
}
}
#region Unity methods
/// <summary>
/// Angle between end of arrow line and the arrow line
/// </summary>
float endAngle = Mathf.PI * 0.2f;
public void OnDrawGizmos() {
Gizmos.color = Color.red;
for (int i = 0; i < (isCircle ? stations.Count : stations.Count - 1); i++) {
int toIndex = i == stations.Count - 1 ? 0 : i + 1;
Gizmos.DrawWireSphere(stations[i].gameObject.transform.position, 0.2f);
Gizmos.DrawLine(stations[i].gameObject.transform.position, stations[toIndex].gameObject.transform.position);
// the vector defined by i + 1 and i positions
Vector3 vector = stations[toIndex].gameObject.transform.position - stations[i].gameObject.transform.position;
// the angle of the little end in the arrow from up vector (left)
float thingyAngleLeft = (-Mathf.Atan2(vector.x, vector.y) + (Mathf.PI - endAngle)) * Mathf.Rad2Deg;
// the same but right
float thingyAngleRight = thingyAngleLeft + endAngle * 2 * Mathf.Rad2Deg;
// the position where the end thingy will be drawn
Vector3 thingyPos = stations[i].gameObject.transform.position + vector / 2f;
// end position of left thingy
Vector3 endPositionLeft = thingyPos + Quaternion.Euler(0, 0, thingyAngleLeft) * Vector3.up;
// end position of right thingy
Vector3 endPositionRight = thingyPos + Quaternion.Euler(0, 0, thingyAngleRight) * Vector3.up;
// drawing arrow end
Gizmos.DrawLine(thingyPos, endPositionLeft);
Gizmos.DrawLine(thingyPos, endPositionRight);
Handles.Label(stations[i].gameObject.transform.position, stations[i].gameObject.name);
}
if (stations.Count > 0)
Gizmos.DrawWireSphere(stations[stations.Count - 1].gameObject.transform.position, 0.2f);
Gizmos.color = Color.white;
}
public void Update() {
// user added a station in game as child
if (transform.childCount > stations.Count) {
for (int i = 0; i < transform.childCount; i++) {
// we don't have it in station list
var station = from st in stations
where st.gameObject.Equals(transform.GetChild(i).gameObject)
select st;
if (station.Count() == 0) {
stations.Add(new Station(transform.GetChild(i).gameObject));
ReCalculateStationWeights();
break;
}
}
// user removed a station in game
} else if (transform.childCount < stations.Count) {
for (int i = stations.Count - 1; i >= 0; i--) {
// this is the station that has been destroyed
if (stations[i] == null) {
stations.RemoveAt(i);
ReCalculateStationWeights();
break;
}
}
}
ReCalculateStationWeights();
}
#endregion
/// <summary>
/// Returns the ditance from the vector of (station[index-1] -> stations[index]) from point
/// </summary>
public float GetDistanceFromPathTo(Vector3 point, int index) {
if (index >= stations.Count || index < 0)
throw new ArgumentException(index + " is not a valid station index for this method!");
return Vector3.Distance(point, GetClosestPointOnPathTo(index, point));
}
/// <summary>
/// Returns the clostest point on the vector of (station[index-1] -> stations[index]) from point
/// </summary>
public Vector3 GetClosestPointOnPathTo(int index, Vector3 point) {
if (index >= stations.Count || index < 0)
throw new ArgumentException(index + " is not a valid station index for this method!");
int lastStationIndex = GetPreviousStationIndex(index);
// the vector of the path to index station
Vector3 pathVector = stations[lastStationIndex].gameObject.transform.position - stations[index].gameObject.transform.position;
float pathLengthSquared = Mathf.Pow(pathVector.magnitude, 2);
// we project the (index station -> point) vector down to the pathVector
// and if it is out of range make it one of the endpoints
float projectionAt = Mathf.Min(1f, Mathf.Max(0f,
Vector3.Dot(point - stations[index].gameObject.transform.position, pathVector) / pathLengthSquared
));
Vector3 projectedPoint = stations[index].gameObject.transform.position + projectionAt * pathVector;
return projectedPoint;
}
/// <summary>
/// Returns the closest point on the path from point
/// </summary>
public Vector3 GetClosestPointOnPath(Vector3 point) {
// Go through each and choose the smallest distance
Vector3 closestPoint = GetClosestPointOnPathTo(stations.Count - 1, point);
float distance = Vector3.Distance(point, closestPoint);
for (int i = (isCircle ? 0 : 1); i < stations.Count - 1; i++) {
Vector3 tempClosestPoint = GetClosestPointOnPathTo(i, point);
float tempDist = Vector3.Distance(point, tempClosestPoint);
if (tempDist < distance) {
distance = tempDist;
closestPoint = tempClosestPoint;
}
}
return closestPoint;
}
/// <summary>
/// Gets the percentage of the closest point on path
/// </summary>
public float GetClosestPointOnPathPercent(Vector3 point) {
// Go through each and choose the smallest distance
// while that's happening store the closest point' percent
float distance = Mathf.Infinity;
float percent = 0f;
float percentSumSoFar = 0f;
for (int i = (isCircle ? 0 : 1); i < stations.Count; i++) {
Vector3 tempClosestPoint = GetClosestPointOnPathTo(i, point);
float tempDist = Vector3.Distance(point, tempClosestPoint);
if (tempDist < distance) {
distance = tempDist;
percent = percentSumSoFar +
(tempClosestPoint - stations[GetPreviousStationIndex(i)].gameObject.transform.position).magnitude / stations[i].distanceToHere * stations[i].weight;
}
percentSumSoFar += stations[i].weight;
}
return percent;
}
/// <summary>
/// Returns point on path from precentage
/// </summary>
public Vector3 GetPointOnPathPercent(float percentage) {
percentage %= 1f;
// go till if we add the stations's weight we go over percentage with the currentSum
// then we know that the point is in the given path so calculate it where it is
float currentSum = 0f;
for (int i = (isCircle ? 0 : 1); i < stations.Count; i++) {
if (currentSum + stations[i].weight < percentage) {
currentSum += stations[i].weight;
} else {
percentage -= currentSum;
int previousIndex = GetPreviousStationIndex(i);
return stations[previousIndex].gameObject.transform.position +
(stations[i].gameObject.transform.position - stations[previousIndex].gameObject.transform.position) * percentage / stations[i].weight;
}
}
return new Vector3();
}
}
[Serializable]
public class Station {
public GameObject gameObject;
public float weight;
/// <summary>
/// Distance to this station from the previous one
/// </summary>
public float distanceToHere;
public Station(GameObject gameObject) {
this.gameObject = gameObject;
weight = 0f;
}
}
[CustomEditor(typeof(Path))]
public class PathEditor : Editor {
private const string stationNames = "Station";
private Color editModeColor = new Color(0.95686f, 0.26275f, 0.21176f);
private Color normalModeColor = new Color(0.29804f, 0.68627f, 0.31373f);
private GUIStyle errorLabel;
private ReorderableList list;
private bool editMode = false;
private Path path;
private SerializedProperty isCircleProperty;
public void OnEnable() {
path = (Path) target;
isCircleProperty = serializedObject.FindProperty("isCircle");
// ====== GUI STYLES ===========
errorLabel = new GUIStyle();
errorLabel.fontSize = 16;
errorLabel.normal.textColor = Color.red;
// ======= REORDERABLE LIST ==========
list = new ReorderableList(path.GetAllStationWARNING(), typeof(Station));
list.drawHeaderCallback = (Rect rect) => {
EditorGUI.LabelField(rect, "Stations");
};
list.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) => {
GameObject station = ((Station) list.list[index]).gameObject;
EditorGUI.Vector2Field(rect, station.name + ":", station.transform.position);
};
list.onAddCallback = (ReorderableList list) => {
Vector3 newStationPosition;
// if no station yet use path parent position otherwise the last station position
if (path.StationsCount == 0)
newStationPosition = path.transform.position;
else
newStationPosition = path.GetStation(path.StationsCount - 1).transform.position;
// set all attributes
GameObject newStation = new GameObject(stationNames + (path.StationsCount + 1));
newStation.transform.position = newStationPosition;
newStation.transform.parent = path.transform;
path.AddStation(newStation);
if (editMode) {
Selection.activeGameObject = newStation;
list.index = list.count;
}
};
list.onRemoveCallback = (ReorderableList list) => {
GameObject selected = (GameObject) list.serializedProperty.GetArrayElementAtIndex(list.index).objectReferenceValue;
// DELETE
GUI.color = Color.red;
{
DestroyImmediate(selected);
((Path) target).RemoveStationAt(list.index);
NameAllCorrectly(path);
}
GUI.color = Color.white;
};
list.onReorderCallback = (ReorderableList list) => {
NameAllCorrectly(path);
path.ReCalculateStationWeights();
};
list.onSelectCallback = (ReorderableList list) => {
if (editMode)
Selection.activeGameObject = ((Station) list.list[list.index]).gameObject;
};
}
public override void OnInspectorGUI() {
serializedObject.Update();
EditorGUILayout.PropertyField(isCircleProperty);
if (editMode) GUI.color = editModeColor;
else GUI.color = normalModeColor;
{
if (GUILayout.Button((editMode ? "Close " : "Enter ") + "edit mode")) {
if (editMode) {
ActiveEditorTracker.sharedTracker.isLocked = false;
Selection.activeGameObject = path.gameObject;
editMode = false;
} else {
ActiveEditorTracker.sharedTracker.isLocked = true;
editMode = true;
}
}
}
GUI.color = Color.white;
if (path.StationsCount < 2) {
GUILayout.Label("You need at least two stations for a path!", errorLabel);
}
list.DoLayoutList();
serializedObject.ApplyModifiedProperties();
}
/// <summary>
/// Names all stations in this path correctly
/// </summary>
private void NameAllCorrectly(Path path) {
for (int k = 0; k < path.StationsCount; k++) {
// if it still has the default name
if (path.GetStation(k).gameObject.name.StartsWith(stationNames))
path.GetStation(k).gameObject.name = stationNames + (k + 1);
}
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
namespace DiscUtils.Nfs
{
using System;
using System.Collections.Generic;
internal sealed class Nfs3Client : IDisposable
{
private RpcClient _rpcClient;
private Nfs3Mount _mountClient;
private Nfs3 _nfsClient;
private Nfs3FileHandle _rootHandle;
private Nfs3FileSystemInfo _fsInfo;
private Dictionary<Nfs3FileHandle, Nfs3FileAttributes> _cachedAttributes;
public Nfs3Client(string address, RpcCredentials credentials, string mountPoint)
{
_rpcClient = new RpcClient(address, credentials);
_mountClient = new Nfs3Mount(_rpcClient);
_rootHandle = _mountClient.Mount(mountPoint).FileHandle;
_nfsClient = new Nfs3(_rpcClient);
Nfs3FileSystemInfoResult fsiResult = _nfsClient.FileSystemInfo(_rootHandle);
_fsInfo = fsiResult.FileSystemInfo;
_cachedAttributes = new Dictionary<Nfs3FileHandle, Nfs3FileAttributes>();
_cachedAttributes[_rootHandle] = fsiResult.PostOpAttributes;
}
public Nfs3FileHandle RootHandle
{
get { return _rootHandle; }
}
public Nfs3FileSystemInfo FileSystemInfo
{
get { return _fsInfo; }
}
public void Dispose()
{
if (_rpcClient != null)
{
_rpcClient.Dispose();
_rpcClient = null;
}
}
public Nfs3FileAttributes GetAttributes(Nfs3FileHandle handle)
{
Nfs3FileAttributes result;
if (_cachedAttributes.TryGetValue(handle, out result))
{
return result;
}
Nfs3GetAttributesResult getResult = _nfsClient.GetAttributes(handle);
if (getResult.Status == Nfs3Status.Ok)
{
_cachedAttributes[handle] = getResult.Attributes;
return getResult.Attributes;
}
else
{
throw new Nfs3Exception(getResult.Status);
}
}
public void SetAttributes(Nfs3FileHandle handle, Nfs3SetAttributes newAttributes)
{
Nfs3ModifyResult result = _nfsClient.SetAttributes(handle, newAttributes);
_cachedAttributes[handle] = result.CacheConsistency.After;
if (result.Status != Nfs3Status.Ok)
{
throw new Nfs3Exception(result.Status);
}
}
public Nfs3FileHandle Lookup(Nfs3FileHandle dirHandle, string name)
{
Nfs3LookupResult result = _nfsClient.Lookup(dirHandle, name);
if (result.ObjectAttributes != null && result.ObjectHandle != null)
{
_cachedAttributes[result.ObjectHandle] = result.ObjectAttributes;
}
if (result.DirAttributes != null)
{
_cachedAttributes[dirHandle] = result.DirAttributes;
}
if (result.Status == Nfs3Status.Ok)
{
return result.ObjectHandle;
}
else if (result.Status == Nfs3Status.NoSuchEntity)
{
return null;
}
else
{
throw new Nfs3Exception(result.Status);
}
}
public Nfs3AccessPermissions Access(Nfs3FileHandle handle, Nfs3AccessPermissions requested)
{
Nfs3AccessResult result = _nfsClient.Access(handle, requested);
if (result.ObjectAttributes != null)
{
_cachedAttributes[handle] = result.ObjectAttributes;
}
if (result.Status == Nfs3Status.Ok)
{
return result.Access;
}
else
{
throw new Nfs3Exception(result.Status);
}
}
public Nfs3ReadResult Read(Nfs3FileHandle fileHandle, long position, int count)
{
Nfs3ReadResult result = _nfsClient.Read(fileHandle, position, count);
if (result.FileAttributes != null)
{
_cachedAttributes[fileHandle] = result.FileAttributes;
}
if (result.Status == Nfs3Status.Ok)
{
return result;
}
else
{
throw new Nfs3Exception(result.Status);
}
}
public int Write(Nfs3FileHandle fileHandle, long position, byte[] buffer, int offset, int count)
{
Nfs3WriteResult result = _nfsClient.Write(fileHandle, position, buffer, offset, count);
_cachedAttributes[fileHandle] = result.CacheConsistency.After;
if (result.Status == Nfs3Status.Ok)
{
return result.Count;
}
else
{
throw new Nfs3Exception(result.Status);
}
}
public Nfs3FileHandle Create(Nfs3FileHandle dirHandle, string name, bool createNew, Nfs3SetAttributes attributes)
{
Nfs3CreateResult result = _nfsClient.Create(dirHandle, name, createNew, attributes);
if (result.Status == Nfs3Status.Ok)
{
_cachedAttributes[result.FileHandle] = result.FileAttributes;
return result.FileHandle;
}
else
{
throw new Nfs3Exception(result.Status);
}
}
public Nfs3FileHandle MakeDirectory(Nfs3FileHandle dirHandle, string name, Nfs3SetAttributes attributes)
{
Nfs3CreateResult result = _nfsClient.MakeDirectory(dirHandle, name, attributes);
if (result.Status == Nfs3Status.Ok)
{
_cachedAttributes[result.FileHandle] = result.FileAttributes;
return result.FileHandle;
}
else
{
throw new Nfs3Exception(result.Status);
}
}
public void Remove(Nfs3FileHandle dirHandle, string name)
{
Nfs3ModifyResult result = _nfsClient.Remove(dirHandle, name);
_cachedAttributes[dirHandle] = result.CacheConsistency.After;
if (result.Status != Nfs3Status.Ok)
{
throw new Nfs3Exception(result.Status);
}
}
public void RemoveDirectory(Nfs3FileHandle dirHandle, string name)
{
Nfs3ModifyResult result = _nfsClient.RemoveDirectory(dirHandle, name);
_cachedAttributes[dirHandle] = result.CacheConsistency.After;
if (result.Status != Nfs3Status.Ok)
{
throw new Nfs3Exception(result.Status);
}
}
public void Rename(Nfs3FileHandle fromDirHandle, string fromName, Nfs3FileHandle toDirHandle, string toName)
{
Nfs3RenameResult result = _nfsClient.Rename(fromDirHandle, fromName, toDirHandle, toName);
_cachedAttributes[fromDirHandle] = result.FromDirCacheConsistency.After;
_cachedAttributes[toDirHandle] = result.ToDirCacheConsistency.After;
if (result.Status != Nfs3Status.Ok)
{
throw new Nfs3Exception(result.Status);
}
}
internal IEnumerable<Nfs3DirectoryEntry> ReadDirectory(Nfs3FileHandle parent, bool silentFail)
{
ulong cookie = 0;
byte[] cookieVerifier = null;
Nfs3ReadDirPlusResult result;
do
{
result = _nfsClient.ReadDirPlus(parent, cookie, cookieVerifier, _fsInfo.DirectoryPreferredBytes, _fsInfo.ReadMaxBytes);
if (result.Status == Nfs3Status.AccessDenied && silentFail)
{
break;
}
else if (result.Status != Nfs3Status.Ok)
{
throw new Nfs3Exception(result.Status);
}
foreach (var entry in result.DirEntries)
{
_cachedAttributes[entry.FileHandle] = entry.FileAttributes;
yield return entry;
cookie = entry.Cookie;
}
cookieVerifier = result.CookieVerifier;
}
while (!result.Eof);
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using ValveResourceFormat.ThirdParty;
namespace ValveResourceFormat.Serialization.VfxEval
{
public class VfxEval
{
// parsed data assigned here
public string DynamicExpressionResult { get; private set; }
// parse the input one line at a time
private readonly List<string> DynamicExpressionList = new();
// function reference, name and number of arguments
private readonly (string Name, int ArgumentCount)[] FUNCTION_REF = {
("sin", 1), // 00
("cos", 1), // 01
("tan", 1), // 02
("frac", 1), // 03
("floor", 1), // 04
("ceil", 1), // 05
("saturate", 1), // 06
("clamp", 3), // 07
("lerp", 3), // 08
("dot4", 2), // 09
("dot3", 2), // 0A
("dot2", 2), // 0B
("log", 1), // 0C
("log2", 1), // 0D
("log10", 1), // 0E
("exp", 1), // 0F
("exp2", 1), // 10
("sqrt", 1), // 11
("rsqrt", 1), // 12
("sign", 1), // 13
("abs", 1), // 14
("pow", 2), // 15
("step", 2), // 16
("smoothstep", 3), // 17
("float4", 4), // 18
("float3", 3), // 19
("float2", 2), // 1A
("time", 0), // 1B
("min", 2), // 1C
("max", 2), // 1D
("SrgbLinearToGamma",1), // 1E
("SrgbGammaToLinear",1), // 1F
("random", 2), // 20
("normalize", 1), // 21
("length", 1), // 22
("sqr", 1), // 23
("TextureSize",1), // 24
("rotation2d", 1), // 25
("rotate2d", 2), // 26
("sincos", 1), // 27
};
private enum OPCODE
{
ENDOFDATA, // 00
UNKNOWN01,
BRANCH_SEP, // 02
UNKNOWN03,
BRANCH, // 04
UNKNOWN05,
FUNC, // 06
FLOAT, // 07
ASSIGN, // 08
LOCALVAR, // 09
UNKNOWN0A,
UNKNOWN0B,
NOT, // 0C
EQUALS, // 0D
NEQUALS, // 0E
GT, // 0F
GTE, // 10
LT, // 11
LTE, // 12
ADD, // 13
SUB, // 14
MUL, // 15
DIV, // 16
MODULO, // 17
NEGATE, // 18
EXTVAR, // 19
COND, // 1A (inferred from the shader code)
UNKNOWN1B,
UNKNOWN1C,
EVAL, // 1D (inferred from the shader code)
SWIZZLE, // 1E
EXISTS, // 1F
UNKNOWN20,
UNKNOWN21,
};
private static readonly Dictionary<OPCODE, string> OpCodeToSymbol = new()
{
{ OPCODE.EQUALS, "==" },
{ OPCODE.NEQUALS, "!=" },
{ OPCODE.GT, ">" },
{ OPCODE.GTE, ">=" },
{ OPCODE.LT, "<" },
{ OPCODE.LTE, "<=" },
{ OPCODE.ADD, "+" },
{ OPCODE.SUB, "-" },
{ OPCODE.MUL, "*" },
{ OPCODE.DIV, "/" },
{ OPCODE.MODULO, "%" },
};
private const uint IFELSE_BRANCH = 0; // <cond> : <e1> ? <e2>
private const uint AND_BRANCH = 1; // <e1> && <e2> (these expressions are encoded as branches on the bytestream!)
private const uint OR_BRANCH = 2; // <e1> || <e2>
private readonly Stack<string> Expressions = new();
// check on each OPS if we are exiting a branch,
// when we do we should combine expressions on the stack
private readonly Stack<uint> OffsetAtBranchExits = new();
private readonly Dictionary<uint, string> LocalVariableNames = new();
// build a dictionary of the external variables seen, passed as 'renderAttributesUsed'
private static readonly ConcurrentDictionary<uint, string> ExternalVarsReference = new();
// The 'return' keyword in the last line of a dynamic expression is optional (it is implied where absent)
// OmitReturnStatement controls whether it is shown
private readonly bool OmitReturnStatement;
public VfxEval(byte[] binaryBlob, bool omitReturnStatement = false)
{
this.OmitReturnStatement = omitReturnStatement;
ParseExpression(binaryBlob);
}
public VfxEval(byte[] binaryBlob, string[] renderAttributesUsed, bool omitReturnStatement = false)
{
this.OmitReturnStatement = omitReturnStatement;
uint MURMUR2SEED = 0x31415926; // pi!
foreach (var externalVarName in renderAttributesUsed)
{
var murmur32 = MurmurHash2.Hash(externalVarName.ToLower(), MURMUR2SEED);
ExternalVarsReference.AddOrUpdate(murmur32, externalVarName, (k, v) => externalVarName);
}
ParseExpression(binaryBlob);
}
private void ParseExpression(byte[] binaryBlob)
{
using var dataReader = new BinaryReader(new MemoryStream(binaryBlob));
OffsetAtBranchExits.Push(0);
while (dataReader.BaseStream.Position < binaryBlob.Length)
{
ProcessOps((OPCODE)dataReader.ReadByte(), dataReader);
}
foreach (var expression in DynamicExpressionList)
{
DynamicExpressionResult += $"{expression}\n";
}
DynamicExpressionResult = DynamicExpressionResult.Trim();
}
private void ProcessOps(OPCODE op, BinaryReader dataReader)
{
// when exiting a branch, combine the conditional expressions on the stack into one
if (OffsetAtBranchExits.Peek() == dataReader.BaseStream.Position)
{
OffsetAtBranchExits.Pop();
var branchType = OffsetAtBranchExits.Pop();
switch (branchType)
{
case IFELSE_BRANCH:
if (Expressions.Count < 3)
{
throw new InvalidDataException($"Error parsing dynamic expression, insufficient expressions evaluating IFELSE_BRANCH (position: {dataReader.BaseStream.Position})");
}
{
var exp3 = Expressions.Pop();
var exp2 = Expressions.Pop();
var exp1 = Expressions.Pop();
// it's not safe to trim here
// string expConditional = $"({trimb2(exp1)} ? {trimb2(exp2)} : {trimb2(exp3)})";
var expConditional = $"({exp1} ? {exp2} : {exp3})";
Expressions.Push(expConditional);
}
break;
case AND_BRANCH:
if (Expressions.Count < 2)
{
throw new InvalidDataException($"Error parsing dynamic expression, insufficient expressions evaluating AND_BRANCH (position: {dataReader.BaseStream.Position})");
}
{
var exp2 = Expressions.Pop();
var exp1 = Expressions.Pop();
var expAndConditional = $"({exp1} && {exp2})";
Expressions.Push(expAndConditional);
}
break;
case OR_BRANCH:
if (Expressions.Count < 2)
{
throw new InvalidDataException($"Error parsing dynamic expression, insufficient expressions evaluating OR_BRANCH (position: {dataReader.BaseStream.Position})");
}
{
var exp2 = Expressions.Pop();
var exp1 = Expressions.Pop();
var expOrConditional = $"({exp1} || {exp2})";
Expressions.Push(expOrConditional);
}
break;
default:
throw new InvalidDataException($"Error parsing dynamic expression, unknown branch switch ({branchType}) (position: {dataReader.BaseStream.Position})");
}
}
if (op == OPCODE.BRANCH_SEP)
{
var branchExit = (uint)dataReader.ReadUInt16();
OffsetAtBranchExits.Push(branchExit + 1);
return;
}
// we will need the branch exit, it becomes available when we get to the branch separator
// (in the middle of the conditional structure)
if (op == OPCODE.BRANCH)
{
var pointer1 = dataReader.ReadUInt16();
var pointer2 = dataReader.ReadUInt16();
var b = dataReader.ReadBytes(5);
// for <e1>&&<e2> expressions we are looking for the pattern
// 04 12 00 0A 00 07 00 00 00 00
if (pointer1 - pointer2 == 8 && b[0] == 7 && b[1] == 0 && b[2] == 0 && b[3] == 0 && b[4] == 0)
{
OffsetAtBranchExits.Push(AND_BRANCH);
return;
}
// for <e1>||<e2> expressions we are looking for the pattern
// 04 17 00 1F 00 07 00 00 80 3F
if (pointer2 - pointer1 == 8 && b[0] == 7 && b[1] == 0 && b[2] == 0 && b[3] == 0x80 && b[4] == 0x3F)
{
OffsetAtBranchExits.Push(OR_BRANCH);
return;
}
// rewind the 5 bytes read above
dataReader.BaseStream.Position -= 5;
OffsetAtBranchExits.Push(IFELSE_BRANCH);
return;
}
if (op == OPCODE.FUNC)
{
var funcId = dataReader.ReadByte();
var funcCheckByte = dataReader.ReadByte();
if (funcId >= FUNCTION_REF.Length)
{
throw new InvalidDataException($"Error parsing dynamic expression, invalid function Id = {funcId:x} (position: {dataReader.BaseStream.Position})");
}
if (funcCheckByte != 0)
{
throw new InvalidDataException($"Error parsing dynamic expression, malformed function signature (position: {dataReader.BaseStream.Position})");
}
var (funcName, nrArguments) = FUNCTION_REF[funcId];
if (nrArguments > Expressions.Count)
{
throw new InvalidDataException($"Error parsing dynamic expression, insufficient expressions evaluatuating function {funcName} (position: {dataReader.BaseStream.Position})");
}
ApplyFunction(funcName, nrArguments);
return;
}
if (op == OPCODE.FLOAT)
{
var floatVal = dataReader.ReadSingle();
var floatLiteral = string.Format("{0:g}", floatVal);
// if a float leads with "0." remove the 0 (as how Valve likes it)
if (floatLiteral.Length > 1 && floatLiteral.Substring(0, 2) == "0.")
{
floatLiteral = floatLiteral[1..];
}
Expressions.Push(floatLiteral);
return;
}
// assignment is always to a local variable, and it terminates the line
if (op == OPCODE.ASSIGN)
{
var varId = dataReader.ReadByte();
var locVarname = GetLocalVarName(varId);
var exp = Expressions.Pop();
var assignExpression = $"{locVarname} = {Trimb(exp)};";
DynamicExpressionList.Add(assignExpression);
return;
}
if (op == OPCODE.LOCALVAR)
{
var varId = dataReader.ReadByte();
var locVarname = GetLocalVarName(varId);
Expressions.Push(locVarname);
return;
}
if (op == OPCODE.NOT)
{
var exp = Expressions.Pop();
Expressions.Push($"!{exp}");
return;
}
if (op >= OPCODE.EQUALS && op <= OPCODE.MODULO)
{
if (Expressions.Count < 2)
{
throw new InvalidDataException($"Error parsing dynamic expression, insufficient expressions for operation {op} (position: {dataReader.BaseStream.Position})");
}
var exp2 = Expressions.Pop();
var exp1 = Expressions.Pop();
Expressions.Push($"({exp1}{OpCodeToSymbol[op]}{exp2})");
return;
}
if (op == OPCODE.NEGATE)
{
var exp = Expressions.Pop();
Expressions.Push($"-{exp}");
return;
}
if (op == OPCODE.EXTVAR)
{
var varId = dataReader.ReadUInt32();
var extVarname = GetExternalVarName(varId);
Expressions.Push(extVarname);
return;
}
if (op == OPCODE.COND)
{
uint expressionId = dataReader.ReadByte();
Expressions.Push($"COND[{expressionId}]");
return;
}
if (op == OPCODE.EVAL)
{
uint intval = dataReader.ReadUInt32();
// if this reference exists in the vars-reference, then show it
string murmurString = ExternalVarsReference.GetValueOrDefault(intval, $"{intval:x08}");
Expressions.Push($"EVAL[{murmurString}]");
return;
}
if (op == OPCODE.SWIZZLE)
{
var exp = Expressions.Pop();
exp += $".{GetSwizzle(dataReader.ReadByte())}";
Expressions.Push($"{exp}");
return;
}
if (op == OPCODE.EXISTS)
{
var varId = dataReader.ReadUInt32();
var extVarname = GetExternalVarName(varId);
Expressions.Push($"exists({extVarname})");
return;
}
// parser terminates here
if (op == OPCODE.ENDOFDATA)
{
if (dataReader.PeekChar() != -1)
{
throw new InvalidDataException($"Looks like we did not read the data correctly (position: {dataReader.BaseStream.Position})");
}
var finalExp = Expressions.Pop();
finalExp = Trimb(finalExp);
if (OmitReturnStatement)
{
DynamicExpressionList.Add(finalExp);
} else
{
DynamicExpressionList.Add($"return {finalExp};");
}
return;
}
throw new InvalidDataException($"Error parsing dynamic expression, unknown opcode = 0x{(int)op:x2} (position: {dataReader.BaseStream.Position})");
}
private void ApplyFunction(string funcName, int nrArguments)
{
if (nrArguments == 0)
{
Expressions.Push($"{funcName}()");
return;
}
var exp1 = Expressions.Pop();
if (nrArguments == 1)
{
Expressions.Push($"{funcName}({Trimb(exp1)})");
return;
}
var exp2 = Expressions.Pop();
if (nrArguments == 2)
{
Expressions.Push($"{funcName}({Trimb(exp2)},{Trimb(exp1)})");
return;
}
var exp3 = Expressions.Pop();
if (nrArguments == 3)
{
// Trimming the brackets here because it's always safe to remove these from functions
// (as they always carry their own brackets)
Expressions.Push($"{funcName}({Trimb(exp3)},{Trimb(exp2)},{Trimb(exp1)})");
return;
}
var exp4 = Expressions.Pop();
if (nrArguments == 4)
{
Expressions.Push($"{funcName}({Trimb(exp4)},{Trimb(exp3)},{Trimb(exp2)},{Trimb(exp1)})");
return;
}
throw new InvalidDataException($"Error parsing dynamic expression, unexpected number of arguments ({nrArguments}) for function ${funcName}");
}
private static string GetSwizzle(byte b)
{
string[] axes = { "x", "y", "z", "w" };
var swizzle = axes[b & 3] + axes[(b >> 2) & 3] + axes[(b >> 4) & 3] + axes[(b >> 6) & 3];
var i = 3;
while (i > 0 && swizzle[i - 1] == swizzle[i])
{
i--;
}
return swizzle[0..(i + 1)];
}
// The decompiler has a tendency to accumulate brackets so we trim them in places where
// it is safe (which is just done for readability).
// The approach to removing brackets is not optimised in any way, arithmetic expressions
// will accumulate brackets and it's not trivial to know when it's safe to remove them
// For example 1+2+3+4 will decompile as ((1+2)+3)+4
private static string Trimb(string exp)
{
return exp[0] == '(' && exp[^1] == ')' ? exp[1..^1] : exp;
}
// if the variable reference is unknown return in the form UNKNOWN[e46d252d] (showing the murmur32)
private static string GetExternalVarName(uint varId)
{
ExternalVarsReference.TryGetValue(varId, out var varKnownName);
if (varKnownName != null)
{
return varKnownName;
} else
{
return $"UNKNOWN[{varId:x08}]";
}
}
// naming local variables v0,v1,v2,..
private string GetLocalVarName(uint varId)
{
LocalVariableNames.TryGetValue(varId, out var varName);
if (varName == null)
{
varName = $"v{LocalVariableNames.Count}";
LocalVariableNames.Add(varId, varName);
}
return varName;
}
}
}
| |
using System;
using System.Diagnostics;
using System.Text;
using u8 = System.Byte;
using u32 = System.UInt32;
namespace Community.CsharpSqlite
{
public partial class Sqlite3
{
/*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that are called by the parser
** in order to generate code for DELETE FROM statements.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e
**
*************************************************************************
*/
//#include "sqliteInt.h"
/*
** While a SrcList can in general represent multiple tables and subqueries
** (as in the FROM clause of a SELECT statement) in this case it contains
** the name of a single table, as one might find in an INSERT, DELETE,
** or UPDATE statement. Look up that table in the symbol table and
** return a pointer. Set an error message and return NULL if the table
** name is not found or if any other error occurs.
**
** The following fields are initialized appropriate in pSrc:
**
** pSrc->a[0].pTab Pointer to the Table object
** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
**
*/
static Table sqlite3SrcListLookup( Parse pParse, SrcList pSrc )
{
SrcList_item pItem = pSrc.a[0];
Table pTab;
Debug.Assert( pItem != null && pSrc.nSrc == 1 );
pTab = sqlite3LocateTable( pParse, 0, pItem.zName, pItem.zDatabase );
sqlite3DeleteTable( pParse.db, ref pItem.pTab );
pItem.pTab = pTab;
if ( pTab != null )
{
pTab.nRef++;
}
if ( sqlite3IndexedByLookup( pParse, pItem ) != 0 )
{
pTab = null;
}
return pTab;
}
/*
** Check to make sure the given table is writable. If it is not
** writable, generate an error message and return 1. If it is
** writable return 0;
*/
static bool sqlite3IsReadOnly( Parse pParse, Table pTab, int viewOk )
{
/* A table is not writable under the following circumstances:
**
** 1) It is a virtual table and no implementation of the xUpdate method
** has been provided, or
** 2) It is a system table (i.e. sqlite_master), this call is not
** part of a nested parse and writable_schema pragma has not
** been specified.
**
** In either case leave an error message in pParse and return non-zero.
*/
if (
( IsVirtual( pTab )
&& sqlite3GetVTable( pParse.db, pTab ).pMod.pModule.xUpdate == null )
|| ( ( pTab.tabFlags & TF_Readonly ) != 0
&& ( pParse.db.flags & SQLITE_WriteSchema ) == 0
&& pParse.nested == 0 )
)
{
sqlite3ErrorMsg( pParse, "table %s may not be modified", pTab.zName );
return true;
}
#if !SQLITE_OMIT_VIEW
if ( viewOk == 0 && pTab.pSelect != null )
{
sqlite3ErrorMsg( pParse, "cannot modify %s because it is a view", pTab.zName );
return true;
}
#endif
return false;
}
#if !SQLITE_OMIT_VIEW && !SQLITE_OMIT_TRIGGER
/*
** Evaluate a view and store its result in an ephemeral table. The
** pWhere argument is an optional WHERE clause that restricts the
** set of rows in the view that are to be added to the ephemeral table.
*/
static void sqlite3MaterializeView(
Parse pParse, /* Parsing context */
Table pView, /* View definition */
Expr pWhere, /* Optional WHERE clause to be added */
int iCur /* VdbeCursor number for ephemerial table */
)
{
SelectDest dest = new SelectDest();
Select pDup;
sqlite3 db = pParse.db;
pDup = sqlite3SelectDup( db, pView.pSelect, 0 );
if ( pWhere != null )
{
SrcList pFrom;
pWhere = sqlite3ExprDup( db, pWhere, 0 );
pFrom = sqlite3SrcListAppend( db, null, null, null );
//if ( pFrom != null )
//{
Debug.Assert( pFrom.nSrc == 1 );
pFrom.a[0].zAlias = pView.zName;// sqlite3DbStrDup( db, pView.zName );
pFrom.a[0].pSelect = pDup;
Debug.Assert( pFrom.a[0].pOn == null );
Debug.Assert( pFrom.a[0].pUsing == null );
//}
//else
//{
// sqlite3SelectDelete( db, ref pDup );
//}
pDup = sqlite3SelectNew( pParse, null, pFrom, pWhere, null, null, null, 0, null, null );
}
sqlite3SelectDestInit( dest, SRT_EphemTab, iCur );
sqlite3Select( pParse, pDup, ref dest );
sqlite3SelectDelete( db, ref pDup );
}
#endif //* !SQLITE_OMIT_VIEW) && !SQLITE_OMIT_TRIGGER) */
#if (SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !(SQLITE_OMIT_SUBQUERY)
/*
** Generate an expression tree to implement the WHERE, ORDER BY,
** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
**
** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
** \__________________________/
** pLimitWhere (pInClause)
*/
Expr sqlite3LimitWhere(
Parse pParse, /* The parser context */
SrcList pSrc, /* the FROM clause -- which tables to scan */
Expr pWhere, /* The WHERE clause. May be null */
ExprList pOrderBy, /* The ORDER BY clause. May be null */
Expr pLimit, /* The LIMIT clause. May be null */
Expr pOffset, /* The OFFSET clause. May be null */
char zStmtType /* Either DELETE or UPDATE. For error messages. */
){
Expr pWhereRowid = null; /* WHERE rowid .. */
Expr pInClause = null; /* WHERE rowid IN ( select ) */
Expr pSelectRowid = null; /* SELECT rowid ... */
ExprList pEList = null; /* Expression list contaning only pSelectRowid */
SrcList pSelectSrc = null; /* SELECT rowid FROM x ... (dup of pSrc) */
Select pSelect = null; /* Complete SELECT tree */
/* Check that there isn't an ORDER BY without a LIMIT clause.
*/
if( pOrderBy!=null && (pLimit == null) ) {
sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
pParse.parseError = 1;
goto limit_where_cleanup_2;
}
/* We only need to generate a select expression if there
** is a limit/offset term to enforce.
*/
if ( pLimit == null )
{
/* if pLimit is null, pOffset will always be null as well. */
Debug.Assert( pOffset == null );
return pWhere;
}
/* Generate a select expression tree to enforce the limit/offset
** term for the DELETE or UPDATE statement. For example:
** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
** becomes:
** DELETE FROM table_a WHERE rowid IN (
** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
** );
*/
pSelectRowid = sqlite3PExpr( pParse, TK_ROW, null, null, null );
if( pSelectRowid == null ) goto limit_where_cleanup_2;
pEList = sqlite3ExprListAppend( pParse, null, pSelectRowid);
if( pEList == null ) goto limit_where_cleanup_2;
/* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
** and the SELECT subtree. */
pSelectSrc = sqlite3SrcListDup(pParse.db, pSrc,0);
if( pSelectSrc == null ) {
sqlite3ExprListDelete(pParse.db, pEList);
goto limit_where_cleanup_2;
}
/* generate the SELECT expression tree. */
pSelect = sqlite3SelectNew( pParse, pEList, pSelectSrc, pWhere, null, null,
pOrderBy, 0, pLimit, pOffset );
if( pSelect == null ) return null;
/* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
pWhereRowid = sqlite3PExpr( pParse, TK_ROW, null, null, null );
if( pWhereRowid == null ) goto limit_where_cleanup_1;
pInClause = sqlite3PExpr( pParse, TK_IN, pWhereRowid, null, null );
if( pInClause == null ) goto limit_where_cleanup_1;
pInClause->x.pSelect = pSelect;
pInClause->flags |= EP_xIsSelect;
sqlite3ExprSetHeight(pParse, pInClause);
return pInClause;
/* something went wrong. clean up anything allocated. */
limit_where_cleanup_1:
sqlite3SelectDelete(pParse.db, pSelect);
return null;
limit_where_cleanup_2:
sqlite3ExprDelete(pParse.db, ref pWhere);
sqlite3ExprListDelete(pParse.db, pOrderBy);
sqlite3ExprDelete(pParse.db, ref pLimit);
sqlite3ExprDelete(pParse.db, ref pOffset);
return null;
}
#endif //* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
/*
** Generate code for a DELETE FROM statement.
**
** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
** \________/ \________________/
** pTabList pWhere
*/
static void sqlite3DeleteFrom(
Parse pParse, /* The parser context */
SrcList pTabList, /* The table from which we should delete things */
Expr pWhere /* The WHERE clause. May be null */
)
{
Vdbe v; /* The virtual database engine */
Table pTab; /* The table from which records will be deleted */
string zDb; /* Name of database holding pTab */
int end, addr = 0; /* A couple addresses of generated code */
int i; /* Loop counter */
WhereInfo pWInfo; /* Information about the WHERE clause */
Index pIdx; /* For looping over indices of the table */
int iCur; /* VDBE VdbeCursor number for pTab */
sqlite3 db; /* Main database structure */
AuthContext sContext; /* Authorization context */
NameContext sNC; /* Name context to resolve expressions in */
int iDb; /* Database number */
int memCnt = -1; /* Memory cell used for change counting */
int rcauth; /* Value returned by authorization callback */
#if !SQLITE_OMIT_TRIGGER
bool isView; /* True if attempting to delete from a view */
Trigger pTrigger; /* List of table triggers, if required */
#endif
sContext = new AuthContext();//memset(&sContext, 0, sizeof(sContext));
db = pParse.db;
if ( pParse.nErr != 0 /*|| db.mallocFailed != 0 */ )
{
goto delete_from_cleanup;
}
Debug.Assert( pTabList.nSrc == 1 );
/* Locate the table which we want to delete. This table has to be
** put in an SrcList structure because some of the subroutines we
** will be calling are designed to work with multiple tables and expect
** an SrcList* parameter instead of just a Table* parameter.
*/
pTab = sqlite3SrcListLookup( pParse, pTabList );
if ( pTab == null )
goto delete_from_cleanup;
/* Figure out if we have any triggers and if the table being
** deleted from is a view
*/
#if !SQLITE_OMIT_TRIGGER
int iDummy = 0;
pTrigger = sqlite3TriggersExist( pParse, pTab, TK_DELETE, null, ref iDummy );
isView = pTab.pSelect != null;
#else
const Trigger pTrigger = null;
bool isView = false;
#endif
#if SQLITE_OMIT_VIEW
//# undef isView
isView = false;
#endif
/* If pTab is really a view, make sure it has been initialized.
*/
if ( sqlite3ViewGetColumnNames( pParse, pTab ) != 0 )
{
goto delete_from_cleanup;
}
if ( sqlite3IsReadOnly( pParse, pTab, ( pTrigger != null ? 1 : 0 ) ) )
{
goto delete_from_cleanup;
}
iDb = sqlite3SchemaToIndex( db, pTab.pSchema );
Debug.Assert( iDb < db.nDb );
zDb = db.aDb[iDb].zName;
#if !SQLITE_OMIT_AUTHORIZATION
rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
#else
rcauth = SQLITE_OK;
#endif
Debug.Assert( rcauth == SQLITE_OK || rcauth == SQLITE_DENY || rcauth == SQLITE_IGNORE );
if ( rcauth == SQLITE_DENY )
{
goto delete_from_cleanup;
}
Debug.Assert( !isView || pTrigger != null );
/* Assign cursor number to the table and all its indices.
*/
Debug.Assert( pTabList.nSrc == 1 );
iCur = pTabList.a[0].iCursor = pParse.nTab++;
for ( pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext )
{
pParse.nTab++;
}
#if !SQLITE_OMIT_AUTHORIZATION
/* Start the view context
*/
if( isView ){
sqlite3AuthContextPush(pParse, sContext, pTab.zName);
}
#endif
/* Begin generating code.
*/
v = sqlite3GetVdbe( pParse );
if ( v == null )
{
goto delete_from_cleanup;
}
if ( pParse.nested == 0 )
sqlite3VdbeCountChanges( v );
sqlite3BeginWriteOperation( pParse, 1, iDb );
/* If we are trying to delete from a view, realize that view into
** a ephemeral table.
*/
#if !(SQLITE_OMIT_VIEW) && !(SQLITE_OMIT_TRIGGER)
if ( isView )
{
sqlite3MaterializeView( pParse, pTab, pWhere, iCur );
}
#endif
/* Resolve the column names in the WHERE clause.
*/
sNC = new NameContext();// memset( &sNC, 0, sizeof( sNC ) );
sNC.pParse = pParse;
sNC.pSrcList = pTabList;
if ( sqlite3ResolveExprNames( sNC, ref pWhere ) != 0 )
{
goto delete_from_cleanup;
}
/* Initialize the counter of the number of rows deleted, if
** we are counting rows.
*/
if ( ( db.flags & SQLITE_CountRows ) != 0 )
{
memCnt = ++pParse.nMem;
sqlite3VdbeAddOp2( v, OP_Integer, 0, memCnt );
}
#if !SQLITE_OMIT_TRUNCATE_OPTIMIZATION
/* Special case: A DELETE without a WHERE clause deletes everything.
** It is easier just to erase the whole table. Prior to version 3.6.5,
** this optimization caused the row change count (the value returned by
** API function sqlite3_count_changes) to be set incorrectly. */
if ( rcauth == SQLITE_OK && pWhere == null && null == pTrigger && !IsVirtual( pTab )
&& 0 == sqlite3FkRequired( pParse, pTab, null, 0 )
)
{
Debug.Assert( !isView );
sqlite3VdbeAddOp4( v, OP_Clear, pTab.tnum, iDb, memCnt,
pTab.zName, P4_STATIC );
for ( pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext )
{
Debug.Assert( pIdx.pSchema == pTab.pSchema );
sqlite3VdbeAddOp2( v, OP_Clear, pIdx.tnum, iDb );
}
}
else
#endif //* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
/* The usual case: There is a WHERE clause so we have to scan through
** the table and pick which records to delete.
*/
{
int iRowSet = ++pParse.nMem; /* Register for rowset of rows to delete */
int iRowid = ++pParse.nMem; /* Used for storing rowid values. */
int regRowid; /* Actual register containing rowids */
/* Collect rowids of every row to be deleted.
*/
sqlite3VdbeAddOp2( v, OP_Null, 0, iRowSet );
ExprList elDummy = null;
pWInfo = sqlite3WhereBegin( pParse, pTabList, pWhere, ref elDummy, WHERE_DUPLICATES_OK );
if ( pWInfo == null )
goto delete_from_cleanup;
regRowid = sqlite3ExprCodeGetColumn( pParse, pTab, -1, iCur, iRowid );
sqlite3VdbeAddOp2( v, OP_RowSetAdd, iRowSet, regRowid );
if ( ( db.flags & SQLITE_CountRows ) != 0 )
{
sqlite3VdbeAddOp2( v, OP_AddImm, memCnt, 1 );
}
sqlite3WhereEnd( pWInfo );
/* Delete every item whose key was written to the list during the
** database scan. We have to delete items after the scan is complete
** because deleting an item can change the scan order. */
end = sqlite3VdbeMakeLabel( v );
/* Unless this is a view, open cursors for the table we are
** deleting from and all its indices. If this is a view, then the
** only effect this statement has is to fire the INSTEAD OF
** triggers. */
if ( !isView )
{
sqlite3OpenTableAndIndices( pParse, pTab, iCur, OP_OpenWrite );
}
addr = sqlite3VdbeAddOp3( v, OP_RowSetRead, iRowSet, end, iRowid );
/* Delete the row */
#if !SQLITE_OMIT_VIRTUALTABLE
if( IsVirtual(pTab) ){
const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
sqlite3VtabMakeWritable(pParse, pTab);
sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
sqlite3MayAbort(pParse);
}else
#endif
{
int count = ( pParse.nested == 0 ) ? 1 : 0; /* True to count changes */
sqlite3GenerateRowDelete( pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default );
}
/* End of the delete loop */
sqlite3VdbeAddOp2( v, OP_Goto, 0, addr );
sqlite3VdbeResolveLabel( v, end );
/* Close the cursors open on the table and its indexes. */
if ( !isView && !IsVirtual( pTab ) )
{
for ( i = 1, pIdx = pTab.pIndex; pIdx != null; i++, pIdx = pIdx.pNext )
{
sqlite3VdbeAddOp2( v, OP_Close, iCur + i, pIdx.tnum );
}
sqlite3VdbeAddOp1( v, OP_Close, iCur );
}
}
/* Update the sqlite_sequence table by storing the content of the
** maximum rowid counter values recorded while inserting into
** autoincrement tables.
*/
if ( pParse.nested == 0 && pParse.pTriggerTab == null )
{
sqlite3AutoincrementEnd( pParse );
}
/* Return the number of rows that were deleted. If this routine is
** generating code because of a call to sqlite3NestedParse(), do not
** invoke the callback function.
*/
if ( ( db.flags & SQLITE_CountRows ) != 0 && 0 == pParse.nested && null == pParse.pTriggerTab )
{
sqlite3VdbeAddOp2( v, OP_ResultRow, memCnt, 1 );
sqlite3VdbeSetNumCols( v, 1 );
sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC );
}
delete_from_cleanup:
#if !SQLITE_OMIT_AUTHORIZATION
sqlite3AuthContextPop(sContext);
#endif
sqlite3SrcListDelete( db, ref pTabList );
sqlite3ExprDelete( db, ref pWhere );
return;
}
/* Make sure "isView" and other macros defined above are undefined. Otherwise
** thely may interfere with compilation of other functions in this file
** (or in another file, if this file becomes part of the amalgamation). */
//#ifdef isView
// #undef isView
//#endif
//#ifdef pTrigger
// #undef pTrigger
//#endif
/*
** This routine generates VDBE code that causes a single row of a
** single table to be deleted.
**
** The VDBE must be in a particular state when this routine is called.
** These are the requirements:
**
** 1. A read/write cursor pointing to pTab, the table containing the row
** to be deleted, must be opened as cursor number $iCur.
**
** 2. Read/write cursors for all indices of pTab must be open as
** cursor number base+i for the i-th index.
**
** 3. The record number of the row to be deleted must be stored in
** memory cell iRowid.
**
** This routine generates code to remove both the table record and all
** index entries that point to that record.
*/
static void sqlite3GenerateRowDelete(
Parse pParse, /* Parsing context */
Table pTab, /* Table containing the row to be deleted */
int iCur, /* VdbeCursor number for the table */
int iRowid, /* Memory cell that contains the rowid to delete */
int count, /* If non-zero, increment the row change counter */
Trigger pTrigger, /* List of triggers to (potentially) fire */
int onconf /* Default ON CONFLICT policy for triggers */
)
{
Vdbe v = pParse.pVdbe; /* Vdbe */
int iOld = 0; /* First register in OLD.* array */
int iLabel; /* Label resolved to end of generated code */
/* Vdbe is guaranteed to have been allocated by this stage. */
Debug.Assert( v != null );
/* Seek cursor iCur to the row to delete. If this row no longer exists
** (this can happen if a trigger program has already deleted it), do
** not attempt to delete it or fire any DELETE triggers. */
iLabel = sqlite3VdbeMakeLabel( v );
sqlite3VdbeAddOp3( v, OP_NotExists, iCur, iLabel, iRowid );
/* If there are any triggers to fire, allocate a range of registers to
** use for the old.* references in the triggers. */
if ( sqlite3FkRequired( pParse, pTab, null, 0 ) != 0 || pTrigger != null )
{
u32 mask; /* Mask of OLD.* columns in use */
int iCol; /* Iterator used while populating OLD.* */
/* TODO: Could use temporary registers here. Also could attempt to
** avoid copying the contents of the rowid register. */
mask = sqlite3TriggerColmask(
pParse, pTrigger, null, 0, TRIGGER_BEFORE | TRIGGER_AFTER, pTab, onconf
);
mask |= sqlite3FkOldmask( pParse, pTab );
iOld = pParse.nMem + 1;
pParse.nMem += ( 1 + pTab.nCol );
/* Populate the OLD.* pseudo-table register array. These values will be
** used by any BEFORE and AFTER triggers that exist. */
sqlite3VdbeAddOp2( v, OP_Copy, iRowid, iOld );
for ( iCol = 0; iCol < pTab.nCol; iCol++ )
{
if ( mask == 0xffffffff || ( mask & ( 1 << iCol ) ) != 0 )
{
sqlite3ExprCodeGetColumnOfTable( v, pTab, iCur, iCol, iOld + iCol + 1 );
}
}
/* Invoke BEFORE DELETE trigger programs. */
sqlite3CodeRowTrigger( pParse, pTrigger,
TK_DELETE, null, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
);
/* Seek the cursor to the row to be deleted again. It may be that
** the BEFORE triggers coded above have already removed the row
** being deleted. Do not attempt to delete the row a second time, and
** do not fire AFTER triggers. */
sqlite3VdbeAddOp3( v, OP_NotExists, iCur, iLabel, iRowid );
/* Do FK processing. This call checks that any FK constraints that
** refer to this table (i.e. constraints attached to other tables)
** are not violated by deleting this row. */
sqlite3FkCheck( pParse, pTab, iOld, 0 );
}
/* Delete the index and table entries. Skip this step if pTab is really
** a view (in which case the only effect of the DELETE statement is to
** fire the INSTEAD OF triggers). */
if ( pTab.pSelect == null )
{
sqlite3GenerateRowIndexDelete( pParse, pTab, iCur, 0 );
sqlite3VdbeAddOp2( v, OP_Delete, iCur, ( count != 0 ? (int)OPFLAG_NCHANGE : 0 ) );
if ( count != 0 )
{
sqlite3VdbeChangeP4( v, -1, pTab.zName, P4_TRANSIENT );
}
}
/* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
** handle rows (possibly in other tables) that refer via a foreign key
** to the row just deleted. */
sqlite3FkActions( pParse, pTab, null, iOld );
/* Invoke AFTER DELETE trigger programs. */
sqlite3CodeRowTrigger( pParse, pTrigger,
TK_DELETE, null, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
);
/* Jump here if the row had already been deleted before any BEFORE
** trigger programs were invoked. Or if a trigger program throws a
** RAISE(IGNORE) exception. */
sqlite3VdbeResolveLabel( v, iLabel );
}
/*
** This routine generates VDBE code that causes the deletion of all
** index entries associated with a single row of a single table.
**
** The VDBE must be in a particular state when this routine is called.
** These are the requirements:
**
** 1. A read/write cursor pointing to pTab, the table containing the row
** to be deleted, must be opened as cursor number "iCur".
**
** 2. Read/write cursors for all indices of pTab must be open as
** cursor number iCur+i for the i-th index.
**
** 3. The "iCur" cursor must be pointing to the row that is to be
** deleted.
*/
static void sqlite3GenerateRowIndexDelete(
Parse pParse, /* Parsing and code generating context */
Table pTab, /* Table containing the row to be deleted */
int iCur, /* VdbeCursor number for the table */
int nothing /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
)
{
int[] aRegIdx = null;
sqlite3GenerateRowIndexDelete( pParse, pTab, iCur, aRegIdx );
}
static void sqlite3GenerateRowIndexDelete(
Parse pParse, /* Parsing and code generating context */
Table pTab, /* Table containing the row to be deleted */
int iCur, /* VdbeCursor number for the table */
int[] aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
)
{
int i;
Index pIdx;
int r1;
for ( i = 1, pIdx = pTab.pIndex; pIdx != null; i++, pIdx = pIdx.pNext )
{
if ( aRegIdx != null && aRegIdx[i - 1] == 0 )
continue;
r1 = sqlite3GenerateIndexKey( pParse, pIdx, iCur, 0, false );
sqlite3VdbeAddOp3( pParse.pVdbe, OP_IdxDelete, iCur + i, r1, pIdx.nColumn + 1 );
}
}
/*
** Generate code that will assemble an index key and put it in register
** regOut. The key with be for index pIdx which is an index on pTab.
** iCur is the index of a cursor open on the pTab table and pointing to
** the entry that needs indexing.
**
** Return a register number which is the first in a block of
** registers that holds the elements of the index key. The
** block of registers has already been deallocated by the time
** this routine returns.
*/
static int sqlite3GenerateIndexKey(
Parse pParse, /* Parsing context */
Index pIdx, /* The index for which to generate a key */
int iCur, /* VdbeCursor number for the pIdx.pTable table */
int regOut, /* Write the new index key to this register */
bool doMakeRec /* Run the OP_MakeRecord instruction if true */
)
{
Vdbe v = pParse.pVdbe;
int j;
Table pTab = pIdx.pTable;
int regBase;
int nCol;
nCol = pIdx.nColumn;
regBase = sqlite3GetTempRange( pParse, nCol + 1 );
sqlite3VdbeAddOp2( v, OP_Rowid, iCur, regBase + nCol );
for ( j = 0; j < nCol; j++ )
{
int idx = pIdx.aiColumn[j];
if ( idx == pTab.iPKey )
{
sqlite3VdbeAddOp2( v, OP_SCopy, regBase + nCol, regBase + j );
}
else
{
sqlite3VdbeAddOp3( v, OP_Column, iCur, idx, regBase + j );
sqlite3ColumnDefault( v, pTab, idx, -1 );
}
}
if ( doMakeRec )
{
sqlite3VdbeAddOp3( v, OP_MakeRecord, regBase, nCol + 1, regOut );
sqlite3VdbeChangeP4( v, -1, sqlite3IndexAffinityStr( v, pIdx ), P4_TRANSIENT );
}
sqlite3ReleaseTempRange( pParse, regBase, nCol + 1 );
return regBase;
}
}
}
| |
namespace gView.Framework.SpatialAlgorithms
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
using gView.Framework.Geometry;
internal enum ClipOperation
{
Difference = 0,
Intersection = 1,
XOr = 2,
Union = 3
}
internal enum BufferOperation
{
Buffer_POINTS=0,
Buffer_LINES =1
}
internal struct GeomVertex
{
public double X;
public double Y;
public GeomVertex( double x, double y )
{
X = x;
Y = y;
}
public override string ToString()
{
return "(" + X.ToString() + "," + Y.ToString() + ")";
}
}
internal class GeomVertexList
{
public int NofVertices;
public GeomVertex[] Vertex;
public GeomVertexList()
{
}
public GeomVertexList( PointF[] p )
{
NofVertices = p.Length;
Vertex = new GeomVertex[NofVertices];
for ( int i=0 ; i<p.Length ; i++ )
Vertex[i] = new GeomVertex( (double)p[i].X, (double)p[i].Y );
}
public GeomVertexList(IPointCollection pColl)
{
pColl = Algorithm.RemoveDoubles(pColl);
if (Algorithm.IsSelfIntersecting(pColl))
return;
NofVertices = pColl.PointCount;
if (NofVertices > 1)
{
if (pColl[0].X != pColl[NofVertices - 1].X ||
pColl[0].Y != pColl[NofVertices - 1].Y)
{
NofVertices++;
}
}
Vertex = new GeomVertex[NofVertices];
for (int i = 0; i < pColl.PointCount; i++)
Vertex[i] = new GeomVertex(pColl[i].X, pColl[i].Y);
if (NofVertices == pColl.PointCount + 1)
{
Vertex[NofVertices-1] = new GeomVertex(pColl[0].X, pColl[0].Y);
}
}
public GraphicsPath ToGraphicsPath()
{
GraphicsPath graphicsPath = new GraphicsPath();
graphicsPath.AddLines( ToPoints() );
return graphicsPath;
}
public IRing ToRing()
{
Ring ring = new Ring();
for (int i = 0; i < NofVertices; i++)
ring.AddPoint(new gView.Framework.Geometry.Point(Vertex[i].X, Vertex[i].Y));
return ring;
}
public PointF[] ToPoints()
{
PointF[] vertexArray = new PointF[NofVertices];
for ( int i=0 ; i<NofVertices ; i++ ) {
vertexArray[i] = new PointF( (float)Vertex[i].X, (float)Vertex[i].Y );
}
return vertexArray;
}
public GraphicsPath TristripToGraphicsPath()
{
GraphicsPath graphicsPath = new GraphicsPath();
for ( int i=0 ; i<NofVertices-2 ; i++ ) {
graphicsPath.AddPolygon( new PointF[3]{ new PointF( (float)Vertex[i].X, (float)Vertex[i].Y ),
new PointF( (float)Vertex[i+1].X, (float)Vertex[i+1].Y ),
new PointF( (float)Vertex[i+2].X, (float)Vertex[i+2].Y ) } );
}
return graphicsPath;
}
public void TristripToPolyons(ref List<IPolygon> polygons)
{
if (polygons == null) return;
for (int i = 0; i < NofVertices - 2; i++)
{
Polygon poly = new Polygon();
Ring ring = new Ring();
ring.AddPoint(new gView.Framework.Geometry.Point(
Vertex[i].X, Vertex[i].Y));
ring.AddPoint(new gView.Framework.Geometry.Point(
Vertex[i + 1].X, Vertex[i + 1].Y));
ring.AddPoint(new gView.Framework.Geometry.Point(
Vertex[i + 2].X, Vertex[i + 2].Y));
poly.AddRing(ring);
polygons.Add(poly);
}
}
public void TripstripToTriangles(ref List<GeomTriangle> triangles)
{
if (triangles == null) return;
for (int i = 0; i < NofVertices - 2; i++)
{
triangles.Add(
new GeomTriangle(
Vertex[i].X, Vertex[i].Y,
Vertex[i + 1].X, Vertex[i + 1].Y,
Vertex[i + 2].X, Vertex[i + 2].Y));
}
}
public PointF CenterOfLargestTriangel
{
get
{
int pos = -1;
for (int i = 0; i < NofVertices - 2; i++)
{
pos = 0;
break;
}
if (pos != -1)
{
double x = (Vertex[pos].X + Vertex[pos + 1].X + Vertex[pos + 2].X) / 3;
double y = (Vertex[pos].Y + Vertex[pos + 1].Y + Vertex[pos + 2].Y) / 3;
return new PointF((float)x, (float)y);
}
return new PointF(0, 0);
}
}
public override string ToString()
{
string s = "Polygon with " + NofVertices + " vertices: ";
for ( int i=0 ; i<NofVertices ; i++ ) {
s += Vertex[i].ToString();
if ( i!=NofVertices-1 )
s += ",";
}
return s;
}
}
internal class GeomPolygon
{
public int NofContours;
public bool[] ContourIsHole;
public GeomVertexList[] Contour;
public GeomPolygon()
{
}
// path should contain only polylines ( use Flatten )
// furthermore the constructor assumes that all Subpathes of path except the first one are holes
public GeomPolygon(GraphicsPath path)
{
NofContours = 0;
foreach (byte b in path.PathTypes)
{
if ((b & ((byte)PathPointType.CloseSubpath)) != 0)
NofContours++;
}
ContourIsHole = new bool[NofContours];
Contour = new GeomVertexList[NofContours];
for (int i = 0; i < NofContours; i++)
ContourIsHole[i] = (i == 0);
int contourNr = 0;
ArrayList contour = new ArrayList();
for (int i = 0; i < path.PathPoints.Length; i++)
{
contour.Add(path.PathPoints[i]);
if ((path.PathTypes[i] & ((byte)PathPointType.CloseSubpath)) != 0)
{
PointF[] pointArray = (PointF[])contour.ToArray(typeof(PointF));
GeomVertexList vl = new GeomVertexList(pointArray);
Contour[contourNr++] = vl;
contour.Clear();
}
}
}
public GeomPolygon(IPolygon polygon, double generalizationDistance = 0)
{
if (polygon == null || polygon.RingCount == 0) return;
NofContours = polygon.RingCount;
ContourIsHole = new bool[NofContours];
Contour = new GeomVertexList[NofContours];
for (int i = 0; i < NofContours; i++)
ContourIsHole[i] = (i != 0);
for (int i = 0; i < polygon.RingCount; i++)
{
Contour[i] = new GeomVertexList(polygon[i]);
}
}
public GeomPolygon(IEnvelope envelope)
{
Polygon polygon = new Polygon();
Ring ring = new Ring();
ring.AddPoint(new gView.Framework.Geometry.Point(envelope.minx, envelope.miny));
ring.AddPoint(new gView.Framework.Geometry.Point(envelope.minx, envelope.maxy));
ring.AddPoint(new gView.Framework.Geometry.Point(envelope.maxx, envelope.maxy));
ring.AddPoint(new gView.Framework.Geometry.Point(envelope.maxx, envelope.miny));
ring.AddPoint(new gView.Framework.Geometry.Point(envelope.minx, envelope.miny));
polygon.AddRing(ring);
NofContours = polygon.RingCount;
ContourIsHole = new bool[NofContours];
Contour = new GeomVertexList[NofContours];
for (int i = 0; i < NofContours; i++)
ContourIsHole[i] = (i != 0);
for (int i = 0; i < polygon.RingCount; i++)
{
Contour[i] = new GeomVertexList(polygon[i]);
}
}
/*
public GeomPolygon(IPolygon poly)
{
}
* */
/*
public static GeomPolygon FromFile( string filename, bool readHoleFlags )
{
return ClipWrapper.ReadPolygon( filename, readHoleFlags );
}
*/
public void AddContour(GeomVertexList contour, bool contourIsHole)
{
bool[] hole = new bool[NofContours+1];
GeomVertexList[] cont = new GeomVertexList[NofContours+1];
for ( int i=0 ; i<NofContours ; i++ ) {
hole[i] = ContourIsHole[i];
cont[i] = Contour[i];
}
hole[NofContours] = contourIsHole;
cont[NofContours++] = contour;
ContourIsHole = hole;
Contour = cont;
}
public GraphicsPath ToGraphicsPath()
{
GraphicsPath path = new GraphicsPath();
for ( int i=0 ; i<NofContours ; i++ ) {
PointF[] points = Contour[i].ToPoints();
if ( ContourIsHole[i] )
Array.Reverse( points );
path.AddPolygon( points );
}
return path;
}
public IPolygon ToPolygon()
{
Polygon polygon = new Polygon();
for (int i = 0; i < NofContours; i++)
{
polygon.AddRing(Contour[i].ToRing());
}
return polygon;
}
public override string ToString()
{
string s = "Polygon with " + NofContours.ToString() + " contours." + "\r\n";
for ( int i=0 ; i<NofContours ; i++ ) {
if ( ContourIsHole[i] )
s += "Hole: ";
else
s += "Contour: ";
s += Contour[i].ToString();
}
return s;
}
public GeomTristrip ClipToTristrip( ClipOperation operation, GeomPolygon polygon )
{
return ClipWrapper.ClipToTristrip( operation, this, polygon );
}
public GeomPolygon Clip( ClipOperation operation, GeomPolygon polygon )
{
return ClipWrapper.Clip( operation, this, polygon );
}
public GeomTristrip ToTristrip()
{
return ClipWrapper.GeomPolygonToTristrip( this );
}
/*
public void Save( string filename, bool writeHoleFlags )
{
ClipWrapper.SavePolygon( filename, writeHoleFlags, this );
}
* */
}
internal class GeomTristrip
{
public int NofStrips;
public GeomVertexList[] Strip;
}
internal class ClipWrapper
{
public static GeomTristrip GeomPolygonToTristrip( GeomPolygon polygon )
{
Clip_tristrip Clip_strip = new Clip_tristrip();
Clip_polygon Clip_pol = ClipWrapper.GeomPolygonTo_Clip_polygon( polygon );
try
{
Polygon2Tristrip(ref Clip_pol, ref Clip_strip);
GeomTristrip tristrip = ClipWrapper.Clip_strip_ToTristrip(Clip_strip);
return tristrip;
}
finally
{
ClipWrapper.Free_Clip_polygon(Clip_pol);
ClipWrapper.FreeTristrip(ref Clip_strip);
}
}
public static GeomTristrip PolygonToTristip(IPolygon polygon)
{
Clip_tristrip clip_strip = new Clip_tristrip();
Clip_polygon clip_pol = ClipWrapper.PolygonTo_Clip_polygon(polygon);
try
{
Polygon2Tristrip(ref clip_pol, ref clip_strip);
GeomTristrip tristrip = ClipWrapper.Clip_strip_ToTristrip(clip_strip);
return tristrip;
}
finally
{
ClipWrapper.Free_Clip_polygon(clip_pol);
ClipWrapper.FreeTristrip(ref clip_strip);
}
}
public static GeomTristrip ClipToTristrip( ClipOperation operation, GeomPolygon subject_polygon, GeomPolygon clip_polygon )
{
Clip_tristrip Clip_strip = new Clip_tristrip();
Clip_polygon Clip_subject_polygon = ClipWrapper.GeomPolygonTo_Clip_polygon( subject_polygon );
Clip_polygon Clip_clip_polygon = ClipWrapper.GeomPolygonTo_Clip_polygon( clip_polygon );
try
{
ClipTristrip(ref Clip_subject_polygon, ref Clip_clip_polygon, operation, ref Clip_strip);
GeomTristrip tristrip = ClipWrapper.Clip_strip_ToTristrip(Clip_strip);
return tristrip;
}
finally
{
ClipWrapper.Free_Clip_polygon(Clip_subject_polygon);
ClipWrapper.Free_Clip_polygon(Clip_clip_polygon);
ClipWrapper.FreeTristrip(ref Clip_strip);
}
}
public static GeomPolygon Clip( ClipOperation operation, GeomPolygon subject_polygon, GeomPolygon clip_polygon )
{
Clip_polygon Clip_polygon = new Clip_polygon();
Clip_polygon Clip_subject_polygon = ClipWrapper.GeomPolygonTo_Clip_polygon( subject_polygon );
Clip_polygon Clip_clip_polygon = ClipWrapper.GeomPolygonTo_Clip_polygon( clip_polygon );
try
{
ClipPolygon(ref Clip_subject_polygon, ref Clip_clip_polygon, operation, ref Clip_polygon);
GeomPolygon polygon = ClipWrapper.Clip_polygon_ToGeomPolygon(Clip_polygon);
return polygon;
}
finally
{
ClipWrapper.Free_Clip_polygon(Clip_subject_polygon);
ClipWrapper.Free_Clip_polygon(Clip_clip_polygon);
ClipWrapper.FreePolygon(ref Clip_polygon);
}
}
public static IPolygon Clip(ClipOperation operation, IPolygon subject_polygon, IPolygon clip_polygon)
{
Clip_polygon Clip_polygon = new Clip_polygon();
Clip_polygon Clip_subject_polygon = ClipWrapper.PolygonTo_Clip_polygon(subject_polygon);
Clip_polygon Clip_clip_polygon = ClipWrapper.PolygonTo_Clip_polygon(clip_polygon);
try
{
ClipPolygon(ref Clip_subject_polygon, ref Clip_clip_polygon, operation, ref Clip_polygon);
IPolygon polygon = ClipWrapper.Clip_polygon_ToPolygon(Clip_polygon);
return polygon;
}
finally
{
ClipWrapper.Free_Clip_polygon(Clip_subject_polygon);
ClipWrapper.Free_Clip_polygon(Clip_clip_polygon);
ClipWrapper.FreePolygon(ref Clip_polygon);
}
}
public static IPolygon Union(List<IPolygon> polygons)
{
if (polygons.Count == 0) return null;
if (polygons.Count == 1) return polygons[0];
/*
if (polygons.Count > 100)
{
return polygons[0];
}
*/
Clip_polygon union_polygon = new Clip_polygon();
Clip_polygon polygon1 = ClipWrapper.PolygonTo_Clip_polygon(polygons[0]);
try
{
for (int i = 1; i < polygons.Count; i++)
{
union_polygon = new Clip_polygon();
Clip_polygon polygon2 = ClipWrapper.PolygonTo_Clip_polygon(polygons[i]);
ClipPolygon(ref polygon1, ref polygon2, ClipOperation.Union, ref union_polygon);
if (i == 1)
ClipWrapper.Free_Clip_polygon(polygon1);
else
ClipWrapper.FreePolygon(ref polygon1);
ClipWrapper.Free_Clip_polygon(polygon2);
polygon1 = union_polygon;
}
IPolygon polygon = ClipWrapper.Clip_polygon_ToPolygon(union_polygon);
return polygon;
}
finally
{
ClipWrapper.FreePolygon(ref union_polygon);
}
}
public static IPolygon BufferPath(IPath path, double distance)
{
Clip_vertex_list vtx_lst = PathTo_Clip_vertex_list(path);
Clip_polygon buffer_polygon = new Clip_polygon();
try
{
BufferVertextList(ref vtx_lst, distance, BufferOperation.Buffer_LINES, ref buffer_polygon);
IPolygon polygon = ClipWrapper.Clip_polygon_ToPolygon(buffer_polygon);
return polygon;
}
finally
{
ClipWrapper.Free_Clip_polygon(buffer_polygon);
ClipWrapper.Free_Clip_vertex_list(vtx_lst);
}
}
/*
public static void SavePolygon( string filename, bool writeHoleFlags, GeomPolygon polygon )
{
Clip_polygon Clip_polygon = ClipWrapper.PolygonTo_Clip_polygon( polygon );
IntPtr fp = fopen( filename, "wb" );
Clip_write_polygon( fp, writeHoleFlags?((int)1):((int)0), ref Clip_polygon );
fclose( fp );
ClipWrapper.Free_Clip_polygon( Clip_polygon );
}
public static GeomPolygon ReadPolygon( string filename, bool readHoleFlags )
{
Clip_polygon Clip_polygon = new Clip_polygon();
IntPtr fp = fopen( filename, "rb" );
Clip_read_polygon( fp, readHoleFlags?((int)1):((int)0), ref Clip_polygon );
GeomPolygon polygon = Clip_polygon_ToPolygon( Clip_polygon );
FreePolygon( ref Clip_polygon );
fclose( fp );
return polygon;
}
* */
private static Clip_polygon GeomPolygonTo_Clip_polygon(GeomPolygon polygon)
{
Clip_polygon Clip_pol = new Clip_polygon();
Clip_pol.num_contours = polygon.NofContours;
int[] hole = new int[polygon.NofContours];
for ( int i=0 ; i<polygon.NofContours ; i++ )
hole[i] = (polygon.ContourIsHole[i] ? 1 : 0 );
Clip_pol.hole = Marshal.AllocCoTaskMem( polygon.NofContours * Marshal.SizeOf(hole[0]) );
Marshal.Copy( hole, 0, Clip_pol.hole, polygon.NofContours );
Clip_pol.contour = Marshal.AllocCoTaskMem( polygon.NofContours * Marshal.SizeOf( new Clip_vertex_list() ) );
IntPtr ptr = Clip_pol.contour;
for ( int i=0 ; i<polygon.NofContours ; i++ ) {
Clip_vertex_list Clip_vtx_list = new Clip_vertex_list();
Clip_vtx_list.num_vertices = polygon.Contour[i].NofVertices;
Clip_vtx_list.vertex = Marshal.AllocCoTaskMem( polygon.Contour[i].NofVertices * Marshal.SizeOf(new Clip_vertex()) );
IntPtr ptr2 = Clip_vtx_list.vertex;
for ( int j=0 ; j<polygon.Contour[i].NofVertices ; j++ ) {
Clip_vertex Clip_vtx = new Clip_vertex();
Clip_vtx.x = polygon.Contour[i].Vertex[j].X;
Clip_vtx.y = polygon.Contour[i].Vertex[j].Y;
Marshal.StructureToPtr( Clip_vtx, ptr2, false );
ptr2 = IntPtrPlus(ptr2, Marshal.SizeOf(Clip_vtx)); // (IntPtr)(((int)ptr2) + Marshal.SizeOf(Clip_vtx));
}
Marshal.StructureToPtr( Clip_vtx_list, ptr, false );
ptr = IntPtrPlus(ptr, Marshal.SizeOf(Clip_vtx_list)); //(IntPtr)(((int)ptr) + Marshal.SizeOf(Clip_vtx_list));
}
return Clip_pol;
}
private static Clip_polygon PolygonTo_Clip_polygon(IPolygon polygon)
{
if (polygon == null || polygon.RingCount == 0) return new Clip_polygon();
int RingCount = polygon.RingCount;
Clip_polygon Clip_pol = new Clip_polygon();
Clip_pol.num_contours = RingCount;
int[] hole = new int[RingCount];
for (int i = 0; i < RingCount; i++)
hole[i] = ((polygon[i] is IHole) ? 1 : 0);
Clip_pol.hole = Marshal.AllocCoTaskMem(RingCount * Marshal.SizeOf(hole[0]));
Marshal.Copy(hole, 0, Clip_pol.hole, hole.Length);
Clip_pol.contour = Marshal.AllocCoTaskMem(RingCount * Marshal.SizeOf(new Clip_vertex_list()));
IntPtr ptr = Clip_pol.contour;
for (int i = 0; i < RingCount; i++)
{
Clip_vertex_list Clip_vtx_lst = new Clip_vertex_list();
IRing ring=polygon[i];
int PointCount=ring.PointCount;
if (ring[0].X != ring[PointCount - 1].X ||
ring[0].Y != ring[PointCount - 1].Y)
{
PointCount += 1;
}
Clip_vtx_lst.num_vertices = PointCount;
Clip_vtx_lst.vertex = Marshal.AllocCoTaskMem(PointCount * Marshal.SizeOf(new Clip_vertex()));
IntPtr ptr2 = Clip_vtx_lst.vertex;
for (int j = 0; j < PointCount; j++)
{
IPoint point = ((j < ring.PointCount) ? ring[j] : ring[0]);
Clip_vertex Clip_vtx = new Clip_vertex();
Clip_vtx.x = point.X;
Clip_vtx.y = point.Y;
Marshal.StructureToPtr(Clip_vtx, ptr2, false);
ptr2 = IntPtrPlus(ptr2, Marshal.SizeOf(Clip_vtx));// (IntPtr)(((int)ptr2) + Marshal.SizeOf(Clip_vtx));
}
Marshal.StructureToPtr(Clip_vtx_lst, ptr, false);
ptr = IntPtrPlus(ptr, Marshal.SizeOf(Clip_vtx_lst)); //(IntPtr)(((int)ptr) + Marshal.SizeOf(Clip_vtx_lst));
}
return Clip_pol;
}
private static Clip_vertex_list PathTo_Clip_vertex_list(IPath path)
{
if (path == null) return new Clip_vertex_list();
Clip_vertex_list Clip_vtx_lst = new Clip_vertex_list();
int PointCount = path.PointCount;
if (path is IRing)
{
if (path[0].X != path[PointCount - 1].X ||
path[0].Y != path[PointCount - 1].Y)
{
PointCount += 1;
}
}
Clip_vtx_lst.num_vertices = PointCount;
Clip_vtx_lst.vertex = Marshal.AllocCoTaskMem(PointCount * Marshal.SizeOf(new Clip_vertex()));
IntPtr ptr2 = Clip_vtx_lst.vertex;
for (int j = 0; j < PointCount; j++)
{
IPoint point = ((j < path.PointCount) ? path[j] : path[0]);
Clip_vertex Clip_vtx = new Clip_vertex();
Clip_vtx.x = point.X;
Clip_vtx.y = point.Y;
Marshal.StructureToPtr(Clip_vtx, ptr2, false);
ptr2 = IntPtrPlus(ptr2, Marshal.SizeOf(Clip_vtx)); //(IntPtr)(((int)ptr2) + Marshal.SizeOf(Clip_vtx));
}
return Clip_vtx_lst;
}
private static GeomPolygon Clip_polygon_ToGeomPolygon(Clip_polygon Clip_polygon)
{
GeomPolygon polygon = new GeomPolygon();
polygon.NofContours = Clip_polygon.num_contours;
if (polygon.NofContours == 0) return new GeomPolygon();
polygon.ContourIsHole = new bool[polygon.NofContours];
polygon.Contour = new GeomVertexList[polygon.NofContours];
short[] holeShort = new short[polygon.NofContours];
IntPtr ptr = Clip_polygon.hole;
Marshal.Copy( Clip_polygon.hole, holeShort, 0, polygon.NofContours );
for ( int i=0 ; i<polygon.NofContours ; i++ )
polygon.ContourIsHole[i] = (holeShort[i]!=0);
ptr = Clip_polygon.contour;
for ( int i=0 ; i<polygon.NofContours ; i++ ) {
Clip_vertex_list Clip_vtx_list = (Clip_vertex_list)Marshal.PtrToStructure( ptr, typeof(Clip_vertex_list) );
polygon.Contour[i] = new GeomVertexList();
polygon.Contour[i].NofVertices = Clip_vtx_list.num_vertices;
polygon.Contour[i].Vertex = new GeomVertex[polygon.Contour[i].NofVertices];
IntPtr ptr2 = Clip_vtx_list.vertex;
for ( int j=0 ; j<polygon.Contour[i].NofVertices ; j++ ) {
Clip_vertex Clip_vtx = (Clip_vertex)Marshal.PtrToStructure( ptr2, typeof(Clip_vertex) );
polygon.Contour[i].Vertex[j].X = Clip_vtx.x;
polygon.Contour[i].Vertex[j].Y = Clip_vtx.y;
ptr2 = IntPtrPlus(ptr2, Marshal.SizeOf(Clip_vtx)); //(IntPtr)(((int)ptr2) + Marshal.SizeOf(Clip_vtx));
}
ptr = IntPtrPlus(ptr, Marshal.SizeOf(Clip_vtx_list)); //(IntPtr)(((int)ptr) + Marshal.SizeOf(Clip_vtx_list));
}
return polygon;
}
private static IPolygon Clip_polygon_ToPolygon(Clip_polygon Clip_polygon)
{
Polygon polygon = new Polygon();
if (Clip_polygon.num_contours == 0) return new Polygon();
short[] holeShort = new short[Clip_polygon.num_contours];
Marshal.Copy(Clip_polygon.hole, holeShort, 0, Clip_polygon.num_contours);
IntPtr ptr = Clip_polygon.contour;
for (int i = 0; i < Clip_polygon.num_contours; i++)
{
Clip_vertex_list Clip_vtx_lst = (Clip_vertex_list)Marshal.PtrToStructure(ptr, typeof(Clip_vertex_list));
IRing ring = ((holeShort[i] == 0) ? new Ring() : new Hole());
IntPtr ptr2 = Clip_vtx_lst.vertex;
for (int j = 0; j < Clip_vtx_lst.num_vertices; j++)
{
Clip_vertex Clip_vtx = (Clip_vertex)Marshal.PtrToStructure(ptr2, typeof(Clip_vertex));
ring.AddPoint(new gView.Framework.Geometry.Point(
Clip_vtx.x, Clip_vtx.y));
ptr2 = IntPtrPlus(ptr2, Marshal.SizeOf(Clip_vtx)); //(IntPtr)(((int)ptr2) + Marshal.SizeOf(Clip_vtx));
}
polygon.AddRing(ring);
ptr = IntPtrPlus(ptr, Marshal.SizeOf(Clip_vtx_lst)); //(IntPtr)(((int)ptr) + Marshal.SizeOf(Clip_vtx_lst));
}
return polygon;
}
private static GeomTristrip Clip_strip_ToTristrip(Clip_tristrip Clip_strip)
{
GeomTristrip tristrip = new GeomTristrip();
tristrip.NofStrips = Clip_strip.num_strips;
tristrip.Strip = new GeomVertexList[tristrip.NofStrips];
IntPtr ptr = Clip_strip.strip;
for ( int i=0 ; i<tristrip.NofStrips ; i++ ) {
tristrip.Strip[i] = new GeomVertexList();
Clip_vertex_list Clip_vtx_list = (Clip_vertex_list)Marshal.PtrToStructure( ptr, typeof(Clip_vertex_list) );
tristrip.Strip[i].NofVertices = Clip_vtx_list.num_vertices;
tristrip.Strip[i].Vertex = new GeomVertex[tristrip.Strip[i].NofVertices];
IntPtr ptr2 = Clip_vtx_list.vertex;
for ( int j=0 ; j<tristrip.Strip[i].NofVertices ; j++ ) {
Clip_vertex Clip_vtx = (Clip_vertex)Marshal.PtrToStructure( ptr2, typeof(Clip_vertex) );
tristrip.Strip[i].Vertex[j].X = Clip_vtx.x;
tristrip.Strip[i].Vertex[j].Y = Clip_vtx.y;
ptr2 = IntPtrPlus(ptr2, Marshal.SizeOf(Clip_vtx)); // (IntPtr)(((int)ptr2) + Marshal.SizeOf(Clip_vtx));
}
ptr = IntPtrPlus(ptr, Marshal.SizeOf(Clip_vtx_list));// (IntPtr)(((int)ptr) + Marshal.SizeOf(Clip_vtx_list));
}
return tristrip;
}
private static void Free_Clip_polygon( Clip_polygon Clip_pol )
{
Marshal.FreeCoTaskMem( Clip_pol.hole );
IntPtr ptr = Clip_pol.contour;
for ( int i=0 ; i<Clip_pol.num_contours ; i++ ) {
Clip_vertex_list Clip_vtx_list = (Clip_vertex_list)Marshal.PtrToStructure( ptr, typeof(Clip_vertex_list) );
Marshal.FreeCoTaskMem( Clip_vtx_list.vertex );
ptr = IntPtrPlus(ptr, Marshal.SizeOf(Clip_vtx_list)); //(IntPtr)(((int)ptr) + Marshal.SizeOf(Clip_vtx_list));
}
Marshal.FreeCoTaskMem(Clip_pol.contour);
}
private static void Free_Clip_vertex_list(Clip_vertex_list Clip_vtx_list)
{
Marshal.FreeCoTaskMem(Clip_vtx_list.vertex);
}
private static IntPtr IntPtrPlus(IntPtr ptr, int plus)
{
if (IntPtr.Size == 8) // 64 Bit
return (IntPtr)(ptr.ToInt64() + plus);
return (IntPtr)(ptr.ToInt32() + plus);
}
[DllImport( "geom.dll" )]
private static extern void Polygon2Tristrip( [In] ref Clip_polygon polygon,
[In,Out] ref Clip_tristrip tristrip );
[DllImport( "geom.dll" )]
private static extern void ClipPolygon( [In] ref Clip_polygon subject_polygon,
[In] ref Clip_polygon clip_polygon,
[In] ClipOperation set_operation,
[In,Out] ref Clip_polygon result_polygon );
[DllImport( "geom.dll" )]
private static extern void ClipTristrip( [In] ref Clip_polygon subject_polygon,
[In] ref Clip_polygon clip_polygon,
[In] ClipOperation set_operation,
[In,Out] ref Clip_tristrip result_tristrip );
[DllImport( "geom.dll" )]
private static extern void FreeTristrip( [In] ref Clip_tristrip tristrip );
[DllImport( "geom.dll" )]
private static extern void FreePolygon( [In] ref Clip_polygon polygon );
[DllImport("geom.dll") ]
private static extern void BufferVertextList( [In] ref Clip_vertex_list vtx_list,
[In] double distance,
[In] BufferOperation buffer_op,
[In, Out] ref Clip_polygon result_polygon );
/*
[DllImport( "geom.dll" )]
private static extern void Clip_read_polygon( [In] IntPtr fp, [In] int read_hole_flags, [In,Out] ref Clip_polygon polygon );
[DllImport( "geom.dll" )]
private static extern void Clip_write_polygon( [In] IntPtr fp, [In] int write_hole_flags, [In] ref Clip_polygon polygon );
*/
/*
[DllImport( "msvcr71.dll" )]
private static extern IntPtr fopen( [In] string filename, [In] string mode );
[DllImport( "msvcr71.dll" )]
private static extern void fclose( [In] IntPtr fp );
[DllImport( "msvcr71.dll" )]
private static extern int fputc( [In] int c, [In] IntPtr fp );
*/
enum Clip_op /* Set operation type */
{
Clip_DIFF = 0, /* Difference */
Clip_INT = 1, /* Intersection */
Clip_XOR = 2, /* Exclusive or */
Clip_UNION = 3 /* Union */
}
[StructLayout(LayoutKind.Sequential)]
private struct Clip_vertex /* Polygon vertex structure */
{
public double x; /* Vertex x component */
public double y; /* vertex y component */
}
[StructLayout(LayoutKind.Sequential)]
private struct Clip_vertex_list /* Vertex list structure */
{
public int num_vertices; /* Number of vertices in list */
public IntPtr vertex; /* Vertex array pointer */
}
[StructLayout(LayoutKind.Sequential)]
private struct Clip_polygon /* Polygon set structure */
{
public int num_contours; /* Number of contours in polygon */
public IntPtr contour; /* Contour array pointer */
public IntPtr hole; /* Hole / external contour flags */
}
[StructLayout(LayoutKind.Sequential)]
private struct Clip_tristrip /* Tristrip set structure */
{
public int num_strips; /* Number of tristrips */
public IntPtr strip; /* Tristrip array pointer */
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.Configuration;
using Orleans.Hosting;
using Orleans.Runtime;
using Orleans.TestingHost;
using Orleans.Utilities;
using Tester;
using TestExtensions;
using UnitTests.GrainInterfaces;
using UnitTests.Grains;
using Xunit;
namespace UnitTests.ActivationsLifeCycleTests
{
public class ActivationCollectorTests : OrleansTestingBase, IDisposable
{
private static readonly TimeSpan DEFAULT_COLLECTION_QUANTUM = TimeSpan.FromSeconds(10);
private static readonly TimeSpan DEFAULT_IDLE_TIMEOUT = DEFAULT_COLLECTION_QUANTUM + TimeSpan.FromSeconds(1);
private static readonly TimeSpan WAIT_TIME = DEFAULT_IDLE_TIMEOUT.Multiply(3.0);
private TestCluster testCluster;
private ILogger logger;
private void Initialize(TimeSpan collectionAgeLimit, TimeSpan quantum)
{
var builder = new TestClusterBuilder(1);
builder.Properties["CollectionQuantum"] = quantum.ToString();
builder.Properties["DefaultCollectionAgeLimit"] = collectionAgeLimit.ToString();
builder.AddSiloBuilderConfigurator<SiloConfigurator>();
testCluster = builder.Build();
testCluster.Deploy();
this.logger = this.testCluster.Client.ServiceProvider.GetRequiredService<ILogger<ActivationCollectorTests>>();
}
public class SiloConfigurator : ISiloBuilderConfigurator
{
public void Configure(ISiloHostBuilder hostBuilder)
{
var config = hostBuilder.GetConfiguration();
var collectionAgeLimit = TimeSpan.Parse(config["DefaultCollectionAgeLimit"]);
var quantum = TimeSpan.Parse(config["CollectionQuantum"]);
hostBuilder
.ConfigureDefaults()
.ConfigureServices(services => services.Where(s => s.ServiceType == typeof(IConfigurationValidator)).ToList().ForEach(s => services.Remove(s)));
hostBuilder.Configure<GrainCollectionOptions>(options =>
{
options.CollectionAge = collectionAgeLimit;
options.CollectionQuantum = quantum;
options.ClassSpecificCollectionAge = new Dictionary<string, TimeSpan>
{
[typeof(IdleActivationGcTestGrain2).FullName] = DEFAULT_IDLE_TIMEOUT,
[typeof(BusyActivationGcTestGrain2).FullName] = DEFAULT_IDLE_TIMEOUT,
[typeof(CollectionSpecificAgeLimitForTenSecondsActivationGcTestGrain).FullName] = TimeSpan.FromSeconds(12),
};
});
}
}
private void Initialize(TimeSpan collectionAgeLimit)
{
Initialize(collectionAgeLimit, DEFAULT_COLLECTION_QUANTUM);
}
private void Initialize()
{
Initialize(TimeSpan.Zero, DEFAULT_COLLECTION_QUANTUM);
}
public void Dispose()
{
testCluster?.StopAllSilos();
testCluster = null;
}
[Fact, TestCategory("ActivationCollector"), TestCategory("Functional")]
public async Task ActivationCollectorForceCollection()
{
Initialize(DEFAULT_IDLE_TIMEOUT);
const int grainCount = 1000;
var fullGrainTypeName = typeof(IdleActivationGcTestGrain1).FullName;
List<Task> tasks = new List<Task>();
logger.Info("ActivationCollectorForceCollection: activating {0} grains.", grainCount);
for (var i = 0; i < grainCount; ++i)
{
IIdleActivationGcTestGrain1 g = this.testCluster.GrainFactory.GetGrain<IIdleActivationGcTestGrain1>(Guid.NewGuid());
tasks.Add(g.Nop());
}
await Task.WhenAll(tasks);
await Task.Delay(TimeSpan.FromSeconds(5));
var grain = this.testCluster.GrainFactory.GetGrain<IManagementGrain>(0);
await grain.ForceActivationCollection(TimeSpan.FromSeconds(4));
int activationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, fullGrainTypeName);
Assert.Equal(0, activationsNotCollected);
await grain.ForceActivationCollection(TimeSpan.FromSeconds(4));
}
[Fact, TestCategory("ActivationCollector"), TestCategory("Functional")]
public async Task ActivationCollectorShouldCollectIdleActivations()
{
Initialize(DEFAULT_IDLE_TIMEOUT);
const int grainCount = 1000;
var fullGrainTypeName = typeof(IdleActivationGcTestGrain1).FullName;
List<Task> tasks = new List<Task>();
logger.Info("IdleActivationCollectorShouldCollectIdleActivations: activating {0} grains.", grainCount);
for (var i = 0; i < grainCount; ++i)
{
IIdleActivationGcTestGrain1 g = this.testCluster.GrainFactory.GetGrain<IIdleActivationGcTestGrain1>(Guid.NewGuid());
tasks.Add(g.Nop());
}
await Task.WhenAll(tasks);
int activationsCreated = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, fullGrainTypeName);
Assert.Equal(grainCount, activationsCreated);
logger.Info("IdleActivationCollectorShouldCollectIdleActivations: grains activated; waiting {0} sec (activation GC idle timeout is {1} sec).", WAIT_TIME.TotalSeconds, DEFAULT_IDLE_TIMEOUT.TotalSeconds);
await Task.Delay(WAIT_TIME);
int activationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, fullGrainTypeName);
Assert.Equal(0, activationsNotCollected);
}
[Fact, TestCategory("ActivationCollector"), TestCategory("Functional")]
public async Task ActivationCollectorShouldNotCollectBusyActivations()
{
Initialize(DEFAULT_IDLE_TIMEOUT);
const int idleGrainCount = 500;
const int busyGrainCount = 500;
var idleGrainTypeName = typeof(IdleActivationGcTestGrain1).FullName;
var busyGrainTypeName = typeof(BusyActivationGcTestGrain1).FullName;
List<Task> tasks0 = new List<Task>();
List<IBusyActivationGcTestGrain1> busyGrains = new List<IBusyActivationGcTestGrain1>();
logger.Info("ActivationCollectorShouldNotCollectBusyActivations: activating {0} busy grains.", busyGrainCount);
for (var i = 0; i < busyGrainCount; ++i)
{
IBusyActivationGcTestGrain1 g = this.testCluster.GrainFactory.GetGrain<IBusyActivationGcTestGrain1>(Guid.NewGuid());
busyGrains.Add(g);
tasks0.Add(g.Nop());
}
await Task.WhenAll(tasks0);
bool[] quit = new bool[]{ false };
Func<Task> busyWorker =
async () =>
{
logger.Info("ActivationCollectorShouldNotCollectBusyActivations: busyWorker started");
List<Task> tasks1 = new List<Task>();
while (!quit[0])
{
foreach (var g in busyGrains)
tasks1.Add(g.Nop());
await Task.WhenAll(tasks1);
}
};
Task.Run(busyWorker).Ignore();
logger.Info("ActivationCollectorShouldNotCollectBusyActivations: activating {0} idle grains.", idleGrainCount);
tasks0.Clear();
for (var i = 0; i < idleGrainCount; ++i)
{
IIdleActivationGcTestGrain1 g = this.testCluster.GrainFactory.GetGrain<IIdleActivationGcTestGrain1>(Guid.NewGuid());
tasks0.Add(g.Nop());
}
await Task.WhenAll(tasks0);
int activationsCreated = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, idleGrainTypeName) + await TestUtils.GetActivationCount(this.testCluster.GrainFactory, busyGrainTypeName);
Assert.Equal(idleGrainCount + busyGrainCount, activationsCreated);
logger.Info("ActivationCollectorShouldNotCollectBusyActivations: grains activated; waiting {0} sec (activation GC idle timeout is {1} sec).", WAIT_TIME.TotalSeconds, DEFAULT_IDLE_TIMEOUT.TotalSeconds);
await Task.Delay(WAIT_TIME);
// we should have only collected grains from the idle category (IdleActivationGcTestGrain1).
int idleActivationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, idleGrainTypeName);
int busyActivationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, busyGrainTypeName);
Assert.Equal(0, idleActivationsNotCollected);
Assert.Equal(busyGrainCount, busyActivationsNotCollected);
quit[0] = true;
}
[Fact, TestCategory("ActivationCollector"), TestCategory("Functional")]
public async Task ManualCollectionShouldNotCollectBusyActivations()
{
Initialize(DEFAULT_IDLE_TIMEOUT);
TimeSpan shortIdleTimeout = TimeSpan.FromSeconds(1);
const int idleGrainCount = 500;
const int busyGrainCount = 500;
var idleGrainTypeName = typeof(IdleActivationGcTestGrain1).FullName;
var busyGrainTypeName = typeof(BusyActivationGcTestGrain1).FullName;
List<Task> tasks0 = new List<Task>();
List<IBusyActivationGcTestGrain1> busyGrains = new List<IBusyActivationGcTestGrain1>();
logger.Info("ManualCollectionShouldNotCollectBusyActivations: activating {0} busy grains.", busyGrainCount);
for (var i = 0; i < busyGrainCount; ++i)
{
IBusyActivationGcTestGrain1 g = this.testCluster.GrainFactory.GetGrain<IBusyActivationGcTestGrain1>(Guid.NewGuid());
busyGrains.Add(g);
tasks0.Add(g.Nop());
}
await Task.WhenAll(tasks0);
bool[] quit = new bool[]{ false };
Func<Task> busyWorker =
async () =>
{
logger.Info("ManualCollectionShouldNotCollectBusyActivations: busyWorker started");
List<Task> tasks1 = new List<Task>();
while (!quit[0])
{
foreach (var g in busyGrains)
tasks1.Add(g.Nop());
await Task.WhenAll(tasks1);
}
};
Task.Run(busyWorker).Ignore();
logger.Info("ManualCollectionShouldNotCollectBusyActivations: activating {0} idle grains.", idleGrainCount);
tasks0.Clear();
for (var i = 0; i < idleGrainCount; ++i)
{
IIdleActivationGcTestGrain1 g = this.testCluster.GrainFactory.GetGrain<IIdleActivationGcTestGrain1>(Guid.NewGuid());
tasks0.Add(g.Nop());
}
await Task.WhenAll(tasks0);
int activationsCreated = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, idleGrainTypeName) + await TestUtils.GetActivationCount(this.testCluster.GrainFactory, busyGrainTypeName);
Assert.Equal(idleGrainCount + busyGrainCount, activationsCreated);
logger.Info("ManualCollectionShouldNotCollectBusyActivations: grains activated; waiting {0} sec (activation GC idle timeout is {1} sec).", shortIdleTimeout.TotalSeconds, DEFAULT_IDLE_TIMEOUT.TotalSeconds);
await Task.Delay(shortIdleTimeout);
TimeSpan everything = TimeSpan.FromMinutes(10);
logger.Info("ManualCollectionShouldNotCollectBusyActivations: triggering manual collection (timespan is {0} sec).", everything.TotalSeconds);
IManagementGrain mgmtGrain = this.testCluster.GrainFactory.GetGrain<IManagementGrain>(0);
await mgmtGrain.ForceActivationCollection(everything);
logger.Info("ManualCollectionShouldNotCollectBusyActivations: waiting {0} sec (activation GC idle timeout is {1} sec).", WAIT_TIME.TotalSeconds, DEFAULT_IDLE_TIMEOUT.TotalSeconds);
await Task.Delay(WAIT_TIME);
// we should have only collected grains from the idle category (IdleActivationGcTestGrain).
int idleActivationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, idleGrainTypeName);
int busyActivationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, busyGrainTypeName);
Assert.Equal(0, idleActivationsNotCollected);
Assert.Equal(busyGrainCount, busyActivationsNotCollected);
quit[0] = true;
}
[Fact, TestCategory("ActivationCollector"), TestCategory("Functional")]
public async Task ActivationCollectorShouldCollectIdleActivationsSpecifiedInPerTypeConfiguration()
{
//make sure default value won't cause activation collection during wait time
var defaultCollectionAgeLimit = WAIT_TIME.Multiply(2);
Initialize(defaultCollectionAgeLimit);
const int grainCount = 1000;
var fullGrainTypeName = typeof(IdleActivationGcTestGrain2).FullName;
List<Task> tasks = new List<Task>();
logger.Info("ActivationCollectorShouldCollectIdleActivationsSpecifiedInPerTypeConfiguration: activating {0} grains.", grainCount);
for (var i = 0; i < grainCount; ++i)
{
IIdleActivationGcTestGrain2 g = this.testCluster.GrainFactory.GetGrain<IIdleActivationGcTestGrain2>(Guid.NewGuid());
tasks.Add(g.Nop());
}
await Task.WhenAll(tasks);
int activationsCreated = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, fullGrainTypeName);
Assert.Equal(grainCount, activationsCreated);
logger.Info("ActivationCollectorShouldCollectIdleActivationsSpecifiedInPerTypeConfiguration: grains activated; waiting {0} sec (activation GC idle timeout is {1} sec).", WAIT_TIME.TotalSeconds, DEFAULT_IDLE_TIMEOUT.TotalSeconds);
await Task.Delay(WAIT_TIME);
int activationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, fullGrainTypeName);
Assert.Equal(0, activationsNotCollected);
}
[Fact, TestCategory("ActivationCollector"), TestCategory("Functional")]
public async Task ActivationCollectorShouldNotCollectBusyActivationsSpecifiedInPerTypeConfiguration()
{
//make sure default value won't cause activation collection during wait time
var defaultCollectionAgeLimit = WAIT_TIME.Multiply(2);
Initialize(defaultCollectionAgeLimit);
const int idleGrainCount = 500;
const int busyGrainCount = 500;
var idleGrainTypeName = typeof(IdleActivationGcTestGrain2).FullName;
var busyGrainTypeName = typeof(BusyActivationGcTestGrain2).FullName;
List<Task> tasks0 = new List<Task>();
List<IBusyActivationGcTestGrain2> busyGrains = new List<IBusyActivationGcTestGrain2>();
logger.Info("ActivationCollectorShouldNotCollectBusyActivationsSpecifiedInPerTypeConfiguration: activating {0} busy grains.", busyGrainCount);
for (var i = 0; i < busyGrainCount; ++i)
{
IBusyActivationGcTestGrain2 g = this.testCluster.GrainFactory.GetGrain<IBusyActivationGcTestGrain2>(Guid.NewGuid());
busyGrains.Add(g);
tasks0.Add(g.Nop());
}
await Task.WhenAll(tasks0);
bool[] quit = new bool[]{ false };
Func<Task> busyWorker =
async () =>
{
logger.Info("ActivationCollectorShouldNotCollectBusyActivationsSpecifiedInPerTypeConfiguration: busyWorker started");
List<Task> tasks1 = new List<Task>();
while (!quit[0])
{
foreach (var g in busyGrains)
tasks1.Add(g.Nop());
await Task.WhenAll(tasks1);
}
};
Task.Run(busyWorker).Ignore();
logger.Info("ActivationCollectorShouldNotCollectBusyActivationsSpecifiedInPerTypeConfiguration: activating {0} idle grains.", idleGrainCount);
tasks0.Clear();
for (var i = 0; i < idleGrainCount; ++i)
{
IIdleActivationGcTestGrain2 g = this.testCluster.GrainFactory.GetGrain<IIdleActivationGcTestGrain2>(Guid.NewGuid());
tasks0.Add(g.Nop());
}
await Task.WhenAll(tasks0);
int activationsCreated = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, idleGrainTypeName) + await TestUtils.GetActivationCount(this.testCluster.GrainFactory, busyGrainTypeName);
Assert.Equal(idleGrainCount + busyGrainCount, activationsCreated);
logger.Info("IdleActivationCollectorShouldNotCollectBusyActivations: grains activated; waiting {0} sec (activation GC idle timeout is {1} sec).", WAIT_TIME.TotalSeconds, DEFAULT_IDLE_TIMEOUT.TotalSeconds);
await Task.Delay(WAIT_TIME);
// we should have only collected grains from the idle category (IdleActivationGcTestGrain2).
int idleActivationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, idleGrainTypeName);
int busyActivationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, busyGrainTypeName);
Assert.Equal(0, idleActivationsNotCollected);
Assert.Equal(busyGrainCount, busyActivationsNotCollected);
quit[0] = true;
}
[Fact(Skip = "Flaky test. Needs to be investigated."), TestCategory("ActivationCollector"), TestCategory("Functional")]
public async Task ActivationCollectorShouldNotCollectBusyStatelessWorkers()
{
Initialize(DEFAULT_IDLE_TIMEOUT);
// the purpose of this test is to determine whether idle stateless worker activations are properly identified by the activation collector.
// in this test, we:
//
// 1. setup the test.
// 2. activate a set of grains by sending a burst of messages to each one. the purpose of the burst is to ensure that multiple activations are used.
// 3. verify that multiple activations for each grain have been created.
// 4. periodically send a message to each grain, ensuring that only one activation remains busy. each time we check the activation id and compare it against the activation id returned by the previous grain call. initially, these may not be identical but as the other activations become idle and are collected, there will be only one activation servicing these calls.
// 5. wait long enough for idle activations to be collected.
// 6. verify that only one activation is still active per grain.
// 7. ensure that test steps 2-6 are repeatable.
const int grainCount = 1;
var grainTypeName = typeof(StatelessWorkerActivationCollectorTestGrain1).FullName;
const int burstLength = 1000;
List<Task> tasks0 = new List<Task>();
List<IStatelessWorkerActivationCollectorTestGrain1> grains = new List<IStatelessWorkerActivationCollectorTestGrain1>();
for (var i = 0; i < grainCount; ++i)
{
IStatelessWorkerActivationCollectorTestGrain1 g = this.testCluster.GrainFactory.GetGrain<IStatelessWorkerActivationCollectorTestGrain1>(Guid.NewGuid());
grains.Add(g);
}
bool[] quit = new bool[] { false };
bool[] matched = new bool[grainCount];
string[] activationIds = new string[grainCount];
Func<int, Task> workFunc =
async index =>
{
// (part of) 4. periodically send a message to each grain...
// take a grain and call Delay to keep it busy.
IStatelessWorkerActivationCollectorTestGrain1 g = grains[index];
await g.Delay(DEFAULT_IDLE_TIMEOUT.Divide(2));
// identify the activation and record whether it matches the activation ID last reported. it probably won't match in the beginning but should always converge on a match as other activations get collected.
string aid = await g.IdentifyActivation();
logger.Info("ActivationCollectorShouldNotCollectBusyStatelessWorkers: identified {0}", aid);
matched[index] = aid == activationIds[index];
activationIds[index] = aid;
};
Func<Task> workerFunc =
async () =>
{
// (part of) 4. periodically send a message to each grain...
logger.Info("ActivationCollectorShouldNotCollectBusyStatelessWorkers: busyWorker started");
List<Task> tasks1 = new List<Task>();
while (!quit[0])
{
for (int index = 0; index < grains.Count; ++index)
{
if (quit[0])
{
break;
}
tasks1.Add(workFunc(index));
}
await Task.WhenAll(tasks1);
}
};
// setup (1) ends here.
for (int i = 0; i < 2; ++i)
{
// 2. activate a set of grains...
this.logger.Info("ActivationCollectorShouldNotCollectBusyStatelessWorkers: activating {0} stateless worker grains (run #{1}).", grainCount, i);
foreach (var g in grains)
{
for (int j = 0; j < burstLength; ++j)
{
// having the activation delay will ensure that one activation cannot serve all requests that we send to it, making it so that additional activations will be created.
tasks0.Add(g.Delay(TimeSpan.FromMilliseconds(10)));
}
}
await Task.WhenAll(tasks0);
// 3. verify that multiple activations for each grain have been created.
int activationsCreated = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, grainTypeName);
Assert.True(activationsCreated > grainCount, string.Format("more than {0} activations should have been created; got {1} instead", grainCount, activationsCreated));
// 4. periodically send a message to each grain...
this.logger.Info("ActivationCollectorShouldNotCollectBusyStatelessWorkers: grains activated; sending heartbeat to {0} stateless worker grains.", grainCount);
Task workerTask = Task.Run(workerFunc);
// 5. wait long enough for idle activations to be collected.
this.logger.Info("ActivationCollectorShouldNotCollectBusyStatelessWorkers: grains activated; waiting {0} sec (activation GC idle timeout is {1} sec).", WAIT_TIME.TotalSeconds, DEFAULT_IDLE_TIMEOUT.TotalSeconds);
await Task.Delay(WAIT_TIME);
// 6. verify that only one activation is still active per grain.
int busyActivationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, grainTypeName);
// signal that the worker task should stop and wait for it to finish.
quit[0] = true;
await workerTask;
quit[0] = false;
Assert.Equal(grainCount, busyActivationsNotCollected);
// verify that we matched activation ids in the final iteration of step 4's loop.
for (int index = 0; index < grains.Count; ++index)
{
Assert.True(matched[index], string.Format("activation ID of final subsequent heartbeats did not match for grain {0}", grains[index]));
}
}
}
[Fact, TestCategory("ActivationCollector"), TestCategory("Performance"), TestCategory("CorePerf")]
public async Task ActivationCollectorShouldNotCauseMessageLoss()
{
Initialize(DEFAULT_IDLE_TIMEOUT);
const int idleGrainCount = 0;
const int busyGrainCount = 500;
var idleGrainTypeName = typeof(IdleActivationGcTestGrain1).FullName;
var busyGrainTypeName = typeof(BusyActivationGcTestGrain1).FullName;
const int burstCount = 100;
List<Task> tasks0 = new List<Task>();
List<IBusyActivationGcTestGrain1> busyGrains = new List<IBusyActivationGcTestGrain1>();
logger.Info("ActivationCollectorShouldNotCauseMessageLoss: activating {0} busy grains.", busyGrainCount);
for (var i = 0; i < busyGrainCount; ++i)
{
IBusyActivationGcTestGrain1 g = this.testCluster.GrainFactory.GetGrain<IBusyActivationGcTestGrain1>(Guid.NewGuid());
busyGrains.Add(g);
tasks0.Add(g.Nop());
}
await busyGrains[0].EnableBurstOnCollection(burstCount);
logger.Info("ActivationCollectorShouldNotCauseMessageLoss: activating {0} idle grains.", idleGrainCount);
tasks0.Clear();
for (var i = 0; i < idleGrainCount; ++i)
{
IIdleActivationGcTestGrain1 g = this.testCluster.GrainFactory.GetGrain<IIdleActivationGcTestGrain1>(Guid.NewGuid());
tasks0.Add(g.Nop());
}
await Task.WhenAll(tasks0);
int activationsCreated = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, idleGrainTypeName) + await TestUtils.GetActivationCount(this.testCluster.GrainFactory, busyGrainTypeName);
Assert.Equal(idleGrainCount + busyGrainCount, activationsCreated);
logger.Info("ActivationCollectorShouldNotCauseMessageLoss: grains activated; waiting {0} sec (activation GC idle timeout is {1} sec).", WAIT_TIME.TotalSeconds, DEFAULT_IDLE_TIMEOUT.TotalSeconds);
await Task.Delay(WAIT_TIME);
// we should have only collected grains from the idle category (IdleActivationGcTestGrain1).
int idleActivationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, idleGrainTypeName);
int busyActivationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, busyGrainTypeName);
Assert.Equal(0, idleActivationsNotCollected);
Assert.Equal(busyGrainCount, busyActivationsNotCollected);
}
[Fact, TestCategory("ActivationCollector"), TestCategory("Functional")]
public async Task ActivationCollectorShouldCollectByCollectionSpecificAgeLimitForTwelveSeconds()
{
var waitTime = TimeSpan.FromSeconds(30);
var defaultCollectionAge = waitTime.Multiply(2);
//make sure defaultCollectionAge value won't cause activation collection in wait time
Initialize(defaultCollectionAge);
const int grainCount = 1000;
// CollectionAgeLimit = 12 seconds
var fullGrainTypeName = typeof(CollectionSpecificAgeLimitForTenSecondsActivationGcTestGrain).FullName;
List<Task> tasks = new List<Task>();
logger.Info("ActivationCollectorShouldCollectByCollectionSpecificAgeLimit: activating {0} grains.", grainCount);
for (var i = 0; i < grainCount; ++i)
{
ICollectionSpecificAgeLimitForTenSecondsActivationGcTestGrain g = this.testCluster.GrainFactory.GetGrain<ICollectionSpecificAgeLimitForTenSecondsActivationGcTestGrain>(Guid.NewGuid());
tasks.Add(g.Nop());
}
await Task.WhenAll(tasks);
int activationsCreated = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, fullGrainTypeName);
Assert.Equal(grainCount, activationsCreated);
logger.Info("ActivationCollectorShouldCollectByCollectionSpecificAgeLimit: grains activated; waiting {0} sec (activation GC idle timeout is {1} sec).", WAIT_TIME.TotalSeconds, DEFAULT_IDLE_TIMEOUT.TotalSeconds);
// Some time is required for GC to collect all of the Grains)
await Task.Delay(waitTime);
int activationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, fullGrainTypeName);
Assert.Equal(0, activationsNotCollected);
}
}
}
| |
// <copyright file="ConvolutionBase.cs" company="Techyian">
// Copyright (c) Ian Auty and contributors. All rights reserved.
// Licensed under the MIT License. Please see LICENSE.txt for License info.
// </copyright>
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using MMALSharp.Common;
using MMALSharp.Common.Utility;
namespace MMALSharp.Processors.Effects
{
/// <summary>
/// Base class for image processors using matrix convolution.
/// </summary>
public abstract class ConvolutionBase
{
private readonly int _horizontalCellCount;
private readonly int _verticalCellCount;
/// <summary>
/// Creates a <see cref="ConvolutionBase"/> object. This uses the default parallel processing
/// cell count based on the image resolution and the recommended values defined by the
/// <see cref="FrameAnalyser"/>. Requires use of one of the standard camera image resolutions.
/// </summary>
public ConvolutionBase()
{
_horizontalCellCount = 0;
_verticalCellCount = 0;
}
/// <summary>
/// Creates a <see cref="ConvolutionBase"/> object with custom parallel processing cell counts.
/// You must use this constructor if you are processing non-standard image resolutions.
/// </summary>
/// <param name="horizontalCellCount">The number of columns to divide the image into.</param>
/// <param name="verticalCellCount">The number of rows to divide the image into.</param>
public ConvolutionBase(int horizontalCellCount, int verticalCellCount)
{
_horizontalCellCount = horizontalCellCount;
_verticalCellCount = verticalCellCount;
}
/// <summary>
/// Apply a convolution based on the kernel passed in.
/// </summary>
/// <param name="kernel">The kernel.</param>
/// <param name="kernelWidth">The kernel's width.</param>
/// <param name="kernelHeight">The kernel's height.</param>
/// <param name="context">An image context providing additional metadata on the data passed in.</param>
public void ApplyConvolution(double[,] kernel, int kernelWidth, int kernelHeight, ImageContext context)
{
var localContext = context.Raw ? context : CloneToRawBitmap(context);
bool storeFromRaw = context.Raw && context.StoreFormat != null;
var analyser = new FrameAnalyser
{
HorizonalCellCount = _horizontalCellCount,
VerticalCellCount = _verticalCellCount,
};
analyser.Apply(localContext);
Parallel.ForEach(analyser.CellRect, (cell)
=> ProcessCell(cell, localContext.Data, kernel, kernelWidth, kernelHeight, analyser.Metadata, storeFromRaw));
if (context.StoreFormat != null)
{
FormatRawBitmap(localContext, context);
context.Raw = false; // context is never raw after formatting
}
else
{
if(!context.Raw)
{
// TakePicture doesn't set the Resolution, copy it from the cloned version which stored it from Bitmap
context.Resolution = new Resolution(localContext.Resolution.Width, localContext.Resolution.Height);
context.Data = new byte[localContext.Data.Length];
Array.Copy(localContext.Data, context.Data, context.Data.Length);
context.Raw = true; // we just copied raw data to the source context
}
}
}
private void ProcessCell(Rectangle rect, byte[] image, double[,] kernel, int kernelWidth, int kernelHeight, FrameAnalysisMetadata metadata, bool storeFromRaw)
{
// Rectangle and FrameAnalysisMetadata are structures; they are by-value copies and all fields are value-types which makes them thread safe
int x2 = rect.X + rect.Width;
int y2 = rect.Y + rect.Height;
int index;
// Indicates RGB needs to be swapped to BGR so that Bitmap.Save works correctly.
if (storeFromRaw)
{
for (var x = rect.X; x < x2; x++)
{
for (var y = rect.Y; y < y2; y++)
{
index = (x * metadata.Bpp) + (y * metadata.Stride);
byte swap = image[index];
image[index] = image[index + 2];
image[index + 2] = swap;
}
}
}
for (var x = rect.X; x < x2; x++)
{
for (var y = rect.Y; y < y2; y++)
{
double r = 0;
double g = 0;
double b = 0;
if (x > kernelWidth && y > kernelHeight)
{
for (var t = 0; t < kernelWidth; t++)
{
for(var u = 0; u < kernelHeight; u++)
{
double k = kernel[t, u];
index = (Clamp(y + u, y2) * metadata.Stride) + (Clamp(x + t, x2) * metadata.Bpp);
r += image[index] * k;
g += image[index + 1] * k;
b += image[index + 2] * k;
}
}
r = (r < 0) ? 0 : r;
g = (g < 0) ? 0 : g;
b = (b < 0) ? 0 : b;
}
index = (x * metadata.Bpp) + (y * metadata.Stride);
image[index] = (byte)r;
image[index + 1] = (byte)g;
image[index + 2] = (byte)b;
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private int Clamp(int value, int maxIndex)
{
if (value < 0)
{
return 0;
}
if (value < maxIndex)
{
return value;
}
return maxIndex - 1;
}
private ImageContext CloneToRawBitmap(ImageContext sourceContext)
{
var newContext = new ImageContext
{
Raw = true,
Eos = sourceContext.Eos,
IFrame = sourceContext.IFrame,
Encoding = sourceContext.Encoding,
Pts = sourceContext.Pts,
StoreFormat = sourceContext.StoreFormat
};
using (var ms = new MemoryStream(sourceContext.Data))
{
using (var sourceBmp = new Bitmap(ms))
{
// sourceContext.Resolution isn't set by TakePicture (width,height is 0,0)
newContext.Resolution = new Resolution(sourceBmp.Width, sourceBmp.Height);
// If the source bitmap has a raw-compatible format, use it, otherwise default to RGBA
newContext.PixelFormat = PixelFormatToMMALEncoding(sourceBmp.PixelFormat, MMALEncoding.RGBA);
var bmpTargetFormat = MMALEncodingToPixelFormat(newContext.PixelFormat);
var rect = new Rectangle(0, 0, sourceBmp.Width, sourceBmp.Height);
using (var newBmp = sourceBmp.Clone(rect, bmpTargetFormat))
{
BitmapData bmpData = null;
try
{
bmpData = newBmp.LockBits(rect, ImageLockMode.ReadOnly, bmpTargetFormat);
var ptr = bmpData.Scan0;
int size = bmpData.Stride * newBmp.Height;
newContext.Data = new byte[size];
newContext.Stride = bmpData.Stride;
Marshal.Copy(ptr, newContext.Data, 0, size);
}
finally
{
newBmp.UnlockBits(bmpData);
}
}
}
}
return newContext;
}
private void FormatRawBitmap(ImageContext sourceContext, ImageContext targetContext)
{
var pixfmt = MMALEncodingToPixelFormat(sourceContext.PixelFormat);
using (var bitmap = new Bitmap(sourceContext.Resolution.Width, sourceContext.Resolution.Height, pixfmt))
{
BitmapData bmpData = null;
try
{
bmpData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, bitmap.PixelFormat);
var ptr = bmpData.Scan0;
int size = bmpData.Stride * bitmap.Height;
var data = sourceContext.Data;
Marshal.Copy(data, 0, ptr, size);
}
finally
{
bitmap.UnlockBits(bmpData);
}
using (var ms = new MemoryStream())
{
bitmap.Save(ms, targetContext.StoreFormat);
targetContext.Data = new byte[ms.Length];
Array.Copy(ms.ToArray(), 0, targetContext.Data, 0, ms.Length);
}
}
}
private PixelFormat MMALEncodingToPixelFormat(MMALEncoding encoding)
{
if (encoding == MMALEncoding.RGB24)
{
return PixelFormat.Format24bppRgb;
}
if (encoding == MMALEncoding.RGB32)
{
return PixelFormat.Format32bppRgb;
}
if (encoding == MMALEncoding.RGBA)
{
return PixelFormat.Format32bppArgb;
}
throw new Exception($"Unsupported pixel format: {encoding}");
}
private MMALEncoding PixelFormatToMMALEncoding(PixelFormat format, MMALEncoding defaultEncoding)
{
if (format == PixelFormat.Format24bppRgb)
{
return MMALEncoding.RGB24;
}
if (format == PixelFormat.Format32bppRgb)
{
return MMALEncoding.RGB32;
}
if (format == PixelFormat.Format32bppArgb)
{
return MMALEncoding.RGBA;
}
return defaultEncoding;
}
}
}
| |
//
// Copyright (c) 2004-2017 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Layouts
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Config;
/// <summary>
/// A specialized layout that renders JSON-formatted events.
/// </summary>
[Layout("JsonLayout")]
[ThreadAgnostic]
[AppDomainFixedOutput]
public class JsonLayout : Layout
{
private IJsonConverter JsonConverter
{
get => _jsonConverter ?? (_jsonConverter = ConfigurationItemFactory.Default.JsonConverter);
set => _jsonConverter = value;
}
private IJsonConverter _jsonConverter = null;
/// <summary>
/// Initializes a new instance of the <see cref="JsonLayout"/> class.
/// </summary>
public JsonLayout()
{
Attributes = new List<JsonAttribute>();
RenderEmptyObject = true;
IncludeAllProperties = false;
ExcludeProperties = new HashSet<string>();
}
/// <summary>
/// Gets the array of attributes' configurations.
/// </summary>
/// <docgen category='CSV Options' order='10' />
[ArrayParameter(typeof(JsonAttribute), "attribute")]
public IList<JsonAttribute> Attributes { get; private set; }
/// <summary>
/// Gets or sets the option to suppress the extra spaces in the output json
/// </summary>
public bool SuppressSpaces { get; set; }
/// <summary>
/// Gets or sets the option to render the empty object value {}
/// </summary>
public bool RenderEmptyObject { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to include contents of the <see cref="MappedDiagnosticsContext"/> dictionary.
/// </summary>
public bool IncludeMdc { get; set; }
#if !SILVERLIGHT
/// <summary>
/// Gets or sets a value indicating whether to include contents of the <see cref="MappedDiagnosticsLogicalContext"/> dictionary.
/// </summary>
public bool IncludeMdlc { get; set; }
#endif
/// <summary>
/// Gets or sets the option to include all properties from the log events
/// </summary>
public bool IncludeAllProperties { get; set; }
/// <summary>
/// List of property names to exclude when <see cref="IncludeAllProperties"/> is true
/// </summary>
#if NET3_5
public HashSet<string> ExcludeProperties { get; set; }
#else
public ISet<string> ExcludeProperties { get; set; }
#endif
/// <summary>
/// Initializes the layout.
/// </summary>
protected override void InitializeLayout()
{
base.InitializeLayout();
if (IncludeMdc)
{
ThreadAgnostic = false;
}
#if !SILVERLIGHT
if (IncludeMdlc)
{
ThreadAgnostic = false;
}
#endif
}
/// <summary>
/// Closes the layout.
/// </summary>
protected override void CloseLayout()
{
JsonConverter = null;
base.CloseLayout();
}
/// <summary>
/// Formats the log event as a JSON document for writing.
/// </summary>
/// <param name="logEvent">The logging event.</param>
/// <param name="target"><see cref="StringBuilder"/> for the result</param>
protected override void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target)
{
int orgLength = target.Length;
RenderJsonFormattedMessage(logEvent, target);
if (target.Length == orgLength && RenderEmptyObject)
{
target.Append(SuppressSpaces ? "{}" : "{ }");
}
}
/// <summary>
/// Formats the log event as a JSON document for writing.
/// </summary>
/// <param name="logEvent">The log event to be formatted.</param>
/// <returns>A JSON string representation of the log event.</returns>
protected override string GetFormattedMessage(LogEventInfo logEvent)
{
return RenderAllocateBuilder(logEvent);
}
private void RenderJsonFormattedMessage(LogEventInfo logEvent, StringBuilder sb)
{
int orgLength = sb.Length;
//Memory profiling pointed out that using a foreach-loop was allocating
//an Enumerator. Switching to a for-loop avoids the memory allocation.
for (int i = 0; i < Attributes.Count; i++)
{
var attrib = Attributes[i];
int beforeAttribLength = sb.Length;
if (!RenderAppendJsonPropertyValue(attrib, logEvent, false, sb, sb.Length == orgLength))
{
sb.Length = beforeAttribLength;
}
}
if (IncludeMdc)
{
foreach (string key in MappedDiagnosticsContext.GetNames())
{
if (string.IsNullOrEmpty(key))
continue;
object propertyValue = MappedDiagnosticsContext.GetObject(key);
AppendJsonPropertyValue(key, propertyValue, sb, sb.Length == orgLength);
}
}
#if !SILVERLIGHT
if (IncludeMdlc)
{
foreach (string key in MappedDiagnosticsLogicalContext.GetNames())
{
if (string.IsNullOrEmpty(key))
continue;
object propertyValue = MappedDiagnosticsLogicalContext.GetObject(key);
AppendJsonPropertyValue(key, propertyValue, sb, sb.Length == orgLength);
}
}
#endif
if (IncludeAllProperties && logEvent.HasProperties)
{
foreach (var prop in logEvent.Properties)
{
//Determine property name
string propName = Internal.XmlHelper.XmlConvertToString(prop.Key ?? string.Empty);
if (string.IsNullOrEmpty(propName))
continue;
//Skips properties in the ExcludeProperties list
if (ExcludeProperties.Contains(propName))
continue;
AppendJsonPropertyValue(propName, prop.Value, sb, sb.Length == orgLength);
}
}
if (sb.Length > orgLength)
CompleteJsonMessage(sb);
}
private void BeginJsonProperty(StringBuilder sb, string propName, bool beginJsonMessage)
{
if (beginJsonMessage)
{
sb.Append(SuppressSpaces ? "{" : "{ ");
}
else
{
sb.Append(',');
if (!SuppressSpaces)
sb.Append(' ');
}
sb.Append('"');
sb.Append(propName);
sb.Append('"');
sb.Append(':');
if (!SuppressSpaces)
sb.Append(' ');
}
private void CompleteJsonMessage(StringBuilder sb)
{
sb.Append(SuppressSpaces ? "}" : " }");
}
private void AppendJsonPropertyValue(string propName, object propertyValue, StringBuilder sb, bool beginJsonMessage)
{
BeginJsonProperty(sb, propName, beginJsonMessage);
JsonConverter.SerializeObject(propertyValue, sb);
}
private bool RenderAppendJsonPropertyValue(JsonAttribute attrib, LogEventInfo logEvent, bool renderEmptyValue, StringBuilder sb, bool beginJsonMessage)
{
BeginJsonProperty(sb, attrib.Name, beginJsonMessage);
if (attrib.Encode)
{
// "\"{0}\":{1}\"{2}\""
sb.Append('"');
}
int beforeValueLength = sb.Length;
attrib.LayoutWrapper.RenderAppendBuilder(logEvent, sb);
if (!renderEmptyValue && beforeValueLength == sb.Length)
{
return false;
}
if (attrib.Encode)
{
sb.Append('"');
}
return true;
}
/// <summary>
/// Generate description of JSON Layout
/// </summary>
/// <returns>JSON Layout String Description</returns>
public override string ToString()
{
return ToStringWithNestedItems(Attributes, a => string.Concat(a.Name, "-", a.Layout?.ToString()));
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="GZipStream.cs" company="XamlNinja">
// 2011 Richard Griffin and Ollie Riches
// </copyright>
// <summary>
// http://www.sharpgis.net/post/2011/08/28/GZIP-Compressed-Web-Requests-in-WP7-Take-2.aspx
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace WP7Contrib.Communications.Compression
{
using System;
using System.IO;
using System.Text;
internal class GZipStream : Stream
{
internal static DateTime _unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
internal static Encoding iso8859dash1 = Encoding.GetEncoding("iso-8859-1");
public DateTime? LastModified;
internal ZlibBaseStream _baseStream;
private bool _disposed;
private bool _firstReadDone;
private string _FileName;
private string _Comment;
private int _Crc32;
public string Comment
{
get
{
return this._Comment;
}
set
{
if (this._disposed)
throw new ObjectDisposedException("GZipStream");
this._Comment = value;
}
}
public string FileName
{
get
{
return this._FileName;
}
set
{
if (this._disposed)
throw new ObjectDisposedException("GZipStream");
this._FileName = value;
if (this._FileName == null)
return;
if (this._FileName.IndexOf("/") != -1)
this._FileName = this._FileName.Replace("/", "\\");
if (this._FileName.EndsWith("\\"))
throw new Exception("Illegal filename");
if (this._FileName.IndexOf("\\") == -1)
return;
this._FileName = Path.GetFileName(this._FileName);
}
}
public int Crc32
{
get
{
return this._Crc32;
}
}
public virtual FlushType FlushMode
{
get
{
return this._baseStream._flushMode;
}
set
{
if (this._disposed)
throw new ObjectDisposedException("GZipStream");
this._baseStream._flushMode = value;
}
}
public int BufferSize
{
get
{
return this._baseStream._bufferSize;
}
set
{
if (this._disposed)
throw new ObjectDisposedException("GZipStream");
if (this._baseStream._workingBuffer != null)
throw new ZlibException("The working buffer is already set.");
if (value < 128)
throw new ZlibException(string.Format("Don't be silly. {0} bytes?? Use a bigger buffer.", (object)value));
this._baseStream._bufferSize = value;
}
}
public virtual long TotalIn
{
get
{
return this._baseStream._z.TotalBytesIn;
}
}
public virtual long TotalOut
{
get
{
return this._baseStream._z.TotalBytesOut;
}
}
public override bool CanRead
{
get
{
if (this._disposed)
throw new ObjectDisposedException("GZipStream");
else
return this._baseStream._stream.CanRead;
}
}
public override bool CanSeek
{
get
{
return false;
}
}
public override bool CanWrite
{
get
{
if (this._disposed)
throw new ObjectDisposedException("GZipStream");
else
return this._baseStream._stream.CanWrite;
}
}
public override long Length
{
get
{
return this._baseStream.Length;
}
}
public override long Position
{
get
{
if (this._baseStream._streamMode == ZlibBaseStream.StreamMode.Reader)
return this._baseStream._z.TotalBytesIn + (long)this._baseStream._gzipHeaderByteCount;
else
return 0L;
}
set
{
throw new NotImplementedException();
}
}
static GZipStream()
{
}
public GZipStream(Stream stream)
{
this._baseStream = new ZlibBaseStream(stream, ZlibStreamFlavor.GZIP, false);
}
protected override void Dispose(bool disposing)
{
try
{
if (this._disposed)
return;
if (disposing && this._baseStream != null)
{
this._baseStream.Close();
this._Crc32 = this._baseStream.Crc32;
}
this._disposed = true;
}
finally
{
base.Dispose(disposing);
}
}
public override void Flush()
{
if (this._disposed)
throw new ObjectDisposedException("GZipStream");
this._baseStream.Flush();
}
public override int Read(byte[] buffer, int offset, int count)
{
if (this._disposed)
throw new ObjectDisposedException("GZipStream");
int num = this._baseStream.Read(buffer, offset, count);
if (!this._firstReadDone)
{
this._firstReadDone = true;
this.FileName = this._baseStream._GzipFileName;
this.Comment = this._baseStream._GzipComment;
}
return num;
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotImplementedException();
}
public override void SetLength(long value)
{
throw new NotImplementedException();
}
private int EmitHeader()
{
byte[] numArray1 = this.Comment == null ? (byte[])null : GZipStream.iso8859dash1.GetBytes(this.Comment);
byte[] numArray2 = this.FileName == null ? (byte[])null : GZipStream.iso8859dash1.GetBytes(this.FileName);
int num1 = this.Comment == null ? 0 : numArray1.Length + 1;
int num2 = this.FileName == null ? 0 : numArray2.Length + 1;
byte[] buffer = new byte[10 + num1 + num2];
int num3 = 0;
byte[] numArray3 = buffer;
int index1 = num3;
int num4 = 1;
int num5 = index1 + num4;
int num6 = 31;
numArray3[index1] = (byte)num6;
byte[] numArray4 = buffer;
int index2 = num5;
int num7 = 1;
int num8 = index2 + num7;
int num9 = 139;
numArray4[index2] = (byte)num9;
byte[] numArray5 = buffer;
int index3 = num8;
int num10 = 1;
int num11 = index3 + num10;
int num12 = 8;
numArray5[index3] = (byte)num12;
byte num13 = (byte)0;
if (this.Comment != null)
num13 ^= (byte)16;
if (this.FileName != null)
num13 ^= (byte)8;
byte[] numArray6 = buffer;
int index4 = num11;
int num14 = 1;
int destinationIndex1 = index4 + num14;
int num15 = (int)num13;
numArray6[index4] = (byte)num15;
if (!this.LastModified.HasValue)
this.LastModified = new DateTime?(DateTime.Now);
Array.Copy((Array)BitConverter.GetBytes((int)(this.LastModified.Value - GZipStream._unixEpoch).TotalSeconds), 0, (Array)buffer, destinationIndex1, 4);
int num16 = destinationIndex1 + 4;
byte[] numArray7 = buffer;
int index5 = num16;
int num17 = 1;
int num18 = index5 + num17;
int num19 = 0;
numArray7[index5] = (byte)num19;
byte[] numArray8 = buffer;
int index6 = num18;
int num20 = 1;
int destinationIndex2 = index6 + num20;
int num21 = (int)byte.MaxValue;
numArray8[index6] = (byte)num21;
if (num2 != 0)
{
Array.Copy((Array)numArray2, 0, (Array)buffer, destinationIndex2, num2 - 1);
int num22 = destinationIndex2 + (num2 - 1);
byte[] numArray9 = buffer;
int index7 = num22;
int num23 = 1;
destinationIndex2 = index7 + num23;
int num24 = 0;
numArray9[index7] = (byte)num24;
}
if (num1 != 0)
{
Array.Copy((Array)numArray1, 0, (Array)buffer, destinationIndex2, num1 - 1);
int num22 = destinationIndex2 + (num1 - 1);
byte[] numArray9 = buffer;
int index7 = num22;
int num23 = 1;
int num24 = index7 + num23;
int num25 = 0;
numArray9[index7] = (byte)num25;
}
this._baseStream._stream.Write(buffer, 0, buffer.Length);
return buffer.Length;
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
}
}
| |
using System;
using System.ComponentModel;
using Android.App;
using Android.OS;
using Android.Views;
using AView = Android.Views.View;
namespace Xamarin.Forms.Platform.Android
{
public abstract class ViewRenderer : ViewRenderer<View, AView>
{
}
public abstract class ViewRenderer<TView, TNativeView> : VisualElementRenderer<TView>, AView.IOnFocusChangeListener where TView : View where TNativeView : AView
{
protected virtual TNativeView CreateNativeControl()
{
return default(TNativeView);
}
ViewGroup _container;
bool _disposed;
EventHandler<VisualElement.FocusRequestArgs> _focusChangeHandler;
SoftInput _startingInputMode;
internal bool HandleKeyboardOnFocus;
public TNativeView Control { get; private set; }
void IOnFocusChangeListener.OnFocusChange(AView v, bool hasFocus)
{
if (Element is Entry || Element is SearchBar || Element is Editor)
{
var isInViewCell = false;
Element parent = Element.RealParent;
while (!(parent is Page) && parent != null)
{
if (parent is Cell)
{
isInViewCell = true;
break;
}
parent = parent.RealParent;
}
if (isInViewCell)
{
Window window = ((Activity)Context).Window;
if (hasFocus)
{
_startingInputMode = window.Attributes.SoftInputMode;
window.SetSoftInputMode(SoftInput.AdjustPan);
}
else
window.SetSoftInputMode(_startingInputMode);
}
}
OnNativeFocusChanged(hasFocus);
((IElementController)Element).SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, hasFocus);
}
public override SizeRequest GetDesiredSize(int widthConstraint, int heightConstraint)
{
//HACK: Seeing some places the renderer is disposed and this happens
if (Handle == IntPtr.Zero)
return new SizeRequest();
if (Control == null)
return (base.GetDesiredSize(widthConstraint, heightConstraint));
AView view = _container == this ? (AView)Control : _container;
//HACK: Seeing some places the view is disposed and this happens
if (view.Handle == IntPtr.Zero)
return new SizeRequest();
view.Measure(widthConstraint, heightConstraint);
return new SizeRequest(new Size(Control.MeasuredWidth, Control.MeasuredHeight), MinimumSize());
}
protected override void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
if (Control != null && ManageNativeControlLifetime)
{
Control.OnFocusChangeListener = null;
RemoveView(Control);
Control.Dispose();
Control = null;
}
if (_container != null && _container != this)
{
_container.RemoveFromParent();
_container.Dispose();
_container = null;
}
if (Element != null && _focusChangeHandler != null)
{
Element.FocusChangeRequested -= _focusChangeHandler;
_focusChangeHandler = null;
}
_disposed = true;
}
base.Dispose(disposing);
}
protected override void OnElementChanged(ElementChangedEventArgs<TView> e)
{
base.OnElementChanged(e);
if (_focusChangeHandler == null)
_focusChangeHandler = OnFocusChangeRequested;
if (e.OldElement != null)
e.OldElement.FocusChangeRequested -= _focusChangeHandler;
if (e.NewElement != null)
e.NewElement.FocusChangeRequested += _focusChangeHandler;
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == VisualElement.IsEnabledProperty.PropertyName)
UpdateIsEnabled();
}
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
base.OnLayout(changed, l, t, r, b);
if (Control == null)
return;
AView view = _container == this ? (AView)Control : _container;
view.Measure(MeasureSpecFactory.MakeMeasureSpec(r - l, MeasureSpecMode.Exactly), MeasureSpecFactory.MakeMeasureSpec(b - t, MeasureSpecMode.Exactly));
view.Layout(0, 0, r - l, b - t);
}
protected override void OnRegisterEffect(PlatformEffect effect)
{
base.OnRegisterEffect(effect);
effect.Control = Control;
}
protected override void SetAutomationId(string id)
{
if (Control == null)
base.SetAutomationId(id);
else
{
ContentDescription = id + "_Container";
Control.ContentDescription = id;
}
}
protected void SetNativeControl(TNativeView control)
{
SetNativeControl(control, this);
}
internal virtual void OnFocusChangeRequested(object sender, VisualElement.FocusRequestArgs e)
{
if (Control == null)
return;
e.Result = true;
if (e.Focus)
{
// use post being BeginInvokeOnMainThread will not delay on android
Looper looper = Context.MainLooper;
var handler = new Handler(looper);
handler.Post(() =>
{
Control?.RequestFocus();
});
}
else
{
Control.ClearFocus();
}
//handles keyboard on focus for Editor, Entry and SearchBar
if (HandleKeyboardOnFocus)
{
if (e.Focus)
Control.ShowKeyboard();
else
Control.HideKeyboard();
}
}
internal virtual void OnNativeFocusChanged(bool hasFocus)
{
}
internal override void SendVisualElementInitialized(VisualElement element, AView nativeView)
{
base.SendVisualElementInitialized(element, Control);
}
internal void SetNativeControl(TNativeView control, ViewGroup container)
{
if (Control != null)
{
Control.OnFocusChangeListener = null;
RemoveView(Control);
}
_container = container;
Control = control;
AView toAdd = container == this ? control : (AView)container;
AddView(toAdd, LayoutParams.MatchParent);
Control.OnFocusChangeListener = this;
UpdateIsEnabled();
}
void UpdateIsEnabled()
{
if (Control != null)
Control.Enabled = Element.IsEnabled;
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Xaml.Actipro.Code.Xaml.ActiproPublic
File: CodePanel.xaml.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Xaml.Actipro.Code
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using ActiproSoftware.Text;
using ActiproSoftware.Text.Languages.CSharp.Implementation;
using ActiproSoftware.Text.Languages.DotNet;
using ActiproSoftware.Text.Languages.DotNet.Reflection;
using ActiproSoftware.Windows.Controls.SyntaxEditor;
using Ecng.Collections;
using Ecng.Common;
using Ecng.Serialization;
using Ecng.Xaml;
using StockSharp.Logging;
using StockSharp.Localization;
using StockSharp.Xaml.Code;
/// <summary>
/// The visual panel for code editing and compiling.
/// </summary>
public partial class CodePanel : IPersistable
{
private class CompileResultItem
{
public CompilationErrorTypes Type { get; set; }
public int Line { get; set; }
public int Column { get; set; }
public string Message { get; set; }
}
/// <summary>
/// The command for the code compilation.
/// </summary>
public static RoutedCommand CompileCommand = new RoutedCommand();
/// <summary>
/// The command for the code saving.
/// </summary>
public static RoutedCommand SaveCommand = new RoutedCommand();
/// <summary>
/// The command for the references modification.
/// </summary>
public static RoutedCommand ReferencesCommand = new RoutedCommand();
/// <summary>
/// The command for undo the changes.
/// </summary>
public static RoutedCommand UndoCommand = new RoutedCommand();
/// <summary>
/// The command for return the changes.
/// </summary>
public static RoutedCommand RedoCommand = new RoutedCommand();
/// <summary>
/// <see cref="DependencyProperty"/> for <see cref="CodePanel.ShowToolBar"/>.
/// </summary>
public static readonly DependencyProperty ShowToolBarProperty = DependencyProperty.Register(nameof(ShowToolBar), typeof(bool), typeof(CodePanel), new PropertyMetadata(true));
/// <summary>
/// To show the review panel.
/// </summary>
public bool ShowToolBar
{
get { return (bool)GetValue(ShowToolBarProperty); }
set { SetValue(ShowToolBarProperty, value); }
}
private readonly IProjectAssembly _projectAssembly;
private readonly ObservableCollection<CompileResultItem> _errorsSource;
private static readonly SynchronizedDictionary<CodeReference, IProjectAssemblyReference> _references = new SynchronizedDictionary<CodeReference, IProjectAssemblyReference>();
/// <summary>
/// Initializes a new instance of the <see cref="CodePanel"/>.
/// </summary>
public CodePanel()
{
InitializeComponent();
_projectAssembly = new CSharpProjectAssembly("StockSharpStrategyCode");
_projectAssembly.AssemblyReferences.AddMsCorLib();
var language = new CSharpSyntaxLanguage();
language.RegisterProjectAssembly(_projectAssembly);
CodeEditor.Document.Language = language;
_errorsSource = new ObservableCollection<CompileResultItem>();
ErrorsGrid.ItemsSource = _errorsSource;
var references = new SynchronizedList<CodeReference>();
references.Added += r => _references.SafeAdd(r, r1 =>
{
IProjectAssemblyReference asmRef = null;
try
{
asmRef = _projectAssembly.AssemblyReferences.AddFrom(r1.Location);
}
catch (Exception ex)
{
ex.LogError();
}
return asmRef;
});
references.Removed += r =>
{
var item = _projectAssembly
.AssemblyReferences
.FirstOrDefault(p =>
{
var assm = p.Assembly as IBinaryAssembly;
if (assm == null)
return false;
return assm.Location == r.Location;
});
if (item != null)
_projectAssembly.AssemblyReferences.Remove(item);
};
references.Cleared += () =>
{
_projectAssembly.AssemblyReferences.Clear();
_projectAssembly.AssemblyReferences.AddMsCorLib();
};
References = references;
}
/// <summary>
/// Code.
/// </summary>
public string Code
{
get
{
CodeEditor.Document.IsModified = false;
return CodeEditor.Text;
}
set
{
CodeEditor.Text = value;
}
}
/// <summary>
/// References.
/// </summary>
public IList<CodeReference> References { get; }
/// <summary>
/// The links update event.
/// </summary>
public event Action ReferencesUpdated;
/// <summary>
/// The code compilation event.
/// </summary>
public event Action CompilingCode;
/// <summary>
/// The code saving event.
/// </summary>
public event Action SavingCode;
/// <summary>
/// The code change event.
/// </summary>
public event Action CodeChanged;
/// <summary>
/// The compilation possibility check event.
/// </summary>
public event Func<bool> CanCompile;
/// <summary>
/// To show the result of the compilation.
/// </summary>
/// <param name="result">The result of the compilation.</param>
/// <param name="isRunning">Whether the previously compiled code launched in the current moment.</param>
public void ShowCompilationResult(CompilationResult result, bool isRunning)
{
if (result == null)
throw new ArgumentNullException(nameof(result));
_errorsSource.Clear();
_errorsSource.AddRange(result.Errors.Select(error => new CompileResultItem
{
Type = error.Type,
Line = error.NativeError.Line,
Column = error.NativeError.Column,
Message = error.NativeError.ErrorText,
}));
if (_errorsSource.All(e => e.Type != CompilationErrorTypes.Error))
{
if (isRunning)
{
_errorsSource.Add(new CompileResultItem
{
Type = CompilationErrorTypes.Warning,
Message = LocalizedStrings.Str1420
});
}
_errorsSource.Add(new CompileResultItem
{
Type = CompilationErrorTypes.Info,
Message = LocalizedStrings.Str1421
});
}
}
/// <summary>
/// To edit links.
/// </summary>
public void EditReferences()
{
var window = new CodeReferencesWindow();
window.References.AddRange(References);
if (!window.ShowModal(this))
return;
var toAdd = window.References.Except(References);
var toRemove = References.Except(window.References);
References.RemoveRange(toRemove);
References.AddRange(toAdd);
ReferencesUpdated.SafeInvoke();
}
private void ExecutedSaveCommand(object sender, ExecutedRoutedEventArgs e)
{
SavingCode.SafeInvoke();
}
private void CanExecuteSaveCodeCommand(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = CodeEditor != null && CodeEditor.Document.IsModified;
}
private void ExecutedCompileCommand(object sender, ExecutedRoutedEventArgs e)
{
CompilingCode.SafeInvoke();
//var compiler = Compiler.Create(CodeLanguage, AssemblyPath, TempPath);
//CodeCompiled.SafeInvoke(compiler.Compile(AssemblyName, Code, References.Select(s => s.Location)));
}
private void ExecutedReferencesCommand(object sender, ExecutedRoutedEventArgs e)
{
EditReferences();
}
private void CanExecuteReferencesCommand(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void ErrorsGrid_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
var error = (CompileResultItem)ErrorsGrid.SelectedItem;
if (error == null)
return;
CodeEditor.ActiveView.Selection.StartPosition = new TextPosition(error.Line - 1, error.Column - 1);
CodeEditor.Focus();
}
/// <summary>
/// Load settings.
/// </summary>
/// <param name="storage">Settings storage.</param>
public void Load(SettingsStorage storage)
{
ErrorsGrid.Load(storage.GetValue<SettingsStorage>("ErrorsGrid"));
var layout = storage.GetValue<string>("Layout");
if (layout != null)
DockSite.LoadLayout(layout, true);
}
/// <summary>
/// Save settings.
/// </summary>
/// <param name="storage">Settings storage.</param>
public void Save(SettingsStorage storage)
{
storage.SetValue("ErrorsGrid", ErrorsGrid.Save());
storage.SetValue("Layout", DockSite.SaveLayout(true));
}
private void CanExecuteCompileCommand(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = CanCompile == null || CanCompile();
}
private void CodeEditor_OnDocumentTextChanged(object sender, EditorSnapshotChangedEventArgs e)
{
if (e.OldSnapshot.Text.IsEmpty())
return;
CodeChanged.SafeInvoke();
}
private void ExecutedUndoCommand(object sender, ExecutedRoutedEventArgs e)
{
CodeEditor.Document.UndoHistory.Undo();
}
private void CanExecuteUndoCommand(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = CodeEditor != null && CodeEditor.Document.UndoHistory.CanUndo;
}
private void ExecutedRedoCommand(object sender, ExecutedRoutedEventArgs e)
{
CodeEditor.Document.UndoHistory.Redo();
}
private void CanExecuteRedoCommand(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = CodeEditor != null && CodeEditor.Document.UndoHistory.CanRedo;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.WebSockets
{
internal sealed class WebSocketHttpListenerDuplexStream : Stream, WebSocketBase.IWebSocketStream
{
private static readonly EventHandler<HttpListenerAsyncEventArgs> s_OnReadCompleted =
new EventHandler<HttpListenerAsyncEventArgs>(OnReadCompleted);
private static readonly EventHandler<HttpListenerAsyncEventArgs> s_OnWriteCompleted =
new EventHandler<HttpListenerAsyncEventArgs>(OnWriteCompleted);
private static readonly Func<Exception, bool> s_CanHandleException = new Func<Exception, bool>(CanHandleException);
private static readonly Action<object> s_OnCancel = new Action<object>(OnCancel);
private readonly HttpRequestStream _inputStream;
private readonly HttpResponseStream _outputStream;
private readonly HttpListenerContext _context;
private bool _inOpaqueMode;
private WebSocketBase _webSocket;
private HttpListenerAsyncEventArgs _writeEventArgs;
private HttpListenerAsyncEventArgs _readEventArgs;
private TaskCompletionSource<object> _writeTaskCompletionSource;
private TaskCompletionSource<int> _readTaskCompletionSource;
private int _cleanedUp;
#if DEBUG
private class OutstandingOperations
{
internal int _reads;
internal int _writes;
}
private readonly OutstandingOperations _outstandingOperations = new OutstandingOperations();
#endif //DEBUG
public WebSocketHttpListenerDuplexStream(HttpRequestStream inputStream,
HttpResponseStream outputStream,
HttpListenerContext context)
{
Debug.Assert(inputStream != null, "'inputStream' MUST NOT be NULL.");
Debug.Assert(outputStream != null, "'outputStream' MUST NOT be NULL.");
Debug.Assert(context != null, "'context' MUST NOT be NULL.");
Debug.Assert(inputStream.CanRead, "'inputStream' MUST support read operations.");
Debug.Assert(outputStream.CanWrite, "'outputStream' MUST support write operations.");
_inputStream = inputStream;
_outputStream = outputStream;
_context = context;
if (NetEventSource.IsEnabled)
{
NetEventSource.Associate(inputStream, this);
NetEventSource.Associate(outputStream, this);
}
}
public override bool CanRead
{
get
{
return _inputStream.CanRead;
}
}
public override bool CanSeek
{
get
{
return false;
}
}
public override bool CanTimeout
{
get
{
return _inputStream.CanTimeout && _outputStream.CanTimeout;
}
}
public override bool CanWrite
{
get
{
return _outputStream.CanWrite;
}
}
public override long Length
{
get
{
throw new NotSupportedException(SR.net_noseek);
}
}
public override long Position
{
get
{
throw new NotSupportedException(SR.net_noseek);
}
set
{
throw new NotSupportedException(SR.net_noseek);
}
}
public override int Read(byte[] buffer, int offset, int count)
{
return _inputStream.Read(buffer, offset, count);
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
WebSocketValidate.ValidateBuffer(buffer, offset, count);
return ReadAsyncCore(buffer, offset, count, cancellationToken);
}
private async Task<int> ReadAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(this, HttpWebSocket.GetTraceMsgForParameters(offset, count, cancellationToken));
}
CancellationTokenRegistration cancellationTokenRegistration = new CancellationTokenRegistration();
int bytesRead = 0;
try
{
if (cancellationToken.CanBeCanceled)
{
cancellationTokenRegistration = cancellationToken.Register(s_OnCancel, this, false);
}
if (!_inOpaqueMode)
{
bytesRead = await _inputStream.ReadAsync(buffer, offset, count, cancellationToken).SuppressContextFlow<int>();
}
else
{
#if DEBUG
// When using fast path only one outstanding read is permitted. By switching into opaque mode
// via IWebSocketStream.SwitchToOpaqueMode (see more detailed comments in interface definition)
// caller takes responsibility for enforcing this constraint.
Debug.Assert(Interlocked.Increment(ref _outstandingOperations._reads) == 1,
"Only one outstanding read allowed at any given time.");
#endif
_readTaskCompletionSource = new TaskCompletionSource<int>();
_readEventArgs.SetBuffer(buffer, offset, count);
if (!ReadAsyncFast(_readEventArgs))
{
if (_readEventArgs.Exception != null)
{
throw _readEventArgs.Exception;
}
bytesRead = _readEventArgs.BytesTransferred;
}
else
{
bytesRead = await _readTaskCompletionSource.Task.SuppressContextFlow<int>();
}
}
}
catch (Exception error)
{
if (s_CanHandleException(error))
{
cancellationToken.ThrowIfCancellationRequested();
}
throw;
}
finally
{
cancellationTokenRegistration.Dispose();
if (NetEventSource.IsEnabled)
{
NetEventSource.Exit(this, bytesRead);
}
}
return bytesRead;
}
// return value indicates sync vs async completion
// false: sync completion
// true: async completion or error
private unsafe bool ReadAsyncFast(HttpListenerAsyncEventArgs eventArgs)
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(this);
}
eventArgs.StartOperationCommon(this, _inputStream.InternalHttpContext.RequestQueueBoundHandle);
eventArgs.StartOperationReceive();
uint statusCode = 0;
bool completedAsynchronouslyOrWithError = false;
try
{
Debug.Assert(eventArgs.Buffer != null, "'BufferList' is not supported for read operations.");
if (eventArgs.Count == 0 || _inputStream.Closed)
{
eventArgs.FinishOperationSuccess(0, true);
return false;
}
uint dataRead = 0;
int offset = eventArgs.Offset;
int remainingCount = eventArgs.Count;
if (_inputStream.BufferedDataChunksAvailable)
{
dataRead = _inputStream.GetChunks(eventArgs.Buffer, eventArgs.Offset, eventArgs.Count);
if (_inputStream.BufferedDataChunksAvailable && dataRead == eventArgs.Count)
{
eventArgs.FinishOperationSuccess(eventArgs.Count, true);
return false;
}
}
Debug.Assert(!_inputStream.BufferedDataChunksAvailable, "'m_InputStream.BufferedDataChunksAvailable' MUST BE 'FALSE' at this point.");
Debug.Assert(dataRead <= eventArgs.Count, "'dataRead' MUST NOT be bigger than 'eventArgs.Count'.");
if (dataRead != 0)
{
offset += (int)dataRead;
remainingCount -= (int)dataRead;
//the http.sys team recommends that we limit the size to 128kb
if (remainingCount > HttpRequestStream.MaxReadSize)
{
remainingCount = HttpRequestStream.MaxReadSize;
}
eventArgs.SetBuffer(eventArgs.Buffer, offset, remainingCount);
}
else if (remainingCount > HttpRequestStream.MaxReadSize)
{
remainingCount = HttpRequestStream.MaxReadSize;
eventArgs.SetBuffer(eventArgs.Buffer, offset, remainingCount);
}
uint flags = 0;
uint bytesReturned = 0;
statusCode =
Interop.HttpApi.HttpReceiveRequestEntityBody(
_inputStream.InternalHttpContext.RequestQueueHandle,
_inputStream.InternalHttpContext.RequestId,
flags,
(byte*)_webSocket.InternalBuffer.ToIntPtr(eventArgs.Offset),
(uint)eventArgs.Count,
out bytesReturned,
eventArgs.NativeOverlapped);
if (statusCode != Interop.HttpApi.ERROR_SUCCESS &&
statusCode != Interop.HttpApi.ERROR_IO_PENDING &&
statusCode != Interop.HttpApi.ERROR_HANDLE_EOF)
{
throw new HttpListenerException((int)statusCode);
}
else if (statusCode == Interop.HttpApi.ERROR_SUCCESS &&
HttpListener.SkipIOCPCallbackOnSuccess)
{
// IO operation completed synchronously. No IO completion port callback is used because
// it was disabled in SwitchToOpaqueMode()
eventArgs.FinishOperationSuccess((int)bytesReturned, true);
completedAsynchronouslyOrWithError = false;
}
else
{
completedAsynchronouslyOrWithError = true;
}
}
catch (Exception e)
{
_readEventArgs.FinishOperationFailure(e, true);
_outputStream.SetClosedFlag();
_outputStream.InternalHttpContext.Abort();
completedAsynchronouslyOrWithError = true;
}
finally
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Exit(this, completedAsynchronouslyOrWithError);
}
}
return completedAsynchronouslyOrWithError;
}
public override int ReadByte()
{
return _inputStream.ReadByte();
}
public bool SupportsMultipleWrite
{
get
{
return true;
}
}
public override IAsyncResult BeginRead(byte[] buffer,
int offset,
int count,
AsyncCallback callback,
object state)
{
return _inputStream.BeginRead(buffer, offset, count, callback, state);
}
public override int EndRead(IAsyncResult asyncResult)
{
return _inputStream.EndRead(asyncResult);
}
public Task MultipleWriteAsync(IList<ArraySegment<byte>> sendBuffers, CancellationToken cancellationToken)
{
Debug.Assert(_inOpaqueMode, "The stream MUST be in opaque mode at this point.");
Debug.Assert(sendBuffers != null, "'sendBuffers' MUST NOT be NULL.");
Debug.Assert(sendBuffers.Count == 1 || sendBuffers.Count == 2,
"'sendBuffers.Count' MUST be either '1' or '2'.");
if (sendBuffers.Count == 1)
{
ArraySegment<byte> buffer = sendBuffers[0];
return WriteAsync(buffer.Array, buffer.Offset, buffer.Count, cancellationToken);
}
return MultipleWriteAsyncCore(sendBuffers, cancellationToken);
}
private async Task MultipleWriteAsyncCore(IList<ArraySegment<byte>> sendBuffers, CancellationToken cancellationToken)
{
Debug.Assert(sendBuffers != null, "'sendBuffers' MUST NOT be NULL.");
Debug.Assert(sendBuffers.Count == 2, "'sendBuffers.Count' MUST be '2' at this point.");
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(this);
}
CancellationTokenRegistration cancellationTokenRegistration = new CancellationTokenRegistration();
try
{
if (cancellationToken.CanBeCanceled)
{
cancellationTokenRegistration = cancellationToken.Register(s_OnCancel, this, false);
}
#if DEBUG
// When using fast path only one outstanding read is permitted. By switching into opaque mode
// via IWebSocketStream.SwitchToOpaqueMode (see more detailed comments in interface definition)
// caller takes responsibility for enforcing this constraint.
Debug.Assert(Interlocked.Increment(ref _outstandingOperations._writes) == 1,
"Only one outstanding write allowed at any given time.");
#endif
_writeTaskCompletionSource = new TaskCompletionSource<object>();
_writeEventArgs.SetBuffer(null, 0, 0);
_writeEventArgs.BufferList = sendBuffers;
if (WriteAsyncFast(_writeEventArgs))
{
await _writeTaskCompletionSource.Task.SuppressContextFlow();
}
}
catch (Exception error)
{
if (s_CanHandleException(error))
{
cancellationToken.ThrowIfCancellationRequested();
}
throw;
}
finally
{
cancellationTokenRegistration.Dispose();
if (NetEventSource.IsEnabled)
{
NetEventSource.Exit(this);
}
}
}
public override void Write(byte[] buffer, int offset, int count)
{
_outputStream.Write(buffer, offset, count);
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
WebSocketValidate.ValidateBuffer(buffer, offset, count);
return WriteAsyncCore(buffer, offset, count, cancellationToken);
}
private async Task WriteAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(this, HttpWebSocket.GetTraceMsgForParameters(offset, count, cancellationToken));
}
CancellationTokenRegistration cancellationTokenRegistration = new CancellationTokenRegistration();
try
{
if (cancellationToken.CanBeCanceled)
{
cancellationTokenRegistration = cancellationToken.Register(s_OnCancel, this, false);
}
if (!_inOpaqueMode)
{
await _outputStream.WriteAsync(buffer, offset, count, cancellationToken).SuppressContextFlow();
}
else
{
#if DEBUG
// When using fast path only one outstanding read is permitted. By switching into opaque mode
// via IWebSocketStream.SwitchToOpaqueMode (see more detailed comments in interface definition)
// caller takes responsibility for enforcing this constraint.
Debug.Assert(Interlocked.Increment(ref _outstandingOperations._writes) == 1,
"Only one outstanding write allowed at any given time.");
#endif
_writeTaskCompletionSource = new TaskCompletionSource<object>();
_writeEventArgs.BufferList = null;
_writeEventArgs.SetBuffer(buffer, offset, count);
if (WriteAsyncFast(_writeEventArgs))
{
await _writeTaskCompletionSource.Task.SuppressContextFlow();
}
}
}
catch (Exception error)
{
if (s_CanHandleException(error))
{
cancellationToken.ThrowIfCancellationRequested();
}
throw;
}
finally
{
cancellationTokenRegistration.Dispose();
if (NetEventSource.IsEnabled)
{
NetEventSource.Exit(this);
}
}
}
// return value indicates sync vs async completion
// false: sync completion
// true: async completion or with error
private unsafe bool WriteAsyncFast(HttpListenerAsyncEventArgs eventArgs)
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(this);
}
Interop.HttpApi.HTTP_FLAGS flags = Interop.HttpApi.HTTP_FLAGS.NONE;
eventArgs.StartOperationCommon(this, _outputStream.InternalHttpContext.RequestQueueBoundHandle);
eventArgs.StartOperationSend();
uint statusCode;
bool completedAsynchronouslyOrWithError = false;
try
{
if (_outputStream.Closed ||
(eventArgs.Buffer != null && eventArgs.Count == 0))
{
eventArgs.FinishOperationSuccess(eventArgs.Count, true);
return false;
}
if (eventArgs.ShouldCloseOutput)
{
flags |= Interop.HttpApi.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_DISCONNECT;
}
else
{
flags |= Interop.HttpApi.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_MORE_DATA;
// When using HTTP_SEND_RESPONSE_FLAG_BUFFER_DATA HTTP.SYS will copy the payload to
// kernel memory (Non-Paged Pool). Http.Sys will buffer up to
// Math.Min(16 MB, current TCP window size)
flags |= Interop.HttpApi.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_BUFFER_DATA;
}
uint bytesSent;
statusCode =
Interop.HttpApi.HttpSendResponseEntityBody(
_outputStream.InternalHttpContext.RequestQueueHandle,
_outputStream.InternalHttpContext.RequestId,
(uint)flags,
eventArgs.EntityChunkCount,
(Interop.HttpApi.HTTP_DATA_CHUNK*)eventArgs.EntityChunks,
&bytesSent,
SafeLocalAllocHandle.Zero,
0,
eventArgs.NativeOverlapped,
null);
if (statusCode != Interop.HttpApi.ERROR_SUCCESS &&
statusCode != Interop.HttpApi.ERROR_IO_PENDING)
{
throw new HttpListenerException((int)statusCode);
}
else if (statusCode == Interop.HttpApi.ERROR_SUCCESS &&
HttpListener.SkipIOCPCallbackOnSuccess)
{
// IO operation completed synchronously - callback won't be called to signal completion.
eventArgs.FinishOperationSuccess((int)bytesSent, true);
completedAsynchronouslyOrWithError = false;
}
else
{
completedAsynchronouslyOrWithError = true;
}
}
catch (Exception e)
{
_writeEventArgs.FinishOperationFailure(e, true);
_outputStream.SetClosedFlag();
_outputStream.InternalHttpContext.Abort();
completedAsynchronouslyOrWithError = true;
}
finally
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Exit(this, completedAsynchronouslyOrWithError);
}
}
return completedAsynchronouslyOrWithError;
}
public override void WriteByte(byte value)
{
_outputStream.WriteByte(value);
}
public override IAsyncResult BeginWrite(byte[] buffer,
int offset,
int count,
AsyncCallback callback,
object state)
{
return _outputStream.BeginWrite(buffer, offset, count, callback, state);
}
public override void EndWrite(IAsyncResult asyncResult)
{
_outputStream.EndWrite(asyncResult);
}
public override void Flush()
{
_outputStream.Flush();
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
return _outputStream.FlushAsync(cancellationToken);
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException(SR.net_noseek);
}
public override void SetLength(long value)
{
throw new NotSupportedException(SR.net_noseek);
}
public async Task CloseNetworkConnectionAsync(CancellationToken cancellationToken)
{
// need to yield here to make sure that we don't get any exception synchronously
await Task.Yield();
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(this);
}
CancellationTokenRegistration cancellationTokenRegistration = new CancellationTokenRegistration();
try
{
if (cancellationToken.CanBeCanceled)
{
cancellationTokenRegistration = cancellationToken.Register(s_OnCancel, this, false);
}
#if DEBUG
// When using fast path only one outstanding read is permitted. By switching into opaque mode
// via IWebSocketStream.SwitchToOpaqueMode (see more detailed comments in interface definition)
// caller takes responsibility for enforcing this constraint.
Debug.Assert(Interlocked.Increment(ref _outstandingOperations._writes) == 1,
"Only one outstanding write allowed at any given time.");
#endif
_writeTaskCompletionSource = new TaskCompletionSource<object>();
_writeEventArgs.SetShouldCloseOutput();
if (WriteAsyncFast(_writeEventArgs))
{
await _writeTaskCompletionSource.Task.SuppressContextFlow();
}
}
catch (Exception error)
{
if (!s_CanHandleException(error))
{
throw;
}
// throw OperationCancelledException when canceled by the caller
// otherwise swallow the exception
cancellationToken.ThrowIfCancellationRequested();
}
finally
{
cancellationTokenRegistration.Dispose();
if (NetEventSource.IsEnabled)
{
NetEventSource.Exit(this);
}
}
}
protected override void Dispose(bool disposing)
{
if (disposing && Interlocked.Exchange(ref _cleanedUp, 1) == 0)
{
if (_readTaskCompletionSource != null)
{
_readTaskCompletionSource.TrySetCanceled();
}
if (_writeTaskCompletionSource != null)
{
_writeTaskCompletionSource.TrySetCanceled();
}
if (_readEventArgs != null)
{
_readEventArgs.Dispose();
}
if (_writeEventArgs != null)
{
_writeEventArgs.Dispose();
}
try
{
_inputStream.Close();
}
finally
{
_outputStream.Close();
}
}
}
public void Abort()
{
OnCancel(this);
}
private static bool CanHandleException(Exception error)
{
return error is HttpListenerException ||
error is ObjectDisposedException ||
error is IOException;
}
private static void OnCancel(object state)
{
Debug.Assert(state != null, "'state' MUST NOT be NULL.");
WebSocketHttpListenerDuplexStream thisPtr = state as WebSocketHttpListenerDuplexStream;
Debug.Assert(thisPtr != null, "'thisPtr' MUST NOT be NULL.");
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(state);
}
try
{
thisPtr._outputStream.SetClosedFlag();
thisPtr._context.Abort();
}
catch { }
TaskCompletionSource<int> readTaskCompletionSourceSnapshot = thisPtr._readTaskCompletionSource;
if (readTaskCompletionSourceSnapshot != null)
{
readTaskCompletionSourceSnapshot.TrySetCanceled();
}
TaskCompletionSource<object> writeTaskCompletionSourceSnapshot = thisPtr._writeTaskCompletionSource;
if (writeTaskCompletionSourceSnapshot != null)
{
writeTaskCompletionSourceSnapshot.TrySetCanceled();
}
if (NetEventSource.IsEnabled)
{
NetEventSource.Exit(state);
}
}
public void SwitchToOpaqueMode(WebSocketBase webSocket)
{
Debug.Assert(webSocket != null, "'webSocket' MUST NOT be NULL.");
Debug.Assert(_outputStream != null, "'m_OutputStream' MUST NOT be NULL.");
Debug.Assert(_outputStream.InternalHttpContext != null,
"'m_OutputStream.InternalHttpContext' MUST NOT be NULL.");
Debug.Assert(_outputStream.InternalHttpContext.Response != null,
"'m_OutputStream.InternalHttpContext.Response' MUST NOT be NULL.");
Debug.Assert(_outputStream.InternalHttpContext.Response.SentHeaders,
"Headers MUST have been sent at this point.");
Debug.Assert(!_inOpaqueMode, "SwitchToOpaqueMode MUST NOT be called multiple times.");
if (_inOpaqueMode)
{
throw new InvalidOperationException();
}
_webSocket = webSocket;
_inOpaqueMode = true;
_readEventArgs = new HttpListenerAsyncEventArgs(webSocket, this);
_readEventArgs.Completed += s_OnReadCompleted;
_writeEventArgs = new HttpListenerAsyncEventArgs(webSocket, this);
_writeEventArgs.Completed += s_OnWriteCompleted;
if (NetEventSource.IsEnabled)
{
NetEventSource.Associate(this, webSocket);
}
}
private static void OnWriteCompleted(object sender, HttpListenerAsyncEventArgs eventArgs)
{
Debug.Assert(eventArgs != null, "'eventArgs' MUST NOT be NULL.");
WebSocketHttpListenerDuplexStream thisPtr = eventArgs.CurrentStream;
Debug.Assert(thisPtr != null, "'thisPtr' MUST NOT be NULL.");
#if DEBUG
Debug.Assert(Interlocked.Decrement(ref thisPtr._outstandingOperations._writes) >= 0,
"'thisPtr.m_OutstandingOperations.m_Writes' MUST NOT be negative.");
#endif
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(thisPtr);
}
if (eventArgs.Exception != null)
{
thisPtr._writeTaskCompletionSource.TrySetException(eventArgs.Exception);
}
else
{
thisPtr._writeTaskCompletionSource.TrySetResult(null);
}
if (NetEventSource.IsEnabled)
{
NetEventSource.Exit(thisPtr);
}
}
private static void OnReadCompleted(object sender, HttpListenerAsyncEventArgs eventArgs)
{
Debug.Assert(eventArgs != null, "'eventArgs' MUST NOT be NULL.");
WebSocketHttpListenerDuplexStream thisPtr = eventArgs.CurrentStream;
Debug.Assert(thisPtr != null, "'thisPtr' MUST NOT be NULL.");
#if DEBUG
Debug.Assert(Interlocked.Decrement(ref thisPtr._outstandingOperations._reads) >= 0,
"'thisPtr.m_OutstandingOperations.m_Reads' MUST NOT be negative.");
#endif
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(thisPtr);
}
if (eventArgs.Exception != null)
{
thisPtr._readTaskCompletionSource.TrySetException(eventArgs.Exception);
}
else
{
thisPtr._readTaskCompletionSource.TrySetResult(eventArgs.BytesTransferred);
}
if (NetEventSource.IsEnabled)
{
NetEventSource.Exit(thisPtr);
}
}
internal class HttpListenerAsyncEventArgs : EventArgs, IDisposable
{
private const int Free = 0;
private const int InProgress = 1;
private const int Disposed = 2;
private int _operating;
private bool _disposeCalled;
private unsafe NativeOverlapped* _ptrNativeOverlapped;
private ThreadPoolBoundHandle _boundHandle;
private event EventHandler<HttpListenerAsyncEventArgs> m_Completed;
private byte[] _buffer;
private IList<ArraySegment<byte>> _bufferList;
private int _count;
private int _offset;
private int _bytesTransferred;
private HttpListenerAsyncOperation _completedOperation;
private Interop.HttpApi.HTTP_DATA_CHUNK[] _dataChunks;
private GCHandle _dataChunksGCHandle;
private ushort _dataChunkCount;
private Exception _exception;
private bool _shouldCloseOutput;
private readonly WebSocketBase _webSocket;
private readonly WebSocketHttpListenerDuplexStream _currentStream;
#if DEBUG
private volatile int _nativeOverlappedCounter = 0;
private volatile int _nativeOverlappedUsed = 0;
private void DebugRefCountReleaseNativeOverlapped()
{
Debug.Assert(Interlocked.Decrement(ref _nativeOverlappedCounter) == 0, "NativeOverlapped released too many times.");
Interlocked.Decrement(ref _nativeOverlappedUsed);
}
private void DebugRefCountAllocNativeOverlapped()
{
Debug.Assert(Interlocked.Increment(ref _nativeOverlappedCounter) == 1, "NativeOverlapped allocated without release.");
}
#endif
public HttpListenerAsyncEventArgs(WebSocketBase webSocket, WebSocketHttpListenerDuplexStream stream)
: base()
{
_webSocket = webSocket;
_currentStream = stream;
}
public int BytesTransferred
{
get { return _bytesTransferred; }
}
public byte[] Buffer
{
get { return _buffer; }
}
// BufferList property.
// Mutually exclusive with Buffer.
// Setting this property with an existing non-null Buffer will cause an assert.
public IList<ArraySegment<byte>> BufferList
{
get { return _bufferList; }
set
{
Debug.Assert(!_shouldCloseOutput, "'m_ShouldCloseOutput' MUST be 'false' at this point.");
Debug.Assert(value == null || _buffer == null,
"Either 'm_Buffer' or 'm_BufferList' MUST be NULL.");
Debug.Assert(_operating == Free,
"This property can only be modified if no IO operation is outstanding.");
Debug.Assert(value == null || value.Count == 2,
"This list can only be 'NULL' or MUST have exactly '2' items.");
_bufferList = value;
}
}
public bool ShouldCloseOutput
{
get { return _shouldCloseOutput; }
}
public int Offset
{
get { return _offset; }
}
public int Count
{
get { return _count; }
}
public Exception Exception
{
get { return _exception; }
}
public ushort EntityChunkCount
{
get
{
if (_dataChunks == null)
{
return 0;
}
return _dataChunkCount;
}
}
internal unsafe NativeOverlapped* NativeOverlapped
{
get
{
#if DEBUG
Debug.Assert(Interlocked.Increment(ref _nativeOverlappedUsed) == 1, "NativeOverlapped reused.");
#endif
return _ptrNativeOverlapped;
}
}
public IntPtr EntityChunks
{
get
{
if (_dataChunks == null)
{
return IntPtr.Zero;
}
return Marshal.UnsafeAddrOfPinnedArrayElement(_dataChunks, 0);
}
}
public WebSocketHttpListenerDuplexStream CurrentStream
{
get { return _currentStream; }
}
public event EventHandler<HttpListenerAsyncEventArgs> Completed
{
add
{
m_Completed += value;
}
remove
{
m_Completed -= value;
}
}
protected virtual void OnCompleted(HttpListenerAsyncEventArgs e)
{
m_Completed?.Invoke(e._currentStream, e);
}
public void SetShouldCloseOutput()
{
_bufferList = null;
_buffer = null;
_shouldCloseOutput = true;
}
public void Dispose()
{
// Remember that Dispose was called.
_disposeCalled = true;
// Check if this object is in-use for an async socket operation.
if (Interlocked.CompareExchange(ref _operating, Disposed, Free) != Free)
{
// Either already disposed or will be disposed when current operation completes.
return;
}
// Don't bother finalizing later.
GC.SuppressFinalize(this);
}
private unsafe void InitializeOverlapped(ThreadPoolBoundHandle boundHandle)
{
#if DEBUG
DebugRefCountAllocNativeOverlapped();
#endif
_boundHandle = boundHandle;
_ptrNativeOverlapped = boundHandle.AllocateNativeOverlapped(CompletionPortCallback, null, null);
}
// Method to clean up any existing Overlapped object and related state variables.
private unsafe void FreeOverlapped(bool checkForShutdown)
{
if (!checkForShutdown || !Environment.HasShutdownStarted)
{
// Free the overlapped object
if (_ptrNativeOverlapped != null)
{
#if DEBUG
DebugRefCountReleaseNativeOverlapped();
#endif
_boundHandle.FreeNativeOverlapped(_ptrNativeOverlapped);
_ptrNativeOverlapped = null;
}
if (_dataChunksGCHandle.IsAllocated)
{
_dataChunksGCHandle.Free();
_dataChunks = null;
}
}
}
// Method called to prepare for a native async http.sys call.
// This method performs the tasks common to all http.sys operations.
internal void StartOperationCommon(WebSocketHttpListenerDuplexStream currentStream, ThreadPoolBoundHandle boundHandle)
{
// Change status to "in-use".
if (Interlocked.CompareExchange(ref _operating, InProgress, Free) != Free)
{
// If it was already "in-use" check if Dispose was called.
if (_disposeCalled)
{
// Dispose was called - throw ObjectDisposed.
throw new ObjectDisposedException(GetType().FullName);
}
Debug.Fail("Only one outstanding async operation is allowed per HttpListenerAsyncEventArgs instance.");
// Only one at a time.
throw new InvalidOperationException();
}
// HttpSendResponseEntityBody can return ERROR_INVALID_PARAMETER if the InternalHigh field of the overlapped
// is not IntPtr.Zero, so we have to reset this field because we are reusing the Overlapped.
// When using the IAsyncResult based approach of HttpListenerResponseStream the Overlapped is reinitialized
// for each operation by the CLR when returned from the OverlappedDataCache.
InitializeOverlapped(boundHandle);
_exception = null;
_bytesTransferred = 0;
}
internal void StartOperationReceive()
{
// Remember the operation type.
_completedOperation = HttpListenerAsyncOperation.Receive;
}
internal void StartOperationSend()
{
UpdateDataChunk();
// Remember the operation type.
_completedOperation = HttpListenerAsyncOperation.Send;
}
public void SetBuffer(byte[] buffer, int offset, int count)
{
Debug.Assert(!_shouldCloseOutput, "'m_ShouldCloseOutput' MUST be 'false' at this point.");
Debug.Assert(buffer == null || _bufferList == null, "Either 'm_Buffer' or 'm_BufferList' MUST be NULL.");
_buffer = buffer;
_offset = offset;
_count = count;
}
private unsafe void UpdateDataChunk()
{
if (_dataChunks == null)
{
_dataChunks = new Interop.HttpApi.HTTP_DATA_CHUNK[2];
_dataChunksGCHandle = GCHandle.Alloc(_dataChunks, GCHandleType.Pinned);
_dataChunks[0] = new Interop.HttpApi.HTTP_DATA_CHUNK();
_dataChunks[0].DataChunkType = Interop.HttpApi.HTTP_DATA_CHUNK_TYPE.HttpDataChunkFromMemory;
_dataChunks[1] = new Interop.HttpApi.HTTP_DATA_CHUNK();
_dataChunks[1].DataChunkType = Interop.HttpApi.HTTP_DATA_CHUNK_TYPE.HttpDataChunkFromMemory;
}
Debug.Assert(_buffer == null || _bufferList == null, "Either 'm_Buffer' or 'm_BufferList' MUST be NULL.");
Debug.Assert(_shouldCloseOutput || _buffer != null || _bufferList != null, "Either 'm_Buffer' or 'm_BufferList' MUST NOT be NULL.");
// The underlying byte[] m_Buffer or each m_BufferList[].Array are pinned already
if (_buffer != null)
{
UpdateDataChunk(0, _buffer, _offset, _count);
UpdateDataChunk(1, null, 0, 0);
_dataChunkCount = 1;
}
else if (_bufferList != null)
{
Debug.Assert(_bufferList != null && _bufferList.Count == 2,
"'m_BufferList' MUST NOT be NULL and have exactly '2' items at this point.");
UpdateDataChunk(0, _bufferList[0].Array, _bufferList[0].Offset, _bufferList[0].Count);
UpdateDataChunk(1, _bufferList[1].Array, _bufferList[1].Offset, _bufferList[1].Count);
_dataChunkCount = 2;
}
else
{
Debug.Assert(_shouldCloseOutput, "'m_ShouldCloseOutput' MUST be 'true' at this point.");
_dataChunks = null;
}
}
private unsafe void UpdateDataChunk(int index, byte[] buffer, int offset, int count)
{
if (buffer == null)
{
_dataChunks[index].pBuffer = null;
_dataChunks[index].BufferLength = 0;
return;
}
if (_webSocket.InternalBuffer.IsInternalBuffer(buffer, offset, count))
{
_dataChunks[index].pBuffer = (byte*)(_webSocket.InternalBuffer.ToIntPtr(offset));
}
else
{
_dataChunks[index].pBuffer =
(byte*)_webSocket.InternalBuffer.ConvertPinnedSendPayloadToNative(buffer, offset, count);
}
_dataChunks[index].BufferLength = (uint)count;
}
// Method to mark this object as no longer "in-use".
// Will also execute a Dispose deferred because I/O was in progress.
internal void Complete()
{
FreeOverlapped(false);
// Mark as not in-use
Interlocked.Exchange(ref _operating, Free);
// Check for deferred Dispose().
// The deferred Dispose is not guaranteed if Dispose is called while an operation is in progress.
// The m_DisposeCalled variable is not managed in a thread-safe manner on purpose for performance.
if (_disposeCalled)
{
Dispose();
}
}
// Method to update internal state after sync or async completion.
private void SetResults(Exception exception, int bytesTransferred)
{
_exception = exception;
_bytesTransferred = bytesTransferred;
}
internal void FinishOperationFailure(Exception exception, bool syncCompletion)
{
SetResults(exception, 0);
if (NetEventSource.IsEnabled)
{
string methodName = _completedOperation == HttpListenerAsyncOperation.Receive ? nameof(ReadAsyncFast) : nameof(WriteAsyncFast);
NetEventSource.Error(_currentStream, $"{methodName} {exception.ToString()}");
}
Complete();
OnCompleted(this);
}
internal void FinishOperationSuccess(int bytesTransferred, bool syncCompletion)
{
SetResults(null, bytesTransferred);
if (NetEventSource.IsEnabled)
{
if (_buffer != null && NetEventSource.IsEnabled)
{
string methodName = _completedOperation == HttpListenerAsyncOperation.Receive ? nameof(ReadAsyncFast) : nameof(WriteAsyncFast);
NetEventSource.DumpBuffer(_currentStream, _buffer, _offset, bytesTransferred, methodName);
}
else if (_bufferList != null)
{
Debug.Assert(_completedOperation == HttpListenerAsyncOperation.Send,
"'BufferList' is only supported for send operations.");
foreach (ArraySegment<byte> buffer in BufferList)
{
NetEventSource.DumpBuffer(this, buffer.Array, buffer.Offset, buffer.Count, nameof(WriteAsyncFast));
}
}
}
if (_shouldCloseOutput)
{
_currentStream._outputStream.SetClosedFlag();
}
// Complete the operation and raise completion event.
Complete();
OnCompleted(this);
}
private unsafe void CompletionPortCallback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped)
{
if (errorCode == Interop.HttpApi.ERROR_SUCCESS ||
errorCode == Interop.HttpApi.ERROR_HANDLE_EOF)
{
FinishOperationSuccess((int)numBytes, false);
}
else
{
FinishOperationFailure(new HttpListenerException((int)errorCode), false);
}
}
public enum HttpListenerAsyncOperation
{
None,
Receive,
Send
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.PropertyEditors;
using Umbraco.Core.Strings;
using Umbraco.Web.Composing;
using Umbraco.Web.Editors;
using Umbraco.Web.Routing;
namespace Umbraco.Web.Macros
{
/// <summary>
/// Legacy class used by macros which converts a published content item into a hashset of values
/// </summary>
internal class PublishedContentHashtableConverter
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="PublishedContentHashtableConverter"/> class for a published document request.
/// </summary>
/// <param name="frequest">The <see cref="PublishedRequest"/> pointing to the document.</param>
/// <remarks>
/// The difference between creating the page with PublishedRequest vs an IPublishedContent item is
/// that the PublishedRequest takes into account how a template is assigned during the routing process whereas
/// with an IPublishedContent item, the template id is assigned purely based on the default.
/// </remarks>
internal PublishedContentHashtableConverter(PublishedRequest frequest)
{
if (!frequest.HasPublishedContent)
throw new ArgumentException("Document request has no node.", nameof(frequest));
PopulatePageData(frequest.PublishedContent.Id,
frequest.PublishedContent.Name, frequest.PublishedContent.ContentType.Id, frequest.PublishedContent.ContentType.Alias,
frequest.PublishedContent.WriterName, frequest.PublishedContent.CreatorName, frequest.PublishedContent.CreateDate, frequest.PublishedContent.UpdateDate,
frequest.PublishedContent.Path, frequest.PublishedContent.Parent?.Id ?? -1);
if (frequest.HasTemplate)
{
Elements["template"] = frequest.TemplateModel.Id.ToString();
}
PopulateElementData(frequest.PublishedContent);
}
/// <summary>
/// Initializes a new instance of the page for a published document
/// </summary>
/// <param name="doc"></param>
internal PublishedContentHashtableConverter(IPublishedContent doc)
{
if (doc == null) throw new ArgumentNullException(nameof(doc));
PopulatePageData(doc.Id,
doc.Name, doc.ContentType.Id, doc.ContentType.Alias,
doc.WriterName, doc.CreatorName, doc.CreateDate, doc.UpdateDate,
doc.Path, doc.Parent?.Id ?? -1);
if (doc.TemplateId.HasValue)
{
//set the template to whatever is assigned to the doc
Elements["template"] = doc.TemplateId.Value.ToString();
}
PopulateElementData(doc);
}
/// <summary>
/// Initializes a new instance of the page for a content.
/// </summary>
/// <param name="content">The content.</param>
/// <param name="variationContextAccessor"></param>
/// <remarks>This is for <see cref="MacroRenderingController"/> usage only.</remarks>
internal PublishedContentHashtableConverter(IContent content, IVariationContextAccessor variationContextAccessor)
: this(new PagePublishedContent(content, variationContextAccessor))
{ }
#endregion
#region Initialize
private void PopulatePageData(int pageId,
string pageName, int nodeType, string nodeTypeAlias,
string writerName, string creatorName, DateTime createDate, DateTime updateDate,
string path, int parentId)
{
// Update the elements hashtable
Elements.Add("pageID", pageId);
Elements.Add("parentID", parentId);
Elements.Add("pageName", pageName);
Elements.Add("nodeType", nodeType);
Elements.Add("nodeTypeAlias", nodeTypeAlias);
Elements.Add("writerName", writerName);
Elements.Add("creatorName", creatorName);
Elements.Add("createDate", createDate);
Elements.Add("updateDate", updateDate);
Elements.Add("path", path);
Elements.Add("splitpath", path.Split(','));
}
/// <summary>
/// Puts the properties of the node into the elements table
/// </summary>
/// <param name="node"></param>
private void PopulateElementData(IPublishedElement node)
{
foreach (var p in node.Properties)
{
if (Elements.ContainsKey(p.Alias) == false)
{
// note: legacy used the raw value (see populating from an Xml node below)
// so we're doing the same here, using DataValue. If we use Value then every
// value will be converted NOW - including RTEs that may contain macros that
// require that the 'page' is already initialized = catch-22.
// to properly fix this, we'd need to turn the elements collection into some
// sort of collection of lazy values.
Elements[p.Alias] = p.GetSourceValue();
}
}
}
#endregion
/// <summary>
/// Returns a Hashtable of data for a published content item
/// </summary>
public Hashtable Elements { get; } = new Hashtable();
#region PublishedContent
private class PagePublishedProperty : PublishedPropertyBase
{
private readonly object _sourceValue;
private readonly IPublishedContent _content;
public PagePublishedProperty(IPublishedPropertyType propertyType, IPublishedContent content)
: base(propertyType, PropertyCacheLevel.Unknown) // cache level is ignored
{
_sourceValue = null;
_content = content;
}
public PagePublishedProperty(IPublishedPropertyType propertyType, IPublishedContent content, Umbraco.Core.Models.Property property)
: base(propertyType, PropertyCacheLevel.Unknown) // cache level is ignored
{
_sourceValue = property.GetValue();
_content = content;
}
public override bool HasValue(string culture = null, string segment = null)
{
return _sourceValue != null && ((_sourceValue is string) == false || string.IsNullOrWhiteSpace((string)_sourceValue) == false);
}
public override object GetSourceValue(string culture = null, string segment = null)
{
return _sourceValue;
}
public override object GetValue(string culture = null, string segment = null)
{
// isPreviewing is true here since we want to preview anyway...
const bool isPreviewing = true;
var source = PropertyType.ConvertSourceToInter(_content, _sourceValue, isPreviewing);
return PropertyType.ConvertInterToObject(_content, PropertyCacheLevel.Unknown, source, isPreviewing);
}
public override object GetXPathValue(string culture = null, string segment = null)
{
throw new NotImplementedException();
}
}
private class PagePublishedContent : IPublishedContent
{
private readonly IContent _inner;
private readonly IPublishedProperty[] _properties;
private IReadOnlyDictionary<string, PublishedCultureInfo> _cultureInfos;
private readonly IVariationContextAccessor _variationContextAccessor;
private static readonly IReadOnlyDictionary<string, PublishedCultureInfo> NoCultureInfos = new Dictionary<string, PublishedCultureInfo>();
private PagePublishedContent(int id)
{
Id = id;
}
public PagePublishedContent(IContent inner, IVariationContextAccessor variationContextAccessor)
{
_inner = inner ?? throw new NullReferenceException("content");
_variationContextAccessor = variationContextAccessor;
Id = _inner.Id;
Key = _inner.Key;
CreatorName = _inner.GetCreatorProfile()?.Name;
WriterName = _inner.GetWriterProfile()?.Name;
// TODO: inject
var contentType = Current.Services.ContentTypeBaseServices.GetContentTypeOf(_inner);
ContentType = Current.PublishedContentTypeFactory.CreateContentType(contentType);
_properties = ContentType.PropertyTypes
.Select(x =>
{
var p = _inner.Properties.SingleOrDefault(xx => xx.Alias == x.Alias);
return p == null ? new PagePublishedProperty(x, this) : new PagePublishedProperty(x, this, p);
})
.Cast<IPublishedProperty>()
.ToArray();
Parent = new PagePublishedContent(_inner.ParentId);
}
public IPublishedContentType ContentType { get; }
public int Id { get; }
public Guid Key { get; }
public int? TemplateId => _inner.TemplateId;
public int SortOrder => _inner.SortOrder;
public string Name => _inner.Name;
public IReadOnlyDictionary<string, PublishedCultureInfo> Cultures
{
get
{
if (!_inner.ContentType.VariesByCulture())
return NoCultureInfos;
if (_cultureInfos != null)
return _cultureInfos;
var urlSegmentProviders = Current.UrlSegmentProviders; // TODO inject
return _cultureInfos = _inner.PublishCultureInfos.Values
.ToDictionary(x => x.Culture, x => new PublishedCultureInfo(x.Culture, x.Name, _inner.GetUrlSegment(urlSegmentProviders, x.Culture), x.Date));
}
}
public string UrlSegment => throw new NotImplementedException();
[Obsolete("Use WriterName(IUserService) extension instead")]
public string WriterName { get; }
[Obsolete("Use CreatorName(IUserService) extension instead")]
public string CreatorName { get; }
public int WriterId => _inner.WriterId;
public int CreatorId => _inner.CreatorId;
public string Path => _inner.Path;
public DateTime CreateDate => _inner.CreateDate;
public DateTime UpdateDate => _inner.UpdateDate;
public int Level => _inner.Level;
public string Url => throw new NotImplementedException();
public PublishedItemType ItemType => PublishedItemType.Content;
public bool IsDraft(string culture = null)
{
throw new NotImplementedException();
}
public bool IsPublished(string culture = null)
{
throw new NotImplementedException();
}
public IPublishedContent Parent { get; }
public IEnumerable<IPublishedContent> Children => throw new NotImplementedException();
public IEnumerable<IPublishedContent> ChildrenForAllCultures => throw new NotImplementedException();
public IEnumerable<IPublishedProperty> Properties => _properties;
public IPublishedProperty GetProperty(string alias)
{
throw new NotImplementedException();
}
}
#endregion
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.Resources;
using Microsoft.Azure.Management.Resources.Models;
namespace Microsoft.Azure.Management.Resources
{
public static partial class ProviderOperationsExtensions
{
/// <summary>
/// Gets a resource provider.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IProviderOperations.
/// </param>
/// <param name='resourceProviderNamespace'>
/// Required. Namespace of the resource provider.
/// </param>
/// <returns>
/// Resource provider information.
/// </returns>
public static ProviderGetResult Get(this IProviderOperations operations, string resourceProviderNamespace)
{
return Task.Factory.StartNew((object s) =>
{
return ((IProviderOperations)s).GetAsync(resourceProviderNamespace);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a resource provider.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IProviderOperations.
/// </param>
/// <param name='resourceProviderNamespace'>
/// Required. Namespace of the resource provider.
/// </param>
/// <returns>
/// Resource provider information.
/// </returns>
public static Task<ProviderGetResult> GetAsync(this IProviderOperations operations, string resourceProviderNamespace)
{
return operations.GetAsync(resourceProviderNamespace, CancellationToken.None);
}
/// <summary>
/// Gets a list of resource providers.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IProviderOperations.
/// </param>
/// <param name='parameters'>
/// Optional. Query parameters. If null is passed returns all
/// deployments.
/// </param>
/// <returns>
/// List of resource providers.
/// </returns>
public static ProviderListResult List(this IProviderOperations operations, ProviderListParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IProviderOperations)s).ListAsync(parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a list of resource providers.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IProviderOperations.
/// </param>
/// <param name='parameters'>
/// Optional. Query parameters. If null is passed returns all
/// deployments.
/// </param>
/// <returns>
/// List of resource providers.
/// </returns>
public static Task<ProviderListResult> ListAsync(this IProviderOperations operations, ProviderListParameters parameters)
{
return operations.ListAsync(parameters, CancellationToken.None);
}
/// <summary>
/// Get a list of deployments.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IProviderOperations.
/// </param>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <returns>
/// List of resource providers.
/// </returns>
public static ProviderListResult ListNext(this IProviderOperations operations, string nextLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IProviderOperations)s).ListNextAsync(nextLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get a list of deployments.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IProviderOperations.
/// </param>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <returns>
/// List of resource providers.
/// </returns>
public static Task<ProviderListResult> ListNextAsync(this IProviderOperations operations, string nextLink)
{
return operations.ListNextAsync(nextLink, CancellationToken.None);
}
/// <summary>
/// Registers provider to be used with a subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IProviderOperations.
/// </param>
/// <param name='resourceProviderNamespace'>
/// Required. Namespace of the resource provider.
/// </param>
/// <returns>
/// Resource provider registration information.
/// </returns>
public static ProviderRegistionResult Register(this IProviderOperations operations, string resourceProviderNamespace)
{
return Task.Factory.StartNew((object s) =>
{
return ((IProviderOperations)s).RegisterAsync(resourceProviderNamespace);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Registers provider to be used with a subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IProviderOperations.
/// </param>
/// <param name='resourceProviderNamespace'>
/// Required. Namespace of the resource provider.
/// </param>
/// <returns>
/// Resource provider registration information.
/// </returns>
public static Task<ProviderRegistionResult> RegisterAsync(this IProviderOperations operations, string resourceProviderNamespace)
{
return operations.RegisterAsync(resourceProviderNamespace, CancellationToken.None);
}
/// <summary>
/// Unregisters provider from a subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IProviderOperations.
/// </param>
/// <param name='resourceProviderNamespace'>
/// Required. Namespace of the resource provider.
/// </param>
/// <returns>
/// Resource provider registration information.
/// </returns>
public static ProviderUnregistionResult Unregister(this IProviderOperations operations, string resourceProviderNamespace)
{
return Task.Factory.StartNew((object s) =>
{
return ((IProviderOperations)s).UnregisterAsync(resourceProviderNamespace);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Unregisters provider from a subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IProviderOperations.
/// </param>
/// <param name='resourceProviderNamespace'>
/// Required. Namespace of the resource provider.
/// </param>
/// <returns>
/// Resource provider registration information.
/// </returns>
public static Task<ProviderUnregistionResult> UnregisterAsync(this IProviderOperations operations, string resourceProviderNamespace)
{
return operations.UnregisterAsync(resourceProviderNamespace, CancellationToken.None);
}
}
}
| |
using System;
using System.Linq.Expressions;
using AutoMapper.Mappers;
namespace AutoMapper
{
public static class Mapper
{
private static readonly Func<ConfigurationStore> _configurationInit =
() => new ConfigurationStore(new TypeMapFactory(), MapperRegistry.AllMappers());
private static Lazy<ConfigurationStore> _configuration = new Lazy<ConfigurationStore>(_configurationInit);
private static readonly Func<IMappingEngine> _mappingEngineInit =
() => new MappingEngine(_configuration.Value);
private static Lazy<IMappingEngine> _mappingEngine = new Lazy<IMappingEngine>(_mappingEngineInit);
public static bool AllowNullDestinationValues
{
get { return Configuration.AllowNullDestinationValues; }
set { Configuration.AllowNullDestinationValues = value; }
}
public static TDestination Map<TDestination>(object source)
{
return Engine.Map<TDestination>(source);
}
public static TDestination Map<TDestination>(object source, Action<IMappingOperationOptions> opts)
{
return Engine.Map<TDestination>(source, opts);
}
public static TDestination Map<TSource, TDestination>(TSource source)
{
return Engine.Map<TSource, TDestination>(source);
}
public static TDestination Map<TSource, TDestination>(TSource source, TDestination destination)
{
return Engine.Map(source, destination);
}
public static TDestination Map<TSource, TDestination>(TSource source, TDestination destination, Action<IMappingOperationOptions> opts)
{
return Engine.Map(source, destination, opts);
}
public static TDestination Map<TSource, TDestination>(TSource source, Action<IMappingOperationOptions> opts)
{
return Engine.Map<TSource, TDestination>(source, opts);
}
public static object Map(object source, Type sourceType, Type destinationType)
{
return Engine.Map(source, sourceType, destinationType);
}
public static object Map(object source, Type sourceType, Type destinationType, Action<IMappingOperationOptions> opts)
{
return Engine.Map(source, sourceType, destinationType, opts);
}
public static object Map(object source, object destination, Type sourceType, Type destinationType)
{
return Engine.Map(source, destination, sourceType, destinationType);
}
public static object Map(object source, object destination, Type sourceType, Type destinationType, Action<IMappingOperationOptions> opts)
{
return Engine.Map(source, destination, sourceType, destinationType, opts);
}
public static Expression<Func<TSource, TDestination>> CreateMapExpression<TSource, TDestination>()
{
return Engine.CreateMapExpression<TSource, TDestination>();
}
public static TDestination DynamicMap<TSource, TDestination>(TSource source)
{
return Engine.DynamicMap<TSource, TDestination>(source);
}
public static void DynamicMap<TSource, TDestination>(TSource source, TDestination destination)
{
Engine.DynamicMap<TSource, TDestination>(source, destination);
}
public static TDestination DynamicMap<TDestination>(object source)
{
return Engine.DynamicMap<TDestination>(source);
}
public static object DynamicMap(object source, Type sourceType, Type destinationType)
{
return Engine.DynamicMap(source, sourceType, destinationType);
}
public static void DynamicMap(object source, object destination, Type sourceType, Type destinationType)
{
Engine.DynamicMap(source, destination, sourceType, destinationType);
}
public static void Initialize(Action<IConfiguration> action)
{
Reset();
action(Configuration);
Configuration.Seal();
}
public static IFormatterCtorExpression<TValueFormatter> AddFormatter<TValueFormatter>() where TValueFormatter : IValueFormatter
{
return Configuration.AddFormatter<TValueFormatter>();
}
public static IFormatterCtorExpression AddFormatter(Type valueFormatterType)
{
return Configuration.AddFormatter(valueFormatterType);
}
public static void AddFormatter(IValueFormatter formatter)
{
Configuration.AddFormatter(formatter);
}
public static void AddFormatExpression(Func<ResolutionContext, string> formatExpression)
{
Configuration.AddFormatExpression(formatExpression);
}
public static void SkipFormatter<TValueFormatter>() where TValueFormatter : IValueFormatter
{
Configuration.SkipFormatter<TValueFormatter>();
}
public static IFormatterExpression ForSourceType<TSource>()
{
return Configuration.ForSourceType<TSource>();
}
public static IMappingExpression<TSource, TDestination> CreateMap<TSource, TDestination>()
{
return Configuration.CreateMap<TSource, TDestination>();
}
public static IMappingExpression CreateMap(Type sourceType, Type destinationType)
{
return Configuration.CreateMap(sourceType, destinationType);
}
public static IProfileExpression CreateProfile(string profileName)
{
return Configuration.CreateProfile(profileName);
}
public static void CreateProfile(string profileName, Action<IProfileExpression> profileConfiguration)
{
Configuration.CreateProfile(profileName, profileConfiguration);
}
public static void AddProfile(Profile profile)
{
Configuration.AddProfile(profile);
}
public static void AddProfile<TProfile>() where TProfile : Profile, new()
{
Configuration.AddProfile<TProfile>();
}
public static TypeMap FindTypeMapFor(Type sourceType, Type destinationType)
{
return ConfigurationProvider.FindTypeMapFor(null, sourceType, destinationType);
}
public static TypeMap FindTypeMapFor<TSource, TDestination>()
{
return ConfigurationProvider.FindTypeMapFor(null, typeof(TSource), typeof(TDestination));
}
public static TypeMap[] GetAllTypeMaps()
{
return ConfigurationProvider.GetAllTypeMaps();
}
public static void AssertConfigurationIsValid()
{
ConfigurationProvider.AssertConfigurationIsValid();
}
public static void AssertConfigurationIsValid(string profileName)
{
ConfigurationProvider.AssertConfigurationIsValid(profileName);
}
public static void Reset()
{
_configuration = new Lazy<ConfigurationStore>(_configurationInit);
_mappingEngine = new Lazy<IMappingEngine>(_mappingEngineInit);
}
public static IMappingEngine Engine
{
get
{
return _mappingEngine.Value;
}
}
public static IConfiguration Configuration
{
get { return (IConfiguration) ConfigurationProvider; }
}
private static IConfigurationProvider ConfigurationProvider
{
get
{
return _configuration.Value;
}
}
public static void AddGlobalIgnore(string startingwith)
{
Configuration.AddGlobalIgnore(startingwith);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace Ploeh.AutoFixture.Kernel
{
/// <summary>
/// Base class for recursion handling. Tracks requests and reacts when a recursion point in the
/// specimen creation process is detected.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "The main responsibility of this class isn't to be a 'collection' (which, by the way, it isn't - it's just an Iterator).")]
public class RecursionGuard : ISpecimenBuilderNode
{
private readonly ISpecimenBuilder builder;
private readonly IRecursionHandler recursionHandler;
private readonly IEqualityComparer comparer;
private readonly ConcurrentDictionary<Thread, Stack<object>>
_requestsByThread = new ConcurrentDictionary<Thread, Stack<object>>();
private Stack<object> GetMonitoredRequestsForCurrentThread()
{
return _requestsByThread.GetOrAdd(Thread.CurrentThread, _ => new Stack<object>());
}
private readonly int recursionDepth;
/// <summary>
/// Initializes a new instance of the <see cref="RecursionGuard"/> class.
/// </summary>
/// <param name="builder">The intercepted builder to decorate.</param>
[Obsolete("This constructor overload is obsolete and will be removed in a future version of AutoFixture. Please use RecursionGuard(ISpecimenBuilder, IRecursionHandler) instead.")]
public RecursionGuard(ISpecimenBuilder builder)
: this(builder, EqualityComparer<object>.Default)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RecursionGuard" />
/// class.
/// </summary>
/// <param name="builder">The intercepted builder to decorate.</param>
/// <param name="recursionHandler">
/// An <see cref="IRecursionHandler" /> that will handle a recursion
/// situation, if one is detected.
/// </param>
public RecursionGuard(
ISpecimenBuilder builder,
IRecursionHandler recursionHandler)
: this(
builder,
recursionHandler,
EqualityComparer<object>.Default,
1)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RecursionGuard" />
/// class.
/// </summary>
/// <param name="builder">The intercepted builder to decorate.</param>
/// <param name="recursionHandler">
/// An <see cref="IRecursionHandler" /> that will handle a recursion
/// situation, if one is detected.
/// </param>
/// <param name="recursionDepth">The recursion depth at which the request will be treated as a recursive
/// request</param>
public RecursionGuard(
ISpecimenBuilder builder,
IRecursionHandler recursionHandler,
int recursionDepth)
: this(
builder,
recursionHandler,
EqualityComparer<object>.Default,
recursionDepth)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RecursionGuard"/> class.
/// </summary>
/// <param name="builder">The intercepted builder to decorate.</param>
/// <param name="comparer">
/// An IEqualityComparer implementation to use when comparing requests to determine recursion.
/// </param>
[Obsolete("This constructor overload is obsolete and will be removed in a future version of AutoFixture. Please use RecursionGuard(ISpecimenBuilder, IRecursionHandler, IEqualityComparer, int) instead.")]
public RecursionGuard(ISpecimenBuilder builder, IEqualityComparer comparer)
{
if (builder == null)
{
throw new ArgumentNullException("builder");
}
if (comparer == null)
{
throw new ArgumentNullException("comparer");
}
this.builder = builder;
this.comparer = comparer;
this.recursionDepth = 1;
}
/// <summary>
/// Initializes a new instance of the <see cref="RecursionGuard" />
/// class.
/// </summary>
/// <param name="builder">The intercepted builder to decorate.</param>
/// <param name="recursionHandler">
/// An <see cref="IRecursionHandler" /> that will handle a recursion
/// situation, if one is detected.
/// </param>
/// <param name="comparer">
/// An <see cref="IEqualityComparer" /> implementation to use when
/// comparing requests to determine recursion.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// builder
/// or
/// recursionHandler
/// or
/// comparer
/// </exception>
[Obsolete("This constructor overload is obsolete and will be removed in a future version of AutoFixture. Please use RecursionGuard(ISpecimenBuilder, IRecursionHandler, IEqualityComparer, int) instead.")]
public RecursionGuard(
ISpecimenBuilder builder,
IRecursionHandler recursionHandler,
IEqualityComparer comparer)
: this(
builder,
recursionHandler,
comparer,
1)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RecursionGuard" />
/// class.
/// </summary>
/// <param name="builder">The intercepted builder to decorate.</param>
/// <param name="recursionHandler">
/// An <see cref="IRecursionHandler" /> that will handle a recursion
/// situation, if one is detected.
/// </param>
/// <param name="comparer">
/// An <see cref="IEqualityComparer" /> implementation to use when
/// comparing requests to determine recursion.
/// </param>
/// <param name="recursionDepth">The recursion depth at which the request will be treated as a recursive
/// request</param>
/// <exception cref="System.ArgumentNullException">
/// builder
/// or
/// recursionHandler
/// or
/// comparer
/// </exception>
public RecursionGuard(
ISpecimenBuilder builder,
IRecursionHandler recursionHandler,
IEqualityComparer comparer,
int recursionDepth)
{
if (builder == null)
throw new ArgumentNullException("builder");
if (recursionHandler == null)
throw new ArgumentNullException("recursionHandler");
if (comparer == null)
throw new ArgumentNullException("comparer");
this.builder = builder;
this.recursionHandler = recursionHandler;
this.comparer = comparer;
this.recursionDepth = recursionDepth;
}
/// <summary>
/// Gets the decorated builder supplied via the constructor.
/// </summary>
/// <seealso cref="RecursionGuard(ISpecimenBuilder)"/>
/// <seealso cref="RecursionGuard(ISpecimenBuilder, IEqualityComparer)" />
public ISpecimenBuilder Builder
{
get { return this.builder; }
}
/// <summary>
/// Gets the recursion handler originally supplied as a constructor
/// argument.
/// </summary>
/// <value>
/// The recursion handler used to handle recursion situations.
/// </value>
/// <seealso cref="RecursionGuard(ISpecimenBuilder, IRecursionHandler)" />
/// <seealso cref="RecursionGuard(ISpecimenBuilder, IRecursionHandler, IEqualityComparer)" />
public IRecursionHandler RecursionHandler
{
get { return this.recursionHandler; }
}
/// <summary>
/// The recursion depth at which the request will be treated as a
/// recursive request
/// </summary>
public int RecursionDepth
{
get { return recursionDepth; }
}
/// <summary>Gets the comparer supplied via the constructor.</summary>
/// <seealso cref="RecursionGuard(ISpecimenBuilder, IEqualityComparer)" />
public IEqualityComparer Comparer
{
get { return this.comparer; }
}
/// <summary>
/// Gets the recorded requests so far.
/// </summary>
protected IEnumerable RecordedRequests
{
get { return GetMonitoredRequestsForCurrentThread(); }
}
/// <summary>
/// Handles a request that would cause recursion.
/// </summary>
/// <param name="request">The recursion causing request.</param>
/// <returns>The specimen to return.</returns>
[Obsolete("This method will be removed in a future version of AutoFixture. Use IRecursionHandler.HandleRecursiveRequest instead.")]
public virtual object HandleRecursiveRequest(object request)
{
return this.recursionHandler.HandleRecursiveRequest(
request,
GetMonitoredRequestsForCurrentThread());
}
/// <summary>
/// Creates a new specimen based on a request.
/// </summary>
/// <param name="request">The request that describes what to create.</param>
/// <param name="context">A container that can be used to create other specimens.</param>
/// <returns>
/// The requested specimen if possible; otherwise a <see cref="NoSpecimen"/> instance.
/// </returns>
/// <remarks>
/// <para>
/// The <paramref name="request"/> can be any object, but will often be a
/// <see cref="Type"/> or other <see cref="System.Reflection.MemberInfo"/> instances.
/// </para>
/// </remarks>
public object Create(object request, ISpecimenContext context)
{
var requestsForCurrentThread = GetMonitoredRequestsForCurrentThread();
if (requestsForCurrentThread.Count > 0)
{
// This is performance-sensitive code when used repeatedly over many requests.
// See discussion at https://github.com/AutoFixture/AutoFixture/pull/218
var requestsArray = requestsForCurrentThread.ToArray();
int numRequestsSameAsThisOne = 0;
for (int i = 0; i < requestsArray.Length; i++)
{
var existingRequest = requestsArray[i];
if (this.comparer.Equals(existingRequest, request))
{
numRequestsSameAsThisOne++;
}
if (numRequestsSameAsThisOne >= this.RecursionDepth)
{
#pragma warning disable 618
return this.HandleRecursiveRequest(request);
#pragma warning restore 618
}
}
}
requestsForCurrentThread.Push(request);
var specimen = this.builder.Create(request, context);
requestsForCurrentThread.Pop();
return specimen;
}
/// <summary>Composes the supplied builders.</summary>
/// <param name="builders">The builders to compose.</param>
/// <returns>A <see cref="ISpecimenBuilderNode" /> instance.</returns>
/// <remarks>
/// <para>
/// Note to implementers:
/// </para>
/// <para>
/// The intent of this method is to compose the supplied
/// <paramref name="builders" /> into a new instance of the type
/// implementing <see cref="ISpecimenBuilderNode" />. Thus, the
/// concrete return type is expected to the same type as the type
/// implementing the method. However, it is not considered a failure to
/// deviate from this idiom - it would just not be a mainstream
/// implementation.
/// </para>
/// <para>
/// The returned instance is normally expected to contain the builders
/// supplied as an argument, but again this is not strictly required.
/// The implementation may decide to filter the sequence or add to it
/// during composition.
/// </para>
/// </remarks>
public virtual ISpecimenBuilderNode Compose(
IEnumerable<ISpecimenBuilder> builders)
{
var composedBuilder = CompositeSpecimenBuilder.ComposeIfMultiple(
builders);
return new RecursionGuard(
composedBuilder,
this.recursionHandler,
this.comparer,
this.RecursionDepth);
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{ISpecimenBuilder}" /> that can be used to
/// iterate through the collection.
/// </returns>
public virtual IEnumerator<ISpecimenBuilder> GetEnumerator()
{
yield return this.builder;
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
}
| |
using System;
using System.Reflection;
using System.Collections.Generic;
namespace Avalonia.Media
{
internal static class KnownColors
{
private static readonly IReadOnlyDictionary<string, KnownColor> _knownColorNames;
private static readonly IReadOnlyDictionary<uint, string> _knownColors;
private static readonly Dictionary<KnownColor, ISolidColorBrush> _knownBrushes;
static KnownColors()
{
var knownColorNames = new Dictionary<string, KnownColor>(StringComparer.OrdinalIgnoreCase);
var knownColors = new Dictionary<uint, string>();
foreach (var field in typeof(KnownColor).GetRuntimeFields())
{
if (field.FieldType != typeof(KnownColor)) continue;
var knownColor = (KnownColor)field.GetValue(null);
if (knownColor == KnownColor.None) continue;
knownColorNames.Add(field.Name, knownColor);
// some known colors have the same value, so use the first
if (!knownColors.ContainsKey((uint)knownColor))
{
knownColors.Add((uint)knownColor, field.Name);
}
}
_knownColorNames = knownColorNames;
_knownColors = knownColors;
_knownBrushes = new Dictionary<KnownColor, ISolidColorBrush>();
}
public static ISolidColorBrush GetKnownBrush(string s)
{
var color = GetKnownColor(s);
return color != KnownColor.None ? color.ToBrush() : null;
}
public static KnownColor GetKnownColor(string s)
{
if (_knownColorNames.TryGetValue(s, out var color))
{
return color;
}
return KnownColor.None;
}
public static string GetKnownColorName(uint rgb)
{
return _knownColors.TryGetValue(rgb, out var name) ? name : null;
}
public static Color ToColor(this KnownColor color)
{
return Color.FromUInt32((uint)color);
}
public static ISolidColorBrush ToBrush(this KnownColor color)
{
lock (_knownBrushes)
{
if (!_knownBrushes.TryGetValue(color, out var brush))
{
brush = new Immutable.ImmutableSolidColorBrush(color.ToColor());
_knownBrushes.Add(color, brush);
}
return brush;
}
}
}
internal enum KnownColor : uint
{
None,
AliceBlue = 0xfff0f8ff,
AntiqueWhite = 0xfffaebd7,
Aqua = 0xff00ffff,
Aquamarine = 0xff7fffd4,
Azure = 0xfff0ffff,
Beige = 0xfff5f5dc,
Bisque = 0xffffe4c4,
Black = 0xff000000,
BlanchedAlmond = 0xffffebcd,
Blue = 0xff0000ff,
BlueViolet = 0xff8a2be2,
Brown = 0xffa52a2a,
BurlyWood = 0xffdeb887,
CadetBlue = 0xff5f9ea0,
Chartreuse = 0xff7fff00,
Chocolate = 0xffd2691e,
Coral = 0xffff7f50,
CornflowerBlue = 0xff6495ed,
Cornsilk = 0xfffff8dc,
Crimson = 0xffdc143c,
Cyan = 0xff00ffff,
DarkBlue = 0xff00008b,
DarkCyan = 0xff008b8b,
DarkGoldenrod = 0xffb8860b,
DarkGray = 0xffa9a9a9,
DarkGreen = 0xff006400,
DarkKhaki = 0xffbdb76b,
DarkMagenta = 0xff8b008b,
DarkOliveGreen = 0xff556b2f,
DarkOrange = 0xffff8c00,
DarkOrchid = 0xff9932cc,
DarkRed = 0xff8b0000,
DarkSalmon = 0xffe9967a,
DarkSeaGreen = 0xff8fbc8f,
DarkSlateBlue = 0xff483d8b,
DarkSlateGray = 0xff2f4f4f,
DarkTurquoise = 0xff00ced1,
DarkViolet = 0xff9400d3,
DeepPink = 0xffff1493,
DeepSkyBlue = 0xff00bfff,
DimGray = 0xff696969,
DodgerBlue = 0xff1e90ff,
Firebrick = 0xffb22222,
FloralWhite = 0xfffffaf0,
ForestGreen = 0xff228b22,
Fuchsia = 0xffff00ff,
Gainsboro = 0xffdcdcdc,
GhostWhite = 0xfff8f8ff,
Gold = 0xffffd700,
Goldenrod = 0xffdaa520,
Gray = 0xff808080,
Green = 0xff008000,
GreenYellow = 0xffadff2f,
Honeydew = 0xfff0fff0,
HotPink = 0xffff69b4,
IndianRed = 0xffcd5c5c,
Indigo = 0xff4b0082,
Ivory = 0xfffffff0,
Khaki = 0xfff0e68c,
Lavender = 0xffe6e6fa,
LavenderBlush = 0xfffff0f5,
LawnGreen = 0xff7cfc00,
LemonChiffon = 0xfffffacd,
LightBlue = 0xffadd8e6,
LightCoral = 0xfff08080,
LightCyan = 0xffe0ffff,
LightGoldenrodYellow = 0xfffafad2,
LightGreen = 0xff90ee90,
LightGray = 0xffd3d3d3,
LightPink = 0xffffb6c1,
LightSalmon = 0xffffa07a,
LightSeaGreen = 0xff20b2aa,
LightSkyBlue = 0xff87cefa,
LightSlateGray = 0xff778899,
LightSteelBlue = 0xffb0c4de,
LightYellow = 0xffffffe0,
Lime = 0xff00ff00,
LimeGreen = 0xff32cd32,
Linen = 0xfffaf0e6,
Magenta = 0xffff00ff,
Maroon = 0xff800000,
MediumAquamarine = 0xff66cdaa,
MediumBlue = 0xff0000cd,
MediumOrchid = 0xffba55d3,
MediumPurple = 0xff9370db,
MediumSeaGreen = 0xff3cb371,
MediumSlateBlue = 0xff7b68ee,
MediumSpringGreen = 0xff00fa9a,
MediumTurquoise = 0xff48d1cc,
MediumVioletRed = 0xffc71585,
MidnightBlue = 0xff191970,
MintCream = 0xfff5fffa,
MistyRose = 0xffffe4e1,
Moccasin = 0xffffe4b5,
NavajoWhite = 0xffffdead,
Navy = 0xff000080,
OldLace = 0xfffdf5e6,
Olive = 0xff808000,
OliveDrab = 0xff6b8e23,
Orange = 0xffffa500,
OrangeRed = 0xffff4500,
Orchid = 0xffda70d6,
PaleGoldenrod = 0xffeee8aa,
PaleGreen = 0xff98fb98,
PaleTurquoise = 0xffafeeee,
PaleVioletRed = 0xffdb7093,
PapayaWhip = 0xffffefd5,
PeachPuff = 0xffffdab9,
Peru = 0xffcd853f,
Pink = 0xffffc0cb,
Plum = 0xffdda0dd,
PowderBlue = 0xffb0e0e6,
Purple = 0xff800080,
Red = 0xffff0000,
RosyBrown = 0xffbc8f8f,
RoyalBlue = 0xff4169e1,
SaddleBrown = 0xff8b4513,
Salmon = 0xfffa8072,
SandyBrown = 0xfff4a460,
SeaGreen = 0xff2e8b57,
SeaShell = 0xfffff5ee,
Sienna = 0xffa0522d,
Silver = 0xffc0c0c0,
SkyBlue = 0xff87ceeb,
SlateBlue = 0xff6a5acd,
SlateGray = 0xff708090,
Snow = 0xfffffafa,
SpringGreen = 0xff00ff7f,
SteelBlue = 0xff4682b4,
Tan = 0xffd2b48c,
Teal = 0xff008080,
Thistle = 0xffd8bfd8,
Tomato = 0xffff6347,
Transparent = 0x00ffffff,
Turquoise = 0xff40e0d0,
Violet = 0xffee82ee,
Wheat = 0xfff5deb3,
White = 0xffffffff,
WhiteSmoke = 0xfff5f5f5,
Yellow = 0xffffff00,
YellowGreen = 0xff9acd32
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.ETrade.ETrade
File: ETradeMessageAdapter.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.ETrade
{
using System;
using Ecng.Common;
using StockSharp.ETrade.Native;
using StockSharp.Logging;
using StockSharp.Messages;
using StockSharp.Localization;
/// <summary>
/// The messages adapter for ETrade.
/// </summary>
public partial class ETradeMessageAdapter : MessageAdapter
{
private ETradeClient _client;
/// <summary>
/// Initializes a new instance of the <see cref="ETradeMessageAdapter"/>.
/// </summary>
/// <param name="transactionIdGenerator">Transaction id generator.</param>
public ETradeMessageAdapter(IdGenerator transactionIdGenerator)
: base(transactionIdGenerator)
{
this.AddMarketDataSupport();
this.AddTransactionalSupport();
this.RemoveSupportedMessage(MessageTypes.PortfolioLookup);
}
/// <summary>
/// <see cref="SecurityLookupMessage"/> required to get securities.
/// </summary>
public override bool SecurityLookupRequired => false;
/// <summary>
/// Create condition for order type <see cref="OrderTypes.Conditional"/>, that supports the adapter.
/// </summary>
/// <returns>Order condition. If the connection does not support the order type <see cref="OrderTypes.Conditional"/>, it will be returned <see langword="null" />.</returns>
public override OrderCondition CreateOrderCondition()
{
return new ETradeOrderCondition();
}
private void DisposeClient()
{
_client.ConnectionStateChanged -= ClientOnConnectionStateChanged;
_client.ConnectionError -= ClientOnConnectionError;
_client.Error -= SendOutError;
_client.OrderRegisterResult -= ClientOnOrderRegisterResult;
_client.OrderReRegisterResult -= ClientOnOrderRegisterResult;
_client.OrderCancelResult -= ClientOnOrderCancelResult;
_client.AccountsData -= ClientOnAccountsData;
_client.PositionsData -= ClientOnPositionsData;
_client.OrdersData -= ClientOnOrdersData;
_client.ProductLookupResult -= ClientOnProductLookupResult;
_client.Disconnect();
}
/// <summary>
/// Send incoming message.
/// </summary>
/// <param name="message">Message.</param>
protected override void OnSendInMessage(Message message)
{
switch (message.Type)
{
case MessageTypes.Reset:
{
if (_client != null)
{
try
{
DisposeClient();
}
catch (Exception ex)
{
SendOutError(ex);
}
_client = null;
}
SendOutMessage(new ResetMessage());
break;
}
case MessageTypes.Connect:
{
if (_client != null)
throw new InvalidOperationException(LocalizedStrings.Str1619);
_client = new ETradeClient
{
ConsumerKey = ConsumerKey,
ConsumerSecret = ConsumerSecret,
AccessToken = AccessToken,
Sandbox = Sandbox,
VerificationCode = VerificationCode,
};
_client.ConnectionStateChanged += ClientOnConnectionStateChanged;
_client.ConnectionError += ClientOnConnectionError;
_client.Error += SendOutError;
_client.OrderRegisterResult += ClientOnOrderRegisterResult;
_client.OrderReRegisterResult += ClientOnOrderRegisterResult;
_client.OrderCancelResult += ClientOnOrderCancelResult;
_client.AccountsData += ClientOnAccountsData;
_client.PositionsData += ClientOnPositionsData;
_client.OrdersData += ClientOnOrdersData;
_client.ProductLookupResult += ClientOnProductLookupResult;
_client.Parent = this;
_client.Connect();
break;
}
case MessageTypes.Disconnect:
{
if (_client == null)
throw new InvalidOperationException(LocalizedStrings.Str1856);
DisposeClient();
_client = null;
break;
}
case MessageTypes.SecurityLookup:
{
var lookupMsg = (SecurityLookupMessage)message;
_client.LookupSecurities(lookupMsg.SecurityId.SecurityCode, lookupMsg.TransactionId);
break;
}
case MessageTypes.OrderRegister:
{
var regMsg = (OrderRegisterMessage)message;
_client.RegisterOrder(
regMsg.PortfolioName,
regMsg.SecurityId.SecurityCode,
regMsg.Side,
regMsg.Price,
regMsg.Volume,
regMsg.TransactionId,
regMsg.TimeInForce == TimeInForce.MatchOrCancel,
regMsg.TillDate,
regMsg.OrderType.Value,
(ETradeOrderCondition)regMsg.Condition);
break;
}
case MessageTypes.OrderReplace:
{
var replaceMsg = (OrderReplaceMessage)message;
if (replaceMsg.OldOrderId == null)
throw new InvalidOperationException(LocalizedStrings.Str2252Params.Put(replaceMsg.OldTransactionId));
SaveOrder(replaceMsg.OldTransactionId, replaceMsg.OldOrderId.Value);
_client.ReRegisterOrder(
replaceMsg.OldOrderId.Value,
replaceMsg.PortfolioName,
replaceMsg.Price,
replaceMsg.Volume,
replaceMsg.TransactionId,
replaceMsg.TimeInForce == TimeInForce.MatchOrCancel,
replaceMsg.TillDate,
replaceMsg.OrderType.Value,
(ETradeOrderCondition)replaceMsg.Condition);
break;
}
case MessageTypes.OrderCancel:
{
var cancelMsg = (OrderCancelMessage)message;
if (cancelMsg.OrderId == null)
throw new InvalidOperationException(LocalizedStrings.Str2252Params.Put(cancelMsg.OrderTransactionId));
_client.CancelOrder(cancelMsg.TransactionId, cancelMsg.OrderId.Value, cancelMsg.PortfolioName);
break;
}
}
}
/// <summary>
/// Connection state changed callback.
/// </summary>
private void ClientOnConnectionStateChanged()
{
this.AddInfoLog(LocalizedStrings.Str3364Params, _client.IsConnected ? LocalizedStrings.Str3365 : LocalizedStrings.Str3366);
SendOutMessage(_client.IsConnected ? (Message)new ConnectMessage() : new DisconnectMessage());
}
/// <summary>
/// Connection error callback.
/// </summary>
/// <param name="ex">Error connection.</param>
private void ClientOnConnectionError(Exception ex)
{
this.AddInfoLog(LocalizedStrings.Str3458Params.Put(ex.Message));
SendOutMessage(new ConnectMessage { Error = ex });
}
/// <summary>
/// Set own authorization mode (the default is browser uses).
/// </summary>
/// <param name="method">ETrade authorization method.</param>
public void SetCustomAuthorizationMethod(Action<string> method)
{
_client.SetCustomAuthorizationMethod(method);
}
}
}
| |
#region License
//
// Copyright (c) 2007-2009, Sean Chambers <[email protected]>
//
// 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.
//
#endregion
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Text;
using FluentMigrator.Expressions;
using FluentMigrator.Infrastructure;
using FluentMigrator.Runner.Initialization;
using FluentMigrator.Runner.Versioning;
namespace FluentMigrator.Runner
{
public class MigrationRunner : IMigrationRunner
{
private Assembly _migrationAssembly;
private IAnnouncer _announcer;
private IStopWatch _stopWatch;
private bool _alreadyOutputPreviewOnlyModeWarning;
/// <summary>The arbitrary application context passed to the task runner.</summary>
public object ApplicationContext { get; private set; }
public bool SilentlyFail { get; set; }
public IMigrationProcessor Processor { get; private set; }
public IMigrationInformationLoader MigrationLoader { get; set; }
public IProfileLoader ProfileLoader { get; set; }
public IMigrationConventions Conventions { get; private set; }
public IList<Exception> CaughtExceptions { get; private set; }
public MigrationRunner(Assembly assembly, IRunnerContext runnerContext, IMigrationProcessor processor)
{
_migrationAssembly = assembly;
_announcer = runnerContext.Announcer;
Processor = processor;
_stopWatch = runnerContext.StopWatch;
ApplicationContext = runnerContext.ApplicationContext;
SilentlyFail = false;
CaughtExceptions = null;
Conventions = new MigrationConventions();
if (!string.IsNullOrEmpty(runnerContext.WorkingDirectory))
Conventions.GetWorkingDirectory = () => runnerContext.WorkingDirectory;
VersionLoader = new VersionLoader(this, _migrationAssembly, Conventions);
MigrationLoader = new DefaultMigrationInformationLoader(Conventions, _migrationAssembly, runnerContext.Namespace, runnerContext.NestedNamespaces, runnerContext.Tags);
ProfileLoader = new ProfileLoader(runnerContext, this, Conventions);
}
public IVersionLoader VersionLoader { get; set; }
public void ApplyProfiles()
{
ProfileLoader.ApplyProfiles();
}
public void MigrateUp()
{
MigrateUp(true);
}
public void MigrateUp(bool useAutomaticTransactionManagement)
{
var migrations = MigrationLoader.LoadMigrations();
foreach (var pair in migrations)
{
ApplyMigrationUp(pair.Value, useAutomaticTransactionManagement && pair.Value.TransactionBehavior == TransactionBehavior.Default);
}
ApplyProfiles();
VersionLoader.LoadVersionInfo();
}
public void MigrateUp(long targetVersion)
{
MigrateUp(targetVersion, true);
}
public void MigrateUp(long targetVersion, bool useAutomaticTransactionManagement)
{
var migrationInfos = GetUpMigrationsToApply(targetVersion);
foreach (var migrationInfo in migrationInfos)
{
ApplyMigrationUp(migrationInfo, useAutomaticTransactionManagement && migrationInfo.TransactionBehavior == TransactionBehavior.Default);
}
VersionLoader.LoadVersionInfo();
}
private IEnumerable<IMigrationInfo> GetUpMigrationsToApply(long version)
{
var migrations = MigrationLoader.LoadMigrations();
return from pair in migrations
where IsMigrationStepNeededForUpMigration(pair.Value, version)
select pair.Value;
}
private bool IsMigrationStepNeededForUpMigration(IMigrationInfo versionOfMigration, long targetVersion)
{
if (versionOfMigration.Version <= targetVersion && !VersionLoader.VersionInfo.HasAppliedMigration(versionOfMigration))
{
return true;
}
return false;
}
public void MigrateDown(long targetVersion)
{
MigrateDown(targetVersion, true);
}
public void MigrateDown(long targetVersion, bool useAutomaticTransactionManagement)
{
var migrationInfos = GetDownMigrationsToApply(targetVersion);
foreach (var migrationInfo in migrationInfos)
{
ApplyMigrationDown(migrationInfo, useAutomaticTransactionManagement && migrationInfo.TransactionBehavior == TransactionBehavior.Default);
}
VersionLoader.LoadVersionInfo();
}
private IEnumerable<IMigrationInfo> GetDownMigrationsToApply(long targetVersion)
{
var migrations = MigrationLoader.LoadMigrations();
var migrationsToApply = (from pair in migrations
where IsMigrationStepNeededForDownMigration(pair.Value, targetVersion)
select pair.Value)
.ToList();
return migrationsToApply.OrderByDescending(x => x.ComplexVersion);
}
private bool IsMigrationStepNeededForDownMigration(IMigrationInfo migrationInfo, long targetVersion)
{
if (migrationInfo.Version > targetVersion && VersionLoader.VersionInfo.HasAppliedMigration(migrationInfo))
{
return true;
}
return false;
}
private void ApplyMigrationUp(IMigrationInfo migrationInfo, bool useTransaction)
{
if (!_alreadyOutputPreviewOnlyModeWarning && Processor.Options.PreviewOnly)
{
_announcer.Heading("PREVIEW-ONLY MODE");
_alreadyOutputPreviewOnlyModeWarning = true;
}
if (!VersionLoader.VersionInfo.HasAppliedMigration(migrationInfo))
{
var name = GetMigrationName(migrationInfo);
_announcer.Heading(string.Format("{0} migrating", name));
try
{
_stopWatch.Start();
if (useTransaction) Processor.BeginTransaction();
ExecuteMigration(migrationInfo.Migration, (m, c) => m.GetUpExpressions(c));
VersionLoader.UpdateVersionInfo(migrationInfo.Version, migrationInfo.FeatureName);
if (useTransaction) Processor.CommitTransaction();
_stopWatch.Stop();
_announcer.Say(string.Format("{0} migrated", name));
_announcer.ElapsedTime(_stopWatch.ElapsedTime());
}
catch (Exception)
{
if (useTransaction) Processor.RollbackTransaction();
throw;
}
}
}
private void ApplyMigrationDown(IMigrationInfo migrationInfo, bool useTransaction)
{
var name = GetMigrationName(migrationInfo);
_announcer.Heading(string.Format("{0} reverting", name));
try
{
_stopWatch.Start();
if (useTransaction) Processor.BeginTransaction();
ExecuteMigration(migrationInfo.Migration, (m, c) => m.GetDownExpressions(c));
VersionLoader.DeleteVersion(migrationInfo.Version, migrationInfo.FeatureName);
if (useTransaction) Processor.CommitTransaction();
_stopWatch.Stop();
_announcer.Say(string.Format("{0} reverted", name));
_announcer.ElapsedTime(_stopWatch.ElapsedTime());
}
catch (Exception)
{
if (useTransaction) Processor.RollbackTransaction();
throw;
}
}
public void Rollback(int steps)
{
Rollback(steps, true);
}
public void Rollback(int steps, bool useAutomaticTransactionManagement)
{
var availableMigrations = MigrationLoader.LoadMigrations();
var migrationsToRollback = new List<IMigrationInfo>();
foreach (string complexVersion in VersionLoader.VersionInfo.AppliedMigrations())
{
if (availableMigrations.Any(x => x.Value.ComplexVersion == complexVersion)) migrationsToRollback.Add(availableMigrations.First(x => x.Value.ComplexVersion == complexVersion).Value);
}
foreach (IMigrationInfo migrationInfo in migrationsToRollback.Take(steps))
{
ApplyMigrationDown(migrationInfo, useAutomaticTransactionManagement && migrationInfo.TransactionBehavior == TransactionBehavior.Default);
}
VersionLoader.LoadVersionInfo();
if (!VersionLoader.VersionInfo.AppliedMigrations().Any())
VersionLoader.RemoveVersionTable();
}
public void RollbackToVersion(long version)
{
RollbackToVersion(version, true);
}
public void RollbackToVersion(long version, bool useAutomaticTransactionManagement)
{
var availableMigrations = MigrationLoader.LoadMigrations();
var migrationsToRollback = new List<IMigrationInfo>();
foreach (string appliedComplexVersion in VersionLoader.VersionInfo.AppliedMigrations())
{
if (availableMigrations.Any(x => x.Value.ComplexVersion == appliedComplexVersion)) migrationsToRollback.Add(availableMigrations.First(x => x.Value.ComplexVersion == appliedComplexVersion).Value);
}
foreach (IMigrationInfo migrationInfo in migrationsToRollback)
{
if (version >= migrationInfo.Version) continue;
ApplyMigrationDown(migrationInfo, useAutomaticTransactionManagement && migrationInfo.TransactionBehavior == TransactionBehavior.Default);
}
VersionLoader.LoadVersionInfo();
if (version == 0 && !VersionLoader.VersionInfo.AppliedMigrations().Any())
VersionLoader.RemoveVersionTable();
}
public Assembly MigrationAssembly
{
get { return _migrationAssembly; }
}
private string GetMigrationName(IMigration migration)
{
if (migration == null) throw new ArgumentNullException("migration");
return string.Format("{0}", migration.GetType().Name);
}
private string GetMigrationName(IMigrationInfo migration)
{
if (migration == null) throw new ArgumentNullException("migration");
return string.Format("{0}: {1}", migration.ComplexVersion, migration.Migration.GetType().Name);
}
public void Up(IMigration migration)
{
var name = GetMigrationName(migration);
_announcer.Heading(string.Format("{0} migrating", name));
try
{
_stopWatch.Start();
Processor.BeginTransaction();
ExecuteMigration(migration, (m, c) => m.GetUpExpressions(c));
Processor.CommitTransaction();
_stopWatch.Stop();
_announcer.Say(string.Format("{0} migrated", name));
_announcer.ElapsedTime(_stopWatch.ElapsedTime());
}
catch (Exception)
{
Processor.RollbackTransaction();
throw;
}
}
private void ExecuteMigration(IMigration migration, Action<IMigration, IMigrationContext> getExpressions)
{
CaughtExceptions = new List<Exception>();
var context = new MigrationContext(Conventions, Processor, MigrationAssembly, ApplicationContext);
getExpressions(migration, context);
ApplyConventionsToAndValidateExpressions(migration, context.Expressions);
ExecuteExpressions(context.Expressions);
}
public void Down(IMigration migration)
{
var name = GetMigrationName(migration);
_announcer.Heading(string.Format("{0} reverting", name));
try
{
_stopWatch.Start();
Processor.BeginTransaction();
ExecuteMigration(migration, (m, c) => m.GetDownExpressions(c));
Processor.CommitTransaction();
_stopWatch.Stop();
_announcer.Say(string.Format("{0} reverted", name));
_announcer.ElapsedTime(_stopWatch.ElapsedTime());
}
catch (Exception)
{
Processor.RollbackTransaction();
throw;
}
}
/// <summary>
/// Validates each migration expression that has implemented the ICanBeValidated interface.
/// It throws an InvalidMigrationException exception if validation fails.
/// </summary>
/// <param name="migration">The current migration being run</param>
/// <param name="expressions">All the expressions contained in the up or down action</param>
protected void ApplyConventionsToAndValidateExpressions(IMigration migration, IEnumerable<IMigrationExpression> expressions)
{
var invalidExpressions = new Dictionary<string, string>();
foreach (var expression in expressions)
{
expression.ApplyConventions(Conventions);
var errors = new Collection<string>();
expression.CollectValidationErrors(errors);
if(errors.Count > 0)
invalidExpressions.Add(expression.GetType().Name, string.Join(" ", errors.ToArray()));
}
if (invalidExpressions.Count > 0)
{
var errorMessage = DictToString(invalidExpressions, "{0}: {1}");
_announcer.Error("The migration {0} contained the following Validation Error(s): {1}", migration.GetType().Name, errorMessage);
throw new InvalidMigrationException(migration, errorMessage);
}
}
private string DictToString<TKey, TValue>(Dictionary<TKey, TValue> items, string format)
{
format = String.IsNullOrEmpty(format) ? "{0}='{1}' " : format;
return items.Aggregate(new StringBuilder(), (sb, kvp) => sb.AppendFormat(format, kvp.Key, kvp.Value).AppendLine()).ToString();
}
/// <summary>
/// execute each migration expression in the expression collection
/// </summary>
/// <param name="expressions"></param>
protected void ExecuteExpressions(ICollection<IMigrationExpression> expressions)
{
long insertTicks = 0;
int insertCount = 0;
foreach (IMigrationExpression expression in expressions)
{
try
{
if (expression is InsertDataExpression)
{
insertTicks += Time(() => expression.ExecuteWith(Processor));
insertCount++;
}
else
{
AnnounceTime(expression.ToString(), () => expression.ExecuteWith(Processor));
}
}
catch (Exception er)
{
_announcer.Error(er.Message);
//catch the error and move onto the next expression
if (SilentlyFail)
{
CaughtExceptions.Add(er);
continue;
}
throw;
}
}
if (insertCount > 0)
{
var avg = new TimeSpan(insertTicks / insertCount);
var msg = string.Format("-> {0} Insert operations completed in {1} taking an average of {2}", insertCount, new TimeSpan(insertTicks), avg);
_announcer.Say(msg);
}
}
private void AnnounceTime(string message, Action action)
{
_announcer.Say(message);
_stopWatch.Start();
action();
_stopWatch.Stop();
_announcer.ElapsedTime(_stopWatch.ElapsedTime());
}
private long Time(Action action)
{
_stopWatch.Start();
action();
_stopWatch.Stop();
return _stopWatch.ElapsedTime().Ticks;
}
public void ValidateVersionOrder()
{
var unappliedVersions = MigrationLoader.LoadMigrations().Where(kvp => MigrationVersionLessThanGreatestAppliedMigration(kvp.Value)).ToList();
if (unappliedVersions.Any())
throw new VersionOrderInvalidException(unappliedVersions);
_announcer.Say("Version ordering valid.");
}
public void ListMigrations()
{
IVersionInfo currentVersionInfo = this.VersionLoader.VersionInfo;
string currentVersion = currentVersionInfo.Latest();
_announcer.Heading("Migrations");
foreach(var migration in MigrationLoader.LoadMigrations())
{
string migrationName = GetMigrationName(migration.Value);
bool isCurrent = migration.Value.ComplexVersion == currentVersion;
string message = string.Format("{0}{1}",
migrationName,
isCurrent ? " (current)" : string.Empty);
if(isCurrent)
_announcer.Emphasize(message);
else
_announcer.Say(message);
}
}
private bool MigrationVersionLessThanGreatestAppliedMigration(IMigrationInfo migrationInfo)
{
return VersionLoader.VersionInfo.HasAppliedMigration(migrationInfo);
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IcqStorageService.cs" company="Jan-Cornelius Molnar">
// The MIT License (MIT)
//
// Copyright (c) 2015 Jan-Cornelius Molnar
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Jcq.Core;
using Jcq.Core.Collections;
using Jcq.Core.Contracts.Collections;
using Jcq.IcqProtocol.Contracts;
using Jcq.IcqProtocol.DataTypes;
namespace Jcq.IcqProtocol
{
public class IcqStorageService : ContextService, IStorageService
{
public delegate void ContactListActivatedEventHandler(object sender, EventArgs e);
public delegate void ContactStatusChangedEventHandler(object sender, StatusChangedEventArgs e);
private readonly KeyedNotifiyingCollection<string, IcqContact> _allContacts =
new KeyedNotifiyingCollection<string, IcqContact>(c => c.Identifier);
private readonly KeyedNotifiyingCollection<string, IcqGroup> _groups =
new KeyedNotifiyingCollection<string, IcqGroup>(g => g.Identifier);
private readonly KeyedNotifiyingCollection<string, IcqContact> _storedContacts =
new KeyedNotifiyingCollection<string, IcqContact>(c => c.Identifier);
private SSIActionResultCode _codeSsiAkk;
private int _maxSsiItemId;
private SemaphoreSlim _transactionSemaphore;
public IcqStorageService(IContext context)
: base(context)
{
_visibleList = new NotifyingCollection<IContact>();
VisibleList = new ReadOnlyNotifyingCollection<IContact>(_visibleList);
_invisibleList = new NotifyingCollection<IContact>();
InvisibleList =
new ReadOnlyNotifyingCollection<IContact>(_invisibleList);
_ignoreList = new NotifyingCollection<IContact>();
IgnoreList =
new ReadOnlyNotifyingCollection<IContact>(_ignoreList);
var connector = context.GetService<IConnector>() as IcqConnector;
if (connector == null)
throw new InvalidCastException("Context Connector Service must be of Type IcqConnector");
_allContacts.Add((IcqContact) context.Identity);
context.Identity.PropertyChanged += OnContactPropertyChanged;
connector.RegisterSnacHandler(0x13, 0x6, new Action<Snac1306>(AnalyseSnac1306));
connector.RegisterSnacHandler(0x13, 0x8, new Action<Snac1308>(AnalyseSnac1308));
connector.RegisterSnacHandler(0x13, 0xa, new Action<Snac130A>(AnalyseSnac130A));
connector.RegisterSnacHandler(0x13, 0xe, new Action<Snac130E>(AnalyseSnac130E));
connector.RegisterSnacHandler(0x13, 0xf, new Action<Snac130F>(AnalyseSnac130F));
}
public IcqGroup MasterGroup { get; private set; }
public void RegisterLocalContactList(int itemCount, DateTime dateChanged)
{
Info = new ContactListInfo(itemCount, dateChanged);
IsFreshContactList = false;
}
public IContactListInfo Info { get; private set; }
public bool IsContactListAvailable
{
get { return Info != null; }
}
public bool IsFreshContactList { get; private set; } = true;
public event EventHandler ContactListActivated;
public event EventHandler<StatusChangedEventArgs> ContactStatusChanged;
IGroup IStorageService.MasterGroup
{
get { return MasterGroup; }
}
IReadOnlyNotifyingCollection<IContact> IStorageService.Contacts
{
get { return _storedContacts; }
}
IReadOnlyNotifyingCollection<IGroup> IStorageService.Groups
{
get { return _groups; }
}
IContact IStorageService.GetContactByIdentifier(string identifier)
{
return GetContactByIdentifier(identifier);
}
IGroup IStorageService.GetGroupByIdentifier(string identifier)
{
return GetGroupByIdentifier(identifier);
}
public bool IsContactStored(IContact contact)
{
var icqContact = contact as IcqContact;
if (icqContact == null)
throw new ArgumentException("Argument of type IcqContact required", nameof(contact));
return IsContactStored(icqContact);
}
public Task AddContact(IContact contact, IGroup group)
{
var icqContact = contact as IcqContact;
var icqGroup = group as IcqGroup;
if (icqContact == null)
throw new ArgumentException("Argument of type IcqContact required", nameof(contact));
if (icqGroup == null)
throw new ArgumentException("Argument of type IcqGroup required", nameof(group));
return AddContact(icqContact, icqGroup);
}
public void AttachContact(IContact contact, IGroup group, bool stored)
{
var icqContact = contact as IcqContact;
var icqGroup = group as IcqGroup;
if (icqContact == null)
throw new ArgumentException("Argument of type IcqContact required", nameof(contact));
if (icqGroup == null)
throw new ArgumentException("Argument of type IcqGroup required", nameof(group));
AttachContact(icqContact, icqGroup, stored);
}
public Task RemoveContact(IContact contact, IGroup group)
{
var icqContact = contact as IcqContact;
var icqGroup = group as IcqGroup;
if (icqContact == null)
throw new ArgumentException("Argument of type IcqContact required", nameof(contact));
if (icqGroup == null)
throw new ArgumentException("Argument of type IcqGroup required", nameof(group));
return RemoveContact(icqContact, icqGroup);
}
public Task UpdateContact(IContact contact)
{
var icqContact = contact as IcqContact;
if (icqContact == null)
throw new ArgumentException("Argument of type IcqContact required", nameof(contact));
return UpdateContact(icqContact);
}
public Task AddGroup(IGroup group)
{
var icqGroup = group as IcqGroup;
if (icqGroup == null)
throw new ArgumentException("Argument of type IcqGroup required", nameof(group));
return AddGroup(icqGroup);
}
public Task RemoveGroup(IGroup group)
{
var icqGroup = group as IcqGroup;
if (icqGroup == null)
throw new ArgumentException("Argument of type IcqGroup required", nameof(group));
return RemoveGroup(icqGroup);
}
public Task UpdateGroup(IGroup group)
{
var icqGroup = group as IcqGroup;
if (icqGroup == null)
throw new ArgumentException("Argument of type IcqGroup required", nameof(group));
return UpdateGroup(icqGroup);
}
public IcqContact GetContactByIdentifier(string identifier)
{
IcqContact contact;
if (!_allContacts.Contains(identifier))
{
contact = new IcqContact(identifier, identifier);
_allContacts.Add(contact);
contact.PropertyChanged += OnContactPropertyChanged;
}
else
{
contact = _allContacts[identifier];
}
return contact;
}
public IcqGroup GetGroupByIdentifier(string identifier)
{
return _groups.Contains(identifier) ? _groups[identifier] : null;
}
public Task AddContact(IcqContact contact, IcqGroup group)
{
var trans = new AddContactTransaction(this, contact, group);
return CommitSSITransaction(trans);
}
public Task RemoveContact(IcqContact contact, IcqGroup group)
{
var trans = new RemoveContactTransaction(this, contact);
return CommitSSITransaction(trans);
}
public void AttachContact(IcqContact contact, IcqGroup group, bool stored)
{
if (!_allContacts.Contains(contact.Identifier))
{
_allContacts.Add(contact);
contact.PropertyChanged += OnContactPropertyChanged;
}
if (!stored) return;
if (!_storedContacts.Contains(contact.Identifier))
_storedContacts.Add(contact);
if (!group.Contacts.Contains(contact))
group.Contacts.Add(contact);
}
public Task AddGroup(IcqGroup group)
{
throw new NotImplementedException();
}
public Task RemoveGroup(IcqGroup group)
{
throw new NotImplementedException();
}
public Task UpdateContact(IcqContact contact)
{
throw new NotImplementedException();
}
public Task UpdateGroup(IcqGroup group)
{
throw new NotImplementedException();
}
public bool IsContactStored(IcqContact contact)
{
return _storedContacts.Contains(contact);
}
private IcqGroup GetGroupByGroupId(int groupId)
{
return _groups.Cast<IcqGroup>().FirstOrDefault(g => g.GroupId == groupId);
}
public int GetNextSsiItemId()
{
return Interlocked.Increment(ref _maxSsiItemId);
}
internal void InnerAddContactToStorage(IcqContact contact, IcqGroup group)
{
if (!_storedContacts.Contains(contact.Identifier))
_storedContacts.Add(contact);
contact.SetGroup(group);
if (!contact.Group.Contacts.Contains(contact))
group.Contacts.Add(contact);
}
internal void InnerAddContactToVisibleList(IcqContact contact)
{
if (!_visibleList.Contains(contact))
_visibleList.Add(contact);
}
internal void InnerAddContactToInvisibleList(IcqContact contact)
{
if (!_invisibleList.Contains(contact))
_invisibleList.Add(contact);
}
internal void InnerAddContactToIgnoreList(IcqContact contact)
{
if (!_ignoreList.Contains(contact))
_ignoreList.Add(contact);
}
internal void InnerRemoveContactFromStorage(IcqContact contact)
{
if (!_storedContacts.Contains(contact.Identifier))
_storedContacts.Remove(contact.Identifier);
if (contact.Group.Contacts.Contains(contact))
contact.Group.Contacts.Remove(contact);
}
internal void InnerRemoveContactFromVisibleList(IcqContact contact)
{
if (_visibleList.Contains(contact))
_visibleList.Remove(contact);
}
internal void InnerRemoveContactFromInvisibleList(IcqContact contact)
{
if (_invisibleList.Contains(contact))
_invisibleList.Remove(contact);
}
internal void InnerRemoveContactFromIgnoreList(IcqContact contact)
{
if (_ignoreList.Contains(contact))
_ignoreList.Remove(contact);
}
public async Task CommitSSITransaction(ISsiTransaction transaction)
{
// Check wheter all prerequirements are met to commit the transaction.
transaction.Validate();
var transfer = (IIcqDataTranferService) Context.GetService<IConnector>();
// Create the transaction data
var beginTransaction = new Snac1311();
Snac item = transaction.CreateSnac();
var endTransaction = new Snac1312();
//_transactionCompletionSource = new TaskCompletionSource<SSIActionResultCode>();
// TODO: Check that there are no concurrent transactions!
_transactionSemaphore = new SemaphoreSlim(0, 1);
// Send data.
await transfer.Send(beginTransaction, item, endTransaction);
// Wait for server response.
if (!await _transactionSemaphore.WaitAsync(TimeSpan.FromSeconds(5)))
{
throw new TimeoutException("Server did not respond.");
}
transaction.OnComplete(_codeSsiAkk);
_transactionSemaphore = null;
}
public void DetachContact(IcqContact contact, IcqGroup group)
{
if (group.Contacts.Contains(contact))
group.Contacts.Add(contact);
if (_storedContacts.Contains(contact.Identifier))
_storedContacts.Add(contact);
}
internal void AnalyseSnac130E(Snac130E dataIn)
{
if (_transactionSemaphore != null)
{
_codeSsiAkk = dataIn.ActionResultCodes.First();
//_waitSsiAkk.Set();
_transactionSemaphore.Release();
}
foreach (SSIActionResultCode code in dataIn.ActionResultCodes)
{
Debug.WriteLine(string.Format("SSI Change Akk: {0}", code), "IcqStorageService");
}
}
internal void AnalyseSnac1306(Snac1306 dataIn)
{
try
{
_maxSsiItemId = Math.Max(_maxSsiItemId, dataIn.MaxItemId);
foreach (SSIGroupRecord ssiGroup in dataIn.GroupRecords)
{
string identifier = ssiGroup.ItemName;
var group = new IcqGroup(identifier, ssiGroup.GroupId);
if (group.GroupId == 0)
{
MasterGroup = group;
}
else
{
_groups.Add(group);
}
}
foreach (IcqGroup x in _groups)
{
MasterGroup.Groups.Add(x);
}
foreach (SSIBuddyRecord ssiContact in dataIn.BuddyRecords)
{
string identifier = ssiContact.ItemName;
IcqGroup group = GetGroupByGroupId(ssiContact.GroupId);
int identifierId;
if (!int.TryParse(identifier, out identifierId))
continue;
IcqContact contact = GetContactByIdentifier(identifier);
if (contact.LastShortUserInfoRequest <= DateTime.MinValue)
contact.Name = ssiContact.LocalScreenName.LocalScreenName;
contact.ItemId = ssiContact.ItemId;
contact.SetGroup(group);
AttachContact(contact, group, true);
}
foreach (SSIDenyRecord record in dataIn.DenyRecords)
{
string identifier = record.ItemName;
IcqContact contact = GetContactByIdentifier(identifier);
contact.DenyRecordItemId = record.ItemId;
_invisibleList.Add(contact);
}
foreach (SSIPermitRecord record in dataIn.PermitRecords)
{
string identifier = record.ItemName;
IcqContact contact = GetContactByIdentifier(identifier);
contact.PermitRecordItemId = record.ItemId;
_visibleList.Add(contact);
}
foreach (SSIIgnoreListRecord record in dataIn.IgnoreListRecords)
{
string identifier = record.ItemName;
IcqContact contact = GetContactByIdentifier(identifier);
contact.IgnoreRecordItemId = record.ItemId;
_ignoreList.Add(contact);
}
Info = new ContactListInfo(dataIn.ItemCount, dataIn.LastChange);
ContactListActivated?.Invoke(this, EventArgs.Empty);
Kernel.Logger.Log("IcqStorageService", TraceEventType.Verbose, "Contact list activated.");
}
catch (Exception ex)
{
Kernel.Exceptions.PublishException(ex);
}
}
internal void AnalyseSnac130F(Snac130F dataIn)
{
try
{
Info = new ContactListInfo(dataIn.NumberOfItems, dataIn.ModificationDate);
ContactListActivated?.Invoke(this, EventArgs.Empty);
}
catch (Exception ex)
{
Kernel.Exceptions.PublishException(ex);
}
}
internal void AnalyseSnac1308(Snac1308 dataIn)
{
// Sever informs the client that items have beend added to the SSI Store.
try
{
foreach (SSIGroupRecord ssiGroup in dataIn.GroupRecords)
{
string identifier = ssiGroup.ItemName;
var group = new IcqGroup(identifier, ssiGroup.GroupId);
_groups.Add(group);
}
foreach (SSIBuddyRecord ssiContact in dataIn.BuddyRecords)
{
string identifier = ssiContact.ItemName;
IcqGroup group = GetGroupByGroupId(ssiContact.GroupId);
int identifierId;
if (!int.TryParse(identifier, out identifierId))
continue;
IcqContact contact = GetContactByIdentifier(identifier);
if (contact.LastShortUserInfoRequest <= DateTime.MinValue)
contact.Name = ssiContact.LocalScreenName.LocalScreenName;
contact.ItemId = ssiContact.ItemId;
contact.SetGroup(group);
AttachContact(contact, group, true);
}
foreach (SSIDenyRecord record in dataIn.DenyRecords)
{
string identifier = record.ItemName;
IcqContact contact = GetContactByIdentifier(identifier);
contact.DenyRecordItemId = record.ItemId;
_invisibleList.Add(contact);
}
foreach (SSIPermitRecord record in dataIn.PermitRecords)
{
string identifier = record.ItemName;
IcqContact contact = GetContactByIdentifier(identifier);
contact.PermitRecordItemId = record.ItemId;
_visibleList.Add(contact);
}
foreach (SSIIgnoreListRecord record in dataIn.IgnoreListRecords)
{
string identifier = record.ItemName;
IcqContact contact = GetContactByIdentifier(identifier);
contact.IgnoreRecordItemId = record.ItemId;
_ignoreList.Add(contact);
}
}
catch (Exception ex)
{
Kernel.Exceptions.PublishException(ex);
}
}
internal void AnalyseSnac130A(Snac130A dataIn)
{
// Sever informs the client that items have beend removed from the SSI Store.
try
{
foreach (
IcqContact contact in dataIn.DenyRecords.Select(record => GetContactByIdentifier(record.ItemName)))
{
contact.DenyRecordItemId = 0;
_invisibleList.Remove(contact);
}
foreach (
IcqContact contact in dataIn.PermitRecords.Select(record => GetContactByIdentifier(record.ItemName))
)
{
contact.PermitRecordItemId = 0;
_visibleList.Remove(contact);
}
foreach (
IcqContact contact in
dataIn.IgnoreListRecords.Select(record => GetContactByIdentifier(record.ItemName)))
{
contact.IgnoreRecordItemId = 0;
_ignoreList.Remove(contact);
}
foreach (SSIBuddyRecord ssiContact in dataIn.BuddyRecords)
{
string identifier = ssiContact.ItemName;
IcqGroup group = GetGroupByGroupId(ssiContact.GroupId);
int identifierId;
if (!int.TryParse(identifier, out identifierId))
continue;
IcqContact contact = GetContactByIdentifier(identifier);
DetachContact(contact, group);
}
foreach (SSIGroupRecord ssiGroup in dataIn.GroupRecords)
{
string identifier = ssiGroup.ItemName;
var group = new IcqGroup(identifier, ssiGroup.GroupId);
_groups.Remove(group);
}
}
catch (Exception ex)
{
Kernel.Exceptions.PublishException(ex);
}
}
protected void OnContactPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName != "Status") return;
var contact = sender as IContact;
if (contact == null) return;
var args = new StatusChangedEventArgs(contact.Status, contact);
ContactStatusChanged?.Invoke(this, args);
}
#region Privacy Lists
private readonly NotifyingCollection<IContact> _visibleList;
public ReadOnlyNotifyingCollection<IContact> VisibleList { get; }
private readonly NotifyingCollection<IContact> _invisibleList;
public ReadOnlyNotifyingCollection<IContact> InvisibleList { get; }
private readonly NotifyingCollection<IContact> _ignoreList;
public ReadOnlyNotifyingCollection<IContact> IgnoreList { get; }
#endregion
}
}
| |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using Google.Protobuf.Collections;
using System;
using System.Collections.Generic;
using System.IO;
namespace Google.Protobuf
{
/// <summary>
/// Reads and decodes protocol message fields.
/// </summary>
/// <remarks>
/// <para>
/// This class is generally used by generated code to read appropriate
/// primitives from the stream. It effectively encapsulates the lowest
/// levels of protocol buffer format.
/// </para>
/// <para>
/// Repeated fields and map fields are not handled by this class; use <see cref="RepeatedField{T}"/>
/// and <see cref="MapField{TKey, TValue}"/> to serialize such fields.
/// </para>
/// </remarks>
public sealed class CodedInputStream
{
/// <summary>
/// Buffer of data read from the stream or provided at construction time.
/// </summary>
private readonly byte[] buffer;
/// <summary>
/// The index of the buffer at which we need to refill from the stream (if there is one).
/// </summary>
private int bufferSize;
private int bufferSizeAfterLimit = 0;
/// <summary>
/// The position within the current buffer (i.e. the next byte to read)
/// </summary>
private int bufferPos = 0;
/// <summary>
/// The stream to read further input from, or null if the byte array buffer was provided
/// directly on construction, with no further data available.
/// </summary>
private readonly Stream input;
/// <summary>
/// The last tag we read. 0 indicates we've read to the end of the stream
/// (or haven't read anything yet).
/// </summary>
private uint lastTag = 0;
/// <summary>
/// The next tag, used to store the value read by PeekTag.
/// </summary>
private uint nextTag = 0;
private bool hasNextTag = false;
internal const int DefaultRecursionLimit = 64;
internal const int DefaultSizeLimit = 64 << 20; // 64MB
internal const int BufferSize = 4096;
/// <summary>
/// The total number of bytes read before the current buffer. The
/// total bytes read up to the current position can be computed as
/// totalBytesRetired + bufferPos.
/// </summary>
private int totalBytesRetired = 0;
/// <summary>
/// The absolute position of the end of the current message.
/// </summary>
private int currentLimit = int.MaxValue;
private int recursionDepth = 0;
private readonly int recursionLimit;
private readonly int sizeLimit;
#region Construction
// Note that the checks are performed such that we don't end up checking obviously-valid things
// like non-null references for arrays we've just created.
/// <summary>
/// Creates a new CodedInputStream reading data from the given byte array.
/// </summary>
public CodedInputStream(byte[] buffer) : this(null, Preconditions.CheckNotNull(buffer, "buffer"), 0, buffer.Length)
{
}
/// <summary>
/// Creates a new CodedInputStream that reads from the given byte array slice.
/// </summary>
public CodedInputStream(byte[] buffer, int offset, int length)
: this(null, Preconditions.CheckNotNull(buffer, "buffer"), offset, offset + length)
{
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException("offset", "Offset must be within the buffer");
}
if (length < 0 || offset + length > buffer.Length)
{
throw new ArgumentOutOfRangeException("length", "Length must be non-negative and within the buffer");
}
}
/// <summary>
/// Creates a new CodedInputStream reading data from the given stream.
/// </summary>
public CodedInputStream(Stream input) : this(input, new byte[BufferSize], 0, 0)
{
Preconditions.CheckNotNull(input, "input");
}
/// <summary>
/// Creates a new CodedInputStream reading data from the given
/// stream and buffer, using the default limits.
/// </summary>
internal CodedInputStream(Stream input, byte[] buffer, int bufferPos, int bufferSize)
{
this.input = input;
this.buffer = buffer;
this.bufferPos = bufferPos;
this.bufferSize = bufferSize;
this.sizeLimit = DefaultSizeLimit;
this.recursionLimit = DefaultRecursionLimit;
}
/// <summary>
/// Creates a new CodedInputStream reading data from the given
/// stream and buffer, using the specified limits.
/// </summary>
/// <remarks>
/// This chains to the version with the default limits instead of vice versa to avoid
/// having to check that the default values are valid every time.
/// </remarks>
internal CodedInputStream(Stream input, byte[] buffer, int bufferPos, int bufferSize, int sizeLimit, int recursionLimit)
: this(input, buffer, bufferPos, bufferSize)
{
if (sizeLimit <= 0)
{
throw new ArgumentOutOfRangeException("sizeLimit", "Size limit must be positive");
}
if (recursionLimit <= 0)
{
throw new ArgumentOutOfRangeException("recursionLimit!", "Recursion limit must be positive");
}
this.sizeLimit = sizeLimit;
this.recursionLimit = recursionLimit;
}
#endregion
/// <summary>
/// Creates a <see cref="CodedInputStream"/> with the specified size and recursion limits, reading
/// from an input stream.
/// </summary>
/// <remarks>
/// This method exists separately from the constructor to reduce the number of constructor overloads.
/// It is likely to be used considerably less frequently than the constructors, as the default limits
/// are suitable for most use cases.
/// </remarks>
/// <param name="input">The input stream to read from</param>
/// <param name="sizeLimit">The total limit of data to read from the stream.</param>
/// <param name="recursionLimit">The maximum recursion depth to allow while reading.</param>
/// <returns>A <c>CodedInputStream</c> reading from <paramref name="input"/> with the specified size
/// and recursion limits.</returns>
public static CodedInputStream CreateWithLimits(Stream input, int sizeLimit, int recursionLimit)
{
return new CodedInputStream(input, new byte[BufferSize], 0, 0, sizeLimit, recursionLimit);
}
/// <summary>
/// Returns the current position in the input stream, or the position in the input buffer
/// </summary>
public long Position
{
get
{
if (input != null)
{
return input.Position - ((bufferSize + bufferSizeAfterLimit) - bufferPos);
}
return bufferPos;
}
}
/// <summary>
/// Returns the last tag read, or 0 if no tags have been read or we've read beyond
/// the end of the stream.
/// </summary>
internal uint LastTag { get { return lastTag; } }
/// <summary>
/// Returns the size limit for this stream.
/// </summary>
/// <remarks>
/// This limit is applied when reading from the underlying stream, as a sanity check. It is
/// not applied when reading from a byte array data source without an underlying stream.
/// The default value is 64MB.
/// </remarks>
/// <value>
/// The size limit.
/// </value>
public int SizeLimit { get { return sizeLimit; } }
/// <summary>
/// Returns the recursion limit for this stream. This limit is applied whilst reading messages,
/// to avoid maliciously-recursive data.
/// </summary>
/// <remarks>
/// The default limit is 64.
/// </remarks>
/// <value>
/// The recursion limit for this stream.
/// </value>
public int RecursionLimit { get { return recursionLimit; } }
#region Validation
/// <summary>
/// Verifies that the last call to ReadTag() returned tag 0 - in other words,
/// we've reached the end of the stream when we expected to.
/// </summary>
/// <exception cref="InvalidProtocolBufferException">The
/// tag read was not the one specified</exception>
internal void CheckReadEndOfStreamTag()
{
if (lastTag != 0)
{
throw InvalidProtocolBufferException.MoreDataAvailable();
}
}
#endregion
#region Reading of tags etc
/// <summary>
/// Peeks at the next field tag. This is like calling <see cref="ReadTag"/>, but the
/// tag is not consumed. (So a subsequent call to <see cref="ReadTag"/> will return the
/// same value.)
/// </summary>
public uint PeekTag()
{
if (hasNextTag)
{
return nextTag;
}
uint savedLast = lastTag;
nextTag = ReadTag();
hasNextTag = true;
lastTag = savedLast; // Undo the side effect of ReadTag
return nextTag;
}
/// <summary>
/// Reads a field tag, returning the tag of 0 for "end of stream".
/// </summary>
/// <remarks>
/// If this method returns 0, it doesn't necessarily mean the end of all
/// the data in this CodedInputStream; it may be the end of the logical stream
/// for an embedded message, for example.
/// </remarks>
/// <returns>The next field tag, or 0 for end of stream. (0 is never a valid tag.)</returns>
public uint ReadTag()
{
if (hasNextTag)
{
lastTag = nextTag;
hasNextTag = false;
return lastTag;
}
// Optimize for the incredibly common case of having at least two bytes left in the buffer,
// and those two bytes being enough to get the tag. This will be true for fields up to 4095.
if (bufferPos + 2 <= bufferSize)
{
int tmp = buffer[bufferPos++];
if (tmp < 128)
{
lastTag = (uint)tmp;
}
else
{
int result = tmp & 0x7f;
if ((tmp = buffer[bufferPos++]) < 128)
{
result |= tmp << 7;
lastTag = (uint) result;
}
else
{
// Nope, rewind and go the potentially slow route.
bufferPos -= 2;
lastTag = ReadRawVarint32();
}
}
}
else
{
if (IsAtEnd)
{
lastTag = 0;
return 0; // This is the only case in which we return 0.
}
lastTag = ReadRawVarint32();
}
if (lastTag == 0)
{
// If we actually read zero, that's not a valid tag.
throw InvalidProtocolBufferException.InvalidTag();
}
return lastTag;
}
/// <summary>
/// Skips the data for the field with the tag we've just read.
/// This should be called directly after <see cref="ReadTag"/>, when
/// the caller wishes to skip an unknown field.
/// </summary>
public void SkipLastField()
{
if (lastTag == 0)
{
throw new InvalidOperationException("SkipLastField cannot be called at the end of a stream");
}
switch (WireFormat.GetTagWireType(lastTag))
{
case WireFormat.WireType.StartGroup:
SkipGroup();
break;
case WireFormat.WireType.EndGroup:
// Just ignore; there's no data following the tag.
break;
case WireFormat.WireType.Fixed32:
ReadFixed32();
break;
case WireFormat.WireType.Fixed64:
ReadFixed64();
break;
case WireFormat.WireType.LengthDelimited:
var length = ReadLength();
SkipRawBytes(length);
break;
case WireFormat.WireType.Varint:
ReadRawVarint32();
break;
}
}
private void SkipGroup()
{
// Note: Currently we expect this to be the way that groups are read. We could put the recursion
// depth changes into the ReadTag method instead, potentially...
recursionDepth++;
if (recursionDepth >= recursionLimit)
{
throw InvalidProtocolBufferException.RecursionLimitExceeded();
}
uint tag;
do
{
tag = ReadTag();
if (tag == 0)
{
throw InvalidProtocolBufferException.TruncatedMessage();
}
// This recursion will allow us to handle nested groups.
SkipLastField();
} while (WireFormat.GetTagWireType(tag) != WireFormat.WireType.EndGroup);
recursionDepth--;
}
/// <summary>
/// Reads a double field from the stream.
/// </summary>
public double ReadDouble()
{
return BitConverter.Int64BitsToDouble((long) ReadRawLittleEndian64());
}
/// <summary>
/// Reads a float field from the stream.
/// </summary>
public float ReadFloat()
{
if (BitConverter.IsLittleEndian && 4 <= bufferSize - bufferPos)
{
float ret = BitConverter.ToSingle(buffer, bufferPos);
bufferPos += 4;
return ret;
}
else
{
byte[] rawBytes = ReadRawBytes(4);
if (!BitConverter.IsLittleEndian)
{
ByteArray.Reverse(rawBytes);
}
return BitConverter.ToSingle(rawBytes, 0);
}
}
/// <summary>
/// Reads a uint64 field from the stream.
/// </summary>
public ulong ReadUInt64()
{
return ReadRawVarint64();
}
/// <summary>
/// Reads an int64 field from the stream.
/// </summary>
public long ReadInt64()
{
return (long) ReadRawVarint64();
}
/// <summary>
/// Reads an int32 field from the stream.
/// </summary>
public int ReadInt32()
{
return (int) ReadRawVarint32();
}
/// <summary>
/// Reads a fixed64 field from the stream.
/// </summary>
public ulong ReadFixed64()
{
return ReadRawLittleEndian64();
}
/// <summary>
/// Reads a fixed32 field from the stream.
/// </summary>
public uint ReadFixed32()
{
return ReadRawLittleEndian32();
}
/// <summary>
/// Reads a bool field from the stream.
/// </summary>
public bool ReadBool()
{
return ReadRawVarint32() != 0;
}
/// <summary>
/// Reads a string field from the stream.
/// </summary>
public string ReadString()
{
int length = ReadLength();
// No need to read any data for an empty string.
if (length == 0)
{
return "";
}
if (length <= bufferSize - bufferPos)
{
// Fast path: We already have the bytes in a contiguous buffer, so
// just copy directly from it.
String result = CodedOutputStream.Utf8Encoding.GetString(buffer, bufferPos, length);
bufferPos += length;
return result;
}
// Slow path: Build a byte array first then copy it.
return CodedOutputStream.Utf8Encoding.GetString(ReadRawBytes(length), 0, length);
}
/// <summary>
/// Reads an embedded message field value from the stream.
/// </summary>
public void ReadMessage(IMessage builder)
{
int length = ReadLength();
if (recursionDepth >= recursionLimit)
{
throw InvalidProtocolBufferException.RecursionLimitExceeded();
}
int oldLimit = PushLimit(length);
++recursionDepth;
builder.MergeFrom(this);
CheckReadEndOfStreamTag();
// Check that we've read exactly as much data as expected.
if (!ReachedLimit)
{
throw InvalidProtocolBufferException.TruncatedMessage();
}
--recursionDepth;
PopLimit(oldLimit);
}
/// <summary>
/// Reads a bytes field value from the stream.
/// </summary>
public ByteString ReadBytes()
{
int length = ReadLength();
if (length <= bufferSize - bufferPos && length > 0)
{
// Fast path: We already have the bytes in a contiguous buffer, so
// just copy directly from it.
ByteString result = ByteString.CopyFrom(buffer, bufferPos, length);
bufferPos += length;
return result;
}
else
{
// Slow path: Build a byte array and attach it to a new ByteString.
return ByteString.AttachBytes(ReadRawBytes(length));
}
}
/// <summary>
/// Reads a uint32 field value from the stream.
/// </summary>
public uint ReadUInt32()
{
return ReadRawVarint32();
}
/// <summary>
/// Reads an enum field value from the stream. If the enum is valid for type T,
/// then the ref value is set and it returns true. Otherwise the unknown output
/// value is set and this method returns false.
/// </summary>
public int ReadEnum()
{
// Currently just a pass-through, but it's nice to separate it logically from WriteInt32.
return (int) ReadRawVarint32();
}
/// <summary>
/// Reads an sfixed32 field value from the stream.
/// </summary>
public int ReadSFixed32()
{
return (int) ReadRawLittleEndian32();
}
/// <summary>
/// Reads an sfixed64 field value from the stream.
/// </summary>
public long ReadSFixed64()
{
return (long) ReadRawLittleEndian64();
}
/// <summary>
/// Reads an sint32 field value from the stream.
/// </summary>
public int ReadSInt32()
{
return DecodeZigZag32(ReadRawVarint32());
}
/// <summary>
/// Reads an sint64 field value from the stream.
/// </summary>
public long ReadSInt64()
{
return DecodeZigZag64(ReadRawVarint64());
}
/// <summary>
/// Reads a length for length-delimited data.
/// </summary>
/// <remarks>
/// This is internally just reading a varint, but this method exists
/// to make the calling code clearer.
/// </remarks>
public int ReadLength()
{
return (int) ReadRawVarint32();
}
/// <summary>
/// Peeks at the next tag in the stream. If it matches <paramref name="tag"/>,
/// the tag is consumed and the method returns <c>true</c>; otherwise, the
/// stream is left in the original position and the method returns <c>false</c>.
/// </summary>
public bool MaybeConsumeTag(uint tag)
{
if (PeekTag() == tag)
{
hasNextTag = false;
return true;
}
return false;
}
#endregion
#region Underlying reading primitives
/// <summary>
/// Same code as ReadRawVarint32, but read each byte individually, checking for
/// buffer overflow.
/// </summary>
private uint SlowReadRawVarint32()
{
int tmp = ReadRawByte();
if (tmp < 128)
{
return (uint) tmp;
}
int result = tmp & 0x7f;
if ((tmp = ReadRawByte()) < 128)
{
result |= tmp << 7;
}
else
{
result |= (tmp & 0x7f) << 7;
if ((tmp = ReadRawByte()) < 128)
{
result |= tmp << 14;
}
else
{
result |= (tmp & 0x7f) << 14;
if ((tmp = ReadRawByte()) < 128)
{
result |= tmp << 21;
}
else
{
result |= (tmp & 0x7f) << 21;
result |= (tmp = ReadRawByte()) << 28;
if (tmp >= 128)
{
// Discard upper 32 bits.
for (int i = 0; i < 5; i++)
{
if (ReadRawByte() < 128)
{
return (uint) result;
}
}
throw InvalidProtocolBufferException.MalformedVarint();
}
}
}
}
return (uint) result;
}
/// <summary>
/// Reads a raw Varint from the stream. If larger than 32 bits, discard the upper bits.
/// This method is optimised for the case where we've got lots of data in the buffer.
/// That means we can check the size just once, then just read directly from the buffer
/// without constant rechecking of the buffer length.
/// </summary>
internal uint ReadRawVarint32()
{
if (bufferPos + 5 > bufferSize)
{
return SlowReadRawVarint32();
}
int tmp = buffer[bufferPos++];
if (tmp < 128)
{
return (uint) tmp;
}
int result = tmp & 0x7f;
if ((tmp = buffer[bufferPos++]) < 128)
{
result |= tmp << 7;
}
else
{
result |= (tmp & 0x7f) << 7;
if ((tmp = buffer[bufferPos++]) < 128)
{
result |= tmp << 14;
}
else
{
result |= (tmp & 0x7f) << 14;
if ((tmp = buffer[bufferPos++]) < 128)
{
result |= tmp << 21;
}
else
{
result |= (tmp & 0x7f) << 21;
result |= (tmp = buffer[bufferPos++]) << 28;
if (tmp >= 128)
{
// Discard upper 32 bits.
// Note that this has to use ReadRawByte() as we only ensure we've
// got at least 5 bytes at the start of the method. This lets us
// use the fast path in more cases, and we rarely hit this section of code.
for (int i = 0; i < 5; i++)
{
if (ReadRawByte() < 128)
{
return (uint) result;
}
}
throw InvalidProtocolBufferException.MalformedVarint();
}
}
}
}
return (uint) result;
}
/// <summary>
/// Reads a varint from the input one byte at a time, so that it does not
/// read any bytes after the end of the varint. If you simply wrapped the
/// stream in a CodedInputStream and used ReadRawVarint32(Stream)
/// then you would probably end up reading past the end of the varint since
/// CodedInputStream buffers its input.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
internal static uint ReadRawVarint32(Stream input)
{
int result = 0;
int offset = 0;
for (; offset < 32; offset += 7)
{
int b = input.ReadByte();
if (b == -1)
{
throw InvalidProtocolBufferException.TruncatedMessage();
}
result |= (b & 0x7f) << offset;
if ((b & 0x80) == 0)
{
return (uint) result;
}
}
// Keep reading up to 64 bits.
for (; offset < 64; offset += 7)
{
int b = input.ReadByte();
if (b == -1)
{
throw InvalidProtocolBufferException.TruncatedMessage();
}
if ((b & 0x80) == 0)
{
return (uint) result;
}
}
throw InvalidProtocolBufferException.MalformedVarint();
}
/// <summary>
/// Reads a raw varint from the stream.
/// </summary>
internal ulong ReadRawVarint64()
{
int shift = 0;
ulong result = 0;
while (shift < 64)
{
byte b = ReadRawByte();
result |= (ulong) (b & 0x7F) << shift;
if ((b & 0x80) == 0)
{
return result;
}
shift += 7;
}
throw InvalidProtocolBufferException.MalformedVarint();
}
/// <summary>
/// Reads a 32-bit little-endian integer from the stream.
/// </summary>
internal uint ReadRawLittleEndian32()
{
uint b1 = ReadRawByte();
uint b2 = ReadRawByte();
uint b3 = ReadRawByte();
uint b4 = ReadRawByte();
return b1 | (b2 << 8) | (b3 << 16) | (b4 << 24);
}
/// <summary>
/// Reads a 64-bit little-endian integer from the stream.
/// </summary>
internal ulong ReadRawLittleEndian64()
{
ulong b1 = ReadRawByte();
ulong b2 = ReadRawByte();
ulong b3 = ReadRawByte();
ulong b4 = ReadRawByte();
ulong b5 = ReadRawByte();
ulong b6 = ReadRawByte();
ulong b7 = ReadRawByte();
ulong b8 = ReadRawByte();
return b1 | (b2 << 8) | (b3 << 16) | (b4 << 24)
| (b5 << 32) | (b6 << 40) | (b7 << 48) | (b8 << 56);
}
/// <summary>
/// Decode a 32-bit value with ZigZag encoding.
/// </summary>
/// <remarks>
/// ZigZag encodes signed integers into values that can be efficiently
/// encoded with varint. (Otherwise, negative values must be
/// sign-extended to 64 bits to be varint encoded, thus always taking
/// 10 bytes on the wire.)
/// </remarks>
internal static int DecodeZigZag32(uint n)
{
return (int)(n >> 1) ^ -(int)(n & 1);
}
/// <summary>
/// Decode a 32-bit value with ZigZag encoding.
/// </summary>
/// <remarks>
/// ZigZag encodes signed integers into values that can be efficiently
/// encoded with varint. (Otherwise, negative values must be
/// sign-extended to 64 bits to be varint encoded, thus always taking
/// 10 bytes on the wire.)
/// </remarks>
internal static long DecodeZigZag64(ulong n)
{
return (long)(n >> 1) ^ -(long)(n & 1);
}
#endregion
#region Internal reading and buffer management
/// <summary>
/// Sets currentLimit to (current position) + byteLimit. This is called
/// when descending into a length-delimited embedded message. The previous
/// limit is returned.
/// </summary>
/// <returns>The old limit.</returns>
internal int PushLimit(int byteLimit)
{
if (byteLimit < 0)
{
throw InvalidProtocolBufferException.NegativeSize();
}
byteLimit += totalBytesRetired + bufferPos;
int oldLimit = currentLimit;
if (byteLimit > oldLimit)
{
throw InvalidProtocolBufferException.TruncatedMessage();
}
currentLimit = byteLimit;
RecomputeBufferSizeAfterLimit();
return oldLimit;
}
private void RecomputeBufferSizeAfterLimit()
{
bufferSize += bufferSizeAfterLimit;
int bufferEnd = totalBytesRetired + bufferSize;
if (bufferEnd > currentLimit)
{
// Limit is in current buffer.
bufferSizeAfterLimit = bufferEnd - currentLimit;
bufferSize -= bufferSizeAfterLimit;
}
else
{
bufferSizeAfterLimit = 0;
}
}
/// <summary>
/// Discards the current limit, returning the previous limit.
/// </summary>
internal void PopLimit(int oldLimit)
{
currentLimit = oldLimit;
RecomputeBufferSizeAfterLimit();
}
/// <summary>
/// Returns whether or not all the data before the limit has been read.
/// </summary>
/// <returns></returns>
internal bool ReachedLimit
{
get
{
if (currentLimit == int.MaxValue)
{
return false;
}
int currentAbsolutePosition = totalBytesRetired + bufferPos;
return currentAbsolutePosition >= currentLimit;
}
}
/// <summary>
/// Returns true if the stream has reached the end of the input. This is the
/// case if either the end of the underlying input source has been reached or
/// the stream has reached a limit created using PushLimit.
/// </summary>
public bool IsAtEnd
{
get { return bufferPos == bufferSize && !RefillBuffer(false); }
}
/// <summary>
/// Called when buffer is empty to read more bytes from the
/// input. If <paramref name="mustSucceed"/> is true, RefillBuffer() gurantees that
/// either there will be at least one byte in the buffer when it returns
/// or it will throw an exception. If <paramref name="mustSucceed"/> is false,
/// RefillBuffer() returns false if no more bytes were available.
/// </summary>
/// <param name="mustSucceed"></param>
/// <returns></returns>
private bool RefillBuffer(bool mustSucceed)
{
if (bufferPos < bufferSize)
{
throw new InvalidOperationException("RefillBuffer() called when buffer wasn't empty.");
}
if (totalBytesRetired + bufferSize == currentLimit)
{
// Oops, we hit a limit.
if (mustSucceed)
{
throw InvalidProtocolBufferException.TruncatedMessage();
}
else
{
return false;
}
}
totalBytesRetired += bufferSize;
bufferPos = 0;
bufferSize = (input == null) ? 0 : input.Read(buffer, 0, buffer.Length);
if (bufferSize < 0)
{
throw new InvalidOperationException("Stream.Read returned a negative count");
}
if (bufferSize == 0)
{
if (mustSucceed)
{
throw InvalidProtocolBufferException.TruncatedMessage();
}
else
{
return false;
}
}
else
{
RecomputeBufferSizeAfterLimit();
int totalBytesRead =
totalBytesRetired + bufferSize + bufferSizeAfterLimit;
if (totalBytesRead > sizeLimit || totalBytesRead < 0)
{
throw InvalidProtocolBufferException.SizeLimitExceeded();
}
return true;
}
}
/// <summary>
/// Read one byte from the input.
/// </summary>
/// <exception cref="InvalidProtocolBufferException">
/// the end of the stream or the current limit was reached
/// </exception>
internal byte ReadRawByte()
{
if (bufferPos == bufferSize)
{
RefillBuffer(true);
}
return buffer[bufferPos++];
}
/// <summary>
/// Reads a fixed size of bytes from the input.
/// </summary>
/// <exception cref="InvalidProtocolBufferException">
/// the end of the stream or the current limit was reached
/// </exception>
internal byte[] ReadRawBytes(int size)
{
if (size < 0)
{
throw InvalidProtocolBufferException.NegativeSize();
}
if (totalBytesRetired + bufferPos + size > currentLimit)
{
// Read to the end of the stream (up to the current limit) anyway.
SkipRawBytes(currentLimit - totalBytesRetired - bufferPos);
// Then fail.
throw InvalidProtocolBufferException.TruncatedMessage();
}
if (size <= bufferSize - bufferPos)
{
// We have all the bytes we need already.
byte[] bytes = new byte[size];
ByteArray.Copy(buffer, bufferPos, bytes, 0, size);
bufferPos += size;
return bytes;
}
else if (size < buffer.Length)
{
// Reading more bytes than are in the buffer, but not an excessive number
// of bytes. We can safely allocate the resulting array ahead of time.
// First copy what we have.
byte[] bytes = new byte[size];
int pos = bufferSize - bufferPos;
ByteArray.Copy(buffer, bufferPos, bytes, 0, pos);
bufferPos = bufferSize;
// We want to use RefillBuffer() and then copy from the buffer into our
// byte array rather than reading directly into our byte array because
// the input may be unbuffered.
RefillBuffer(true);
while (size - pos > bufferSize)
{
Buffer.BlockCopy(buffer, 0, bytes, pos, bufferSize);
pos += bufferSize;
bufferPos = bufferSize;
RefillBuffer(true);
}
ByteArray.Copy(buffer, 0, bytes, pos, size - pos);
bufferPos = size - pos;
return bytes;
}
else
{
// The size is very large. For security reasons, we can't allocate the
// entire byte array yet. The size comes directly from the input, so a
// maliciously-crafted message could provide a bogus very large size in
// order to trick the app into allocating a lot of memory. We avoid this
// by allocating and reading only a small chunk at a time, so that the
// malicious message must actually *be* extremely large to cause
// problems. Meanwhile, we limit the allowed size of a message elsewhere.
// Remember the buffer markers since we'll have to copy the bytes out of
// it later.
int originalBufferPos = bufferPos;
int originalBufferSize = bufferSize;
// Mark the current buffer consumed.
totalBytesRetired += bufferSize;
bufferPos = 0;
bufferSize = 0;
// Read all the rest of the bytes we need.
int sizeLeft = size - (originalBufferSize - originalBufferPos);
List<byte[]> chunks = new List<byte[]>();
while (sizeLeft > 0)
{
byte[] chunk = new byte[Math.Min(sizeLeft, buffer.Length)];
int pos = 0;
while (pos < chunk.Length)
{
int n = (input == null) ? -1 : input.Read(chunk, pos, chunk.Length - pos);
if (n <= 0)
{
throw InvalidProtocolBufferException.TruncatedMessage();
}
totalBytesRetired += n;
pos += n;
}
sizeLeft -= chunk.Length;
chunks.Add(chunk);
}
// OK, got everything. Now concatenate it all into one buffer.
byte[] bytes = new byte[size];
// Start by copying the leftover bytes from this.buffer.
int newPos = originalBufferSize - originalBufferPos;
ByteArray.Copy(buffer, originalBufferPos, bytes, 0, newPos);
// And now all the chunks.
foreach (byte[] chunk in chunks)
{
Buffer.BlockCopy(chunk, 0, bytes, newPos, chunk.Length);
newPos += chunk.Length;
}
// Done.
return bytes;
}
}
/// <summary>
/// Reads and discards <paramref name="size"/> bytes.
/// </summary>
/// <exception cref="InvalidProtocolBufferException">the end of the stream
/// or the current limit was reached</exception>
private void SkipRawBytes(int size)
{
if (size < 0)
{
throw InvalidProtocolBufferException.NegativeSize();
}
if (totalBytesRetired + bufferPos + size > currentLimit)
{
// Read to the end of the stream anyway.
SkipRawBytes(currentLimit - totalBytesRetired - bufferPos);
// Then fail.
throw InvalidProtocolBufferException.TruncatedMessage();
}
if (size <= bufferSize - bufferPos)
{
// We have all the bytes we need already.
bufferPos += size;
}
else
{
// Skipping more bytes than are in the buffer. First skip what we have.
int pos = bufferSize - bufferPos;
// ROK 5/7/2013 Issue #54: should retire all bytes in buffer (bufferSize)
// totalBytesRetired += pos;
totalBytesRetired += bufferSize;
bufferPos = 0;
bufferSize = 0;
// Then skip directly from the InputStream for the rest.
if (pos < size)
{
if (input == null)
{
throw InvalidProtocolBufferException.TruncatedMessage();
}
SkipImpl(size - pos);
totalBytesRetired += size - pos;
}
}
}
/// <summary>
/// Abstraction of skipping to cope with streams which can't really skip.
/// </summary>
private void SkipImpl(int amountToSkip)
{
if (input.CanSeek)
{
long previousPosition = input.Position;
input.Position += amountToSkip;
if (input.Position != previousPosition + amountToSkip)
{
throw InvalidProtocolBufferException.TruncatedMessage();
}
}
else
{
byte[] skipBuffer = new byte[Math.Min(1024, amountToSkip)];
while (amountToSkip > 0)
{
int bytesRead = input.Read(skipBuffer, 0, Math.Min(skipBuffer.Length, amountToSkip));
if (bytesRead <= 0)
{
throw InvalidProtocolBufferException.TruncatedMessage();
}
amountToSkip -= bytesRead;
}
}
}
#endregion
}
}
| |
namespace Schema.NET.Test.Examples;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
public class ItemListTest
{
private readonly ItemList itemlist = new()
{
ItemListElement = new List<IListItem>() // Required
{
new ListItem() // Required
{
Position = 1, // Required
Item = new Recipe() // Required
{
Name = "Recipe 1",
},
},
new ListItem()
{
Position = 2,
Item = new Recipe()
{
Name = "Recipe 2",
},
},
},
};
private readonly string json =
"{" +
"\"@context\":\"https://schema.org\"," +
"\"@type\":\"ItemList\"," +
"\"itemListElement\":[" +
"{" +
"\"@type\":\"ListItem\"," +
"\"item\":{" +
"\"@type\":\"Recipe\"," +
"\"name\":\"Recipe 1\"" +
"}," +
"\"position\":1" +
"}," +
"{" +
"\"@type\":\"ListItem\"," +
"\"item\":{" +
"\"@type\":\"Recipe\"," +
"\"name\":\"Recipe 2\"" +
"}," +
"\"position\":2" +
"}" +
"]" +
"}";
[Fact]
public void Deserializing_ItemListJsonLd_ReturnsMatchingItemList()
{
Assert.Equal(this.itemlist.ToString(), SchemaSerializer.DeserializeObject<ItemList>(this.json)!.ToString());
Assert.Equal(SchemaSerializer.SerializeObject(this.itemlist), SchemaSerializer.SerializeObject(SchemaSerializer.DeserializeObject<ItemList>(this.json)!));
}
// https://developers.google.com/search/docs/guides/mark-up-listings
[Fact]
public void ToString_CarouselSummaryPageSearchBoxGoogleStructuredData_ReturnsExpectedJsonLd()
{
// All items in the list must be of the same type. Recipe, Film, Course, Article, Recipe are supported.
var itemList = new ItemList()
{
ItemListElement = new List<IListItem>() // Required
{
new ListItem() // Required
{
Position = 1, // Required
Url = new Uri("https://example.com/articles/1"), // Required
},
new ListItem()
{
Position = 2,
Url = new Uri("https://example.com/articles/2"),
},
},
};
var expectedJson =
"{" +
"\"@context\":\"https://schema.org\"," +
"\"@type\":\"ItemList\"," +
"\"itemListElement\":[" +
"{" +
"\"@type\":\"ListItem\"," +
"\"url\":\"https://example.com/articles/1\"," +
"\"position\":1" +
"}," +
"{" +
"\"@type\":\"ListItem\"," +
"\"url\":\"https://example.com/articles/2\"," +
"\"position\":2" +
"}" +
"]" +
"}";
var json = itemList.ToString();
Assert.Equal(expectedJson, json);
}
// https://developers.google.com/search/docs/guides/mark-up-listings
[Fact]
public void ToString_CarouselAllInOnePageSearchBoxGoogleStructuredData_ReturnsExpectedJsonLd()
{
// All items in the list must be of the same type. Recipe, Film, Course, Article, Recipe are supported.
var itemList = new ItemList()
{
ItemListElement = new List<IListItem>() // Required
{
new ListItem() // Required
{
Position = 1, // Required
Item = new Recipe() // Required
{
Name = "Recipe 1",
},
},
new ListItem()
{
Position = 2,
Item = new Recipe()
{
Name = "Recipe 2",
},
},
},
};
var expectedJson =
"{" +
"\"@context\":\"https://schema.org\"," +
"\"@type\":\"ItemList\"," +
"\"itemListElement\":[" +
"{" +
"\"@type\":\"ListItem\"," +
"\"item\":{" +
"\"@type\":\"Recipe\"," +
"\"name\":\"Recipe 1\"" +
"}," +
"\"position\":1" +
"}," +
"{" +
"\"@type\":\"ListItem\"," +
"\"item\":{" +
"\"@type\":\"Recipe\"," +
"\"name\":\"Recipe 2\"" +
"}," +
"\"position\":2" +
"}" +
"]" +
"}";
var json = itemList.ToString();
Assert.Equal(expectedJson, json);
}
[Fact]
public void Deserializing_ItemListJsonLd_ReturnsItemList()
{
var json =
"{" +
"\"@context\":\"https://schema.org\"," +
"\"@type\":\"ItemList\"," +
"\"itemListElement\":[" +
"{" +
"\"@type\":\"ListItem\"," +
"\"item\":{" +
"\"@type\":\"Recipe\"," +
"\"name\":\"Recipe 1\"" +
"}," +
"\"position\":1" +
"}," +
"{" +
"\"@type\":\"ListItem\"," +
"\"item\":{" +
"\"@type\":\"Recipe\"," +
"\"name\":\"Recipe 2\"" +
"}," +
"\"position\":2" +
"}" +
"]" +
"}";
var itemList = SchemaSerializer.DeserializeObject<ItemList>(json)!;
Assert.Equal("ItemList", itemList.Type);
Assert.True(itemList.ItemListElement.HasValue);
Assert.Equal(2, itemList.ItemListElement.Count);
var listItems = (List<IListItem>)itemList.ItemListElement;
var things = (List<IThing>)itemList.ItemListElement;
Assert.Empty(listItems);
Assert.Equal(2, things.Count);
var thing1 = things.First();
var thing2 = things.Last();
var listItem1 = (IListItem)thing1;
var listItem2 = (IListItem)thing2;
Assert.Equal(1, (int)listItem1.Position!);
Assert.Equal(2, (int)listItem2.Position!);
var recipe1 = Assert.IsType<Recipe>(listItem1.Item.Single());
var recipe2 = Assert.IsType<Recipe>(listItem2.Item.Single());
Assert.Equal("Recipe 1", recipe1.Name);
Assert.Equal("Recipe 2", recipe2.Name);
}
}
| |
namespace AngleSharp.Core.Tests.Html
{
using AngleSharp.Dom;
using AngleSharp.Dom.Html;
using NUnit.Framework;
using System;
/// <summary>
/// Tests generated according to the W3C-Test.org page:
/// http://www.w3c-test.org/html/semantics/forms/constraints/form-validation-validity-rangeUnderflow.html
/// </summary>
[TestFixture]
public class ValidityRangeUnderflowTests
{
static IDocument Html(String code)
{
return code.ToHtmlDocument();
}
[Test]
public void TestRangeunderflowInputDatetime1()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "datetime";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "");
element.Value = "2000-01-01T12:00:00Z";
Assert.AreEqual("datetime", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDatetime2()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "datetime";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2000-01-01T12:00:00Z");
element.Value = "";
Assert.AreEqual("datetime", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDatetime3()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "datetime";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2001-01-01 12:00:00Z");
element.Value = "2000-01-01T12:00:00Z";
Assert.AreEqual("datetime", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDatetime4()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "datetime";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2000-01-01T11:00:00Z");
element.Value = "2000-01-01T12:00:00Z";
Assert.AreEqual("datetime", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDatetime5()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "datetime";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2001-01-01T23:59:59Z");
element.Value = "2000-01-01T24:00:00Z";
Assert.AreEqual("datetime", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDatetime6()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "datetime";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "1980-01-01T12:00Z");
element.Value = "79-01-01T12:00Z";
Assert.AreEqual("datetime", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDatetime7()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "datetime";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2000-01-01T13:00:00Z");
element.Value = "2000-01-01T12:00:00Z";
Assert.AreEqual("datetime", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDatetime8()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "datetime";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2000-01-01T12:00:00.2Z");
element.Value = "2000-01-01T12:00:00.1Z";
Assert.AreEqual("datetime", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDatetime9()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "datetime";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2000-01-01T12:00:00.02Z");
element.Value = "2000-01-01T12:00:00.01Z";
Assert.AreEqual("datetime", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDatetime10()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "datetime";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2000-01-01T12:00:00.002Z");
element.Value = "2000-01-01T12:00:00.001Z";
Assert.AreEqual("datetime", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDatetime11()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "datetime";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "9999-01-01T12:00:00Z");
element.Value = "2000-01-01T12:00:00Z";
Assert.AreEqual("datetime", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDatetime12()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "datetime";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "8593-01-01T02:09+02:09");
element.Value = "8592-01-01T02:09+02:09";
Assert.AreEqual("datetime", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDate1()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "date";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "");
element.Value = "2000-01-01";
Assert.AreEqual("date", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDate2()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "date";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2000-01-01");
element.Value = "";
Assert.AreEqual("date", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDate3()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "date";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2001/01/01");
element.Value = "2000-01-01";
Assert.AreEqual("date", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDate4()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "date";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2000-02-02");
element.Value = "2000-1-1";
Assert.AreEqual("date", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDate5()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "date";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "988-01-01");
element.Value = "987-01-01";
Assert.AreEqual("date", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDate6()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "date";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2001-01-01");
element.Value = "2000-13-01";
Assert.AreEqual("date", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDate7()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "date";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2001-01-01");
element.Value = "2000-02-30";
Assert.AreEqual("date", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDate8()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "date";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2000-01-01");
element.Value = "2000-12-01";
Assert.AreEqual("date", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDate9()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "date";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2000-12-01");
element.Value = "2000-01-01";
Assert.AreEqual("date", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDate10()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "date";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "9999-01-02");
element.Value = "9999-01-01";
Assert.AreEqual("date", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputMonth1()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "month";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "");
element.Value = "2000-01";
Assert.AreEqual("month", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputMonth2()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "month";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2000-01");
element.Value = "";
Assert.AreEqual("month", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputMonth3()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "month";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2001/01");
element.Value = "2000-02";
Assert.AreEqual("month", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputMonth4()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "month";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2000-02");
element.Value = "2000-1";
Assert.AreEqual("month", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputMonth5()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "month";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "988-01");
element.Value = "987-01";
Assert.AreEqual("month", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputMonth6()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "month";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2001-01");
element.Value = "2000-13";
Assert.AreEqual("month", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputMonth7()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "month";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2000-01");
element.Value = "2000-12";
Assert.AreEqual("month", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputMonth8()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "month";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2001-01");
element.Value = "2000-12";
Assert.AreEqual("month", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputMonth9()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "month";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "9999-01");
element.Value = "2000-01";
Assert.AreEqual("month", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputWeek1()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "week";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "");
element.Value = "2000-W01";
Assert.AreEqual("week", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputWeek2()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "week";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2000-W01");
element.Value = "";
Assert.AreEqual("week", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputWeek3()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "week";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2001/W02");
element.Value = "2000-W01";
Assert.AreEqual("week", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputWeek4()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "week";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2001-W02");
element.Value = "2000-W1";
Assert.AreEqual("week", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputWeek5()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "week";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2001-W02");
element.Value = "2000-w01";
Assert.AreEqual("week", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputWeek6()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "week";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "988-W01");
element.Value = "987-W01";
Assert.AreEqual("week", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputWeek7()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "week";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2001-W01");
element.Value = "2000-W57";
Assert.AreEqual("week", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputWeek8()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "week";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2000-W01");
element.Value = "2000-W12";
Assert.AreEqual("week", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputWeek9()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "week";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2000-W12");
element.Value = "2000-W01";
Assert.AreEqual("week", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputWeek10()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "week";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "9999-W01");
element.Value = "2000-W01";
Assert.AreEqual("week", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputTime1()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "time";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "");
element.Value = "12:00:00";
Assert.AreEqual("time", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputTime2()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "time";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "12:00:00");
element.Value = "";
Assert.AreEqual("time", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputTime3()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "time";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "12.00.01");
element.Value = "12:00:00";
Assert.AreEqual("time", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputTime4()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "time";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "12:00:01");
element.Value = "12.00.00";
Assert.AreEqual("time", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputTime5()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "time";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "12:00:00");
element.Value = "13:00:00";
Assert.AreEqual("time", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputTime6()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "time";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "13:00:00");
element.Value = "12";
Assert.AreEqual("time", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputTime7()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "time";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "12:00:02");
element.Value = "12:00:00";
Assert.AreEqual("time", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputTime8()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "time";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "12:00:00.2");
element.Value = "12:00:00.1";
Assert.AreEqual("time", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputTime9()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "time";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "12:00:00.02");
element.Value = "12:00:00.01";
Assert.AreEqual("time", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputTime10()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "time";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "12:00:00.002");
element.Value = "12:00:00.001";
Assert.AreEqual("time", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputTime11()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "time";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "12:00:00");
element.Value = "11:59";
Assert.AreEqual("time", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputNumber1()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "number";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "");
element.Value = "10";
Assert.AreEqual("number", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputNumber2()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "number";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "5");
element.Value = "";
Assert.AreEqual("number", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputNumber3()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "number";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "4");
element.Value = "5";
Assert.AreEqual("number", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputNumber4()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "number";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "-5.6");
element.Value = "-5.5";
Assert.AreEqual("number", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputNumber5()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "number";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "0");
element.Value = "-0";
Assert.AreEqual("number", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputNumber6()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "number";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "5");
element.Value = "6abc";
Assert.AreEqual("number", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputNumber7()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "number";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "6");
element.Value = "5";
Assert.AreEqual("number", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputNumber8()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "number";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "-5.4");
element.Value = "-5.5";
Assert.AreEqual("number", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputNumber9()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "number";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "5e+2");
element.Value = "-5e-1";
Assert.AreEqual("number", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Test.ModuleCore;
using System;
using System.IO;
using System.Text;
using System.Xml;
namespace CoreXml.Test.XLinq
{
public partial class XNodeReaderFunctionalTests : TestModule
{
public partial class XNodeReaderTests : XLinqTestCase
{
public partial class TCReadContentAsBinHex : BridgeHelpers
{
public const string ST_ELEM_NAME1 = "ElemAll";
public const string ST_ELEM_NAME2 = "ElemEmpty";
public const string ST_ELEM_NAME3 = "ElemNum";
public const string ST_ELEM_NAME4 = "ElemText";
public const string ST_ELEM_NAME5 = "ElemNumText";
public const string ST_ELEM_NAME6 = "ElemLong";
public const string strTextBinHex = "ABCDEF";
public const string strNumBinHex = "0123456789";
public override void Init()
{
base.Init();
CreateBinHexTestFile(pBinHexXml);
}
public override void Terminate()
{
base.Terminate();
}
private bool VerifyInvalidReadBinHex(int iBufferSize, int iIndex, int iCount, Type exceptionType)
{
bool bPassed = false;
byte[] buffer = new byte[iBufferSize];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return true;
try
{
DataReader.ReadContentAsBinHex(buffer, iIndex, iCount);
}
catch (Exception e)
{
bPassed = (e.GetType().ToString() == exceptionType.ToString());
if (!bPassed)
{
TestLog.WriteLine("Actual exception:{0}", e.GetType().ToString());
TestLog.WriteLine("Expected exception:{0}", exceptionType.ToString());
}
}
return bPassed;
}
protected void TestInvalidNodeType(XmlNodeType nt)
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnNodeType(DataReader, nt);
string name = DataReader.Name;
string value = DataReader.Value;
byte[] buffer = new byte[1];
if (!DataReader.CanReadBinaryContent) return;
try
{
int nBytes = DataReader.ReadContentAsBinHex(buffer, 0, 1);
}
catch (InvalidOperationException)
{
return;
}
TestLog.Compare(false, "Invalid OP exception not thrown on wrong nodetype");
}
//[Variation("ReadBinHex Element with all valid value")]
public void TestReadBinHex_1()
{
int binhexlen = 0;
byte[] binhex = new byte[1000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
binhexlen = DataReader.ReadContentAsBinHex(binhex, 0, binhex.Length);
string strActbinhex = "";
for (int i = 0; i < binhexlen; i = i + 2)
{
strActbinhex += System.BitConverter.ToChar(binhex, i);
}
TestLog.Compare(strActbinhex, (strNumBinHex + strTextBinHex), "1. Compare All Valid BinHex");
}
//[Variation("ReadBinHex Element with all valid Num value", Priority = 0)]
public void TestReadBinHex_2()
{
int BinHexlen = 0;
byte[] BinHex = new byte[1000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME3);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length);
string strActBinHex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
strActBinHex += System.BitConverter.ToChar(BinHex, i);
}
TestLog.Compare(strActBinHex, strNumBinHex, "Compare All Valid BinHex");
}
//[Variation("ReadBinHex Element with all valid Text value")]
public void TestReadBinHex_3()
{
int BinHexlen = 0;
byte[] BinHex = new byte[1000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length);
string strActBinHex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
strActBinHex += System.BitConverter.ToChar(BinHex, i);
}
TestLog.Compare(strActBinHex, strTextBinHex, "Compare All Valid BinHex");
}
//[Variation("ReadBinHex Element on CDATA", Priority = 0)]
public void TestReadBinHex_4()
{
int BinHexlen = 0;
byte[] BinHex = new byte[3];
string xmlStr = "<root><![CDATA[ABCDEF]]></root>";
XmlReader DataReader = GetReader(new StringReader(xmlStr));
PositionOnElement(DataReader, "root");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length);
TestLog.Compare(BinHexlen, 3, "BinHex");
BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length);
TestLog.Compare(BinHexlen, 0, "BinHex");
DataReader.Read();
TestLog.Compare(DataReader.NodeType, XmlNodeType.None, "Not on none");
}
//[Variation("ReadBinHex Element with all valid value (from concatenation), Priority=0")]
public void TestReadBinHex_5()
{
int BinHexlen = 0;
byte[] BinHex = new byte[1000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME5);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length);
string strActBinHex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
strActBinHex += System.BitConverter.ToChar(BinHex, i);
}
TestLog.Compare(strActBinHex, (strNumBinHex + strTextBinHex), "Compare All Valid BinHex");
}
//[Variation("ReadBinHex Element with all long valid value (from concatenation)")]
public void TestReadBinHex_6()
{
int BinHexlen = 0;
byte[] BinHex = new byte[2000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME6);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length);
string strActBinHex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
strActBinHex += System.BitConverter.ToChar(BinHex, i);
}
string strExpBinHex = "";
for (int i = 0; i < 10; i++)
strExpBinHex += (strNumBinHex + strTextBinHex);
TestLog.Compare(strActBinHex, strExpBinHex, "Compare All Valid BinHex");
}
//[Variation("ReadBinHex with count > buffer size")]
public void TestReadBinHex_7()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, 0, 6, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex with count < 0")]
public void TestReadBinHex_8()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, 2, -1, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex with index > buffer size")]
public void vReadBinHex_9()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, 5, 1, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex with index < 0")]
public void TestReadBinHex_10()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, -1, 1, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex with index + count exceeds buffer")]
public void TestReadBinHex_11()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, 0, 10, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex index & count =0")]
public void TestReadBinHex_12()
{
byte[] buffer = new byte[5];
int iCount = 0;
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
try
{
iCount = DataReader.ReadContentAsBinHex(buffer, 0, 0);
}
catch (Exception e)
{
TestLog.WriteLine(e.ToString());
throw new TestException(TestResult.Failed, "");
}
TestLog.Compare(iCount, 0, "has to be zero");
}
//[Variation("ReadBinHex Element multiple into same buffer (using offset), Priority=0")]
public void TestReadBinHex_13()
{
int BinHexlen = 10;
byte[] BinHex = new byte[BinHexlen];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
string strActbinhex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
DataReader.ReadContentAsBinHex(BinHex, i, 2);
strActbinhex = (System.BitConverter.ToChar(BinHex, i)).ToString();
TestLog.Compare(String.Compare(strActbinhex, 0, strTextBinHex, i / 2, 1), 0, "Compare All Valid Base64");
}
}
//[Variation("ReadBinHex with buffer == null")]
public void TestReadBinHex_14()
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
try
{
DataReader.ReadContentAsBinHex(null, 0, 0);
}
catch (ArgumentNullException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadBinHex after failed ReadBinHex")]
public void TestReadBinHex_15()
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, "ElemErr");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[10];
int nRead = 0;
try
{
nRead = DataReader.ReadContentAsBinHex(buffer, 0, 1);
throw new TestException(TestResult.Failed, "");
}
catch (XmlException e)
{
int idx = e.Message.IndexOf("a&");
TestLog.Compare(idx >= 0, "msg");
CheckXmlException("Xml_UserException", e, 1, 968);
}
}
//[Variation("Read after partial ReadBinHex")]
public void TestReadBinHex_16()
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, "ElemNum");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[10];
int nRead = DataReader.ReadContentAsBinHex(buffer, 0, 8);
TestLog.Compare(nRead, 8, "0");
DataReader.Read();
TestLog.Compare(VerifyNode(DataReader, XmlNodeType.Element, "ElemText", String.Empty), "1vn");
}
//[Variation("Current node on multiple calls")]
public void TestReadBinHex_17()
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, "ElemNum");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[30];
int nRead = DataReader.ReadContentAsBinHex(buffer, 0, 2);
TestLog.Compare(nRead, 2, "0");
nRead = DataReader.ReadContentAsBinHex(buffer, 0, 19);
TestLog.Compare(nRead, 18, "1");
TestLog.Compare(VerifyNode(DataReader, XmlNodeType.EndElement, "ElemNum", String.Empty), "1vn");
}
//[Variation("ReadBinHex with whitespace")]
public void TestTextReadBinHex_21()
{
byte[] buffer = new byte[1];
string strxml = "<abc> 1 1 B </abc>";
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "abc");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
int result = 0;
int nRead;
while ((nRead = DataReader.ReadContentAsBinHex(buffer, 0, 1)) > 0)
result += nRead;
TestLog.Compare(result, 1, "res");
TestLog.Compare(buffer[0], (byte)17, "buffer[0]");
}
//[Variation("ReadBinHex with odd number of chars")]
public void TestTextReadBinHex_22()
{
byte[] buffer = new byte[1];
string strxml = "<abc>11B</abc>";
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "abc");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
int result = 0;
int nRead;
while ((nRead = DataReader.ReadContentAsBinHex(buffer, 0, 1)) > 0)
result += nRead;
TestLog.Compare(result, 1, "res");
TestLog.Compare(buffer[0], (byte)17, "buffer[0]");
}
//[Variation("ReadBinHex when end tag doesn't exist")]
public void TestTextReadBinHex_23()
{
byte[] buffer = new byte[5000];
string strxml = "<B>" + new string('A', 5000);
try
{
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "B");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
DataReader.ReadContentAsBinHex(buffer, 0, 5000);
TestLog.WriteLine("Accepted incomplete element");
throw new TestException(TestResult.Failed, "");
}
catch (XmlException e)
{
CheckXmlException("Xml_UnexpectedEOFInElementContent", e, 1, 5004);
}
}
//[Variation("WS:WireCompat:hex binary fails to send/return data after 1787 bytes going Whidbey to Everett")]
public void TestTextReadBinHex_24()
{
string filename = Path.Combine("TestData", "XmlReader", "Common", "Bug99148.xml");
XmlReader DataReader = GetReader(filename);
DataReader.MoveToContent();
int bytes = -1;
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
StringBuilder output = new StringBuilder();
while (bytes != 0)
{
byte[] bbb = new byte[1024];
bytes = DataReader.ReadContentAsBinHex(bbb, 0, bbb.Length);
for (int i = 0; i < bytes; i++)
{
output.AppendFormat(bbb[i].ToString());
}
}
if (TestLog.Compare(output.ToString().Length, 1735, "Expected Length : 1735"))
return;
else
throw new TestException(TestResult.Failed, "");
}
//[Variation("DebugAssert in ReadContentAsBinHex")]
public void DebugAssertInReadContentAsBinHex()
{
XmlReader DataReader = GetReaderStr(@"<root>
<boo>hey</boo>
</root>");
byte[] buffer = new byte[5];
int iCount = 0;
while (DataReader.Read())
{
if (DataReader.NodeType == XmlNodeType.Element)
break;
}
if (!DataReader.CanReadBinaryContent) return;
DataReader.Read();
iCount = DataReader.ReadContentAsBinHex(buffer, 0, 0);
}
}
//[TestCase(Name = "ReadElementContentAsBinHex", Desc = "ReadElementContentAsBinHex")]
public partial class TCReadElementContentAsBinHex : BridgeHelpers
{
public const string ST_ELEM_NAME1 = "ElemAll";
public const string ST_ELEM_NAME2 = "ElemEmpty";
public const string ST_ELEM_NAME3 = "ElemNum";
public const string ST_ELEM_NAME4 = "ElemText";
public const string ST_ELEM_NAME5 = "ElemNumText";
public const string ST_ELEM_NAME6 = "ElemLong";
public const string strTextBinHex = "ABCDEF";
public const string strNumBinHex = "0123456789";
public override void Init()
{
base.Init();
CreateBinHexTestFile(pBinHexXml);
}
public override void Terminate()
{
base.Terminate();
}
private bool VerifyInvalidReadBinHex(int iBufferSize, int iIndex, int iCount, Type exceptionType)
{
bool bPassed = false;
byte[] buffer = new byte[iBufferSize];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
if (!DataReader.CanReadBinaryContent) return true;
try
{
DataReader.ReadElementContentAsBinHex(buffer, iIndex, iCount);
}
catch (Exception e)
{
bPassed = (e.GetType().ToString() == exceptionType.ToString());
if (!bPassed)
{
TestLog.WriteLine("Actual exception:{0}", e.GetType().ToString());
TestLog.WriteLine("Expected exception:{0}", exceptionType.ToString());
}
}
return bPassed;
}
protected void TestInvalidNodeType(XmlNodeType nt)
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnNodeType(DataReader, nt);
string name = DataReader.Name;
string value = DataReader.Value;
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[1];
try
{
int nBytes = DataReader.ReadElementContentAsBinHex(buffer, 0, 1);
}
catch (InvalidOperationException)
{
return;
}
TestLog.Compare(false, "Invalid OP exception not thrown on wrong nodetype");
}
//[Variation("ReadBinHex Element with all valid value")]
public void TestReadBinHex_1()
{
int binhexlen = 0;
byte[] binhex = new byte[1000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
if (!DataReader.CanReadBinaryContent) return;
binhexlen = DataReader.ReadElementContentAsBinHex(binhex, 0, binhex.Length);
string strActbinhex = "";
for (int i = 0; i < binhexlen; i = i + 2)
{
strActbinhex += System.BitConverter.ToChar(binhex, i);
}
TestLog.Compare(strActbinhex, (strNumBinHex + strTextBinHex), "1. Compare All Valid BinHex");
}
//[Variation("ReadBinHex Element with all valid Num value", Priority = 0)]
public void TestReadBinHex_2()
{
int BinHexlen = 0;
byte[] BinHex = new byte[1000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME3);
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length);
string strActBinHex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
strActBinHex += System.BitConverter.ToChar(BinHex, i);
}
TestLog.Compare(strActBinHex, strNumBinHex, "Compare All Valid BinHex");
}
//[Variation("ReadBinHex Element with all valid Text value")]
public void TestReadBinHex_3()
{
int BinHexlen = 0;
byte[] BinHex = new byte[1000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length);
string strActBinHex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
strActBinHex += System.BitConverter.ToChar(BinHex, i);
}
TestLog.Compare(strActBinHex, strTextBinHex, "Compare All Valid BinHex");
}
//[Variation("ReadBinHex Element with Comments and PIs", Priority = 0)]
public void TestReadBinHex_4()
{
int BinHexlen = 0;
byte[] BinHex = new byte[3];
XmlReader DataReader = GetReader(new StringReader("<root>AB<!--Comment-->CD<?pi target?>EF</root>"));
PositionOnElement(DataReader, "root");
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length);
TestLog.Compare(BinHexlen, 3, "BinHex");
}
//[Variation("ReadBinHex Element with all valid value (from concatenation), Priority=0")]
public void TestReadBinHex_5()
{
int BinHexlen = 0;
byte[] BinHex = new byte[1000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME5);
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length);
string strActBinHex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
strActBinHex += System.BitConverter.ToChar(BinHex, i);
}
TestLog.Compare(strActBinHex, (strNumBinHex + strTextBinHex), "Compare All Valid BinHex");
}
//[Variation("ReadBinHex Element with all long valid value (from concatenation)")]
public void TestReadBinHex_6()
{
int BinHexlen = 0;
byte[] BinHex = new byte[2000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME6);
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length);
string strActBinHex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
strActBinHex += System.BitConverter.ToChar(BinHex, i);
}
string strExpBinHex = "";
for (int i = 0; i < 10; i++)
strExpBinHex += (strNumBinHex + strTextBinHex);
TestLog.Compare(strActBinHex, strExpBinHex, "Compare All Valid BinHex");
}
//[Variation("ReadBinHex with count > buffer size")]
public void TestReadBinHex_7()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, 0, 6, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex with count < 0")]
public void TestReadBinHex_8()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, 2, -1, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex with index > buffer size")]
public void vReadBinHex_9()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, 5, 1, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex with index < 0")]
public void TestReadBinHex_10()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, -1, 1, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex with index + count exceeds buffer")]
public void TestReadBinHex_11()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, 0, 10, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex index & count =0")]
public void TestReadBinHex_12()
{
byte[] buffer = new byte[5];
int iCount = 0;
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
if (!DataReader.CanReadBinaryContent) return;
try
{
iCount = DataReader.ReadElementContentAsBinHex(buffer, 0, 0);
}
catch (Exception e)
{
TestLog.WriteLine(e.ToString());
throw new TestException(TestResult.Failed, "");
}
TestLog.Compare(iCount, 0, "has to be zero");
}
//[Variation("ReadBinHex Element multiple into same buffer (using offset), Priority=0")]
public void TestReadBinHex_13()
{
int BinHexlen = 10;
byte[] BinHex = new byte[BinHexlen];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
if (!DataReader.CanReadBinaryContent) return;
string strActbinhex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
DataReader.ReadElementContentAsBinHex(BinHex, i, 2);
strActbinhex = (System.BitConverter.ToChar(BinHex, i)).ToString();
TestLog.Compare(String.Compare(strActbinhex, 0, strTextBinHex, i / 2, 1), 0, "Compare All Valid Base64");
}
}
//[Variation("ReadBinHex with buffer == null")]
public void TestReadBinHex_14()
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
if (!DataReader.CanReadBinaryContent) return;
try
{
DataReader.ReadElementContentAsBinHex(null, 0, 0);
}
catch (ArgumentNullException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadBinHex after failed ReadBinHex")]
public void TestReadBinHex_15()
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, "ElemErr");
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[10];
int nRead = 0;
try
{
nRead = DataReader.ReadElementContentAsBinHex(buffer, 0, 1);
throw new TestException(TestResult.Failed, "");
}
catch (XmlException e)
{
int idx = e.Message.IndexOf("a&");
TestLog.Compare(idx >= 0, "msg");
CheckXmlException("Xml_UserException", e, 1, 968);
}
}
//[Variation("Read after partial ReadBinHex")]
public void TestReadBinHex_16()
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, "ElemNum");
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[10];
int nRead = DataReader.ReadElementContentAsBinHex(buffer, 0, 8);
TestLog.Compare(nRead, 8, "0");
DataReader.Read();
TestLog.Compare(DataReader.NodeType, XmlNodeType.Text, "Not on text node");
}
//[Variation("ReadBinHex with whitespace")]
public void TestTextReadBinHex_21()
{
byte[] buffer = new byte[1];
string strxml = "<abc> 1 1 B </abc>";
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "abc");
if (!DataReader.CanReadBinaryContent) return;
int result = 0;
int nRead;
while ((nRead = DataReader.ReadElementContentAsBinHex(buffer, 0, 1)) > 0)
result += nRead;
TestLog.Compare(result, 1, "res");
TestLog.Compare(buffer[0], (byte)17, "buffer[0]");
}
//[Variation("ReadBinHex with odd number of chars")]
public void TestTextReadBinHex_22()
{
byte[] buffer = new byte[1];
string strxml = "<abc>11B</abc>";
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "abc");
if (!DataReader.CanReadBinaryContent) return;
int result = 0;
int nRead;
while ((nRead = DataReader.ReadElementContentAsBinHex(buffer, 0, 1)) > 0)
result += nRead;
TestLog.Compare(result, 1, "res");
TestLog.Compare(buffer[0], (byte)17, "buffer[0]");
}
//[Variation("ReadBinHex when end tag doesn't exist")]
public void TestTextReadBinHex_23()
{
byte[] buffer = new byte[5000];
string strxml = "<B>" + new string('A', 5000);
try
{
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "B");
DataReader.ReadElementContentAsBinHex(buffer, 0, 5000);
TestLog.WriteLine("Accepted incomplete element");
throw new TestException(TestResult.Failed, "");
}
catch (XmlException e)
{
CheckXmlException("Xml_UnexpectedEOFInElementContent", e, 1, 5004);
}
}
//[Variation("WS:WireCompat:hex binary fails to send/return data after 1787 bytes going Whidbey to Everett")]
public void TestTextReadBinHex_24()
{
string filename = Path.Combine("TestData", "XmlReader", "Common", "Bug99148.xml");
XmlReader DataReader = GetReader(filename);
DataReader.MoveToContent();
if (!DataReader.CanReadBinaryContent) return;
int bytes = -1;
StringBuilder output = new StringBuilder();
while (bytes != 0)
{
byte[] bbb = new byte[1024];
bytes = DataReader.ReadElementContentAsBinHex(bbb, 0, bbb.Length);
for (int i = 0; i < bytes; i++)
{
output.AppendFormat(bbb[i].ToString());
}
}
if (TestLog.Compare(output.ToString().Length, 1735, "Expected Length : 1735"))
return;
else
throw new TestException(TestResult.Failed, "");
}
//[Variation("SubtreeReader inserted attributes don't work with ReadContentAsBinHex")]
public void TestTextReadBinHex_25()
{
string strxml = "<root xmlns='0102030405060708090a0B0c'><bar/></root>";
using (XmlReader r = GetReader(new StringReader(strxml)))
{
r.Read();
r.Read();
using (XmlReader sr = r.ReadSubtree())
{
if (!sr.CanReadBinaryContent) return;
sr.Read();
sr.MoveToFirstAttribute();
sr.MoveToFirstAttribute();
byte[] bytes = new byte[4];
while ((sr.ReadContentAsBinHex(bytes, 0, bytes.Length)) > 0) { }
}
}
}
}
}
}
}
| |
/////////////////////////////////////////////////////////////////////////////////
// Paint.NET //
// Copyright (C) Rick Brewster, Tom Jackson, and past contributors. //
// Portions Copyright (C) Microsoft Corporation. All Rights Reserved. //
// See license-pdn.txt for full licensing and attribution details. //
/////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Runtime.InteropServices;
namespace Pinta.Core
{
/// <summary>
/// This is our pixel format that we will work with. It is always 32-bits / 4-bytes and is
/// always laid out in BGRA order.
/// Generally used with the Surface class.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Explicit)]
public struct ColorBgra
{
[FieldOffset(0)]
public byte B;
[FieldOffset(1)]
public byte G;
[FieldOffset(2)]
public byte R;
[FieldOffset(3)]
public byte A;
/// <summary>
/// Lets you change B, G, R, and A at the same time.
/// </summary>
[NonSerialized]
[FieldOffset(0)]
public uint Bgra;
public const int BlueChannel = 0;
public const int GreenChannel = 1;
public const int RedChannel = 2;
public const int AlphaChannel = 3;
public const int SizeOf = 4;
public static ColorBgra ParseHexString(string hexString)
{
uint value = Convert.ToUInt32(hexString, 16);
return ColorBgra.FromUInt32(value);
}
public string ToHexString()
{
int rgbNumber = (this.R << 16) | (this.G << 8) | this.B;
string colorString = Convert.ToString(rgbNumber, 16);
while (colorString.Length < 6)
{
colorString = "0" + colorString;
}
string alphaString = System.Convert.ToString(this.A, 16);
while (alphaString.Length < 2)
{
alphaString = "0" + alphaString;
}
colorString = alphaString + colorString;
return colorString.ToUpper();
}
/// <summary>
/// Gets or sets the byte value of the specified color channel.
/// </summary>
public unsafe byte this[int channel]
{
get
{
if (channel < 0 || channel > 3)
{
throw new ArgumentOutOfRangeException("channel", channel, "valid range is [0,3]");
}
fixed (byte *p = &B)
{
return p[channel];
}
}
set
{
if (channel < 0 || channel > 3)
{
throw new ArgumentOutOfRangeException("channel", channel, "valid range is [0,3]");
}
fixed (byte *p = &B)
{
p[channel] = value;
}
}
}
/// <summary>
/// Gets the luminance intensity of the pixel based on the values of the red, green, and blue components. Alpha is ignored.
/// </summary>
/// <returns>A value in the range 0 to 1 inclusive.</returns>
public double GetIntensity()
{
return ((0.114 * (double)B) + (0.587 * (double)G) + (0.299 * (double)R)) / 255.0;
}
/// <summary>
/// Gets the luminance intensity of the pixel based on the values of the red, green, and blue components. Alpha is ignored.
/// </summary>
/// <returns>A value in the range 0 to 255 inclusive.</returns>
public byte GetIntensityByte()
{
return (byte)((7471 * B + 38470 * G + 19595 * R) >> 16);
}
/// <summary>
/// Returns the maximum value out of the B, G, and R values. Alpha is ignored.
/// </summary>
/// <returns></returns>
public byte GetMaxColorChannelValue()
{
return Math.Max(this.B, Math.Max(this.G, this.R));
}
/// <summary>
/// Returns the average of the B, G, and R values. Alpha is ignored.
/// </summary>
/// <returns></returns>
public byte GetAverageColorChannelValue()
{
return (byte)((this.B + this.G + this.R) / 3);
}
/// <summary>
/// Compares two ColorBgra instance to determine if they are equal.
/// </summary>
public static bool operator == (ColorBgra lhs, ColorBgra rhs)
{
return lhs.Bgra == rhs.Bgra;
}
/// <summary>
/// Compares two ColorBgra instance to determine if they are not equal.
/// </summary>
public static bool operator != (ColorBgra lhs, ColorBgra rhs)
{
return lhs.Bgra != rhs.Bgra;
}
/// <summary>
/// Compares two ColorBgra instance to determine if they are equal.
/// </summary>
public override bool Equals(object obj)
{
if (obj != null && obj is ColorBgra && ((ColorBgra)obj).Bgra == this.Bgra)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// Returns a hash code for this color value.
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
unchecked
{
return (int)Bgra;
}
}
/// <summary>
/// Gets the equivalent GDI+ PixelFormat.
/// </summary>
/// <remarks>
/// This property always returns PixelFormat.Format32bppArgb.
/// </remarks>
// public static PixelFormat PixelFormat
// {
// get
// {
// return PixelFormat.Format32bppArgb;
// }
// }
/// <summary>
/// Returns a new ColorBgra with the same color values but with a new alpha component value.
/// </summary>
public ColorBgra NewAlpha(byte newA)
{
return ColorBgra.FromBgra(B, G, R, newA);
}
/// <summary>
/// Creates a new ColorBgra instance with the given color and alpha values.
/// </summary>
[Obsolete ("Use FromBgra() instead (make sure to swap the order of your b and r parameters)")]
public static ColorBgra FromRgba(byte r, byte g, byte b, byte a)
{
return FromBgra(b, g, r, a);
}
/// <summary>
/// Creates a new ColorBgra instance with the given color values, and 255 for alpha.
/// </summary>
[Obsolete ("Use FromBgr() instead (make sure to swap the order of your b and r parameters)")]
public static ColorBgra FromRgb(byte r, byte g, byte b)
{
return FromBgr(b, g, r);
}
/// <summary>
/// Creates a new ColorBgra instance with the given color and alpha values.
/// </summary>
public static ColorBgra FromBgra(byte b, byte g, byte r, byte a)
{
ColorBgra color = new ColorBgra();
color.Bgra = BgraToUInt32(b, g, r, a);
return color;
}
/// <summary>
/// Creates a new ColorBgra instance with the given color and alpha values.
/// </summary>
public static ColorBgra FromBgraClamped(int b, int g, int r, int a)
{
return FromBgra(
ClampToByte(b),
ClampToByte(g),
ClampToByte(r),
ClampToByte(a));
}
/// <summary>
/// Creates a new ColorBgra instance with the given color and alpha values.
/// </summary>
public static ColorBgra FromBgraClamped(float b, float g, float r, float a)
{
return FromBgra(
ClampToByte(b),
ClampToByte(g),
ClampToByte(r),
ClampToByte(a));
}
public static byte ClampToByte(float x)
{
if (x > 255)
{
return 255;
}
else if (x < 0)
{
return 0;
}
else
{
return (byte)x;
}
}
/// <summary>
/// Packs color and alpha values into a 32-bit integer.
/// </summary>
public static UInt32 BgraToUInt32(byte b, byte g, byte r, byte a)
{
return (uint)b + ((uint)g << 8) + ((uint)r << 16) + ((uint)a << 24);
}
/// <summary>
/// Packs color and alpha values into a 32-bit integer.
/// </summary>
public static UInt32 BgraToUInt32(int b, int g, int r, int a)
{
return (uint)b + ((uint)g << 8) + ((uint)r << 16) + ((uint)a << 24);
}
/// <summary>
/// Creates a new ColorBgra instance with the given color values, and 255 for alpha.
/// </summary>
public static ColorBgra FromBgr(byte b, byte g, byte r)
{
return FromBgra(b, g, r, 255);
}
/// <summary>
/// Constructs a new ColorBgra instance with the given 32-bit value.
/// </summary>
public static ColorBgra FromUInt32(UInt32 bgra)
{
ColorBgra color = new ColorBgra();
color.Bgra = bgra;
return color;
}
public static byte ClampToByte(int x)
{
if (x > 255)
{
return 255;
}
else if (x < 0)
{
return 0;
}
else
{
return (byte)x;
}
}
/// <summary>
/// Constructs a new ColorBgra instance from the values in the given Color instance.
/// </summary>
// public static ColorBgra FromColor(Color c)
// {
// return FromBgra(c.B, c.G, c.R, c.A);
// }
/// <summary>
/// Converts this ColorBgra instance to a Color instance.
/// </summary>
// public Color ToColor()
// {
// return Color.FromArgb(A, R, G, B);
// }
/// <summary>
/// Smoothly blends between two colors.
/// </summary>
public static ColorBgra Blend(ColorBgra ca, ColorBgra cb, byte cbAlpha)
{
uint caA = (uint)Utility.FastScaleByteByByte((byte)(255 - cbAlpha), ca.A);
uint cbA = (uint)Utility.FastScaleByteByByte(cbAlpha, cb.A);
uint cbAT = caA + cbA;
uint r;
uint g;
uint b;
if (cbAT == 0)
{
r = 0;
g = 0;
b = 0;
}
else
{
r = ((ca.R * caA) + (cb.R * cbA)) / cbAT;
g = ((ca.G * caA) + (cb.G * cbA)) / cbAT;
b = ((ca.B * caA) + (cb.B * cbA)) / cbAT;
}
return ColorBgra.FromBgra((byte)b, (byte)g, (byte)r, (byte)cbAT);
}
/// <summary>
/// Smoothly blends the given colors together, assuming equal weighting for each one.
/// </summary>
/// <param name="colors"></param>
/// <param name="colorCount"></param>
/// <returns></returns>
public unsafe static ColorBgra Blend (ColorBgra* colors, int count)
{
if (count < 0) {
throw new ArgumentOutOfRangeException ("count must be 0 or greater");
}
if (count == 0) {
return ColorBgra.Transparent;
}
ulong aSum = 0;
for (int i = 0; i < count; ++i) {
aSum += (ulong)colors[i].A;
}
byte b = 0;
byte g = 0;
byte r = 0;
byte a = (byte)(aSum / (ulong)count);
if (aSum != 0) {
ulong bSum = 0;
ulong gSum = 0;
ulong rSum = 0;
for (int i = 0; i < count; ++i) {
bSum += (ulong)(colors[i].A * colors[i].B);
gSum += (ulong)(colors[i].A * colors[i].G);
rSum += (ulong)(colors[i].A * colors[i].R);
}
b = (byte)(bSum / aSum);
g = (byte)(gSum / aSum);
r = (byte)(rSum / aSum);
}
return ColorBgra.FromBgra (b, g, r, a);
}
/// <summary>
/// Linearly interpolates between two color values.
/// </summary>
/// <param name="from">The color value that represents 0 on the lerp number line.</param>
/// <param name="to">The color value that represents 1 on the lerp number line.</param>
/// <param name="frac">A value in the range [0, 1].</param>
/// <remarks>
/// This method does a simple lerp on each color value and on the alpha channel. It does
/// not properly take into account the alpha channel's effect on color blending.
/// </remarks>
public static ColorBgra Lerp(ColorBgra from, ColorBgra to, float frac)
{
ColorBgra ret = new ColorBgra();
ret.B = (byte)ClampToByte(Lerp(from.B, to.B, frac));
ret.G = (byte)ClampToByte(Lerp(from.G, to.G, frac));
ret.R = (byte)ClampToByte(Lerp(from.R, to.R, frac));
ret.A = (byte)ClampToByte(Lerp(from.A, to.A, frac));
return ret;
}
public static float Lerp(float from, float to, float frac)
{
return (from + frac * (to - from));
}
public static double Lerp(double from, double to, double frac)
{
return (from + frac * (to - from));
}
/// <summary>
/// Linearly interpolates between two color values.
/// </summary>
/// <param name="from">The color value that represents 0 on the lerp number line.</param>
/// <param name="to">The color value that represents 1 on the lerp number line.</param>
/// <param name="frac">A value in the range [0, 1].</param>
/// <remarks>
/// This method does a simple lerp on each color value and on the alpha channel. It does
/// not properly take into account the alpha channel's effect on color blending.
/// </remarks>
public static ColorBgra Lerp(ColorBgra from, ColorBgra to, double frac)
{
ColorBgra ret = new ColorBgra();
ret.B = (byte)ClampToByte(Lerp(from.B, to.B, frac));
ret.G = (byte)ClampToByte(Lerp(from.G, to.G, frac));
ret.R = (byte)ClampToByte(Lerp(from.R, to.R, frac));
ret.A = (byte)ClampToByte(Lerp(from.A, to.A, frac));
return ret;
}
public static byte ClampToByte(double x)
{
if (x > 255)
{
return 255;
}
else if (x < 0)
{
return 0;
}
else
{
return (byte)x;
}
}
/// <summary>
/// Blends four colors together based on the given weight values.
/// </summary>
/// <returns>The blended color.</returns>
/// <remarks>
/// The weights should be 16-bit fixed point numbers that add up to 65536 ("1.0").
/// 4W16IP means "4 colors, weights, 16-bit integer precision"
/// </remarks>
public static ColorBgra BlendColors4W16IP(ColorBgra c1, uint w1, ColorBgra c2, uint w2, ColorBgra c3, uint w3, ColorBgra c4, uint w4)
{
#if DEBUG
if ((w1 + w2 + w3 + w4) != 65536)
{
throw new ArgumentOutOfRangeException("w1 + w2 + w3 + w4 must equal 65536!");
}
#endif
const uint ww = 32768;
uint af = (c1.A * w1) + (c2.A * w2) + (c3.A * w3) + (c4.A * w4);
uint a = (af + ww) >> 16;
uint b;
uint g;
uint r;
if (a == 0)
{
b = 0;
g = 0;
r = 0;
}
else
{
b = (uint)((((long)c1.A * c1.B * w1) + ((long)c2.A * c2.B * w2) + ((long)c3.A * c3.B * w3) + ((long)c4.A * c4.B * w4)) / af);
g = (uint)((((long)c1.A * c1.G * w1) + ((long)c2.A * c2.G * w2) + ((long)c3.A * c3.G * w3) + ((long)c4.A * c4.G * w4)) / af);
r = (uint)((((long)c1.A * c1.R * w1) + ((long)c2.A * c2.R * w2) + ((long)c3.A * c3.R * w3) + ((long)c4.A * c4.R * w4)) / af);
}
return ColorBgra.FromBgra((byte)b, (byte)g, (byte)r, (byte)a);
}
/// <summary>
/// Blends the colors based on the given weight values.
/// </summary>
/// <param name="c">The array of color values.</param>
/// <param name="w">The array of weight values.</param>
/// <returns>
/// The weights should be fixed point numbers.
/// The total summation of the weight values will be treated as "1.0".
/// Each color will be blended in proportionally to its weight value respective to
/// the total summation of the weight values.
/// </returns>
/// <remarks>
/// "WAIP" stands for "weights, arbitrary integer precision"</remarks>
public static ColorBgra BlendColorsWAIP(ColorBgra[] c, uint[] w)
{
if (c.Length != w.Length)
{
throw new ArgumentException("c.Length != w.Length");
}
if (c.Length == 0)
{
return ColorBgra.FromUInt32(0);
}
long wsum = 0;
long asum = 0;
for (int i = 0; i < w.Length; ++i)
{
wsum += w[i];
asum += c[i].A * w[i];
}
uint a = (uint)((asum + (wsum >> 1)) / wsum);
long b;
long g;
long r;
if (a == 0)
{
b = 0;
g = 0;
r = 0;
}
else
{
b = 0;
g = 0;
r = 0;
for (int i = 0; i < c.Length; ++i)
{
b += (long)c[i].A * c[i].B * w[i];
g += (long)c[i].A * c[i].G * w[i];
r += (long)c[i].A * c[i].R * w[i];
}
b /= asum;
g /= asum;
r /= asum;
}
return ColorBgra.FromUInt32((uint)b + ((uint)g << 8) + ((uint)r << 16) + ((uint)a << 24));
}
/// <summary>
/// Blends the colors based on the given weight values.
/// </summary>
/// <param name="c">The array of color values.</param>
/// <param name="w">The array of weight values.</param>
/// <returns>
/// Each color will be blended in proportionally to its weight value respective to
/// the total summation of the weight values.
/// </returns>
/// <remarks>
/// "WAIP" stands for "weights, floating-point"</remarks>
public static ColorBgra BlendColorsWFP(ColorBgra[] c, double[] w)
{
if (c.Length != w.Length)
{
throw new ArgumentException("c.Length != w.Length");
}
if (c.Length == 0)
{
return ColorBgra.FromUInt32(0);
}
double wsum = 0;
double asum = 0;
for (int i = 0; i < w.Length; ++i)
{
wsum += w[i];
asum += (double)c[i].A * w[i];
}
double a = asum / wsum;
double aMultWsum = a * wsum;
double b;
double g;
double r;
if (asum == 0)
{
b = 0;
g = 0;
r = 0;
}
else
{
b = 0;
g = 0;
r = 0;
for (int i = 0; i < c.Length; ++i)
{
b += (double)c[i].A * c[i].B * w[i];
g += (double)c[i].A * c[i].G * w[i];
r += (double)c[i].A * c[i].R * w[i];
}
b /= aMultWsum;
g /= aMultWsum;
r /= aMultWsum;
}
return ColorBgra.FromBgra((byte)b, (byte)g, (byte)r, (byte)a);
}
public override string ToString()
{
return "B: " + B + ", G: " + G + ", R: " + R + ", A: " + A;
}
/// <summary>
/// Casts a ColorBgra to a UInt32.
/// </summary>
public static explicit operator UInt32(ColorBgra color)
{
return color.Bgra;
}
/// <summary>
/// Casts a UInt32 to a ColorBgra.
/// </summary>
public static explicit operator ColorBgra(UInt32 uint32)
{
return ColorBgra.FromUInt32(uint32);
}
//// Colors: copied from System.Drawing.Color's list (don't worry I didn't type it in
//// manually, I used a code generator w/ reflection ...)
public static ColorBgra Transparent { get { return ColorBgra.FromBgra (255, 255, 255, 0); } }
public static ColorBgra Zero { get { return (ColorBgra)0; } }
public static ColorBgra Black { get { return ColorBgra.FromBgra (0, 0, 0, 255); } }
public static ColorBgra Blue { get { return ColorBgra.FromBgra (255, 0, 0, 255); } }
public static ColorBgra Cyan { get { return ColorBgra.FromBgra (255, 255, 0, 255); } }
public static ColorBgra Green { get { return ColorBgra.FromBgra (0, 128, 0, 255); } }
public static ColorBgra Magenta { get { return ColorBgra.FromBgra (255, 0, 255, 255); } }
public static ColorBgra Red { get { return ColorBgra.FromBgra (0, 0, 255, 255); } }
public static ColorBgra White { get { return ColorBgra.FromBgra (255, 255, 255, 255); } }
public static ColorBgra Yellow { get { return ColorBgra.FromBgra (0, 255, 255, 255); } }
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using log4net;
namespace OpenSim.Framework.Communications.Clients
{
public class RegionClient
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public bool DoCreateChildAgentCall(GridRegion region, AgentCircuitData aCircuit, string authKey, uint teleportFlags, out string reason)
{
reason = String.Empty;
// Eventually, we want to use a caps url instead of the agentID
string uri = string.Empty;
try
{
uri = "http://" + region.ExternalEndPoint.Address + ":" + region.HttpPort + "/agent/" + aCircuit.AgentID + "/";
}
catch (Exception e)
{
m_log.Debug("[REST COMMS]: Unable to resolve external endpoint on agent create. Reason: " + e.Message);
reason = e.Message;
return false;
}
//Console.WriteLine(" >>> DoCreateChildAgentCall <<< " + uri);
HttpWebRequest AgentCreateRequest = (HttpWebRequest)WebRequest.Create(uri);
AgentCreateRequest.Method = "POST";
AgentCreateRequest.ContentType = "application/json";
AgentCreateRequest.Timeout = 10000;
//AgentCreateRequest.KeepAlive = false;
AgentCreateRequest.Headers.Add("Authorization", authKey);
// Fill it in
OSDMap args = null;
try
{
args = aCircuit.PackAgentCircuitData();
}
catch (Exception e)
{
m_log.Debug("[REST COMMS]: PackAgentCircuitData failed with exception: " + e.Message);
}
// Add the regionhandle of the destination region
ulong regionHandle = GetRegionHandle(region.RegionHandle);
args["destination_handle"] = OSD.FromString(regionHandle.ToString());
args["teleport_flags"] = OSD.FromString(teleportFlags.ToString());
string strBuffer = "";
byte[] buffer = new byte[1];
try
{
strBuffer = OSDParser.SerializeJsonString(args);
Encoding str = Util.UTF8;
buffer = str.GetBytes(strBuffer);
}
catch (Exception e)
{
m_log.WarnFormat("[REST COMMS]: Exception thrown on serialization of ChildCreate: {0}", e.Message);
// ignore. buffer will be empty, caller should check.
}
Stream os = null;
try
{ // send the Post
AgentCreateRequest.ContentLength = buffer.Length; //Count bytes to send
os = AgentCreateRequest.GetRequestStream();
os.Write(buffer, 0, strBuffer.Length); //Send it
//m_log.InfoFormat("[REST COMMS]: Posted CreateChildAgent request to remote sim {0}", uri);
}
//catch (WebException ex)
catch
{
//m_log.InfoFormat("[REST COMMS]: Bad send on ChildAgentUpdate {0}", ex.Message);
reason = "cannot contact remote region";
return false;
}
finally
{
if (os != null)
os.Close();
}
// Let's wait for the response
//m_log.Info("[REST COMMS]: Waiting for a reply after DoCreateChildAgentCall");
WebResponse webResponse = null;
StreamReader sr = null;
try
{
webResponse = AgentCreateRequest.GetResponse();
if (webResponse == null)
{
m_log.Info("[REST COMMS]: Null reply on DoCreateChildAgentCall post");
}
else
{
sr = new StreamReader(webResponse.GetResponseStream());
string response = sr.ReadToEnd().Trim();
m_log.InfoFormat("[REST COMMS]: DoCreateChildAgentCall reply was {0} ", response);
if (!String.IsNullOrEmpty(response))
{
try
{
// we assume we got an OSDMap back
OSDMap r = GetOSDMap(response);
bool success = r["success"].AsBoolean();
reason = r["reason"].AsString();
return success;
}
catch (NullReferenceException e)
{
m_log.InfoFormat("[REST COMMS]: exception on reply of DoCreateChildAgentCall {0}", e.Message);
// check for old style response
if (response.ToLower().StartsWith("true"))
return true;
return false;
}
}
}
}
catch (Exception ex)
{
m_log.DebugFormat("[REST COMMS]: exception on reply of DoCreateChildAgentCall {0}", ex.Message);
// ignore, really
}
finally
{
if (sr != null)
sr.Close();
}
return true;
}
public bool DoChildAgentUpdateCall(GridRegion region, IAgentData cAgentData)
{
// Eventually, we want to use a caps url instead of the agentID
string uri = string.Empty;
try
{
uri = "http://" + region.ExternalEndPoint.Address + ":" + region.HttpPort + "/agent/" + cAgentData.AgentID + "/";
}
catch (Exception e)
{
m_log.Debug("[REST COMMS]: Unable to resolve external endpoint on agent update. Reason: " + e.Message);
return false;
}
//Console.WriteLine(" >>> DoChildAgentUpdateCall <<< " + uri);
HttpWebRequest ChildUpdateRequest = (HttpWebRequest)WebRequest.Create(uri);
ChildUpdateRequest.Method = "PUT";
ChildUpdateRequest.ContentType = "application/json";
ChildUpdateRequest.Timeout = 10000;
//ChildUpdateRequest.KeepAlive = false;
// Fill it in
OSDMap args = null;
try
{
args = cAgentData.Pack();
}
catch (Exception e)
{
m_log.Debug("[REST COMMS]: PackUpdateMessage failed with exception: " + e.Message);
}
// Add the regionhandle of the destination region
ulong regionHandle = GetRegionHandle(region.RegionHandle);
args["destination_handle"] = OSD.FromString(regionHandle.ToString());
string strBuffer = "";
byte[] buffer = new byte[1];
try
{
strBuffer = OSDParser.SerializeJsonString(args);
Encoding str = Util.UTF8;
buffer = str.GetBytes(strBuffer);
}
catch (Exception e)
{
m_log.WarnFormat("[REST COMMS]: Exception thrown on serialization of ChildUpdate: {0}", e.Message);
// ignore. buffer will be empty, caller should check.
}
Stream os = null;
try
{ // send the Post
ChildUpdateRequest.ContentLength = buffer.Length; //Count bytes to send
os = ChildUpdateRequest.GetRequestStream();
os.Write(buffer, 0, strBuffer.Length); //Send it
//m_log.InfoFormat("[REST COMMS]: Posted ChildAgentUpdate request to remote sim {0}", uri);
}
//catch (WebException ex)
catch
{
//m_log.InfoFormat("[REST COMMS]: Bad send on ChildAgentUpdate {0}", ex.Message);
return false;
}
finally
{
if (os != null)
os.Close();
}
// Let's wait for the response
//m_log.Info("[REST COMMS]: Waiting for a reply after ChildAgentUpdate");
WebResponse webResponse = null;
StreamReader sr = null;
try
{
webResponse = ChildUpdateRequest.GetResponse();
if (webResponse == null)
{
m_log.Info("[REST COMMS]: Null reply on ChilAgentUpdate post");
}
sr = new StreamReader(webResponse.GetResponseStream());
//reply = sr.ReadToEnd().Trim();
sr.ReadToEnd().Trim();
sr.Close();
//m_log.InfoFormat("[REST COMMS]: ChilAgentUpdate reply was {0} ", reply);
}
catch (WebException ex)
{
m_log.InfoFormat("[REST COMMS]: exception on reply of ChilAgentUpdate {0}", ex.Message);
// ignore, really
}
finally
{
if (sr != null)
sr.Close();
}
return true;
}
public bool DoRetrieveRootAgentCall(GridRegion region, UUID id, out IAgentData agent)
{
agent = null;
// Eventually, we want to use a caps url instead of the agentID
string uri = "http://" + region.ExternalEndPoint.Address + ":" + region.HttpPort + "/agent/" + id + "/" + region.RegionHandle.ToString() + "/";
//Console.WriteLine(" >>> DoRetrieveRootAgentCall <<< " + uri);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "GET";
request.Timeout = 10000;
//request.Headers.Add("authorization", ""); // coming soon
HttpWebResponse webResponse = null;
string reply = string.Empty;
StreamReader sr = null;
try
{
webResponse = (HttpWebResponse)request.GetResponse();
if (webResponse == null)
{
m_log.Info("[REST COMMS]: Null reply on agent get ");
}
sr = new StreamReader(webResponse.GetResponseStream());
reply = sr.ReadToEnd().Trim();
//Console.WriteLine("[REST COMMS]: ChilAgentUpdate reply was " + reply);
}
catch (WebException ex)
{
m_log.InfoFormat("[REST COMMS]: exception on reply of agent get {0}", ex.Message);
// ignore, really
return false;
}
finally
{
if (sr != null)
sr.Close();
}
if (webResponse.StatusCode == HttpStatusCode.OK)
{
// we know it's jason
OSDMap args = GetOSDMap(reply);
if (args == null)
{
//Console.WriteLine("[REST COMMS]: Error getting OSDMap from reply");
return false;
}
agent = new CompleteAgentData();
agent.Unpack(args);
return true;
}
//Console.WriteLine("[REST COMMS]: DoRetrieveRootAgentCall returned status " + webResponse.StatusCode);
return false;
}
public bool DoReleaseAgentCall(ulong regionHandle, UUID id, string uri)
{
//m_log.Debug(" >>> DoReleaseAgentCall <<< " + uri);
WebRequest request = WebRequest.Create(uri);
request.Method = "DELETE";
request.Timeout = 10000;
StreamReader sr = null;
try
{
WebResponse webResponse = request.GetResponse();
if (webResponse == null)
{
m_log.Info("[REST COMMS]: Null reply on agent delete ");
}
sr = new StreamReader(webResponse.GetResponseStream());
//reply = sr.ReadToEnd().Trim();
sr.ReadToEnd().Trim();
sr.Close();
//m_log.InfoFormat("[REST COMMS]: ChilAgentUpdate reply was {0} ", reply);
}
catch (WebException ex)
{
m_log.InfoFormat("[REST COMMS]: exception on reply of agent delete {0}", ex.Message);
// ignore, really
}
finally
{
if (sr != null)
sr.Close();
}
return true;
}
public bool DoCloseAgentCall(GridRegion region, UUID id)
{
string uri = string.Empty;
try
{
uri = "http://" + region.ExternalEndPoint.Address + ":" + region.HttpPort + "/agent/" + id + "/" + region.RegionHandle.ToString() + "/";
}
catch (Exception e)
{
m_log.Debug("[REST COMMS]: Unable to resolve external endpoint on agent close. Reason: " + e.Message);
return false;
}
//Console.WriteLine(" >>> DoCloseAgentCall <<< " + uri);
WebRequest request = WebRequest.Create(uri);
request.Method = "DELETE";
request.Timeout = 10000;
StreamReader sr = null;
try
{
WebResponse webResponse = request.GetResponse();
if (webResponse == null)
{
m_log.Info("[REST COMMS]: Null reply on agent delete ");
}
sr = new StreamReader(webResponse.GetResponseStream());
//reply = sr.ReadToEnd().Trim();
sr.ReadToEnd().Trim();
sr.Close();
//m_log.InfoFormat("[REST COMMS]: ChilAgentUpdate reply was {0} ", reply);
}
catch (WebException ex)
{
m_log.InfoFormat("[REST COMMS]: exception on reply of agent delete {0}", ex.Message);
// ignore, really
}
finally
{
if (sr != null)
sr.Close();
}
return true;
}
public bool DoCreateObjectCall(GridRegion region, ISceneObject sog, string sogXml2, bool allowScriptCrossing)
{
ulong regionHandle = GetRegionHandle(region.RegionHandle);
string uri
= "http://" + region.ExternalEndPoint.Address + ":" + region.HttpPort
+ "/object/" + sog.UUID + "/" + regionHandle.ToString() + "/";
//m_log.Debug(" >>> DoCreateChildAgentCall <<< " + uri);
WebRequest ObjectCreateRequest = WebRequest.Create(uri);
ObjectCreateRequest.Method = "POST";
ObjectCreateRequest.ContentType = "application/json";
ObjectCreateRequest.Timeout = 10000;
OSDMap args = new OSDMap(2);
args["sog"] = OSD.FromString(sogXml2);
args["extra"] = OSD.FromString(sog.ExtraToXmlString());
if (allowScriptCrossing)
{
string state = sog.GetStateSnapshot();
if (state.Length > 0)
args["state"] = OSD.FromString(state);
}
string strBuffer = "";
byte[] buffer = new byte[1];
try
{
strBuffer = OSDParser.SerializeJsonString(args);
Encoding str = Util.UTF8;
buffer = str.GetBytes(strBuffer);
}
catch (Exception e)
{
m_log.WarnFormat("[REST COMMS]: Exception thrown on serialization of CreateObject: {0}", e.Message);
// ignore. buffer will be empty, caller should check.
}
Stream os = null;
try
{ // send the Post
ObjectCreateRequest.ContentLength = buffer.Length; //Count bytes to send
os = ObjectCreateRequest.GetRequestStream();
os.Write(buffer, 0, strBuffer.Length); //Send it
m_log.InfoFormat("[REST COMMS]: Posted ChildAgentUpdate request to remote sim {0}", uri);
}
//catch (WebException ex)
catch
{
// m_log.InfoFormat("[REST COMMS]: Bad send on CreateObject {0}", ex.Message);
return false;
}
finally
{
if (os != null)
os.Close();
}
// Let's wait for the response
//m_log.Info("[REST COMMS]: Waiting for a reply after DoCreateChildAgentCall");
StreamReader sr = null;
try
{
WebResponse webResponse = ObjectCreateRequest.GetResponse();
if (webResponse == null)
{
m_log.Info("[REST COMMS]: Null reply on DoCreateObjectCall post");
}
sr = new StreamReader(webResponse.GetResponseStream());
//reply = sr.ReadToEnd().Trim();
sr.ReadToEnd().Trim();
//m_log.InfoFormat("[REST COMMS]: DoCreateChildAgentCall reply was {0} ", reply);
}
catch (WebException ex)
{
m_log.InfoFormat("[REST COMMS]: exception on reply of DoCreateObjectCall {0}", ex.Message);
// ignore, really
}
finally
{
if (sr != null)
sr.Close();
}
return true;
}
public bool DoCreateObjectCall(GridRegion region, UUID userID, UUID itemID)
{
ulong regionHandle = GetRegionHandle(region.RegionHandle);
string uri = "http://" + region.ExternalEndPoint.Address + ":" + region.HttpPort + "/object/" + UUID.Zero + "/" + regionHandle.ToString() + "/";
//m_log.Debug(" >>> DoCreateChildAgentCall <<< " + uri);
WebRequest ObjectCreateRequest = WebRequest.Create(uri);
ObjectCreateRequest.Method = "PUT";
ObjectCreateRequest.ContentType = "application/json";
ObjectCreateRequest.Timeout = 10000;
OSDMap args = new OSDMap(2);
args["userid"] = OSD.FromUUID(userID);
args["itemid"] = OSD.FromUUID(itemID);
string strBuffer = "";
byte[] buffer = new byte[1];
try
{
strBuffer = OSDParser.SerializeJsonString(args);
Encoding str = Util.UTF8;
buffer = str.GetBytes(strBuffer);
}
catch (Exception e)
{
m_log.WarnFormat("[REST COMMS]: Exception thrown on serialization of CreateObject: {0}", e.Message);
// ignore. buffer will be empty, caller should check.
}
Stream os = null;
try
{ // send the Post
ObjectCreateRequest.ContentLength = buffer.Length; //Count bytes to send
os = ObjectCreateRequest.GetRequestStream();
os.Write(buffer, 0, strBuffer.Length); //Send it
//m_log.InfoFormat("[REST COMMS]: Posted CreateObject request to remote sim {0}", uri);
}
//catch (WebException ex)
catch
{
// m_log.InfoFormat("[REST COMMS]: Bad send on CreateObject {0}", ex.Message);
return false;
}
finally
{
if (os != null)
os.Close();
}
// Let's wait for the response
//m_log.Info("[REST COMMS]: Waiting for a reply after DoCreateChildAgentCall");
StreamReader sr = null;
try
{
WebResponse webResponse = ObjectCreateRequest.GetResponse();
if (webResponse == null)
{
m_log.Info("[REST COMMS]: Null reply on DoCreateObjectCall post");
}
sr = new StreamReader(webResponse.GetResponseStream());
sr.ReadToEnd().Trim();
sr.ReadToEnd().Trim();
//m_log.InfoFormat("[REST COMMS]: DoCreateChildAgentCall reply was {0} ", reply);
}
catch (WebException ex)
{
m_log.InfoFormat("[REST COMMS]: exception on reply of DoCreateObjectCall {0}", ex.Message);
// ignore, really
}
finally
{
if (sr != null)
sr.Close();
}
return true;
}
public bool DoHelloNeighbourCall(RegionInfo region, RegionInfo thisRegion)
{
string uri = "http://" + region.ExternalEndPoint.Address + ":" + region.HttpPort + "/region/" + thisRegion.RegionID + "/";
//m_log.Debug(" >>> DoHelloNeighbourCall <<< " + uri);
WebRequest HelloNeighbourRequest = WebRequest.Create(uri);
HelloNeighbourRequest.Method = "POST";
HelloNeighbourRequest.ContentType = "application/json";
HelloNeighbourRequest.Timeout = 10000;
// Fill it in
OSDMap args = null;
try
{
args = thisRegion.PackRegionInfoData();
}
catch (Exception e)
{
m_log.Debug("[REST COMMS]: PackRegionInfoData failed with exception: " + e.Message);
}
// Add the regionhandle of the destination region
ulong regionHandle = GetRegionHandle(region.RegionHandle);
args["destination_handle"] = OSD.FromString(regionHandle.ToString());
string strBuffer = "";
byte[] buffer = new byte[1];
try
{
strBuffer = OSDParser.SerializeJsonString(args);
Encoding str = Util.UTF8;
buffer = str.GetBytes(strBuffer);
}
catch (Exception e)
{
m_log.WarnFormat("[REST COMMS]: Exception thrown on serialization of HelloNeighbour: {0}", e.Message);
// ignore. buffer will be empty, caller should check.
}
Stream os = null;
try
{ // send the Post
HelloNeighbourRequest.ContentLength = buffer.Length; //Count bytes to send
os = HelloNeighbourRequest.GetRequestStream();
os.Write(buffer, 0, strBuffer.Length); //Send it
//m_log.InfoFormat("[REST COMMS]: Posted HelloNeighbour request to remote sim {0}", uri);
}
//catch (WebException ex)
catch
{
//m_log.InfoFormat("[REST COMMS]: Bad send on HelloNeighbour {0}", ex.Message);
return false;
}
finally
{
if (os != null)
os.Close();
}
// Let's wait for the response
//m_log.Info("[REST COMMS]: Waiting for a reply after DoHelloNeighbourCall");
StreamReader sr = null;
try
{
WebResponse webResponse = HelloNeighbourRequest.GetResponse();
if (webResponse == null)
{
m_log.Info("[REST COMMS]: Null reply on DoHelloNeighbourCall post");
}
sr = new StreamReader(webResponse.GetResponseStream());
//reply = sr.ReadToEnd().Trim();
sr.ReadToEnd().Trim();
//m_log.InfoFormat("[REST COMMS]: DoHelloNeighbourCall reply was {0} ", reply);
}
catch (WebException ex)
{
m_log.InfoFormat("[REST COMMS]: exception on reply of DoHelloNeighbourCall {0}", ex.Message);
// ignore, really
}
finally
{
if (sr != null)
sr.Close();
}
return true;
}
#region Hyperlinks
public virtual ulong GetRegionHandle(ulong handle)
{
return handle;
}
public virtual bool IsHyperlink(ulong handle)
{
return false;
}
public virtual void SendUserInformation(GridRegion regInfo, AgentCircuitData aCircuit)
{
}
public virtual void AdjustUserInformation(AgentCircuitData aCircuit)
{
}
#endregion /* Hyperlinks */
public static OSDMap GetOSDMap(string data)
{
OSDMap args = null;
try
{
OSD buffer;
// We should pay attention to the content-type, but let's assume we know it's Json
buffer = OSDParser.DeserializeJson(data);
if (buffer.Type == OSDType.Map)
{
args = (OSDMap)buffer;
return args;
}
else
{
// uh?
System.Console.WriteLine("[REST COMMS]: Got OSD of type " + buffer.Type.ToString());
return null;
}
}
catch (Exception ex)
{
System.Console.WriteLine("[REST COMMS]: exception on parse of REST message " + ex.Message);
return null;
}
}
}
}
| |
// 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.Xml.Serialization
{
using System;
using System.IO;
using System.Collections;
using System.ComponentModel;
using System.Threading;
using System.Reflection;
using System.Security;
using System.Globalization;
///<internalonly/>
public abstract class XmlSerializationGeneratedCode
{
internal void Init(TempAssembly tempAssembly)
{
}
// this method must be called at the end of serialization
internal void Dispose()
{
}
}
internal class XmlSerializationCodeGen
{
private IndentedWriter _writer;
private int _nextMethodNumber = 0;
private Hashtable _methodNames = new Hashtable();
private ReflectionAwareCodeGen _raCodeGen;
private TypeScope[] _scopes;
private TypeDesc _stringTypeDesc = null;
private TypeDesc _qnameTypeDesc = null;
private string _access;
private string _className;
private TypeMapping[] _referencedMethods;
private int _references = 0;
private Hashtable _generatedMethods = new Hashtable();
internal XmlSerializationCodeGen(IndentedWriter writer, TypeScope[] scopes, string access, string className)
{
_writer = writer;
_scopes = scopes;
if (scopes.Length > 0)
{
_stringTypeDesc = scopes[0].GetTypeDesc(typeof(string));
_qnameTypeDesc = scopes[0].GetTypeDesc(typeof(XmlQualifiedName));
}
_raCodeGen = new ReflectionAwareCodeGen(writer);
_className = className;
_access = access;
}
internal IndentedWriter Writer { get { return _writer; } }
internal int NextMethodNumber { get { return _nextMethodNumber; } set { _nextMethodNumber = value; } }
internal ReflectionAwareCodeGen RaCodeGen { get { return _raCodeGen; } }
internal TypeDesc StringTypeDesc { get { return _stringTypeDesc; } }
internal TypeDesc QnameTypeDesc { get { return _qnameTypeDesc; } }
internal string ClassName { get { return _className; } }
internal string Access { get { return _access; } }
internal TypeScope[] Scopes { get { return _scopes; } }
internal Hashtable MethodNames { get { return _methodNames; } }
internal Hashtable GeneratedMethods { get { return _generatedMethods; } }
internal virtual void GenerateMethod(TypeMapping mapping) { }
internal void GenerateReferencedMethods()
{
while (_references > 0)
{
TypeMapping mapping = _referencedMethods[--_references];
GenerateMethod(mapping);
}
}
internal string ReferenceMapping(TypeMapping mapping)
{
if (!mapping.IsSoap)
{
if (_generatedMethods[mapping] == null)
{
_referencedMethods = EnsureArrayIndex(_referencedMethods, _references);
_referencedMethods[_references++] = mapping;
}
}
return (string)_methodNames[mapping];
}
private TypeMapping[] EnsureArrayIndex(TypeMapping[] a, int index)
{
if (a == null) return new TypeMapping[32];
if (index < a.Length) return a;
TypeMapping[] b = new TypeMapping[a.Length + 32];
Array.Copy(a, 0, b, 0, index);
return b;
}
internal void WriteQuotedCSharpString(string value)
{
_raCodeGen.WriteQuotedCSharpString(value);
}
internal void GenerateHashtableGetBegin(string privateName, string publicName)
{
_writer.Write(typeof(Hashtable).FullName);
_writer.Write(" ");
_writer.Write(privateName);
_writer.WriteLine(" = null;");
_writer.Write("public override ");
_writer.Write(typeof(Hashtable).FullName);
_writer.Write(" ");
_writer.Write(publicName);
_writer.WriteLine(" {");
_writer.Indent++;
_writer.WriteLine("get {");
_writer.Indent++;
_writer.Write("if (");
_writer.Write(privateName);
_writer.WriteLine(" == null) {");
_writer.Indent++;
_writer.Write(typeof(Hashtable).FullName);
_writer.Write(" _tmp = new ");
_writer.Write(typeof(Hashtable).FullName);
_writer.WriteLine("();");
}
internal void GenerateHashtableGetEnd(string privateName)
{
_writer.Write("if (");
_writer.Write(privateName);
_writer.Write(" == null) ");
_writer.Write(privateName);
_writer.WriteLine(" = _tmp;");
_writer.Indent--;
_writer.WriteLine("}");
_writer.Write("return ");
_writer.Write(privateName);
_writer.WriteLine(";");
_writer.Indent--;
_writer.WriteLine("}");
_writer.Indent--;
_writer.WriteLine("}");
}
internal void GeneratePublicMethods(string privateName, string publicName, string[] methods, XmlMapping[] xmlMappings)
{
GenerateHashtableGetBegin(privateName, publicName);
if (methods != null && methods.Length != 0 && xmlMappings != null && xmlMappings.Length == methods.Length)
{
for (int i = 0; i < methods.Length; i++)
{
if (methods[i] == null)
continue;
_writer.Write("_tmp[");
WriteQuotedCSharpString(xmlMappings[i].Key);
_writer.Write("] = ");
WriteQuotedCSharpString(methods[i]);
_writer.WriteLine(";");
}
}
GenerateHashtableGetEnd(privateName);
}
internal void GenerateSupportedTypes(Type[] types)
{
_writer.Write("public override ");
_writer.Write(typeof(bool).FullName);
_writer.Write(" CanSerialize(");
_writer.Write(typeof(Type).FullName);
_writer.WriteLine(" type) {");
_writer.Indent++;
Hashtable uniqueTypes = new Hashtable();
for (int i = 0; i < types.Length; i++)
{
Type type = types[i];
if (type == null)
continue;
if (!type.IsPublic && !type.IsNestedPublic)
continue;
if (uniqueTypes[type] != null)
continue;
if (DynamicAssemblies.IsTypeDynamic(type))
continue;
if (type.IsGenericType || type.ContainsGenericParameters && DynamicAssemblies.IsTypeDynamic(type.GetGenericArguments()))
continue;
uniqueTypes[type] = type;
_writer.Write("if (type == typeof(");
_writer.Write(CodeIdentifier.GetCSharpName(type));
_writer.WriteLine(")) return true;");
}
_writer.WriteLine("return false;");
_writer.Indent--;
_writer.WriteLine("}");
}
internal string GenerateBaseSerializer(string baseSerializer, string readerClass, string writerClass, CodeIdentifiers classes)
{
baseSerializer = CodeIdentifier.MakeValid(baseSerializer);
baseSerializer = classes.AddUnique(baseSerializer, baseSerializer);
_writer.WriteLine();
_writer.Write("public abstract class ");
_writer.Write(CodeIdentifier.GetCSharpName(baseSerializer));
_writer.Write(" : ");
_writer.Write(typeof(System.Xml.Serialization.XmlSerializer).FullName);
_writer.WriteLine(" {");
_writer.Indent++;
_writer.Write("protected override ");
_writer.Write(typeof(System.Xml.Serialization.XmlSerializationReader).FullName);
_writer.WriteLine(" CreateReader() {");
_writer.Indent++;
_writer.Write("return new ");
_writer.Write(readerClass);
_writer.WriteLine("();");
_writer.Indent--;
_writer.WriteLine("}");
_writer.Write("protected override ");
_writer.Write(typeof(System.Xml.Serialization.XmlSerializationWriter).FullName);
_writer.WriteLine(" CreateWriter() {");
_writer.Indent++;
_writer.Write("return new ");
_writer.Write(writerClass);
_writer.WriteLine("();");
_writer.Indent--;
_writer.WriteLine("}");
_writer.Indent--;
_writer.WriteLine("}");
return baseSerializer;
}
internal string GenerateTypedSerializer(string readMethod, string writeMethod, XmlMapping mapping, CodeIdentifiers classes, string baseSerializer, string readerClass, string writerClass)
{
string serializerName = CodeIdentifier.MakeValid(Accessor.UnescapeName(mapping.Accessor.Mapping.TypeDesc.Name));
serializerName = classes.AddUnique(serializerName + "Serializer", mapping);
_writer.WriteLine();
_writer.Write("public sealed class ");
_writer.Write(CodeIdentifier.GetCSharpName(serializerName));
_writer.Write(" : ");
_writer.Write(baseSerializer);
_writer.WriteLine(" {");
_writer.Indent++;
_writer.WriteLine();
_writer.Write("public override ");
_writer.Write(typeof(bool).FullName);
_writer.Write(" CanDeserialize(");
_writer.Write(typeof(XmlReader).FullName);
_writer.WriteLine(" xmlReader) {");
_writer.Indent++;
if (mapping.Accessor.Any)
{
_writer.WriteLine("return true;");
}
else
{
_writer.Write("return xmlReader.IsStartElement(");
WriteQuotedCSharpString(mapping.Accessor.Name);
_writer.Write(", ");
WriteQuotedCSharpString(mapping.Accessor.Namespace);
_writer.WriteLine(");");
}
_writer.Indent--;
_writer.WriteLine("}");
if (writeMethod != null)
{
_writer.WriteLine();
_writer.Write("protected override void Serialize(object objectToSerialize, ");
_writer.Write(typeof(System.Xml.Serialization.XmlSerializationWriter).FullName);
_writer.WriteLine(" writer) {");
_writer.Indent++;
_writer.Write("((");
_writer.Write(writerClass);
_writer.Write(")writer).");
_writer.Write(writeMethod);
_writer.Write("(");
if (mapping is XmlMembersMapping)
{
_writer.Write("(object[])");
}
_writer.WriteLine("objectToSerialize);");
_writer.Indent--;
_writer.WriteLine("}");
}
if (readMethod != null)
{
_writer.WriteLine();
_writer.Write("protected override object Deserialize(");
_writer.Write(typeof(System.Xml.Serialization.XmlSerializationReader).FullName);
_writer.WriteLine(" reader) {");
_writer.Indent++;
_writer.Write("return ((");
_writer.Write(readerClass);
_writer.Write(")reader).");
_writer.Write(readMethod);
_writer.WriteLine("();");
_writer.Indent--;
_writer.WriteLine("}");
}
_writer.Indent--;
_writer.WriteLine("}");
return serializerName;
}
private void GenerateTypedSerializers(Hashtable serializers)
{
string privateName = "typedSerializers";
GenerateHashtableGetBegin(privateName, "TypedSerializers");
foreach (string key in serializers.Keys)
{
_writer.Write("_tmp.Add(");
WriteQuotedCSharpString(key);
_writer.Write(", new ");
_writer.Write((string)serializers[key]);
_writer.WriteLine("());");
}
GenerateHashtableGetEnd("typedSerializers");
}
//GenerateGetSerializer(serializers, xmlMappings);
private void GenerateGetSerializer(Hashtable serializers, XmlMapping[] xmlMappings)
{
_writer.Write("public override ");
_writer.Write(typeof(System.Xml.Serialization.XmlSerializer).FullName);
_writer.Write(" GetSerializer(");
_writer.Write(typeof(Type).FullName);
_writer.WriteLine(" type) {");
_writer.Indent++;
for (int i = 0; i < xmlMappings.Length; i++)
{
if (xmlMappings[i] is XmlTypeMapping)
{
Type type = xmlMappings[i].Accessor.Mapping.TypeDesc.Type;
if (type == null)
continue;
if (!type.IsPublic && !type.IsNestedPublic)
continue;
if (DynamicAssemblies.IsTypeDynamic(type))
continue;
if (type.IsGenericType || type.ContainsGenericParameters && DynamicAssemblies.IsTypeDynamic(type.GetGenericArguments()))
continue;
_writer.Write("if (type == typeof(");
_writer.Write(CodeIdentifier.GetCSharpName(type));
_writer.Write(")) return new ");
_writer.Write((string)serializers[xmlMappings[i].Key]);
_writer.WriteLine("();");
}
}
_writer.WriteLine("return null;");
_writer.Indent--;
_writer.WriteLine("}");
}
internal void GenerateSerializerContract(string className, XmlMapping[] xmlMappings, Type[] types, string readerType, string[] readMethods, string writerType, string[] writerMethods, Hashtable serializers)
{
_writer.WriteLine();
_writer.Write("public class XmlSerializerContract : global::");
_writer.Write(typeof(System.Xml.Serialization.XmlSerializerImplementation).FullName);
_writer.WriteLine(" {");
_writer.Indent++;
_writer.Write("public override global::");
_writer.Write(typeof(System.Xml.Serialization.XmlSerializationReader).FullName);
_writer.Write(" Reader { get { return new ");
_writer.Write(readerType);
_writer.WriteLine("(); } }");
_writer.Write("public override global::");
_writer.Write(typeof(System.Xml.Serialization.XmlSerializationWriter).FullName);
_writer.Write(" Writer { get { return new ");
_writer.Write(writerType);
_writer.WriteLine("(); } }");
GeneratePublicMethods(nameof(readMethods), "ReadMethods", readMethods, xmlMappings);
GeneratePublicMethods("writeMethods", "WriteMethods", writerMethods, xmlMappings);
GenerateTypedSerializers(serializers);
GenerateSupportedTypes(types);
GenerateGetSerializer(serializers, xmlMappings);
_writer.Indent--;
_writer.WriteLine("}");
}
internal static bool IsWildcard(SpecialMapping mapping)
{
if (mapping is SerializableMapping)
return ((SerializableMapping)mapping).IsAny;
return mapping.TypeDesc.CanBeElementValue;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V8.Resources
{
/// <summary>Resource name for the <c>BiddingStrategy</c> resource.</summary>
public sealed partial class BiddingStrategyName : gax::IResourceName, sys::IEquatable<BiddingStrategyName>
{
/// <summary>The possible contents of <see cref="BiddingStrategyName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/biddingStrategies/{bidding_strategy_id}</c>.
/// </summary>
CustomerBiddingStrategy = 1,
}
private static gax::PathTemplate s_customerBiddingStrategy = new gax::PathTemplate("customers/{customer_id}/biddingStrategies/{bidding_strategy_id}");
/// <summary>Creates a <see cref="BiddingStrategyName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="BiddingStrategyName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static BiddingStrategyName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new BiddingStrategyName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="BiddingStrategyName"/> with the pattern
/// <c>customers/{customer_id}/biddingStrategies/{bidding_strategy_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="biddingStrategyId">The <c>BiddingStrategy</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="BiddingStrategyName"/> constructed from the provided ids.</returns>
public static BiddingStrategyName FromCustomerBiddingStrategy(string customerId, string biddingStrategyId) =>
new BiddingStrategyName(ResourceNameType.CustomerBiddingStrategy, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), biddingStrategyId: gax::GaxPreconditions.CheckNotNullOrEmpty(biddingStrategyId, nameof(biddingStrategyId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="BiddingStrategyName"/> with pattern
/// <c>customers/{customer_id}/biddingStrategies/{bidding_strategy_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="biddingStrategyId">The <c>BiddingStrategy</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="BiddingStrategyName"/> with pattern
/// <c>customers/{customer_id}/biddingStrategies/{bidding_strategy_id}</c>.
/// </returns>
public static string Format(string customerId, string biddingStrategyId) =>
FormatCustomerBiddingStrategy(customerId, biddingStrategyId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="BiddingStrategyName"/> with pattern
/// <c>customers/{customer_id}/biddingStrategies/{bidding_strategy_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="biddingStrategyId">The <c>BiddingStrategy</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="BiddingStrategyName"/> with pattern
/// <c>customers/{customer_id}/biddingStrategies/{bidding_strategy_id}</c>.
/// </returns>
public static string FormatCustomerBiddingStrategy(string customerId, string biddingStrategyId) =>
s_customerBiddingStrategy.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(biddingStrategyId, nameof(biddingStrategyId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="BiddingStrategyName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/biddingStrategies/{bidding_strategy_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="biddingStrategyName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="BiddingStrategyName"/> if successful.</returns>
public static BiddingStrategyName Parse(string biddingStrategyName) => Parse(biddingStrategyName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="BiddingStrategyName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/biddingStrategies/{bidding_strategy_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="biddingStrategyName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="BiddingStrategyName"/> if successful.</returns>
public static BiddingStrategyName Parse(string biddingStrategyName, bool allowUnparsed) =>
TryParse(biddingStrategyName, allowUnparsed, out BiddingStrategyName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="BiddingStrategyName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/biddingStrategies/{bidding_strategy_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="biddingStrategyName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="BiddingStrategyName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string biddingStrategyName, out BiddingStrategyName result) =>
TryParse(biddingStrategyName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="BiddingStrategyName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/biddingStrategies/{bidding_strategy_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="biddingStrategyName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="BiddingStrategyName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string biddingStrategyName, bool allowUnparsed, out BiddingStrategyName result)
{
gax::GaxPreconditions.CheckNotNull(biddingStrategyName, nameof(biddingStrategyName));
gax::TemplatedResourceName resourceName;
if (s_customerBiddingStrategy.TryParseName(biddingStrategyName, out resourceName))
{
result = FromCustomerBiddingStrategy(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(biddingStrategyName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private BiddingStrategyName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string biddingStrategyId = null, string customerId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
BiddingStrategyId = biddingStrategyId;
CustomerId = customerId;
}
/// <summary>
/// Constructs a new instance of a <see cref="BiddingStrategyName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/biddingStrategies/{bidding_strategy_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="biddingStrategyId">The <c>BiddingStrategy</c> ID. Must not be <c>null</c> or empty.</param>
public BiddingStrategyName(string customerId, string biddingStrategyId) : this(ResourceNameType.CustomerBiddingStrategy, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), biddingStrategyId: gax::GaxPreconditions.CheckNotNullOrEmpty(biddingStrategyId, nameof(biddingStrategyId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>BiddingStrategy</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string BiddingStrategyId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerBiddingStrategy: return s_customerBiddingStrategy.Expand(CustomerId, BiddingStrategyId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as BiddingStrategyName);
/// <inheritdoc/>
public bool Equals(BiddingStrategyName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(BiddingStrategyName a, BiddingStrategyName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(BiddingStrategyName a, BiddingStrategyName b) => !(a == b);
}
public partial class BiddingStrategy
{
/// <summary>
/// <see cref="gagvr::BiddingStrategyName"/>-typed view over the <see cref="ResourceName"/> resource name
/// property.
/// </summary>
internal BiddingStrategyName ResourceNameAsBiddingStrategyName
{
get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::BiddingStrategyName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagvr::BiddingStrategyName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
internal BiddingStrategyName BiddingStrategyName
{
get => string.IsNullOrEmpty(Name) ? null : gagvr::BiddingStrategyName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: booking/rpc/ota_sync_svc.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace HOLMS.Types.Booking.RPC {
/// <summary>Holder for reflection information generated from booking/rpc/ota_sync_svc.proto</summary>
public static partial class OtaSyncSvcReflection {
#region Descriptor
/// <summary>File descriptor for booking/rpc/ota_sync_svc.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static OtaSyncSvcReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Ch5ib29raW5nL3JwYy9vdGFfc3luY19zdmMucHJvdG8SF2hvbG1zLnR5cGVz",
"LmJvb2tpbmcucnBjGhtnb29nbGUvcHJvdG9idWYvZW1wdHkucHJvdG8aH2dv",
"b2dsZS9wcm90b2J1Zi90aW1lc3RhbXAucHJvdG8iSAoRU2VydmVyVGFza0Rl",
"dGFpbHMSMwoPbGFzdF93b3JraW5nX2F0GAEgASgLMhouZ29vZ2xlLnByb3Rv",
"YnVmLlRpbWVzdGFtcCI7Ch1TY2hlZHVsZXJTdGFydEF0dGVtcHRSZXNwb25z",
"ZRIaChJJc1NjaGVkdWxlclN0YXJ0ZWQYASABKAgiPQoeUEJYU2VydmljZVN0",
"YXJ0QXR0ZW1wdFJlc3BvbnNlEhsKE0lzUEJYU2VydmljZVN0YXJ0ZWQYASAB",
"KAgyoAQKCk9UQVN5bmNTdmMSQgoQU3luY1Jlc2VydmF0aW9ucxIWLmdvb2ds",
"ZS5wcm90b2J1Zi5FbXB0eRoWLmdvb2dsZS5wcm90b2J1Zi5FbXB0eRJhChtH",
"ZXRTY2hlZHVsZXJMYXN0V29ya2luZ1RpbWUSFi5nb29nbGUucHJvdG9idWYu",
"RW1wdHkaKi5ob2xtcy50eXBlcy5ib29raW5nLnJwYy5TZXJ2ZXJUYXNrRGV0",
"YWlscxJnChVBdHRlbXB0U3RhcnRTY2hlZHVsZXISFi5nb29nbGUucHJvdG9i",
"dWYuRW1wdHkaNi5ob2xtcy50eXBlcy5ib29raW5nLnJwYy5TY2hlZHVsZXJT",
"dGFydEF0dGVtcHRSZXNwb25zZRJpChZBdHRlbXB0U3RhcnRQQlhTZXJ2aWNl",
"EhYuZ29vZ2xlLnByb3RvYnVmLkVtcHR5GjcuaG9sbXMudHlwZXMuYm9va2lu",
"Zy5ycGMuUEJYU2VydmljZVN0YXJ0QXR0ZW1wdFJlc3BvbnNlEk0KG1N5bmNQ",
"cmljZUZvck9jY3VwYW5jeUZhY3RvchIWLmdvb2dsZS5wcm90b2J1Zi5FbXB0",
"eRoWLmdvb2dsZS5wcm90b2J1Zi5FbXB0eRJIChZTeW5jUHJpY2VGb3JUaW1l",
"RmFjdG9yEhYuZ29vZ2xlLnByb3RvYnVmLkVtcHR5GhYuZ29vZ2xlLnByb3Rv",
"YnVmLkVtcHR5QhqqAhdIT0xNUy5UeXBlcy5Cb29raW5nLlJQQ2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.EmptyReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.RPC.ServerTaskDetails), global::HOLMS.Types.Booking.RPC.ServerTaskDetails.Parser, new[]{ "LastWorkingAt" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.RPC.SchedulerStartAttemptResponse), global::HOLMS.Types.Booking.RPC.SchedulerStartAttemptResponse.Parser, new[]{ "IsSchedulerStarted" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.RPC.PBXServiceStartAttemptResponse), global::HOLMS.Types.Booking.RPC.PBXServiceStartAttemptResponse.Parser, new[]{ "IsPBXServiceStarted" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class ServerTaskDetails : pb::IMessage<ServerTaskDetails> {
private static readonly pb::MessageParser<ServerTaskDetails> _parser = new pb::MessageParser<ServerTaskDetails>(() => new ServerTaskDetails());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ServerTaskDetails> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Booking.RPC.OtaSyncSvcReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ServerTaskDetails() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ServerTaskDetails(ServerTaskDetails other) : this() {
LastWorkingAt = other.lastWorkingAt_ != null ? other.LastWorkingAt.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ServerTaskDetails Clone() {
return new ServerTaskDetails(this);
}
/// <summary>Field number for the "last_working_at" field.</summary>
public const int LastWorkingAtFieldNumber = 1;
private global::Google.Protobuf.WellKnownTypes.Timestamp lastWorkingAt_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Timestamp LastWorkingAt {
get { return lastWorkingAt_; }
set {
lastWorkingAt_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ServerTaskDetails);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ServerTaskDetails other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(LastWorkingAt, other.LastWorkingAt)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (lastWorkingAt_ != null) hash ^= LastWorkingAt.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (lastWorkingAt_ != null) {
output.WriteRawTag(10);
output.WriteMessage(LastWorkingAt);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (lastWorkingAt_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(LastWorkingAt);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ServerTaskDetails other) {
if (other == null) {
return;
}
if (other.lastWorkingAt_ != null) {
if (lastWorkingAt_ == null) {
lastWorkingAt_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
LastWorkingAt.MergeFrom(other.LastWorkingAt);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (lastWorkingAt_ == null) {
lastWorkingAt_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(lastWorkingAt_);
break;
}
}
}
}
}
public sealed partial class SchedulerStartAttemptResponse : pb::IMessage<SchedulerStartAttemptResponse> {
private static readonly pb::MessageParser<SchedulerStartAttemptResponse> _parser = new pb::MessageParser<SchedulerStartAttemptResponse>(() => new SchedulerStartAttemptResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<SchedulerStartAttemptResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Booking.RPC.OtaSyncSvcReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public SchedulerStartAttemptResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public SchedulerStartAttemptResponse(SchedulerStartAttemptResponse other) : this() {
isSchedulerStarted_ = other.isSchedulerStarted_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public SchedulerStartAttemptResponse Clone() {
return new SchedulerStartAttemptResponse(this);
}
/// <summary>Field number for the "IsSchedulerStarted" field.</summary>
public const int IsSchedulerStartedFieldNumber = 1;
private bool isSchedulerStarted_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool IsSchedulerStarted {
get { return isSchedulerStarted_; }
set {
isSchedulerStarted_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as SchedulerStartAttemptResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(SchedulerStartAttemptResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (IsSchedulerStarted != other.IsSchedulerStarted) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (IsSchedulerStarted != false) hash ^= IsSchedulerStarted.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (IsSchedulerStarted != false) {
output.WriteRawTag(8);
output.WriteBool(IsSchedulerStarted);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (IsSchedulerStarted != false) {
size += 1 + 1;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(SchedulerStartAttemptResponse other) {
if (other == null) {
return;
}
if (other.IsSchedulerStarted != false) {
IsSchedulerStarted = other.IsSchedulerStarted;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
IsSchedulerStarted = input.ReadBool();
break;
}
}
}
}
}
public sealed partial class PBXServiceStartAttemptResponse : pb::IMessage<PBXServiceStartAttemptResponse> {
private static readonly pb::MessageParser<PBXServiceStartAttemptResponse> _parser = new pb::MessageParser<PBXServiceStartAttemptResponse>(() => new PBXServiceStartAttemptResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PBXServiceStartAttemptResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Booking.RPC.OtaSyncSvcReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PBXServiceStartAttemptResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PBXServiceStartAttemptResponse(PBXServiceStartAttemptResponse other) : this() {
isPBXServiceStarted_ = other.isPBXServiceStarted_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PBXServiceStartAttemptResponse Clone() {
return new PBXServiceStartAttemptResponse(this);
}
/// <summary>Field number for the "IsPBXServiceStarted" field.</summary>
public const int IsPBXServiceStartedFieldNumber = 1;
private bool isPBXServiceStarted_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool IsPBXServiceStarted {
get { return isPBXServiceStarted_; }
set {
isPBXServiceStarted_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PBXServiceStartAttemptResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PBXServiceStartAttemptResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (IsPBXServiceStarted != other.IsPBXServiceStarted) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (IsPBXServiceStarted != false) hash ^= IsPBXServiceStarted.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (IsPBXServiceStarted != false) {
output.WriteRawTag(8);
output.WriteBool(IsPBXServiceStarted);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (IsPBXServiceStarted != false) {
size += 1 + 1;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PBXServiceStartAttemptResponse other) {
if (other == null) {
return;
}
if (other.IsPBXServiceStarted != false) {
IsPBXServiceStarted = other.IsPBXServiceStarted;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
IsPBXServiceStarted = input.ReadBool();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
#if UNITY_EDITOR
//////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014 Audiokinetic Inc. / All Rights Reserved
//
//////////////////////////////////////////////////////////////////////
using UnityEngine;
using UnityEditor;
using System;
using System.Collections.Generic;
using AK.Wwise.TreeView;
public class AkWwiseComponentPicker : EditorWindow
{
static AkWwiseComponentPicker s_componentPicker = null;
AkWwiseTreeView m_treeView = new AkWwiseTreeView();
SerializedProperty[] m_selectedItemGuid;
SerializedObject m_serializedObject;
AkWwiseProjectData.WwiseObjectType m_type;
bool m_close = false;
static public void Create(AkWwiseProjectData.WwiseObjectType in_type, SerializedProperty[] in_guid, SerializedObject in_serializedObject, Rect in_pos)
{
if(s_componentPicker == null)
{
s_componentPicker = ScriptableObject.CreateInstance<AkWwiseComponentPicker> ();
//position the window below the button
Rect pos = new Rect (in_pos.x, in_pos.yMax, 0, 0);
//If the window gets out of the screen, we place it on top of the button instead
if(in_pos.yMax > (Screen.currentResolution.height / 2))
{
pos.y = in_pos.y - (Screen.currentResolution.height / 2);
}
//We show a drop down window which is automatically destroyed when focus is lost
s_componentPicker.ShowAsDropDown(pos, new Vector2 (in_pos.width >= 250 ? in_pos.width : 250, Screen.currentResolution.height / 2));
s_componentPicker.m_selectedItemGuid = in_guid;
s_componentPicker.m_serializedObject = in_serializedObject;
s_componentPicker.m_type = in_type;
//Make a backup of the tree's expansion status and replace it with an empty list to make sure nothing will get expanded
//when we populate the tree
List<string> expandedItemsBackUp = AkWwiseProjectInfo.GetData ().ExpandedItems;
AkWwiseProjectInfo.GetData ().ExpandedItems = new List<string> ();
s_componentPicker.m_treeView.AssignDefaults();
s_componentPicker.m_treeView.SetRootItem(System.IO.Path.GetFileNameWithoutExtension(WwiseSetupWizard.Settings.WwiseProjectPath), AkWwiseProjectData.WwiseObjectType.PROJECT);
//Populate the tree with the correct type
if(in_type == AkWwiseProjectData.WwiseObjectType.EVENT)
{
s_componentPicker.m_treeView.PopulateItem(s_componentPicker.m_treeView.RootItem, "Events", AkWwiseProjectInfo.GetData().EventWwu);
}
else if(in_type == AkWwiseProjectData.WwiseObjectType.SWITCH)
{
s_componentPicker.m_treeView.PopulateItem(s_componentPicker.m_treeView.RootItem, "Switches", AkWwiseProjectInfo.GetData().SwitchWwu);
}
else if(in_type == AkWwiseProjectData.WwiseObjectType.STATE)
{
s_componentPicker.m_treeView.PopulateItem(s_componentPicker.m_treeView.RootItem, "States", AkWwiseProjectInfo.GetData().StateWwu);
}
else if(in_type == AkWwiseProjectData.WwiseObjectType.SOUNDBANK)
{
s_componentPicker.m_treeView.PopulateItem(s_componentPicker.m_treeView.RootItem, "Banks", AkWwiseProjectInfo.GetData().BankWwu);
}
else if(in_type == AkWwiseProjectData.WwiseObjectType.AUXBUS)
{
s_componentPicker.m_treeView.PopulateItem(s_componentPicker.m_treeView.RootItem, "Auxiliary Busses", AkWwiseProjectInfo.GetData().AuxBusWwu);
}
else if (in_type == AkWwiseProjectData.WwiseObjectType.GAMEPARAMETER)
{
s_componentPicker.m_treeView.PopulateItem(s_componentPicker.m_treeView.RootItem, "Game Parameters", AkWwiseProjectInfo.GetData().RtpcWwu);
}
else if (in_type == AkWwiseProjectData.WwiseObjectType.TRIGGER)
{
s_componentPicker.m_treeView.PopulateItem(s_componentPicker.m_treeView.RootItem, "Triggers", AkWwiseProjectInfo.GetData().TriggerWwu);
}
TreeViewItem item = null;
byte[] byteArray = AkUtilities.GetByteArrayProperty(in_guid[0]);
if (byteArray != null)
item = s_componentPicker.m_treeView.GetItemByGuid(new Guid(byteArray));
if(item != null)
{
item.ParentControl.SelectedItem = item;
int itemIndexFromRoot = 0;
//Expand all the parents of the selected item.
//Count the number of items that are displayed before the selected item
while(true)
{
item.IsExpanded = true;
if(item.Parent != null)
{
itemIndexFromRoot += item.Parent.Items.IndexOf(item) + 1;
item = item.Parent;
}
else
{
break;
}
}
//Scroll down the window to make sure that the selected item is always visible when the window opens
float itemHeight = item.ParentControl.m_skinSelected.button.CalcSize(new GUIContent(item.Header)).y + 2.0f; //there seems to be 1 pixel between each item so we add 2 pixels(top and bottom)
s_componentPicker.m_treeView.SetScrollViewPosition(new Vector2(0.0f, (itemHeight*itemIndexFromRoot)-(Screen.currentResolution.height / 4)));
}
//Restore the tree's expansion status
AkWwiseProjectInfo.GetData ().ExpandedItems = expandedItemsBackUp;
}
}
public void OnGUI()
{
GUILayout.BeginVertical ();
{
m_treeView.DisplayTreeView(TreeViewControl.DisplayTypes.USE_SCROLL_VIEW);
EditorGUILayout.BeginHorizontal("Box");
{
if(GUILayout.Button("Ok"))
{
//Get the selected item
TreeViewItem selectedItem = m_treeView.GetSelectedItem();
//Check if the selected item has the correct type
if(selectedItem != null && m_type == (selectedItem.DataContext as AkWwiseTreeView.AkTreeInfo).ObjectType)
{
SetGuid(selectedItem);
}
//The window can now be closed
m_close = true;
}
else if(GUILayout.Button("Cancel"))
{
m_close = true;
}
else if (GUILayout.Button("Reset"))
{
ResetGuid();
m_close = true;
}
//We must be in 'used' mode in order for this to work
else if(Event.current.type == EventType.used && m_treeView.LastDoubleClickedItem != null && m_type == (m_treeView.LastDoubleClickedItem.DataContext as AkWwiseTreeView.AkTreeInfo).ObjectType)
{
SetGuid(m_treeView.LastDoubleClickedItem);
m_close = true;
}
}
EditorGUILayout.EndHorizontal ();
}
EditorGUILayout.EndVertical ();
}
void SetGuid(TreeViewItem in_item)
{
m_serializedObject.Update();
//we set the items guid
AkUtilities.SetByteArrayProperty(m_selectedItemGuid[0], (in_item.DataContext as AkWwiseTreeView.AkTreeInfo).Guid);
//When its a State or a Switch, we set the group's guid
if(m_selectedItemGuid.Length == 2)
{
AkUtilities.SetByteArrayProperty(m_selectedItemGuid[1], (in_item.Parent.DataContext as AkWwiseTreeView.AkTreeInfo).Guid);
}
m_serializedObject.ApplyModifiedProperties();
}
void ResetGuid()
{
m_serializedObject.Update();
byte[] emptyArray = new byte[16];
//we set the items guid
AkUtilities.SetByteArrayProperty(m_selectedItemGuid[0], emptyArray);
//When its a State or a Switch, we set the group's guid
if (m_selectedItemGuid.Length == 2)
{
AkUtilities.SetByteArrayProperty(m_selectedItemGuid[1], emptyArray);
}
m_serializedObject.ApplyModifiedProperties();
}
public void Update()
{
//Unity sometimes generates an error when the window is closed from the OnGUI function.
//So We close it here
if(m_close)
Close();
}
}
#endif
| |
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using CommandLine;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V10.Errors;
using Google.Ads.GoogleAds.V10.Resources;
using Google.Ads.GoogleAds.V10.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using static Google.Ads.GoogleAds.V10.Enums.FeedAttributeTypeEnum.Types;
using static Google.Ads.GoogleAds.V10.Enums.FlightPlaceholderFieldEnum.Types;
using static Google.Ads.GoogleAds.V10.Enums.PlaceholderTypeEnum.Types;
namespace Google.Ads.GoogleAds.Examples.V10
{
/// <summary>
/// This code example adds a flights feed, creates the associated feed mapping, and
/// adds a feed item. To update feeds, see UpdateFeedItemAttributeValue.cs.
/// </summary>
public class AddFlightsFeed : ExampleBase
{
/// <summary>
/// Command line options for running the <see cref="AddFlightsFeed"/> example.
/// </summary>
public class Options : OptionsBase
{
/// <summary>
/// The Google Ads customer ID to which the flights feed is added.
/// </summary>
[Option("customerId", Required = true, HelpText =
"The Google Ads customer ID to which the flights feed is added.")]
public long CustomerId { get; set; }
}
/// <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)
{
Options options = new Options();
CommandLine.Parser.Default.ParseArguments<Options>(args).MapResult(
delegate (Options o)
{
options = o;
return 0;
}, delegate (IEnumerable<Error> errors)
{
// The Google Ads customer ID to which the flights feed is added.
options.CustomerId = long.Parse("INSERT_CUSTOMER_ID_HERE");
return 0;
});
AddFlightsFeed codeExample = new AddFlightsFeed();
Console.WriteLine(codeExample.Description);
codeExample.Run(new GoogleAdsClient(), options.CustomerId);
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description =>
"This code example adds a flights feed, creates the associated feed mapping, and " +
"adds a feed item. To update feeds, see UpdateFeedItemAttributeValue.cs.";
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID to which the flights feed is
/// added.</param>
public void Run(GoogleAdsClient client, long customerId)
{
try
{
// Creates a new flights feed.
string feedResourceName = CreateFeed(client, customerId);
// Get the newly creates feed's attributes and packages them into a map. This read
// operation is required to retrieve the attribute IDs.
Dictionary<FlightPlaceholderField, FeedAttribute> feedAttributes =
GetFeed(client, customerId, feedResourceName);
// Creates the feed mapping.
CreateFeedMapping(client, customerId, feedAttributes, feedResourceName);
// Creates a feed item.
CreateFeedItem(client, customerId, feedAttributes, feedResourceName);
}
catch (GoogleAdsException e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
Console.WriteLine($"Failure: {e.Failure}");
Console.WriteLine($"Request ID: {e.RequestId}");
throw;
}
}
/// <summary>
/// Creates the feed.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID for which the flights feed is
/// added.</param>
/// <returns>Resource name of the newly created feed.</returns>
private string CreateFeed(GoogleAdsClient client, long customerId)
{
// Get the FeedService.
FeedServiceClient feedService = client.GetService(Services.V10.FeedService);
// Creates a Flight Description attribute.
FeedAttribute flightDescriptionAttribute = new FeedAttribute()
{
Type = FeedAttributeType.String,
Name = "Flight Description"
};
// Creates a Destination ID attribute.
FeedAttribute destinationIdAttribute = new FeedAttribute()
{
Type = FeedAttributeType.String,
Name = "Destination ID"
};
// Creates a Flight Price attribute.
FeedAttribute flightPriceAttribute = new FeedAttribute()
{
Type = FeedAttributeType.String,
Name = "Flight Price"
};
// Creates a Flight Sale Price attribute.
FeedAttribute flightSalesPriceAttribute = new FeedAttribute()
{
Type = FeedAttributeType.String,
Name = "Flight Sale Price"
};
// Creates a Final URLs attribute.
FeedAttribute finalUrlsAttribute = new FeedAttribute()
{
Type = FeedAttributeType.UrlList,
Name = "Final URLs"
};
// Creates the feed.
Feed feed = new Feed()
{
Name = "Flights Feed #" + ExampleUtilities.GetRandomString(),
Attributes =
{
flightDescriptionAttribute,
destinationIdAttribute,
flightPriceAttribute,
flightSalesPriceAttribute,
finalUrlsAttribute
}
};
// Creates the operation.
FeedOperation operation = new FeedOperation()
{
Create = feed
};
// Adds the feed.
MutateFeedsResponse response =
feedService.MutateFeeds(customerId.ToString(), new[] { operation });
string feedResourceName = response.Results[0].ResourceName;
// Displays the result.
Console.WriteLine($"Feed with resource name '{feedResourceName}' was created.");
return feedResourceName;
}
/// <summary>
/// Retrieves details about a feed. The initial query retrieves the FeedAttributes,
/// or columns, of the feed. Each FeedAttribute will also include the FeedAttributeId,
/// which will be used in a subsequent step. The example then inserts a new key, value
/// pair into a map for each FeedAttribute, which is the return value of the method.
/// The keys are the placeholder types that the columns will be. The values are the
/// FeedAttributes.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID for which the flights feed is
/// added.</param>
/// <param name="feedResourceName">The resource name of the feed.</param>
/// <returns>
/// A Map containing the FlightPlaceholderField and FeedAttribute.
/// </returns>
public Dictionary<FlightPlaceholderField, FeedAttribute> GetFeed(
GoogleAdsClient client, long customerId, string feedResourceName)
{
// Get the GoogleAdsService.
GoogleAdsServiceClient googleAdsService = client.GetService(
Services.V10.GoogleAdsService);
// Constructs the query.
string query = $"SELECT feed.attributes FROM feed WHERE feed.resource_name = " +
$"'{feedResourceName}'";
// Constructs the request.
SearchGoogleAdsRequest request = new SearchGoogleAdsRequest()
{
CustomerId = customerId.ToString(),
Query = query
};
// Issues the search request and get the first result, since we only need the
// single feed item we created previously.
GoogleAdsRow googleAdsRow = googleAdsService.Search(request).First();
// Gets the attributes list from the feed and creates a map with keys of each attribute and
// values of each corresponding ID.
Dictionary<FlightPlaceholderField, FeedAttribute> feedAttributes =
new Dictionary<FlightPlaceholderField, FeedAttribute>();
// Loops through the feed attributes to populate the map.
foreach (FeedAttribute feedAttribute in googleAdsRow.Feed.Attributes)
{
switch (feedAttribute.Name)
{
case "Flight Description":
feedAttributes[FlightPlaceholderField.FlightDescription] = feedAttribute;
break;
case "Destination ID":
feedAttributes[FlightPlaceholderField.DestinationId] = feedAttribute;
break;
case "Flight Price":
feedAttributes[FlightPlaceholderField.FlightPrice] = feedAttribute;
break;
case "Flight Sale Price":
feedAttributes[FlightPlaceholderField.FlightSalePrice] = feedAttribute;
break;
case "Final URLs":
feedAttributes[FlightPlaceholderField.FinalUrls] = feedAttribute;
break;
// The full list of FlightPlaceholderFields can be found here
// https://developers.google.com/google-ads/api/reference/rpc/latest/FlightPlaceholderFieldEnum.FlightPlaceholderField
default:
throw new Exception("Invalid attribute name.");
}
}
return feedAttributes;
}
/// <summary>
/// Creates a feed mapping for a given feed.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID for which the flights feed is
/// added.</param>
/// <param name="feedAttributes">The feed attributes.</param>
/// <param name="feedResourceName">The resource name of the feed.</param>
private void CreateFeedMapping(GoogleAdsClient client, long customerId,
Dictionary<FlightPlaceholderField, FeedAttribute> feedAttributes,
string feedResourceName)
{
// Get the FeedMappingServiceClient.
FeedMappingServiceClient feedMappingService = client.GetService(
Services.V10.FeedMappingService);
// Maps the FeedAttributeIds to the fieldId constants.
AttributeFieldMapping flightDescriptionMapping = new AttributeFieldMapping()
{
FeedAttributeId = feedAttributes[FlightPlaceholderField.FlightDescription].Id,
FlightField = FlightPlaceholderField.FlightDescription
};
AttributeFieldMapping destinationIdMapping = new AttributeFieldMapping()
{
FeedAttributeId = feedAttributes[FlightPlaceholderField.DestinationId].Id,
FlightField = FlightPlaceholderField.DestinationId
};
AttributeFieldMapping flightPriceMapping = new AttributeFieldMapping()
{
FeedAttributeId = feedAttributes[FlightPlaceholderField.FlightPrice].Id,
FlightField = FlightPlaceholderField.FlightPrice
};
AttributeFieldMapping flightSalePriceMapping = new AttributeFieldMapping()
{
FeedAttributeId = feedAttributes[FlightPlaceholderField.FlightSalePrice].Id,
FlightField = FlightPlaceholderField.FlightSalePrice
};
AttributeFieldMapping finalUrlsMapping = new AttributeFieldMapping()
{
FeedAttributeId = feedAttributes[FlightPlaceholderField.FinalUrls].Id,
FlightField = FlightPlaceholderField.FinalUrls
};
// Creates the feed mapping.
FeedMapping feedMapping = new FeedMapping()
{
PlaceholderType = PlaceholderType.DynamicFlight,
Feed = feedResourceName,
AttributeFieldMappings =
{
flightDescriptionMapping,
destinationIdMapping,
flightPriceMapping,
flightSalePriceMapping,
finalUrlsMapping
}
};
// Creates the operation.
FeedMappingOperation operation = new FeedMappingOperation()
{
Create = feedMapping
};
// Adds the FeedMapping.
MutateFeedMappingsResponse response = feedMappingService.MutateFeedMappings(
customerId.ToString(), new[] { operation });
// Displays the results.
foreach (MutateFeedMappingResult result in response.Results)
{
Console.WriteLine($"Created feed mapping with resource name" +
$" '{result.ResourceName}'.");
}
}
/// <summary>
/// Adds a new item to the feed.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID for which the flights feed is
/// added.</param>
/// <param name="feedAttributes">The feed attributes.</param>
/// <param name="feedResourceName">The resource name of the feed.</param>
private void CreateFeedItem(GoogleAdsClient client, long customerId,
Dictionary<FlightPlaceholderField, FeedAttribute> feedAttributes,
string feedResourceName)
{
// Get the FeedItemServiceClient.
FeedItemServiceClient feedItemService = client.GetService(
Services.V10.FeedItemService);
// Creates the flight description feed attribute value.
FeedItemAttributeValue flightDescription = new FeedItemAttributeValue()
{
FeedAttributeId = feedAttributes[FlightPlaceholderField.FlightDescription].Id,
StringValue = "Earth to Mars"
};
// Creates the destination ID feed attribute value.
FeedItemAttributeValue destinationId = new FeedItemAttributeValue()
{
FeedAttributeId = feedAttributes[FlightPlaceholderField.DestinationId].Id,
StringValue = "Mars"
};
// Creates the flight price feed attribute value.
FeedItemAttributeValue flightPrice = new FeedItemAttributeValue()
{
FeedAttributeId = feedAttributes[FlightPlaceholderField.FlightPrice].Id,
StringValue = "499.99 USD"
};
// Creates the flight sale price feed attribute value.
FeedItemAttributeValue flightSalePrice = new FeedItemAttributeValue()
{
FeedAttributeId = feedAttributes[FlightPlaceholderField.FlightSalePrice].Id,
StringValue = "299.99 USD"
};
// Creates the final URLs feed attribute value.
FeedItemAttributeValue finalUrls = new FeedItemAttributeValue()
{
FeedAttributeId = feedAttributes[FlightPlaceholderField.FinalUrls].Id,
StringValues = { "http://www.example.com/flights/" }
};
// Creates the FeedItem, specifying the Feed ID and the attributes created above.
FeedItem feedItem = new FeedItem()
{
Feed = feedResourceName,
AttributeValues =
{
flightDescription,
destinationId,
flightPrice,
flightSalePrice,
finalUrls
}
};
// Creates an operation to add the FeedItem.
FeedItemOperation operation = new FeedItemOperation()
{
Create = feedItem
};
// Adds the feed item.
MutateFeedItemsResponse response =
feedItemService.MutateFeedItems(customerId.ToString(),
new FeedItemOperation[] { operation });
foreach (MutateFeedItemResult result in response.Results)
{
Console.WriteLine($"Created feed item with resource name '{result.ResourceName}'.");
}
}
}
}
| |
using Kitware.VTK;
using System;
// input file is C:\VTK\Graphics\Testing\Tcl\combStreamers.tcl
// output file is AVcombStreamers.cs
/// <summary>
/// The testing class derived from AVcombStreamers
/// </summary>
public class AVcombStreamersClass
{
/// <summary>
/// The main entry method called by the CSharp driver
/// </summary>
/// <param name="argv"></param>
public static void AVcombStreamers(String [] argv)
{
//Prefix Content is: ""
// Create the RenderWindow, Renderer and both Actors[]
//[]
ren1 = vtkRenderer.New();
renWin = vtkRenderWindow.New();
renWin.AddRenderer((vtkRenderer)ren1);
iren = new vtkRenderWindowInteractor();
iren.SetRenderWindow((vtkRenderWindow)renWin);
// create pipeline[]
//[]
pl3d = new vtkMultiBlockPLOT3DReader();
pl3d.SetXYZFileName((string)"" + (VTK_DATA_ROOT.ToString()) + "/Data/combxyz.bin");
pl3d.SetQFileName((string)"" + (VTK_DATA_ROOT.ToString()) + "/Data/combq.bin");
pl3d.SetScalarFunctionNumber((int)100);
pl3d.SetVectorFunctionNumber((int)202);
pl3d.Update();
ps = new vtkPlaneSource();
ps.SetXResolution((int)4);
ps.SetYResolution((int)4);
ps.SetOrigin((double)2,(double)-2,(double)26);
ps.SetPoint1((double)2,(double)2,(double)26);
ps.SetPoint2((double)2,(double)-2,(double)32);
psMapper = vtkPolyDataMapper.New();
psMapper.SetInputConnection((vtkAlgorithmOutput)ps.GetOutputPort());
psActor = new vtkActor();
psActor.SetMapper((vtkMapper)psMapper);
psActor.GetProperty().SetRepresentationToWireframe();
rk4 = new vtkRungeKutta4();
streamer = new vtkStreamLine();
streamer.SetInputData((vtkDataSet)pl3d.GetOutput().GetBlock(0));
streamer.SetSourceConnection(ps.GetOutputPort());
streamer.SetMaximumPropagationTime((double)100);
streamer.SetIntegrationStepLength((double).2);
streamer.SetStepLength((double).001);
streamer.SetNumberOfThreads((int)1);
streamer.SetIntegrationDirectionToForward();
streamer.VorticityOn();
streamer.SetIntegrator((vtkInitialValueProblemSolver)rk4);
rf = new vtkRibbonFilter();
rf.SetInputConnection((vtkAlgorithmOutput)streamer.GetOutputPort());
rf.SetWidth((double)0.1);
rf.SetWidthFactor((double)5);
streamMapper = vtkPolyDataMapper.New();
streamMapper.SetInputConnection((vtkAlgorithmOutput)rf.GetOutputPort());
streamMapper.SetScalarRange(
(double)((vtkDataSet)pl3d.GetOutput().GetBlock(0)).GetScalarRange()[0],
(double)((vtkDataSet)pl3d.GetOutput().GetBlock(0)).GetScalarRange()[1]);
streamline = new vtkActor();
streamline.SetMapper((vtkMapper)streamMapper);
outline = new vtkStructuredGridOutlineFilter();
outline.SetInputData((vtkDataSet)pl3d.GetOutput().GetBlock(0));
outlineMapper = vtkPolyDataMapper.New();
outlineMapper.SetInputConnection((vtkAlgorithmOutput)outline.GetOutputPort());
outlineActor = new vtkActor();
outlineActor.SetMapper((vtkMapper)outlineMapper);
// Add the actors to the renderer, set the background and size[]
//[]
ren1.AddActor((vtkProp)psActor);
ren1.AddActor((vtkProp)outlineActor);
ren1.AddActor((vtkProp)streamline);
ren1.SetBackground((double)1,(double)1,(double)1);
renWin.SetSize((int)300,(int)300);
ren1.SetBackground((double)0.1,(double)0.2,(double)0.4);
cam1 = ren1.GetActiveCamera();
cam1.SetClippingRange((double)3.95297,(double)50);
cam1.SetFocalPoint((double)9.71821,(double)0.458166,(double)29.3999);
cam1.SetPosition((double)2.7439,(double)-37.3196,(double)38.7167);
cam1.SetViewUp((double)-0.16123,(double)0.264271,(double)0.950876);
// render the image[]
//[]
renWin.Render();
// prevent the tk window from showing up then start the event loop[]
// for testing[]
threshold = 15;
//deleteAllVTKObjects();
}
static string VTK_DATA_ROOT;
static int threshold;
static vtkRenderer ren1;
static vtkRenderWindow renWin;
static vtkRenderWindowInteractor iren;
static vtkMultiBlockPLOT3DReader pl3d;
static vtkPlaneSource ps;
static vtkPolyDataMapper psMapper;
static vtkActor psActor;
static vtkRungeKutta4 rk4;
static vtkStreamLine streamer;
static vtkRibbonFilter rf;
static vtkPolyDataMapper streamMapper;
static vtkActor streamline;
static vtkStructuredGridOutlineFilter outline;
static vtkPolyDataMapper outlineMapper;
static vtkActor outlineActor;
static vtkCamera cam1;
///<summary> A Get Method for Static Variables </summary>
public static string GetVTK_DATA_ROOT()
{
return VTK_DATA_ROOT;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetVTK_DATA_ROOT(string toSet)
{
VTK_DATA_ROOT = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static int Getthreshold()
{
return threshold;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setthreshold(int toSet)
{
threshold = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderer Getren1()
{
return ren1;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setren1(vtkRenderer toSet)
{
ren1 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindow GetrenWin()
{
return renWin;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetrenWin(vtkRenderWindow toSet)
{
renWin = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindowInteractor Getiren()
{
return iren;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setiren(vtkRenderWindowInteractor toSet)
{
iren = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkMultiBlockPLOT3DReader Getpl3d()
{
return pl3d;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setpl3d(vtkMultiBlockPLOT3DReader toSet)
{
pl3d = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPlaneSource Getps()
{
return ps;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setps(vtkPlaneSource toSet)
{
ps = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper GetpsMapper()
{
return psMapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetpsMapper(vtkPolyDataMapper toSet)
{
psMapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetpsActor()
{
return psActor;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetpsActor(vtkActor toSet)
{
psActor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRungeKutta4 Getrk4()
{
return rk4;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setrk4(vtkRungeKutta4 toSet)
{
rk4 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkStreamLine Getstreamer()
{
return streamer;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setstreamer(vtkStreamLine toSet)
{
streamer = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRibbonFilter Getrf()
{
return rf;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setrf(vtkRibbonFilter toSet)
{
rf = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper GetstreamMapper()
{
return streamMapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetstreamMapper(vtkPolyDataMapper toSet)
{
streamMapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor Getstreamline()
{
return streamline;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setstreamline(vtkActor toSet)
{
streamline = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkStructuredGridOutlineFilter Getoutline()
{
return outline;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setoutline(vtkStructuredGridOutlineFilter toSet)
{
outline = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper GetoutlineMapper()
{
return outlineMapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetoutlineMapper(vtkPolyDataMapper toSet)
{
outlineMapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetoutlineActor()
{
return outlineActor;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetoutlineActor(vtkActor toSet)
{
outlineActor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkCamera Getcam1()
{
return cam1;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setcam1(vtkCamera toSet)
{
cam1 = toSet;
}
///<summary>Deletes all static objects created</summary>
public static void deleteAllVTKObjects()
{
//clean up vtk objects
if(ren1!= null){ren1.Dispose();}
if(renWin!= null){renWin.Dispose();}
if(iren!= null){iren.Dispose();}
if(pl3d!= null){pl3d.Dispose();}
if(ps!= null){ps.Dispose();}
if(psMapper!= null){psMapper.Dispose();}
if(psActor!= null){psActor.Dispose();}
if(rk4!= null){rk4.Dispose();}
if(streamer!= null){streamer.Dispose();}
if(rf!= null){rf.Dispose();}
if(streamMapper!= null){streamMapper.Dispose();}
if(streamline!= null){streamline.Dispose();}
if(outline!= null){outline.Dispose();}
if(outlineMapper!= null){outlineMapper.Dispose();}
if(outlineActor!= null){outlineActor.Dispose();}
if(cam1!= null){cam1.Dispose();}
}
}
//--- end of script --//
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace UMA
{
/// <summary>
/// Default mesh combiner for UMA UMAMeshdata from slots.
/// </summary>
public class UMADefaultMeshCombiner : UMAMeshCombiner
{
protected List<SkinnedMeshCombiner.CombineInstance> combinedMeshList;
protected List<UMAData.GeneratedMaterial> combinedMaterialList;
UMAData umaData;
int atlasResolution;
private UMAClothProperties clothProperties;
int currentRendererIndex;
SkinnedMeshRenderer[] renderers;
protected void EnsureUMADataSetup(UMAData umaData)
{
if (umaData.umaRecipe != null)
{
umaData.umaRecipe.UpdateMeshHideMasks();
}
#region SetupSkeleton
// First, ensure that the skeleton is setup, and if not,
// then generate the root, global and set it up.
if (umaData.umaRoot == null)
{
umaData.SetupSkeleton();
}
#endregion
if (umaData.umaRoot != null)
{
umaData.CleanMesh(false);
if (umaData.rendererCount == umaData.generatedMaterials.rendererAssets.Count && umaData.AreRenderersEqual(umaData.generatedMaterials.rendererAssets))
{
renderers = umaData.GetRenderers();
}
else
{
var oldRenderers = umaData.GetRenderers();
var globalTransform = umaData.GetGlobalTransform();
renderers = new SkinnedMeshRenderer[umaData.generatedMaterials.rendererAssets.Count];
for (int i = 0; i < umaData.generatedMaterials.rendererAssets.Count; i++)
{
if (oldRenderers != null && oldRenderers.Length > i)
{
renderers[i] = oldRenderers[i];
if (umaData.generatedMaterials.rendererAssets[i] != null)
umaData.generatedMaterials.rendererAssets[i].ApplySettingsToRenderer(renderers[i]);
else
umaData.ResetRendererSettings(i);
continue;
}
UMARendererAsset rendererAsset = umaData.generatedMaterials.rendererAssets[i];
if (rendererAsset == null)
rendererAsset = umaData.defaultRendererAsset;
renderers[i] = MakeRenderer(i, globalTransform, rendererAsset);
}
if (oldRenderers != null)
{
for (int i = umaData.generatedMaterials.rendererAssets.Count; i < oldRenderers.Length; i++)
{
DestroyImmediate(oldRenderers[i].gameObject);
//For cloth, be aware of issue: 845868
//https://issuetracker.unity3d.com/issues/cloth-repeatedly-destroying-objects-with-cloth-components-causes-a-crash-in-unity-cloth-updatenormals
}
}
umaData.SetRenderers(renderers);
umaData.SetRendererAssets(umaData.generatedMaterials.rendererAssets.ToArray());
}
return;
}
//Clear out old cloth components
for (int i = 0; i < umaData.rendererCount; i++)
{
Cloth cloth = renderers[i].GetComponent<Cloth>();
if (cloth != null)
DestroyImmediate(cloth,false); //Crashes if trying to use Destroy()
}
}
private SkinnedMeshRenderer MakeRenderer(int i, Transform rootBone, UMARendererAsset rendererAsset = null)
{
GameObject newSMRGO = new GameObject(i == 0 ? "UMARenderer" : ("UMARenderer " + i));
newSMRGO.transform.parent = umaData.transform;
newSMRGO.transform.localPosition = Vector3.zero;
newSMRGO.transform.localRotation = Quaternion.Euler(0, 0, 0f);
newSMRGO.transform.localScale = Vector3.one;
newSMRGO.gameObject.layer = umaData.gameObject.layer;
var newRenderer = newSMRGO.AddComponent<SkinnedMeshRenderer>();
newRenderer.enabled = false;
newRenderer.sharedMesh = new Mesh();
#if UMA_32BITBUFFERS
newRenderer.sharedMesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;
#endif
newRenderer.rootBone = rootBone;
newRenderer.quality = SkinQuality.Auto;
newRenderer.sharedMesh.name = i == 0 ? "UMAMesh" : ("UMAMesh " + i);
if(rendererAsset != null)
{
rendererAsset.ApplySettingsToRenderer(newRenderer);
}
return newRenderer;
}
/// <summary>
/// Updates the UMA mesh and skeleton to match current slots.
/// </summary>
/// <param name="updatedAtlas">If set to <c>true</c> atlas has changed.</param>
/// <param name="umaData">UMA data.</param>
/// <param name="atlasResolution">Atlas resolution.</param>
public override void UpdateUMAMesh(bool updatedAtlas, UMAData umaData, int atlasResolution)
{
this.umaData = umaData;
this.atlasResolution = atlasResolution;
combinedMeshList = new List<SkinnedMeshCombiner.CombineInstance>(umaData.umaRecipe.slotDataList.Length);
combinedMaterialList = new List<UMAData.GeneratedMaterial>();
EnsureUMADataSetup(umaData);
umaData.skeleton.BeginSkeletonUpdate();
for (currentRendererIndex = 0; currentRendererIndex < umaData.generatedMaterials.rendererAssets.Count; currentRendererIndex++)
{
//Move umaMesh creation to with in the renderer loops
//May want to make sure to set all it's buffers to null instead of creating a new UMAMeshData
combinedMeshList.Clear();
combinedMaterialList.Clear();
clothProperties = null;
BuildCombineInstances();
if (combinedMeshList.Count == 1)
{
// fast track
var tempMesh = SkinnedMeshCombiner.ShallowInstanceMesh(combinedMeshList[0].meshData, combinedMeshList[0].triangleMask );
tempMesh.ApplyDataToUnityMesh(renderers[currentRendererIndex], umaData.skeleton);
}
else
{
UMAMeshData umaMesh = new UMAMeshData();
umaMesh.ClaimSharedBuffers();
umaMesh.subMeshCount = 0;
umaMesh.vertexCount = 0;
SkinnedMeshCombiner.CombineMeshes(umaMesh, combinedMeshList.ToArray(), umaData.blendShapeSettings );
if (updatedAtlas)
{
RecalculateUV(umaMesh);
}
umaMesh.ApplyDataToUnityMesh(renderers[currentRendererIndex], umaData.skeleton);
umaMesh.ReleaseSharedBuffers();
}
var cloth = renderers[currentRendererIndex].GetComponent<Cloth>();
if (clothProperties != null)
{
if (cloth != null)
{
clothProperties.ApplyValues(cloth);
}
}
else
{
UMAUtils.DestroySceneObject(cloth);
}
Material[] materials = new Material[combinedMaterialList.Count];
for(int i=0;i<combinedMaterialList.Count;i++)
{
materials[i] = combinedMaterialList[i].material;
combinedMaterialList[i].skinnedMeshRenderer = renderers[currentRendererIndex];
}
renderers[currentRendererIndex].sharedMaterials = materials;
}
umaData.umaRecipe.ClearDNAConverters();
for (int i = 0; i < umaData.umaRecipe.slotDataList.Length; i++)
{
SlotData slotData = umaData.umaRecipe.slotDataList[i];
if (slotData != null)
{
umaData.umaRecipe.AddDNAUpdater(slotData.asset.slotDNA);
}
}
umaData.firstBake = false;
}
protected void BuildCombineInstances()
{
SkinnedMeshCombiner.CombineInstance combineInstance;
//Since BuildCombineInstances is called within a renderer loop, use a variable to keep track of the materialIndex per renderer
int rendererMaterialIndex = 0;
for (int materialIndex = 0; materialIndex < umaData.generatedMaterials.materials.Count; materialIndex++)
{
UMARendererAsset rendererAsset = umaData.GetRendererAsset(currentRendererIndex);
var generatedMaterial = umaData.generatedMaterials.materials[materialIndex];
if (generatedMaterial.rendererAsset != rendererAsset)
continue;
combinedMaterialList.Add(generatedMaterial);
generatedMaterial.materialIndex = materialIndex;
for (int materialDefinitionIndex = 0; materialDefinitionIndex < generatedMaterial.materialFragments.Count; materialDefinitionIndex++)
{
var materialDefinition = generatedMaterial.materialFragments[materialDefinitionIndex];
var slotData = materialDefinition.slotData;
combineInstance = new SkinnedMeshCombiner.CombineInstance();
combineInstance.meshData = slotData.asset.meshData;
//New MeshHiding
if (slotData.meshHideMask != null)
combineInstance.triangleMask = slotData.meshHideMask;
combineInstance.targetSubmeshIndices = new int[combineInstance.meshData.subMeshCount];
for (int i = 0; i < combineInstance.meshData.subMeshCount; i++)
{
combineInstance.targetSubmeshIndices[i] = -1;
}
combineInstance.targetSubmeshIndices[slotData.asset.subMeshIndex] = rendererMaterialIndex;
combinedMeshList.Add(combineInstance);
if (slotData.asset.SlotAtlassed != null)
{
slotData.asset.SlotAtlassed.Invoke(umaData, slotData, generatedMaterial.material, materialDefinition.atlasRegion);
}
if (rendererAsset != null && rendererAsset.ClothProperties != null)
{
clothProperties = rendererAsset.ClothProperties;
}
}
rendererMaterialIndex++;
}
}
protected void RecalculateUV(UMAMeshData umaMesh)
{
int idx = 0;
//Handle Atlassed Verts
for (int materialIndex = 0; materialIndex < umaData.generatedMaterials.materials.Count; materialIndex++)
{
var generatedMaterial = umaData.generatedMaterials.materials[materialIndex];
if (generatedMaterial.rendererAsset != umaData.GetRendererAsset(currentRendererIndex))
continue;
if (generatedMaterial.umaMaterial.materialType != UMAMaterial.MaterialType.Atlas)
{
foreach (var fragment in generatedMaterial.materialFragments)
{
int vertexCount = fragment.slotData.asset.meshData.vertices.Length;
idx += vertexCount;
}
continue;
}
for (int materialDefinitionIndex = 0; materialDefinitionIndex < generatedMaterial.materialFragments.Count; materialDefinitionIndex++)
{
var fragment = generatedMaterial.materialFragments[materialDefinitionIndex];
var tempAtlasRect = fragment.atlasRegion;
int vertexCount = fragment.slotData.asset.meshData.vertices.Length;
float atlasXMin = tempAtlasRect.xMin / atlasResolution;
float atlasXMax = tempAtlasRect.xMax / atlasResolution;
float atlasXRange = atlasXMax - atlasXMin;
float atlasYMin = tempAtlasRect.yMin / atlasResolution;
float atlasYMax = tempAtlasRect.yMax / atlasResolution;
float atlasYRange = atlasYMax - atlasYMin;
// code below is for UVs remap based on rel pos in the atlas
if (fragment.isRectShared && fragment.slotData.useAtlasOverlay)
{
var foundRect = fragment.overlayList.FirstOrDefault(szname => fragment.slotData.slotName != null && szname.overlayName.Contains(fragment.slotData.slotName));
if (null != foundRect && foundRect.rect != Rect.zero)
{
var size = foundRect.rect.size * generatedMaterial.resolutionScale;
var offsetX = foundRect.rect.x * generatedMaterial.resolutionScale.x;
var offsetY = foundRect.rect.y * generatedMaterial.resolutionScale.x;
atlasXMin += (offsetX / generatedMaterial.cropResolution.x);
atlasXRange = size.x / generatedMaterial.cropResolution.x;
atlasYMin += (offsetY / generatedMaterial.cropResolution.y);
atlasYRange = size.y / generatedMaterial.cropResolution.y;
}
}
while (vertexCount-- > 0)
{
umaMesh.uv[idx].x = atlasXMin + atlasXRange * umaMesh.uv[idx].x;
umaMesh.uv[idx].y = atlasYMin + atlasYRange * umaMesh.uv[idx].y;
idx++;
}
}
}
}
}
}
| |
// # Namespaces
using System;
using System.Collections.Generic;
// # NuGet Install
// Visual Studio 2012 and 2010 Command:
// Install-Package PayPalMerchantSDK
// Visual Studio 2005 and 2008 (NuGet.exe) Command:
// install PayPalMerchantSDK
using PayPal.PayPalAPIInterfaceService;
using PayPal.PayPalAPIInterfaceService.Model;
namespace Merchello.Tests.PayPal.Prototype.ExpressCheckout
{
// # Sample for DoExpressCheckoutPayment API
// Authorize a payment.
// This sample code uses Merchant .NET SDK to make API call. You can
// download the SDKs [here](https://github.com/paypal/sdk-packages/tree/gh-pages/merchant-sdk/dotnet)
public class DoExpressCheckoutPaymentSample
{
// # Static constructor for configuration setting
static DoExpressCheckoutPaymentSample()
{
}
// # DoExpressCheckoutPayment API Operation
// The DoExpressCheckoutPayment API operation completes an Express Checkout transaction.
// If you set up a billing agreement in your SetExpressCheckout API call,
// the billing agreement is created when you call the DoExpressCheckoutPayment API operation.
public DoExpressCheckoutPaymentResponseType DoExpressCheckoutPaymentAPIOperation()
{
// Create the DoExpressCheckoutPaymentResponseType object
DoExpressCheckoutPaymentResponseType responseDoExpressCheckoutPaymentResponseType =
new DoExpressCheckoutPaymentResponseType();
try
{
// Create the DoExpressCheckoutPaymentReq object
DoExpressCheckoutPaymentReq doExpressCheckoutPayment = new DoExpressCheckoutPaymentReq();
DoExpressCheckoutPaymentRequestDetailsType doExpressCheckoutPaymentRequestDetails =
new DoExpressCheckoutPaymentRequestDetailsType();
// The timestamped token value that was returned in the
// `SetExpressCheckout` response and passed in the
// `GetExpressCheckoutDetails` request.
doExpressCheckoutPaymentRequestDetails.Token = "EC-3PG29673CT337061M";
// Unique paypal buyer account identification number as returned in
// `GetExpressCheckoutDetails` Response
doExpressCheckoutPaymentRequestDetails.PayerID = "WJ3Q38FZ9FDYS";
// # Payment Information
// list of information about the payment
List<PaymentDetailsType> paymentDetailsList = new List<PaymentDetailsType>();
// information about the first payment
PaymentDetailsType paymentDetails1 = new PaymentDetailsType();
// Total cost of the transaction to the buyer. If shipping cost and tax
// charges are known, include them in this value. If not, this value
// should be the current sub-total of the order.
//
// If the transaction includes one or more one-time purchases, this field must be equal to
// the sum of the purchases. Set this field to 0 if the transaction does
// not include a one-time purchase such as when you set up a billing
// agreement for a recurring payment that is not immediately charged.
// When the field is set to 0, purchase-specific fields are ignored.
//
// * `Currency Code` - You must set the currencyID attribute to one of the
// 3-character currency codes for any of the supported PayPal
// currencies.
// * `Amount`
BasicAmountType orderTotal1 = new BasicAmountType(CurrencyCodeType.USD, "2.00");
paymentDetails1.OrderTotal = orderTotal1;
// How you want to obtain payment. When implementing parallel payments,
// this field is required and must be set to `Order`. When implementing
// digital goods, this field is required and must be set to `Sale`. If the
// transaction does not include a one-time purchase, this field is
// ignored. It is one of the following values:
//
// * `Sale` - This is a final sale for which you are requesting payment
// (default).
// * `Authorization` - This payment is a basic authorization subject to
// settlement with PayPal Authorization and Capture.
// * `Order` - This payment is an order authorization subject to
// settlement with PayPal Authorization and Capture.
// Note:
// You cannot set this field to Sale in SetExpressCheckout request and
// then change the value to Authorization or Order in the
// DoExpressCheckoutPayment request. If you set the field to
// Authorization or Order in SetExpressCheckout, you may set the field
// to Sale.
paymentDetails1.PaymentAction = PaymentActionCodeType.ORDER;
// Unique identifier for the merchant. For parallel payments, this field
// is required and must contain the Payer Id or the email address of the
// merchant.
SellerDetailsType sellerDetails1 = new SellerDetailsType();
sellerDetails1.PayPalAccountID = "[email protected]";
paymentDetails1.SellerDetails = sellerDetails1;
// A unique identifier of the specific payment request, which is
// required for parallel payments.
paymentDetails1.PaymentRequestID = "PaymentRequest1";
// information about the second payment
PaymentDetailsType paymentDetails2 = new PaymentDetailsType();
// Total cost of the transaction to the buyer. If shipping cost and tax
// charges are known, include them in this value. If not, this value
// should be the current sub-total of the order.
//
// If the transaction includes one or more one-time purchases, this field must be equal to
// the sum of the purchases. Set this field to 0 if the transaction does
// not include a one-time purchase such as when you set up a billing
// agreement for a recurring payment that is not immediately charged.
// When the field is set to 0, purchase-specific fields are ignored.
//
// * `Currency Code` - You must set the currencyID attribute to one of the
// 3-character currency codes for any of the supported PayPal
// currencies.
// * `Amount`
BasicAmountType orderTotal2 = new BasicAmountType(CurrencyCodeType.USD, "4.00");
paymentDetails2.OrderTotal = orderTotal2;
// How you want to obtain payment. When implementing parallel payments,
// this field is required and must be set to `Order`. When implementing
// digital goods, this field is required and must be set to `Sale`. If the
// transaction does not include a one-time purchase, this field is
// ignored. It is one of the following values:
//
// * `Sale` - This is a final sale for which you are requesting payment
// (default).
// * `Authorization` - This payment is a basic authorization subject to
// settlement with PayPal Authorization and Capture.
// * `Order` - This payment is an order authorization subject to
// settlement with PayPal Authorization and Capture.
// `Note:
// You cannot set this field to Sale in SetExpressCheckout request and
// then change the value to Authorization or Order in the
// DoExpressCheckoutPayment request. If you set the field to
// Authorization or Order in SetExpressCheckout, you may set the field
// to Sale.`
paymentDetails2.PaymentAction = PaymentActionCodeType.ORDER;
// Unique identifier for the merchant. For parallel payments, this field
// is required and must contain the Payer Id or the email address of the
// merchant.
SellerDetailsType sellerDetails2 = new SellerDetailsType();
sellerDetails2.PayPalAccountID = "[email protected]";
paymentDetails2.SellerDetails = sellerDetails2;
// A unique identifier of the specific payment request, which is
// required for parallel payments.
paymentDetails2.PaymentRequestID = "PaymentRequest2";
paymentDetailsList.Add(paymentDetails1);
paymentDetailsList.Add(paymentDetails2);
doExpressCheckoutPaymentRequestDetails.PaymentDetails = paymentDetailsList;
DoExpressCheckoutPaymentRequestType doExpressCheckoutPaymentRequest =
new DoExpressCheckoutPaymentRequestType(doExpressCheckoutPaymentRequestDetails);
doExpressCheckoutPayment.DoExpressCheckoutPaymentRequest = doExpressCheckoutPaymentRequest;
var config = new Dictionary<string, string>
{
{"mode", "sandbox"},
{"account1.apiUsername", "konstantin_merchant_api1.scandiaconsulting.com"},
{"account1.apiPassword", "1398157263"},
{"account1.apiSignature", "AFcWxV21C7fd0v3bYYYRCpSSRl31AlRjlcug7qV.VXWV14E1KtmQPsPL"}
};
// Create the service wrapper object to make the API call
PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(config);
// # API call
// Invoke the DoExpressCheckoutPayment method in service wrapper object
responseDoExpressCheckoutPaymentResponseType = service.DoExpressCheckoutPayment(doExpressCheckoutPayment);
if (responseDoExpressCheckoutPaymentResponseType != null)
{
// Response envelope acknowledgement
string acknowledgement = "DoExpressCheckoutPayment API Operation - ";
acknowledgement += responseDoExpressCheckoutPaymentResponseType.Ack.ToString();
Console.WriteLine(acknowledgement + "\n");
// # Success values
if (responseDoExpressCheckoutPaymentResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
{
// Transaction identification number of the transaction that was
// created.
// This field is only returned after a successful transaction
// for DoExpressCheckout has occurred.
if (responseDoExpressCheckoutPaymentResponseType.DoExpressCheckoutPaymentResponseDetails.PaymentInfo != null)
{
IEnumerator<PaymentInfoType> paymentInfoIterator =
responseDoExpressCheckoutPaymentResponseType.DoExpressCheckoutPaymentResponseDetails.PaymentInfo.GetEnumerator();
while (paymentInfoIterator.MoveNext())
{
PaymentInfoType paymentInfo = paymentInfoIterator.Current;
Console.WriteLine("Transaction ID : " + paymentInfo.TransactionID + "\n");
}
}
}
// # Error Values
else
{
List<ErrorType> errorMessages = responseDoExpressCheckoutPaymentResponseType.Errors;
foreach (ErrorType error in errorMessages)
{
Console.WriteLine("API Error Message : " + error.LongMessage + "\n");
}
}
}
return responseDoExpressCheckoutPaymentResponseType;
}
// # Exception log
catch (System.Exception ex)
{
// Log the exception message
Console.WriteLine("Error Message : " + ex.Message);
}
return responseDoExpressCheckoutPaymentResponseType;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Management.Compute;
using Microsoft.WindowsAzure.Management.Compute.Models;
namespace Microsoft.WindowsAzure
{
/// <summary>
/// The Service Management API provides programmatic access to much of the
/// functionality available through the Management Portal. The Service
/// Management API is a REST API. All API operations are performed over
/// SSL, and are mutually authenticated using X.509 v3 certificates. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460799.aspx for
/// more information)
/// </summary>
public static partial class VirtualMachineVMImageOperationsExtensions
{
/// <summary>
/// The Begin Deleting Virtual Machine Image operation deletes the
/// specified virtual machine image.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineVMImageOperations.
/// </param>
/// <param name='vmImageName'>
/// Required. The name of the virtual machine image to delete.
/// </param>
/// <param name='deleteFromStorage'>
/// Required. Specifies that the source blob for the image should also
/// be deleted from storage.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static OperationResponse BeginDeleting(this IVirtualMachineVMImageOperations operations, string vmImageName, bool deleteFromStorage)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVirtualMachineVMImageOperations)s).BeginDeletingAsync(vmImageName, deleteFromStorage);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Begin Deleting Virtual Machine Image operation deletes the
/// specified virtual machine image.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineVMImageOperations.
/// </param>
/// <param name='vmImageName'>
/// Required. The name of the virtual machine image to delete.
/// </param>
/// <param name='deleteFromStorage'>
/// Required. Specifies that the source blob for the image should also
/// be deleted from storage.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<OperationResponse> BeginDeletingAsync(this IVirtualMachineVMImageOperations operations, string vmImageName, bool deleteFromStorage)
{
return operations.BeginDeletingAsync(vmImageName, deleteFromStorage, CancellationToken.None);
}
/// <summary>
/// Share an already replicated VM image. This operation is only for
/// publishers. You have to be registered as image publisher with
/// Windows Azure to be able to call this.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineVMImageOperations.
/// </param>
/// <param name='vmImageName'>
/// Required. The name of the virtual machine image to share.
/// </param>
/// <param name='permission'>
/// Required. The sharing permission: public, msdn, or private.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static OperationResponse BeginSharing(this IVirtualMachineVMImageOperations operations, string vmImageName, string permission)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVirtualMachineVMImageOperations)s).BeginSharingAsync(vmImageName, permission);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Share an already replicated VM image. This operation is only for
/// publishers. You have to be registered as image publisher with
/// Windows Azure to be able to call this.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineVMImageOperations.
/// </param>
/// <param name='vmImageName'>
/// Required. The name of the virtual machine image to share.
/// </param>
/// <param name='permission'>
/// Required. The sharing permission: public, msdn, or private.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<OperationResponse> BeginSharingAsync(this IVirtualMachineVMImageOperations operations, string vmImageName, string permission)
{
return operations.BeginSharingAsync(vmImageName, permission, CancellationToken.None);
}
/// <summary>
/// Unreplicate an VM image to multiple target locations. This
/// operation is only for publishers. You have to be registered as
/// image publisher with Windows Azure to be able to call this. Note:
/// The operation removes the published copies of the user VM Image.
/// It does not remove the actual user VM Image. To remove the actual
/// user VM Image, the publisher will have to call Delete VM Image.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineVMImageOperations.
/// </param>
/// <param name='vmImageName'>
/// Required. The name of the virtual machine image to replicate. Note:
/// The VM Image Name should be the user VM Image, not the published
/// name of the VM Image.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static OperationResponse BeginUnreplicating(this IVirtualMachineVMImageOperations operations, string vmImageName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVirtualMachineVMImageOperations)s).BeginUnreplicatingAsync(vmImageName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Unreplicate an VM image to multiple target locations. This
/// operation is only for publishers. You have to be registered as
/// image publisher with Windows Azure to be able to call this. Note:
/// The operation removes the published copies of the user VM Image.
/// It does not remove the actual user VM Image. To remove the actual
/// user VM Image, the publisher will have to call Delete VM Image.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineVMImageOperations.
/// </param>
/// <param name='vmImageName'>
/// Required. The name of the virtual machine image to replicate. Note:
/// The VM Image Name should be the user VM Image, not the published
/// name of the VM Image.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<OperationResponse> BeginUnreplicatingAsync(this IVirtualMachineVMImageOperations operations, string vmImageName)
{
return operations.BeginUnreplicatingAsync(vmImageName, CancellationToken.None);
}
/// <summary>
/// The Delete Virtual Machine Image operation deletes the specified
/// virtual machine image.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineVMImageOperations.
/// </param>
/// <param name='vmImageName'>
/// Required. The name of the virtual machine image to delete.
/// </param>
/// <param name='deleteFromStorage'>
/// Required. Specifies that the source blob for the image should also
/// be deleted from storage.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public static OperationStatusResponse Delete(this IVirtualMachineVMImageOperations operations, string vmImageName, bool deleteFromStorage)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVirtualMachineVMImageOperations)s).DeleteAsync(vmImageName, deleteFromStorage);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Delete Virtual Machine Image operation deletes the specified
/// virtual machine image.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineVMImageOperations.
/// </param>
/// <param name='vmImageName'>
/// Required. The name of the virtual machine image to delete.
/// </param>
/// <param name='deleteFromStorage'>
/// Required. Specifies that the source blob for the image should also
/// be deleted from storage.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public static Task<OperationStatusResponse> DeleteAsync(this IVirtualMachineVMImageOperations operations, string vmImageName, bool deleteFromStorage)
{
return operations.DeleteAsync(vmImageName, deleteFromStorage, CancellationToken.None);
}
/// <summary>
/// Gets VMImage's properties and its replication details. This
/// operation is only for publishers. You have to be registered as
/// image publisher with Windows Azure to be able to call this.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineVMImageOperations.
/// </param>
/// <param name='vmImageName'>
/// Required. The name of the virtual machine image to replicate.
/// </param>
/// <returns>
/// The Get Details VM Images operation response.
/// </returns>
public static VirtualMachineVMImageGetDetailsResponse GetDetails(this IVirtualMachineVMImageOperations operations, string vmImageName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVirtualMachineVMImageOperations)s).GetDetailsAsync(vmImageName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets VMImage's properties and its replication details. This
/// operation is only for publishers. You have to be registered as
/// image publisher with Windows Azure to be able to call this.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineVMImageOperations.
/// </param>
/// <param name='vmImageName'>
/// Required. The name of the virtual machine image to replicate.
/// </param>
/// <returns>
/// The Get Details VM Images operation response.
/// </returns>
public static Task<VirtualMachineVMImageGetDetailsResponse> GetDetailsAsync(this IVirtualMachineVMImageOperations operations, string vmImageName)
{
return operations.GetDetailsAsync(vmImageName, CancellationToken.None);
}
/// <summary>
/// The List Virtual Machine Images operation retrieves a list of the
/// virtual machine images.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineVMImageOperations.
/// </param>
/// <returns>
/// The List VM Images operation response.
/// </returns>
public static VirtualMachineVMImageListResponse List(this IVirtualMachineVMImageOperations operations)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVirtualMachineVMImageOperations)s).ListAsync();
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List Virtual Machine Images operation retrieves a list of the
/// virtual machine images.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineVMImageOperations.
/// </param>
/// <returns>
/// The List VM Images operation response.
/// </returns>
public static Task<VirtualMachineVMImageListResponse> ListAsync(this IVirtualMachineVMImageOperations operations)
{
return operations.ListAsync(CancellationToken.None);
}
/// <summary>
/// Replicate an VM image to multiple target locations. This operation
/// is only for publishers. You have to be registered as image
/// publisher with Windows Azure to be able to call this.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineVMImageOperations.
/// </param>
/// <param name='vmImageName'>
/// Required. The name of the virtual machine image to replicate.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Replicate Virtual Machine
/// Image operation.
/// </param>
/// <returns>
/// The response body contains the published name of the image.
/// </returns>
public static VirtualMachineVMImageReplicateResponse Replicate(this IVirtualMachineVMImageOperations operations, string vmImageName, VirtualMachineVMImageReplicateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVirtualMachineVMImageOperations)s).ReplicateAsync(vmImageName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Replicate an VM image to multiple target locations. This operation
/// is only for publishers. You have to be registered as image
/// publisher with Windows Azure to be able to call this.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineVMImageOperations.
/// </param>
/// <param name='vmImageName'>
/// Required. The name of the virtual machine image to replicate.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Replicate Virtual Machine
/// Image operation.
/// </param>
/// <returns>
/// The response body contains the published name of the image.
/// </returns>
public static Task<VirtualMachineVMImageReplicateResponse> ReplicateAsync(this IVirtualMachineVMImageOperations operations, string vmImageName, VirtualMachineVMImageReplicateParameters parameters)
{
return operations.ReplicateAsync(vmImageName, parameters, CancellationToken.None);
}
/// <summary>
/// Share an already replicated VM image. This operation is only for
/// publishers. You have to be registered as image publisher with
/// Windows Azure to be able to call this.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineVMImageOperations.
/// </param>
/// <param name='vmImageName'>
/// Required. The name of the virtual machine image to share.
/// </param>
/// <param name='permission'>
/// Required. The sharing permission: public, msdn, or private.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public static OperationStatusResponse Share(this IVirtualMachineVMImageOperations operations, string vmImageName, string permission)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVirtualMachineVMImageOperations)s).ShareAsync(vmImageName, permission);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Share an already replicated VM image. This operation is only for
/// publishers. You have to be registered as image publisher with
/// Windows Azure to be able to call this.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineVMImageOperations.
/// </param>
/// <param name='vmImageName'>
/// Required. The name of the virtual machine image to share.
/// </param>
/// <param name='permission'>
/// Required. The sharing permission: public, msdn, or private.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public static Task<OperationStatusResponse> ShareAsync(this IVirtualMachineVMImageOperations operations, string vmImageName, string permission)
{
return operations.ShareAsync(vmImageName, permission, CancellationToken.None);
}
/// <summary>
/// Unreplicate an VM image to multiple target locations. This
/// operation is only for publishers. You have to be registered as
/// image publisher with Windows Azure to be able to call this. Note:
/// The operation removes the published copies of the user VM Image.
/// It does not remove the actual user VM Image. To remove the actual
/// user VM Image, the publisher will have to call Delete VM Image.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineVMImageOperations.
/// </param>
/// <param name='vmImageName'>
/// Required. The name of the virtual machine image to replicate. Note:
/// The VM Image Name should be the user VM Image, not the published
/// name of the VM Image.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public static OperationStatusResponse Unreplicate(this IVirtualMachineVMImageOperations operations, string vmImageName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVirtualMachineVMImageOperations)s).UnreplicateAsync(vmImageName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Unreplicate an VM image to multiple target locations. This
/// operation is only for publishers. You have to be registered as
/// image publisher with Windows Azure to be able to call this. Note:
/// The operation removes the published copies of the user VM Image.
/// It does not remove the actual user VM Image. To remove the actual
/// user VM Image, the publisher will have to call Delete VM Image.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineVMImageOperations.
/// </param>
/// <param name='vmImageName'>
/// Required. The name of the virtual machine image to replicate. Note:
/// The VM Image Name should be the user VM Image, not the published
/// name of the VM Image.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public static Task<OperationStatusResponse> UnreplicateAsync(this IVirtualMachineVMImageOperations operations, string vmImageName)
{
return operations.UnreplicateAsync(vmImageName, CancellationToken.None);
}
/// <summary>
/// The Update VM Image operation updates a VM image that in your image
/// repository.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineVMImageOperations.
/// </param>
/// <param name='imageName'>
/// Required. The name of the virtual machine image to be updated.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update Virtual Machine Image
/// operation.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static OperationResponse Update(this IVirtualMachineVMImageOperations operations, string imageName, VirtualMachineVMImageUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVirtualMachineVMImageOperations)s).UpdateAsync(imageName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Update VM Image operation updates a VM image that in your image
/// repository.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineVMImageOperations.
/// </param>
/// <param name='imageName'>
/// Required. The name of the virtual machine image to be updated.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update Virtual Machine Image
/// operation.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<OperationResponse> UpdateAsync(this IVirtualMachineVMImageOperations operations, string imageName, VirtualMachineVMImageUpdateParameters parameters)
{
return operations.UpdateAsync(imageName, parameters, CancellationToken.None);
}
}
}
| |
// 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.IO;
using System.Xml;
using Microsoft.Test.ModuleCore;
namespace CoreXml.Test.XLinq
{
public partial class FunctionalTests : TestModule
{
public partial class XNodeReaderTests : XLinqTestCase
{
public partial class TCReadSubtree : BridgeHelpers
{
//[Variation("ReadSubtree only works on Element Node")]
public void ReadSubtreeOnlyWorksOnElementNode()
{
XmlReader DataReader = GetReader();
while (DataReader.Read())
{
if (DataReader.NodeType != XmlNodeType.Element)
{
string nodeType = DataReader.NodeType.ToString();
bool flag = true;
try
{
DataReader.ReadSubtree();
}
catch (InvalidOperationException)
{
flag = false;
}
if (flag)
{
TestLog.WriteLine("ReadSubtree doesnt throw InvalidOp Exception on NodeType : " + nodeType);
throw new TestException(TestResult.Failed, "");
}
// now try next read
try
{
DataReader.Read();
}
catch (XmlException)
{
TestLog.WriteLine("Cannot Read after an invalid operation exception");
throw new TestException(TestResult.Failed, "");
}
}
else
{
if (DataReader.HasAttributes)
{
bool flag = true;
DataReader.MoveToFirstAttribute();
try
{
DataReader.ReadSubtree();
}
catch (InvalidOperationException)
{
flag = false;
}
if (flag)
{
TestLog.WriteLine("ReadSubtree doesnt throw InvalidOp Exception on Attribute Node Type");
throw new TestException(TestResult.Failed, "");
}
//now try next read.
try
{
DataReader.Read();
}
catch (XmlException)
{
TestLog.WriteLine("Cannot Read after an invalid operation exception");
throw new TestException(TestResult.Failed, "");
}
}
}
}//end while
}
private string _xml = "<root><elem1><elempi/><?pi target?><elem2 xmlns='xyz'><elem/><!--Comment--><x:elem3 xmlns:x='pqr'><elem4 attr4='4'/></x:elem3></elem2></elem1><elem5/><elem6/></root>";
//[Variation("ReadSubtree Test on Root", Priority = 0, Params = new object[] { "root", "", "ELEMENT", "", "", "NONE" })]
//[Variation("ReadSubtree Test depth=1", Priority = 0, Params = new object[] { "elem1", "", "ELEMENT", "elem5", "", "ELEMENT" })]
//[Variation("ReadSubtree Test depth=2", Priority = 0, Params = new object[] { "elem2", "", "ELEMENT", "elem1", "", "ENDELEMENT" })]
//[Variation("ReadSubtree Test depth=3", Priority = 0, Params = new object[] { "x:elem3", "", "ELEMENT", "elem2", "", "ENDELEMENT" })]
//[Variation("ReadSubtree Test depth=4", Priority = 0, Params = new object[] { "elem4", "", "ELEMENT", "x:elem3", "", "ENDELEMENT" })]
//[Variation("ReadSubtree Test empty element", Priority = 0, Params = new object[] { "elem5", "", "ELEMENT", "elem6", "", "ELEMENT" })]
//[Variation("ReadSubtree Test empty element before root", Priority = 0, Params = new object[] { "elem6", "", "ELEMENT", "root", "", "ENDELEMENT" })]
//[Variation("ReadSubtree Test PI after element", Priority = 0, Params = new object[] { "elempi", "", "ELEMENT", "pi", "target", "PROCESSINGINSTRUCTION" })]
//[Variation("ReadSubtree Test Comment after element", Priority = 0, Params = new object[] { "elem", "", "ELEMENT", "", "Comment", "COMMENT" })]
public void v2()
{
int count = 0;
string name = Variation.Params[count++].ToString();
string value = Variation.Params[count++].ToString();
string type = Variation.Params[count++].ToString();
string oname = Variation.Params[count++].ToString();
string ovalue = Variation.Params[count++].ToString();
string otype = Variation.Params[count++].ToString();
XmlReader DataReader = GetReader(new StringReader(_xml));
PositionOnElement(DataReader, name);
XmlReader r = DataReader.ReadSubtree();
TestLog.Compare(r.ReadState, ReadState.Initial, "Reader state is not Initial");
TestLog.Compare(r.Name, String.Empty, "Name is not empty");
TestLog.Compare(r.NodeType, XmlNodeType.None, "Nodetype is not empty");
TestLog.Compare(r.Depth, 0, "Depth is not zero");
r.Read();
TestLog.Compare(r.ReadState, ReadState.Interactive, "Reader state is not Interactive");
TestLog.Compare(r.Name, name, "Subreader name doesnt match");
TestLog.Compare(r.Value, value, "Subreader value doesnt match");
TestLog.Compare(r.NodeType.ToString().ToUpperInvariant(), type, "Subreader nodetype doesnt match");
TestLog.Compare(r.Depth, 0, "Subreader Depth is not zero");
while (r.Read()) ;
r.Dispose();
TestLog.Compare(r.ReadState, ReadState.Closed, "Reader state is not Initial");
TestLog.Compare(r.Name, String.Empty, "Name is not empty");
TestLog.Compare(r.NodeType, XmlNodeType.None, "Nodetype is not empty");
DataReader.Read();
TestLog.Compare(DataReader.Name, oname, "Main name doesnt match");
TestLog.Compare(DataReader.Value, ovalue, "Main value doesnt match");
TestLog.Compare(DataReader.NodeType.ToString().ToUpperInvariant(), otype, "Main nodetype doesnt match");
DataReader.Dispose();
}
//[Variation("Read with entities", Priority = 1)]
public void v3()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "PLAY");
XmlReader r = DataReader.ReadSubtree();
while (r.Read())
{
if (r.NodeType == XmlNodeType.EntityReference)
{
if (r.CanResolveEntity)
r.ResolveEntity();
}
}
r.Dispose();
DataReader.Dispose();
}
//[Variation("Inner XML on Subtree reader", Priority = 1)]
public void v4()
{
string xmlStr = "<elem1><elem2/></elem1>";
XmlReader DataReader = GetReaderStr(xmlStr);
PositionOnElement(DataReader, "elem1");
XmlReader r = DataReader.ReadSubtree();
r.Read();
TestLog.Compare(r.ReadInnerXml(), "<elem2 />", "Inner Xml Fails");
TestLog.Compare(r.Read(), false, "Read returns false");
r.Dispose();
DataReader.Dispose();
}
//[Variation("Outer XML on Subtree reader", Priority = 1)]
public void v5()
{
string xmlStr = "<elem1><elem2/></elem1>";
XmlReader DataReader = GetReaderStr(xmlStr);
PositionOnElement(DataReader, "elem1");
XmlReader r = DataReader.ReadSubtree();
r.Read();
TestLog.Compare(r.ReadOuterXml(), "<elem1><elem2 /></elem1>", "Outer Xml Fails");
TestLog.Compare(r.Read(), false, "Read returns true");
r.Dispose();
DataReader.Dispose();
}
//[Variation("ReadString on Subtree reader", Priority = 1)]
public void v6()
{
string xmlStr = "<elem1><elem2/></elem1>";
XmlReader DataReader = GetReaderStr(xmlStr);
PositionOnElement(DataReader, "elem1");
XmlReader r = DataReader.ReadSubtree();
r.Read();
TestLog.Compare(r.Read(), true, "Read returns false");
r.Dispose();
DataReader.Dispose();
}
//[Variation("Close on inner reader with CloseInput should not close the outer reader", Priority = 1, Params = new object[] { "true" })]
//[Variation("Close on inner reader with CloseInput should not close the outer reader", Priority = 1, Params = new object[] { "false" })]
public void v7()
{
XmlReader DataReader = GetReader();
bool ci = Boolean.Parse(Variation.Params[0].ToString());
XmlReaderSettings settings = new XmlReaderSettings();
settings.CloseInput = ci;
PositionOnElement(DataReader, "elem2");
XmlReader r = DataReader.ReadSubtree();
r.Dispose();
TestLog.Compare(DataReader.ReadState, ReadState.Interactive, "ReadState not interactive");
DataReader.Dispose();
}
private XmlReader NestRead(XmlReader r)
{
r.Read();
r.Read();
if (!(r.Name == "elem0" && r.NodeType == XmlNodeType.Element))
{
NestRead(r.ReadSubtree());
}
r.Dispose();
return r;
}
//[Variation("Nested Subtree reader calls", Priority = 2)]
public void v8()
{
string xmlStr = "<elem1><elem2><elem3><elem4><elem5><elem6><elem7><elem8><elem9><elem0></elem0></elem9></elem8></elem7></elem6></elem5></elem4></elem3></elem2></elem1>";
XmlReader r = GetReader(new StringReader(xmlStr));
NestRead(r);
TestLog.Compare(r.ReadState, ReadState.Closed, "Reader Read State is not closed");
}
//[Variation("ReadSubtree for element depth more than 4K chars", Priority = 2)]
public void v100()
{
ManagedNodeWriter mnw = new ManagedNodeWriter();
mnw.PutPattern("X");
do
{
mnw.OpenElement();
mnw.CloseElement();
}
while (mnw.GetNodes().Length < 4096);
mnw.Finish();
XmlReader DataReader = GetReader(new StringReader(mnw.GetNodes()));
PositionOnElement(DataReader, "ELEMENT_2");
XmlReader r = DataReader.ReadSubtree();
while (r.Read()) ;
r.Dispose();
DataReader.Read();
TestLog.Compare(DataReader.Name, "ELEMENT_1", "Main name doesnt match");
TestLog.Compare(DataReader.Value, "", "Main value doesnt match");
TestLog.Compare(DataReader.NodeType.ToString().ToUpperInvariant(), "ENDELEMENT", "Main nodetype doesnt match");
DataReader.Dispose();
}
//[Variation("Multiple Namespaces on Subtree reader", Priority = 1)]
public void MultipleNamespacesOnSubtreeReader()
{
string xmlStr = "<root xmlns:p1='a' xmlns:p2='b'><e p1:a='' p2:a=''></e></root>";
XmlReader DataReader = GetReader(new StringReader(xmlStr));
PositionOnElement(DataReader, "e");
XmlReader r = DataReader.ReadSubtree();
while (r.Read()) ;
r.Dispose();
DataReader.Dispose();
}
//[Variation("Subtree Reader caches the NodeType and reports node type of Attribute on subsequent reads.", Priority = 1)]
public void SubtreeReaderCachesNodeTypeAndReportsNodeTypeOfAttributeOnSubsequentReads()
{
string xmlStr = "<root xmlns='foo'><b blah='blah'/><b/></root>";
XmlReader DataReader = GetReader(new StringReader(xmlStr));
PositionOnElement(DataReader, "root");
XmlReader xxr = DataReader.ReadSubtree();
//Now on root.
xxr.Read();
TestLog.Compare(xxr.Name, "root", "Root Elem");
TestLog.Compare(xxr.MoveToNextAttribute(), true, "MTNA 1");
TestLog.Compare(xxr.NodeType, XmlNodeType.Attribute, "XMLNS NT");
TestLog.Compare(xxr.Name, "xmlns", "XMLNS Attr");
TestLog.Compare(xxr.Value, "foo", "XMLNS Value");
TestLog.Compare(xxr.MoveToNextAttribute(), false, "MTNA 2");
//Now on b.
xxr.Read();
TestLog.Compare(xxr.Name, "b", "b Elem");
TestLog.Compare(xxr.MoveToNextAttribute(), true, "MTNA 3");
TestLog.Compare(xxr.NodeType, XmlNodeType.Attribute, "blah NT");
TestLog.Compare(xxr.Name, "blah", "blah Attr");
TestLog.Compare(xxr.Value, "blah", "blah Value");
TestLog.Compare(xxr.MoveToNextAttribute(), false, "MTNA 4");
// Now on /b.
xxr.Read();
TestLog.Compare(xxr.Name, "b", "b EndElem");
TestLog.Compare(xxr.NodeType, XmlNodeType.Element, "b Elem NT");
TestLog.Compare(xxr.MoveToNextAttribute(), false, "MTNA 5");
xxr.Read();
TestLog.Compare(xxr.Name, "root", "root EndElem");
TestLog.Compare(xxr.NodeType, XmlNodeType.EndElement, "root EndElem NT");
TestLog.Compare(xxr.MoveToNextAttribute(), false, "MTNA 6");
xxr.Dispose();
DataReader.Dispose();
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.