context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using System;
using System.Collections.Generic;
using System.Text;
// Copyright (c) 2009 by Hugh Pyle, inguzaudio.com
namespace DSPUtil
{
abstract public class Matrix
{
// how many channels
protected ushort _dimension;
// square matrix [rows][columns]
protected double[,] _matrix;
// parameter (usually degrees, sometimes something else)
protected double _param = double.NaN;
virtual public double Param
{
get { return _param; }
set { _param = value; }
}
public ISample Process(ISample sample)
{
if (sample.NumChannels != _dimension)
{
throw new InvalidOperationException();
}
Sample s = new Sample(_dimension);
// row of matrix
// channel of output
for (ushort j = 0; j < _dimension; j++)
{
// channel of original sample
// column of matrix
for (ushort c = 0; c < _dimension; c++)
{
s[j] += sample[c] * _matrix[j,c];
}
}
return s;
}
}
abstract public class Amb1Matrix : Matrix
{
public Amb1Matrix()
{
_dimension = 4;
_matrix = new double[4,4];
}
}
// Classic rotation matrices for first-order
// http://www.muse.demon.co.uk/fmhrotat.html
public class Amb1RotAboutX : Amb1Matrix
{
public Amb1RotAboutX(double degrees)
: base()
{
Param = degrees;
}
override public double Param
{
set
{
if (_param != value)
{
_param = value;
double r = MathUtil.Radians(value);
_matrix[0, 0] = 1;
_matrix[1, 1] = 1;
_matrix[2, 2] = Math.Cos(r);
_matrix[3, 2] = Math.Sin(r);
_matrix[2, 3] = -Math.Sin(r);
_matrix[3, 3] = Math.Cos(r);
}
}
}
}
public class Amb1RotAboutY : Amb1Matrix
{
public Amb1RotAboutY(double degrees)
: base()
{
Param = degrees;
}
override public double Param
{
set
{
if (_param != value)
{
_param = value;
double r = MathUtil.Radians(value);
_matrix[0, 0] = 1;
_matrix[1, 1] = Math.Cos(r);
_matrix[3, 1] = Math.Sin(r);
_matrix[2, 2] = 1;
_matrix[1, 3] = -Math.Sin(r);
_matrix[3, 3] = Math.Cos(r);
}
}
}
}
public class Amb1RotAboutZ : Amb1Matrix
{
public Amb1RotAboutZ(double degrees)
: base()
{
Param = degrees;
}
override public double Param
{
set
{
if (_param != value)
{
_param = value;
double r = MathUtil.Radians(value);
_matrix[0, 0] = 1;
_matrix[1, 1] = Math.Cos(r);
_matrix[2, 1] = Math.Sin(r);
_matrix[1, 2] = -Math.Sin(r);
_matrix[2, 2] = Math.Cos(r);
_matrix[3, 3] = 1;
}
}
}
}
// Classic dominance and
// Joseph Anderson's push etc
// http://ambisonics.iem.at/symposium2009/proceedings/ambisym09-josephanderson-ambitk-poster.pdf/at_download/file
public class Amb1Dominance : Amb1Matrix
{
private double _az, _el;
public Amb1Dominance(double lambda, double az, double el)
: base()
{
Param = lambda;
_az = az;
_el = el;
}
override public double Param
{
set
{
if (_param != value)
{
_param = value;
double lambda = value;
_matrix[0, 0] = 0.5 * (lambda + (1 / lambda));
_matrix[1, 0] = (1 / Math.Sqrt(2)) * (lambda - (1 / lambda));
_matrix[0, 1] = (1 / Math.Sqrt(8)) * (lambda - (1 / lambda));
_matrix[1, 1] = 0.5 * (lambda + (1 / lambda));
_matrix[2, 2] = 1;
_matrix[3, 3] = 1;
}
}
}
}
public class Amb1Focus : Amb1Matrix
{
private double _az, _el;
public Amb1Focus(double degrees, double az, double el)
: base()
{
Param = degrees;
_az = az;
_el = el;
}
override public double Param
{
set
{
if (_param != value)
{
_param = value;
double r = MathUtil.Radians(value);
double sinr = Math.Sin(r);
double sqr2 = Math.Sqrt(2);
_matrix[0, 0] = (1 / (1 + Math.Abs(sinr)));
_matrix[1, 0] = sqr2 * (sinr / (1 + Math.Abs(sinr)));
_matrix[0, 1] = (1 / sqr2) * (sinr / (1 + Math.Abs(sinr)));
_matrix[1, 1] = (1 / (1 + Math.Abs(sinr)));
_matrix[2, 2] = Math.Sqrt((1 - Math.Abs(sinr)) / (1 + Math.Abs(sinr)));
_matrix[3, 3] = Math.Sqrt((1 - Math.Abs(sinr)) / (1 + Math.Abs(sinr)));
}
}
}
}
public class Amb1Push : Amb1Matrix
{
private double _az, _el;
public Amb1Push(double degrees, double az, double el)
: base()
{
Param = degrees;
_az = az;
_el = el;
}
override public double Param
{
set
{
if (_param != value)
{
_param = value;
double r = MathUtil.Radians(value);
_matrix[0, 0] = 1;
_matrix[1, 0] = Math.Sqrt(2) * Math.Abs(Math.Sin(r)) * Math.Sin(r);
_matrix[1, 1] = Math.Cos(r) * Math.Cos(r);
_matrix[2, 2] = Math.Cos(r) * Math.Cos(r);
_matrix[3, 3] = Math.Cos(r) * Math.Cos(r);
}
}
}
}
public class Amb1Press : Amb1Matrix
{
private double _az, _el;
public Amb1Press(double degrees, double az, double el)
: base()
{
Param = degrees;
_az = az;
_el = el;
}
override public double Param
{
set
{
if (_param != value)
{
_param = value;
double r = MathUtil.Radians(value);
_matrix[0, 0] = 1;
_matrix[1, 0] = Math.Sqrt(2) * Math.Abs(Math.Sin(r)) * Math.Sin(r);
_matrix[1, 1] = Math.Cos(r) * Math.Cos(r);
_matrix[2, 2] = Math.Cos(r);
_matrix[3, 3] = Math.Cos(r);
}
}
}
}
}
| |
using UnityEditor;
using UnityEngine;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using V1=AssetBundleGraph;
using Model=UnityEngine.AssetGraph.DataModel.Version2;
namespace UnityEngine.AssetGraph {
[CustomNode("Configure Bundle/Configure Bundle From Group", 70)]
public class BundleConfigurator : Node, Model.NodeDataImporter {
[Serializable]
public class Variant {
[SerializeField] private string m_name;
[SerializeField] private string m_pointId;
public Variant(string name, Model.ConnectionPointData point) {
m_name = name;
m_pointId = point.Id;
}
public Variant(Variant v) {
m_name = v.m_name;
m_pointId = v.m_pointId;
}
public string Name {
get {
return m_name;
}
set {
m_name = value;
}
}
public string ConnectionPointId {
get {
return m_pointId;
}
}
}
[SerializeField] private SerializableMultiTargetString m_bundleNameTemplate;
[SerializeField] private List<Variant> m_variants;
[SerializeField] private bool m_useGroupAsVariants;
public override string ActiveStyle {
get {
return "node 3 on";
}
}
public override string InactiveStyle {
get {
return "node 3";
}
}
public override string Category {
get {
return "Configure";
}
}
public override Model.NodeOutputSemantics NodeOutputType {
get {
return Model.NodeOutputSemantics.AssetBundleConfigurations;
}
}
public override void Initialize(Model.NodeData data) {
m_bundleNameTemplate = new SerializableMultiTargetString(Model.Settings.BUNDLECONFIG_BUNDLENAME_TEMPLATE_DEFAULT);
m_useGroupAsVariants = false;
m_variants = new List<Variant>();
data.AddDefaultInputPoint();
data.AddDefaultOutputPoint();
}
public void Import(V1.NodeData v1, Model.NodeData v2) {
m_bundleNameTemplate = new SerializableMultiTargetString(v1.BundleNameTemplate);
m_useGroupAsVariants = v1.BundleConfigUseGroupAsVariants;
foreach(var v in v1.Variants) {
m_variants.Add(new Variant(v.Name, v2.FindInputPoint(v.ConnectionPointId)));
}
}
public override Node Clone(Model.NodeData newData) {
var newNode = new BundleConfigurator();
newNode.m_bundleNameTemplate = new SerializableMultiTargetString(m_bundleNameTemplate);
newNode.m_variants = new List<Variant>(m_variants.Count);
newNode.m_useGroupAsVariants = m_useGroupAsVariants;
newData.AddDefaultInputPoint();
newData.AddDefaultOutputPoint();
foreach(var v in m_variants) {
newNode.AddVariant(newData, v.Name);
}
return newNode;
}
public override bool IsValidInputConnectionPoint(Model.ConnectionPointData point) {
if(!m_useGroupAsVariants) {
if(m_variants.Count > 0 && m_variants.Find(v => v.ConnectionPointId == point.Id) == null)
{
return false;
}
}
return true;
}
private void AddVariant(Model.NodeData n, string name) {
var p = n.AddInputPoint(name);
var newEntry = new Variant(name, p);
m_variants.Add(newEntry);
UpdateVariant(n, newEntry);
}
private void RemoveVariant(Model.NodeData n, Variant v) {
m_variants.Remove(v);
n.InputPoints.Remove(GetConnectionPoint(n, v));
}
private Model.ConnectionPointData GetConnectionPoint(Model.NodeData n, Variant v) {
Model.ConnectionPointData p = n.InputPoints.Find(point => point.Id == v.ConnectionPointId);
UnityEngine.Assertions.Assert.IsNotNull(p);
return p;
}
private void UpdateVariant(Model.NodeData n,Variant variant) {
Model.ConnectionPointData p = n.InputPoints.Find(v => v.Id == variant.ConnectionPointId);
UnityEngine.Assertions.Assert.IsNotNull(p);
p.Label = variant.Name;
}
public override void OnInspectorGUI(NodeGUI node, AssetReferenceStreamManager streamManager, NodeGUIEditor editor, Action onValueChanged) {
if (m_bundleNameTemplate == null) return;
EditorGUILayout.HelpBox("Configure Bundle From Group: Create asset bundle settings from incoming group of assets.", MessageType.Info);
editor.UpdateNodeName(node);
GUILayout.Space(10f);
using (new EditorGUILayout.VerticalScope(GUI.skin.box)) {
var newUseGroupAsVariantValue = GUILayout.Toggle(m_useGroupAsVariants, "Use input group as variants");
if(newUseGroupAsVariantValue != m_useGroupAsVariants) {
using(new RecordUndoScope("Change Bundle Config", node, true)){
m_useGroupAsVariants = newUseGroupAsVariantValue;
List<Variant> rv = new List<Variant>(m_variants);
foreach(var v in rv) {
NodeGUIUtility.NodeEventHandler(
new NodeEvent(NodeEvent.EventType.EVENT_CONNECTIONPOINT_DELETED, node, Vector2.zero, GetConnectionPoint(node.Data, v)));
RemoveVariant(node.Data, v);
}
onValueChanged();
}
}
using (new EditorGUI.DisabledScope(newUseGroupAsVariantValue)) {
GUILayout.Label("Variants:");
var variantNames = m_variants.Select(v => v.Name).ToList();
Variant removing = null;
foreach (var v in m_variants) {
using (new GUILayout.HorizontalScope()) {
if (GUILayout.Button("-", GUILayout.Width(30))) {
removing = v;
}
else {
GUIStyle s = new GUIStyle((GUIStyle)"TextFieldDropDownText");
Action makeStyleBold = () => {
s.fontStyle = FontStyle.Bold;
s.fontSize = 12;
};
ValidateVariantName(v.Name, variantNames,
makeStyleBold,
makeStyleBold,
makeStyleBold);
var variantName = EditorGUILayout.TextField(v.Name, s);
if (variantName != v.Name) {
using(new RecordUndoScope("Change Variant Name", node, true)){
v.Name = variantName;
UpdateVariant(node.Data, v);
onValueChanged();
}
}
}
}
}
if (GUILayout.Button("+")) {
using(new RecordUndoScope("Add Variant", node, true)){
if(m_variants.Count == 0) {
NodeGUIUtility.NodeEventHandler(new NodeEvent(NodeEvent.EventType.EVENT_DELETE_ALL_CONNECTIONS_TO_POINT, node, Vector2.zero, node.Data.InputPoints[0]));
}
AddVariant(node.Data, Model.Settings.BUNDLECONFIG_VARIANTNAME_DEFAULT);
onValueChanged();
}
}
if(removing != null) {
using(new RecordUndoScope("Remove Variant", node, true)){
// event must raise to remove connection associated with point
NodeGUIUtility.NodeEventHandler(new NodeEvent(NodeEvent.EventType.EVENT_CONNECTIONPOINT_DELETED, node, Vector2.zero, GetConnectionPoint(node.Data, removing)));
RemoveVariant(node.Data, removing);
onValueChanged();
}
}
}
}
//Show target configuration tab
editor.DrawPlatformSelector(node);
using (new EditorGUILayout.VerticalScope(GUI.skin.box)) {
var disabledScope = editor.DrawOverrideTargetToggle(node, m_bundleNameTemplate.ContainsValueOf(editor.CurrentEditingGroup), (bool enabled) => {
using(new RecordUndoScope("Remove Target Bundle Name Template Setting", node, true)){
if(enabled) {
m_bundleNameTemplate[editor.CurrentEditingGroup] = m_bundleNameTemplate.DefaultValue;
} else {
m_bundleNameTemplate.Remove(editor.CurrentEditingGroup);
}
onValueChanged();
}
});
using (disabledScope) {
var bundleNameTemplate = EditorGUILayout.TextField("Bundle Name Template", m_bundleNameTemplate[editor.CurrentEditingGroup]).ToLower();
if (bundleNameTemplate != m_bundleNameTemplate[editor.CurrentEditingGroup]) {
using(new RecordUndoScope("Change Bundle Name Template", node, true)){
m_bundleNameTemplate[editor.CurrentEditingGroup] = bundleNameTemplate;
onValueChanged();
}
}
}
}
}
public override void Prepare (BuildTarget target,
Model.NodeData node,
IEnumerable<PerformGraph.AssetGroups> incoming,
IEnumerable<Model.ConnectionData> connectionsToOutput,
PerformGraph.Output Output)
{
int groupCount = 0;
if(incoming != null) {
var groupNames = new List<string>();
foreach(var ag in incoming) {
foreach (var groupKey in ag.assetGroups.Keys) {
if(!groupNames.Contains(groupKey)) {
groupNames.Add(groupKey);
}
}
}
groupCount = groupNames.Count;
}
ValidateBundleNameTemplate(
m_bundleNameTemplate[target],
m_useGroupAsVariants,
groupCount,
() => {
throw new NodeException("Bundle Name Template is empty.",
"Set valid bundle name template from inspector.",node);
},
() => {
throw new NodeException("Bundle Name Template can not contain '" + Model.Settings.KEYWORD_WILDCARD.ToString()
+ "' when group name is used for variants.",
"Set valid bundle name without '" + Model.Settings.KEYWORD_WILDCARD.ToString() + "' from inspector.", node);
},
() => {
throw new NodeException("Bundle Name Template must contain '" + Model.Settings.KEYWORD_WILDCARD.ToString()
+ "' when group name is not used for variants and expecting multiple incoming groups.",
"Set valid bundle name without '" + Model.Settings.KEYWORD_WILDCARD.ToString() + "' from inspector.", node);
}
);
var variantNames = m_variants.Select(v=>v.Name).ToList();
foreach(var variant in m_variants) {
ValidateVariantName(variant.Name, variantNames,
() => {
throw new NodeException("Variant name is empty.", "Set valid variant name from inspector.", node);
},
() => {
throw new NodeException("Variant name cannot contain whitespace \"" + variant.Name + "\".", "Remove whitespace from variant name.", node);
},
() => {
throw new NodeException("Variant name already exists \"" + variant.Name + "\".", "Avoid variant name collision.", node);
});
}
if(incoming != null) {
/**
* Check if incoming asset has valid import path
*/
var invalids = new List<AssetReference>();
foreach(var ag in incoming) {
foreach (var groupKey in ag.assetGroups.Keys) {
ag.assetGroups[groupKey].ForEach( a => { if (string.IsNullOrEmpty(a.importFrom)) invalids.Add(a); } );
}
}
if (invalids.Any()) {
throw new NodeException(
"Invalid files are found. Following files need to be imported to put into asset bundle: " +
string.Join(", ", invalids.Select(a =>a.absolutePath).ToArray()), "Import these files before building asset bundles.", node );
}
}
Dictionary<string, List<AssetReference>> output = null;
if(Output != null) {
output = new Dictionary<string, List<AssetReference>>();
}
if(incoming != null) {
Dictionary<string, List<string>> variantsInfo = new Dictionary<string, List<string>> ();
var buildMap = AssetBundleBuildMap.GetBuildMap ();
buildMap.ClearFromId (node.Id);
foreach(var ag in incoming) {
string variantName = null;
if(!m_useGroupAsVariants) {
var currentVariant = m_variants.Find( v => v.ConnectionPointId == ag.connection.ToNodeConnectionPointId );
variantName = (currentVariant == null) ? null : currentVariant.Name;
}
// set configured assets in bundle name
foreach (var groupKey in ag.assetGroups.Keys) {
if(m_useGroupAsVariants) {
variantName = groupKey;
}
var bundleName = GetBundleName(target, node, groupKey);
var assets = ag.assetGroups[groupKey];
ConfigureAssetBundleSettings(variantName, assets);
if (!string.IsNullOrEmpty (variantName)) {
if (!variantsInfo.ContainsKey (bundleName)) {
variantsInfo [bundleName] = new List<string> ();
}
variantsInfo [bundleName].Add (variantName.ToLower());
}
if(output != null) {
if(!output.ContainsKey(bundleName)) {
output[bundleName] = new List<AssetReference>();
}
output[bundleName].AddRange(assets);
}
var bundleConfig = buildMap.GetAssetBundleWithNameAndVariant (node.Id, bundleName, variantName);
bundleConfig.AddAssets (node.Id, assets.Select(a => a.importFrom));
}
}
if (output != null) {
ValidateVariantsProperlyConfiguired (node, output, variantsInfo);
}
}
if(Output != null) {
var dst = (connectionsToOutput == null || !connectionsToOutput.Any())?
null : connectionsToOutput.First();
Output(dst, output);
}
}
public void ConfigureAssetBundleSettings (string variantName, List<AssetReference> assets) {
foreach(var a in assets) {
a.variantName = (string.IsNullOrEmpty(variantName))? null : variantName.ToLower();
}
}
public static void ValidateBundleNameTemplate (string bundleNameTemplate, bool useGroupAsVariants, int groupCount,
Action NullOrEmpty,
Action InvalidBundleNameTemplateForVariants,
Action InvalidBundleNameTemplateForNotVariants
) {
if (string.IsNullOrEmpty(bundleNameTemplate)){
NullOrEmpty();
}
if(useGroupAsVariants && bundleNameTemplate.IndexOf(Model.Settings.KEYWORD_WILDCARD) >= 0) {
InvalidBundleNameTemplateForVariants();
}
if(!useGroupAsVariants && bundleNameTemplate.IndexOf(Model.Settings.KEYWORD_WILDCARD) < 0 &&
groupCount > 1) {
InvalidBundleNameTemplateForNotVariants();
}
}
public static void ValidateVariantName (string variantName, List<string> names, Action NullOrEmpty, Action ContainsSpace, Action NameAlreadyExists) {
if (string.IsNullOrEmpty(variantName)) {
NullOrEmpty();
}
if(Regex.IsMatch(variantName, "\\s")) {
ContainsSpace();
}
var overlappings = names.GroupBy(x => x)
.Where(group => 1 < group.Count())
.Select(group => group.Key)
.ToList();
if (overlappings.Any()) {
NameAlreadyExists();
}
}
private void ValidateVariantsProperlyConfiguired(
Model.NodeData node,
Dictionary<string, List<AssetReference>> output, Dictionary<string, List<string>> variantsInfo)
{
foreach (var bundleName in output.Keys) {
if (!variantsInfo.ContainsKey (bundleName)) {
continue;
}
List<string> variants = variantsInfo [bundleName];
if (variants.Count < 2) {
throw new NodeException (bundleName + " is not configured to create more than 2 variants.", "Add another variant or remove variant to this bundle.", node);
}
List<AssetReference> assets = output [bundleName];
List<AssetReference> variant0Assets = assets.Where (a => a.variantName == variants [0]).ToList ();
for(int i = 1; i< variants.Count; ++i) {
List<AssetReference> variantAssets = assets.Where (a => a.variantName == variants [i]).ToList ();
if(variant0Assets.Count != variantAssets.Count) {
throw new NodeException ("Variant mismatch found." + bundleName + " variant " + variants [0] + " and " + variants [i] + " do not match containing assets.",
"Configure variants' content and make sure they all match."
,node);
}
foreach (var a0 in variant0Assets) {
if(!variantAssets.Any( a => a.fileName == a0.fileName)) {
throw new NodeException ("Variant mismatch found." + bundleName + " does not contain " + a0.fileNameAndExtension + " in variant " + variants [i],
"Configure variants' content and make sure they all match.", node);
}
}
}
}
}
public string GetBundleName(BuildTarget target, Model.NodeData node, string groupKey) {
var bundleName = m_bundleNameTemplate[target];
if(m_useGroupAsVariants) {
return bundleName.ToLower();
} else {
return bundleName.Replace(Model.Settings.KEYWORD_WILDCARD.ToString(), groupKey).ToLower();
}
}
}
}
| |
#if !UNITY_WINRT || UNITY_EDITOR || UNITY_WP8
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#pragma warning disable 436
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Linq;
using System.Runtime.CompilerServices;
namespace Newtonsoft.Json.Serialization
{
internal struct ResolverContractKey : IEquatable<ResolverContractKey>
{
private readonly Type _resolverType;
private readonly Type _contractType;
public ResolverContractKey(Type resolverType, Type contractType)
{
_resolverType = resolverType;
_contractType = contractType;
}
public override int GetHashCode()
{
return _resolverType.GetHashCode() ^ _contractType.GetHashCode();
}
public override bool Equals(object obj)
{
if (!(obj is ResolverContractKey))
return false;
return Equals((ResolverContractKey)obj);
}
public bool Equals(ResolverContractKey other)
{
return (_resolverType == other._resolverType && _contractType == other._contractType);
}
}
/// <summary>
/// Used by <see cref="JsonSerializer"/> to resolves a <see cref="JsonContract"/> for a given <see cref="Type"/>.
/// </summary>
public class DefaultContractResolver : IContractResolver
{
private static readonly IContractResolver _instance = new DefaultContractResolver(true);
internal static IContractResolver Instance
{
get { return _instance; }
}
private static readonly IList<JsonConverter> BuiltInConverters = new List<JsonConverter>
{
new KeyValuePairConverter(),
#if !(UNITY_ANDROID || (UNITY_IOS || UNITY_IPHONE || JSONNET_XMLDISABLE || UNITY_WP8 || UNITY_WINRT))
new XmlNodeConverter(),
#endif
new BsonObjectIdConverter()
};
#if !(UNITY_IOS || UNITY_IPHONE)
private static Dictionary<ResolverContractKey, JsonContract> _sharedContractCache;
private static readonly object _typeContractCacheLock = new object();
private Dictionary<ResolverContractKey, JsonContract> _instanceContractCache;
private readonly bool _sharedCache;
#else
private readonly ThreadSafeStore<Type, JsonContract> _typeContractCache;
#endif
/// <summary>
/// Gets a value indicating whether members are being get and set using dynamic code generation.
/// This value is determined by the runtime permissions available.
/// </summary>
/// <value>
/// <c>true</c> if using dynamic code generation; otherwise, <c>false</c>.
/// </value>
public bool DynamicCodeGeneration
{
get { return JsonTypeReflector.DynamicCodeGeneration; }
}
/// <summary>
/// Gets or sets the default members search flags.
/// </summary>
/// <value>The default members search flags.</value>
public BindingFlags DefaultMembersSearchFlags { get; set; }
/// <summary>
/// Gets or sets a value indicating whether compiler generated members should be serialized.
/// </summary>
/// <value>
/// <c>true</c> if serialized compiler generated members; otherwise, <c>false</c>.
/// </value>
public bool SerializeCompilerGeneratedMembers { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="DefaultContractResolver"/> class.
/// </summary>
public DefaultContractResolver()
: this(false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DefaultContractResolver"/> class.
/// </summary>
/// <param name="shareCache">
/// If set to <c>true</c> the <see cref="DefaultContractResolver"/> will use a cached shared with other resolvers of the same type.
/// Sharing the cache will significantly performance because expensive reflection will only happen once but could cause unexpected
/// behavior if different instances of the resolver are suppose to produce different results. When set to false it is highly
/// recommended to reuse <see cref="DefaultContractResolver"/> instances with the <see cref="JsonSerializer"/>.
/// </param>
public DefaultContractResolver(bool shareCache)
{
DefaultMembersSearchFlags = BindingFlags.Public | BindingFlags.Instance;
#if !(UNITY_IOS || UNITY_IPHONE)
_sharedCache = shareCache;
#else
_typeContractCache = new ThreadSafeStore<Type, JsonContract>(CreateContract);
#endif
}
#if !(UNITY_IOS || UNITY_IPHONE)
private Dictionary<ResolverContractKey, JsonContract> GetCache()
{
if (_sharedCache)
return _sharedContractCache;
else
return _instanceContractCache;
}
private void UpdateCache(Dictionary<ResolverContractKey, JsonContract> cache)
{
if (_sharedCache)
_sharedContractCache = cache;
else
_instanceContractCache = cache;
}
#endif
/// <summary>
/// Resolves the contract for a given type.
/// </summary>
/// <param name="type">The type to resolve a contract for.</param>
/// <returns>The contract for a given type.</returns>
public virtual JsonContract ResolveContract(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
#if (UNITY_IOS || UNITY_IPHONE)
return _typeContractCache.Get(type);
#else
JsonContract contract;
ResolverContractKey key = new ResolverContractKey(GetType(), type);
Dictionary<ResolverContractKey, JsonContract> cache = GetCache();
if (cache == null || !cache.TryGetValue(key, out contract))
{
contract = CreateContract(type);
// avoid the possibility of modifying the cache dictionary while another thread is accessing it
lock (_typeContractCacheLock)
{
cache = GetCache();
Dictionary<ResolverContractKey, JsonContract> updatedCache =
(cache != null)
? new Dictionary<ResolverContractKey, JsonContract>(cache)
: new Dictionary<ResolverContractKey, JsonContract>();
updatedCache[key] = contract;
UpdateCache(updatedCache);
}
}
return contract;
#endif
}
/// <summary>
/// Gets the serializable members for the type.
/// </summary>
/// <param name="objectType">The type to get serializable members for.</param>
/// <returns>The serializable members for the type.</returns>
protected virtual List<MemberInfo> GetSerializableMembers(Type objectType)
{
DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(objectType);
List<MemberInfo> defaultMembers = ReflectionUtils.GetFieldsAndProperties(objectType, DefaultMembersSearchFlags)
.Where(m => !ReflectionUtils.IsIndexedProperty(m)).ToList();
List<MemberInfo> allMembers = ReflectionUtils.GetFieldsAndProperties(objectType, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)
.Where(m => !ReflectionUtils.IsIndexedProperty(m)).ToList();
List<MemberInfo> serializableMembers = new List<MemberInfo>();
foreach (MemberInfo member in allMembers)
{
// exclude members that are compiler generated if set
if (SerializeCompilerGeneratedMembers || !member.IsDefined(typeof(CompilerGeneratedAttribute), true))
{
if (defaultMembers.Contains(member))
{
// add all members that are found by default member search
serializableMembers.Add(member);
}
else
{
// add members that are explicitly marked with JsonProperty/DataMember attribute
if (JsonTypeReflector.GetAttribute<JsonPropertyAttribute>(member) != null)
serializableMembers.Add(member);
else if (dataContractAttribute != null && JsonTypeReflector.GetAttribute<DataMemberAttribute>(member) != null)
serializableMembers.Add(member);
}
}
}
Type match;
// don't include EntityKey on entities objects... this is a bit hacky
if (objectType.AssignableToTypeName("System.Data.Objects.DataClasses.EntityObject", out match))
serializableMembers = serializableMembers.Where(ShouldSerializeEntityMember).ToList();
return serializableMembers;
}
private bool ShouldSerializeEntityMember(MemberInfo memberInfo)
{
PropertyInfo propertyInfo = memberInfo as PropertyInfo;
if (propertyInfo != null)
{
if (propertyInfo.PropertyType.IsGenericType && propertyInfo.PropertyType.GetGenericTypeDefinition().FullName == "System.Data.Objects.DataClasses.EntityReference`1")
return false;
}
return true;
}
/// <summary>
/// Creates a <see cref="JsonObjectContract"/> for the given type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>A <see cref="JsonObjectContract"/> for the given type.</returns>
protected virtual JsonObjectContract CreateObjectContract(Type objectType)
{
JsonObjectContract contract = new JsonObjectContract(objectType);
InitializeContract(contract);
contract.MemberSerialization = JsonTypeReflector.GetObjectMemberSerialization(objectType);
contract.Properties.AddRange(CreateProperties(contract.UnderlyingType, contract.MemberSerialization));
// check if a JsonConstructorAttribute has been defined and use that
if (objectType.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Any(c => c.IsDefined(typeof(JsonConstructorAttribute), true)))
{
ConstructorInfo constructor = GetAttributeConstructor(objectType);
if (constructor != null)
{
contract.OverrideConstructor = constructor;
contract.ConstructorParameters.AddRange(CreateConstructorParameters(constructor, contract.Properties));
}
}
else if (contract.DefaultCreator == null || contract.DefaultCreatorNonPublic)
{
ConstructorInfo constructor = GetParametrizedConstructor(objectType);
if (constructor != null)
{
contract.ParametrizedConstructor = constructor;
contract.ConstructorParameters.AddRange(CreateConstructorParameters(constructor, contract.Properties));
}
}
return contract;
}
private ConstructorInfo GetAttributeConstructor(Type objectType)
{
IList<ConstructorInfo> markedConstructors = objectType.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(c => c.IsDefined(typeof(JsonConstructorAttribute), true)).ToList();
if (markedConstructors.Count > 1)
throw new Exception("Multiple constructors with the JsonConstructorAttribute.");
else if (markedConstructors.Count == 1)
return markedConstructors[0];
return null;
}
private ConstructorInfo GetParametrizedConstructor(Type objectType)
{
IList<ConstructorInfo> constructors = objectType.GetConstructors(BindingFlags.Public | BindingFlags.Instance);
if (constructors.Count == 1)
return constructors[0];
else
return null;
}
/// <summary>
/// Creates the constructor parameters.
/// </summary>
/// <param name="constructor">The constructor to create properties for.</param>
/// <param name="memberProperties">The type's member properties.</param>
/// <returns>Properties for the given <see cref="ConstructorInfo"/>.</returns>
protected virtual IList<JsonProperty> CreateConstructorParameters(ConstructorInfo constructor, JsonPropertyCollection memberProperties)
{
var constructorParameters = constructor.GetParameters();
JsonPropertyCollection parameterCollection = new JsonPropertyCollection(constructor.DeclaringType);
foreach (ParameterInfo parameterInfo in constructorParameters)
{
JsonProperty matchingMemberProperty = memberProperties.GetClosestMatchProperty(parameterInfo.Name);
// type must match as well as name
if (matchingMemberProperty != null && matchingMemberProperty.PropertyType != parameterInfo.ParameterType)
matchingMemberProperty = null;
JsonProperty property = CreatePropertyFromConstructorParameter(matchingMemberProperty, parameterInfo);
if (property != null)
{
parameterCollection.AddProperty(property);
}
}
return parameterCollection;
}
/// <summary>
/// Creates a <see cref="JsonProperty"/> for the given <see cref="ParameterInfo"/>.
/// </summary>
/// <param name="matchingMemberProperty">The matching member property.</param>
/// <param name="parameterInfo">The constructor parameter.</param>
/// <returns>A created <see cref="JsonProperty"/> for the given <see cref="ParameterInfo"/>.</returns>
protected virtual JsonProperty CreatePropertyFromConstructorParameter(JsonProperty matchingMemberProperty, ParameterInfo parameterInfo)
{
JsonProperty property = new JsonProperty();
property.PropertyType = parameterInfo.ParameterType;
bool allowNonPublicAccess;
bool hasExplicitAttribute;
SetPropertySettingsFromAttributes(property, parameterInfo, parameterInfo.Name, parameterInfo.Member.DeclaringType, MemberSerialization.OptOut, out allowNonPublicAccess, out hasExplicitAttribute);
property.Readable = false;
property.Writable = true;
// "inherit" values from matching member property if unset on parameter
if (matchingMemberProperty != null)
{
property.PropertyName = (property.PropertyName != parameterInfo.Name) ? property.PropertyName : matchingMemberProperty.PropertyName;
property.Converter = property.Converter ?? matchingMemberProperty.Converter;
property.MemberConverter = property.MemberConverter ?? matchingMemberProperty.MemberConverter;
property.DefaultValue = property.DefaultValue ?? matchingMemberProperty.DefaultValue;
property.Required = (property.Required != Required.Default) ? property.Required : matchingMemberProperty.Required;
property.IsReference = property.IsReference ?? matchingMemberProperty.IsReference;
property.NullValueHandling = property.NullValueHandling ?? matchingMemberProperty.NullValueHandling;
property.DefaultValueHandling = property.DefaultValueHandling ?? matchingMemberProperty.DefaultValueHandling;
property.ReferenceLoopHandling = property.ReferenceLoopHandling ?? matchingMemberProperty.ReferenceLoopHandling;
property.ObjectCreationHandling = property.ObjectCreationHandling ?? matchingMemberProperty.ObjectCreationHandling;
property.TypeNameHandling = property.TypeNameHandling ?? matchingMemberProperty.TypeNameHandling;
}
return property;
}
/// <summary>
/// Resolves the default <see cref="JsonConverter" /> for the contract.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns></returns>
protected virtual JsonConverter ResolveContractConverter(Type objectType)
{
return JsonTypeReflector.GetJsonConverter(objectType, objectType);
}
private Func<object> GetDefaultCreator(Type createdType)
{
return JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor<object>(createdType);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Portability", "CA1903:UseOnlyApiFromTargetedFramework", MessageId = "System.Runtime.Serialization.DataContractAttribute.#get_IsReference()")]
private void InitializeContract(JsonContract contract)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(contract.UnderlyingType);
if (containerAttribute != null)
{
contract.IsReference = containerAttribute._isReference;
}
else
{
DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(contract.UnderlyingType);
// doesn't have a null value
if (dataContractAttribute != null && dataContractAttribute.IsReference)
contract.IsReference = true;
}
contract.Converter = ResolveContractConverter(contract.UnderlyingType);
// then see whether object is compadible with any of the built in converters
contract.InternalConverter = JsonSerializer.GetMatchingConverter(BuiltInConverters, contract.UnderlyingType);
if (ReflectionUtils.HasDefaultConstructor(contract.CreatedType, true)
|| contract.CreatedType.IsValueType)
{
contract.DefaultCreator = GetDefaultCreator(contract.CreatedType);
contract.DefaultCreatorNonPublic = (!contract.CreatedType.IsValueType &&
ReflectionUtils.GetDefaultConstructor(contract.CreatedType) == null);
}
ResolveCallbackMethods(contract, contract.UnderlyingType);
}
private void ResolveCallbackMethods(JsonContract contract, Type t)
{
if (t.BaseType != null)
ResolveCallbackMethods(contract, t.BaseType);
MethodInfo onSerializing;
MethodInfo onSerialized;
MethodInfo onDeserializing;
MethodInfo onDeserialized;
MethodInfo onError;
GetCallbackMethodsForType(t, out onSerializing, out onSerialized, out onDeserializing, out onDeserialized, out onError);
if (onSerializing != null)
contract.OnSerializing = onSerializing;
if (onSerialized != null)
contract.OnSerialized = onSerialized;
if (onDeserializing != null)
contract.OnDeserializing = onDeserializing;
if (onDeserialized != null)
contract.OnDeserialized = onDeserialized;
if (onError != null)
contract.OnError = onError;
}
private void GetCallbackMethodsForType(Type type, out MethodInfo onSerializing, out MethodInfo onSerialized, out MethodInfo onDeserializing, out MethodInfo onDeserialized, out MethodInfo onError)
{
onSerializing = null;
onSerialized = null;
onDeserializing = null;
onDeserialized = null;
onError = null;
foreach (MethodInfo method in type.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
// compact framework errors when getting parameters for a generic method
// lame, but generic methods should not be callbacks anyway
if (method.ContainsGenericParameters)
continue;
Type prevAttributeType = null;
ParameterInfo[] parameters = method.GetParameters();
if (IsValidCallback(method, parameters, typeof(OnSerializingAttribute), onSerializing, ref prevAttributeType))
{
onSerializing = method;
}
if (IsValidCallback(method, parameters, typeof(OnSerializedAttribute), onSerialized, ref prevAttributeType))
{
onSerialized = method;
}
if (IsValidCallback(method, parameters, typeof(OnDeserializingAttribute), onDeserializing, ref prevAttributeType))
{
onDeserializing = method;
}
if (IsValidCallback(method, parameters, typeof(OnDeserializedAttribute), onDeserialized, ref prevAttributeType))
{
onDeserialized = method;
}
if (IsValidCallback(method, parameters, typeof(OnErrorAttribute), onError, ref prevAttributeType))
{
onError = method;
}
}
}
/// <summary>
/// Creates a <see cref="JsonDictionaryContract"/> for the given type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>A <see cref="JsonDictionaryContract"/> for the given type.</returns>
protected virtual JsonDictionaryContract CreateDictionaryContract(Type objectType)
{
JsonDictionaryContract contract = new JsonDictionaryContract(objectType);
InitializeContract(contract);
contract.PropertyNameResolver = ResolvePropertyName;
return contract;
}
/// <summary>
/// Creates a <see cref="JsonArrayContract"/> for the given type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>A <see cref="JsonArrayContract"/> for the given type.</returns>
protected virtual JsonArrayContract CreateArrayContract(Type objectType)
{
JsonArrayContract contract = new JsonArrayContract(objectType);
InitializeContract(contract);
return contract;
}
/// <summary>
/// Creates a <see cref="JsonPrimitiveContract"/> for the given type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>A <see cref="JsonPrimitiveContract"/> for the given type.</returns>
protected virtual JsonPrimitiveContract CreatePrimitiveContract(Type objectType)
{
JsonPrimitiveContract contract = new JsonPrimitiveContract(objectType);
InitializeContract(contract);
return contract;
}
/// <summary>
/// Creates a <see cref="JsonLinqContract"/> for the given type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>A <see cref="JsonLinqContract"/> for the given type.</returns>
protected virtual JsonLinqContract CreateLinqContract(Type objectType)
{
JsonLinqContract contract = new JsonLinqContract(objectType);
InitializeContract(contract);
return contract;
}
#if !((UNITY_WINRT && !UNITY_EDITOR) || UNITY_WP8)
/// <summary>
/// Creates a <see cref="JsonISerializableContract"/> for the given type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>A <see cref="JsonISerializableContract"/> for the given type.</returns>
protected virtual JsonISerializableContract CreateISerializableContract(Type objectType)
{
JsonISerializableContract contract = new JsonISerializableContract(objectType);
InitializeContract(contract);
ConstructorInfo constructorInfo = objectType.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(SerializationInfo), typeof(StreamingContext) }, null);
if (constructorInfo != null)
{
MethodCall<object, object> methodCall = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(constructorInfo);
contract.ISerializableCreator = (args => methodCall(null, args));
}
return contract;
}
#endif
/// <summary>
/// Creates a <see cref="JsonStringContract"/> for the given type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>A <see cref="JsonStringContract"/> for the given type.</returns>
protected virtual JsonStringContract CreateStringContract(Type objectType)
{
JsonStringContract contract = new JsonStringContract(objectType);
InitializeContract(contract);
return contract;
}
/// <summary>
/// Determines which contract type is created for the given type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>A <see cref="JsonContract"/> for the given type.</returns>
protected virtual JsonContract CreateContract(Type objectType)
{
Type t = ReflectionUtils.EnsureNotNullableType(objectType);
if (JsonConvert.IsJsonPrimitiveType(t))
return CreatePrimitiveContract(t);
if (JsonTypeReflector.GetJsonObjectAttribute(t) != null)
return CreateObjectContract(t);
if (JsonTypeReflector.GetJsonArrayAttribute(t) != null)
return CreateArrayContract(t);
if (t == typeof(JToken) || t.IsSubclassOf(typeof(JToken)))
return CreateLinqContract(t);
if (CollectionUtils.IsDictionaryType(t))
return CreateDictionaryContract(t);
if (typeof(IEnumerable).IsAssignableFrom(t))
return CreateArrayContract(t);
if (CanConvertToString(t))
return CreateStringContract(t);
#if !((UNITY_WINRT && !UNITY_EDITOR) || UNITY_WP8)
if (typeof(ISerializable).IsAssignableFrom(t))
return CreateISerializableContract(t);
#endif
return CreateObjectContract(t);
}
internal static bool CanConvertToString(Type type)
{
#if !UNITY_WP8
TypeConverter converter = ConvertUtils.GetConverter(type);
// use the objectType's TypeConverter if it has one and can convert to a string
if (converter != null
#if !UNITY_WP8
&& !(converter is ComponentConverter)
&& !(converter is ReferenceConverter)
#endif
&& converter.GetType() != typeof(TypeConverter))
{
if (converter.CanConvertTo(typeof(string)))
return true;
}
#endif
if (type == typeof(Type) || type.IsSubclassOf(typeof(Type)))
return true;
#if UNITY_WP8
if (type == typeof(Guid) || type == typeof(Uri) || type == typeof(TimeSpan))
return true;
#endif
return false;
}
private static bool IsValidCallback(MethodInfo method, ParameterInfo[] parameters, Type attributeType, MethodInfo currentCallback, ref Type prevAttributeType)
{
if (!method.IsDefined(attributeType, false))
return false;
if (currentCallback != null)
throw new Exception("Invalid attribute. Both '{0}' and '{1}' in type '{2}' have '{3}'.".FormatWith(CultureInfo.InvariantCulture, method, currentCallback, GetClrTypeFullName(method.DeclaringType), attributeType));
if (prevAttributeType != null)
throw new Exception("Invalid Callback. Method '{3}' in type '{2}' has both '{0}' and '{1}'.".FormatWith(CultureInfo.InvariantCulture, prevAttributeType, attributeType, GetClrTypeFullName(method.DeclaringType), method));
if (method.IsVirtual)
throw new Exception("Virtual Method '{0}' of type '{1}' cannot be marked with '{2}' attribute.".FormatWith(CultureInfo.InvariantCulture, method, GetClrTypeFullName(method.DeclaringType), attributeType));
if (method.ReturnType != typeof(void))
throw new Exception("Serialization Callback '{1}' in type '{0}' must return void.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method));
if (attributeType == typeof(OnErrorAttribute))
{
if (parameters == null || parameters.Length != 2 || parameters[0].ParameterType != typeof(StreamingContext) || parameters[1].ParameterType != typeof(ErrorContext))
throw new Exception("Serialization Error Callback '{1}' in type '{0}' must have two parameters of type '{2}' and '{3}'.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method, typeof(StreamingContext), typeof(ErrorContext)));
}
else
{
if (parameters == null || parameters.Length != 1 || parameters[0].ParameterType != typeof(StreamingContext))
throw new Exception("Serialization Callback '{1}' in type '{0}' must have a single parameter of type '{2}'.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method, typeof(StreamingContext)));
}
prevAttributeType = attributeType;
return true;
}
internal static string GetClrTypeFullName(Type type)
{
if (type.IsGenericTypeDefinition || !type.ContainsGenericParameters)
return type.FullName;
return string.Format(CultureInfo.InvariantCulture, "{0}.{1}", new object[] { type.Namespace, type.Name });
}
/// <summary>
/// Creates properties for the given <see cref="JsonContract"/>.
/// </summary>
/// <param name="type">The type to create properties for.</param>
/// /// <param name="memberSerialization">The member serialization mode for the type.</param>
/// <returns>Properties for the given <see cref="JsonContract"/>.</returns>
protected virtual IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
List<MemberInfo> members = GetSerializableMembers(type);
if (members == null)
throw new JsonSerializationException("Null collection of seralizable members returned.");
JsonPropertyCollection properties = new JsonPropertyCollection(type);
foreach (MemberInfo member in members)
{
JsonProperty property = CreateProperty(member, memberSerialization);
if (property != null)
properties.AddProperty(property);
}
IList<JsonProperty> orderedProperties = properties.OrderBy(p => p.Order ?? -1).ToList();
return orderedProperties;
}
/// <summary>
/// Creates the <see cref="IValueProvider"/> used by the serializer to get and set values from a member.
/// </summary>
/// <param name="member">The member.</param>
/// <returns>The <see cref="IValueProvider"/> used by the serializer to get and set values from a member.</returns>
protected virtual IValueProvider CreateMemberValueProvider(MemberInfo member)
{
if (DynamicCodeGeneration)
return new DynamicValueProvider(member);
return new ReflectionValueProvider(member);
}
/// <summary>
/// Creates a <see cref="JsonProperty"/> for the given <see cref="MemberInfo"/>.
/// </summary>
/// <param name="memberSerialization">The member's parent <see cref="MemberSerialization"/>.</param>
/// <param name="member">The member to create a <see cref="JsonProperty"/> for.</param>
/// <returns>A created <see cref="JsonProperty"/> for the given <see cref="MemberInfo"/>.</returns>
protected virtual JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = new JsonProperty();
property.PropertyType = ReflectionUtils.GetMemberUnderlyingType(member);
property.ValueProvider = CreateMemberValueProvider(member);
bool allowNonPublicAccess;
bool hasExplicitAttribute;
SetPropertySettingsFromAttributes(property, member, member.Name, member.DeclaringType, memberSerialization, out allowNonPublicAccess, out hasExplicitAttribute);
property.Readable = ReflectionUtils.CanReadMemberValue(member, allowNonPublicAccess);
property.Writable = ReflectionUtils.CanSetMemberValue(member, allowNonPublicAccess, hasExplicitAttribute);
property.ShouldSerialize = CreateShouldSerializeTest(member);
SetIsSpecifiedActions(property, member, allowNonPublicAccess);
return property;
}
private void SetPropertySettingsFromAttributes(JsonProperty property, ICustomAttributeProvider attributeProvider, string name, Type declaringType, MemberSerialization memberSerialization, out bool allowNonPublicAccess, out bool hasExplicitAttribute)
{
hasExplicitAttribute = false;
DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(declaringType);
DataMemberAttribute dataMemberAttribute;
if (dataContractAttribute != null && attributeProvider is MemberInfo)
dataMemberAttribute = JsonTypeReflector.GetDataMemberAttribute((MemberInfo)attributeProvider);
else
dataMemberAttribute = null;
JsonPropertyAttribute propertyAttribute = JsonTypeReflector.GetAttribute<JsonPropertyAttribute>(attributeProvider);
if (propertyAttribute != null)
hasExplicitAttribute = true;
bool hasIgnoreAttribute = (JsonTypeReflector.GetAttribute<JsonIgnoreAttribute>(attributeProvider) != null);
string mappedName;
if (propertyAttribute != null && propertyAttribute.PropertyName != null)
mappedName = propertyAttribute.PropertyName;
else if (dataMemberAttribute != null && dataMemberAttribute.Name != null)
mappedName = dataMemberAttribute.Name;
else
mappedName = name;
property.PropertyName = ResolvePropertyName(mappedName);
property.UnderlyingName = name;
if (propertyAttribute != null)
{
property.Required = propertyAttribute.Required;
property.Order = propertyAttribute._order;
}
else if (dataMemberAttribute != null)
{
property.Required = (dataMemberAttribute.IsRequired) ? Required.AllowNull : Required.Default;
property.Order = (dataMemberAttribute.Order != -1) ? (int?)dataMemberAttribute.Order : null;
}
else
{
property.Required = Required.Default;
}
property.Ignored = (hasIgnoreAttribute ||
(memberSerialization == MemberSerialization.OptIn
&& propertyAttribute == null
&& dataMemberAttribute == null
));
// resolve converter for property
// the class type might have a converter but the property converter takes presidence
property.Converter = JsonTypeReflector.GetJsonConverter(attributeProvider, property.PropertyType);
property.MemberConverter = JsonTypeReflector.GetJsonConverter(attributeProvider, property.PropertyType);
DefaultValueAttribute defaultValueAttribute = JsonTypeReflector.GetAttribute<DefaultValueAttribute>(attributeProvider);
property.DefaultValue = (defaultValueAttribute != null) ? defaultValueAttribute.Value : null;
property.NullValueHandling = (propertyAttribute != null) ? propertyAttribute._nullValueHandling : null;
property.DefaultValueHandling = (propertyAttribute != null) ? propertyAttribute._defaultValueHandling : null;
property.ReferenceLoopHandling = (propertyAttribute != null) ? propertyAttribute._referenceLoopHandling : null;
property.ObjectCreationHandling = (propertyAttribute != null) ? propertyAttribute._objectCreationHandling : null;
property.TypeNameHandling = (propertyAttribute != null) ? propertyAttribute._typeNameHandling : null;
property.IsReference = (propertyAttribute != null) ? propertyAttribute._isReference : null;
allowNonPublicAccess = false;
if ((DefaultMembersSearchFlags & BindingFlags.NonPublic) == BindingFlags.NonPublic)
allowNonPublicAccess = true;
if (propertyAttribute != null)
allowNonPublicAccess = true;
if (dataMemberAttribute != null)
{
allowNonPublicAccess = true;
hasExplicitAttribute = true;
}
}
private Predicate<object> CreateShouldSerializeTest(MemberInfo member)
{
MethodInfo shouldSerializeMethod = member.DeclaringType.GetMethod(JsonTypeReflector.ShouldSerializePrefix + member.Name, new Type[0]);
if (shouldSerializeMethod == null || shouldSerializeMethod.ReturnType != typeof(bool))
return null;
MethodCall<object, object> shouldSerializeCall =
JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(shouldSerializeMethod);
return o => (bool)shouldSerializeCall(o);
}
private void SetIsSpecifiedActions(JsonProperty property, MemberInfo member, bool allowNonPublicAccess)
{
MemberInfo specifiedMember = member.DeclaringType.GetProperty(member.Name + JsonTypeReflector.SpecifiedPostfix);
if (specifiedMember == null)
specifiedMember = member.DeclaringType.GetField(member.Name + JsonTypeReflector.SpecifiedPostfix);
if (specifiedMember == null || ReflectionUtils.GetMemberUnderlyingType(specifiedMember) != typeof(bool))
{
return;
}
Func<object, object> specifiedPropertyGet = JsonTypeReflector.ReflectionDelegateFactory.CreateGet<object>(specifiedMember);
property.GetIsSpecified = o => (bool)specifiedPropertyGet(o);
if (ReflectionUtils.CanSetMemberValue(specifiedMember, allowNonPublicAccess, false))
property.SetIsSpecified = JsonTypeReflector.ReflectionDelegateFactory.CreateSet<object>(specifiedMember);
}
/// <summary>
/// Resolves the name of the property.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
/// <returns>Name of the property.</returns>
protected internal virtual string ResolvePropertyName(string propertyName)
{
return propertyName;
}
}
}
#pragma warning restore 436
#endif
| |
namespace EIDSS.Reports.Document.Lim.Case
{
partial class TestReport
{
#region 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(TestReport));
this.DetailReportTest = new DevExpress.XtraReports.UI.DetailReportBand();
this.DetailTest = new DevExpress.XtraReports.UI.DetailBand();
this.DetailTable = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell391 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell51 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell52 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow8 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTable5 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow5 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow10 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell22 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell39 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell40 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell41 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell42 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell43 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell44 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell45 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell46 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell47 = new DevExpress.XtraReports.UI.XRTableCell();
this.ExternalOrganizationTable = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow9 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow11 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow12 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell48 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell49 = new DevExpress.XtraReports.UI.XRTableCell();
this.ReportHeaderTest = new DevExpress.XtraReports.UI.ReportHeaderBand();
this.VetHeaderTable = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow14 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell53 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow15 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell54 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow16 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell55 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell56 = new DevExpress.XtraReports.UI.XRTableCell();
this.VetBarcodeCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell59 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell60 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell61 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell62 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow17 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell63 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell64 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell65 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell66 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell67 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell68 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow18 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell69 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell70 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell71 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell72 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell73 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell74 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell75 = new DevExpress.XtraReports.UI.XRTableCell();
this.HumanHeaderTable = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow13 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell50 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow4 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell57 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell26 = new DevExpress.XtraReports.UI.XRTableCell();
this.HumanBarcodeCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell25 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell27 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell28 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow6 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell30 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell31 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell32 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell33 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell24 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow7 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell101 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell34 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell35 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell36 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell37 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell38 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell29 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrLabel3 = new DevExpress.XtraReports.UI.XRLabel();
this.ReportFooter = new DevExpress.XtraReports.UI.ReportFooterBand();
this.m_Adapter = new EIDSS.Reports.Document.Lim.Case.CaseTestDataSetTableAdapters.CaseTestsAdapter();
this.m_DataSet = new EIDSS.Reports.Document.Lim.Case.CaseTestDataSet();
this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell();
this.DetailReport = new DevExpress.XtraReports.UI.DetailReportBand();
this.Detail1 = new DevExpress.XtraReports.UI.DetailBand();
this.xrSubreport1 = new DevExpress.XtraReports.UI.XRSubreport();
((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.DetailTable)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable5)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.ExternalOrganizationTable)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.VetHeaderTable)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.HumanHeaderTable)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.m_DataSet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// cellLanguage
//
this.cellLanguage.StylePriority.UseTextAlignment = false;
//
// lblReportName
//
resources.ApplyResources(this.lblReportName, "lblReportName");
this.lblReportName.StylePriority.UseBorders = false;
this.lblReportName.StylePriority.UseBorderWidth = false;
this.lblReportName.StylePriority.UseFont = false;
this.lblReportName.StylePriority.UseTextAlignment = false;
//
// Detail
//
this.Detail.Expanded = false;
this.Detail.StylePriority.UseFont = false;
this.Detail.StylePriority.UsePadding = false;
//
// PageHeader
//
this.PageHeader.Expanded = false;
this.PageHeader.StylePriority.UseFont = false;
this.PageHeader.StylePriority.UsePadding = false;
//
// PageFooter
//
resources.ApplyResources(this.PageFooter, "PageFooter");
this.PageFooter.StylePriority.UseBorders = false;
//
// ReportHeader
//
resources.ApplyResources(this.ReportHeader, "ReportHeader");
//
// xrPageInfo1
//
resources.ApplyResources(this.xrPageInfo1, "xrPageInfo1");
this.xrPageInfo1.StylePriority.UseBorders = false;
//
// cellReportHeader
//
this.cellReportHeader.StylePriority.UseBorders = false;
this.cellReportHeader.StylePriority.UseFont = false;
this.cellReportHeader.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.cellReportHeader, "cellReportHeader");
//
// cellBaseSite
//
this.cellBaseSite.StylePriority.UseBorders = false;
this.cellBaseSite.StylePriority.UseFont = false;
this.cellBaseSite.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.cellBaseSite, "cellBaseSite");
//
// cellBaseCountry
//
resources.ApplyResources(this.cellBaseCountry, "cellBaseCountry");
//
// cellBaseLeftHeader
//
resources.ApplyResources(this.cellBaseLeftHeader, "cellBaseLeftHeader");
//
// tableBaseHeader
//
resources.ApplyResources(this.tableBaseHeader, "tableBaseHeader");
this.tableBaseHeader.StylePriority.UseBorders = false;
this.tableBaseHeader.StylePriority.UseBorderWidth = false;
this.tableBaseHeader.StylePriority.UseFont = false;
this.tableBaseHeader.StylePriority.UsePadding = false;
this.tableBaseHeader.StylePriority.UseTextAlignment = false;
//
// DetailReportTest
//
this.DetailReportTest.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.DetailTest,
this.ReportHeaderTest,
this.ReportFooter});
this.DetailReportTest.DataAdapter = this.m_Adapter;
this.DetailReportTest.DataMember = "CaseTests";
this.DetailReportTest.DataSource = this.m_DataSet;
resources.ApplyResources(this.DetailReportTest, "DetailReportTest");
this.DetailReportTest.Level = 0;
this.DetailReportTest.Name = "DetailReportTest";
this.DetailReportTest.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F);
//
// DetailTest
//
this.DetailTest.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.DetailTest.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.DetailTable,
this.ExternalOrganizationTable});
resources.ApplyResources(this.DetailTest, "DetailTest");
this.DetailTest.Name = "DetailTest";
this.DetailTest.StylePriority.UseBorders = false;
this.DetailTest.StylePriority.UseTextAlignment = false;
//
// DetailTable
//
this.DetailTable.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.DetailTable.KeepTogether = true;
resources.ApplyResources(this.DetailTable, "DetailTable");
this.DetailTable.Name = "DetailTable";
this.DetailTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow1,
this.xrTableRow8});
this.DetailTable.StylePriority.UseBorders = false;
//
// xrTableRow1
//
this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell4,
this.xrTableCell391,
this.xrTableCell51,
this.xrTableCell1,
this.xrTableCell6,
this.xrTableCell52,
this.xrTableCell2,
this.xrTableCell8,
this.xrTableCell9,
this.xrTableCell3});
this.xrTableRow1.Name = "xrTableRow1";
resources.ApplyResources(this.xrTableRow1, "xrTableRow1");
//
// xrTableCell4
//
this.xrTableCell4.Multiline = true;
this.xrTableCell4.Name = "xrTableCell4";
resources.ApplyResources(this.xrTableCell4, "xrTableCell4");
this.xrTableCell4.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.xrTableCell4_BeforePrint);
//
// xrTableCell391
//
this.xrTableCell391.Name = "xrTableCell391";
resources.ApplyResources(this.xrTableCell391, "xrTableCell391");
//
// xrTableCell51
//
this.xrTableCell51.Name = "xrTableCell51";
resources.ApplyResources(this.xrTableCell51, "xrTableCell51");
//
// xrTableCell1
//
this.xrTableCell1.Name = "xrTableCell1";
resources.ApplyResources(this.xrTableCell1, "xrTableCell1");
//
// xrTableCell6
//
this.xrTableCell6.Angle = 90F;
this.xrTableCell6.Name = "xrTableCell6";
resources.ApplyResources(this.xrTableCell6, "xrTableCell6");
//
// xrTableCell52
//
this.xrTableCell52.Angle = 90F;
this.xrTableCell52.Name = "xrTableCell52";
resources.ApplyResources(this.xrTableCell52, "xrTableCell52");
//
// xrTableCell2
//
this.xrTableCell2.Name = "xrTableCell2";
resources.ApplyResources(this.xrTableCell2, "xrTableCell2");
//
// xrTableCell8
//
this.xrTableCell8.Name = "xrTableCell8";
resources.ApplyResources(this.xrTableCell8, "xrTableCell8");
//
// xrTableCell9
//
this.xrTableCell9.Name = "xrTableCell9";
resources.ApplyResources(this.xrTableCell9, "xrTableCell9");
//
// xrTableCell3
//
this.xrTableCell3.Name = "xrTableCell3";
resources.ApplyResources(this.xrTableCell3, "xrTableCell3");
//
// xrTableRow8
//
this.xrTableRow8.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell7,
this.xrTableCell39,
this.xrTableCell40,
this.xrTableCell41,
this.xrTableCell42,
this.xrTableCell43,
this.xrTableCell44,
this.xrTableCell45,
this.xrTableCell46,
this.xrTableCell47});
this.xrTableRow8.Name = "xrTableRow8";
resources.ApplyResources(this.xrTableRow8, "xrTableRow8");
//
// xrTableCell7
//
this.xrTableCell7.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable5});
this.xrTableCell7.Name = "xrTableCell7";
resources.ApplyResources(this.xrTableCell7, "xrTableCell7");
//
// xrTable5
//
this.xrTable5.Borders = DevExpress.XtraPrinting.BorderSide.None;
resources.ApplyResources(this.xrTable5, "xrTable5");
this.xrTable5.Name = "xrTable5";
this.xrTable5.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow5,
this.xrTableRow10});
this.xrTable5.StylePriority.UseBorders = false;
//
// xrTableRow5
//
this.xrTableRow5.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell21});
this.xrTableRow5.Name = "xrTableRow5";
resources.ApplyResources(this.xrTableRow5, "xrTableRow5");
//
// xrTableCell21
//
this.xrTableCell21.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Right | DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableCell21.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "CaseTests.strLocalSampleID")});
this.xrTableCell21.Name = "xrTableCell21";
this.xrTableCell21.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell21, "xrTableCell21");
//
// xrTableRow10
//
this.xrTableRow10.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell22});
this.xrTableRow10.Name = "xrTableRow10";
resources.ApplyResources(this.xrTableRow10, "xrTableRow10");
//
// xrTableCell22
//
this.xrTableCell22.Borders = DevExpress.XtraPrinting.BorderSide.Right;
this.xrTableCell22.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "CaseTests.strLabSampleID")});
this.xrTableCell22.Name = "xrTableCell22";
this.xrTableCell22.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell22, "xrTableCell22");
//
// xrTableCell39
//
this.xrTableCell39.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "CaseTests.strSampleType")});
this.xrTableCell39.Name = "xrTableCell39";
resources.ApplyResources(this.xrTableCell39, "xrTableCell39");
//
// xrTableCell40
//
this.xrTableCell40.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "CaseTests.strTestDiagnosis")});
this.xrTableCell40.Name = "xrTableCell40";
resources.ApplyResources(this.xrTableCell40, "xrTableCell40");
//
// xrTableCell41
//
this.xrTableCell41.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "CaseTests.strTestName")});
this.xrTableCell41.Name = "xrTableCell41";
resources.ApplyResources(this.xrTableCell41, "xrTableCell41");
//
// xrTableCell42
//
this.xrTableCell42.Angle = 90F;
this.xrTableCell42.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "CaseTests.strTestRunID")});
this.xrTableCell42.Name = "xrTableCell42";
resources.ApplyResources(this.xrTableCell42, "xrTableCell42");
//
// xrTableCell43
//
this.xrTableCell43.Angle = 90F;
this.xrTableCell43.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "CaseTests.datResultDate", "{0:dd/MM/yyyy}")});
this.xrTableCell43.Name = "xrTableCell43";
resources.ApplyResources(this.xrTableCell43, "xrTableCell43");
//
// xrTableCell44
//
this.xrTableCell44.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "CaseTests.strFunctionalArea")});
this.xrTableCell44.Name = "xrTableCell44";
resources.ApplyResources(this.xrTableCell44, "xrTableCell44");
//
// xrTableCell45
//
this.xrTableCell45.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "CaseTests.strTestCategory")});
this.xrTableCell45.Name = "xrTableCell45";
resources.ApplyResources(this.xrTableCell45, "xrTableCell45");
//
// xrTableCell46
//
this.xrTableCell46.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "CaseTests.strTestStatus")});
this.xrTableCell46.Name = "xrTableCell46";
resources.ApplyResources(this.xrTableCell46, "xrTableCell46");
//
// xrTableCell47
//
this.xrTableCell47.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "CaseTests.strTestResult")});
this.xrTableCell47.Name = "xrTableCell47";
resources.ApplyResources(this.xrTableCell47, "xrTableCell47");
//
// ExternalOrganizationTable
//
this.ExternalOrganizationTable.Borders = DevExpress.XtraPrinting.BorderSide.None;
this.ExternalOrganizationTable.KeepTogether = true;
resources.ApplyResources(this.ExternalOrganizationTable, "ExternalOrganizationTable");
this.ExternalOrganizationTable.Name = "ExternalOrganizationTable";
this.ExternalOrganizationTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow2,
this.xrTableRow9,
this.xrTableRow11,
this.xrTableRow12});
this.ExternalOrganizationTable.StylePriority.UseBorders = false;
this.ExternalOrganizationTable.StylePriority.UseTextAlignment = false;
//
// xrTableRow2
//
this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell11});
this.xrTableRow2.Name = "xrTableRow2";
resources.ApplyResources(this.xrTableRow2, "xrTableRow2");
//
// xrTableCell11
//
resources.ApplyResources(this.xrTableCell11, "xrTableCell11");
this.xrTableCell11.Name = "xrTableCell11";
this.xrTableCell11.StylePriority.UseFont = false;
//
// xrTableRow9
//
this.xrTableRow9.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell12,
this.xrTableCell13,
this.xrTableCell14});
this.xrTableRow9.Name = "xrTableRow9";
resources.ApplyResources(this.xrTableRow9, "xrTableRow9");
//
// xrTableCell12
//
this.xrTableCell12.Name = "xrTableCell12";
resources.ApplyResources(this.xrTableCell12, "xrTableCell12");
//
// xrTableCell13
//
this.xrTableCell13.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell13.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "CaseTests.strExternalLaboratory")});
this.xrTableCell13.Name = "xrTableCell13";
this.xrTableCell13.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell13, "xrTableCell13");
//
// xrTableCell14
//
this.xrTableCell14.Name = "xrTableCell14";
resources.ApplyResources(this.xrTableCell14, "xrTableCell14");
//
// xrTableRow11
//
this.xrTableRow11.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell15,
this.xrTableCell16,
this.xrTableCell17});
this.xrTableRow11.Name = "xrTableRow11";
resources.ApplyResources(this.xrTableRow11, "xrTableRow11");
//
// xrTableCell15
//
this.xrTableCell15.Name = "xrTableCell15";
resources.ApplyResources(this.xrTableCell15, "xrTableCell15");
//
// xrTableCell16
//
this.xrTableCell16.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell16.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "CaseTests.strExternalEmployee")});
this.xrTableCell16.Name = "xrTableCell16";
this.xrTableCell16.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell16, "xrTableCell16");
//
// xrTableCell17
//
this.xrTableCell17.Name = "xrTableCell17";
resources.ApplyResources(this.xrTableCell17, "xrTableCell17");
//
// xrTableRow12
//
this.xrTableRow12.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell18,
this.xrTableCell48,
this.xrTableCell49});
this.xrTableRow12.Name = "xrTableRow12";
resources.ApplyResources(this.xrTableRow12, "xrTableRow12");
//
// xrTableCell18
//
this.xrTableCell18.Name = "xrTableCell18";
resources.ApplyResources(this.xrTableCell18, "xrTableCell18");
//
// xrTableCell48
//
this.xrTableCell48.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell48.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "CaseTests.strExternalDataTestResultReceived")});
this.xrTableCell48.Name = "xrTableCell48";
this.xrTableCell48.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell48, "xrTableCell48");
//
// xrTableCell49
//
this.xrTableCell49.Name = "xrTableCell49";
resources.ApplyResources(this.xrTableCell49, "xrTableCell49");
//
// ReportHeaderTest
//
this.ReportHeaderTest.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.VetHeaderTable,
this.HumanHeaderTable,
this.xrLabel3});
resources.ApplyResources(this.ReportHeaderTest, "ReportHeaderTest");
this.ReportHeaderTest.Name = "ReportHeaderTest";
this.ReportHeaderTest.StylePriority.UseBorders = false;
this.ReportHeaderTest.StylePriority.UseFont = false;
this.ReportHeaderTest.StylePriority.UseTextAlignment = false;
//
// VetHeaderTable
//
this.VetHeaderTable.KeepTogether = true;
resources.ApplyResources(this.VetHeaderTable, "VetHeaderTable");
this.VetHeaderTable.Name = "VetHeaderTable";
this.VetHeaderTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow14,
this.xrTableRow15,
this.xrTableRow16,
this.xrTableRow17,
this.xrTableRow18});
this.VetHeaderTable.StylePriority.UseTextAlignment = false;
//
// xrTableRow14
//
this.xrTableRow14.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell53});
this.xrTableRow14.Name = "xrTableRow14";
resources.ApplyResources(this.xrTableRow14, "xrTableRow14");
//
// xrTableCell53
//
this.xrTableCell53.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.xrTableCell53, "xrTableCell53");
this.xrTableCell53.Name = "xrTableCell53";
this.xrTableCell53.StylePriority.UseBorders = false;
this.xrTableCell53.StylePriority.UseFont = false;
this.xrTableCell53.StylePriority.UseTextAlignment = false;
//
// xrTableRow15
//
this.xrTableRow15.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell54});
this.xrTableRow15.Name = "xrTableRow15";
resources.ApplyResources(this.xrTableRow15, "xrTableRow15");
//
// xrTableCell54
//
this.xrTableCell54.Name = "xrTableCell54";
resources.ApplyResources(this.xrTableCell54, "xrTableCell54");
//
// xrTableRow16
//
this.xrTableRow16.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell55,
this.xrTableCell56,
this.VetBarcodeCell,
this.xrTableCell59,
this.xrTableCell60,
this.xrTableCell61,
this.xrTableCell62});
this.xrTableRow16.Name = "xrTableRow16";
resources.ApplyResources(this.xrTableRow16, "xrTableRow16");
//
// xrTableCell55
//
this.xrTableCell55.Name = "xrTableCell55";
resources.ApplyResources(this.xrTableCell55, "xrTableCell55");
//
// xrTableCell56
//
this.xrTableCell56.Name = "xrTableCell56";
this.xrTableCell56.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell56, "xrTableCell56");
//
// VetBarcodeCell
//
resources.ApplyResources(this.VetBarcodeCell, "VetBarcodeCell");
this.VetBarcodeCell.Name = "VetBarcodeCell";
this.VetBarcodeCell.StylePriority.UseFont = false;
this.VetBarcodeCell.StylePriority.UseTextAlignment = false;
//
// xrTableCell59
//
this.xrTableCell59.Name = "xrTableCell59";
resources.ApplyResources(this.xrTableCell59, "xrTableCell59");
//
// xrTableCell60
//
this.xrTableCell60.Name = "xrTableCell60";
resources.ApplyResources(this.xrTableCell60, "xrTableCell60");
//
// xrTableCell61
//
this.xrTableCell61.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell61.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "CaseTests.strVetFarmOwner")});
this.xrTableCell61.Name = "xrTableCell61";
this.xrTableCell61.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell61, "xrTableCell61");
//
// xrTableCell62
//
this.xrTableCell62.Name = "xrTableCell62";
resources.ApplyResources(this.xrTableCell62, "xrTableCell62");
//
// xrTableRow17
//
this.xrTableRow17.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell63,
this.xrTableCell64,
this.xrTableCell65,
this.xrTableCell66,
this.xrTableCell67,
this.xrTableCell68});
this.xrTableRow17.Name = "xrTableRow17";
resources.ApplyResources(this.xrTableRow17, "xrTableRow17");
//
// xrTableCell63
//
this.xrTableCell63.Name = "xrTableCell63";
resources.ApplyResources(this.xrTableCell63, "xrTableCell63");
//
// xrTableCell64
//
this.xrTableCell64.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "CaseTests.strVetCaseId")});
this.xrTableCell64.Name = "xrTableCell64";
this.xrTableCell64.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell64, "xrTableCell64");
//
// xrTableCell65
//
this.xrTableCell65.Name = "xrTableCell65";
resources.ApplyResources(this.xrTableCell65, "xrTableCell65");
//
// xrTableCell66
//
this.xrTableCell66.Name = "xrTableCell66";
resources.ApplyResources(this.xrTableCell66, "xrTableCell66");
//
// xrTableCell67
//
this.xrTableCell67.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell67.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "CaseTests.strVetDiagnoses")});
this.xrTableCell67.Name = "xrTableCell67";
this.xrTableCell67.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell67, "xrTableCell67");
//
// xrTableCell68
//
this.xrTableCell68.Name = "xrTableCell68";
resources.ApplyResources(this.xrTableCell68, "xrTableCell68");
//
// xrTableRow18
//
this.xrTableRow18.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell69,
this.xrTableCell70,
this.xrTableCell71,
this.xrTableCell72,
this.xrTableCell73,
this.xrTableCell74,
this.xrTableCell75});
this.xrTableRow18.Name = "xrTableRow18";
resources.ApplyResources(this.xrTableRow18, "xrTableRow18");
//
// xrTableCell69
//
this.xrTableCell69.Name = "xrTableCell69";
resources.ApplyResources(this.xrTableCell69, "xrTableCell69");
//
// xrTableCell70
//
this.xrTableCell70.Name = "xrTableCell70";
resources.ApplyResources(this.xrTableCell70, "xrTableCell70");
//
// xrTableCell71
//
this.xrTableCell71.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell71.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "CaseTests.strVetCaseStatus")});
this.xrTableCell71.Name = "xrTableCell71";
this.xrTableCell71.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell71, "xrTableCell71");
//
// xrTableCell72
//
this.xrTableCell72.Name = "xrTableCell72";
resources.ApplyResources(this.xrTableCell72, "xrTableCell72");
//
// xrTableCell73
//
this.xrTableCell73.Name = "xrTableCell73";
resources.ApplyResources(this.xrTableCell73, "xrTableCell73");
//
// xrTableCell74
//
this.xrTableCell74.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell74.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "CaseTests.strVetCaseClassification")});
this.xrTableCell74.Name = "xrTableCell74";
this.xrTableCell74.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell74, "xrTableCell74");
//
// xrTableCell75
//
this.xrTableCell75.Name = "xrTableCell75";
resources.ApplyResources(this.xrTableCell75, "xrTableCell75");
//
// HumanHeaderTable
//
this.HumanHeaderTable.KeepTogether = true;
resources.ApplyResources(this.HumanHeaderTable, "HumanHeaderTable");
this.HumanHeaderTable.Name = "HumanHeaderTable";
this.HumanHeaderTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow3,
this.xrTableRow13,
this.xrTableRow4,
this.xrTableRow6,
this.xrTableRow7});
this.HumanHeaderTable.StylePriority.UseTextAlignment = false;
//
// xrTableRow3
//
this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell19});
this.xrTableRow3.Name = "xrTableRow3";
resources.ApplyResources(this.xrTableRow3, "xrTableRow3");
//
// xrTableCell19
//
this.xrTableCell19.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.xrTableCell19, "xrTableCell19");
this.xrTableCell19.Name = "xrTableCell19";
this.xrTableCell19.StylePriority.UseBorders = false;
this.xrTableCell19.StylePriority.UseFont = false;
this.xrTableCell19.StylePriority.UseTextAlignment = false;
//
// xrTableRow13
//
this.xrTableRow13.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell50});
this.xrTableRow13.Name = "xrTableRow13";
resources.ApplyResources(this.xrTableRow13, "xrTableRow13");
//
// xrTableCell50
//
this.xrTableCell50.Name = "xrTableCell50";
resources.ApplyResources(this.xrTableCell50, "xrTableCell50");
//
// xrTableRow4
//
this.xrTableRow4.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell57,
this.xrTableCell26,
this.HumanBarcodeCell,
this.xrTableCell25,
this.xrTableCell27,
this.xrTableCell28,
this.xrTableCell10});
this.xrTableRow4.Name = "xrTableRow4";
resources.ApplyResources(this.xrTableRow4, "xrTableRow4");
//
// xrTableCell57
//
this.xrTableCell57.Name = "xrTableCell57";
resources.ApplyResources(this.xrTableCell57, "xrTableCell57");
//
// xrTableCell26
//
this.xrTableCell26.Name = "xrTableCell26";
this.xrTableCell26.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell26, "xrTableCell26");
//
// HumanBarcodeCell
//
resources.ApplyResources(this.HumanBarcodeCell, "HumanBarcodeCell");
this.HumanBarcodeCell.Name = "HumanBarcodeCell";
this.HumanBarcodeCell.StylePriority.UseFont = false;
this.HumanBarcodeCell.StylePriority.UseTextAlignment = false;
//
// xrTableCell25
//
this.xrTableCell25.Name = "xrTableCell25";
resources.ApplyResources(this.xrTableCell25, "xrTableCell25");
//
// xrTableCell27
//
this.xrTableCell27.Name = "xrTableCell27";
resources.ApplyResources(this.xrTableCell27, "xrTableCell27");
//
// xrTableCell28
//
this.xrTableCell28.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell28.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "CaseTests.strHumPatient")});
this.xrTableCell28.Name = "xrTableCell28";
this.xrTableCell28.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell28, "xrTableCell28");
//
// xrTableCell10
//
this.xrTableCell10.Name = "xrTableCell10";
resources.ApplyResources(this.xrTableCell10, "xrTableCell10");
//
// xrTableRow6
//
this.xrTableRow6.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell5,
this.xrTableCell30,
this.xrTableCell31,
this.xrTableCell32,
this.xrTableCell33,
this.xrTableCell24});
this.xrTableRow6.Name = "xrTableRow6";
resources.ApplyResources(this.xrTableRow6, "xrTableRow6");
//
// xrTableCell5
//
this.xrTableCell5.Name = "xrTableCell5";
resources.ApplyResources(this.xrTableCell5, "xrTableCell5");
//
// xrTableCell30
//
this.xrTableCell30.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "CaseTests.strHumCaseId")});
this.xrTableCell30.Name = "xrTableCell30";
this.xrTableCell30.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell30, "xrTableCell30");
//
// xrTableCell31
//
this.xrTableCell31.Name = "xrTableCell31";
resources.ApplyResources(this.xrTableCell31, "xrTableCell31");
//
// xrTableCell32
//
this.xrTableCell32.Name = "xrTableCell32";
resources.ApplyResources(this.xrTableCell32, "xrTableCell32");
//
// xrTableCell33
//
this.xrTableCell33.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell33.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "CaseTests.strHumDiagnosis")});
this.xrTableCell33.Name = "xrTableCell33";
this.xrTableCell33.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell33, "xrTableCell33");
//
// xrTableCell24
//
this.xrTableCell24.Name = "xrTableCell24";
resources.ApplyResources(this.xrTableCell24, "xrTableCell24");
//
// xrTableRow7
//
this.xrTableRow7.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell101,
this.xrTableCell34,
this.xrTableCell35,
this.xrTableCell36,
this.xrTableCell37,
this.xrTableCell38,
this.xrTableCell29});
this.xrTableRow7.Name = "xrTableRow7";
resources.ApplyResources(this.xrTableRow7, "xrTableRow7");
//
// xrTableCell101
//
this.xrTableCell101.Name = "xrTableCell101";
resources.ApplyResources(this.xrTableCell101, "xrTableCell101");
//
// xrTableCell34
//
this.xrTableCell34.Name = "xrTableCell34";
resources.ApplyResources(this.xrTableCell34, "xrTableCell34");
//
// xrTableCell35
//
this.xrTableCell35.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell35.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "CaseTests.strHumCaseStatus")});
this.xrTableCell35.Name = "xrTableCell35";
this.xrTableCell35.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell35, "xrTableCell35");
//
// xrTableCell36
//
this.xrTableCell36.Name = "xrTableCell36";
resources.ApplyResources(this.xrTableCell36, "xrTableCell36");
//
// xrTableCell37
//
this.xrTableCell37.Name = "xrTableCell37";
resources.ApplyResources(this.xrTableCell37, "xrTableCell37");
//
// xrTableCell38
//
this.xrTableCell38.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell38.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "CaseTests.strHumCaseClassification")});
this.xrTableCell38.Name = "xrTableCell38";
this.xrTableCell38.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell38, "xrTableCell38");
//
// xrTableCell29
//
this.xrTableCell29.Name = "xrTableCell29";
resources.ApplyResources(this.xrTableCell29, "xrTableCell29");
//
// xrLabel3
//
this.xrLabel3.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.xrLabel3, "xrLabel3");
this.xrLabel3.Name = "xrLabel3";
this.xrLabel3.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrLabel3.StylePriority.UseBorders = false;
this.xrLabel3.StylePriority.UseFont = false;
this.xrLabel3.StylePriority.UseTextAlignment = false;
//
// ReportFooter
//
resources.ApplyResources(this.ReportFooter, "ReportFooter");
this.ReportFooter.Name = "ReportFooter";
//
// m_Adapter
//
this.m_Adapter.ClearBeforeFill = true;
//
// m_DataSet
//
this.m_DataSet.DataSetName = "CaseTestDataSet";
this.m_DataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// xrTableCell20
//
this.xrTableCell20.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimCaseTests.LabBarcode")});
this.xrTableCell20.Name = "xrTableCell20";
resources.ApplyResources(this.xrTableCell20, "xrTableCell20");
//
// DetailReport
//
this.DetailReport.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail1});
this.DetailReport.Level = 1;
this.DetailReport.Name = "DetailReport";
//
// Detail1
//
this.Detail1.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrSubreport1});
resources.ApplyResources(this.Detail1, "Detail1");
this.Detail1.Name = "Detail1";
this.Detail1.PageBreak = DevExpress.XtraReports.UI.PageBreak.BeforeBand;
//
// xrSubreport1
//
resources.ApplyResources(this.xrSubreport1, "xrSubreport1");
this.xrSubreport1.Name = "xrSubreport1";
this.xrSubreport1.ReportSource = new EIDSS.Reports.Document.Lim.Case.TestValidationReport();
//
// TestReport
//
this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail,
this.PageHeader,
this.PageFooter,
this.ReportHeader,
this.DetailReportTest,
this.DetailReport});
this.ExportOptions.Xls.SheetName = resources.GetString("TestReport.ExportOptions.Xls.SheetName");
this.ExportOptions.Xlsx.SheetName = resources.GetString("TestReport.ExportOptions.Xlsx.SheetName");
resources.ApplyResources(this, "$this");
this.Version = "14.1";
this.Controls.SetChildIndex(this.DetailReport, 0);
this.Controls.SetChildIndex(this.DetailReportTest, 0);
this.Controls.SetChildIndex(this.ReportHeader, 0);
this.Controls.SetChildIndex(this.PageFooter, 0);
this.Controls.SetChildIndex(this.PageHeader, 0);
this.Controls.SetChildIndex(this.Detail, 0);
((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.DetailTable)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable5)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.ExternalOrganizationTable)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.VetHeaderTable)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.HumanHeaderTable)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.m_DataSet)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
private DevExpress.XtraReports.UI.DetailReportBand DetailReportTest;
private DevExpress.XtraReports.UI.DetailBand DetailTest;
private DevExpress.XtraReports.UI.ReportHeaderBand ReportHeaderTest;
private CaseTestDataSet m_DataSet;
private CaseTestDataSetTableAdapters.CaseTestsAdapter m_Adapter;
private DevExpress.XtraReports.UI.XRLabel xrLabel3;
private DevExpress.XtraReports.UI.XRTable DetailTable;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell4;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell6;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell8;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell9;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell3;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell20;
private DevExpress.XtraReports.UI.XRTable xrTable5;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell21;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow10;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell22;
private DevExpress.XtraReports.UI.DetailReportBand DetailReport;
private DevExpress.XtraReports.UI.DetailBand Detail1;
private DevExpress.XtraReports.UI.XRSubreport xrSubreport1;
private DevExpress.XtraReports.UI.XRTable HumanHeaderTable;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow4;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell26;
private DevExpress.XtraReports.UI.XRTableCell HumanBarcodeCell;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell25;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell27;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell28;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow6;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell30;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell32;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell33;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow7;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell34;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell35;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell36;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell37;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell38;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell391;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell51;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell52;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell57;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell101;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell10;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell31;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell24;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell29;
private DevExpress.XtraReports.UI.ReportFooterBand ReportFooter;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow8;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell7;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell39;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell40;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell41;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell42;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell43;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell44;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell45;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell46;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell47;
private DevExpress.XtraReports.UI.XRTable ExternalOrganizationTable;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell11;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow9;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell12;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell13;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell14;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow11;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell15;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell16;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell17;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow12;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell18;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell48;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell49;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow3;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell19;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow13;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell50;
private DevExpress.XtraReports.UI.XRTable VetHeaderTable;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow14;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell53;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow15;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell54;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow16;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell55;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell56;
private DevExpress.XtraReports.UI.XRTableCell VetBarcodeCell;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell59;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell60;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell61;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell62;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow17;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell63;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell64;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell65;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell66;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell67;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell68;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow18;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell69;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell70;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell71;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell72;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell73;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell74;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell75;
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
namespace Embree
{
/// <summary>
/// Represents a read-only, lightweight key-value mapping.
/// </summary>
public struct IdentifierMapping<K, V> : IEnumerable<KeyValuePair<K, V>>
{
/// <summary>
/// Gets the value corresponding to a given key.
/// </summary>
/// <param name="key">The key to map to a value.</param>
public V this[K key] { get { return mapping[key]; } }
private readonly IDictionary<K, V> mapping;
internal IdentifierMapping(IDictionary<K, V> mapping)
{
this.mapping = mapping;
}
public IEnumerator<KeyValuePair<K, V>> GetEnumerator()
{
return mapping.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
/// <summary>
/// Represents a collection of geometries and instances.
/// </summary>
public sealed class Scene : IDisposable
{
/// <summary>
/// Gets this scene's underlying native pointer.
/// </summary>
internal IntPtr NativePtr { get { CheckDisposed(); return nativePtr; } }
private readonly IntPtr nativePtr;
/// <summary>
/// Gets this scene's scene flags.
/// </summary>
public SceneFlags SceneFlags { get { CheckDisposed(); return sceneFlags; } }
private readonly SceneFlags sceneFlags;
/// <summary>
/// Gets this scene's algorithm flags.
/// </summary>
public AlgorithmFlags AlgorithmFlags { get { CheckDisposed(); return algorithmFlags; } }
private readonly AlgorithmFlags algorithmFlags;
/// <summary>
/// Gets the mapping from instance ID's to instance objects.
/// </summary>
public IdentifierMapping<Int32, Instance> Instances {
get { CheckDisposed(); return new IdentifierMapping<Int32, Instance>(instanceMapping); }
}
/// <summary>
/// Gets the mapping from geometry ID's to geometry objects.
/// </summary>
public IdentifierMapping<Int32, Geometry> Geometries {
get { CheckDisposed(); return new IdentifierMapping<Int32, Geometry>(geometryMapping); }
}
private readonly IDictionary<Int32, Instance> instanceMapping = new Dictionary<Int32, Instance>();
private readonly IDictionary<Instance, Int32> instanceInverse = new Dictionary<Instance, Int32>();
private readonly IDictionary<Int32, Geometry> geometryMapping = new Dictionary<Int32, Geometry>();
private readonly IDictionary<Geometry, Int32> geometryInverse = new Dictionary<Geometry, Int32>();
/// <summary>
/// Instantiates a new scene with the given scene and algorithm flags.
/// </summary>
/// <param name="sceneFlags">The scene flags to use.</param>
/// <param name="algorithmFlags">The algorithm flags to use.</param>
public Scene(SceneFlags sceneFlags = SceneFlags.Dynamic
| SceneFlags.Coherent,
AlgorithmFlags algorithmFlags = AlgorithmFlags.Intersect1
| AlgorithmFlags.Intersect4)
{
if (!sceneFlags.HasFlag(SceneFlags.Dynamic)) {
sceneFlags |= SceneFlags.Dynamic;
}
this.sceneFlags = sceneFlags;
this.algorithmFlags = algorithmFlags;
this.nativePtr = RTC.NewScene(SceneFlags,
AlgorithmFlags);
}
/// <summary>
/// Commits all geometry within this scene.
/// </summary>
public void Commit()
{
CheckDisposed();
RTC.Commit(NativePtr);
}
/// <summary>
/// Creates a new instance of a scene in this scene.
/// </summary>
/// <returns>The newly created instance.</returns>
/// <param name="source">The scene to instance.</param>
public Instance NewInstance(Scene source)
{
CheckDisposed();
if (source == null) {
throw new ArgumentNullException("source");
}
var instance = new Instance(this, source);
instanceMapping[instance.ID] = instance;
instanceInverse[instance] = instance.ID;
return instance;
}
/// <summary>
/// Creates a new triangle mesh in this scene.
/// </summary>
/// <returns>The newly created geometry.</returns>
/// <param name="desc">The geometry's description.</param>
public TriangleMesh NewTriangleMesh(TriangleMeshDescription desc)
{
CheckDisposed();
var geometry = new TriangleMesh(this, desc);
geometryMapping[geometry.ID] = geometry;
geometryInverse[geometry] = geometry.ID;
return geometry;
}
/// <summary>
/// Removes an instance from this scene.
/// </summary>
public Boolean Remove(Instance instance)
{
CheckDisposed();
if (instance == null) {
throw new ArgumentNullException("instance");
}
if (instanceInverse.ContainsKey(instance)) {
RTC.DeleteGeometry(NativePtr, instance.ID);
instanceMapping.Remove(instance.ID);
instanceInverse.Remove(instance);
return true;
} else {
return false;
}
}
/// <summary>
/// Removes a geometry from this scene.
/// </summary>
public Boolean Remove(Geometry geometry)
{
CheckDisposed();
if (geometry == null) {
throw new ArgumentNullException("geometry");
}
if (geometryInverse.ContainsKey(geometry)) {
RTC.DeleteGeometry(NativePtr, geometry.ID);
geometryMapping.Remove(geometry.ID);
geometryInverse.Remove(geometry);
return true;
} else {
return false;
}
}
/// <summary>
/// Performs an intersection query on this scene.
/// </summary>
/// <param name="ray">The ray structure to use.</param>
public unsafe void Intersection(RayStruct1* ray)
{
#if DEBUG
CheckDisposed();
if (!AlgorithmFlags.HasFlag(AlgorithmFlags.Intersect1)) {
throw new InvalidOperationException("AlgorithmFlags.Intersect1 not set.");
}
#endif
RTC.Intersect(NativePtr, ray);
}
/// <summary>
/// Performs an intersection query on this scene.
/// </summary>
/// <param name="ray">The ray structure to use.</param>
/// <param name="activityMask">The ray activity mask.</param>
public unsafe void Intersection4(RayStruct4* ray, uint* activityMask)
{
#if DEBUG
CheckDisposed();
if (!AlgorithmFlags.HasFlag(AlgorithmFlags.Intersect4)) {
throw new InvalidOperationException("AlgorithmFlags.Intersect4 not set.");
}
#endif
RTC.Intersect4(activityMask, NativePtr, ray);
}
/// <summary>
/// Performs an intersection query on this scene.
/// </summary>
/// <param name="ray">The ray structure to use.</param>
/// <param name="activityMask">The ray activity mask.</param>
public unsafe void Intersection8(RayStruct8* ray, uint* activityMask)
{
#if DEBUG
CheckDisposed();
if (!AlgorithmFlags.HasFlag(AlgorithmFlags.Intersect8)) {
throw new InvalidOperationException("AlgorithmFlags.Intersect8 not set.");
}
#endif
RTC.Intersect8(activityMask, NativePtr, ray);
}
/// <summary>
/// Performs an intersection query on this scene.
/// </summary>
/// <param name="ray">The ray structure to use.</param>
/// <param name="activityMask">The ray activity mask.</param>
public unsafe void Intersection16(RayStruct16* ray, uint* activityMask)
{
#if DEBUG
CheckDisposed();
if (!AlgorithmFlags.HasFlag(AlgorithmFlags.Intersect16)) {
throw new InvalidOperationException("AlgorithmFlags.Intersect16 not set.");
}
#endif
RTC.Intersect16(activityMask, NativePtr, ray);
}
/// <summary>
/// Performs an occlusion query on this scene.
/// </summary>
/// <param name="ray">The ray structure to use.</param>
public unsafe void Occlusion(RayStruct1* ray)
{
#if DEBUG
CheckDisposed();
if (!AlgorithmFlags.HasFlag(AlgorithmFlags.Intersect1)) {
throw new InvalidOperationException("AlgorithmFlags.Intersect1 not set.");
}
#endif
RTC.Occluded(NativePtr, ray);
}
/// <summary>
/// Performs an occlusion query on this scene.
/// </summary>
/// <param name="ray">The ray structure to use.</param>
/// <param name="activityMask">The ray activity mask.</param>
public unsafe void Occlusion4<T>(RayStruct4* ray, uint* activityMask)
{
#if DEBUG
CheckDisposed();
if (!AlgorithmFlags.HasFlag(AlgorithmFlags.Intersect4)) {
throw new InvalidOperationException("AlgorithmFlags.Intersect4 not set.");
}
#endif
RTC.Occluded4(activityMask, NativePtr, ray);
}
/// <summary>
/// Performs an occlusion query on this scene.
/// </summary>
/// <param name="ray">The ray structure to use.</param>
/// <param name="activityMask">The ray activity mask.</param>
public unsafe void Occlusion8(RayStruct8* ray, uint* activityMask)
{
#if DEBUG
CheckDisposed();
if (!AlgorithmFlags.HasFlag(AlgorithmFlags.Intersect8)) {
throw new InvalidOperationException("AlgorithmFlags.Intersect8 not set.");
}
#endif
RTC.Occluded8(activityMask, NativePtr, ray);
}
/// <summary>
/// Performs an occlusion query on this scene.
/// </summary>
/// <param name="ray">The ray structure to use.</param>
/// <param name="activityMask">The ray activity mask.</param>
public unsafe void Occlusion16(RayStruct16* ray, uint* activityMask)
{
#if DEBUG
CheckDisposed();
if (!AlgorithmFlags.HasFlag(AlgorithmFlags.Intersect16)) {
throw new InvalidOperationException("AlgorithmFlags.Intersect16 not set.");
}
#endif
RTC.Occluded16(activityMask, NativePtr, ray);
}
private void Dispose(bool disposing)
{
if (!disposed) {
RTC.DeleteScene(NativePtr);
disposed = true;
}
}
#region IDisposable
private bool disposed;
~Scene()
{
Dispose(false);
}
/// <summary>
/// Disposes of this instance, releasing all resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void CheckDisposed()
{
if (disposed) {
throw new ObjectDisposedException(GetType().FullName);
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Data.SqlClient;
using System.Data;
using System.ComponentModel;
using System.Configuration;
namespace Xenosynth.Configuration {
/// <summary>
/// Provides access to Xenosynth system configuration.
/// <remarks>
/// The system configuration provides an easy way to have a configuration that can be managed using the end user from the Xenosynth Admin. Settings that should not be managed by the end user should reside in the web/user config.
/// </remarks>
/// </summary>
public class SystemConfiguration : IEnumerable {
private static SystemConfiguration current = new SystemConfiguration();
private Hashtable settingsCache;
private string connectionString;
private const string CONNECTION_STRING_SETTINGS_NAME = "Xenosynth";
/// <summary>
/// This property supports the Xenosynth Framework and is not intended to be used directly from your code.
/// </summary>
public string ConnectionString {
set { connectionString = value; }
get {
if (connectionString == null) {
ConnectionStringSettings connectionStringSetting = ConfigurationManager.ConnectionStrings[CONNECTION_STRING_SETTINGS_NAME];
if (connectionStringSetting == null || string.IsNullOrEmpty(connectionStringSetting.ConnectionString)) {
throw new ConfigurationErrorsException(string.Format(Properties.Resources.ConnectionStringSettingsNullOrEmpty, CONNECTION_STRING_SETTINGS_NAME));
} else {
connectionString = connectionStringSetting.ConnectionString;
}
}
return connectionString;
}
}
/// <summary>
/// This property supports the Xenosynth Framework and is not intended to be used directly from your code.
/// </summary>
public string TableName {
get { return "ConfigSettings"; }
}
private SystemConfiguration() {
}
/// <summary>
/// Gets the <see cref="SystemConfiguration"/> object.
/// </summary>
public static SystemConfiguration Current {
get { return current; }
}
/// <summary>
/// A list categories in the current system configuration.
/// </summary>
public string[] Categories {
get {
ArrayList categories = new ArrayList();
foreach (ConfigurationSetting c in Settings.Values) {
if (!categories.Contains(c.Category)) {
categories.Add(c.Category);
}
}
categories.Sort();
return (string[])categories.ToArray(typeof(string));
}
}
/// <summary>
/// Gets a list of <see cref="ConfigurationSetting"/> for the given category.
/// </summary>
/// <param name="category">
/// A <see cref="System.String"/> for the category.
/// </param>
/// <returns>
/// A <see cref="IList"/> of <see cref="ConfigurationSetting"/>.
/// </returns>
public IList GetConfigurationSettingByCategory(string category) {
ArrayList settings = new ArrayList();
foreach (ConfigurationSetting c in Settings.Values) {
if (c.Category == category) {
settings.Add(c);
}
}
return settings;
}
/// <summary>
/// Returns the value for a setting.
/// </summary>
/// <param name="key">
/// The key for the setting.
/// </param>
/// <param name="throwErrorRequired">
/// Whether to throw an error if no setting exists for the key. If false and no key exists, returns null.
/// </param>
/// <returns>
/// The value for the configuration settings.
/// </returns>
public object GetValue(string key, bool throwErrorRequired) {
ConfigurationSetting setting = this[key];
if (setting == null) {
if (throwErrorRequired) {
throw new ConfigurationErrorsException(string.Format(Properties.Resources.ConfigurationSettingNullOrEmpty, key));
} else {
return null;
}
}
return setting.Value;
}
/// <summary>
/// A Hashtable of <see cref="ConfigurationSetting"/> indexed by the setting's key.
/// </summary>
private Hashtable Settings {
get {
if (settingsCache == null) {
settingsCache = new Hashtable();
SqlConnection conn = null;
try {
conn = new SqlConnection(ConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM " + TableName, conn);
SqlDataReader r = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (r.Read()) {
Type type = Type.GetType(r["Type"].ToString(), true);
ConfigurationSetting setting = new ConfigurationSetting(
r["Key"].ToString(),
r["Category"].ToString(),
r["Name"].ToString(),
r["Description"].ToString(),
type,
ConvertFromString(r["Value"].ToString(), type)
);
AddToCache(setting);
}
} catch (Exception e) {
settingsCache = null;
throw e;
} finally {
if (conn != null && conn.State == ConnectionState.Open) {
conn.Close();
}
}
}
return settingsCache;
}
}
private void AddToCache(ConfigurationSetting setting) {
settingsCache.Add(setting.Key, setting);
setting.Change += new EventHandler(OnSettingChange);
}
private object ConvertFromString(string value, Type type) {
TypeConverter converter = TypeDescriptor.GetConverter(type);
if (converter != null) {
return converter.ConvertFromString(value);
} else {
return Convert.ChangeType(value, type);
}
}
private string ConvertToString(object value) {
TypeConverter converter = TypeDescriptor.GetConverter(value);
if (converter != null) {
return converter.ConvertToString(value);
} else {
return value.ToString();
}
}
/// <summary>
/// Whether the system configuration can be changed.
/// </summary>
public bool IsReadOnly {
get {
return false;
}
}
/// <summary>
/// Returns the <see cref="ConfigurationSetting"/> for the supplied key.
/// </summary>
/// <param name="key">
/// A <see cref="System.String"/>
/// </param>
public ConfigurationSetting this[string key] {
get {
return (ConfigurationSetting)Settings[key];
}
}
/// <summary>
/// Removes the <see cref="ConfigurationSetting"/> for the supplied key.
/// </summary>
/// <param name="key">
/// A <see cref="System.String"/>
/// </param>
public void Remove(string key) {
if (!this.Contains(key)) {
throw new ApplicationException("A setting with key '" + key + "' does not exists.");
}
string sql = "DELETE " + TableName + " WHERE [Key] = @Key";
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("@Key", key);
try {
conn.Open();
cmd.ExecuteNonQuery();
} finally {
if (conn.State == ConnectionState.Open) {
conn.Close();
}
}
RemoveFromCache(this[key]);
}
private void RemoveFromCache(ConfigurationSetting setting) {
settingsCache.Remove(setting.Key);
setting.Change -= new EventHandler(OnSettingChange);
}
/// <summary>
/// Whether the configuration contains a <see cref="ConfigurationSetting"/> for the supplied key.
/// </summary>
/// <param name="key">
/// A <see cref="System.String"/>
/// </param>
/// <returns>
/// A <see cref="System.Boolean"/>
/// </returns>
public bool Contains(string key) {
return Settings.Contains(key);
}
/// <summary>
/// This method supports the Xenosynth Framework and is not intended to be used directly from your code.
/// </summary>
public void Clear() {
throw new NotImplementedException();
}
/// <summary>
/// Returns a collection of all the <see cref="ConfigurationSetting"/>.
/// </summary>
public ICollection Values {
get {
return Settings.Values;
}
}
/// <summary>
/// Adds a <see cref="ConfigurationSetting"/> to the system configuration.
/// </summary>
/// <param name="setting">
/// A <see cref="ConfigurationSetting"/>
/// </param>
public void Add(ConfigurationSetting setting) {
if (this.Contains(setting.Key)) {
throw new ApplicationException("A setting with key '" + setting.Key + "' already exists.");
}
string sql = "INSERT " + TableName + " ([Key], Category, Name, Description, Type, Value) Values (@Key, @Category, @Name, @Description, @Type, @Value)";
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("@Key", setting.Key);
cmd.Parameters.Add("@Name", setting.Value);
cmd.Parameters.Add("@Category", setting.Category);
cmd.Parameters.Add("@Description", setting.Description);
cmd.Parameters.Add("@Type", setting.ValueType.AssemblyQualifiedName);
cmd.Parameters.Add("@Value", ConvertToString(setting.Value));
try {
conn.Open();
cmd.ExecuteNonQuery();
} finally {
if (conn.State == ConnectionState.Open) {
conn.Close();
}
}
AddToCache(setting);
}
/// <summary>
/// The collection of configuration <see cref="System.String"/> keys.
/// </summary>
public ICollection Keys {
get {
return Settings.Keys;
}
}
/// <summary>
/// The count of configurations settings.
/// </summary>
public int Count {
get {
return Settings.Count;
}
}
#region IEnumerable Members
/// <summary>
/// An enumerator for the configuration settings.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator"/>
/// </returns>
IEnumerator System.Collections.IEnumerable.GetEnumerator() {
return settingsCache.GetEnumerator();
}
#endregion
private void OnSettingChange(object sender, EventArgs e) {
ConfigurationSetting setting = (ConfigurationSetting)sender;
string sql = "UPDATE " + TableName + " SET Value = @Value WHERE [Key] = @Key";
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("@Key", setting.Key);
cmd.Parameters.Add("@Value", ConvertToString(setting.Value));
try {
conn.Open();
cmd.ExecuteNonQuery();
} finally {
if (conn.State == ConnectionState.Open) {
conn.Close();
}
}
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
#if DEBUG
#define TRACK_REPRESENTATION_IDENTITY
#else
//#define TRACK_REPRESENTATION_IDENTITY
#endif
namespace Microsoft.Zelig.Runtime.TypeSystem
{
using System;
using System.Collections.Generic;
public abstract class BaseRepresentation
{
//
// State
//
#if TRACK_REPRESENTATION_IDENTITY
protected static int s_identity;
#endif
public int m_identity;
//--//
protected CustomAttributeAssociationRepresentation[] m_customAttributes;
//--//
//
// Constructor Methods
//
protected BaseRepresentation()
{
#if TRACK_REPRESENTATION_IDENTITY
m_identity = s_identity++;
#endif
m_customAttributes = CustomAttributeAssociationRepresentation.SharedEmptyArray;
}
//
// MetaDataEquality Methods
//
public abstract bool EqualsThroughEquivalence( object obj ,
EquivalenceSet set );
public static bool EqualsThroughEquivalence( BaseRepresentation left ,
BaseRepresentation right ,
EquivalenceSet set )
{
if(Object.ReferenceEquals( left, right ))
{
return true;
}
if(left != null && right != null)
{
return left.EqualsThroughEquivalence( right, set );
}
return false;
}
public static bool ArrayEqualsThroughEquivalence<T>( T[] s ,
T[] d ,
EquivalenceSet set ) where T : BaseRepresentation
{
return ArrayEqualsThroughEquivalence( s, d, 0, -1, set );
}
public static bool ArrayEqualsThroughEquivalence<T>( T[] s ,
T[] d ,
int offset ,
int count ,
EquivalenceSet set ) where T : BaseRepresentation
{
int sLen = s != null ? s.Length : 0;
int dLen = d != null ? d.Length : 0;
if(count < 0)
{
if(sLen != dLen)
{
return false;
}
count = sLen - offset;
}
else
{
if(sLen < count + offset ||
dLen < count + offset )
{
return false;
}
}
while(count > 0)
{
if(EqualsThroughEquivalence( s[offset], d[offset], set ) == false)
{
return false;
}
offset++;
count--;
}
return true;
}
//--//
//
// Helper Methods
//
public virtual void ApplyTransformation( TransformationContext context )
{
context.Push( this );
context.Transform( ref m_customAttributes );
context.Pop();
}
//--//
public void AddCustomAttribute( CustomAttributeAssociationRepresentation cca )
{
m_customAttributes = ArrayUtility.AddUniqueToNotNullArray( m_customAttributes, cca );
}
public void CopyCustomAttribute( CustomAttributeAssociationRepresentation caa )
{
AddCustomAttribute( new CustomAttributeAssociationRepresentation( caa.CustomAttribute, this, caa.ParameterIndex ) );
}
public void RemoveCustomAttribute( CustomAttributeAssociationRepresentation cca )
{
m_customAttributes = ArrayUtility.RemoveUniqueFromNotNullArray( m_customAttributes, cca );
}
public void RemoveCustomAttribute( CustomAttributeRepresentation ca )
{
foreach(CustomAttributeAssociationRepresentation caa in m_customAttributes)
{
if(caa.CustomAttribute == ca)
{
RemoveCustomAttribute( caa );
}
}
}
public bool HasCustomAttribute( TypeRepresentation target )
{
return FindCustomAttribute( target, -1 ) != null;
}
public CustomAttributeRepresentation FindCustomAttribute( TypeRepresentation target )
{
return FindCustomAttribute( target, -1 );
}
public CustomAttributeRepresentation FindCustomAttribute( TypeRepresentation target ,
int index )
{
return FindCustomAttribute( target, -1, index );
}
public virtual void EnumerateCustomAttributes( CustomAttributeAssociationEnumerationCallback callback )
{
foreach(CustomAttributeAssociationRepresentation caa in m_customAttributes)
{
callback( caa );
}
}
//--//
protected CustomAttributeRepresentation FindCustomAttribute( TypeRepresentation target ,
int paramIndex ,
int index )
{
int pos = index >= 0 ? 0 : index; // So we don't have the double check in the loop.
foreach(CustomAttributeAssociationRepresentation caa in m_customAttributes)
{
if(caa.CustomAttribute.Constructor.OwnerType == target &&
caa.ParameterIndex == paramIndex )
{
if(index == pos)
{
return caa.CustomAttribute;
}
pos++;
}
}
return null;
}
//--//
internal virtual void ProhibitUse( TypeSystem.Reachability reachability ,
bool fApply )
{
reachability.ExpandProhibition( this );
foreach(CustomAttributeAssociationRepresentation caa in m_customAttributes)
{
reachability.ExpandProhibition( caa );
}
}
internal virtual void Reduce( TypeSystem.Reachability reachability ,
bool fApply )
{
for(int i = m_customAttributes.Length; --i >= 0; )
{
CustomAttributeAssociationRepresentation caa = m_customAttributes[i];
CHECKS.ASSERT( reachability.Contains( caa.Target ) == true, "{0} cannot be reachable since its owner is not in the Reachability set", caa );
if(reachability.Contains( caa.CustomAttribute.Constructor ) == false)
{
CHECKS.ASSERT( reachability.Contains( caa ) == false, "{0} cannot belong to both the Reachability and the Prohibition set", caa );
CHECKS.ASSERT( reachability.Contains( caa.CustomAttribute ) == false, "{0} cannot belong to both the Reachability and the Prohibition set", caa.CustomAttribute );
reachability.ExpandProhibition( caa );
reachability.ExpandProhibition( caa.CustomAttribute );
if(fApply)
{
if(m_customAttributes.Length == 1)
{
m_customAttributes = CustomAttributeAssociationRepresentation.SharedEmptyArray;
return;
}
m_customAttributes = ArrayUtility.RemoveAtPositionFromNotNullArray( m_customAttributes, i );
}
}
}
}
//--//
//
// Access Methods
//
public CustomAttributeAssociationRepresentation[] CustomAttributes
{
get
{
return m_customAttributes;
}
}
//--//
//
// Debug Methods
//
}
}
| |
#region License
/*
* 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.
*/
#endregion
#region Imports
using System.Globalization;
using NUnit.Framework;
using Rhino.Mocks;
#endregion
namespace Spring.Context.Support
{
[TestFixture]
public sealed class AbstractMessageSourceTests : AbstractMessageSource
{
private MockRepository mocks;
[SetUp]
public void Init()
{
mocks = new MockRepository();
resetMe();
}
[Test]
[ExpectedException(typeof (NoSuchMessageException))]
public void GetResolvableNullCodes()
{
IMessageSourceResolvable res = mocks.StrictMock<IMessageSourceResolvable>();
Expect.Call(res.GetCodes()).Return(null);
Expect.Call(res.DefaultMessage).Return(null);
mocks.ReplayAll();
GetMessage(res, CultureInfo.CurrentCulture);
mocks.VerifyAll();
}
[Test]
public void GetResolvableDefaultsToParentMessageSource()
{
string MSGCODE = "nullCode";
object[] MSGARGS = new object[] { "arg1", "arg2" };
IMessageSourceResolvable res = mocks.StrictMock<IMessageSourceResolvable>();
Expect.Call(res.GetArguments()).Return(MSGARGS);
Expect.Call(res.GetCodes()).Return(new string[] {MSGCODE}).Repeat.Once();
IMessageSource parentSource = mocks.StrictMock<IMessageSource>();
Expect.Call(parentSource.GetMessage(MSGCODE, null, CultureInfo.CurrentCulture, MSGARGS)).Return(
"MockMessageSource");
ParentMessageSource = parentSource;
mocks.ReplayAll();
Assert.AreEqual("MockMessageSource", GetMessage(res, CultureInfo.CurrentCulture), "My Message");
mocks.VerifyAll();
}
[Test]
public void GetMessageParentMessageSource()
{
object[] args = new object[] {"arguments"};
IMessageSource parentSource = mocks.StrictMock<IMessageSource>();
Expect.Call(parentSource.GetMessage("null", null, CultureInfo.CurrentCulture, args)).Return(
"my parent message");
ParentMessageSource = parentSource;
mocks.ReplayAll();
Assert.AreEqual("my parent message", GetMessage("null", "message", CultureInfo.CurrentCulture, args[0]));
mocks.VerifyAll();
}
[Test]
public void GetMessageResolvableDefaultMessage()
{
IMessageSourceResolvable res = mocks.StrictMock<IMessageSourceResolvable>();
Expect.Call(res.DefaultMessage).Return("MyDefaultMessage").Repeat.AtLeastOnce();
Expect.Call(res.GetCodes()).Return(null);
Expect.Call(res.GetArguments()).Return(null);
mocks.ReplayAll();
Assert.AreEqual("MyDefaultMessage", GetMessage(res, CultureInfo.CurrentCulture), "Default");
mocks.VerifyAll();
}
[Test]
public void GetMessageResolvableReturnsFirstCode()
{
IMessageSourceResolvable res = mocks.StrictMock<IMessageSourceResolvable>();
Expect.Call(res.DefaultMessage).Return(null).Repeat.AtLeastOnce();
Expect.Call(res.GetCodes()).Return(new string[] {"null"});
Expect.Call(res.GetArguments()).Return(null).Repeat.AtLeastOnce();
mocks.ReplayAll();
UseCodeAsDefaultMessage = true;
Assert.AreEqual("null", GetMessage(res, CultureInfo.CurrentCulture), "Code");
mocks.VerifyAll();
}
[Test]
[ExpectedException(typeof (NoSuchMessageException))]
public void GetMessageResolvableNoValidMessage()
{
IMessageSourceResolvable res = mocks.StrictMock<IMessageSourceResolvable>();
Expect.Call(res.DefaultMessage).Return(null).Repeat.AtLeastOnce();
Expect.Call(res.GetCodes()).Return(null);
Expect.Call(res.GetArguments()).Return(null).Repeat.AtLeastOnce();
mocks.ReplayAll();
GetMessage(res, CultureInfo.CurrentCulture);
}
[Test]
public void GetMessageResolvableValidMessageAndCode()
{
IMessageSourceResolvable res = mocks.StrictMock<IMessageSourceResolvable>();
Expect.Call(res.GetCodes()).Return(new string[] {"code1"});
Expect.Call(res.GetArguments()).Return(new object[] { "my", "arguments" }).Repeat.AtLeastOnce();
mocks.ReplayAll();
Assert.AreEqual("my arguments", GetMessage(res, CultureInfo.CurrentCulture), "Resolve");
mocks.VerifyAll();
}
[Test]
public void GetMessageResolvableValidMessageAndCodeNullCulture()
{
IMessageSourceResolvable res = mocks.StrictMock<IMessageSourceResolvable>();
Expect.Call(res.GetCodes()).Return(new string[] { "code1" });
Expect.Call(res.GetArguments()).Return(new object[] { "my", "arguments" }).Repeat.AtLeastOnce();
mocks.ReplayAll();
Assert.AreEqual("my arguments", GetMessage(res, null), "Resolve");
mocks.VerifyAll();
}
[Test]
[ExpectedException(typeof(NoSuchMessageException))]
public void GetMessageNullCode()
{
Assert.IsNull(GetMessage(null));
}
[Test]
public void GetMessageValidMessageAndCode()
{
Assert.AreEqual("my arguments", GetMessage("code1", new object[] {"my", "arguments"}), "Resolve");
}
[Test]
public void GetMessageValidMessageAndCodeNullCulture()
{
Assert.AreEqual("my arguments", GetMessage("code1", null, new object[] {"my", "arguments"}), "Resolve");
}
[Test]
public void GetMessageUseDefaultCode()
{
UseCodeAsDefaultMessage = true;
Assert.AreEqual("null", GetMessage("null", new object[] {"arguments"}), "message");
Assert.IsTrue(UseCodeAsDefaultMessage, "default");
}
[Test]
[ExpectedException(typeof (NoSuchMessageException))]
public void GetMessageNoValidMessage()
{
GetMessage("null", new object[] {"arguments"});
}
[Test]
public void GetMessageWithResolvableArguments()
{
IMessageSourceResolvable res = mocks.StrictMock<IMessageSourceResolvable>();
Expect.Call(res.GetCodes()).Return(new string[] { "code1" });
Expect.Call(res.GetArguments()).Return(new object[] { "my", "resolvable" }).Repeat.AtLeastOnce();
mocks.ReplayAll();
Assert.AreEqual("spring my resolvable", GetMessage("code2", CultureInfo.CurrentCulture, new object[] {"spring", res}), "Resolve");
mocks.VerifyAll();
}
[Test]
public void GetMessageResolvableValidMessageAndCodNullMessageFormat()
{
IMessageSourceResolvable res = mocks.StrictMock<IMessageSourceResolvable>();
Expect.Call(res.DefaultMessage).Return("myDefaultMessage").Repeat.AtLeastOnce();
Expect.Call(res.GetCodes()).Return(new string[] { "nullCode" });
Expect.Call(res.GetArguments()).Return(null).Repeat.AtLeastOnce();
mocks.ReplayAll();
Assert.AreEqual("myDefaultMessage", GetMessage(res, null), "Resolve");
mocks.VerifyAll();
}
private void resetMe()
{
ParentMessageSource = null;
UseCodeAsDefaultMessage = false;
}
protected override string ResolveMessage(string code, CultureInfo cultureInfo)
{
if (code.Equals("null"))
{
return null;
}
else if (code.Equals("nullCode"))
{
return null;
}
else
{
return "{0} {1}";
}
}
protected override object ResolveObject(string code, CultureInfo cultureInfo)
{
return null;
}
protected override void ApplyResourcesToObject(object value, string objectName, CultureInfo cultureInfo)
{
}
}
}
| |
// Google Maps User Control for ASP.Net version 1.0:
// ========================
// Copyright (C) 2008 Shabdar Ghata
// Email : [email protected]
// URL : http://www.shabdar.org
// 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 3 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, see <http://www.gnu.org/licenses/>.
// This program comes with ABSOLUTELY NO WARRANTY.
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Drawing;
/// <summary>
/// Summary description for cGoogleMap
/// </summary>
///
public class GoogleObject
{
public GoogleObject()
{
}
public GoogleObject(GoogleObject prev)
{
Points = GooglePoints.CloneMe(prev.Points);
Polylines = GooglePolylines.CloneMe(prev.Polylines);
Polygons = GooglePolygons.CloneMe(prev.Polygons);
ZoomLevel = prev.ZoomLevel;
ShowZoomControl = prev.ShowZoomControl;
ShowMapTypesControl = prev.ShowMapTypesControl;
Width = prev.Width;
Height = prev.Height;
MapType = prev.MapType;
APIKey = prev.APIKey;
ShowTraffic = prev.ShowTraffic;
}
GooglePoints _gpoints = new GooglePoints();
public GooglePoints Points
{
get { return _gpoints; }
set { _gpoints = value; }
}
GooglePolylines _gpolylines = new GooglePolylines();
public GooglePolylines Polylines
{
get { return _gpolylines; }
set { _gpolylines = value; }
}
GooglePolygons _gpolygons = new GooglePolygons();
public GooglePolygons Polygons
{
get { return _gpolygons; }
set { _gpolygons = value; }
}
GooglePoint _centerpoint = new GooglePoint();
public GooglePoint CenterPoint
{
get { return _centerpoint; }
set { _centerpoint = value; }
}
int _zoomlevel = 3;
public int ZoomLevel
{
get { return _zoomlevel; }
set { _zoomlevel = value; }
}
bool _showzoomcontrol = true;
public bool ShowZoomControl
{
get { return _showzoomcontrol; }
set { _showzoomcontrol = value; }
}
bool _showtraffic = false;
public bool ShowTraffic
{
get { return _showtraffic; }
set { _showtraffic = value; }
}
bool _showmaptypescontrol = true;
public bool ShowMapTypesControl
{
get { return _showmaptypescontrol; }
set { _showmaptypescontrol = value; }
}
string _width = "500px";
public string Width
{
get
{
return _width;
}
set
{
_width = value;
}
}
string _height = "400px";
public string Height
{
get
{
return _height;
}
set
{
_height = value;
}
}
string _maptype = "";
public string MapType
{
get
{
return _maptype;
}
set
{
_maptype = value;
}
}
string _apikey = "";
public string APIKey
{
get
{
return _apikey;
}
set
{
_apikey = value;
}
}
string _apiversion = "2";
public string APIVersion
{
get
{
return _apiversion;
}
set
{
_apiversion = value;
}
}
}
public class GooglePoint
{
public GooglePoint()
{
}
string _pointstatus = ""; //N-New, D-Deleted, C-Changed, ''-No Action
public string PointStatus
{
get { return _pointstatus; }
set { _pointstatus = value; }
}
public GooglePoint(string pID,double plat, double plon, string picon, string pinfohtml)
{
ID = pID;
Latitude = plat;
Longitude = plon;
IconImage = picon;
InfoHTML = pinfohtml;
}
public GooglePoint(string pID, double plat, double plon, string picon)
{
ID = pID;
Latitude = plat;
Longitude = plon;
IconImage = picon;
}
public GooglePoint(string pID, double plat, double plon)
{
ID = pID;
Latitude = plat;
Longitude = plon;
}
string _id = "";
public string ID
{
get
{
return _id;
}
set
{
_id = value;
}
}
string _icon = "";
public string IconImage
{
get
{
return _icon;
}
set
{
//Get physical path of icon image. Necessary for Bitmap object.
string sIconImage = value;
if (sIconImage == "")
return;
string ImageIconPhysicalPath = cCommon.GetLocalPath() + sIconImage.Replace("/", "\\");
//Find width and height of icon using Bitmap image.
using (System.Drawing.Image img = System.Drawing.Image.FromFile(ImageIconPhysicalPath))
{
IconImageWidth = img.Width;
IconImageHeight = img.Height;
}
_icon = cCommon.GetHttpURL() + sIconImage;
_icon = value;
}
}
int _iconimagewidth = 32;
public int IconImageWidth
{
get
{
return _iconimagewidth;
}
set
{
_iconimagewidth = value;
}
}
int _iconimageheight = 32;
public int IconImageHeight
{
get
{
return _iconimageheight;
}
set
{
_iconimageheight = value;
}
}
double _lat = 0.0;
public double Latitude
{
get
{
return _lat;
}
set
{
_lat = value;
}
}
double _lon = 0.0;
public double Longitude
{
get
{
return _lon;
}
set
{
_lon = value;
}
}
string _infohtml = "";
public string InfoHTML
{
get
{
return _infohtml;
}
set
{
_infohtml = value;
}
}
public override bool Equals(System.Object obj)
{
// If parameter is null return false.
if (obj == null)
{
return false;
}
// If parameter cannot be cast to Point return false.
GooglePoint p = obj as GooglePoint;
if ((System.Object)p == null)
{
return false;
}
// Return true if the fields match:
return (InfoHTML == p.InfoHTML) && (IconImage == p.IconImage) && (p.ID==ID) && (p.Latitude==Latitude) && (p.Longitude==Longitude);
}
}
public class GooglePoints : CollectionBase
{
public GooglePoints()
{
}
public static GooglePoints CloneMe(GooglePoints prev)
{
GooglePoints p = new GooglePoints();
for (int i = 0; i < prev.Count; i++)
{
p.Add(new GooglePoint(prev[i].ID, prev[i].Latitude, prev[i].Longitude, prev[i].IconImage, prev[i].InfoHTML));
}
return p;
}
public GooglePoint this[int pIndex]
{
get
{
return (GooglePoint)this.List[pIndex];
}
set
{
this.List[pIndex] = value;
}
}
public GooglePoint this[string pID]
{
get
{
for (int i = 0; i < Count; i++)
{
if (this[i].ID == pID)
{
return (GooglePoint)this.List[i];
}
}
return null;
}
set
{
for (int i = 0; i < Count; i++)
{
if (this[i].ID == pID)
{
this.List[i] = value;
}
}
}
}
public void Add(GooglePoint pPoint)
{
this.List.Add(pPoint);
}
public void Remove(int pIndex)
{
this.RemoveAt(pIndex);
}
public void Remove(string pID)
{
for (int i = 0; i < Count; i++)
{
if (this[i].ID == pID)
{
this.List.RemoveAt(i);
return;
}
}
}
public void RemoveAll()
{
this.List.Clear();
}
public override bool Equals(System.Object obj)
{
// If parameter is null return false.
if (obj == null)
{
return false;
}
// If parameter cannot be cast to Point return false.
GooglePoints p = obj as GooglePoints;
if ((System.Object)p == null)
{
return false;
}
if(p.Count!=Count)
return false;
for(int i=0;i<p.Count;i++)
{
if(!this[i].Equals(p[i]))
return false;
}
// Return true if the fields match:
return true;
}
}
public class GooglePolyline
{
string _linestatus = ""; //N-New, D-Deleted, C-Changed, ''-No Action
public string LineStatus
{
get { return _linestatus; }
set { _linestatus = value; }
}
string _id = "";
public string ID
{
get { return _id; }
set { _id = value; }
}
GooglePoints _gpoints=new GooglePoints();
public GooglePoints Points
{
get { return _gpoints; }
set { _gpoints = value; }
}
string _colorcode = "#66FF00";
public string ColorCode
{
get { return _colorcode; }
set { _colorcode = value; }
}
int _width = 10;
public int Width
{
get { return _width; }
set { _width = value; }
}
bool _geodesic = false;
public bool Geodesic
{
get { return _geodesic; }
set { _geodesic = value; }
}
public override bool Equals(System.Object obj)
{
// If parameter is null return false.
if (obj == null)
{
return false;
}
// If parameter cannot be cast to Point return false.
GooglePolyline p = obj as GooglePolyline;
if ((System.Object)p == null)
{
return false;
}
// Return true if the fields match:
return (Geodesic == p.Geodesic) && (Width == p.Width) && (p.ID == ID) && (p.ColorCode == ColorCode) && (p.Points.Equals(Points));
}
}
public class GooglePolylines : CollectionBase
{
public GooglePolylines()
{
}
public static GooglePolylines CloneMe(GooglePolylines prev)
{
GooglePolylines p = new GooglePolylines();
for (int i = 0; i < prev.Count; i++)
{
GooglePolyline GPL = new GooglePolyline();
GPL.ColorCode = prev[i].ColorCode;
GPL.Geodesic = prev[i].Geodesic;
GPL.ID = prev[i].ID;
GPL.Points = GooglePoints.CloneMe(prev[i].Points);
GPL.Width = prev[i].Width;
p.Add(GPL);
}
return p;
}
public GooglePolyline this[int pIndex]
{
get
{
return (GooglePolyline)this.List[pIndex];
}
set
{
this.List[pIndex] = value;
}
}
public GooglePolyline this[string pID]
{
get
{
for (int i = 0; i < Count; i++)
{
if (this[i].ID == pID)
{
return (GooglePolyline)this.List[i];
}
}
return null;
}
set
{
for (int i = 0; i < Count; i++)
{
if (this[i].ID == pID)
{
this.List[i] = value;
}
}
}
}
public void Add(GooglePolyline pPolyline)
{
this.List.Add(pPolyline);
}
public void Remove(int pIndex)
{
this.RemoveAt(pIndex);
}
public void Remove(string pID)
{
for (int i = 0; i < Count; i++)
{
if (this[i].ID == pID)
{
this.List.RemoveAt(i);
return;
}
}
}
}
public sealed class GoogleMapType
{
public const string NORMAL_MAP = "G_NORMAL_MAP";
public const string SATELLITE_MAP = "G_SATELLITE_MAP";
public const string HYBRID_MAP = "G_HYBRID_MAP";
}
public class cCommon
{
public cCommon()
{
//
// TODO: Add constructor logic here
//
}
public static Random random = new Random();
public static string GetHttpURL()
{
string[] s = System.Web.HttpContext.Current.Request.Url.AbsoluteUri.Split(new char[] { '/' });
string path = s[0] + "/";
for (int i = 1; i < s.Length - 1; i++)
{
path = path + s[i] + "/";
}
return path;
}
public static string GetLocalPath()
{
string[] s = System.Web.HttpContext.Current.Request.Url.AbsoluteUri.Split(new char[] { '/' });
string PageName = s[s.Length - 1];
s = System.Web.HttpContext.Current.Request.MapPath(PageName).Split(new char[] { '\\' });
string path = s[0] + "\\";
for (int i = 1; i < s.Length - 1; i++)
{
path = path + s[i] + "\\";
}
return path;
}
public static decimal RandomNumber(decimal min, decimal max)
{
decimal Fractions = 10000000;
int iMin = (int)GetIntegerPart(min * Fractions);
int iMax = (int)GetIntegerPart(max * Fractions);
int iRand = random.Next(iMin, iMax);
decimal dRand = (decimal)iRand;
dRand = dRand / Fractions;
return dRand;
}
public static decimal GetFractional(decimal source)
{
return source % 1.0m;
}
public static decimal GetIntegerPart(decimal source)
{
return decimal.Parse(source.ToString("#.00"));
}
}
public class GooglePolygon
{
string _status = ""; //N-New, D-Deleted, C-Changed, ''-No Action
public string Status
{
get { return _status; }
set { _status = value; }
}
string _id = "";
public string ID
{
get { return _id; }
set { _id = value; }
}
GooglePoints _gpoints = new GooglePoints();
public GooglePoints Points
{
get { return _gpoints; }
set { _gpoints = value; }
}
string _strokecolor = "#0000FF";
public string StrokeColor
{
get { return _strokecolor; }
set { _strokecolor = value; }
}
string _fillcolor = "#66FF00";
public string FillColor
{
get { return _fillcolor; }
set { _fillcolor = value; }
}
int _strokeweight = 10;
public int StrokeWeight
{
get { return _strokeweight; }
set { _strokeweight = value; }
}
double _strokeopacity = 1;
public double StrokeOpacity
{
get { return _strokeopacity; }
set { _strokeopacity = value; }
}
double _fillopacity = 0.2;
public double FillOpacity
{
get { return _fillopacity; }
set { _fillopacity = value; }
}
public override bool Equals(System.Object obj)
{
// If parameter is null return false.
if (obj == null)
{
return false;
}
// If parameter cannot be cast to Point return false.
GooglePolygon p = obj as GooglePolygon;
if ((System.Object)p == null)
{
return false;
}
// Return true if the fields match:
return (FillColor == p.FillColor) && (FillOpacity == p.FillOpacity) && (p.ID == ID) && (p.Status == Status) && (p.StrokeColor == StrokeColor) && (p.StrokeOpacity == StrokeOpacity) && (p.StrokeWeight == StrokeWeight) && (p.Points.Equals(Points));
}
}
public class GooglePolygons : CollectionBase
{
public GooglePolygons()
{
}
public static GooglePolygons CloneMe(GooglePolygons prev)
{
GooglePolygons p = new GooglePolygons();
for (int i = 0; i < prev.Count; i++)
{
GooglePolygon GPL = new GooglePolygon();
GPL.FillColor = prev[i].FillColor;
GPL.FillOpacity = prev[i].FillOpacity;
GPL.ID = prev[i].ID;
GPL.Status = prev[i].Status;
GPL.StrokeColor = prev[i].StrokeColor;
GPL.StrokeOpacity = prev[i].StrokeOpacity;
GPL.StrokeWeight = prev[i].StrokeWeight;
GPL.Points = GooglePoints.CloneMe(prev[i].Points);
p.Add(GPL);
}
return p;
}
public GooglePolygon this[int pIndex]
{
get
{
return (GooglePolygon)this.List[pIndex];
}
set
{
this.List[pIndex] = value;
}
}
public GooglePolygon this[string pID]
{
get
{
for (int i = 0; i < Count; i++)
{
if (this[i].ID == pID)
{
return (GooglePolygon)this.List[i];
}
}
return null;
}
set
{
for (int i = 0; i < Count; i++)
{
if (this[i].ID == pID)
{
this.List[i] = value;
}
}
}
}
public void Add(GooglePolygon pPolygon)
{
this.List.Add(pPolygon);
}
public void Remove(int pIndex)
{
this.RemoveAt(pIndex);
}
public void Remove(string pID)
{
for (int i = 0; i < Count; i++)
{
if (this[i].ID == pID)
{
this.List.RemoveAt(i);
return;
}
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using ProtoBuf;
using QuantConnect.Logging;
using QuantConnect.Util;
using static QuantConnect.StringExtensions;
namespace QuantConnect.Data.Market
{
/// <summary>
/// QuoteBar class for second and minute resolution data:
/// An OHLC implementation of the QuantConnect BaseData class with parameters for candles.
/// </summary>
[ProtoContract(SkipConstructor = true)]
public class QuoteBar : BaseData, IBaseDataBar
{
// scale factor used in QC equity/option/indexOption data files
private const decimal _scaleFactor = 1 / 10000m;
/// <summary>
/// Average bid size
/// </summary>
[ProtoMember(201)]
public decimal LastBidSize { get; set; }
/// <summary>
/// Average ask size
/// </summary>
[ProtoMember(202)]
public decimal LastAskSize { get; set; }
/// <summary>
/// Bid OHLC
/// </summary>
[ProtoMember(203)]
public Bar Bid { get; set; }
/// <summary>
/// Ask OHLC
/// </summary>
[ProtoMember(204)]
public Bar Ask { get; set; }
/// <summary>
/// Opening price of the bar: Defined as the price at the start of the time period.
/// </summary>
public decimal Open
{
get
{
if (Bid != null && Ask != null)
{
if (Bid.Open != 0m && Ask.Open != 0m)
return (Bid.Open + Ask.Open) / 2m;
if (Bid.Open != 0)
return Bid.Open;
if (Ask.Open != 0)
return Ask.Open;
return 0m;
}
if (Bid != null)
{
return Bid.Open;
}
if (Ask != null)
{
return Ask.Open;
}
return 0m;
}
}
/// <summary>
/// High price of the QuoteBar during the time period.
/// </summary>
public decimal High
{
get
{
if (Bid != null && Ask != null)
{
if (Bid.High != 0m && Ask.High != 0m)
return (Bid.High + Ask.High) / 2m;
if (Bid.High != 0)
return Bid.High;
if (Ask.High != 0)
return Ask.High;
return 0m;
}
if (Bid != null)
{
return Bid.High;
}
if (Ask != null)
{
return Ask.High;
}
return 0m;
}
}
/// <summary>
/// Low price of the QuoteBar during the time period.
/// </summary>
public decimal Low
{
get
{
if (Bid != null && Ask != null)
{
if (Bid.Low != 0m && Ask.Low != 0m)
return (Bid.Low + Ask.Low) / 2m;
if (Bid.Low != 0)
return Bid.Low;
if (Ask.Low != 0)
return Ask.Low;
return 0m;
}
if (Bid != null)
{
return Bid.Low;
}
if (Ask != null)
{
return Ask.Low;
}
return 0m;
}
}
/// <summary>
/// Closing price of the QuoteBar. Defined as the price at Start Time + TimeSpan.
/// </summary>
public decimal Close
{
get
{
if (Bid != null && Ask != null)
{
if (Bid.Close != 0m && Ask.Close != 0m)
return (Bid.Close + Ask.Close) / 2m;
if (Bid.Close != 0)
return Bid.Close;
if (Ask.Close != 0)
return Ask.Close;
return 0m;
}
if (Bid != null)
{
return Bid.Close;
}
if (Ask != null)
{
return Ask.Close;
}
return Value;
}
}
/// <summary>
/// The closing time of this bar, computed via the Time and Period
/// </summary>
public override DateTime EndTime
{
get { return Time + Period; }
set { Period = value - Time; }
}
/// <summary>
/// The period of this quote bar, (second, minute, daily, ect...)
/// </summary>
[ProtoMember(205)]
public TimeSpan Period { get; set; }
/// <summary>
/// Default initializer to setup an empty quotebar.
/// </summary>
public QuoteBar()
{
Symbol = Symbol.Empty;
Time = new DateTime();
Bid = new Bar();
Ask = new Bar();
Value = 0;
Period = TimeSpan.FromMinutes(1);
DataType = MarketDataType.QuoteBar;
}
/// <summary>
/// Initialize Quote Bar with Bid(OHLC) and Ask(OHLC) Values:
/// </summary>
/// <param name="time">DateTime Timestamp of the bar</param>
/// <param name="symbol">Market MarketType Symbol</param>
/// <param name="bid">Bid OLHC bar</param>
/// <param name="lastBidSize">Average bid size over period</param>
/// <param name="ask">Ask OLHC bar</param>
/// <param name="lastAskSize">Average ask size over period</param>
/// <param name="period">The period of this bar, specify null for default of 1 minute</param>
public QuoteBar(DateTime time, Symbol symbol, IBar bid, decimal lastBidSize, IBar ask, decimal lastAskSize, TimeSpan? period = null)
{
Symbol = symbol;
Time = time;
Bid = bid == null ? null : new Bar(bid.Open, bid.High, bid.Low, bid.Close);
Ask = ask == null ? null : new Bar(ask.Open, ask.High, ask.Low, ask.Close);
if (Bid != null) LastBidSize = lastBidSize;
if (Ask != null) LastAskSize = lastAskSize;
Value = Close;
Period = period ?? TimeSpan.FromMinutes(1);
DataType = MarketDataType.QuoteBar;
}
/// <summary>
/// Update the quotebar - build the bar from this pricing information:
/// </summary>
/// <param name="lastTrade">The last trade price</param>
/// <param name="bidPrice">Current bid price</param>
/// <param name="askPrice">Current asking price</param>
/// <param name="volume">Volume of this trade</param>
/// <param name="bidSize">The size of the current bid, if available, if not, pass 0</param>
/// <param name="askSize">The size of the current ask, if available, if not, pass 0</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void Update(decimal lastTrade, decimal bidPrice, decimal askPrice, decimal volume, decimal bidSize, decimal askSize)
{
// update our bid and ask bars - handle null values, this is to give good values for midpoint OHLC
if (Bid == null && bidPrice != 0) Bid = new Bar(bidPrice, bidPrice, bidPrice, bidPrice);
else if (Bid != null) Bid.Update(ref bidPrice);
if (Ask == null && askPrice != 0) Ask = new Bar(askPrice, askPrice, askPrice, askPrice);
else if (Ask != null) Ask.Update(ref askPrice);
if (bidSize > 0)
{
LastBidSize = bidSize;
}
if (askSize > 0)
{
LastAskSize = askSize;
}
// be prepared for updates without trades
if (lastTrade != 0) Value = lastTrade;
else if (askPrice != 0) Value = askPrice;
else if (bidPrice != 0) Value = bidPrice;
}
/// <summary>
/// QuoteBar Reader: Fetch the data from the QC storage and feed it line by line into the engine.
/// </summary>
/// <param name="config">Symbols, Resolution, DataType, </param>
/// <param name="stream">The file data stream</param>
/// <param name="date">Date of this reader request</param>
/// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param>
/// <returns>Enumerable iterator for returning each line of the required data.</returns>
public override BaseData Reader(SubscriptionDataConfig config, StreamReader stream, DateTime date, bool isLiveMode)
{
try
{
switch (config.SecurityType)
{
case SecurityType.Equity:
return ParseEquity(config, stream, date);
case SecurityType.Forex:
case SecurityType.Crypto:
return ParseForex(config, stream, date);
case SecurityType.Cfd:
return ParseCfd(config, stream, date);
case SecurityType.Option:
case SecurityType.FutureOption:
case SecurityType.IndexOption:
return ParseOption(config, stream, date);
case SecurityType.Future:
return ParseFuture(config, stream, date);
}
}
catch (Exception err)
{
Log.Error(Invariant($"QuoteBar.Reader(): Error parsing stream, Symbol: {config.Symbol.Value}, SecurityType: {config.SecurityType}, ") +
Invariant($"Resolution: {config.Resolution}, Date: {date.ToStringInvariant("yyyy-MM-dd")}, Message: {err}")
);
}
// we need to consume a line anyway, to advance the stream
stream.ReadLine();
// if we couldn't parse it above return a default instance
return new QuoteBar { Symbol = config.Symbol, Period = config.Increment };
}
/// <summary>
/// QuoteBar Reader: Fetch the data from the QC storage and feed it line by line into the engine.
/// </summary>
/// <param name="config">Symbols, Resolution, DataType, </param>
/// <param name="line">Line from the data file requested</param>
/// <param name="date">Date of this reader request</param>
/// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param>
/// <returns>Enumerable iterator for returning each line of the required data.</returns>
public override BaseData Reader(SubscriptionDataConfig config, string line, DateTime date, bool isLiveMode)
{
try
{
switch (config.SecurityType)
{
case SecurityType.Equity:
return ParseEquity(config, line, date);
case SecurityType.Forex:
case SecurityType.Crypto:
return ParseForex(config, line, date);
case SecurityType.Cfd:
return ParseCfd(config, line, date);
case SecurityType.Option:
case SecurityType.FutureOption:
case SecurityType.IndexOption:
return ParseOption(config, line, date);
case SecurityType.Future:
return ParseFuture(config, line, date);
}
}
catch (Exception err)
{
Log.Error(Invariant($"QuoteBar.Reader(): Error parsing line: '{line}', Symbol: {config.Symbol.Value}, SecurityType: {config.SecurityType}, ") +
Invariant($"Resolution: {config.Resolution}, Date: {date.ToStringInvariant("yyyy-MM-dd")}, Message: {err}")
);
}
// if we couldn't parse it above return a default instance
return new QuoteBar { Symbol = config.Symbol, Period = config.Increment };
}
private static bool HasShownWarning;
/// <summary>
/// "Scaffold" code - If the data being read is formatted as a TradeBar, use this method to deserialize it
/// TODO: Once all Forex data refactored to use QuoteBar formatted data, remove this method
/// </summary>
/// <param name="config">Symbols, Resolution, DataType, </param>
/// <param name="line">Line from the data file requested</param>
/// <param name="date">Date of this reader request</param>
/// <returns><see cref="QuoteBar"/> with the bid/ask prices set to same values</returns>
[Obsolete("All Forex data should use Quotes instead of Trades.")]
private QuoteBar ParseTradeAsQuoteBar(SubscriptionDataConfig config, DateTime date, string line)
{
if (!HasShownWarning)
{
Logging.Log.Error("QuoteBar.ParseTradeAsQuoteBar(): Data formatted as Trade when Quote format was expected. Support for this will disappear June 2017.");
HasShownWarning = true;
}
var quoteBar = new QuoteBar
{
Period = config.Increment,
Symbol = config.Symbol
};
var csv = line.ToCsv(5);
if (config.Resolution == Resolution.Daily || config.Resolution == Resolution.Hour)
{
// hourly and daily have different time format, and can use slow, robust c# parser.
quoteBar.Time = DateTime.ParseExact(csv[0], DateFormat.TwelveCharacter, CultureInfo.InvariantCulture).ConvertTo(config.DataTimeZone, config.ExchangeTimeZone);
}
else
{
//Fast decimal conversion
quoteBar.Time = date.Date.AddMilliseconds(csv[0].ToInt32()).ConvertTo(config.DataTimeZone, config.ExchangeTimeZone);
}
var bid = new Bar
{
Open = csv[1].ToDecimal(),
High = csv[2].ToDecimal(),
Low = csv[3].ToDecimal(),
Close = csv[4].ToDecimal()
};
var ask = new Bar
{
Open = csv[1].ToDecimal(),
High = csv[2].ToDecimal(),
Low = csv[3].ToDecimal(),
Close = csv[4].ToDecimal()
};
quoteBar.Ask = ask;
quoteBar.Bid = bid;
quoteBar.Value = quoteBar.Close;
return quoteBar;
}
/// <summary>
/// Parse a quotebar representing a future with a scaling factor
/// </summary>
/// <param name="config">Symbols, Resolution, DataType</param>
/// <param name="line">Line from the data file requested</param>
/// <param name="date">Date of this reader request</param>
/// <returns><see cref="QuoteBar"/> with the bid/ask set to same values</returns>
public QuoteBar ParseFuture(SubscriptionDataConfig config, string line, DateTime date)
{
return ParseQuote(config, date, line, false);
}
/// <summary>
/// Parse a quotebar representing a future with a scaling factor
/// </summary>
/// <param name="config">Symbols, Resolution, DataType</param>
/// <param name="streamReader">The data stream of the requested file</param>
/// <param name="date">Date of this reader request</param>
/// <returns><see cref="QuoteBar"/> with the bid/ask set to same values</returns>
public QuoteBar ParseFuture(SubscriptionDataConfig config, StreamReader streamReader, DateTime date)
{
return ParseQuote(config, date, streamReader, false);
}
/// <summary>
/// Parse a quotebar representing an option with a scaling factor
/// </summary>
/// <param name="config">Symbols, Resolution, DataType</param>
/// <param name="line">Line from the data file requested</param>
/// <param name="date">Date of this reader request</param>
/// <returns><see cref="QuoteBar"/> with the bid/ask set to same values</returns>
public QuoteBar ParseOption(SubscriptionDataConfig config, string line, DateTime date)
{
return ParseQuote(config, date, line, OptionUseScaleFactor(config.Symbol));
}
/// <summary>
/// Parse a quotebar representing an option with a scaling factor
/// </summary>
/// <param name="config">Symbols, Resolution, DataType</param>
/// <param name="streamReader">The data stream of the requested file</param>
/// <param name="date">Date of this reader request</param>
/// <returns><see cref="QuoteBar"/> with the bid/ask set to same values</returns>
public QuoteBar ParseOption(SubscriptionDataConfig config, StreamReader streamReader, DateTime date)
{
// scale factor only applies for equity and index options
return ParseQuote(config, date, streamReader, useScaleFactor: OptionUseScaleFactor(config.Symbol));
}
/// <summary>
/// Helper method that defines the types of options that should use scale factor
/// </summary>
/// <param name="symbol"></param>
/// <returns></returns>
private static bool OptionUseScaleFactor(Symbol symbol)
{
return symbol.SecurityType == SecurityType.Option ||
symbol.SecurityType == SecurityType.IndexOption;
}
/// <summary>
/// Parse a quotebar representing a cfd without a scaling factor
/// </summary>
/// <param name="config">Symbols, Resolution, DataType</param>
/// <param name="line">Line from the data file requested</param>
/// <param name="date">Date of this reader request</param>
/// <returns><see cref="QuoteBar"/> with the bid/ask set to same values</returns>
public QuoteBar ParseCfd(SubscriptionDataConfig config, string line, DateTime date)
{
return ParseQuote(config, date, line, false);
}
/// <summary>
/// Parse a quotebar representing a cfd without a scaling factor
/// </summary>
/// <param name="config">Symbols, Resolution, DataType</param>
/// <param name="streamReader">The data stream of the requested file</param>
/// <param name="date">Date of this reader request</param>
/// <returns><see cref="QuoteBar"/> with the bid/ask set to same values</returns>
public QuoteBar ParseCfd(SubscriptionDataConfig config, StreamReader streamReader, DateTime date)
{
return ParseQuote(config, date, streamReader, false);
}
/// <summary>
/// Parse a quotebar representing a forex without a scaling factor
/// </summary>
/// <param name="config">Symbols, Resolution, DataType</param>
/// <param name="line">Line from the data file requested</param>
/// <param name="date">Date of this reader request</param>
/// <returns><see cref="QuoteBar"/> with the bid/ask set to same values</returns>
public QuoteBar ParseForex(SubscriptionDataConfig config, string line, DateTime date)
{
return ParseQuote(config, date, line, false);
}
/// <summary>
/// Parse a quotebar representing a forex without a scaling factor
/// </summary>
/// <param name="config">Symbols, Resolution, DataType</param>
/// <param name="streamReader">The data stream of the requested file</param>
/// <param name="date">Date of this reader request</param>
/// <returns><see cref="QuoteBar"/> with the bid/ask set to same values</returns>
public QuoteBar ParseForex(SubscriptionDataConfig config, StreamReader streamReader, DateTime date)
{
return ParseQuote(config, date, streamReader, false);
}
/// <summary>
/// Parse a quotebar representing an equity with a scaling factor
/// </summary>
/// <param name="config">Symbols, Resolution, DataType</param>
/// <param name="line">Line from the data file requested</param>
/// <param name="date">Date of this reader request</param>
/// <returns><see cref="QuoteBar"/> with the bid/ask set to same values</returns>
public QuoteBar ParseEquity(SubscriptionDataConfig config, string line, DateTime date)
{
return ParseQuote(config, date, line, true);
}
/// <summary>
/// Parse a quotebar representing an equity with a scaling factor
/// </summary>
/// <param name="config">Symbols, Resolution, DataType</param>
/// <param name="streamReader">The data stream of the requested file</param>
/// <param name="date">Date of this reader request</param>
/// <returns><see cref="QuoteBar"/> with the bid/ask set to same values</returns>
public QuoteBar ParseEquity(SubscriptionDataConfig config, StreamReader streamReader, DateTime date)
{
return ParseQuote(config, date, streamReader, true);
}
/// <summary>
/// "Scaffold" code - If the data being read is formatted as a QuoteBar, use this method to deserialize it
/// </summary>
/// <param name="config">Symbols, Resolution, DataType, </param>
/// <param name="streamReader">The data stream of the requested file</param>
/// <param name="date">Date of this reader request</param>
/// <param name="useScaleFactor">Whether the data has a scaling factor applied</param>
/// <returns><see cref="QuoteBar"/> with the bid/ask prices set appropriately</returns>
private QuoteBar ParseQuote(SubscriptionDataConfig config, DateTime date, StreamReader streamReader, bool useScaleFactor)
{
// Non-equity asset classes will not use scaling, including options that have a non-equity underlying asset class.
var scaleFactor = useScaleFactor
? _scaleFactor
: 1;
var quoteBar = new QuoteBar
{
Period = config.Increment,
Symbol = config.Symbol
};
if (config.Resolution == Resolution.Daily || config.Resolution == Resolution.Hour)
{
// hourly and daily have different time format, and can use slow, robust c# parser.
quoteBar.Time = streamReader.GetDateTime().ConvertTo(config.DataTimeZone, config.ExchangeTimeZone);
}
else
{
// Using custom int conversion for speed on high resolution data.
quoteBar.Time = date.Date.AddMilliseconds(streamReader.GetInt32()).ConvertTo(config.DataTimeZone, config.ExchangeTimeZone);
}
var open = streamReader.GetDecimal();
var high = streamReader.GetDecimal();
var low = streamReader.GetDecimal();
var close = streamReader.GetDecimal();
var lastSize = streamReader.GetDecimal();
// only create the bid if it exists in the file
if (open != 0 || high != 0 || low != 0 || close != 0)
{
quoteBar.Bid = new Bar
{
Open = open * scaleFactor,
High = high * scaleFactor,
Low = low * scaleFactor,
Close = close * scaleFactor
};
quoteBar.LastBidSize = lastSize;
}
else
{
quoteBar.Bid = null;
}
open = streamReader.GetDecimal();
high = streamReader.GetDecimal();
low = streamReader.GetDecimal();
close = streamReader.GetDecimal();
lastSize = streamReader.GetDecimal();
// only create the ask if it exists in the file
if (open != 0 || high != 0 || low != 0 || close != 0)
{
quoteBar.Ask = new Bar
{
Open = open * scaleFactor,
High = high * scaleFactor,
Low = low * scaleFactor,
Close = close * scaleFactor
};
quoteBar.LastAskSize = lastSize;
}
else
{
quoteBar.Ask = null;
}
quoteBar.Value = quoteBar.Close;
return quoteBar;
}
/// <summary>
/// "Scaffold" code - If the data being read is formatted as a QuoteBar, use this method to deserialize it
/// TODO: Once all Forex data refactored to use QuoteBar formatted data, use only this method
/// </summary>
/// <param name="config">Symbols, Resolution, DataType, </param>
/// <param name="line">Line from the data file requested</param>
/// <param name="date">Date of this reader request</param>
/// <param name="useScaleFactor">Whether the data has a scaling factor applied</param>
/// <returns><see cref="QuoteBar"/> with the bid/ask prices set appropriately</returns>
private QuoteBar ParseQuote(SubscriptionDataConfig config, DateTime date, string line, bool useScaleFactor)
{
var scaleFactor = useScaleFactor
? _scaleFactor
: 1;
var quoteBar = new QuoteBar
{
Period = config.Increment,
Symbol = config.Symbol
};
var csv = line.ToCsv(10);
if (config.Resolution == Resolution.Daily || config.Resolution == Resolution.Hour)
{
// hourly and daily have different time format, and can use slow, robust c# parser.
quoteBar.Time = DateTime.ParseExact(csv[0], DateFormat.TwelveCharacter, CultureInfo.InvariantCulture).ConvertTo(config.DataTimeZone, config.ExchangeTimeZone);
}
else
{
// Using custom "ToDecimal" conversion for speed on high resolution data.
quoteBar.Time = date.Date.AddMilliseconds((double)csv[0].ToDecimal()).ConvertTo(config.DataTimeZone, config.ExchangeTimeZone);
}
// only create the bid if it exists in the file
if (csv[1].Length != 0 || csv[2].Length != 0 || csv[3].Length != 0 || csv[4].Length != 0)
{
quoteBar.Bid = new Bar
{
Open = csv[1].ToDecimal() * scaleFactor,
High = csv[2].ToDecimal() * scaleFactor,
Low = csv[3].ToDecimal() * scaleFactor,
Close = csv[4].ToDecimal() * scaleFactor
};
quoteBar.LastBidSize = csv.Count == 6 ? csv[5].ToDecimal() : 0m;
}
else
{
quoteBar.Bid = null;
}
// only create the ask if it exists in the file
if (csv.Count == 10 && (csv[6].Length != 0 || csv[7].Length != 0 || csv[8].Length != 0 || csv[9].Length != 0))
{
quoteBar.Ask = new Bar
{
Open = csv[6].ToDecimal() * scaleFactor,
High = csv[7].ToDecimal() * scaleFactor,
Low = csv[8].ToDecimal() * scaleFactor,
Close = csv[9].ToDecimal() * scaleFactor
};
quoteBar.LastAskSize = csv[10].ToDecimal();
}
else
{
quoteBar.Ask = null;
}
quoteBar.Value = quoteBar.Close;
return quoteBar;
}
/// <summary>
/// Get Source for Custom Data File
/// >> What source file location would you prefer for each type of usage:
/// </summary>
/// <param name="config">Configuration object</param>
/// <param name="date">Date of this source request if source spread across multiple files</param>
/// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param>
/// <returns>String source location of the file</returns>
public override SubscriptionDataSource GetSource(SubscriptionDataConfig config, DateTime date, bool isLiveMode)
{
if (isLiveMode)
{
// this data type is streamed in live mode
return new SubscriptionDataSource(string.Empty, SubscriptionTransportMedium.Streaming);
}
var source = LeanData.GenerateZipFilePath(Globals.DataFolder, config.Symbol, date, config.Resolution, config.TickType);
if (config.SecurityType == SecurityType.Future || config.SecurityType.IsOption())
{
source += "#" + LeanData.GenerateZipEntryName(config.Symbol, date, config.Resolution, config.TickType);
}
return new SubscriptionDataSource(source, SubscriptionTransportMedium.LocalFile, FileFormat.Csv);
}
/// <summary>
/// Return a new instance clone of this quote bar, used in fill forward
/// </summary>
/// <returns>A clone of the current quote bar</returns>
public override BaseData Clone()
{
return new QuoteBar
{
Ask = Ask == null ? null : Ask.Clone(),
Bid = Bid == null ? null : Bid.Clone(),
LastAskSize = LastAskSize,
LastBidSize = LastBidSize,
Symbol = Symbol,
Time = Time,
Period = Period,
Value = Value,
DataType = DataType
};
}
/// <summary>
/// Collapses QuoteBars into TradeBars object when
/// algorithm requires FX data, but calls OnData(<see cref="TradeBars"/>)
/// TODO: (2017) Remove this method in favor of using OnData(<see cref="Slice"/>)
/// </summary>
/// <returns><see cref="TradeBars"/></returns>
public TradeBar Collapse()
{
return new TradeBar(Time, Symbol, Open, High, Low, Close, 0)
{
Period = Period
};
}
/// <summary>
/// Convert this <see cref="QuoteBar"/> to string form.
/// </summary>
/// <returns>String representation of the <see cref="QuoteBar"/></returns>
public override string ToString()
{
return $"{Symbol}: " +
$"Bid: O: {Bid?.Open.SmartRounding()} " +
$"Bid: H: {Bid?.High.SmartRounding()} " +
$"Bid: L: {Bid?.Low.SmartRounding()} " +
$"Bid: C: {Bid?.Close.SmartRounding()} " +
$"Ask: O: {Ask?.Open.SmartRounding()} " +
$"Ask: H: {Ask?.High.SmartRounding()} " +
$"Ask: L: {Ask?.Low.SmartRounding()} " +
$"Ask: C: {Ask?.Close.SmartRounding()} ";
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DomainUpDown.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms {
using System.Diagnostics;
using System;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;
using System.Globalization;
using System.Windows.Forms.Layout;
using System.Collections;
using Microsoft.Win32;
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown"]/*' />
/// <devdoc>
/// <para>Represents a Windows up-down control that displays string values.</para>
/// </devdoc>
[
ComVisible(true),
ClassInterface(ClassInterfaceType.AutoDispatch),
DefaultProperty("Items"),
DefaultEvent("SelectedItemChanged"),
DefaultBindingProperty("SelectedItem"),
SRDescription(SR.DescriptionDomainUpDown)
]
public class DomainUpDown : UpDownBase {
private readonly static string DefaultValue = "";
private readonly static bool DefaultWrap = false;
//////////////////////////////////////////////////////////////
// Member variables
//
//////////////////////////////////////////////////////////////
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.domainItems"]/*' />
/// <devdoc>
/// Allowable strings for the domain updown.
/// </devdoc>
private DomainUpDownItemCollection domainItems = null;
private string stringValue = DefaultValue; // Current string value
private int domainIndex = -1; // Index in the domain list
private bool sorted = false; // Sort the domain values
private bool wrap = DefaultWrap; // Wrap around domain items
private EventHandler onSelectedItemChanged = null;
private bool inSort = false;
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.DomainUpDown"]/*' />
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Windows.Forms.DomainUpDown'/> class.
/// </para>
/// </devdoc>
public DomainUpDown() : base() {
// this class overrides GetPreferredSizeCore, let Control automatically cache the result
SetState2(STATE2_USEPREFERREDSIZECACHE, true);
Text = String.Empty;
}
// Properties
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.Items"]/*' />
/// <devdoc>
/// <para>
/// Gets the collection of objects assigned to the
/// up-down control.
/// </para>
/// </devdoc>
[
SRCategory(SR.CatData),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
SRDescription(SR.DomainUpDownItemsDescr),
Localizable(true),
Editor("System.Windows.Forms.Design.StringCollectionEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor))
]
public DomainUpDownItemCollection Items {
get {
if (domainItems == null) {
domainItems = new DomainUpDownItemCollection(this);
}
return domainItems;
}
}
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.Padding"]/*' />
/// <devdoc>
/// <para>
/// <para>[To be supplied.]</para>
/// </para>
/// </devdoc>
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public new Padding Padding {
get { return base.Padding; }
set { base.Padding = value;}
}
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never)
]
public new event EventHandler PaddingChanged {
add { base.PaddingChanged += value; }
remove { base.PaddingChanged -= value; }
}
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.SelectedIndex"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the index value of the selected item.
/// </para>
/// </devdoc>
[
Browsable(false),
DefaultValue(-1),
SRCategory(SR.CatAppearance),
SRDescription(SR.DomainUpDownSelectedIndexDescr)
]
public int SelectedIndex {
get {
if (UserEdit) {
return -1;
}
else {
return domainIndex;
}
}
set {
if (value < -1 || value >= Items.Count) {
throw new ArgumentOutOfRangeException("SelectedIndex", SR.GetString(SR.InvalidArgument, "SelectedIndex", (value).ToString(CultureInfo.CurrentCulture)));
}
if (value != SelectedIndex) {
SelectIndex(value);
}
}
}
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.SelectedItem"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the selected item based on the index value
/// of the selected item in the
/// collection.
/// </para>
/// </devdoc>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
SRDescription(SR.DomainUpDownSelectedItemDescr)
]
public object SelectedItem {
get {
int index = SelectedIndex;
return(index == -1) ? null : Items[index];
}
set {
// Treat null as selecting no item
//
if (value == null) {
SelectedIndex = -1;
}
else {
// Attempt to find the given item in the list of items
//
for (int i = 0; i < Items.Count; i++) {
if (value != null && value.Equals(Items[i])) {
SelectedIndex = i;
break;
}
}
}
}
}
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.Sorted"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets a value indicating whether the item collection is sorted.
/// </para>
/// </devdoc>
[
SRCategory(SR.CatBehavior),
DefaultValue(false),
SRDescription(SR.DomainUpDownSortedDescr)
]
public bool Sorted {
get {
return sorted;
}
set {
sorted = value;
if (sorted) {
SortDomainItems();
}
}
}
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.Wrap"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets a value indicating whether the collection of items continues to
/// the first or last item if the user continues past the end of the list.
/// </para>
/// </devdoc>
[
SRCategory(SR.CatBehavior),
Localizable(true),
DefaultValue(false),
SRDescription(SR.DomainUpDownWrapDescr)
]
public bool Wrap {
get {
return wrap;
}
set {
wrap = value;
}
}
//////////////////////////////////////////////////////////////
// Methods
//
//////////////////////////////////////////////////////////////
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.SelectedItemChanged"]/*' />
/// <devdoc>
/// <para>
/// Occurs when the <see cref='System.Windows.Forms.DomainUpDown.SelectedItem'/> property has
/// been changed.
/// </para>
/// </devdoc>
[SRCategory(SR.CatBehavior), SRDescription(SR.DomainUpDownOnSelectedItemChangedDescr)]
public event EventHandler SelectedItemChanged {
add {
onSelectedItemChanged += value;
}
remove {
onSelectedItemChanged -= value;
}
}
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.CreateAccessibilityInstance"]/*' />
/// <internalonly/>
/// <devdoc>
/// Constructs the new instance of the accessibility object for this control. Subclasses
/// should not call base.CreateAccessibilityObject.
/// </devdoc>
protected override AccessibleObject CreateAccessibilityInstance() {
return new DomainUpDownAccessibleObject(this);
}
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.DownButton"]/*' />
/// <devdoc>
/// <para>
/// Displays the next item in the object collection.
/// </para>
/// </devdoc>
public override void DownButton() {
// Make sure domain values exist, and there are >0 items
//
if (domainItems == null) {
return;
}
if (domainItems.Count <= 0) {
return;
}
// If the user has entered text, attempt to match it to the domain list
//
int matchIndex = -1;
if (UserEdit) {
matchIndex = MatchIndex(Text, false, domainIndex);
}
if (matchIndex != -1) {
// Found a match, so select this value
//
SelectIndex(matchIndex);
}
// Otherwise, get the next string in the domain list
//
else {
if (domainIndex < domainItems.Count - 1) {
SelectIndex(domainIndex + 1);
}
else if (Wrap) {
SelectIndex(0);
}
}
}
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.MatchIndex"]/*' />
/// <devdoc>
/// Tries to find a match of the supplied text in the domain list.
/// If complete is true, a complete match is required for success
/// (i.e. the supplied text is the same length as the matched domain value)
/// Returns the index in the domain list if the match is successful,
/// returns -1 otherwise.
/// </devdoc>
internal int MatchIndex(string text, bool complete) {
return MatchIndex(text, complete, domainIndex);
}
internal int MatchIndex(string text, bool complete, int startPosition) {
// Make sure domain values exist
if (domainItems == null) {
return -1;
}
// Sanity check of parameters
if (text.Length < 1) {
return -1;
}
if (domainItems.Count <= 0) {
return -1;
}
if (startPosition < 0) {
startPosition = domainItems.Count - 1;
}
if (startPosition >= domainItems.Count) {
startPosition = 0;
}
// Attempt to match the supplied string text with
// the domain list. Returns the index in the list if successful,
// otherwise returns -1.
int index = startPosition;
int matchIndex = -1;
bool found = false;
if (!complete) {
text = text.ToUpper(CultureInfo.InvariantCulture);
}
// Attempt to match the string with Items[index]
do {
if (complete)
found = Items[index].ToString().Equals(text);
else
found = Items[index].ToString().ToUpper(CultureInfo.InvariantCulture).StartsWith(text);
if (found) {
matchIndex = index;
}
// Calculate the next index to attempt to match
index++;
if (index >= domainItems.Count) {
index = 0;
}
} while (!found && index != startPosition);
return matchIndex;
}
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.OnChanged"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>
/// In the case of a DomainUpDown, the handler for changing
/// values is called OnSelectedItemChanged - so just forward it to that
/// function.
/// </para>
/// </devdoc>
protected override void OnChanged(object source, EventArgs e) {
OnSelectedItemChanged(source, e);
}
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.OnTextBoxKeyPress"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>Handles the <see cref='System.Windows.Forms.Control.KeyPress'/>
/// event, using the input character to find the next matching item in our
/// item collection.</para>
/// </devdoc>
protected override void OnTextBoxKeyPress(object source, KeyPressEventArgs e) {
if (ReadOnly) {
char[] character = new char[] { e.KeyChar };
UnicodeCategory uc = Char.GetUnicodeCategory(character[0]);
if (uc == UnicodeCategory.LetterNumber
|| uc == UnicodeCategory.LowercaseLetter
|| uc == UnicodeCategory.DecimalDigitNumber
|| uc == UnicodeCategory.MathSymbol
|| uc == UnicodeCategory.OtherLetter
|| uc == UnicodeCategory.OtherNumber
|| uc == UnicodeCategory.UppercaseLetter) {
// Attempt to match the character to a domain item
int matchIndex = MatchIndex(new string(character), false, domainIndex + 1);
if (matchIndex != -1) {
// Select the matching domain item
SelectIndex(matchIndex);
}
e.Handled = true;
}
}
base.OnTextBoxKeyPress(source, e);
}
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.OnSelectedItemChanged"]/*' />
/// <devdoc>
/// <para>
/// Raises the <see cref='System.Windows.Forms.DomainUpDown.SelectedItemChanged'/> event.
/// </para>
/// </devdoc>
protected void OnSelectedItemChanged(object source, EventArgs e) {
// Call the event handler
if (onSelectedItemChanged != null) {
onSelectedItemChanged(this, e);
}
}
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.SelectIndex"]/*' />
/// <devdoc>
/// Selects the item in the domain list at the given index
/// </devdoc>
private void SelectIndex(int index) {
// Sanity check index
Debug.Assert(domainItems != null, "Domain values array is null");
Debug.Assert(index < domainItems.Count && index >= -1, "SelectValue: index out of range");
if (domainItems == null || index < -1 || index >= domainItems.Count) {
// Defensive programming
index = -1;
return;
}
// If the selected index has changed, update the text
//
domainIndex = index;
if (domainIndex >= 0) {
stringValue = domainItems[domainIndex].ToString();
UserEdit = false;
UpdateEditText();
}
else {
UserEdit = true;
}
Debug.Assert(domainIndex >=0 || UserEdit == true, "UserEdit should be true when domainIndex < 0 " + UserEdit);
}
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.SortDomainItems"]/*' />
/// <devdoc>
/// Sorts the domain values
/// </devdoc>
private void SortDomainItems() {
if (inSort)
return;
inSort = true;
try {
// Sanity check
Debug.Assert(sorted == true, "Sorted == false");
if (!sorted) {
return;
}
if (domainItems != null) {
// Sort the domain values
ArrayList.Adapter(domainItems).Sort(new DomainUpDownItemCompare());
// Update the domain index
if (!UserEdit) {
int newIndex = MatchIndex(stringValue, true);
if (newIndex != -1) {
SelectIndex(newIndex);
}
}
}
}
finally {
inSort = false;
}
}
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.ToString"]/*' />
/// <devdoc>
/// Provides some interesting info about this control in String form.
/// </devdoc>
/// <internalonly/>
public override string ToString() {
string s = base.ToString();
if (Items != null) {
s += ", Items.Count: " + Items.Count.ToString(CultureInfo.CurrentCulture);
s += ", SelectedIndex: " + SelectedIndex.ToString(CultureInfo.CurrentCulture);
}
return s;
}
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.UpButton"]/*' />
/// <devdoc>
/// <para>
/// Displays the previous item in the collection.
/// </para>
/// </devdoc>
public override void UpButton() {
// Make sure domain values exist, and there are >0 items
if (domainItems == null) {
return;
}
if (domainItems.Count <= 0) {
return;
}
if (domainIndex == -1) {
return;
}
// If the user has entered text, attempt to match it to the domain list
int matchIndex = -1;
if (UserEdit) {
matchIndex = MatchIndex(Text, false, domainIndex);
}
if (matchIndex != -1) {
// Found a match, so set the domain index accordingly
SelectIndex(matchIndex);
}
// Otherwise, get the previous string in the domain list
else {
if (domainIndex > 0) {
SelectIndex(domainIndex - 1);
}
else if (Wrap) {
SelectIndex(domainItems.Count - 1);
}
}
}
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.UpdateEditText"]/*' />
/// <devdoc>
/// <para>
/// Updates the text in the up-down control to display the selected item.
/// </para>
/// </devdoc>
protected override void UpdateEditText() {
Debug.Assert(!UserEdit, "UserEdit should be false");
// Defensive programming
UserEdit = false;
ChangingText = true;
Text = stringValue;
}
// This is not a breaking change -- Even though this control previously autosized to hieght,
// it didn't actually have an AutoSize property. The new AutoSize property enables the
// smarter behavior.
internal override Size GetPreferredSizeCore(Size proposedConstraints) {
int height = PreferredHeight;
int width = LayoutUtils.OldGetLargestStringSizeInCollection(Font, Items).Width;
// AdjuctWindowRect with our border, since textbox is borderless.
width = SizeFromClientSize(width, height).Width + upDownButtons.Width;
return new Size(width, height) + Padding.Size;
}
// DomainUpDown collection class
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.DomainUpDownItemCollection"]/*' />
/// <devdoc>
/// <para>Encapsulates a collection of objects for use by the <see cref='System.Windows.Forms.DomainUpDown'/>
/// class.</para>
/// </devdoc>
public class DomainUpDownItemCollection : ArrayList {
DomainUpDown owner;
internal DomainUpDownItemCollection(DomainUpDown owner)
: base() {
this.owner = owner;
}
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.DomainUpDownItemCollection.this"]/*' />
/// <devdoc>
/// </devdoc>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public override object this[int index] {
get {
return base[index];
}
set {
base[index] = value;
if (owner.SelectedIndex == index) {
owner.SelectIndex(index);
}
if (owner.Sorted) {
owner.SortDomainItems();
}
}
}
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.DomainUpDownItemCollection.Add"]/*' />
/// <devdoc>
/// </devdoc>
public override int Add(object item) {
// Overridden to perform sorting after adding an item
int ret = base.Add(item);
if (owner.Sorted) {
owner.SortDomainItems();
}
return ret;
}
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.DomainUpDownItemCollection.Remove"]/*' />
/// <devdoc>
/// </devdoc>
public override void Remove(object item) {
int index = IndexOf(item);
if (index == -1) {
throw new ArgumentOutOfRangeException("item", SR.GetString(SR.InvalidArgument, "item", item.ToString()));
}
else {
RemoveAt(index);
}
}
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.DomainUpDownItemCollection.RemoveAt"]/*' />
/// <devdoc>
/// </devdoc>
public override void RemoveAt(int item) {
// Overridden to update the domain index if neccessary
base.RemoveAt(item);
if (item < owner.domainIndex) {
// The item removed was before the currently selected item
owner.SelectIndex(owner.domainIndex - 1);
}
else if (item == owner.domainIndex) {
// The currently selected item was removed
//
owner.SelectIndex(-1);
}
}
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.DomainUpDownItemCollection.Insert"]/*' />
/// <devdoc>
/// </devdoc>
public override void Insert(int index, object item) {
base.Insert(index, item);
if (owner.Sorted) {
owner.SortDomainItems();
}
}
} // end class DomainUpDownItemCollection
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.DomainUpDownItemCompare"]/*' />
/// <devdoc>
/// </devdoc>
private sealed class DomainUpDownItemCompare : IComparer {
public int Compare(object p, object q) {
if (p == q) return 0;
if (p == null || q == null) {
return 0;
}
return String.Compare(p.ToString(), q.ToString(), false, CultureInfo.CurrentCulture);
}
}
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.DomainUpDownAccessibleObject"]/*' />
/// <internalonly/>
/// <devdoc>
/// </devdoc>
[System.Runtime.InteropServices.ComVisible(true)]
public class DomainUpDownAccessibleObject : ControlAccessibleObject {
private DomainItemListAccessibleObject itemList;
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.DomainUpDownAccessibleObject.DomainUpDownAccessibleObject"]/*' />
/// <devdoc>
/// </devdoc>
public DomainUpDownAccessibleObject(Control owner) : base(owner) {
}
private DomainItemListAccessibleObject ItemList {
get {
if (itemList == null) {
itemList = new DomainItemListAccessibleObject(this);
}
return itemList;
}
}
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.DomainUpDownAccessibleObject.Role"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override AccessibleRole Role {
get {
AccessibleRole role = Owner.AccessibleRole;
if (role != AccessibleRole.Default) {
return role;
}
return AccessibleRole.ComboBox;
}
}
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.DomainUpDownAccessibleObject.GetChild"]/*' />
/// <devdoc>
/// </devdoc>
public override AccessibleObject GetChild(int index) {
switch(index) {
// TextBox child
//
case 0:
return ((UpDownBase)Owner).TextBox.AccessibilityObject.Parent;
// Up/down buttons
//
case 1:
return ((UpDownBase)Owner).UpDownButtonsInternal.AccessibilityObject.Parent;
case 2:
return ItemList;
}
return null;
}
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.DomainUpDownAccessibleObject.GetChildCount"]/*' />
/// <devdoc>
/// </devdoc>
public override int GetChildCount() {
return 3;
}
}
internal class DomainItemListAccessibleObject : AccessibleObject {
private DomainUpDownAccessibleObject parent;
public DomainItemListAccessibleObject(DomainUpDownAccessibleObject parent) : base() {
this.parent = parent;
}
public override string Name {
get {
string baseName = base.Name;
if (baseName == null || baseName.Length == 0) {
return "Items";
}
return baseName;
}
set {
base.Name = value;
}
}
public override AccessibleObject Parent {
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
get {
return parent;
}
}
public override AccessibleRole Role {
get {
return AccessibleRole.List;
}
}
public override AccessibleStates State {
get {
return AccessibleStates.Invisible | AccessibleStates.Offscreen;
}
}
public override AccessibleObject GetChild(int index) {
if (index >=0 && index < GetChildCount()) {
return new DomainItemAccessibleObject(((DomainUpDown)parent.Owner).Items[index].ToString(), this);
}
return null;
}
public override int GetChildCount() {
return ((DomainUpDown)parent.Owner).Items.Count;
}
}
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.DomainItemAccessibleObject"]/*' />
/// <internalonly/>
/// <devdoc>
/// </devdoc>
[System.Runtime.InteropServices.ComVisible(true)]
public class DomainItemAccessibleObject : AccessibleObject {
private string name;
private DomainItemListAccessibleObject parent;
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.DomainItemAccessibleObject.DomainItemAccessibleObject"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public DomainItemAccessibleObject(string name, AccessibleObject parent) : base() {
this.name = name;
this.parent = (DomainItemListAccessibleObject)parent;
}
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.DomainItemAccessibleObject.Name"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override string Name {
get {
return name;
}
set {
name = value;
}
}
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.DomainItemAccessibleObject.Parent"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override AccessibleObject Parent {
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
get {
return parent;
}
}
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.DomainItemAccessibleObject.Role"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override AccessibleRole Role {
get {
return AccessibleRole.ListItem;
}
}
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.DomainItemAccessibleObject.State"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override AccessibleStates State {
get {
return AccessibleStates.Selectable;
}
}
/// <include file='doc\DomainUpDown.uex' path='docs/doc[@for="DomainUpDown.DomainItemAccessibleObject.Value"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override string Value {
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
get {
return name;
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Net.Http.Headers;
namespace Microsoft.AspNetCore.Authentication.JwtBearer
{
/// <summary>
/// An <see cref="AuthenticationHandler{TOptions}"/> that can perform JWT-bearer based authentication.
/// </summary>
public class JwtBearerHandler : AuthenticationHandler<JwtBearerOptions>
{
private OpenIdConnectConfiguration? _configuration;
/// <summary>
/// Initializes a new instance of <see cref="JwtBearerHandler"/>.
/// </summary>
/// <inheritdoc />
public JwtBearerHandler(IOptionsMonitor<JwtBearerOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
: base(options, logger, encoder, clock)
{ }
/// <summary>
/// The handler calls methods on the events which give the application control at certain points where processing is occurring.
/// If it is not provided a default instance is supplied which does nothing when the methods are called.
/// </summary>
protected new JwtBearerEvents Events
{
get => (JwtBearerEvents)base.Events!;
set => base.Events = value;
}
/// <inheritdoc />
protected override Task<object> CreateEventsAsync() => Task.FromResult<object>(new JwtBearerEvents());
/// <summary>
/// Searches the 'Authorization' header for a 'Bearer' token. If the 'Bearer' token is found, it is validated using <see cref="TokenValidationParameters"/> set in the options.
/// </summary>
/// <returns></returns>
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
string? token = null;
try
{
// Give application opportunity to find from a different location, adjust, or reject token
var messageReceivedContext = new MessageReceivedContext(Context, Scheme, Options);
// event can set the token
await Events.MessageReceived(messageReceivedContext);
if (messageReceivedContext.Result != null)
{
return messageReceivedContext.Result;
}
// If application retrieved token from somewhere else, use that.
token = messageReceivedContext.Token;
if (string.IsNullOrEmpty(token))
{
string authorization = Request.Headers.Authorization.ToString();
// If no authorization header found, nothing to process further
if (string.IsNullOrEmpty(authorization))
{
return AuthenticateResult.NoResult();
}
if (authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
{
token = authorization.Substring("Bearer ".Length).Trim();
}
// If no token found, no further work possible
if (string.IsNullOrEmpty(token))
{
return AuthenticateResult.NoResult();
}
}
if (_configuration == null && Options.ConfigurationManager != null)
{
_configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.RequestAborted);
}
var validationParameters = Options.TokenValidationParameters.Clone();
if (_configuration != null)
{
var issuers = new[] { _configuration.Issuer };
validationParameters.ValidIssuers = validationParameters.ValidIssuers?.Concat(issuers) ?? issuers;
validationParameters.IssuerSigningKeys = validationParameters.IssuerSigningKeys?.Concat(_configuration.SigningKeys)
?? _configuration.SigningKeys;
}
List<Exception>? validationFailures = null;
SecurityToken? validatedToken = null;
foreach (var validator in Options.SecurityTokenValidators)
{
if (validator.CanReadToken(token))
{
ClaimsPrincipal principal;
try
{
principal = validator.ValidateToken(token, validationParameters, out validatedToken);
}
catch (Exception ex)
{
Logger.TokenValidationFailed(ex);
// Refresh the configuration for exceptions that may be caused by key rollovers. The user can also request a refresh in the event.
if (Options.RefreshOnIssuerKeyNotFound && Options.ConfigurationManager != null
&& ex is SecurityTokenSignatureKeyNotFoundException)
{
Options.ConfigurationManager.RequestRefresh();
}
if (validationFailures == null)
{
validationFailures = new List<Exception>(1);
}
validationFailures.Add(ex);
continue;
}
Logger.TokenValidationSucceeded();
var tokenValidatedContext = new TokenValidatedContext(Context, Scheme, Options)
{
Principal = principal,
SecurityToken = validatedToken
};
tokenValidatedContext.Properties.ExpiresUtc = GetSafeDateTime(validatedToken.ValidTo);
tokenValidatedContext.Properties.IssuedUtc = GetSafeDateTime(validatedToken.ValidFrom);
await Events.TokenValidated(tokenValidatedContext);
if (tokenValidatedContext.Result != null)
{
return tokenValidatedContext.Result;
}
if (Options.SaveToken)
{
tokenValidatedContext.Properties.StoreTokens(new[]
{
new AuthenticationToken { Name = "access_token", Value = token }
});
}
tokenValidatedContext.Success();
return tokenValidatedContext.Result!;
}
}
if (validationFailures != null)
{
var authenticationFailedContext = new AuthenticationFailedContext(Context, Scheme, Options)
{
Exception = (validationFailures.Count == 1) ? validationFailures[0] : new AggregateException(validationFailures)
};
await Events.AuthenticationFailed(authenticationFailedContext);
if (authenticationFailedContext.Result != null)
{
return authenticationFailedContext.Result;
}
return AuthenticateResult.Fail(authenticationFailedContext.Exception);
}
return AuthenticateResult.Fail("No SecurityTokenValidator available for token.");
}
catch (Exception ex)
{
Logger.ErrorProcessingMessage(ex);
var authenticationFailedContext = new AuthenticationFailedContext(Context, Scheme, Options)
{
Exception = ex
};
await Events.AuthenticationFailed(authenticationFailedContext);
if (authenticationFailedContext.Result != null)
{
return authenticationFailedContext.Result;
}
throw;
}
}
private static DateTime? GetSafeDateTime(DateTime dateTime)
{
// Assigning DateTime.MinValue or default(DateTime) to a DateTimeOffset when in a UTC+X timezone will throw
// Since we don't really care about DateTime.MinValue in this case let's just set the field to null
if (dateTime == DateTime.MinValue)
{
return null;
}
return dateTime;
}
/// <inheritdoc />
protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
{
var authResult = await HandleAuthenticateOnceSafeAsync();
var eventContext = new JwtBearerChallengeContext(Context, Scheme, Options, properties)
{
AuthenticateFailure = authResult?.Failure
};
// Avoid returning error=invalid_token if the error is not caused by an authentication failure (e.g missing token).
if (Options.IncludeErrorDetails && eventContext.AuthenticateFailure != null)
{
eventContext.Error = "invalid_token";
eventContext.ErrorDescription = CreateErrorDescription(eventContext.AuthenticateFailure);
}
await Events.Challenge(eventContext);
if (eventContext.Handled)
{
return;
}
Response.StatusCode = 401;
if (string.IsNullOrEmpty(eventContext.Error) &&
string.IsNullOrEmpty(eventContext.ErrorDescription) &&
string.IsNullOrEmpty(eventContext.ErrorUri))
{
Response.Headers.Append(HeaderNames.WWWAuthenticate, Options.Challenge);
}
else
{
// https://tools.ietf.org/html/rfc6750#section-3.1
// WWW-Authenticate: Bearer realm="example", error="invalid_token", error_description="The access token expired"
var builder = new StringBuilder(Options.Challenge);
if (Options.Challenge.IndexOf(' ') > 0)
{
// Only add a comma after the first param, if any
builder.Append(',');
}
if (!string.IsNullOrEmpty(eventContext.Error))
{
builder.Append(" error=\"");
builder.Append(eventContext.Error);
builder.Append('\"');
}
if (!string.IsNullOrEmpty(eventContext.ErrorDescription))
{
if (!string.IsNullOrEmpty(eventContext.Error))
{
builder.Append(',');
}
builder.Append(" error_description=\"");
builder.Append(eventContext.ErrorDescription);
builder.Append('\"');
}
if (!string.IsNullOrEmpty(eventContext.ErrorUri))
{
if (!string.IsNullOrEmpty(eventContext.Error) ||
!string.IsNullOrEmpty(eventContext.ErrorDescription))
{
builder.Append(',');
}
builder.Append(" error_uri=\"");
builder.Append(eventContext.ErrorUri);
builder.Append('\"');
}
Response.Headers.Append(HeaderNames.WWWAuthenticate, builder.ToString());
}
}
/// <inheritdoc />
protected override Task HandleForbiddenAsync(AuthenticationProperties properties)
{
var forbiddenContext = new ForbiddenContext(Context, Scheme, Options);
Response.StatusCode = 403;
return Events.Forbidden(forbiddenContext);
}
private static string CreateErrorDescription(Exception authFailure)
{
IReadOnlyCollection<Exception> exceptions;
if (authFailure is AggregateException agEx)
{
exceptions = agEx.InnerExceptions;
}
else
{
exceptions = new[] { authFailure };
}
var messages = new List<string>(exceptions.Count);
foreach (var ex in exceptions)
{
// Order sensitive, some of these exceptions derive from others
// and we want to display the most specific message possible.
switch (ex)
{
case SecurityTokenInvalidAudienceException stia:
messages.Add($"The audience '{stia.InvalidAudience ?? "(null)"}' is invalid");
break;
case SecurityTokenInvalidIssuerException stii:
messages.Add($"The issuer '{stii.InvalidIssuer ?? "(null)"}' is invalid");
break;
case SecurityTokenNoExpirationException _:
messages.Add("The token has no expiration");
break;
case SecurityTokenInvalidLifetimeException stil:
messages.Add("The token lifetime is invalid; NotBefore: "
+ $"'{stil.NotBefore?.ToString(CultureInfo.InvariantCulture) ?? "(null)"}'"
+ $", Expires: '{stil.Expires?.ToString(CultureInfo.InvariantCulture) ?? "(null)"}'");
break;
case SecurityTokenNotYetValidException stnyv:
messages.Add($"The token is not valid before '{stnyv.NotBefore.ToString(CultureInfo.InvariantCulture)}'");
break;
case SecurityTokenExpiredException ste:
messages.Add($"The token expired at '{ste.Expires.ToString(CultureInfo.InvariantCulture)}'");
break;
case SecurityTokenSignatureKeyNotFoundException _:
messages.Add("The signature key was not found");
break;
case SecurityTokenInvalidSignatureException _:
messages.Add("The signature is invalid");
break;
}
}
return string.Join("; ", messages);
}
}
}
| |
/*
* 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.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.CoreModules.Avatar.AvatarFactory
{
public class AvatarFactoryModule : IAvatarFactory, IRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Scene m_scene = null;
private static readonly AvatarAppearance def = new AvatarAppearance();
public bool TryGetAvatarAppearance(UUID avatarId, out AvatarAppearance appearance)
{
AvatarData avatar = m_scene.AvatarService.GetAvatar(avatarId);
//if ((profile != null) && (profile.RootFolder != null))
if (avatar != null)
{
appearance = avatar.ToAvatarAppearance(avatarId);
return true;
}
m_log.ErrorFormat("[APPEARANCE]: Appearance not found for {0}, creating default", avatarId);
appearance = CreateDefault(avatarId);
return false;
}
private AvatarAppearance CreateDefault(UUID avatarId)
{
AvatarAppearance appearance = null;
AvatarWearable[] wearables;
byte[] visualParams;
GetDefaultAvatarAppearance(out wearables, out visualParams);
appearance = new AvatarAppearance(avatarId, wearables, visualParams);
return appearance;
}
public void Initialise(Scene scene, IConfigSource source)
{
scene.RegisterModuleInterface<IAvatarFactory>(this);
scene.EventManager.OnNewClient += NewClient;
if (m_scene == null)
{
m_scene = scene;
}
}
public void PostInitialise()
{
}
public void Close()
{
}
public string Name
{
get { return "Default Avatar Factory"; }
}
public bool IsSharedModule
{
get { return false; }
}
public void NewClient(IClientAPI client)
{
client.OnAvatarNowWearing += AvatarIsWearing;
}
public void RemoveClient(IClientAPI client)
{
// client.OnAvatarNowWearing -= AvatarIsWearing;
}
public void SetAppearanceAssets(UUID userID, ref AvatarAppearance appearance)
{
IInventoryService invService = m_scene.InventoryService;
if (invService.GetRootFolder(userID) != null)
{
for (int i = 0; i < 13; i++)
{
if (appearance.Wearables[i].ItemID == UUID.Zero)
{
appearance.Wearables[i].AssetID = UUID.Zero;
}
else
{
InventoryItemBase baseItem = new InventoryItemBase(appearance.Wearables[i].ItemID, userID);
baseItem = invService.GetItem(baseItem);
if (baseItem != null)
{
appearance.Wearables[i].AssetID = baseItem.AssetID;
}
else
{
m_log.ErrorFormat(
"[APPEARANCE]: Can't find inventory item {0} for {1}, setting to default",
appearance.Wearables[i].ItemID, (WearableType)i);
appearance.Wearables[i].AssetID = def.Wearables[i].AssetID;
}
}
}
}
else
{
m_log.WarnFormat("[APPEARANCE]: user {0} has no inventory, appearance isn't going to work", userID);
}
}
/// <summary>
/// Update what the avatar is wearing using an item from their inventory.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void AvatarIsWearing(Object sender, AvatarWearingArgs e)
{
m_log.DebugFormat("[APPEARANCE]: AvatarIsWearing");
IClientAPI clientView = (IClientAPI)sender;
ScenePresence sp = m_scene.GetScenePresence(clientView.AgentId);
if (sp == null)
{
m_log.Error("[APPEARANCE]: Avatar is child agent, ignoring AvatarIsWearing event");
return;
}
AvatarAppearance avatAppearance = sp.Appearance;
//if (!TryGetAvatarAppearance(clientView.AgentId, out avatAppearance))
//{
// m_log.Warn("[APPEARANCE]: We didn't seem to find the appearance, falling back to ScenePresence");
// avatAppearance = sp.Appearance;
//}
//m_log.DebugFormat("[APPEARANCE]: Received wearables for {0}", clientView.Name);
foreach (AvatarWearingArgs.Wearable wear in e.NowWearing)
{
if (wear.Type < 13)
{
avatAppearance.Wearables[wear.Type].ItemID = wear.ItemID;
}
}
SetAppearanceAssets(sp.UUID, ref avatAppearance);
AvatarData adata = new AvatarData(avatAppearance);
m_scene.AvatarService.SetAvatar(clientView.AgentId, adata);
sp.Appearance = avatAppearance;
}
public static void GetDefaultAvatarAppearance(out AvatarWearable[] wearables, out byte[] visualParams)
{
visualParams = GetDefaultVisualParams();
wearables = AvatarWearable.DefaultWearables;
}
public void UpdateDatabase(UUID user, AvatarAppearance appearance)
{
m_log.DebugFormat("[APPEARANCE]: UpdateDatabase");
AvatarData adata = new AvatarData(appearance);
m_scene.AvatarService.SetAvatar(user, adata);
}
private static byte[] GetDefaultVisualParams()
{
byte[] visualParams;
visualParams = new byte[218];
for (int i = 0; i < 218; i++)
{
visualParams[i] = 100;
}
return visualParams;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Communications.Clients;
using OpenSim.Region.Communications.OGS1;
using OpenSim.Region.Communications.Local;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.Communications.Hypergrid
{
/// <summary>
/// For the time being, this class is just an identity wrapper around OGS1UserServices,
/// so it always fails for foreign users.
/// Later it needs to talk with the foreign users' user servers.
/// </summary>
public class HGUserServices : OGS1UserServices
{
//private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
//private OGS1UserServices m_remoteUserServices;
private LocalUserServices m_localUserServices;
// Constructor called when running in grid mode
public HGUserServices(CommunicationsManager commsManager)
: base(commsManager)
{
}
// Constructor called when running in standalone
public HGUserServices(CommunicationsManager commsManager, LocalUserServices local)
: base(commsManager)
{
m_localUserServices = local;
}
public override void SetInventoryService(IInventoryService invService)
{
base.SetInventoryService(invService);
if (m_localUserServices != null)
m_localUserServices.SetInventoryService(invService);
}
public override UUID AddUser(
string firstName, string lastName, string password, string email, uint regX, uint regY, UUID uuid)
{
// Only valid to create users locally
if (m_localUserServices != null)
return m_localUserServices.AddUser(firstName, lastName, password, email, regX, regY, uuid);
return UUID.Zero;
}
public override bool AddUserAgent(UserAgentData agentdata)
{
if (m_localUserServices != null)
return m_localUserServices.AddUserAgent(agentdata);
return base.AddUserAgent(agentdata);
}
public override UserAgentData GetAgentByUUID(UUID userId)
{
string url = string.Empty;
if ((m_localUserServices != null) && !IsForeignUser(userId, out url))
return m_localUserServices.GetAgentByUUID(userId);
return base.GetAgentByUUID(userId);
}
public override void LogOffUser(UUID userid, UUID regionid, ulong regionhandle, Vector3 position, Vector3 lookat)
{
string url = string.Empty;
if ((m_localUserServices != null) && !IsForeignUser(userid, out url))
m_localUserServices.LogOffUser(userid, regionid, regionhandle, position, lookat);
else
base.LogOffUser(userid, regionid, regionhandle, position, lookat);
}
public override UserProfileData GetUserProfile(string firstName, string lastName)
{
if (m_localUserServices != null)
return m_localUserServices.GetUserProfile(firstName, lastName);
return base.GetUserProfile(firstName, lastName);
}
public override List<AvatarPickerAvatar> GenerateAgentPickerRequestResponse(UUID queryID, string query)
{
if (m_localUserServices != null)
return m_localUserServices.GenerateAgentPickerRequestResponse(queryID, query);
return base.GenerateAgentPickerRequestResponse(queryID, query);
}
/// <summary>
/// Get a user profile from the user server
/// </summary>
/// <param name="avatarID"></param>
/// <returns>null if the request fails</returns>
public override UserProfileData GetUserProfile(UUID avatarID)
{
//string url = string.Empty;
// Unfortunately we can't query for foreigners here,
// because we'll end up in an infinite loop...
//if ((m_localUserServices != null) && (!IsForeignUser(avatarID, out url)))
if (m_localUserServices != null)
return m_localUserServices.GetUserProfile(avatarID);
return base.GetUserProfile(avatarID);
}
public override void ClearUserAgent(UUID avatarID)
{
if (m_localUserServices != null)
m_localUserServices.ClearUserAgent(avatarID);
else
base.ClearUserAgent(avatarID);
}
/// <summary>
/// Retrieve the user information for the given master uuid.
/// </summary>
/// <param name="uuid"></param>
/// <returns></returns>
public override UserProfileData SetupMasterUser(string firstName, string lastName)
{
if (m_localUserServices != null)
return m_localUserServices.SetupMasterUser(firstName, lastName);
return base.SetupMasterUser(firstName, lastName);
}
/// <summary>
/// Retrieve the user information for the given master uuid.
/// </summary>
/// <param name="uuid"></param>
/// <returns></returns>
public override UserProfileData SetupMasterUser(string firstName, string lastName, string password)
{
if (m_localUserServices != null)
return m_localUserServices.SetupMasterUser(firstName, lastName, password);
return base.SetupMasterUser(firstName, lastName, password);
}
/// <summary>
/// Retrieve the user information for the given master uuid.
/// </summary>
/// <param name="uuid"></param>
/// <returns></returns>
public override UserProfileData SetupMasterUser(UUID uuid)
{
if (m_localUserServices != null)
return m_localUserServices.SetupMasterUser(uuid);
return base.SetupMasterUser(uuid);
}
public override bool ResetUserPassword(string firstName, string lastName, string newPassword)
{
if (m_localUserServices != null)
return m_localUserServices.ResetUserPassword(firstName, lastName, newPassword);
else
return base.ResetUserPassword(firstName, lastName, newPassword);
}
public override bool UpdateUserProfile(UserProfileData userProfile)
{
string url = string.Empty;
if ((m_localUserServices != null) && (!IsForeignUser(userProfile.ID, out url)))
return m_localUserServices.UpdateUserProfile(userProfile);
return base.UpdateUserProfile(userProfile);
}
#region IUserServices Friend Methods
// NOTE: We're still not dealing with foreign user friends
/// <summary>
/// Adds a new friend to the database for XUser
/// </summary>
/// <param name="friendlistowner">The agent that who's friends list is being added to</param>
/// <param name="friend">The agent that being added to the friends list of the friends list owner</param>
/// <param name="perms">A uint bit vector for set perms that the friend being added has; 0 = none, 1=This friend can see when they sign on, 2 = map, 4 edit objects </param>
public override void AddNewUserFriend(UUID friendlistowner, UUID friend, uint perms)
{
if (m_localUserServices != null)
m_localUserServices.AddNewUserFriend(friendlistowner, friend, perms);
else
base.AddNewUserFriend(friendlistowner, friend, perms);
}
/// <summary>
/// Delete friend on friendlistowner's friendlist.
/// </summary>
/// <param name="friendlistowner">The agent that who's friends list is being updated</param>
/// <param name="friend">The Ex-friend agent</param>
public override void RemoveUserFriend(UUID friendlistowner, UUID friend)
{
if (m_localUserServices != null)
m_localUserServices.RemoveUserFriend(friendlistowner, friend);
else
base.RemoveUserFriend(friend, friend);
}
/// <summary>
/// Update permissions for friend on friendlistowner's friendlist.
/// </summary>
/// <param name="friendlistowner">The agent that who's friends list is being updated</param>
/// <param name="friend">The agent that is getting or loosing permissions</param>
/// <param name="perms">A uint bit vector for set perms that the friend being added has; 0 = none, 1=This friend can see when they sign on, 2 = map, 4 edit objects </param>
public override void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms)
{
if (m_localUserServices != null)
m_localUserServices.UpdateUserFriendPerms(friendlistowner, friend, perms);
else
base.UpdateUserFriendPerms(friendlistowner, friend, perms);
}
/// <summary>
/// Returns a list of FriendsListItems that describe the friends and permissions in the friend relationship for UUID friendslistowner
/// </summary>
/// <param name="friendlistowner">The agent that we're retreiving the friends Data.</param>
public override List<FriendListItem> GetUserFriendList(UUID friendlistowner)
{
if (m_localUserServices != null)
return m_localUserServices.GetUserFriendList(friendlistowner);
return base.GetUserFriendList(friendlistowner);
}
#endregion
/// Appearance
public override AvatarAppearance GetUserAppearance(UUID user)
{
string url = string.Empty;
if ((m_localUserServices != null) && (!IsForeignUser(user, out url)))
return m_localUserServices.GetUserAppearance(user);
else
return base.GetUserAppearance(user);
}
public override void UpdateUserAppearance(UUID user, AvatarAppearance appearance)
{
string url = string.Empty;
if ((m_localUserServices != null) && (!IsForeignUser(user, out url)))
m_localUserServices.UpdateUserAppearance(user, appearance);
else
base.UpdateUserAppearance(user, appearance);
}
#region IMessagingService
public override Dictionary<UUID, FriendRegionInfo> GetFriendRegionInfos(List<UUID> uuids)
{
if (m_localUserServices != null)
return m_localUserServices.GetFriendRegionInfos(uuids);
return base.GetFriendRegionInfos(uuids);
}
#endregion
public override bool VerifySession(UUID userID, UUID sessionID)
{
string url = string.Empty;
if ((m_localUserServices != null) && (!IsForeignUser(userID, out url)))
return m_localUserServices.VerifySession(userID, sessionID);
else
return base.VerifySession(userID, sessionID);
}
protected override string GetUserServerURL(UUID userID)
{
string serverURL = string.Empty;
if (IsForeignUser(userID, out serverURL))
return serverURL;
return m_commsManager.NetworkServersInfo.UserURL;
}
public bool IsForeignUser(UUID userID, out string userServerURL)
{
userServerURL = m_commsManager.NetworkServersInfo.UserURL;
CachedUserInfo uinfo = m_commsManager.UserProfileCacheService.GetUserDetails(userID);
if (uinfo != null)
{
if (!HGNetworkServersInfo.Singleton.IsLocalUser(uinfo.UserProfile))
{
userServerURL = ((ForeignUserProfileData)(uinfo.UserProfile)).UserServerURI;
return true;
}
}
return 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;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Reactive.Disposables;
namespace Avalonia.Collections
{
/// <summary>
/// Defines extension methods for working with <see cref="AvaloniaList{T}"/>s.
/// </summary>
public static class AvaloniaListExtensions
{
/// <summary>
/// Invokes an action for each item in a collection and subsequently each item added or
/// removed from the collection.
/// </summary>
/// <typeparam name="T">The type of the collection items.</typeparam>
/// <param name="collection">The collection.</param>
/// <param name="added">
/// An action called initially for each item in the collection and subsequently for each
/// item added to the collection. The parameters passed are the index in the collection and
/// the item.
/// </param>
/// <param name="removed">
/// An action called for each item removed from the collection. The parameters passed are
/// the index in the collection and the item.
/// </param>
/// <param name="reset">
/// An action called when the collection is reset.
/// </param>
/// <param name="weakSubscription">
/// Indicates if a weak subscription should be used to track changes to the collection.
/// </param>
/// <returns>A disposable used to terminate the subscription.</returns>
public static IDisposable ForEachItem<T>(
this IAvaloniaReadOnlyList<T> collection,
Action<T> added,
Action<T> removed,
Action reset,
bool weakSubscription = false)
{
return collection.ForEachItem((_, i) => added(i), (_, i) => removed(i), reset, weakSubscription);
}
/// <summary>
/// Invokes an action for each item in a collection and subsequently each item added or
/// removed from the collection.
/// </summary>
/// <typeparam name="T">The type of the collection items.</typeparam>
/// <param name="collection">The collection.</param>
/// <param name="added">
/// An action called initially for each item in the collection and subsequently for each
/// item added to the collection. The parameters passed are the index in the collection and
/// the item.
/// </param>
/// <param name="removed">
/// An action called for each item removed from the collection. The parameters passed are
/// the index in the collection and the item.
/// </param>
/// <param name="reset">
/// An action called when the collection is reset. This will be followed by calls to
/// <paramref name="added"/> for each item present in the collection after the reset.
/// </param>
/// <param name="weakSubscription">
/// Indicates if a weak subscription should be used to track changes to the collection.
/// </param>
/// <returns>A disposable used to terminate the subscription.</returns>
public static IDisposable ForEachItem<T>(
this IAvaloniaReadOnlyList<T> collection,
Action<int, T> added,
Action<int, T> removed,
Action reset,
bool weakSubscription = false)
{
void Add(int index, IList items)
{
foreach (T item in items)
{
added(index++, item);
}
}
void Remove(int index, IList items)
{
for (var i = items.Count - 1; i >= 0; --i)
{
removed(index + i, (T)items[i]);
}
}
NotifyCollectionChangedEventHandler handler = (_, e) =>
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
Add(e.NewStartingIndex, e.NewItems);
break;
case NotifyCollectionChangedAction.Move:
case NotifyCollectionChangedAction.Replace:
Remove(e.OldStartingIndex, e.OldItems);
Add(e.NewStartingIndex, e.NewItems);
break;
case NotifyCollectionChangedAction.Remove:
Remove(e.OldStartingIndex, e.OldItems);
break;
case NotifyCollectionChangedAction.Reset:
if (reset == null)
{
throw new InvalidOperationException(
"Reset called on collection without reset handler.");
}
reset();
Add(0, (IList)collection);
break;
}
};
Add(0, (IList)collection);
if (weakSubscription)
{
return collection.WeakSubscribe(handler);
}
else
{
collection.CollectionChanged += handler;
return Disposable.Create(() => collection.CollectionChanged -= handler);
}
}
public static IAvaloniaReadOnlyList<TDerived> CreateDerivedList<TSource, TDerived>(
this IAvaloniaReadOnlyList<TSource> collection,
Func<TSource, TDerived> select)
{
var result = new AvaloniaList<TDerived>();
collection.ForEachItem(
(i, item) => result.Insert(i, select(item)),
(i, item) => result.RemoveAt(i),
() => result.Clear());
return result;
}
/// <summary>
/// Listens for property changed events from all items in a collection.
/// </summary>
/// <typeparam name="T">The type of the collection items.</typeparam>
/// <param name="collection">The collection.</param>
/// <param name="callback">A callback to call for each property changed event.</param>
/// <returns>A disposable used to terminate the subscription.</returns>
public static IDisposable TrackItemPropertyChanged<T>(
this IAvaloniaReadOnlyList<T> collection,
Action<Tuple<object, PropertyChangedEventArgs>> callback)
{
List<INotifyPropertyChanged> tracked = new List<INotifyPropertyChanged>();
PropertyChangedEventHandler handler = (s, e) =>
{
callback(Tuple.Create(s, e));
};
collection.ForEachItem(
x =>
{
var inpc = x as INotifyPropertyChanged;
if (inpc != null)
{
inpc.PropertyChanged += handler;
tracked.Add(inpc);
}
},
x =>
{
var inpc = x as INotifyPropertyChanged;
if (inpc != null)
{
inpc.PropertyChanged -= handler;
tracked.Remove(inpc);
}
},
null);
return Disposable.Create(() =>
{
foreach (var i in tracked)
{
i.PropertyChanged -= handler;
}
});
}
}
}
| |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using IdentityModel;
using IdentityModel.Client;
using IdentityServer.IntegrationTests.Clients.Setup;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Xunit;
namespace IdentityServer.IntegrationTests.Clients
{
public class CustomTokenResponseClients
{
private const string TokenEndpoint = "https://server/connect/token";
private readonly HttpClient _client;
public CustomTokenResponseClients()
{
var builder = new WebHostBuilder()
.UseStartup<StartupWithCustomTokenResponses>();
var server = new TestServer(builder);
_client = server.CreateClient();
}
[Fact]
public async Task Resource_owner_success_should_return_custom_response()
{
var response = await _client.RequestPasswordTokenAsync(new PasswordTokenRequest
{
Address = TokenEndpoint,
ClientId = "roclient",
ClientSecret = "secret",
UserName = "bob",
Password = "bob",
Scope = "api1"
});
// raw fields
var fields = GetFields(response);
fields.Should().Contain("string_value", "some_string");
((Int64)fields["int_value"]).Should().Be(42);
object temp;
fields.TryGetValue("identity_token", out temp).Should().BeFalse();
fields.TryGetValue("refresh_token", out temp).Should().BeFalse();
fields.TryGetValue("error", out temp).Should().BeFalse();
fields.TryGetValue("error_description", out temp).Should().BeFalse();
fields.TryGetValue("token_type", out temp).Should().BeTrue();
fields.TryGetValue("expires_in", out temp).Should().BeTrue();
var responseObject = fields["dto"] as JObject;
responseObject.Should().NotBeNull();
var responseDto = GetDto(responseObject);
var dto = CustomResponseDto.Create;
responseDto.string_value.Should().Be(dto.string_value);
responseDto.int_value.Should().Be(dto.int_value);
responseDto.nested.string_value.Should().Be(dto.nested.string_value);
responseDto.nested.int_value.Should().Be(dto.nested.int_value);
// token client response
response.IsError.Should().Be(false);
response.ExpiresIn.Should().Be(3600);
response.TokenType.Should().Be("Bearer");
response.IdentityToken.Should().BeNull();
response.RefreshToken.Should().BeNull();
// token content
var payload = GetPayload(response);
payload.Count().Should().Be(10);
payload.Should().Contain("iss", "https://idsvr4");
payload.Should().Contain("client_id", "roclient");
payload.Should().Contain("sub", "bob");
payload.Should().Contain("idp", "local");
payload["aud"].Should().Be("api");
var scopes = payload["scope"] as JArray;
scopes.First().ToString().Should().Be("api1");
var amr = payload["amr"] as JArray;
amr.Count().Should().Be(1);
amr.First().ToString().Should().Be("password");
}
[Fact]
public async Task Resource_owner_failure_should_return_custom_error_response()
{
var response = await _client.RequestPasswordTokenAsync(new PasswordTokenRequest
{
Address = TokenEndpoint,
ClientId = "roclient",
ClientSecret = "secret",
UserName = "bob",
Password = "invalid",
Scope = "api1"
});
// raw fields
var fields = GetFields(response);
fields.Should().Contain("string_value", "some_string");
((Int64)fields["int_value"]).Should().Be(42);
object temp;
fields.TryGetValue("identity_token", out temp).Should().BeFalse();
fields.TryGetValue("refresh_token", out temp).Should().BeFalse();
fields.TryGetValue("error", out temp).Should().BeTrue();
fields.TryGetValue("error_description", out temp).Should().BeTrue();
fields.TryGetValue("token_type", out temp).Should().BeFalse();
fields.TryGetValue("expires_in", out temp).Should().BeFalse();
var responseObject = fields["dto"] as JObject;
responseObject.Should().NotBeNull();
var responseDto = GetDto(responseObject);
var dto = CustomResponseDto.Create;
responseDto.string_value.Should().Be(dto.string_value);
responseDto.int_value.Should().Be(dto.int_value);
responseDto.nested.string_value.Should().Be(dto.nested.string_value);
responseDto.nested.int_value.Should().Be(dto.nested.int_value);
// token client response
response.IsError.Should().Be(true);
response.Error.Should().Be("invalid_grant");
response.ErrorDescription.Should().Be("invalid_credential");
response.ExpiresIn.Should().Be(0);
response.TokenType.Should().BeNull();
response.IdentityToken.Should().BeNull();
response.RefreshToken.Should().BeNull();
}
[Fact]
public async Task Extension_grant_success_should_return_custom_response()
{
var response = await _client.RequestTokenAsync(new TokenRequest
{
Address = TokenEndpoint,
GrantType = "custom",
ClientId = "client.custom",
ClientSecret = "secret",
Parameters =
{
{ "scope", "api1" },
{ "outcome", "succeed"}
}
});
// raw fields
var fields = GetFields(response);
fields.Should().Contain("string_value", "some_string");
((Int64)fields["int_value"]).Should().Be(42);
object temp;
fields.TryGetValue("identity_token", out temp).Should().BeFalse();
fields.TryGetValue("refresh_token", out temp).Should().BeFalse();
fields.TryGetValue("error", out temp).Should().BeFalse();
fields.TryGetValue("error_description", out temp).Should().BeFalse();
fields.TryGetValue("token_type", out temp).Should().BeTrue();
fields.TryGetValue("expires_in", out temp).Should().BeTrue();
var responseObject = fields["dto"] as JObject;
responseObject.Should().NotBeNull();
var responseDto = GetDto(responseObject);
var dto = CustomResponseDto.Create;
responseDto.string_value.Should().Be(dto.string_value);
responseDto.int_value.Should().Be(dto.int_value);
responseDto.nested.string_value.Should().Be(dto.nested.string_value);
responseDto.nested.int_value.Should().Be(dto.nested.int_value);
// token client response
response.IsError.Should().Be(false);
response.ExpiresIn.Should().Be(3600);
response.TokenType.Should().Be("Bearer");
response.IdentityToken.Should().BeNull();
response.RefreshToken.Should().BeNull();
// token content
var payload = GetPayload(response);
payload.Count().Should().Be(10);
payload.Should().Contain("iss", "https://idsvr4");
payload.Should().Contain("client_id", "client.custom");
payload.Should().Contain("sub", "bob");
payload.Should().Contain("idp", "local");
payload["aud"].Should().Be("api");
var scopes = payload["scope"] as JArray;
scopes.First().ToString().Should().Be("api1");
var amr = payload["amr"] as JArray;
amr.Count().Should().Be(1);
amr.First().ToString().Should().Be("custom");
}
[Fact]
public async Task Extension_grant_failure_should_return_custom_error_response()
{
var response = await _client.RequestTokenAsync(new TokenRequest
{
Address = TokenEndpoint,
GrantType = "custom",
ClientId = "client.custom",
ClientSecret = "secret",
Parameters =
{
{ "scope", "api1" },
{ "outcome", "fail"}
}
});
// raw fields
var fields = GetFields(response);
fields.Should().Contain("string_value", "some_string");
((Int64)fields["int_value"]).Should().Be(42);
object temp;
fields.TryGetValue("identity_token", out temp).Should().BeFalse();
fields.TryGetValue("refresh_token", out temp).Should().BeFalse();
fields.TryGetValue("error", out temp).Should().BeTrue();
fields.TryGetValue("error_description", out temp).Should().BeTrue();
fields.TryGetValue("token_type", out temp).Should().BeFalse();
fields.TryGetValue("expires_in", out temp).Should().BeFalse();
var responseObject = fields["dto"] as JObject;
responseObject.Should().NotBeNull();
var responseDto = GetDto(responseObject);
var dto = CustomResponseDto.Create;
responseDto.string_value.Should().Be(dto.string_value);
responseDto.int_value.Should().Be(dto.int_value);
responseDto.nested.string_value.Should().Be(dto.nested.string_value);
responseDto.nested.int_value.Should().Be(dto.nested.int_value);
// token client response
response.IsError.Should().Be(true);
response.Error.Should().Be("invalid_grant");
response.ErrorDescription.Should().Be("invalid_credential");
response.ExpiresIn.Should().Be(0);
response.TokenType.Should().BeNull();
response.IdentityToken.Should().BeNull();
response.RefreshToken.Should().BeNull();
}
private CustomResponseDto GetDto(JObject responseObject)
{
return responseObject.ToObject<CustomResponseDto>();
}
private Dictionary<string, object> GetFields(TokenResponse response)
{
return response.Json.ToObject<Dictionary<string, object>>();
}
private Dictionary<string, object> GetPayload(TokenResponse response)
{
var token = response.AccessToken.Split('.').Skip(1).Take(1).First();
var dictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(
Encoding.UTF8.GetString(Base64Url.Decode(token)));
return dictionary;
}
}
}
| |
using System;
using System.Data;
using System.Data.OleDb;
using System.Collections;
using System.Configuration;
using PCSComUtils.DataAccess;
using PCSComUtils.PCSExc;
using PCSComUtils.Common;
namespace PCSComSale.Order.DS
{
public class SO_ReturnedGoodsMasterDS
{
public SO_ReturnedGoodsMasterDS()
{
}
private const string THIS = "PCSComSale.Order.DS.SO_ReturnedGoodsMasterDS";
//**************************************************************************
/// <Description>
/// This method uses to add data to SO_ReturnedGoodsMaster
/// </Description>
/// <Inputs>
/// SO_ReturnedGoodsMasterVO
/// </Inputs>
/// <Outputs>
/// newly inserted primarkey value
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, February 22, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Add(object pobjObjectVO)
{
const string METHOD_NAME = THIS + ".Add()";
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS =null;
try
{
SO_ReturnedGoodsMasterVO objObject = (SO_ReturnedGoodsMasterVO) pobjObjectVO;
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand("", oconPCS);
strSql= "INSERT INTO SO_ReturnedGoodsMaster("
+ SO_ReturnedGoodsMasterTable.RETURNEDGOODSNUMBER_FLD + ","
+ SO_ReturnedGoodsMasterTable.RECEIVERID_FLD + ","
+ SO_ReturnedGoodsMasterTable.CCNID_FLD + ","
+ SO_ReturnedGoodsMasterTable.TRANSDATE_FLD + ","
+ SO_ReturnedGoodsMasterTable.DESCRIPTION_FLD + ","
+ SO_ReturnedGoodsMasterTable.POSTDATE_FLD + ","
+ SO_ReturnedGoodsMasterTable.SALEORDERMASTERID_FLD + ","
+ SO_ReturnedGoodsMasterTable.PARTYID_FLD + ","
+ SO_ReturnedGoodsMasterTable.PARTYCONTACTID_FLD + ","
+ SO_ReturnedGoodsMasterTable.MASTERLOCATIONID_FLD + ","
+ SO_ReturnedGoodsMasterTable.PARTYLOCATIONID_FLD + ")"
+ "VALUES(?,?,?,?,?,?,?,?,?,?,?)";
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.RETURNEDGOODSNUMBER_FLD, OleDbType.WChar));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.RETURNEDGOODSNUMBER_FLD].Value = objObject.ReturnedGoodsNumber;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.RECEIVERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.RECEIVERID_FLD].Value = objObject.ReceiverID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.CCNID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.CCNID_FLD].Value = objObject.CCNID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.TRANSDATE_FLD, OleDbType.Date));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.TRANSDATE_FLD].Value = objObject.TransDate;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.DESCRIPTION_FLD, OleDbType.WChar));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.DESCRIPTION_FLD].Value = objObject.Description;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.POSTDATE_FLD, OleDbType.Date));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.POSTDATE_FLD].Value = objObject.PostDate;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.SALEORDERMASTERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.SALEORDERMASTERID_FLD].Value = objObject.SaleOrderMasterID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.PARTYID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.PARTYID_FLD].Value = objObject.PartyID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.PARTYCONTACTID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.PARTYCONTACTID_FLD].Value = objObject.PartyContactID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.MASTERLOCATIONID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.MASTERLOCATIONID_FLD].Value = objObject.MasterLocationID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.PARTYLOCATIONID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.PARTYLOCATIONID_FLD].Value = objObject.PartyLocationID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to add data to SO_ReturnedGoodsMaster
/// </Description>
/// <Inputs>
/// SO_ReturnedGoodsMasterVO
/// </Inputs>
/// <Outputs>
/// newly inserted primarkey value
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, February 22, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public int AddReturnedGoodsAndReturnID(object pobjObjectVO)
{
const string METHOD_NAME = THIS + ".AddReturnedGoodsAndReturnID()";
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS =null;
try
{
SO_ReturnedGoodsMasterVO objObject = (SO_ReturnedGoodsMasterVO) pobjObjectVO;
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand("", oconPCS);
strSql= "INSERT INTO SO_ReturnedGoodsMaster("
+ SO_ReturnedGoodsMasterTable.RETURNEDGOODSNUMBER_FLD + ","
+ SO_ReturnedGoodsMasterTable.RECEIVERID_FLD + ","
+ SO_ReturnedGoodsMasterTable.CCNID_FLD + ","
+ SO_ReturnedGoodsMasterTable.TRANSDATE_FLD + ","
+ SO_ReturnedGoodsMasterTable.DESCRIPTION_FLD + ","
+ SO_ReturnedGoodsMasterTable.POSTDATE_FLD + ","
+ SO_ReturnedGoodsMasterTable.SALEORDERMASTERID_FLD + ","
+ SO_ReturnedGoodsMasterTable.PARTYID_FLD + ","
+ SO_ReturnedGoodsMasterTable.PARTYCONTACTID_FLD + ","
+ SO_ReturnedGoodsMasterTable.MASTERLOCATIONID_FLD + ","
+ SO_ReturnedGoodsMasterTable.CURRENCYID_FLD + ","
+ SO_ReturnedGoodsMasterTable.EXCHANGERATE_FLD + ","
+ SO_ReturnedGoodsMasterTable.PARTYLOCATIONID_FLD + ")"
+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)";
//get the latest inserted new ID
strSql += " ; Select @@IDENTITY as NEWID";
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.RETURNEDGOODSNUMBER_FLD, OleDbType.WChar));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.RETURNEDGOODSNUMBER_FLD].Value = objObject.ReturnedGoodsNumber;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.RECEIVERID_FLD, OleDbType.Integer));
if (objObject.ReceiverID > 0)
{
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.RECEIVERID_FLD].Value = objObject.ReceiverID;
}
else
{
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.RECEIVERID_FLD].Value = DBNull.Value;
}
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.CCNID_FLD, OleDbType.Integer));
if (objObject.CCNID > 0)
{
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.CCNID_FLD].Value = objObject.CCNID;
}
else
{
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.CCNID_FLD].Value = DBNull.Value;
}
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.TRANSDATE_FLD, OleDbType.Date));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.TRANSDATE_FLD].Value = objObject.TransDate;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.DESCRIPTION_FLD, OleDbType.WChar));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.DESCRIPTION_FLD].Value = objObject.Description;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.POSTDATE_FLD, OleDbType.Date));
if (objObject.PostDate != DateTime.MinValue)
{
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.POSTDATE_FLD].Value = objObject.PostDate;
}
else
{
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.POSTDATE_FLD].Value = DBNull.Value;
}
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.SALEORDERMASTERID_FLD, OleDbType.Integer));
if (objObject.SaleOrderMasterID > 0)
{
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.SALEORDERMASTERID_FLD].Value = objObject.SaleOrderMasterID;
}
else
{
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.SALEORDERMASTERID_FLD].Value = DBNull.Value;
}
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.PARTYID_FLD, OleDbType.Integer));
if (objObject.PartyID > 0)
{
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.PARTYID_FLD].Value = objObject.PartyID;
}
else
{
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.PARTYID_FLD].Value = DBNull.Value;
}
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.PARTYCONTACTID_FLD, OleDbType.Integer));
if (objObject.PartyContactID > 0)
{
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.PARTYCONTACTID_FLD].Value = objObject.PartyContactID;
}
else
{
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.PARTYCONTACTID_FLD].Value = DBNull.Value;
}
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.MASTERLOCATIONID_FLD, OleDbType.Integer));
if (objObject.MasterLocationID > 0)
{
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.MASTERLOCATIONID_FLD].Value = objObject.MasterLocationID;
}
else
{
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.MASTERLOCATIONID_FLD].Value = DBNull.Value;
}
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.CURRENCYID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.CURRENCYID_FLD].Value = objObject.CurrencyID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.EXCHANGERATE_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.EXCHANGERATE_FLD].Value = objObject.ExchangeRate;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.PARTYLOCATIONID_FLD, OleDbType.Integer));
if (objObject.PartyLocationID > 0)
{
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.PARTYLOCATIONID_FLD].Value = objObject.PartyLocationID;
}
else
{
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.PARTYLOCATIONID_FLD].Value = DBNull.Value;
}
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
//insert and return new id
return int.Parse(ocmdPCS.ExecuteScalar().ToString());
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else if (ex.Errors[1].NativeError == ErrorCode.SQLDBNULL_VIALATION_KEYCODE)
{
throw new PCSDBException(ErrorCode.DBNULL_VIALATION,METHOD_NAME,ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to delete data from SO_ReturnedGoodsMaster
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// void
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Delete(int pintID)
{
const string METHOD_NAME = THIS + ".Delete()";
string strSql = String.Empty;
strSql= "DELETE " + SO_ReturnedGoodsMasterTable.TABLE_NAME + " WHERE " + "ReturnedGoodsMasterID" + "=" + pintID.ToString();
OleDbConnection oconPCS=null;
OleDbCommand ocmdPCS =null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
ocmdPCS = null;
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get data from SO_ReturnedGoodsMaster
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// SO_ReturnedGoodsMasterVO
/// </Outputs>
/// <Returns>
/// SO_ReturnedGoodsMasterVO
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, February 22, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetReturnedGoodsMasterVO(int pintID)
{
const string METHOD_NAME = THIS + ".GetReturnedGoodsMasterVO()";
DataSet dstPCS = new DataSet();
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ SO_ReturnedGoodsMasterTable.RETURNEDGOODSMASTERID_FLD + ","
+ SO_ReturnedGoodsMasterTable.RETURNEDGOODSNUMBER_FLD + ","
+ SO_ReturnedGoodsMasterTable.RECEIVERID_FLD + ","
+ SO_ReturnedGoodsMasterTable.CCNID_FLD + ","
+ SO_ReturnedGoodsMasterTable.TRANSDATE_FLD + ","
+ SO_ReturnedGoodsMasterTable.DESCRIPTION_FLD + ","
+ SO_ReturnedGoodsMasterTable.POSTDATE_FLD + ","
+ SO_ReturnedGoodsMasterTable.SALEORDERMASTERID_FLD + ","
+ SO_ReturnedGoodsMasterTable.PARTYID_FLD + ","
+ SO_ReturnedGoodsMasterTable.PARTYCONTACTID_FLD + ","
+ SO_ReturnedGoodsMasterTable.MASTERLOCATIONID_FLD + ","
+ SO_ReturnedGoodsMasterTable.PARTYLOCATIONID_FLD
+ " FROM " + SO_ReturnedGoodsMasterTable.TABLE_NAME
+" WHERE " + SO_ReturnedGoodsMasterTable.RETURNEDGOODSMASTERID_FLD + "=" + pintID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
SO_ReturnedGoodsMasterVO objObject = new SO_ReturnedGoodsMasterVO();
while (odrPCS.Read())
{
objObject.ReturnedGoodsMasterID = int.Parse(odrPCS[SO_ReturnedGoodsMasterTable.RETURNEDGOODSMASTERID_FLD].ToString().Trim());
objObject.ReturnedGoodsNumber = odrPCS[SO_ReturnedGoodsMasterTable.RETURNEDGOODSNUMBER_FLD].ToString().Trim();
if (odrPCS[SO_ReturnedGoodsMasterTable.RECEIVERID_FLD] != DBNull.Value && odrPCS[SO_ReturnedGoodsMasterTable.RECEIVERID_FLD].ToString().Trim() != String.Empty)
{
objObject.ReceiverID = int.Parse(odrPCS[SO_ReturnedGoodsMasterTable.RECEIVERID_FLD].ToString().Trim());
}
if (odrPCS[SO_ReturnedGoodsMasterTable.CCNID_FLD] != DBNull.Value && odrPCS[SO_ReturnedGoodsMasterTable.CCNID_FLD].ToString().Trim() != String.Empty)
{
objObject.CCNID = int.Parse(odrPCS[SO_ReturnedGoodsMasterTable.CCNID_FLD].ToString().Trim());
}
if (odrPCS[SO_ReturnedGoodsMasterTable.TRANSDATE_FLD] != DBNull.Value && odrPCS[SO_ReturnedGoodsMasterTable.TRANSDATE_FLD].ToString().Trim() != String.Empty)
{
objObject.TransDate = DateTime.Parse(odrPCS[SO_ReturnedGoodsMasterTable.TRANSDATE_FLD].ToString().Trim());
}
objObject.Description = odrPCS[SO_ReturnedGoodsMasterTable.DESCRIPTION_FLD].ToString().Trim();
if (odrPCS[SO_ReturnedGoodsMasterTable.POSTDATE_FLD] != DBNull.Value && odrPCS[SO_ReturnedGoodsMasterTable.POSTDATE_FLD].ToString().Trim() != String.Empty)
{
objObject.PostDate = DateTime.Parse(odrPCS[SO_ReturnedGoodsMasterTable.POSTDATE_FLD].ToString().Trim());
}
if (odrPCS[SO_ReturnedGoodsMasterTable.SALEORDERMASTERID_FLD] != DBNull.Value && odrPCS[SO_ReturnedGoodsMasterTable.SALEORDERMASTERID_FLD].ToString().Trim() != String.Empty)
{
objObject.SaleOrderMasterID = int.Parse(odrPCS[SO_ReturnedGoodsMasterTable.SALEORDERMASTERID_FLD].ToString().Trim());
}
if (odrPCS[SO_ReturnedGoodsMasterTable.PARTYID_FLD] != DBNull.Value && odrPCS[SO_ReturnedGoodsMasterTable.PARTYID_FLD].ToString().Trim() != String.Empty)
{
objObject.PartyID = int.Parse(odrPCS[SO_ReturnedGoodsMasterTable.PARTYID_FLD].ToString().Trim());
}
if (odrPCS[SO_ReturnedGoodsMasterTable.PARTYCONTACTID_FLD] != DBNull.Value && odrPCS[SO_ReturnedGoodsMasterTable.PARTYCONTACTID_FLD].ToString().Trim() != String.Empty)
{
objObject.PartyContactID = int.Parse(odrPCS[SO_ReturnedGoodsMasterTable.PARTYCONTACTID_FLD].ToString().Trim());
}
if (odrPCS[SO_ReturnedGoodsMasterTable.MASTERLOCATIONID_FLD] != DBNull.Value && odrPCS[SO_ReturnedGoodsMasterTable.MASTERLOCATIONID_FLD].ToString().Trim() != String.Empty)
{
objObject.MasterLocationID = int.Parse(odrPCS[SO_ReturnedGoodsMasterTable.MASTERLOCATIONID_FLD].ToString().Trim());
}
if (odrPCS[SO_ReturnedGoodsMasterTable.PARTYLOCATIONID_FLD] != DBNull.Value && odrPCS[SO_ReturnedGoodsMasterTable.PARTYLOCATIONID_FLD].ToString().Trim() != String.Empty)
{
objObject.PartyLocationID = int.Parse(odrPCS[SO_ReturnedGoodsMasterTable.PARTYLOCATIONID_FLD].ToString().Trim());
}
}
return objObject;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get data from SO_ReturnedGoodsMaster
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// SO_ReturnedGoodsMasterVO
/// </Outputs>
/// <Returns>
/// SO_ReturnedGoodsMasterVO
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, February 22, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public string GetReturnedGoodsMasterIDByNumber(string pstrReturnedGoodsNumber)
{
const string METHOD_NAME = THIS + ".GetReturnedGoodsMasterIDByNumber()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ SO_ReturnedGoodsMasterTable.RETURNEDGOODSMASTERID_FLD
+ " FROM " + SO_ReturnedGoodsMasterTable.TABLE_NAME
+ " WHERE " + SO_ReturnedGoodsMasterTable.RETURNEDGOODSNUMBER_FLD + "=?" ;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.RETURNEDGOODSNUMBER_FLD, OleDbType.WChar));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.RETURNEDGOODSNUMBER_FLD].Value = pstrReturnedGoodsNumber;
object objReturnValue = null;
objReturnValue = ocmdPCS.ExecuteScalar();
if (objReturnValue != null)
{
return objReturnValue.ToString();
}
else
{
return String.Empty;
}
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get data from SO_ReturnedGoodsMaster
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// SO_ReturnedGoodsMasterVO
/// </Outputs>
/// <Returns>
/// SO_ReturnedGoodsMasterVO
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, February 22, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetObjectVO(int pintID)
{
const string METHOD_NAME = THIS + ".GetObjectVO()";
DataSet dstPCS = new DataSet();
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ SO_ReturnedGoodsMasterTable.RETURNEDGOODSMASTERID_FLD + ","
+ SO_ReturnedGoodsMasterTable.RETURNEDGOODSNUMBER_FLD + ","
+ SO_ReturnedGoodsMasterTable.RECEIVERID_FLD + ","
+ SO_ReturnedGoodsMasterTable.CCNID_FLD + ","
+ SO_ReturnedGoodsMasterTable.TRANSDATE_FLD + ","
+ SO_ReturnedGoodsMasterTable.DESCRIPTION_FLD + ","
+ SO_ReturnedGoodsMasterTable.POSTDATE_FLD + ","
+ SO_ReturnedGoodsMasterTable.SALEORDERMASTERID_FLD + ","
+ SO_ReturnedGoodsMasterTable.PARTYID_FLD + ","
+ SO_ReturnedGoodsMasterTable.PARTYCONTACTID_FLD + ","
+ SO_ReturnedGoodsMasterTable.MASTERLOCATIONID_FLD + ","
+ SO_ReturnedGoodsMasterTable.PARTYLOCATIONID_FLD
+ " FROM " + SO_ReturnedGoodsMasterTable.TABLE_NAME
+" WHERE " + SO_ReturnedGoodsMasterTable.RETURNEDGOODSMASTERID_FLD + "=" + pintID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
SO_ReturnedGoodsMasterVO objObject = new SO_ReturnedGoodsMasterVO();
while (odrPCS.Read())
{
objObject.ReturnedGoodsMasterID = int.Parse(odrPCS[SO_ReturnedGoodsMasterTable.RETURNEDGOODSMASTERID_FLD].ToString().Trim());
objObject.ReturnedGoodsNumber = odrPCS[SO_ReturnedGoodsMasterTable.RETURNEDGOODSNUMBER_FLD].ToString().Trim();
objObject.ReceiverID = int.Parse(odrPCS[SO_ReturnedGoodsMasterTable.RECEIVERID_FLD].ToString().Trim());
objObject.CCNID = int.Parse(odrPCS[SO_ReturnedGoodsMasterTable.CCNID_FLD].ToString().Trim());
objObject.TransDate = DateTime.Parse(odrPCS[SO_ReturnedGoodsMasterTable.TRANSDATE_FLD].ToString().Trim());
objObject.Description = odrPCS[SO_ReturnedGoodsMasterTable.DESCRIPTION_FLD].ToString().Trim();
objObject.PostDate = DateTime.Parse(odrPCS[SO_ReturnedGoodsMasterTable.POSTDATE_FLD].ToString().Trim());
try
{
objObject.SaleOrderMasterID = int.Parse(odrPCS[SO_ReturnedGoodsMasterTable.SALEORDERMASTERID_FLD].ToString().Trim());
}
catch
{
objObject.SaleOrderMasterID = 0;
}
try
{
objObject.PartyID = int.Parse(odrPCS[SO_ReturnedGoodsMasterTable.PARTYID_FLD].ToString().Trim());
}
catch
{
objObject.PartyID = 0;
}
try
{
objObject.PartyContactID = int.Parse(odrPCS[SO_ReturnedGoodsMasterTable.PARTYCONTACTID_FLD].ToString().Trim());
}
catch
{
objObject.PartyContactID = 0;
}
try
{
objObject.MasterLocationID = int.Parse(odrPCS[SO_ReturnedGoodsMasterTable.MASTERLOCATIONID_FLD].ToString().Trim());
}
catch
{
objObject.MasterLocationID = 0;
}
try
{
objObject.PartyLocationID = int.Parse(odrPCS[SO_ReturnedGoodsMasterTable.PARTYLOCATIONID_FLD].ToString().Trim());
}
catch
{
objObject.PartyLocationID = 0;
}
}
return objObject;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update data to SO_ReturnedGoodsMaster
/// </Description>
/// <Inputs>
/// SO_ReturnedGoodsMasterVO
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Update(object pobjObjecVO)
{
const string METHOD_NAME = THIS + ".Update()";
SO_ReturnedGoodsMasterVO objObject = (SO_ReturnedGoodsMasterVO) pobjObjecVO;
//prepare value for parameters
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
strSql= "UPDATE SO_ReturnedGoodsMaster SET "
+ SO_ReturnedGoodsMasterTable.RETURNEDGOODSNUMBER_FLD + "= ?" + ","
+ SO_ReturnedGoodsMasterTable.RECEIVERID_FLD + "= ?" + ","
+ SO_ReturnedGoodsMasterTable.CCNID_FLD + "= ?" + ","
+ SO_ReturnedGoodsMasterTable.TRANSDATE_FLD + "= ?" + ","
+ SO_ReturnedGoodsMasterTable.DESCRIPTION_FLD + "= ?" + ","
+ SO_ReturnedGoodsMasterTable.POSTDATE_FLD + "= ?" + ","
+ SO_ReturnedGoodsMasterTable.SALEORDERMASTERID_FLD + "= ?" + ","
+ SO_ReturnedGoodsMasterTable.PARTYID_FLD + "= ?" + ","
+ SO_ReturnedGoodsMasterTable.PARTYCONTACTID_FLD + "= ?" + ","
+ SO_ReturnedGoodsMasterTable.MASTERLOCATIONID_FLD + "= ?" + ","
+ SO_ReturnedGoodsMasterTable.PARTYLOCATIONID_FLD + "= ?"
+" WHERE " + SO_ReturnedGoodsMasterTable.RETURNEDGOODSMASTERID_FLD + "= ?";
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.RETURNEDGOODSNUMBER_FLD, OleDbType.WChar));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.RETURNEDGOODSNUMBER_FLD].Value = objObject.ReturnedGoodsNumber;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.RECEIVERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.RECEIVERID_FLD].Value = objObject.ReceiverID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.CCNID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.CCNID_FLD].Value = objObject.CCNID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.TRANSDATE_FLD, OleDbType.Date));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.TRANSDATE_FLD].Value = objObject.TransDate;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.DESCRIPTION_FLD, OleDbType.WChar));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.DESCRIPTION_FLD].Value = objObject.Description;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.POSTDATE_FLD, OleDbType.Date));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.POSTDATE_FLD].Value = objObject.PostDate;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.SALEORDERMASTERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.SALEORDERMASTERID_FLD].Value = objObject.SaleOrderMasterID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.PARTYID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.PARTYID_FLD].Value = objObject.PartyID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.PARTYCONTACTID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.PARTYCONTACTID_FLD].Value = objObject.PartyContactID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.MASTERLOCATIONID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.MASTERLOCATIONID_FLD].Value = objObject.MasterLocationID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.PARTYLOCATIONID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.PARTYLOCATIONID_FLD].Value = objObject.PartyLocationID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.RETURNEDGOODSMASTERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.RETURNEDGOODSMASTERID_FLD].Value = objObject.ReturnedGoodsMasterID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update data to SO_ReturnedGoodsMaster
/// </Description>
/// <Inputs>
/// SO_ReturnedGoodsMasterVO
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void UpdateReturnedGoods(object pobjObjecVO)
{
const string METHOD_NAME = THIS + ".UpdateReturnedGoods()";
SO_ReturnedGoodsMasterVO objObject = (SO_ReturnedGoodsMasterVO) pobjObjecVO;
//prepare value for parameters
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
strSql= "UPDATE SO_ReturnedGoodsMaster SET "
+ SO_ReturnedGoodsMasterTable.RETURNEDGOODSNUMBER_FLD + "= ?" + ","
+ SO_ReturnedGoodsMasterTable.RECEIVERID_FLD + "= ?" + ","
+ SO_ReturnedGoodsMasterTable.CCNID_FLD + "= ?" + ","
+ SO_ReturnedGoodsMasterTable.TRANSDATE_FLD + "= ?" + ","
+ SO_ReturnedGoodsMasterTable.DESCRIPTION_FLD + "= ?" + ","
+ SO_ReturnedGoodsMasterTable.POSTDATE_FLD + "= ?" + ","
+ SO_ReturnedGoodsMasterTable.SALEORDERMASTERID_FLD + "= ?" + ","
+ SO_ReturnedGoodsMasterTable.PARTYID_FLD + "= ?" + ","
+ SO_ReturnedGoodsMasterTable.PARTYCONTACTID_FLD + "= ?" + ","
+ SO_ReturnedGoodsMasterTable.MASTERLOCATIONID_FLD + "= ?" + ","
+ SO_ReturnedGoodsMasterTable.PARTYLOCATIONID_FLD + "= ?"
+" WHERE " + SO_ReturnedGoodsMasterTable.RETURNEDGOODSMASTERID_FLD + "= ?";
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.RETURNEDGOODSNUMBER_FLD, OleDbType.WChar));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.RETURNEDGOODSNUMBER_FLD].Value = objObject.ReturnedGoodsNumber;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.RECEIVERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.RECEIVERID_FLD].Value = DBNull.Value;
/*
if (objObject.ReceiverID > 0)
{
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.RECEIVERID_FLD].Value = objObject.ReceiverID;
}
else
{
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.RECEIVERID_FLD].Value = DBNull.Value;
}
*/
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.CCNID_FLD, OleDbType.Integer));
if (objObject.CCNID > 0)
{
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.CCNID_FLD].Value = objObject.CCNID;
}
else
{
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.CCNID_FLD].Value = DBNull.Value;
}
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.TRANSDATE_FLD, OleDbType.Date));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.TRANSDATE_FLD].Value = objObject.TransDate;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.DESCRIPTION_FLD, OleDbType.WChar));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.DESCRIPTION_FLD].Value = objObject.Description;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.POSTDATE_FLD, OleDbType.Date));
if (objObject.PostDate != DateTime.MinValue)
{
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.POSTDATE_FLD].Value = objObject.PostDate;
}
else
{
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.POSTDATE_FLD].Value = DBNull.Value;
}
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.SALEORDERMASTERID_FLD, OleDbType.Integer));
if (objObject.SaleOrderMasterID > 0)
{
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.SALEORDERMASTERID_FLD].Value = objObject.SaleOrderMasterID;
}
else
{
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.SALEORDERMASTERID_FLD].Value = DBNull.Value;
}
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.PARTYID_FLD, OleDbType.Integer));
if (objObject.PartyID > 0)
{
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.PARTYID_FLD].Value = objObject.PartyID;
}
else
{
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.PARTYID_FLD].Value = DBNull.Value;
}
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.PARTYCONTACTID_FLD, OleDbType.Integer));
if (objObject.PartyContactID > 0)
{
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.PARTYCONTACTID_FLD].Value = objObject.PartyContactID;
}
else
{
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.PARTYCONTACTID_FLD].Value = DBNull.Value;
}
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.MASTERLOCATIONID_FLD, OleDbType.Integer));
if (objObject.MasterLocationID > 0)
{
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.MASTERLOCATIONID_FLD].Value = objObject.MasterLocationID;
}
else
{
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.MASTERLOCATIONID_FLD].Value = DBNull.Value;
}
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.PARTYLOCATIONID_FLD, OleDbType.Integer));
if (objObject.PartyLocationID > 0)
{
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.PARTYLOCATIONID_FLD].Value = objObject.PartyLocationID;
}
else
{
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.PARTYLOCATIONID_FLD].Value = DBNull.Value;
}
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsMasterTable.RETURNEDGOODSMASTERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsMasterTable.RETURNEDGOODSMASTERID_FLD].Value = objObject.ReturnedGoodsMasterID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all data from SO_ReturnedGoodsMaster
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, February 22, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataTable GetReturnGoodsMaster(int pintReturnedGoodsID)
{
const string METHOD_NAME = THIS + ".List()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ SO_ReturnedGoodsMasterTable.TABLE_NAME + "." + SO_ReturnedGoodsMasterTable.RETURNEDGOODSMASTERID_FLD + ","
+ SO_ReturnedGoodsMasterTable.TABLE_NAME + "." + SO_ReturnedGoodsMasterTable.RETURNEDGOODSNUMBER_FLD + ","
+ SO_ReturnedGoodsMasterTable.TABLE_NAME + "." + SO_ReturnedGoodsMasterTable.RECEIVERID_FLD + ","
+ SO_ReturnedGoodsMasterTable.TABLE_NAME + "." + SO_ReturnedGoodsMasterTable.CCNID_FLD + ","
+ SO_ReturnedGoodsMasterTable.TABLE_NAME + "." + SO_ReturnedGoodsMasterTable.TRANSDATE_FLD + ","
+ SO_ReturnedGoodsMasterTable.TABLE_NAME + "." + SO_ReturnedGoodsMasterTable.CURRENCYID_FLD + ","
+ SO_ReturnedGoodsMasterTable.TABLE_NAME + "." + SO_ReturnedGoodsMasterTable.EXCHANGERATE_FLD + ","
+ " CUR." + MST_CurrencyTable.CODE_FLD + " " + MST_CurrencyTable.TABLE_NAME + MST_CurrencyTable.CODE_FLD + ","
+ SO_ReturnedGoodsMasterTable.TABLE_NAME + "." + SO_ReturnedGoodsMasterTable.DESCRIPTION_FLD + ","
+ SO_ReturnedGoodsMasterTable.TABLE_NAME + "." + SO_ReturnedGoodsMasterTable.POSTDATE_FLD + ","
+ SO_ReturnedGoodsMasterTable.TABLE_NAME + "." + SO_ReturnedGoodsMasterTable.SALEORDERMASTERID_FLD + ","
+ SO_ReturnedGoodsMasterTable.TABLE_NAME + "." + SO_ReturnedGoodsMasterTable.PARTYID_FLD + ","
+ SO_ReturnedGoodsMasterTable.TABLE_NAME + "." + SO_ReturnedGoodsMasterTable.PARTYCONTACTID_FLD + ","
+ SO_ReturnedGoodsMasterTable.TABLE_NAME + "." + SO_ReturnedGoodsMasterTable.MASTERLOCATIONID_FLD + ","
+ SO_ReturnedGoodsMasterTable.TABLE_NAME + "." + SO_ReturnedGoodsMasterTable.PARTYLOCATIONID_FLD + ","
+ SO_SaleOrderMasterTable.TABLE_NAME + "." + SO_SaleOrderMasterTable.CODE_FLD + " " + SO_SaleOrderMasterTable.TABLE_NAME + SO_SaleOrderMasterTable.CODE_FLD + ","
+ MST_PartyTable.TABLE_NAME + "." + MST_PartyTable.CODE_FLD + " " + MST_PartyTable.TABLE_NAME + MST_PartyTable.CODE_FLD + ","
+ MST_PartyTable.TABLE_NAME + "." + MST_PartyTable.NAME_FLD + " " + MST_PartyTable.TABLE_NAME + MST_PartyTable.NAME_FLD
+ " FROM " + SO_ReturnedGoodsMasterTable.TABLE_NAME
+ " left join " + SO_SaleOrderMasterTable.TABLE_NAME + " on "
+ SO_ReturnedGoodsMasterTable.TABLE_NAME + "." + SO_ReturnedGoodsMasterTable.SALEORDERMASTERID_FLD
+ "="
+ SO_SaleOrderMasterTable.TABLE_NAME + "." + SO_SaleOrderMasterTable.SALEORDERMASTERID_FLD
+ " Left join " + MST_PartyTable.TABLE_NAME + " on "
+ SO_ReturnedGoodsMasterTable.TABLE_NAME + "." + SO_ReturnedGoodsMasterTable.PARTYID_FLD
+ "="
+ MST_PartyTable.TABLE_NAME + "." + MST_PartyTable.PARTYID_FLD
+ " left join " + MST_CurrencyTable.TABLE_NAME + " CUR ON CUR." + MST_CurrencyTable.CURRENCYID_FLD
+ " = " + SO_ReturnedGoodsMasterTable.TABLE_NAME + "." + SO_ReturnedGoodsMasterTable.CURRENCYID_FLD
+ " WHERE " + SO_ReturnedGoodsMasterTable.TABLE_NAME + "." + SO_ReturnedGoodsMasterTable.RETURNEDGOODSMASTERID_FLD + "=" + pintReturnedGoodsID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,SO_ReturnedGoodsMasterTable.TABLE_NAME);
return dstPCS.Tables[0];
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all data from SO_ReturnedGoodsMaster
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, February 22, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet List()
{
const string METHOD_NAME = THIS + ".List()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ SO_ReturnedGoodsMasterTable.RETURNEDGOODSMASTERID_FLD + ","
+ SO_ReturnedGoodsMasterTable.RETURNEDGOODSNUMBER_FLD + ","
+ SO_ReturnedGoodsMasterTable.RECEIVERID_FLD + ","
+ SO_ReturnedGoodsMasterTable.CCNID_FLD + ","
+ SO_ReturnedGoodsMasterTable.TRANSDATE_FLD + ","
+ SO_ReturnedGoodsMasterTable.DESCRIPTION_FLD + ","
+ SO_ReturnedGoodsMasterTable.POSTDATE_FLD + ","
+ SO_ReturnedGoodsMasterTable.SALEORDERMASTERID_FLD + ","
+ SO_ReturnedGoodsMasterTable.PARTYID_FLD + ","
+ SO_ReturnedGoodsMasterTable.PARTYCONTACTID_FLD + ","
+ SO_ReturnedGoodsMasterTable.MASTERLOCATIONID_FLD + ","
+ SO_ReturnedGoodsMasterTable.PARTYLOCATIONID_FLD
+ " FROM " + SO_ReturnedGoodsMasterTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,SO_ReturnedGoodsMasterTable.TABLE_NAME);
return dstPCS;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update a DataSet
/// </Description>
/// <Inputs>
/// DataSet
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, February 22, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void UpdateDataSet(DataSet pData)
{
const string METHOD_NAME = THIS + ".UpdateDataSet()";
string strSql;
OleDbConnection oconPCS =null;
OleDbCommandBuilder odcbPCS ;
OleDbDataAdapter odadPCS = new OleDbDataAdapter();
try
{
strSql= "SELECT "
+ SO_ReturnedGoodsMasterTable.RETURNEDGOODSMASTERID_FLD + ","
+ SO_ReturnedGoodsMasterTable.RETURNEDGOODSNUMBER_FLD + ","
+ SO_ReturnedGoodsMasterTable.RECEIVERID_FLD + ","
+ SO_ReturnedGoodsMasterTable.CCNID_FLD + ","
+ SO_ReturnedGoodsMasterTable.TRANSDATE_FLD + ","
+ SO_ReturnedGoodsMasterTable.DESCRIPTION_FLD + ","
+ SO_ReturnedGoodsMasterTable.POSTDATE_FLD + ","
+ SO_ReturnedGoodsMasterTable.SALEORDERMASTERID_FLD + ","
+ SO_ReturnedGoodsMasterTable.PARTYID_FLD + ","
+ SO_ReturnedGoodsMasterTable.PARTYCONTACTID_FLD + ","
+ SO_ReturnedGoodsMasterTable.MASTERLOCATIONID_FLD + ","
+ SO_ReturnedGoodsMasterTable.PARTYLOCATIONID_FLD
+ " FROM " + SO_ReturnedGoodsMasterTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS);
odcbPCS = new OleDbCommandBuilder(odadPCS);
pData.EnforceConstraints = false;
odadPCS.Update(pData,SO_ReturnedGoodsMasterTable.TABLE_NAME);
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
}
}
| |
#region References
using System;
using System.Globalization;
using System.Runtime.InteropServices;
using Raspberry.IO.GeneralPurpose;
using Raspberry.Timers;
#endregion
namespace Raspberry.IO.InterIntegratedCircuit
{
/// <summary>
/// Represents a driver for I2C devices.
/// </summary>
public class I2cDriver : IDisposable
{
#region Fields
private readonly object driverLock = new object();
private readonly ProcessorPin sdaPin;
private readonly ProcessorPin sclPin;
private readonly bool wasSdaPinSet;
private readonly bool wasSclPinSet;
private readonly IntPtr gpioAddress;
private readonly IntPtr bscAddress;
private int currentDeviceAddress;
private int waitInterval;
#endregion
#region Instance Management
/// <summary>
/// Initializes a new instance of the <see cref="I2cDriver"/> class.
/// </summary>
/// <param name="sdaPin">The SDA pin.</param>
/// <param name="sclPin">The SCL pin.</param>
public I2cDriver(ProcessorPin sdaPin, ProcessorPin sclPin)
{
this.sdaPin = sdaPin;
this.sclPin = sclPin;
var bscBase = GetBscBase(sdaPin, sclPin);
var memoryFile = Interop.open("/dev/mem", Interop.O_RDWR + Interop.O_SYNC);
try
{
gpioAddress = Interop.mmap(
IntPtr.Zero,
Interop.BCM2835_BLOCK_SIZE,
Interop.PROT_READ | Interop.PROT_WRITE,
Interop.MAP_SHARED,
memoryFile,
GetProcessorGpioAddress(Board.Current.Processor));
bscAddress = Interop.mmap(
IntPtr.Zero,
Interop.BCM2835_BLOCK_SIZE,
Interop.PROT_READ | Interop.PROT_WRITE,
Interop.MAP_SHARED,
memoryFile,
bscBase);
}
finally
{
Interop.close(memoryFile);
}
if (bscAddress == (IntPtr) Interop.MAP_FAILED)
throw new InvalidOperationException("Unable to access device memory");
// Set the I2C pins to the Alt 0 function to enable I2C access on them
// remembers if the values were actually changed to clear them or not upon dispose
wasSdaPinSet = SetPinMode((uint)(int)sdaPin, Interop.BCM2835_GPIO_FSEL_ALT0); // SDA
wasSclPinSet = SetPinMode((uint) (int) sclPin, Interop.BCM2835_GPIO_FSEL_ALT0); // SCL
// Read the clock divider register
var dividerAddress = bscAddress + (int) Interop.BCM2835_BSC_DIV;
var divider = (ushort) SafeReadUInt32(dividerAddress);
waitInterval = GetWaitInterval(divider);
var addressAddress = bscAddress + (int) Interop.BCM2835_BSC_A;
SafeWriteUInt32(addressAddress, (uint) currentDeviceAddress);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
// Set all the I2C/BSC1 pins back to original values if changed
if (wasSdaPinSet)
{
SetPinMode((uint)(int)sdaPin, Interop.BCM2835_GPIO_FSEL_INPT); // SDA
}
if (wasSclPinSet)
{
SetPinMode((uint)(int)sclPin, Interop.BCM2835_GPIO_FSEL_INPT); // SCL
}
Interop.munmap(gpioAddress, Interop.BCM2835_BLOCK_SIZE);
Interop.munmap(bscAddress, Interop.BCM2835_BLOCK_SIZE);
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the clock divider.
/// </summary>
/// <value>
/// The clock divider.
/// </value>
public int ClockDivider
{
get
{
var dividerAddress = bscAddress + (int) Interop.BCM2835_BSC_DIV;
return (ushort) SafeReadUInt32(dividerAddress);
}
set
{
var dividerAddress = bscAddress + (int) Interop.BCM2835_BSC_DIV;
SafeWriteUInt32(dividerAddress, (uint) value);
var actualDivider = (ushort) SafeReadUInt32(dividerAddress);
waitInterval = GetWaitInterval(actualDivider);
}
}
#endregion
#region Methods
/// <summary>
/// Connects the specified device address.
/// </summary>
/// <param name="deviceAddress">The device address.</param>
/// <returns>The device connection</returns>
public I2cDeviceConnection Connect(int deviceAddress)
{
return new I2cDeviceConnection(this, deviceAddress);
}
#endregion
#region Internal Methods
/// <summary>
/// Executes the specified transaction.
/// </summary>
/// <param name="deviceAddress">The address of the device.</param>
/// <param name="transaction">The transaction.</param>
internal void Execute(int deviceAddress, I2cTransaction transaction)
{
lock (driverLock)
{
var control = bscAddress + (int)Interop.BCM2835_BSC_C;
foreach (I2cAction action in transaction.Actions)
{
if (action is I2cWriteAction)
{
Write(deviceAddress, action.Buffer);
}
else if (action is I2cReadAction)
{
Read(deviceAddress, action.Buffer);
}
else
{
throw new InvalidOperationException("Only read and write transactions are allowed.");
}
}
WriteUInt32Mask(control, Interop.BCM2835_BSC_S_DONE, Interop.BCM2835_BSC_S_DONE);
}
}
#endregion
#region Private Helpers
private void Write(int deviceAddress, byte[] buffer)
{
this.EnsureDeviceAddress(deviceAddress);
var len = (uint)buffer.Length;
var dlen = this.bscAddress + (int)Interop.BCM2835_BSC_DLEN;
var fifo = this.bscAddress + (int)Interop.BCM2835_BSC_FIFO;
var status = this.bscAddress + (int)Interop.BCM2835_BSC_S;
var control = this.bscAddress + (int)Interop.BCM2835_BSC_C;
var remaining = len;
var i = 0;
// Clear FIFO
WriteUInt32Mask(control, Interop.BCM2835_BSC_C_CLEAR_1, Interop.BCM2835_BSC_C_CLEAR_1);
// Clear Status
WriteUInt32(status, Interop.BCM2835_BSC_S_CLKT | Interop.BCM2835_BSC_S_ERR | Interop.BCM2835_BSC_S_DONE);
// Set Data Length
WriteUInt32(dlen, len);
while (remaining != 0 && i < Interop.BCM2835_BSC_FIFO_SIZE)
{
WriteUInt32(fifo, buffer[i]);
i++;
remaining--;
}
// Enable device and start transfer
WriteUInt32(control, Interop.BCM2835_BSC_C_I2CEN | Interop.BCM2835_BSC_C_ST);
while ((ReadUInt32(status) & Interop.BCM2835_BSC_S_DONE) == 0)
{
while (remaining != 0 && (ReadUInt32(status) & Interop.BCM2835_BSC_S_TXD) != 0)
{
// Write to FIFO, no barrier
WriteUInt32(fifo, buffer[i]);
i++;
remaining--;
}
this.Wait(remaining);
}
if ((SafeReadUInt32(status) & Interop.BCM2835_BSC_S_ERR) != 0) // Received a NACK
throw new InvalidOperationException("Read operation failed with BCM2835_I2C_REASON_ERROR_NACK status");
if ((SafeReadUInt32(status) & Interop.BCM2835_BSC_S_CLKT) != 0) // Received Clock Stretch Timeout
throw new InvalidOperationException("Read operation failed with BCM2835_I2C_REASON_ERROR_CLKT status");
if (remaining != 0) // Not all data is sent
throw new InvalidOperationException(string.Format("Read operation failed with BCM2835_I2C_REASON_ERROR_DATA status, missing {0} bytes", remaining));
}
private void Read(int deviceAddress, byte[] buffer)
{
this.EnsureDeviceAddress(deviceAddress);
var dlen = this.bscAddress + (int)Interop.BCM2835_BSC_DLEN;
var fifo = this.bscAddress + (int)Interop.BCM2835_BSC_FIFO;
var status = this.bscAddress + (int)Interop.BCM2835_BSC_S;
var control = this.bscAddress + (int)Interop.BCM2835_BSC_C;
var remaining = (uint)buffer.Length;
uint i = 0;
// Clear FIFO
WriteUInt32Mask(control, Interop.BCM2835_BSC_C_CLEAR_1, Interop.BCM2835_BSC_C_CLEAR_1);
// Clear Status
WriteUInt32(status, Interop.BCM2835_BSC_S_CLKT | Interop.BCM2835_BSC_S_ERR | Interop.BCM2835_BSC_S_DONE);
// Set Data Length
WriteUInt32(dlen, (uint)buffer.Length);
// Start read
WriteUInt32(control, Interop.BCM2835_BSC_C_I2CEN | Interop.BCM2835_BSC_C_ST | Interop.BCM2835_BSC_C_READ);
while ((ReadUInt32(status) & Interop.BCM2835_BSC_S_DONE) == 0)
{
while ((ReadUInt32(status) & Interop.BCM2835_BSC_S_RXD) != 0)
{
// Read from FIFO, no barrier
buffer[i] = (byte)ReadUInt32(fifo);
i++;
remaining--;
}
this.Wait(remaining);
}
while (remaining != 0 && (ReadUInt32(status) & Interop.BCM2835_BSC_S_RXD) != 0)
{
buffer[i] = (byte)ReadUInt32(fifo);
i++;
remaining--;
}
if ((SafeReadUInt32(status) & Interop.BCM2835_BSC_S_ERR) != 0) // Received a NACK
throw new InvalidOperationException("Read operation failed with BCM2835_I2C_REASON_ERROR_NACK status");
if ((SafeReadUInt32(status) & Interop.BCM2835_BSC_S_CLKT) != 0) // Received Clock Stretch Timeout
throw new InvalidOperationException("Read operation failed with BCM2835_I2C_REASON_ERROR_CLKT status");
if (remaining != 0) // Not all data is received
throw new InvalidOperationException(string.Format("Read operation failed with BCM2835_I2C_REASON_ERROR_DATA status, missing {0} bytes", remaining));
}
private static uint GetProcessorBscAddress(Processor processor)
{
switch (processor)
{
case Processor.Bcm2708:
return Interop.BCM2835_BSC1_BASE;
case Processor.Bcm2709:
return Interop.BCM2836_BSC1_BASE;
default:
throw new ArgumentOutOfRangeException("processor");
}
}
private static uint GetProcessorGpioAddress(Processor processor)
{
switch (processor)
{
case Processor.Bcm2708:
return Interop.BCM2835_GPIO_BASE;
case Processor.Bcm2709:
case Processor.Bcm2835:
return Interop.BCM2836_GPIO_BASE;
default:
throw new ArgumentOutOfRangeException("processor");
}
}
private void EnsureDeviceAddress(int deviceAddress)
{
if (deviceAddress != currentDeviceAddress)
{
var addressAddress = bscAddress + (int)Interop.BCM2835_BSC_A;
SafeWriteUInt32(addressAddress, (uint)deviceAddress);
currentDeviceAddress = deviceAddress;
}
}
private void Wait(uint remaining)
{
// When remaining data is to be received, then wait for a fully FIFO
if (remaining != 0)
Timer.Sleep(TimeSpan.FromMilliseconds(waitInterval * (remaining >= Interop.BCM2835_BSC_FIFO_SIZE ? Interop.BCM2835_BSC_FIFO_SIZE : remaining) / 1000d));
}
private static int GetWaitInterval(ushort actualDivider)
{
// Calculate time for transmitting one byte
// 1000000 = micros seconds in a second
// 9 = Clocks per byte : 8 bits + ACK
return (int)((decimal)actualDivider * 1000000 * 9 / Interop.BCM2835_CORE_CLK_HZ);
}
private static uint GetBscBase(ProcessorPin sdaPin, ProcessorPin sclPin)
{
switch (GpioConnectionSettings.ConnectorPinout)
{
case ConnectorPinout.Rev1:
if (sdaPin == ProcessorPin.Pin0 && sclPin == ProcessorPin.Pin1)
return Interop.BCM2835_BSC0_BASE;
throw new InvalidOperationException("No I2C device exist on the specified pins");
case ConnectorPinout.Rev2:
if (sdaPin == ProcessorPin.Pin28 && sclPin == ProcessorPin.Pin29)
return Interop.BCM2835_BSC0_BASE;
if (sdaPin == ProcessorPin.Pin2 && sclPin == ProcessorPin.Pin3)
return Interop.BCM2835_BSC1_BASE;
throw new InvalidOperationException("No I2C device exist on the specified pins");
case ConnectorPinout.Plus:
if (sdaPin == ProcessorPin.Pin2 && sclPin == ProcessorPin.Pin3)
return GetProcessorBscAddress(Board.Current.Processor);
throw new InvalidOperationException("No I2C device exist on the specified pins");
default:
throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "Connector pinout {0} is not supported", GpioConnectionSettings.ConnectorPinout));
}
}
/// <summary>
///
/// </summary>
/// <param name="pin"></param>
/// <param name="mode"></param>
/// <returns>True when value was changed, false otherwise.</returns>
private bool SetPinMode(uint pin, uint mode)
{
// Function selects are 10 pins per 32 bit word, 3 bits per pin
var paddr = gpioAddress + (int) (Interop.BCM2835_GPFSEL0 + 4*(pin/10));
var shift = (pin%10)*3;
var mask = Interop.BCM2835_GPIO_FSEL_MASK << (int) shift;
var value = mode << (int) shift;
var existing = ReadUInt32(paddr) & mask;
if (existing != value)
{
//Console.WriteLine($"existing is {x} masked:{x & mask} vs mask:{mask} value:{value}");
WriteUInt32Mask(paddr, value, mask);
return true;
}
else
{
return false;
}
}
private static void WriteUInt32Mask(IntPtr address, uint value, uint mask)
{
var v = SafeReadUInt32(address);
v = (v & ~mask) | (value & mask);
SafeWriteUInt32(address, v);
}
private static uint SafeReadUInt32(IntPtr address)
{
// Make sure we dont return the _last_ read which might get lost
// if subsequent code changes to a different peripheral
unchecked
{
var returnValue = (uint) Marshal.ReadInt32(address);
Marshal.ReadInt32(address);
return returnValue;
}
}
private static uint ReadUInt32(IntPtr address)
{
unchecked
{
return (uint) Marshal.ReadInt32(address);
}
}
private static void SafeWriteUInt32(IntPtr address, uint value)
{
// Make sure we don't rely on the first write, which may get
// lost if the previous access was to a different peripheral.
unchecked
{
Marshal.WriteInt32(address, (int)value);
Marshal.WriteInt32(address, (int)value);
}
}
private static void WriteUInt32(IntPtr address, uint value)
{
unchecked
{
Marshal.WriteInt32(address, (int)value);
}
}
#endregion
}
}
| |
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Forms;
using System.Collections;
using Thinktecture.Tools.Web.Services.Wscf.Environment;
using Thinktecture.Tools.Web.Services.CodeGeneration;
namespace Thinktecture.Tools.Wscf.UI.Dialogs
{
/// <summary>
/// Summary description for WebServiceCodeGenOptions.
/// </summary>
public partial class WebServiceCodeGenDialogNew : Form
{
private Button btnGenerate;
private Button btnCancel;
private GroupBox groupBox2;
private Label label1;
private TextBox tbDestinationFilename;
private Label label2;
private TextBox tbDestinationNamespace;
private ToolTip cfTooltip;
private Panel panel1;
private GroupBox groupBox5;
private Label label4;
private Button bnBrowse;
private OpenFileDialog openFileDialogWSDL;
private IContainer components;
private CheckBox cbSettings;
private CheckBox cbSeperateFiles;
private PictureBox pbWizard;
private ComboBox cbWsdlLocation;
private System.Windows.Forms.CheckBox cbOverwrite;
private System.Windows.Forms.PictureBox pbWscf;
private System.Windows.Forms.CheckBox cbAdjustCasing;
private System.Windows.Forms.CheckBox cbMultipleFiles;
private System.Windows.Forms.CheckBox cbCollections;
private System.Windows.Forms.CheckBox cbFormatSoapActions;
private System.Windows.Forms.CheckBox cbProperties;
private System.Windows.Forms.RadioButton rbServer;
private System.Windows.Forms.RadioButton rbClient;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.GroupBox groupBox4;
private CheckBox cbOrderIds;
private CheckBox cbAsync;
private CheckBox cbDataBinding;
private CheckBox cbGenericList;
private CheckBox cbEnableWsdlEndpoint;
private GroupBox gbServiceBehavior;
private CheckBox cbUseSynchronizationContext;
private Label label3;
private Label label5;
private ComboBox cbConcurrencyMode;
private ComboBox cbInstanceContextMode;
private CheckBox cbGenerateSvcFile;
private bool isLoading = true;
private GroupBox gbServiceMethodImplementation;
private RadioButton rbAbstractMethods;
private RadioButton rbPartialClassMethodCalls;
private RadioButton rbNotImplementedException;
private CodeGenerationOptions options;
public WebServiceCodeGenDialogNew()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
// Initialize the .wsdl file cache.
wsdlFileCache = new ArrayList();
options= new CodeGenerationOptions();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <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()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(WebServiceCodeGenDialogNew));
this.cbSeperateFiles = new System.Windows.Forms.CheckBox();
this.btnGenerate = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.tbDestinationNamespace = new System.Windows.Forms.TextBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.label2 = new System.Windows.Forms.Label();
this.tbDestinationFilename = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.cfTooltip = new System.Windows.Forms.ToolTip(this.components);
this.cbSettings = new System.Windows.Forms.CheckBox();
this.pbWscf = new System.Windows.Forms.PictureBox();
this.cbAdjustCasing = new System.Windows.Forms.CheckBox();
this.cbMultipleFiles = new System.Windows.Forms.CheckBox();
this.cbCollections = new System.Windows.Forms.CheckBox();
this.cbFormatSoapActions = new System.Windows.Forms.CheckBox();
this.cbProperties = new System.Windows.Forms.CheckBox();
this.rbServer = new System.Windows.Forms.RadioButton();
this.rbClient = new System.Windows.Forms.RadioButton();
this.cbOverwrite = new System.Windows.Forms.CheckBox();
this.cbAsync = new System.Windows.Forms.CheckBox();
this.cbDataBinding = new System.Windows.Forms.CheckBox();
this.cbOrderIds = new System.Windows.Forms.CheckBox();
this.cbGenericList = new System.Windows.Forms.CheckBox();
this.cbEnableWsdlEndpoint = new System.Windows.Forms.CheckBox();
this.cbUseSynchronizationContext = new System.Windows.Forms.CheckBox();
this.cbConcurrencyMode = new System.Windows.Forms.ComboBox();
this.cbInstanceContextMode = new System.Windows.Forms.ComboBox();
this.cbGenerateSvcFile = new System.Windows.Forms.CheckBox();
this.panel1 = new System.Windows.Forms.Panel();
this.pbWizard = new System.Windows.Forms.PictureBox();
this.groupBox5 = new System.Windows.Forms.GroupBox();
this.cbWsdlLocation = new System.Windows.Forms.ComboBox();
this.bnBrowse = new System.Windows.Forms.Button();
this.label4 = new System.Windows.Forms.Label();
this.openFileDialogWSDL = new System.Windows.Forms.OpenFileDialog();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.gbServiceBehavior = new System.Windows.Forms.GroupBox();
this.label3 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.gbServiceMethodImplementation = new System.Windows.Forms.GroupBox();
this.rbAbstractMethods = new System.Windows.Forms.RadioButton();
this.rbPartialClassMethodCalls = new System.Windows.Forms.RadioButton();
this.rbNotImplementedException = new System.Windows.Forms.RadioButton();
this.groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pbWscf)).BeginInit();
this.panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pbWizard)).BeginInit();
this.groupBox5.SuspendLayout();
this.groupBox1.SuspendLayout();
this.gbServiceBehavior.SuspendLayout();
this.groupBox4.SuspendLayout();
this.gbServiceMethodImplementation.SuspendLayout();
this.SuspendLayout();
//
// cbSeperateFiles
//
this.cbSeperateFiles.Location = new System.Drawing.Point(0, 0);
this.cbSeperateFiles.Name = "cbSeperateFiles";
this.cbSeperateFiles.Size = new System.Drawing.Size(104, 24);
this.cbSeperateFiles.TabIndex = 0;
this.cfTooltip.SetToolTip(this.cbSeperateFiles, "Generates collection-based members instead of arrays.");
//
// btnGenerate
//
this.btnGenerate.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.btnGenerate.DialogResult = System.Windows.Forms.DialogResult.OK;
this.btnGenerate.Enabled = false;
this.btnGenerate.Location = new System.Drawing.Point(401, 628);
this.btnGenerate.Name = "btnGenerate";
this.btnGenerate.Size = new System.Drawing.Size(77, 28);
this.btnGenerate.TabIndex = 5;
this.btnGenerate.Text = "Generate";
this.btnGenerate.Click += new System.EventHandler(this.btnGenerate_Click);
//
// btnCancel
//
this.btnCancel.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Location = new System.Drawing.Point(484, 628);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(77, 28);
this.btnCancel.TabIndex = 6;
this.btnCancel.Text = "Cancel";
//
// tbDestinationNamespace
//
this.tbDestinationNamespace.Location = new System.Drawing.Point(152, 49);
this.tbDestinationNamespace.Name = "tbDestinationNamespace";
this.tbDestinationNamespace.Size = new System.Drawing.Size(392, 20);
this.tbDestinationNamespace.TabIndex = 3;
this.cfTooltip.SetToolTip(this.tbDestinationNamespace, "Please enter the name of .NET namespace for the client proxy.");
//
// groupBox2
//
this.groupBox2.Controls.Add(this.tbDestinationNamespace);
this.groupBox2.Controls.Add(this.label2);
this.groupBox2.Controls.Add(this.tbDestinationFilename);
this.groupBox2.Controls.Add(this.label1);
this.groupBox2.Location = new System.Drawing.Point(8, 493);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(553, 80);
this.groupBox2.TabIndex = 2;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Files and namespaces ";
//
// label2
//
this.label2.Location = new System.Drawing.Point(8, 26);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(118, 16);
this.label2.TabIndex = 0;
this.label2.Text = "Destination file name";
//
// tbDestinationFilename
//
this.tbDestinationFilename.Location = new System.Drawing.Point(152, 26);
this.tbDestinationFilename.Name = "tbDestinationFilename";
this.tbDestinationFilename.Size = new System.Drawing.Size(392, 20);
this.tbDestinationFilename.TabIndex = 1;
this.cfTooltip.SetToolTip(this.tbDestinationFilename, "Please enter the name of .NET proxy file that gets generated.");
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 52);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(118, 16);
this.label1.TabIndex = 2;
this.label1.Text = "Destination namespace";
//
// cbSettings
//
this.cbSettings.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.cbSettings.Location = new System.Drawing.Point(10, 632);
this.cbSettings.Name = "cbSettings";
this.cbSettings.Size = new System.Drawing.Size(128, 23);
this.cbSettings.TabIndex = 3;
this.cbSettings.Text = "Remember settings";
this.cfTooltip.SetToolTip(this.cbSettings, "Save dialog settings for future use.");
this.cbSettings.CheckedChanged += new System.EventHandler(this.cbSettings_CheckedChanged);
//
// pbWscf
//
this.pbWscf.Image = ((System.Drawing.Image)(resources.GetObject("pbWscf.Image")));
this.pbWscf.Location = new System.Drawing.Point(462, 4);
this.pbWscf.Name = "pbWscf";
this.pbWscf.Size = new System.Drawing.Size(104, 32);
this.pbWscf.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pbWscf.TabIndex = 11;
this.pbWscf.TabStop = false;
this.cfTooltip.SetToolTip(this.pbWscf, "http://www.thinktecture.com/");
this.pbWscf.Click += new System.EventHandler(this.pbWscf_Click);
//
// cbAdjustCasing
//
this.cbAdjustCasing.Location = new System.Drawing.Point(16, 76);
this.cbAdjustCasing.Name = "cbAdjustCasing";
this.cbAdjustCasing.Size = new System.Drawing.Size(102, 24);
this.cbAdjustCasing.TabIndex = 2;
this.cbAdjustCasing.Text = "Adjust casing";
this.cfTooltip.SetToolTip(this.cbAdjustCasing, "Ensures that generated .NET types follow the .NET guidelines for casing.");
//
// cbMultipleFiles
//
this.cbMultipleFiles.Location = new System.Drawing.Point(425, 49);
this.cbMultipleFiles.Name = "cbMultipleFiles";
this.cbMultipleFiles.Size = new System.Drawing.Size(96, 24);
this.cbMultipleFiles.TabIndex = 8;
this.cbMultipleFiles.Text = "Separate files";
this.cfTooltip.SetToolTip(this.cbMultipleFiles, "Generates each data type into its own seperate source file.");
//
// cbCollections
//
this.cbCollections.Location = new System.Drawing.Point(299, 23);
this.cbCollections.Name = "cbCollections";
this.cbCollections.Size = new System.Drawing.Size(80, 24);
this.cbCollections.TabIndex = 5;
this.cbCollections.Text = "Collections";
this.cfTooltip.SetToolTip(this.cbCollections, "Generates collection-based members instead of arrays.");
this.cbCollections.CheckedChanged += new System.EventHandler(this.cbCollections_CheckedChanged);
//
// cbFormatSoapActions
//
this.cbFormatSoapActions.Location = new System.Drawing.Point(144, 25);
this.cbFormatSoapActions.Name = "cbFormatSoapActions";
this.cbFormatSoapActions.Size = new System.Drawing.Size(128, 20);
this.cbFormatSoapActions.TabIndex = 3;
this.cbFormatSoapActions.Text = "FormatSoapActions";
this.cfTooltip.SetToolTip(this.cbFormatSoapActions, "Set the Action and ReplyActions according to standards");
//
// cbProperties
//
this.cbProperties.Location = new System.Drawing.Point(16, 24);
this.cbProperties.Name = "cbProperties";
this.cbProperties.Size = new System.Drawing.Size(115, 23);
this.cbProperties.TabIndex = 0;
this.cbProperties.Text = "Public properties";
this.cfTooltip.SetToolTip(this.cbProperties, "Generate public properties in your data classes instead of public fields.");
//
// rbServer
//
this.rbServer.Location = new System.Drawing.Point(148, 19);
this.rbServer.Name = "rbServer";
this.rbServer.Size = new System.Drawing.Size(112, 24);
this.rbServer.TabIndex = 1;
this.rbServer.Text = "Service-side stub";
this.cfTooltip.SetToolTip(this.rbServer, "Select this to generate the service-side stub");
this.rbServer.CheckedChanged += new System.EventHandler(this.rbServer_CheckedChanged);
//
// rbClient
//
this.rbClient.Location = new System.Drawing.Point(17, 19);
this.rbClient.Name = "rbClient";
this.rbClient.Size = new System.Drawing.Size(111, 24);
this.rbClient.TabIndex = 0;
this.rbClient.Text = "Client-side proxy";
this.cfTooltip.SetToolTip(this.rbClient, "Select this to generate the client-side proxy");
this.rbClient.CheckedChanged += new System.EventHandler(this.rbClient_CheckedChanged);
//
// cbOverwrite
//
this.cbOverwrite.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.cbOverwrite.Location = new System.Drawing.Point(136, 631);
this.cbOverwrite.Name = "cbOverwrite";
this.cbOverwrite.Size = new System.Drawing.Size(144, 24);
this.cbOverwrite.TabIndex = 4;
this.cbOverwrite.Text = "Overwrite existing files";
this.cfTooltip.SetToolTip(this.cbOverwrite, "Overwrite all files upon code generation.");
this.cbOverwrite.CheckedChanged += new System.EventHandler(this.cbOverwrite_CheckedChanged);
//
// cbAsync
//
this.cbAsync.AutoSize = true;
this.cbAsync.Location = new System.Drawing.Point(299, 53);
this.cbAsync.Name = "cbAsync";
this.cbAsync.Size = new System.Drawing.Size(98, 17);
this.cbAsync.TabIndex = 6;
this.cbAsync.Text = "Async methods";
this.cfTooltip.SetToolTip(this.cbAsync, "Creates Begin and End methods for the asynchronous invocation of Web Services.");
this.cbAsync.UseVisualStyleBackColor = true;
//
// cbDataBinding
//
this.cbDataBinding.AutoSize = true;
this.cbDataBinding.Location = new System.Drawing.Point(16, 53);
this.cbDataBinding.Name = "cbDataBinding";
this.cbDataBinding.Size = new System.Drawing.Size(86, 17);
this.cbDataBinding.TabIndex = 1;
this.cbDataBinding.Text = "Data binding";
this.cfTooltip.SetToolTip(this.cbDataBinding, "Implement INotifyPropertyChanged interface on all generated types to enable data " +
"binding.");
this.cbDataBinding.UseVisualStyleBackColor = true;
this.cbDataBinding.CheckedChanged += new System.EventHandler(this.cbDataBinding_CheckedChanged);
//
// cbOrderIds
//
this.cbOrderIds.AutoSize = true;
this.cbOrderIds.Location = new System.Drawing.Point(144, 53);
this.cbOrderIds.Name = "cbOrderIds";
this.cbOrderIds.Size = new System.Drawing.Size(99, 17);
this.cbOrderIds.TabIndex = 4;
this.cbOrderIds.Text = "Order identifiers";
this.cfTooltip.SetToolTip(this.cbOrderIds, "Generate explicit order identifiers on particle members.");
this.cbOrderIds.UseVisualStyleBackColor = true;
//
// cbGenericList
//
this.cbGenericList.AutoSize = true;
this.cbGenericList.Location = new System.Drawing.Point(425, 27);
this.cbGenericList.Name = "cbGenericList";
this.cbGenericList.Size = new System.Drawing.Size(61, 17);
this.cbGenericList.TabIndex = 7;
this.cbGenericList.Text = "List<T>";
this.cfTooltip.SetToolTip(this.cbGenericList, "Generates List<T>-based members instead of arrays.");
this.cbGenericList.UseVisualStyleBackColor = true;
this.cbGenericList.CheckedChanged += new System.EventHandler(this.cbGenericList_CheckedChanged);
//
// cbEnableWsdlEndpoint
//
this.cbEnableWsdlEndpoint.Location = new System.Drawing.Point(299, 49);
this.cbEnableWsdlEndpoint.Name = "cbEnableWsdlEndpoint";
this.cbEnableWsdlEndpoint.Size = new System.Drawing.Size(160, 24);
this.cbEnableWsdlEndpoint.TabIndex = 5;
this.cbEnableWsdlEndpoint.Text = "Enable WSDL Endpoint";
this.cfTooltip.SetToolTip(this.cbEnableWsdlEndpoint, "Adds the configuration required to expose the WSDL file as metadata service endpo" +
"int.");
//
// cbUseSynchronizationContext
//
this.cbUseSynchronizationContext.Checked = true;
this.cbUseSynchronizationContext.CheckState = System.Windows.Forms.CheckState.Checked;
this.cbUseSynchronizationContext.Location = new System.Drawing.Point(299, 22);
this.cbUseSynchronizationContext.Name = "cbUseSynchronizationContext";
this.cbUseSynchronizationContext.Size = new System.Drawing.Size(191, 24);
this.cbUseSynchronizationContext.TabIndex = 4;
this.cbUseSynchronizationContext.Text = "Use Synchronization Context ";
this.cfTooltip.SetToolTip(this.cbUseSynchronizationContext, "Specifies whether to use the current synchronization context to choose the thread" +
" of execution. ");
this.cbUseSynchronizationContext.UseVisualStyleBackColor = true;
//
// cbConcurrencyMode
//
this.cbConcurrencyMode.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbConcurrencyMode.FormattingEnabled = true;
this.cbConcurrencyMode.Items.AddRange(new object[] {
"Single",
"Multiple",
"Reentrant"});
this.cbConcurrencyMode.Location = new System.Drawing.Point(139, 24);
this.cbConcurrencyMode.Name = "cbConcurrencyMode";
this.cbConcurrencyMode.Size = new System.Drawing.Size(121, 21);
this.cbConcurrencyMode.TabIndex = 1;
this.cfTooltip.SetToolTip(this.cbConcurrencyMode, "Determines whether a service supports one thread, multiple threads, or reentrant " +
"calls. ");
//
// cbInstanceContextMode
//
this.cbInstanceContextMode.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbInstanceContextMode.FormattingEnabled = true;
this.cbInstanceContextMode.Items.AddRange(new object[] {
"PerCall",
"PerSession",
"Single"});
this.cbInstanceContextMode.Location = new System.Drawing.Point(139, 51);
this.cbInstanceContextMode.Name = "cbInstanceContextMode";
this.cbInstanceContextMode.Size = new System.Drawing.Size(121, 21);
this.cbInstanceContextMode.TabIndex = 3;
this.cfTooltip.SetToolTip(this.cbInstanceContextMode, "Specifies the number of service instances available for handling calls that are c" +
"ontained in incoming messages. ");
//
// cbGenerateSvcFile
//
this.cbGenerateSvcFile.AutoSize = true;
this.cbGenerateSvcFile.Location = new System.Drawing.Point(299, 79);
this.cbGenerateSvcFile.Name = "cbGenerateSvcFile";
this.cbGenerateSvcFile.Size = new System.Drawing.Size(109, 17);
this.cbGenerateSvcFile.TabIndex = 6;
this.cbGenerateSvcFile.Text = "Generate .svc file";
this.cfTooltip.SetToolTip(this.cbGenerateSvcFile, "Determines if a .svc file will be generated for hosting in IIS and WAS.");
this.cbGenerateSvcFile.UseVisualStyleBackColor = true;
//
// panel1
//
this.panel1.BackColor = System.Drawing.Color.White;
this.panel1.Controls.Add(this.pbWscf);
this.panel1.Controls.Add(this.pbWizard);
this.panel1.Location = new System.Drawing.Point(0, 0);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(648, 40);
this.panel1.TabIndex = 10;
//
// pbWizard
//
this.pbWizard.Image = ((System.Drawing.Image)(resources.GetObject("pbWizard.Image")));
this.pbWizard.Location = new System.Drawing.Point(10, 3);
this.pbWizard.Name = "pbWizard";
this.pbWizard.Size = new System.Drawing.Size(40, 32);
this.pbWizard.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pbWizard.TabIndex = 10;
this.pbWizard.TabStop = false;
//
// groupBox5
//
this.groupBox5.Controls.Add(this.cbWsdlLocation);
this.groupBox5.Controls.Add(this.bnBrowse);
this.groupBox5.Controls.Add(this.label4);
this.groupBox5.Location = new System.Drawing.Point(8, 48);
this.groupBox5.Name = "groupBox5";
this.groupBox5.Size = new System.Drawing.Size(553, 49);
this.groupBox5.TabIndex = 0;
this.groupBox5.TabStop = false;
this.groupBox5.Text = "Contract information ";
//
// cbWsdlLocation
//
this.cbWsdlLocation.Enabled = false;
this.cbWsdlLocation.Location = new System.Drawing.Point(96, 18);
this.cbWsdlLocation.MaxDropDownItems = 10;
this.cbWsdlLocation.Name = "cbWsdlLocation";
this.cbWsdlLocation.Size = new System.Drawing.Size(404, 21);
this.cbWsdlLocation.TabIndex = 1;
this.cbWsdlLocation.SelectedIndexChanged += new System.EventHandler(this.cbWsdlLocation_SelectedIndexChanged);
this.cbWsdlLocation.MouseMove += new System.Windows.Forms.MouseEventHandler(this.cbWsdlLocation_MouseMove);
this.cbWsdlLocation.TextChanged += new System.EventHandler(this.tbWSDLLocation_TextChanged);
//
// bnBrowse
//
this.bnBrowse.Location = new System.Drawing.Point(512, 17);
this.bnBrowse.Name = "bnBrowse";
this.bnBrowse.Size = new System.Drawing.Size(32, 23);
this.bnBrowse.TabIndex = 2;
this.bnBrowse.Text = "...";
this.bnBrowse.Click += new System.EventHandler(this.bnBrowse_Click);
//
// label4
//
this.label4.Location = new System.Drawing.Point(8, 21);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(87, 20);
this.label4.TabIndex = 0;
this.label4.Text = "WSDL location:";
//
// openFileDialogWSDL
//
this.openFileDialogWSDL.Filter = "WSDL files|*.wsdl|All Files|*.*";
//
// groupBox1
//
this.groupBox1.Controls.Add(this.gbServiceMethodImplementation);
this.groupBox1.Controls.Add(this.gbServiceBehavior);
this.groupBox1.Controls.Add(this.rbServer);
this.groupBox1.Controls.Add(this.groupBox4);
this.groupBox1.Controls.Add(this.rbClient);
this.groupBox1.Location = new System.Drawing.Point(8, 103);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(553, 279);
this.groupBox1.TabIndex = 1;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Code generation ";
//
// gbServiceBehavior
//
this.gbServiceBehavior.Controls.Add(this.cbGenerateSvcFile);
this.gbServiceBehavior.Controls.Add(this.cbEnableWsdlEndpoint);
this.gbServiceBehavior.Controls.Add(this.cbUseSynchronizationContext);
this.gbServiceBehavior.Controls.Add(this.label3);
this.gbServiceBehavior.Controls.Add(this.label5);
this.gbServiceBehavior.Controls.Add(this.cbConcurrencyMode);
this.gbServiceBehavior.Controls.Add(this.cbInstanceContextMode);
this.gbServiceBehavior.Enabled = false;
this.gbServiceBehavior.Location = new System.Drawing.Point(8, 162);
this.gbServiceBehavior.Name = "gbServiceBehavior";
this.gbServiceBehavior.Size = new System.Drawing.Size(536, 107);
this.gbServiceBehavior.TabIndex = 3;
this.gbServiceBehavior.TabStop = false;
this.gbServiceBehavior.Text = "Service Behavior";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(16, 27);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(97, 13);
this.label3.TabIndex = 0;
this.label3.Text = "Concurrency Mode";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(16, 54);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(117, 13);
this.label5.TabIndex = 2;
this.label5.Text = "Instance Context Mode";
//
// groupBox4
//
this.groupBox4.Controls.Add(this.cbGenericList);
this.groupBox4.Controls.Add(this.cbAsync);
this.groupBox4.Controls.Add(this.cbDataBinding);
this.groupBox4.Controls.Add(this.cbOrderIds);
this.groupBox4.Controls.Add(this.cbCollections);
this.groupBox4.Controls.Add(this.cbMultipleFiles);
this.groupBox4.Controls.Add(this.cbProperties);
this.groupBox4.Controls.Add(this.cbAdjustCasing);
this.groupBox4.Controls.Add(this.cbFormatSoapActions);
this.groupBox4.Location = new System.Drawing.Point(8, 49);
this.groupBox4.Name = "groupBox4";
this.groupBox4.Size = new System.Drawing.Size(536, 107);
this.groupBox4.TabIndex = 2;
this.groupBox4.TabStop = false;
this.groupBox4.Text = "Options ";
//
// gbServiceMethodImplementation
//
this.gbServiceMethodImplementation.Controls.Add(this.rbAbstractMethods);
this.gbServiceMethodImplementation.Controls.Add(this.rbPartialClassMethodCalls);
this.gbServiceMethodImplementation.Controls.Add(this.rbNotImplementedException);
this.gbServiceMethodImplementation.Location = new System.Drawing.Point(15, 385);
this.gbServiceMethodImplementation.Name = "gbServiceMethodImplementation";
this.gbServiceMethodImplementation.Size = new System.Drawing.Size(536, 95);
this.gbServiceMethodImplementation.TabIndex = 11;
this.gbServiceMethodImplementation.TabStop = false;
this.gbServiceMethodImplementation.Text = "Service Method Implementation";
this.cfTooltip.SetToolTip(this.gbServiceMethodImplementation, "Determines if the operation methods on the service class will throw a NotImplemen" +
"tedException, call an implementation method in a partial class, or will be defin" +
"ed as abstract methods.");
//
// rbAbstractMethods
//
this.rbAbstractMethods.AutoSize = true;
this.rbAbstractMethods.Location = new System.Drawing.Point(16, 66);
this.rbAbstractMethods.Name = "rbAbstractMethods";
this.rbAbstractMethods.Size = new System.Drawing.Size(508, 20);
this.rbAbstractMethods.TabIndex = 2;
this.rbAbstractMethods.Text = "Generate an abstract service class and abstract methods that can be implemented i" +
"n a derived class.";
this.rbAbstractMethods.UseVisualStyleBackColor = true;
//
// rbPartialClassMethodCalls
//
this.rbPartialClassMethodCalls.AutoSize = true;
this.rbPartialClassMethodCalls.Location = new System.Drawing.Point(16, 43);
this.rbPartialClassMethodCalls.Name = "rbPartialClassMethodCalls";
this.rbPartialClassMethodCalls.Size = new System.Drawing.Size(504, 20);
this.rbPartialClassMethodCalls.TabIndex = 1;
this.rbPartialClassMethodCalls.Text = "Generate a partial service class with calls to partial methods that must be imple" +
"mented in another file.";
this.rbPartialClassMethodCalls.UseVisualStyleBackColor = true;
//
// rbNotImplementedException
//
this.rbNotImplementedException.AutoSize = true;
this.rbNotImplementedException.Checked = true;
this.rbNotImplementedException.Location = new System.Drawing.Point(16, 20);
this.rbNotImplementedException.Name = "rbNotImplementedException";
this.rbNotImplementedException.Size = new System.Drawing.Size(498, 20);
this.rbNotImplementedException.TabIndex = 0;
this.rbNotImplementedException.TabStop = true;
this.rbNotImplementedException.Text = "Generate a regular service class with methods that throw a NotImplementedExceptio" +
"n in their body.";
this.rbNotImplementedException.UseVisualStyleBackColor = true;
//
// WebServiceCodeGenDialogNew
//
this.AcceptButton = this.btnGenerate;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.btnCancel;
this.ClientSize = new System.Drawing.Size(570, 664);
this.Controls.Add(this.gbServiceMethodImplementation);
this.Controls.Add(this.cbOverwrite);
this.Controls.Add(this.groupBox5);
this.Controls.Add(this.panel1);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnGenerate);
this.Controls.Add(this.cbSettings);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "WebServiceCodeGenDialogNew";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "WSCF.blue Code Generation 1.0 ";
this.Load += new System.EventHandler(this.WebServiceCodeGenOptions_Load);
this.Closed += new System.EventHandler(this.WebServiceCodeGenOptions_Closed);
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pbWscf)).EndInit();
this.panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pbWizard)).EndInit();
this.groupBox5.ResumeLayout(false);
this.groupBox1.ResumeLayout(false);
this.gbServiceBehavior.ResumeLayout(false);
this.gbServiceBehavior.PerformLayout();
this.groupBox4.ResumeLayout(false);
this.groupBox4.PerformLayout();
this.gbServiceMethodImplementation.ResumeLayout(false);
this.gbServiceMethodImplementation.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private void btnGenerate_Click(object sender, EventArgs e)
{
if(rbClient.Checked || rbServer.Checked)
{
HandleClientOrServerGeneration();
}
else
{
this.DialogResult = DialogResult.None;
btnGenerate.DialogResult = DialogResult.None;
DisplayMessage("Please choose code generation options");
}
}
// TODO: These validations should be part of the service which
// returns an appropriate error that is then wrapped in a message box
private bool ValidateWsdlLocation()
{
if (cbWsdlLocation.Text.Length == 0)
{
DisplayMessage("Invalid WSDL Location");
return false;
}
else
{
return true;
}
}
private bool ValidateDestinationNamespace()
{
if(tbDestinationNamespace.Text.Length == 0 ||
!ValidationHelper.IsDotNetNamespace(tbDestinationNamespace.Text))
{
DisplayMessage("Error in destination namespace. Please enter valid values");
return false;
}
else
{
return true;
}
}
private bool ValidateDestinationFileName()
{
if(tbDestinationFilename.Text.Length == 0 ||
!ValidationHelper.IsWindowsFileName(tbDestinationFilename.Text))
{
DisplayMessage("Error in destination file name. Please enter valid file name.");
return false;
}
else
{
return true;
}
}
private void DisplayMessage(string message)
{
MessageBox.Show(message , "Web Services Contract-First code generation",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
private void WebServiceCodeGenOptions_Load(object sender, EventArgs e)
{
if(wsdlLocation.Length == 0)
{
cbWsdlLocation.Enabled = true;
cbWsdlLocation.Focus();
}
if(!cbWsdlLocation.Enabled) bnBrowse.Enabled = false;
cbConcurrencyMode.SelectedIndex = 0;
cbInstanceContextMode.SelectedIndex = 0;
LoadFormValues();
if(rbClient.Checked || rbServer.Checked) btnGenerate.Enabled = true;
isLoading = false;
gbServiceBehavior.DataBindings.Add("Enabled", rbServer, "Checked");
gbServiceMethodImplementation.DataBindings.Add("Enabled", rbServer, "Checked");
}
private void ttPicBox_Click(object sender, EventArgs e)
{
Process.Start("http://www.thinktecture.com/");
}
private void bnBrowse_Click(object sender, EventArgs e)
{
if(openFileDialogWSDL.ShowDialog() == DialogResult.OK)
{
AddWsdlFileToCache(openFileDialogWSDL.FileName);
}
}
private void ttPicBox_MouseEnter(object sender, EventArgs e)
{
Cursor.Current = Cursors.Hand;
}
private void ttPicBox_MouseLeave(object sender, EventArgs e)
{
Cursor.Current = Cursors.Default;
}
private void ttPicBox_MouseMove(object sender, MouseEventArgs e)
{
}
private void tbWSDLLocation_TextChanged(object sender, EventArgs e)
{
}
private void WebServiceCodeGenOptions_Closed(object sender, EventArgs e)
{
// BDS: Save the values only if the OK button is clicked.
if(this.DialogResult == DialogResult.OK)
{
SaveFormValues();
}
}
private void cbWsdlLocation_SelectedIndexChanged(object sender, System.EventArgs e)
{
}
/// <summary>
/// Disply the location of the WSDL when moving the mouse over the combo box.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">Event arguments.</param>
private void cbWsdlLocation_MouseMove(object sender, MouseEventArgs e)
{
if(cbWsdlLocation.SelectedIndex >= 0)
{
cfTooltip.SetToolTip(cbWsdlLocation,
wsdlFileCache[cbWsdlLocation.SelectedIndex].ToString());
}
}
private void cbOverwrite_CheckedChanged(object sender, System.EventArgs e)
{
if (!isLoading)
{
if (cbOverwrite.Checked)
{
if (MessageBox.Show(this,
"This will overwrite the existing files in the project. Are you sure you want to enable this option anyway?",
"Web Services Contract-First code generation",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.No)
{
cbOverwrite.Checked = false;
}
}
}
}
private void pbWscf_Click(object sender, System.EventArgs e)
{
Process.Start("http://www.thinktecture.com/");
}
private void cbDataBinding_CheckedChanged(object sender, EventArgs e)
{
if (!cbProperties.Checked)
{
cbProperties.Checked = true;
cbProperties.CheckState = CheckState.Indeterminate;
cbProperties.Enabled = false;
}
else
{
if (cbProperties.Checked &&
cbProperties.CheckState == CheckState.Indeterminate)
{
cbProperties.Checked = false;
}
cbProperties.Enabled = true;
}
}
private void cbSettings_CheckedChanged(object sender, EventArgs e)
{
}
private void cbCollections_CheckedChanged(object sender, EventArgs e)
{
if (cbGenericList.Checked)
{
cbGenericList.Checked = !cbCollections.Checked;
}
}
private void cbGenericList_CheckedChanged(object sender, EventArgs e)
{
if (cbCollections.Checked)
{
cbCollections.Checked = !cbGenericList.Checked;
}
}
private void rbClient_CheckedChanged(object sender, EventArgs e)
{
btnGenerate.Enabled = true;
}
private void rbServer_CheckedChanged(object sender, EventArgs e)
{
btnGenerate.Enabled = true;
}
}
}
| |
#region Disclaimer/Info
///////////////////////////////////////////////////////////////////////////////////////////////////
// Subtext WebLog
//
// Subtext is an open source weblog system that is a fork of the .TEXT
// weblog system.
//
// For updated news and information please visit http://subtextproject.com/
// Subtext is hosted at Google Code at http://code.google.com/p/subtext/
// The development mailing list is at [email protected]
//
// This project is licensed under the BSD license. See the License.txt file for more information.
///////////////////////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using Subtext.Framework.Configuration;
using Subtext.Framework.Exceptions;
using Subtext.Framework.Properties;
using Subtext.Framework.Providers;
using Subtext.Framework.Security;
using Subtext.Framework.Services;
namespace Subtext.Framework
{
/// <summary>
/// Represents the system, and its settings, that hosts the blogs within this Subtext installation.
/// </summary>
public class HostInfo
{
private static LazyNotNull<HostInfo> _instance = new LazyNotNull<HostInfo>(EnsureHostInfo);
public HostInfo(NameValueCollection appSettings)
{
BlogAggregationEnabled =
String.Equals(appSettings["AggregateEnabled"], "true",
StringComparison.OrdinalIgnoreCase);
if (BlogAggregationEnabled)
{
Initialize();
}
}
public static HostInfo Instance
{
get
{
return _instance.Value;
}
}
private static HostInfo EnsureHostInfo()
{
var repository = DependencyResolver.Current.GetService<ObjectRepository>();
var hostInfo = LoadHostInfoFromDatabase(repository, suppressException: true);
return hostInfo;
}
public static HostInfo LoadHostInfoFromDatabase(ObjectRepository repository, bool suppressException)
{
try
{
return repository.LoadHostInfo(new HostInfo(ConfigurationManager.AppSettings));
}
catch (SqlException e)
{
// LoadHostInfo now executes the stored proc subtext_GetHost, instead of checking the table subtext_Host
if (e.Message.IndexOf("Invalid object name 'subtext_Host'") >= 0
|| e.Message.IndexOf("Could not find stored procedure 'subtext_GetHost'") >= 0)
{
if (suppressException)
{
return null;
}
throw new HostDataDoesNotExistException();
}
throw;
}
}
/// <summary>
/// Gets or sets the name of the host user.
/// </summary>
/// <value></value>
public virtual string HostUserName { get; set; }
public string Email { get; set; }
/// <summary>
/// Gets or sets the host password.
/// </summary>
/// <value></value>
public string Password { get; set; }
/// <summary>
/// Gets or sets the salt.
/// </summary>
/// <value></value>
public string Salt { get; set; }
/// <summary>
/// Gets or sets the date this record was created.
/// This is essentially the date that Subtext was
/// installed.
/// </summary>
/// <value></value>
public DateTime DateCreatedUtc { get; set; }
public bool BlogAggregationEnabled { get; private set; }
public Blog AggregateBlog { get; set; }
/// <summary>
/// Updates the host in the persistent store.
/// </summary>
/// <param name="host">Host.</param>
/// <returns></returns>
public static bool UpdateHost(ObjectRepository repository, HostInfo host)
{
if (repository.UpdateHost(host))
{
return true;
}
return false;
}
/// <summary>
/// Creates the host in the persistent store.
/// </summary>
/// <returns></returns>
public static bool CreateHost(ObjectRepository repository, string hostUserName, string hostPassword, string email)
{
if (_instance.Value != null)
{
throw new InvalidOperationException(Resources.InvalidOperation_HostRecordAlreadyExists);
}
var host = new HostInfo(ConfigurationManager.AppSettings) { HostUserName = hostUserName, Email = email };
SetHostPassword(host, hostPassword);
return repository.UpdateHost(host);
}
public static void SetHostPassword(HostInfo host, string newPassword)
{
host.Salt = SecurityHelper.CreateRandomSalt();
if (Config.Settings.UseHashedPasswords)
{
string hashedPassword = SecurityHelper.HashPassword(newPassword, host.Salt);
host.Password = hashedPassword;
}
else
{
host.Password = newPassword;
}
}
private void Initialize()
{
string aggregateHost = ConfigurationManager.AppSettings["AggregateUrl"];
if (aggregateHost == null)
{
return;
}
// validate host.
var regex = new Regex(@"^(https?://)?(?<host>.+?)(/.*)?$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
Match match = regex.Match(aggregateHost);
if (match.Success)
{
aggregateHost = match.Groups["host"].Value;
}
var blog = new Blog(true /*isAggregateBlog*/)
{
Title = ConfigurationManager.AppSettings["AggregateTitle"],
Skin = GetAggregateSkin(),
Host = aggregateHost,
Subfolder = string.Empty,
IsActive = true
};
//TODO: blog.MobileSkin = ...
blog.UserName = HostUserName;
AggregateBlog = blog;
}
public static SkinConfig GetAggregateSkin()
{
string aggregateSkin = ConfigurationManager.AppSettings["AggregateSkin"] as string;
if (String.IsNullOrEmpty(aggregateSkin))
{
aggregateSkin = "Aggregate/Simple";
}
return new SkinConfig { TemplateFolder = aggregateSkin };
}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// 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.Linq;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Gallio.Model;
using Gallio.Runner.Reports;
using Gallio.Tests;
using Gallio.Tests.Integration;
using MbUnit.Framework;
using MbUnit.Framework.ContractVerifiers;
namespace MbUnit.Tests.Framework.ContractVerifiers
{
[TestFixture]
[TestsOn(typeof(ComparisonContract<>))]
[RunSample(typeof(FullContractOnComparableSample))]
[RunSample(typeof(PartialContractOnComparableSample))]
[RunSample(typeof(PartialContractOnInterfaceComparableSample))]
[RunSample(typeof(PartialContractInheritedComparableSample))]
[RunSample(typeof(PartialContractUnrelatedComparableSample))]
public class ComparisonContractTest : AbstractContractTest
{
[Test]
[Row(typeof(FullContractOnComparableSample), "ComparableCompareTo", TestStatus.Passed)]
[Row(typeof(FullContractOnComparableSample), "OperatorGreaterThan", TestStatus.Passed)]
[Row(typeof(FullContractOnComparableSample), "OperatorGreaterThanOrEqual", TestStatus.Passed)]
[Row(typeof(FullContractOnComparableSample), "OperatorLessThan", TestStatus.Passed)]
[Row(typeof(FullContractOnComparableSample), "OperatorLessThanOrEqual", TestStatus.Passed)]
[Row(typeof(PartialContractOnComparableSample), "ComparableCompareTo", TestStatus.Passed)]
[Row(typeof(PartialContractOnComparableSample), "OperatorGreaterThan", TestStatus.Inconclusive)]
[Row(typeof(PartialContractOnComparableSample), "OperatorGreaterThanOrEqual", TestStatus.Inconclusive)]
[Row(typeof(PartialContractOnComparableSample), "OperatorLessThan", TestStatus.Inconclusive)]
[Row(typeof(PartialContractOnComparableSample), "OperatorLessThanOrEqual", TestStatus.Inconclusive)]
[Row(typeof(PartialContractOnInterfaceComparableSample), "ComparableCompareTo_ISampleComparable", TestStatus.Passed)]
[Row(typeof(PartialContractOnInterfaceComparableSample), "ComparableCompareTo_SampleParentComparable", TestStatus.Passed)]
[Row(typeof(PartialContractOnInterfaceComparableSample), "OperatorGreaterThan", TestStatus.Inconclusive)]
[Row(typeof(PartialContractOnInterfaceComparableSample), "OperatorGreaterThanOrEqual", TestStatus.Inconclusive)]
[Row(typeof(PartialContractOnInterfaceComparableSample), "OperatorLessThan", TestStatus.Inconclusive)]
[Row(typeof(PartialContractOnInterfaceComparableSample), "OperatorLessThanOrEqual", TestStatus.Inconclusive)]
[Row(typeof(PartialContractInheritedComparableSample), "ComparableCompareTo_ISampleComparable", TestStatus.Passed)]
[Row(typeof(PartialContractInheritedComparableSample), "ComparableCompareTo_SampleParentComparable", TestStatus.Passed)]
[Row(typeof(PartialContractInheritedComparableSample), "ComparableCompareTo_SampleChildComparable", TestStatus.Passed)]
[Row(typeof(PartialContractInheritedComparableSample), "OperatorGreaterThan", TestStatus.Inconclusive)]
[Row(typeof(PartialContractInheritedComparableSample), "OperatorGreaterThanOrEqual", TestStatus.Inconclusive)]
[Row(typeof(PartialContractInheritedComparableSample), "OperatorLessThan", TestStatus.Inconclusive)]
[Row(typeof(PartialContractInheritedComparableSample), "OperatorLessThanOrEqual", TestStatus.Inconclusive)]
[Row(typeof(PartialContractUnrelatedComparableSample), "ComparableCompareTo_SampleUnrelatedComparable", TestStatus.Passed)]
[Row(typeof(PartialContractUnrelatedComparableSample), "ComparableCompareTo_Int32", TestStatus.Passed)]
[Row(typeof(PartialContractUnrelatedComparableSample), "ComparableCompareTo_String", TestStatus.Passed)]
[Row(typeof(PartialContractUnrelatedComparableSample), "OperatorGreaterThan", TestStatus.Inconclusive)]
[Row(typeof(PartialContractUnrelatedComparableSample), "OperatorGreaterThanOrEqual", TestStatus.Inconclusive)]
[Row(typeof(PartialContractUnrelatedComparableSample), "OperatorLessThan", TestStatus.Inconclusive)]
[Row(typeof(PartialContractUnrelatedComparableSample), "OperatorLessThanOrEqual", TestStatus.Inconclusive)]
public void VerifySampleEqualityContract(Type fixtureType, string testMethodName, TestStatus expectedTestStatus)
{
VerifySampleContract("ComparisonTests", fixtureType, testMethodName, expectedTestStatus);
}
[TestFixture, Explicit("Sample")]
private class FullContractOnComparableSample
{
[VerifyContract]
public readonly IContract ComparisonTests = new ComparisonContract<SampleComparable>
{
ImplementsOperatorOverloads = true,
EquivalenceClasses =
{
{ new SampleComparable(123), new SampleComparable(123), new SampleComparable(123) },
{ new SampleComparable(456) },
{ new SampleComparable(789), new SampleComparable(789) },
}
};
}
[TestFixture, Explicit("Sample")]
private class PartialContractOnComparableSample
{
[VerifyContract]
public readonly IContract ComparisonTests = new ComparisonContract<SampleComparable>
{
ImplementsOperatorOverloads = false,
EquivalenceClasses =
{
{ new SampleComparable(123), new SampleComparable(123), new SampleComparable(123) },
{ new SampleComparable(456) },
{ new SampleComparable(789), new SampleComparable(789) },
}
};
}
[TestFixture, Explicit("Sample")]
private class PartialContractOnInterfaceComparableSample
{
[VerifyContract]
public readonly IContract ComparisonTests = new ComparisonContract<ISampleComparable>
{
ImplementsOperatorOverloads = false,
EquivalenceClasses =
{
{ new SampleParentComparable(123) },
{ new SampleParentComparable(456) },
{ new SampleParentComparable(789) },
}
};
}
[TestFixture, Explicit("Sample")]
private class PartialContractInheritedComparableSample
{
[VerifyContract]
public readonly IContract ComparisonTests = new ComparisonContract<SampleParentComparable>
{
ImplementsOperatorOverloads = false,
EquivalenceClasses =
{
{ new SampleParentComparable(123), new SampleChildComparable(123) },
{ new SampleChildComparable(456) },
{ new SampleParentComparable(789) },
}
};
}
[TestFixture, Explicit("Sample")]
private class PartialContractUnrelatedComparableSample
{
[VerifyContract]
public readonly IContract ComparisonTests = new ComparisonContract<SampleUnrelatedComparable>
{
ImplementsOperatorOverloads = false,
EquivalenceClasses =
{
{ new SampleUnrelatedComparable(123), 123, "123", " 123 " },
{ new SampleUnrelatedComparable(456), 456, "456", " 456 " },
{ new SampleUnrelatedComparable(789), 789, "789", " 789 " },
}
};
}
#region Samples
private class SampleComparable : IComparable<SampleComparable>
{
private int value;
public int Value
{
get { return value; }
}
public SampleComparable(int value)
{
this.value = value;
}
public int CompareTo(SampleComparable other)
{
return (other == null) ? Int32.MaxValue : value.CompareTo(other.value);
}
public static bool operator >=(SampleComparable left, SampleComparable right)
{
return ((left == null) && (right == null)) || ((left != null) && (left.CompareTo(right) >= 0));
}
public static bool operator <=(SampleComparable left, SampleComparable right)
{
return (left == null) || (left.CompareTo(right) <= 0);
}
public static bool operator >(SampleComparable left, SampleComparable right)
{
return (left != null) && (left.CompareTo(right) > 0);
}
public static bool operator <(SampleComparable left, SampleComparable right)
{
return ((left != null) || (right != null)) && ((left == null) || (left.CompareTo(right) < 0));
}
}
private interface ISampleComparable : IComparable<ISampleComparable>
{
}
private class SampleParentComparable : ISampleComparable, IComparable<SampleParentComparable>
{
private int value;
public int Value
{
get { return value; }
}
public SampleParentComparable(int value)
{
this.value = value;
}
public int CompareTo(SampleParentComparable other)
{
return (other == null) ? Int32.MaxValue : value.CompareTo(other.Value);
}
int IComparable<ISampleComparable>.CompareTo(ISampleComparable other)
{
return CompareTo(other as SampleParentComparable);
}
}
private class SampleChildComparable : SampleParentComparable, IComparable<SampleChildComparable>
{
public SampleChildComparable(int value)
: base(value)
{
}
public int CompareTo(SampleChildComparable other)
{
return base.CompareTo(other);
}
}
private class SampleUnrelatedComparable : IComparable<SampleUnrelatedComparable>, IComparable<int>, IComparable<string>
{
private int value;
public int Value
{
get { return value; }
}
public SampleUnrelatedComparable(int value)
{
this.value = value;
}
public int CompareTo(SampleUnrelatedComparable other)
{
return (other == null) ? Int32.MaxValue : CompareTo(other.value);
}
public int CompareTo(int other)
{
return value.CompareTo(other);
}
public int CompareTo(string other)
{
return (other == null) ? Int32.MaxValue : CompareTo(Int32.Parse(other.Trim()));
}
}
#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.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Threading;
namespace LayoutTransitionsDemo
{
public class LayoutToLayoutHost : Border
{
public static readonly DependencyProperty TargetProperty =
DependencyProperty.Register("Target", typeof (LayoutToLayoutTarget), typeof (LayoutToLayoutHost), null);
//Animation duration
private readonly int _timeSpan = 500;
//Is this a fade-out animation?
private bool _disappearOnCompletion;
//This keeps track of time for when all the animations finish
private DispatcherTimer _refresher;
//This is kept as a member object so that local animations can affect it
private TranslateTransform _translation;
//Should I animate my way to future layout changes?
public bool AnimateChanges;
//Am I currently in the middle of an animation?
public bool Animating;
public LayoutToLayoutHost()
{
Loaded += OnLoad;
}
public LayoutToLayoutTarget Target
{
get { return (LayoutToLayoutTarget) GetValue(TargetProperty); }
set { SetValue(TargetProperty, value); }
}
private void OnLoad(object sender, RoutedEventArgs e)
{
if (Target != null)
{
Debug.WriteLine("Binding Target!!!");
BindToTarget(Target);
}
else
Debug.WriteLine("Target was NULL!");
Unloaded += OnUnload; //this gets done here rather in the ctor to avoid a frame bug (Windows OS 1224171)
}
/*
* If the host gets unloaded, break the cyclical reference to make sure the GC does its job
* */
private void OnUnload(object sender, RoutedEventArgs e)
{
Target.Host = null;
Target = null;
}
/*
* Link up the Host to the Target and initialize but do not start the timer
* */
public void BindToTarget(LayoutToLayoutTarget t)
{
Target = t;
t.Host = this;
_translation = new TranslateTransform(0, 0);
RenderTransform = _translation;
_refresher = new DispatcherTimer {Interval = TimeSpan.FromMilliseconds(_timeSpan)};
_refresher.Tick += OnAnimStateInvalidated;
UpdateFromTarget();
}
/*
* Start a new animation
* */
public void BeginAnimating(bool disappear)
{
if (Animating)
{
EndAnimations();
//numActive -= 4;
}
Animating = false;
AnimateChanges = true;
_disappearOnCompletion = disappear;
if (Visibility != Visibility.Visible)
{
Visibility = Visibility.Visible;
Opacity = 0.0;
}
}
/*
* Do an immediate update, as long as there is not an animation running
* */
public void UpdateFromTarget()
{
if ((Target == null) || Animating)
return;
if (AnimateChanges)
AnimateFromTarget();
else
MatchLayout();
}
/*
* The double-check might not be necessary anymore, but this fixed a layout infinite loop
* */
private void MatchLayout()
{
if (Width != Target.ActualWidth)
Width = Target.ActualWidth;
if (Height != Target.ActualHeight)
Height = Target.ActualHeight;
var pt = Target.TranslatePoint(new Point(0, 0), Parent as UIElement);
var t = RenderTransform as TranslateTransform;
if (Math.Abs(t.X - pt.X) > 1)
t.X = pt.X;
if (Math.Abs(t.Y - pt.Y) > 1)
t.Y = pt.Y;
}
/*
* Make a local animation for each animated property
* Base the destination on the new layout position of the target
* */
private void AnimateFromTarget()
{
var time = _timeSpan;
Animating = true;
AnimateChanges = false;
var pt = Target.TranslatePoint(new Point(0, 0), Parent as UIElement);
var t = RenderTransform as TranslateTransform;
BeginAnimation(WidthProperty, SetupDoubleAnimation(Width, Target.ActualWidth, time));
BeginAnimation(HeightProperty, SetupDoubleAnimation(Height, Target.ActualHeight, time));
_translation.BeginAnimation(TranslateTransform.XProperty, SetupDoubleAnimation(t.X, pt.X, time));
_translation.BeginAnimation(TranslateTransform.YProperty, SetupDoubleAnimation(t.Y, pt.Y, time));
BeginAnimation(OpacityProperty,
_disappearOnCompletion
? SetupDoubleAnimation(Opacity, 0.0, time)
: SetupDoubleAnimation(Opacity, 1.0, time));
_refresher.IsEnabled = false; //this restarts the timer
_refresher.IsEnabled = true;
_refresher.Start();
}
/*
* This gets called by the DispatcherTimer Refresher when it is done
* */
private void OnAnimStateInvalidated(object sender, EventArgs e)
{
Animating = false;
_refresher.IsEnabled = false;
_refresher.Stop();
EndAnimations();
if (_disappearOnCompletion)
Visibility = Visibility.Hidden;
}
/*
* Explicitly replace all of the local animations will null
* */
public void EndAnimations()
{
var xBuffer = _translation.X;
var yBuffer = _translation.Y;
var widthBuffer = Width;
var heightBuffer = Height;
var opacityBuffer = Opacity;
BeginAnimation(WidthProperty, null);
BeginAnimation(HeightProperty, null);
_translation.BeginAnimation(TranslateTransform.XProperty, null);
_translation.BeginAnimation(TranslateTransform.YProperty, null);
BeginAnimation(OpacityProperty, null);
_translation.X = xBuffer;
_translation.Y = yBuffer;
Height = heightBuffer;
Width = widthBuffer;
Opacity = opacityBuffer;
}
/*
* Helper function to create a DoubleAnimation
* */
public DoubleAnimation SetupDoubleAnimation(double @from, double to, int time)
{
var myDoubleAnimation = new DoubleAnimation
{
From = @from,
To = to,
Duration = new Duration(TimeSpan.FromMilliseconds(time)),
AutoReverse = false
};
return myDoubleAnimation;
}
/*
* Break the cyclical reference
* */
public void ReleaseFromTarget()
{
Target.Host = null;
Target = 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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Drawing
{
public partial struct Color : System.IEquatable<System.Drawing.Color>
{
public static readonly System.Drawing.Color Empty;
public byte A { get { throw null; } }
public static System.Drawing.Color AliceBlue { get { throw null; } }
public static System.Drawing.Color AntiqueWhite { get { throw null; } }
public static System.Drawing.Color Aqua { get { throw null; } }
public static System.Drawing.Color Aquamarine { get { throw null; } }
public static System.Drawing.Color Azure { get { throw null; } }
public byte B { get { throw null; } }
public static System.Drawing.Color Beige { get { throw null; } }
public static System.Drawing.Color Bisque { get { throw null; } }
public static System.Drawing.Color Black { get { throw null; } }
public static System.Drawing.Color BlanchedAlmond { get { throw null; } }
public static System.Drawing.Color Blue { get { throw null; } }
public static System.Drawing.Color BlueViolet { get { throw null; } }
public static System.Drawing.Color Brown { get { throw null; } }
public static System.Drawing.Color BurlyWood { get { throw null; } }
public static System.Drawing.Color CadetBlue { get { throw null; } }
public static System.Drawing.Color Chartreuse { get { throw null; } }
public static System.Drawing.Color Chocolate { get { throw null; } }
public static System.Drawing.Color Coral { get { throw null; } }
public static System.Drawing.Color CornflowerBlue { get { throw null; } }
public static System.Drawing.Color Cornsilk { get { throw null; } }
public static System.Drawing.Color Crimson { get { throw null; } }
public static System.Drawing.Color Cyan { get { throw null; } }
public static System.Drawing.Color DarkBlue { get { throw null; } }
public static System.Drawing.Color DarkCyan { get { throw null; } }
public static System.Drawing.Color DarkGoldenrod { get { throw null; } }
public static System.Drawing.Color DarkGray { get { throw null; } }
public static System.Drawing.Color DarkGreen { get { throw null; } }
public static System.Drawing.Color DarkKhaki { get { throw null; } }
public static System.Drawing.Color DarkMagenta { get { throw null; } }
public static System.Drawing.Color DarkOliveGreen { get { throw null; } }
public static System.Drawing.Color DarkOrange { get { throw null; } }
public static System.Drawing.Color DarkOrchid { get { throw null; } }
public static System.Drawing.Color DarkRed { get { throw null; } }
public static System.Drawing.Color DarkSalmon { get { throw null; } }
public static System.Drawing.Color DarkSeaGreen { get { throw null; } }
public static System.Drawing.Color DarkSlateBlue { get { throw null; } }
public static System.Drawing.Color DarkSlateGray { get { throw null; } }
public static System.Drawing.Color DarkTurquoise { get { throw null; } }
public static System.Drawing.Color DarkViolet { get { throw null; } }
public static System.Drawing.Color DeepPink { get { throw null; } }
public static System.Drawing.Color DeepSkyBlue { get { throw null; } }
public static System.Drawing.Color DimGray { get { throw null; } }
public static System.Drawing.Color DodgerBlue { get { throw null; } }
public static System.Drawing.Color Firebrick { get { throw null; } }
public static System.Drawing.Color FloralWhite { get { throw null; } }
public static System.Drawing.Color ForestGreen { get { throw null; } }
public static System.Drawing.Color Fuchsia { get { throw null; } }
public byte G { get { throw null; } }
public static System.Drawing.Color Gainsboro { get { throw null; } }
public static System.Drawing.Color GhostWhite { get { throw null; } }
public static System.Drawing.Color Gold { get { throw null; } }
public static System.Drawing.Color Goldenrod { get { throw null; } }
public static System.Drawing.Color Gray { get { throw null; } }
public static System.Drawing.Color Green { get { throw null; } }
public static System.Drawing.Color GreenYellow { get { throw null; } }
public static System.Drawing.Color Honeydew { get { throw null; } }
public static System.Drawing.Color HotPink { get { throw null; } }
public static System.Drawing.Color IndianRed { get { throw null; } }
public static System.Drawing.Color Indigo { get { throw null; } }
public bool IsEmpty { get { throw null; } }
public bool IsNamedColor { get { throw null; } }
public static System.Drawing.Color Ivory { get { throw null; } }
public static System.Drawing.Color Khaki { get { throw null; } }
public static System.Drawing.Color Lavender { get { throw null; } }
public static System.Drawing.Color LavenderBlush { get { throw null; } }
public static System.Drawing.Color LawnGreen { get { throw null; } }
public static System.Drawing.Color LemonChiffon { get { throw null; } }
public static System.Drawing.Color LightBlue { get { throw null; } }
public static System.Drawing.Color LightCoral { get { throw null; } }
public static System.Drawing.Color LightCyan { get { throw null; } }
public static System.Drawing.Color LightGoldenrodYellow { get { throw null; } }
public static System.Drawing.Color LightGray { get { throw null; } }
public static System.Drawing.Color LightGreen { get { throw null; } }
public static System.Drawing.Color LightPink { get { throw null; } }
public static System.Drawing.Color LightSalmon { get { throw null; } }
public static System.Drawing.Color LightSeaGreen { get { throw null; } }
public static System.Drawing.Color LightSkyBlue { get { throw null; } }
public static System.Drawing.Color LightSlateGray { get { throw null; } }
public static System.Drawing.Color LightSteelBlue { get { throw null; } }
public static System.Drawing.Color LightYellow { get { throw null; } }
public static System.Drawing.Color Lime { get { throw null; } }
public static System.Drawing.Color LimeGreen { get { throw null; } }
public static System.Drawing.Color Linen { get { throw null; } }
public static System.Drawing.Color Magenta { get { throw null; } }
public static System.Drawing.Color Maroon { get { throw null; } }
public static System.Drawing.Color MediumAquamarine { get { throw null; } }
public static System.Drawing.Color MediumBlue { get { throw null; } }
public static System.Drawing.Color MediumOrchid { get { throw null; } }
public static System.Drawing.Color MediumPurple { get { throw null; } }
public static System.Drawing.Color MediumSeaGreen { get { throw null; } }
public static System.Drawing.Color MediumSlateBlue { get { throw null; } }
public static System.Drawing.Color MediumSpringGreen { get { throw null; } }
public static System.Drawing.Color MediumTurquoise { get { throw null; } }
public static System.Drawing.Color MediumVioletRed { get { throw null; } }
public static System.Drawing.Color MidnightBlue { get { throw null; } }
public static System.Drawing.Color MintCream { get { throw null; } }
public static System.Drawing.Color MistyRose { get { throw null; } }
public static System.Drawing.Color Moccasin { get { throw null; } }
public string Name { get { throw null; } }
public static System.Drawing.Color NavajoWhite { get { throw null; } }
public static System.Drawing.Color Navy { get { throw null; } }
public static System.Drawing.Color OldLace { get { throw null; } }
public static System.Drawing.Color Olive { get { throw null; } }
public static System.Drawing.Color OliveDrab { get { throw null; } }
public static System.Drawing.Color Orange { get { throw null; } }
public static System.Drawing.Color OrangeRed { get { throw null; } }
public static System.Drawing.Color Orchid { get { throw null; } }
public static System.Drawing.Color PaleGoldenrod { get { throw null; } }
public static System.Drawing.Color PaleGreen { get { throw null; } }
public static System.Drawing.Color PaleTurquoise { get { throw null; } }
public static System.Drawing.Color PaleVioletRed { get { throw null; } }
public static System.Drawing.Color PapayaWhip { get { throw null; } }
public static System.Drawing.Color PeachPuff { get { throw null; } }
public static System.Drawing.Color Peru { get { throw null; } }
public static System.Drawing.Color Pink { get { throw null; } }
public static System.Drawing.Color Plum { get { throw null; } }
public static System.Drawing.Color PowderBlue { get { throw null; } }
public static System.Drawing.Color Purple { get { throw null; } }
public byte R { get { throw null; } }
public static System.Drawing.Color Red { get { throw null; } }
public static System.Drawing.Color RosyBrown { get { throw null; } }
public static System.Drawing.Color RoyalBlue { get { throw null; } }
public static System.Drawing.Color SaddleBrown { get { throw null; } }
public static System.Drawing.Color Salmon { get { throw null; } }
public static System.Drawing.Color SandyBrown { get { throw null; } }
public static System.Drawing.Color SeaGreen { get { throw null; } }
public static System.Drawing.Color SeaShell { get { throw null; } }
public static System.Drawing.Color Sienna { get { throw null; } }
public static System.Drawing.Color Silver { get { throw null; } }
public static System.Drawing.Color SkyBlue { get { throw null; } }
public static System.Drawing.Color SlateBlue { get { throw null; } }
public static System.Drawing.Color SlateGray { get { throw null; } }
public static System.Drawing.Color Snow { get { throw null; } }
public static System.Drawing.Color SpringGreen { get { throw null; } }
public static System.Drawing.Color SteelBlue { get { throw null; } }
public static System.Drawing.Color Tan { get { throw null; } }
public static System.Drawing.Color Teal { get { throw null; } }
public static System.Drawing.Color Thistle { get { throw null; } }
public static System.Drawing.Color Tomato { get { throw null; } }
public static System.Drawing.Color Transparent { get { throw null; } }
public static System.Drawing.Color Turquoise { get { throw null; } }
public static System.Drawing.Color Violet { get { throw null; } }
public static System.Drawing.Color Wheat { get { throw null; } }
public static System.Drawing.Color White { get { throw null; } }
public static System.Drawing.Color WhiteSmoke { get { throw null; } }
public static System.Drawing.Color Yellow { get { throw null; } }
public static System.Drawing.Color YellowGreen { get { throw null; } }
public bool Equals(System.Drawing.Color other) { throw null; }
public override bool Equals(object obj) { throw null; }
public static System.Drawing.Color FromArgb(int argb) { throw null; }
public static System.Drawing.Color FromArgb(int alpha, System.Drawing.Color baseColor) { throw null; }
public static System.Drawing.Color FromArgb(int red, int green, int blue) { throw null; }
public static System.Drawing.Color FromArgb(int alpha, int red, int green, int blue) { throw null; }
public static System.Drawing.Color FromName(string name) { throw null; }
public float GetBrightness() { throw null; }
public override int GetHashCode() { throw null; }
public float GetHue() { throw null; }
public float GetSaturation() { throw null; }
public static bool operator ==(System.Drawing.Color left, System.Drawing.Color right) { throw null; }
public static bool operator !=(System.Drawing.Color left, System.Drawing.Color right) { throw null; }
public int ToArgb() { throw null; }
public override string ToString() { throw null; }
}
public partial struct Point : System.IEquatable<System.Drawing.Point>
{
public static readonly System.Drawing.Point Empty;
public Point(System.Drawing.Size sz) { throw null; }
public Point(int dw) { throw null; }
public Point(int x, int y) { throw null; }
[System.ComponentModel.Browsable(false)]
public bool IsEmpty { get { throw null; } }
public int X { get { throw null; } set { } }
public int Y { get { throw null; } set { } }
public static System.Drawing.Point Add(System.Drawing.Point pt, System.Drawing.Size sz) { throw null; }
public static System.Drawing.Point Ceiling(System.Drawing.PointF value) { throw null; }
public bool Equals(System.Drawing.Point other) { throw null; }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public void Offset(System.Drawing.Point p) { }
public void Offset(int dx, int dy) { }
public static System.Drawing.Point operator +(System.Drawing.Point pt, System.Drawing.Size sz) { throw null; }
public static bool operator ==(System.Drawing.Point left, System.Drawing.Point right) { throw null; }
public static explicit operator System.Drawing.Size (System.Drawing.Point p) { throw null; }
public static implicit operator System.Drawing.PointF (System.Drawing.Point p) { throw null; }
public static bool operator !=(System.Drawing.Point left, System.Drawing.Point right) { throw null; }
public static System.Drawing.Point operator -(System.Drawing.Point pt, System.Drawing.Size sz) { throw null; }
public static System.Drawing.Point Round(System.Drawing.PointF value) { throw null; }
public static System.Drawing.Point Subtract(System.Drawing.Point pt, System.Drawing.Size sz) { throw null; }
public override string ToString() { throw null; }
public static System.Drawing.Point Truncate(System.Drawing.PointF value) { throw null; }
}
public partial struct PointF : System.IEquatable<System.Drawing.PointF>
{
public static readonly System.Drawing.PointF Empty;
public PointF(float x, float y) { throw null; }
[System.ComponentModel.Browsable(false)]
public bool IsEmpty { get { throw null; } }
public float X { get { throw null; } set { } }
public float Y { get { throw null; } set { } }
public static System.Drawing.PointF Add(System.Drawing.PointF pt, System.Drawing.Size sz) { throw null; }
public static System.Drawing.PointF Add(System.Drawing.PointF pt, System.Drawing.SizeF sz) { throw null; }
public bool Equals(System.Drawing.PointF other) { throw null; }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Drawing.PointF operator +(System.Drawing.PointF pt, System.Drawing.Size sz) { throw null; }
public static System.Drawing.PointF operator +(System.Drawing.PointF pt, System.Drawing.SizeF sz) { throw null; }
public static bool operator ==(System.Drawing.PointF left, System.Drawing.PointF right) { throw null; }
public static bool operator !=(System.Drawing.PointF left, System.Drawing.PointF right) { throw null; }
public static System.Drawing.PointF operator -(System.Drawing.PointF pt, System.Drawing.Size sz) { throw null; }
public static System.Drawing.PointF operator -(System.Drawing.PointF pt, System.Drawing.SizeF sz) { throw null; }
public static System.Drawing.PointF Subtract(System.Drawing.PointF pt, System.Drawing.Size sz) { throw null; }
public static System.Drawing.PointF Subtract(System.Drawing.PointF pt, System.Drawing.SizeF sz) { throw null; }
public override string ToString() { throw null; }
}
public partial struct Rectangle : System.IEquatable<System.Drawing.Rectangle>
{
public static readonly System.Drawing.Rectangle Empty;
public Rectangle(System.Drawing.Point location, System.Drawing.Size size) { throw null; }
public Rectangle(int x, int y, int width, int height) { throw null; }
[System.ComponentModel.Browsable(false)]
public int Bottom { get { throw null; } }
public int Height { get { throw null; } set { } }
[System.ComponentModel.Browsable(false)]
public bool IsEmpty { get { throw null; } }
[System.ComponentModel.Browsable(false)]
public int Left { get { throw null; } }
[System.ComponentModel.Browsable(false)]
public System.Drawing.Point Location { get { throw null; } set { } }
[System.ComponentModel.Browsable(false)]
public int Right { get { throw null; } }
[System.ComponentModel.Browsable(false)]
public System.Drawing.Size Size { get { throw null; } set { } }
[System.ComponentModel.Browsable(false)]
public int Top { get { throw null; } }
public int Width { get { throw null; } set { } }
public int X { get { throw null; } set { } }
public int Y { get { throw null; } set { } }
public static System.Drawing.Rectangle Ceiling(System.Drawing.RectangleF value) { throw null; }
public bool Contains(System.Drawing.Point pt) { throw null; }
public bool Contains(System.Drawing.Rectangle rect) { throw null; }
public bool Contains(int x, int y) { throw null; }
public bool Equals(System.Drawing.Rectangle other) { throw null; }
public override bool Equals(object obj) { throw null; }
public static System.Drawing.Rectangle FromLTRB(int left, int top, int right, int bottom) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Drawing.Rectangle Inflate(System.Drawing.Rectangle rect, int x, int y) { throw null; }
public void Inflate(System.Drawing.Size size) { }
public void Inflate(int width, int height) { }
public void Intersect(System.Drawing.Rectangle rect) { }
public static System.Drawing.Rectangle Intersect(System.Drawing.Rectangle a, System.Drawing.Rectangle b) { throw null; }
public bool IntersectsWith(System.Drawing.Rectangle rect) { throw null; }
public void Offset(System.Drawing.Point pos) { }
public void Offset(int x, int y) { }
public static bool operator ==(System.Drawing.Rectangle left, System.Drawing.Rectangle right) { throw null; }
public static bool operator !=(System.Drawing.Rectangle left, System.Drawing.Rectangle right) { throw null; }
public static System.Drawing.Rectangle Round(System.Drawing.RectangleF value) { throw null; }
public override string ToString() { throw null; }
public static System.Drawing.Rectangle Truncate(System.Drawing.RectangleF value) { throw null; }
public static System.Drawing.Rectangle Union(System.Drawing.Rectangle a, System.Drawing.Rectangle b) { throw null; }
}
public partial struct RectangleF : System.IEquatable<System.Drawing.RectangleF>
{
public static readonly System.Drawing.RectangleF Empty;
public RectangleF(System.Drawing.PointF location, System.Drawing.SizeF size) { throw null; }
public RectangleF(float x, float y, float width, float height) { throw null; }
[System.ComponentModel.Browsable(false)]
public float Bottom { get { throw null; } }
public float Height { get { throw null; } set { } }
[System.ComponentModel.Browsable(false)]
public bool IsEmpty { get { throw null; } }
[System.ComponentModel.Browsable(false)]
public float Left { get { throw null; } }
[System.ComponentModel.Browsable(false)]
public System.Drawing.PointF Location { get { throw null; } set { } }
[System.ComponentModel.Browsable(false)]
public float Right { get { throw null; } }
[System.ComponentModel.Browsable(false)]
public System.Drawing.SizeF Size { get { throw null; } set { } }
[System.ComponentModel.Browsable(false)]
public float Top { get { throw null; } }
public float Width { get { throw null; } set { } }
public float X { get { throw null; } set { } }
public float Y { get { throw null; } set { } }
public bool Contains(System.Drawing.PointF pt) { throw null; }
public bool Contains(System.Drawing.RectangleF rect) { throw null; }
public bool Contains(float x, float y) { throw null; }
public bool Equals(System.Drawing.RectangleF other) { throw null; }
public override bool Equals(object obj) { throw null; }
public static System.Drawing.RectangleF FromLTRB(float left, float top, float right, float bottom) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Drawing.RectangleF Inflate(System.Drawing.RectangleF rect, float x, float y) { throw null; }
public void Inflate(System.Drawing.SizeF size) { }
public void Inflate(float x, float y) { }
public void Intersect(System.Drawing.RectangleF rect) { }
public static System.Drawing.RectangleF Intersect(System.Drawing.RectangleF a, System.Drawing.RectangleF b) { throw null; }
public bool IntersectsWith(System.Drawing.RectangleF rect) { throw null; }
public void Offset(System.Drawing.PointF pos) { }
public void Offset(float x, float y) { }
public static bool operator ==(System.Drawing.RectangleF left, System.Drawing.RectangleF right) { throw null; }
public static implicit operator System.Drawing.RectangleF (System.Drawing.Rectangle r) { throw null; }
public static bool operator !=(System.Drawing.RectangleF left, System.Drawing.RectangleF right) { throw null; }
public override string ToString() { throw null; }
public static System.Drawing.RectangleF Union(System.Drawing.RectangleF a, System.Drawing.RectangleF b) { throw null; }
}
public partial struct Size : System.IEquatable<System.Drawing.Size>
{
public static readonly System.Drawing.Size Empty;
public Size(System.Drawing.Point pt) { throw null; }
public Size(int width, int height) { throw null; }
public int Height { get { throw null; } set { } }
[System.ComponentModel.Browsable(false)]
public bool IsEmpty { get { throw null; } }
public int Width { get { throw null; } set { } }
public static System.Drawing.Size Add(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; }
public static System.Drawing.Size Ceiling(System.Drawing.SizeF value) { throw null; }
public bool Equals(System.Drawing.Size other) { throw null; }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Drawing.Size operator +(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; }
public static bool operator ==(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; }
public static explicit operator System.Drawing.Point (System.Drawing.Size size) { throw null; }
public static implicit operator System.Drawing.SizeF (System.Drawing.Size p) { throw null; }
public static bool operator !=(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; }
public static System.Drawing.Size operator -(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; }
public static System.Drawing.Size Round(System.Drawing.SizeF value) { throw null; }
public static System.Drawing.Size Subtract(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; }
public override string ToString() { throw null; }
public static System.Drawing.Size Truncate(System.Drawing.SizeF value) { throw null; }
}
public partial struct SizeF : System.IEquatable<System.Drawing.SizeF>
{
public static readonly System.Drawing.SizeF Empty;
public SizeF(System.Drawing.PointF pt) { throw null; }
public SizeF(System.Drawing.SizeF size) { throw null; }
public SizeF(float width, float height) { throw null; }
public float Height { get { throw null; } set { } }
[System.ComponentModel.Browsable(false)]
public bool IsEmpty { get { throw null; } }
public float Width { get { throw null; } set { } }
public static System.Drawing.SizeF Add(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; }
public bool Equals(System.Drawing.SizeF other) { throw null; }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Drawing.SizeF operator +(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; }
public static bool operator ==(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; }
public static explicit operator System.Drawing.PointF (System.Drawing.SizeF size) { throw null; }
public static bool operator !=(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; }
public static System.Drawing.SizeF operator -(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; }
public static System.Drawing.SizeF Subtract(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; }
public System.Drawing.PointF ToPointF() { throw null; }
public System.Drawing.Size ToSize() { throw null; }
public override string ToString() { throw null; }
}
}
| |
// 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 gcov = Google.Cloud.OsConfig.V1;
using sys = System;
namespace Google.Cloud.OsConfig.V1
{
/// <summary>Resource name for the <c>VulnerabilityReport</c> resource.</summary>
public sealed partial class VulnerabilityReportName : gax::IResourceName, sys::IEquatable<VulnerabilityReportName>
{
/// <summary>The possible contents of <see cref="VulnerabilityReportName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport</c>.
/// </summary>
ProjectLocationInstance = 1,
}
private static gax::PathTemplate s_projectLocationInstance = new gax::PathTemplate("projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport");
/// <summary>Creates a <see cref="VulnerabilityReportName"/> 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="VulnerabilityReportName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static VulnerabilityReportName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new VulnerabilityReportName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="VulnerabilityReportName"/> with the pattern
/// <c>projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport</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="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// A new instance of <see cref="VulnerabilityReportName"/> constructed from the provided ids.
/// </returns>
public static VulnerabilityReportName FromProjectLocationInstance(string projectId, string locationId, string instanceId) =>
new VulnerabilityReportName(ResourceNameType.ProjectLocationInstance, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), instanceId: gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="VulnerabilityReportName"/> with pattern
/// <c>projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport</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="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="VulnerabilityReportName"/> with pattern
/// <c>projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport</c>.
/// </returns>
public static string Format(string projectId, string locationId, string instanceId) =>
FormatProjectLocationInstance(projectId, locationId, instanceId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="VulnerabilityReportName"/> with pattern
/// <c>projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport</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="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="VulnerabilityReportName"/> with pattern
/// <c>projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport</c>.
/// </returns>
public static string FormatProjectLocationInstance(string projectId, string locationId, string instanceId) =>
s_projectLocationInstance.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="VulnerabilityReportName"/> 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}/instances/{instance}/vulnerabilityReport</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="vulnerabilityReportName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="VulnerabilityReportName"/> if successful.</returns>
public static VulnerabilityReportName Parse(string vulnerabilityReportName) => Parse(vulnerabilityReportName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="VulnerabilityReportName"/> 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}/instances/{instance}/vulnerabilityReport</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="vulnerabilityReportName">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="VulnerabilityReportName"/> if successful.</returns>
public static VulnerabilityReportName Parse(string vulnerabilityReportName, bool allowUnparsed) =>
TryParse(vulnerabilityReportName, allowUnparsed, out VulnerabilityReportName 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="VulnerabilityReportName"/> 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}/instances/{instance}/vulnerabilityReport</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="vulnerabilityReportName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="VulnerabilityReportName"/>, 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 vulnerabilityReportName, out VulnerabilityReportName result) =>
TryParse(vulnerabilityReportName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="VulnerabilityReportName"/> 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}/instances/{instance}/vulnerabilityReport</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="vulnerabilityReportName">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="VulnerabilityReportName"/>, 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 vulnerabilityReportName, bool allowUnparsed, out VulnerabilityReportName result)
{
gax::GaxPreconditions.CheckNotNull(vulnerabilityReportName, nameof(vulnerabilityReportName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationInstance.TryParseName(vulnerabilityReportName, out resourceName))
{
result = FromProjectLocationInstance(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(vulnerabilityReportName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private VulnerabilityReportName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string instanceId = null, string locationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
InstanceId = instanceId;
LocationId = locationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="VulnerabilityReportName"/> class from the component parts of
/// pattern <c>projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport</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="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param>
public VulnerabilityReportName(string projectId, string locationId, string instanceId) : this(ResourceNameType.ProjectLocationInstance, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), instanceId: gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId)))
{
}
/// <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>Instance</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string InstanceId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { 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>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.ProjectLocationInstance: return s_projectLocationInstance.Expand(ProjectId, LocationId, InstanceId);
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 VulnerabilityReportName);
/// <inheritdoc/>
public bool Equals(VulnerabilityReportName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(VulnerabilityReportName a, VulnerabilityReportName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(VulnerabilityReportName a, VulnerabilityReportName b) => !(a == b);
}
public partial class VulnerabilityReport
{
/// <summary>
/// <see cref="gcov::VulnerabilityReportName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcov::VulnerabilityReportName VulnerabilityReportName
{
get => string.IsNullOrEmpty(Name) ? null : gcov::VulnerabilityReportName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class GetVulnerabilityReportRequest
{
/// <summary>
/// <see cref="gcov::VulnerabilityReportName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcov::VulnerabilityReportName VulnerabilityReportName
{
get => string.IsNullOrEmpty(Name) ? null : gcov::VulnerabilityReportName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListVulnerabilityReportsRequest
{
/// <summary>
/// <see cref="InstanceName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public InstanceName ParentAsInstanceName
{
get => string.IsNullOrEmpty(Parent) ? null : InstanceName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
}
| |
// <developer>[email protected]</developer>
// <completed>20</completed>
using System.Xml;
using SharpVectors.Dom.Events;
namespace SharpVectors.Dom.Svg
{
/// <summary>
/// A key interface definition is the
/// <see cref="ISvgSvgElement">ISvgSvgElement</see> interface, which is
/// the interface that corresponds to the 'svg' element.
/// </summary>
/// <remarks>
/// This interface
/// contains various miscellaneous commonly-used utility methods, such
/// as matrix operations and the ability to control the time of redraw
/// on visual rendering devices.
/// <see cref="ISvgSvgElement">ISvgSvgElement</see> extends ViewCSS and
/// DocumentCSS to provide access to
/// the computed values of properties and the override style sheet as
/// described in DOM2.
/// </remarks>
public interface ISvgSvgElement : ISvgElement, ISvgTests, ISvgLangSpace,
ISvgExternalResourcesRequired, ISvgStylable, ISvgLocatable, ISvgFitToViewBox,
ISvgZoomAndPan, IEventTarget
{
/// <summary>
/// Corresponds to attribute x on the given 'svg' element.
/// </summary>
ISvgAnimatedLength X
{
get;
}
/// <summary>
/// Corresponds to attribute y on the given 'svg' element.
/// </summary>
ISvgAnimatedLength Y
{
get;
}
/// <summary>
/// Corresponds to attribute width on the given 'svg' element.
/// </summary>
ISvgAnimatedLength Width
{
get;
}
/// <summary>
/// Corresponds to attribute height on the given 'svg' element.
/// </summary>
ISvgAnimatedLength Height
{
get;
}
/// <summary>
/// Corresponds to attribute contentScriptType on the given 'svg'
/// element.
/// </summary>
string ContentScriptType
{
get;
set;
}
/// <summary>
/// Corresponds to attribute contentStyleType on the given 'svg' element.
/// </summary>
string ContentStyleType
{
get;
set;
}
/// <summary>
/// The position and size of the viewport (implicit or explicit) that
/// corresponds to this 'svg' element.
/// </summary>
/// <remarks>
/// <para>
/// When the user agent is
/// actually rendering the content, then the position and size values
/// represent the actual values when rendering. The position and size
/// values are unitless values in the coordinate system of the parent
/// element. If no parent element exists (i.e., 'svg' element
/// represents the root of the document tree), if this SVG document
/// is embedded as part of another document (e.g., via the HTML
/// 'object' element), then the position and size are unitless values
/// in the coordinate system of the parent document. (If the parent
/// uses CSS or XSL layout, then unitless values represent pixel units
/// for the current CSS or XSL viewport, as described in the CSS2
/// specification.) If the parent element does not have a coordinate
/// system, then the user agent should provide reasonable default
/// values for this attribute.
/// </para>
/// <para>
/// The object itself and its contents are both readonly.
/// </para>
/// </remarks>
ISvgRect Viewport
{
get;
}
/// <summary>
/// Size of a pixel unit (as defined by CSS2) along the x-axis of the
/// viewport, which represents a unit somewhere in the range of 70dpi
/// to 120dpi, and, on systems that support this, might actually match
/// the characteristics of the target medium.
/// </summary>
/// <remarks>
/// On systems where it is impossible to know the size of a pixel, a
/// suitable default pixel size is provided.
/// </remarks>
float PixelUnitToMillimeterX
{
get;
}
/// <summary>
/// Corresponding size of a pixel unit along the y-axis of the viewport.
/// </summary>
float PixelUnitToMillimeterY
{
get;
}
/// <summary>
/// User interface (UI) events in DOM Level 2 indicate the screen
/// positions at which the given UI event occurred. When the user
/// agent actually knows the physical size of a "screen unit", this
/// attribute will express that information; otherwise, user agents
/// will provide a suitable default value such as .28mm.
/// </summary>
float ScreenPixelToMillimeterX
{
get;
}
/// <summary>
/// Corresponding size of a screen pixel along the y-axis of the
/// viewport.
/// </summary>
float ScreenPixelToMillimeterY
{
get;
}
/// <summary>
/// The initial view (i.e., before magnification and panning) of the
/// current innermost SVG document fragment can be either the
/// "standard" view (i.e., based on attributes on the 'svg' element
/// such as fitBoxToViewport) or to a "custom" view (i.e., a
/// hyperlink into a particular 'view' or other element - see
/// <see href="http://www.w3.org/TR/SVG/linking.html#LinksIntoSVG"
/// >Linking into SVG content: URI fragments and SVG views</see>). If
/// the initial view is the "standard" view, then this attribute is
/// false. If the initial view is a "custom" view, then this
/// attribute is true.
/// </summary>
bool UseCurrentView
{
get;
set;
}
/// <summary>
/// The definition of the initial view (i.e., before magnification
/// and panning) of the current innermost SVG document fragment.
/// </summary>
/// <remarks>
/// The meaning depends on the situation:
/// <list type="bullet">
/// <item><description>
/// If the initial view was a "standard" view, then:
/// <list type="bullet">
/// <item><description>
/// the values for viewBox, preserveAspectRatio and zoomAndPan
/// within currentView will match the values for the corresponding
/// DOM attributes that are on SVGSVGElement directly
/// </description></item>
/// <item><description>
/// the values for transform and viewTarget within currentView will
/// be null
/// </description></item>
/// </list>
/// </description></item>
/// <item><description>
/// If the initial view was a link into a 'view' element, then:
/// <list type="bullet">
/// <item><description>
/// the values for viewBox, preserveAspectRatio and zoomAndPan within
/// currentView will correspond to the corresponding attributes for
/// the given 'view' element
/// </description></item>
/// <item><description>
/// the values for transform and viewTarget within currentView will
/// be null
/// </description></item>
/// </list>
/// </description></item>
/// <item><description>
/// If the initial view was a link into another element (i.e., other
/// than a 'view'), then:
/// <list type="bullet">
/// <item><description>
/// the values for viewBox, preserveAspectRatio and zoomAndPan
/// within currentView will match the values for the corresponding
/// DOM attributes that are on SVGSVGElement directly for the
/// closest ancestor 'svg' element
/// </description></item>
/// <item><description>
/// the values for transform within currentView will be null
/// </description></item>
/// <item><description>
/// the viewTarget within currentView will represent the target of
/// the link
/// </description></item>
/// </list>
/// </description></item>
/// <item><description>
/// If the initial view was a link into the SVG document fragment
/// using an SVG view specification fragment identifier (i.e.,
/// #svgView(...)), then:
/// <list type="bullet">
/// <item><description>
/// the values for viewBox, preserveAspectRatio, zoomAndPan,
/// transform and viewTarget within currentView will correspond
/// to the values from the SVG view specification fragment
/// identifier
/// </description></item>
/// </list>
/// </description></item>
/// </list>
/// The object itself and its contents are both readonly.
/// </remarks>
ISvgViewSpec CurrentView
{
get;
}
/// <summary>
/// This attribute indicates the current scale factor relative to
/// the initial view to take into account user magnification and
/// panning operations, as described under <see
/// href="http://www.w3.org/TR/SVG/interact.html#ZoomAndPanAttribute"
/// >Magnification and panning</see>.
/// </summary>
/// <remarks>
/// DOM attributes currentScale and currentTranslate are
/// equivalent to the 2x3 matrix [a b c d e f] = [currentScale 0
/// 0 currentScale currentTranslate.x currentTranslate.y]. If
/// "magnification" is enabled (i.e., zoomAndPan="magnify"), then
/// the effect is as if an extra transformation were placed at the
/// outermost level on the SVG document fragment (i.e., outside the
/// outermost 'svg' element).
/// </remarks>
float CurrentScale
{
get;
set;
}
/// <summary>
/// The corresponding translation factor that takes into account
/// user "magnification".
/// </summary>
ISvgPoint CurrentTranslate
{
get;
}
/// <summary>
/// Takes a time-out value which indicates that redraw shall not
/// occur until certain conditions are met.
/// </summary>
/// <remarks>
/// Takes a time-out value which indicates that redraw shall not
/// occur until: (a) the corresponding unsuspendRedraw(
/// suspend_handle_id) call has been made, (b) an
/// unsuspendRedrawAll() call has been made, or (c) its timer
/// has timed out. In environments that do not support
/// interactivity (e.g., print media), then redraw shall not be
/// suspended. suspend_handle_id = suspendRedraw(
/// max_wait_milliseconds) and unsuspendRedraw(suspend_handle_id)
/// must be packaged as balanced pairs. When you want to suspend
/// redraw actions as a collection of SVG DOM changes occur,
/// then precede the changes to the SVG DOM with a method call
/// similar to suspend_handle_id = suspendRedraw(
/// max_wait_milliseconds) and follow the changes with a method
/// call similar to unsuspendRedraw(suspend_handle_id). Note
/// that multiple suspendRedraw calls can be used at once and
/// that each such method call is treated independently of the
/// other suspendRedraw method calls.
/// </remarks>
/// <param name="max_wait_milliseconds">
/// The amount of time in milliseconds to hold off before redrawing
/// the device. Values greater than 60 seconds will be truncated down
/// to 60 seconds.
/// </param>
/// <returns>
/// A number which acts as a unique identifier for the given
/// suspendRedraw() call. This value must be passed as the parameter
/// to the corresponding unsuspendRedraw() method call.
/// </returns>
int SuspendRedraw(int max_wait_milliseconds);
/// <summary>
/// Cancels a specified suspendRedraw() by providing a unique
/// suspend_handle_id.
/// </summary>
/// <param name="suspend_handle_id">
/// A number which acts as a unique identifier for the desired
/// suspendRedraw() call. The number supplied must be a value
/// returned from a previous call to suspendRedraw()
/// </param>
void UnsuspendRedraw(int suspend_handle_id);
/// <summary>
/// Cancels all currently active suspendRedraw() method calls.
/// been cancelled.
/// </summary>
/// <remarks>
/// This method is most useful at the very end of a set of SVG
/// DOM calls to ensure that all pending suspendRedraw() method
/// calls have been cancelled.
/// </remarks>
void UnsuspendRedrawAll();
/// <summary>
/// In rendering environments supporting interactivity, forces the
/// user agent to immediately redraw all regions of the viewport
/// that require updating.
/// </summary>
void ForceRedraw();
/// <summary>
/// Suspends (i.e., pauses) all currently running animations that are
/// defined within the SVG document fragment corresponding to this
/// 'svg' element, causing the animation clock corresponding to this
/// document fragment to stand still until it is unpaused.
/// </summary>
void PauseAnimations();
/// <summary>
/// Unsuspends (i.e., unpauses) currently running animations that are
/// defined within the SVG document fragment, causing the animation
/// clock to continue from the time at which it was suspended.
/// </summary>
void UnpauseAnimations();
/// <summary>
/// Returns true if this SVG document fragment is in a paused state.
/// </summary>
/// <returns>
/// Boolean indicating whether this SVG document fragment is in a
/// paused state.
/// </returns>
bool AnimationsPaused();
/// <summary>
/// The current time in seconds relative to the start time
/// for the current SVG document fragment.
/// </summary>
float CurrentTime
{
get;
set;
}
/// <summary>
/// Returns the list of graphics elements whose rendered content
/// intersects the supplied rectangle, honoring the 'pointer-events'
/// property value on each candidate graphics element.
/// </summary>
/// <param name="rect">
/// The test rectangle. The values are in the initial coordinate
/// system for the current 'svg' element.
/// </param>
/// <param name="referenceElement">
/// If not null, then only return elements whose drawing order has
/// them below the given reference element.
/// </param>
/// <returns>
/// A list of Elements whose content intersects the supplied
/// rectangle.
/// </returns>
XmlNodeList GetIntersectionList(ISvgRect rect, ISvgElement referenceElement);
/// <summary>
/// Returns the list of graphics elements whose rendered content is
/// entirely contained within the supplied rectangle, honoring the
/// 'pointer-events' property value on each candidate graphics
/// element.
/// </summary>
/// <param name="rect">
/// The test rectangle. The values are in the initial coordinate
/// system for the current 'svg' element.
/// </param>
/// <param name="referenceElement">
/// If not null, then only return elements whose drawing order has
/// them below the given reference element.
/// </param>
/// <returns>
/// A list of Elements whose content is enclosed by the supplied
/// rectangle.
/// </returns>
XmlNodeList GetEnclosureList(ISvgRect rect, ISvgElement referenceElement);
/// <summary>
/// Returns true if the rendered content of the given element
/// intersects the supplied rectangle, honoring the 'pointer-events'
/// property value on each candidate graphics element.
/// </summary>
/// <param name="element">
/// The element on which to perform the given test.
/// </param>
/// <param name="rect">
/// The test rectangle. The values are in the initial coordinate
/// system for the current 'svg' element.
/// </param>
/// <returns>
/// True or false, depending on whether the given element intersects
/// the supplied rectangle.
/// </returns>
bool CheckIntersection(ISvgElement element, ISvgRect rect);
/// <summary>
/// Returns true if the rendered content of the given element is
/// entirely contained within the supplied rectangle, honoring the
/// 'pointer-events' property value on each candidate graphics
/// element.
/// </summary>
/// <param name="element">
/// The element on which to perform the given test.
/// </param>
/// <param name="rect">
/// The test rectangle. The values are in the initial coordinate
/// system for the current 'svg' element.
/// </param>
/// <returns>
/// True or false, depending on whether the given element is
/// enclosed by the supplied rectangle.
/// </returns>
bool CheckEnclosure(ISvgElement element, ISvgRect rect);
/// <summary>
/// Unselects any selected objects, including any selections of text
/// strings and type-in bars.
/// </summary>
void DeselectAll();
/// <summary>
/// Creates an SVGNumber object outside of any document trees. The
/// object is initialized to a value of zero.
/// </summary>
/// <returns>
/// An SVGNumber object.
/// </returns>
ISvgNumber CreateSvgNumber();
/// <summary>
/// Creates an SVGLength object outside of any document trees. The
/// object is initialized to the value of 0 user units.
/// </summary>
/// <returns>
/// An SVGLength object.
/// </returns>
ISvgLength CreateSvgLength();
/// <summary>
/// Creates an SVGAngle object outside of any document trees. The
/// object is initialized to the value 0 degrees (unitless).
/// </summary>
/// <returns>
/// An SVGAngle object.
/// </returns>
ISvgAngle CreateSvgAngle();
/// <summary>
/// Creates an SVGPoint object outside of any document trees. The
/// object is initialized to the point (0,0) in the user coordinate
/// system.
/// </summary>
/// <returns>
/// An SVGPoint object.
/// </returns>
ISvgPoint CreateSvgPoint();
/// <summary>
/// Creates an SVGMatrix object outside of any document trees. The
/// object is initialized to the identity matrix.
/// </summary>
/// <returns>
/// An SVGMatrix object.
/// </returns>
ISvgMatrix CreateSvgMatrix();
/// <summary>
/// Creates an SVGRect object outside of any document trees. The
/// object is initialized such that all values are set to 0 user
/// units.
/// </summary>
/// <returns>
/// An SVGRect object.
/// </returns>
ISvgRect CreateSvgRect();
/// <summary>
/// Creates an SVGTransform object outside of any document trees. The
/// object is initialized to an identity matrix transform
/// (SVG_TRANSFORM_MATRIX).
/// </summary>
/// <returns>
/// An SVGTransform object.
/// </returns>
ISvgTransform CreateSvgTransform();
/// <summary>
/// Creates an SVGTransform object outside of any document trees.
/// The object is initialized to the given matrix transform (i.e.,
/// SVG_TRANSFORM_MATRIX).
/// </summary>
/// <param name="matrix">
/// The transform matrix.
/// </param>
/// <returns>
/// An SVGTransform object.
/// </returns>
ISvgTransform CreateSvgTransformFromMatrix(ISvgMatrix matrix);
/// <summary>
/// Searches this SVG document fragment (i.e., the search is
/// restricted to a subset of the document tree) for an Element whose
/// id is given by elementId.
/// </summary>
/// <remarks>
/// If an Element is found, that Element is
/// returned. If no such element exists, returns null. Behavior is
/// not defined if more than one element has this id.
/// </remarks>
/// <param name="elementId">
/// The unique id value for an element.
/// </param>
/// <returns>
/// The matching element.
/// </returns>
XmlElement GetElementById(string elementId);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Runtime.InteropServices.Tests.Common;
using Xunit;
namespace System.Runtime.InteropServices.Tests
{
public class StructureToPtrTests
{
[Fact]
public void StructureToPtr_ByValBoolArray_Success()
{
var structure1 = new StructWithBoolArray()
{
array = new bool[] { true, true, true, true }
};
int size = Marshal.SizeOf(structure1);
IntPtr memory = Marshal.AllocHGlobal(size + sizeof(int));
try
{
Marshal.WriteInt32(memory, size, 0xFF);
Marshal.StructureToPtr(structure1, memory, false);
Marshal.StructureToPtr(structure1, memory, true);
Assert.Equal(0xFF, Marshal.ReadInt32(memory, size));
}
finally
{
Marshal.FreeHGlobal(memory);
}
}
[Fact]
public void StructureToPtr_ByValArrayInStruct_Success()
{
var structure = new StructWithByValArray()
{
array = new StructWithIntField[]
{
new StructWithIntField { value = 1 },
new StructWithIntField { value = 2 },
new StructWithIntField { value = 3 },
new StructWithIntField { value = 4 },
new StructWithIntField { value = 5 }
}
};
int size = Marshal.SizeOf(structure);
IntPtr memory = Marshal.AllocHGlobal(size);
try
{
Marshal.StructureToPtr(structure, memory, false);
Marshal.StructureToPtr(structure, memory, true);
}
finally
{
Marshal.FreeHGlobal(memory);
}
}
[Fact]
public void StructureToPtr_OverflowByValArrayInStruct_Success()
{
var structure = new StructWithByValArray()
{
array = new StructWithIntField[]
{
new StructWithIntField { value = 1 },
new StructWithIntField { value = 2 },
new StructWithIntField { value = 3 },
new StructWithIntField { value = 4 },
new StructWithIntField { value = 5 },
new StructWithIntField { value = 6 }
}
};
int size = Marshal.SizeOf(structure);
IntPtr memory = Marshal.AllocHGlobal(size);
try
{
Marshal.StructureToPtr(structure, memory, false);
Marshal.StructureToPtr(structure, memory, true);
}
finally
{
Marshal.FreeHGlobal(memory);
}
}
[Fact]
public void StructureToPtr_ByValDateArray_Success()
{
var structure = new StructWithDateArray()
{
array = new DateTime[]
{
DateTime.Now, DateTime.Now , DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now , DateTime.Now, DateTime.Now
}
};
int size = Marshal.SizeOf(structure);
IntPtr memory = Marshal.AllocHGlobal(size);
try
{
Marshal.StructureToPtr(structure, memory, false);
Marshal.StructureToPtr(structure, memory, true);
}
finally
{
Marshal.DestroyStructure(memory, structure.GetType());
Marshal.FreeHGlobal(memory);
}
}
[Fact]
public void StructureToPtr_NullPtr_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("ptr", () => Marshal.StructureToPtr((object)new SomeTestStruct_Auto(), IntPtr.Zero, fDeleteOld: true));
AssertExtensions.Throws<ArgumentNullException>("ptr", () => Marshal.StructureToPtr(new SomeTestStruct_Auto(), IntPtr.Zero, fDeleteOld: true));
}
[Fact]
public void StructureToPtr_NullStructure_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("structure", () => Marshal.StructureToPtr(null, (IntPtr)1, fDeleteOld: true));
AssertExtensions.Throws<ArgumentNullException>("structure", () => Marshal.StructureToPtr<object>(null, (IntPtr)1, fDeleteOld: true));
}
public static IEnumerable<object[]> StructureToPtr_GenericClass_TestData()
{
yield return new object[] { new GenericClass<string>() };
yield return new object[] { new GenericStruct<string>() };
}
[Theory]
[MemberData(nameof(StructureToPtr_GenericClass_TestData))]
public void StructureToPtr_GenericObject_ThrowsArgumentException(object o)
{
AssertExtensions.Throws<ArgumentException>("structure", () => Marshal.StructureToPtr(o, (IntPtr)1, fDeleteOld: true));
AssertExtensions.Throws<ArgumentException>("structure", () => Marshal.StructureToPtr<object>(o, (IntPtr)1, fDeleteOld: true));
}
public static IEnumerable<object[]> StructureToPtr_NonBlittableObject_TestData()
{
yield return new object[] { new NonGenericClass() };
yield return new object[] { "string" };
}
[Theory]
[MemberData(nameof(StructureToPtr_NonBlittableObject_TestData))]
public void StructureToPtr_NonBlittable_ThrowsArgumentException(object o)
{
AssertExtensions.Throws<ArgumentException>("structure", () => Marshal.StructureToPtr(o, (IntPtr)1, fDeleteOld: true));
AssertExtensions.Throws<ArgumentException>("structure", () => Marshal.StructureToPtr<object>(o, (IntPtr)1, fDeleteOld: true));
}
[Fact]
public void StructureToPtr_AutoLayout_ThrowsArgumentException()
{
var someTs_Auto = new SomeTestStruct_Auto();
AssertExtensions.Throws<ArgumentException>("structure", () => Marshal.StructureToPtr((object)someTs_Auto, (IntPtr)1, fDeleteOld: true));
AssertExtensions.Throws<ArgumentException>("structure", () => Marshal.StructureToPtr(someTs_Auto, (IntPtr)1, fDeleteOld: true));
}
[Fact]
public void StructureToPtr_InvalidLengthByValArrayInStruct_ThrowsArgumentException()
{
var structure = new StructWithByValArray
{
array = new StructWithIntField[]
{
new StructWithIntField { value = 1 },
new StructWithIntField { value = 2 },
new StructWithIntField { value = 3 },
new StructWithIntField { value = 4 }
}
};
int size = Marshal.SizeOf(structure);
IntPtr memory = Marshal.AllocHGlobal(size);
try
{
Assert.Throws<ArgumentException>(() => Marshal.StructureToPtr(structure, memory, false));
Assert.Throws<ArgumentException>(() => Marshal.StructureToPtr(structure, memory, true));
}
finally
{
Marshal.FreeHGlobal(memory);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public unsafe void StructureToPtr_StructWithBlittableFixedBuffer_In_NonBlittable_Success()
{
var str = default(NonBlittableContainingBuffer);
// Assign values to the bytes.
byte* ptr = (byte*)&str.bufferStruct;
for (int i = 0; i < sizeof(HasFixedBuffer); i++)
ptr[i] = (byte)(0x11 * (i + 1));
HasFixedBuffer* original = (HasFixedBuffer*)ptr;
// Marshal the parent struct.
var parentStructIntPtr = Marshal.AllocHGlobal(Marshal.SizeOf<NonBlittableContainingBuffer>());
Marshal.StructureToPtr(str, parentStructIntPtr, false);
try
{
HasFixedBuffer* bufferStructPtr = (HasFixedBuffer*)parentStructIntPtr.ToPointer();
Assert.Equal(original->buffer[0], bufferStructPtr->buffer[0]);
Assert.Equal(original->buffer[1], bufferStructPtr->buffer[1]);
}
finally
{
Marshal.DestroyStructure<NonBlittableContainingBuffer>(parentStructIntPtr);
Marshal.FreeHGlobal(parentStructIntPtr);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public unsafe void StructureToPtr_NonBlittableStruct_WithBlittableFixedBuffer_Success()
{
NonBlittableWithBlittableBuffer x = new NonBlittableWithBlittableBuffer();
x.f[0] = 1;
x.f[1] = 2;
x.f[2] = 3;
x.s = null;
int size = Marshal.SizeOf(typeof(NonBlittableWithBlittableBuffer));
byte* p = stackalloc byte[size];
Marshal.StructureToPtr(x, (IntPtr)p, false);
NonBlittableWithBlittableBuffer y = Marshal.PtrToStructure<NonBlittableWithBlittableBuffer>((IntPtr)p);
Assert.Equal(x.f[0], y.f[0]);
Assert.Equal(x.f[1], y.f[1]);
Assert.Equal(x.f[2], y.f[2]);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public unsafe void StructureToPtr_OpaqueStruct_In_NonBlittableStructure_Success()
{
NonBlittableWithOpaque x = new NonBlittableWithOpaque();
byte* opaqueData = (byte*)&x.opaque;
*opaqueData = 1;
int size = Marshal.SizeOf(typeof(NonBlittableWithOpaque));
byte* p = stackalloc byte[size];
Marshal.StructureToPtr(x, (IntPtr)p, false);
NonBlittableWithOpaque y = Marshal.PtrToStructure<NonBlittableWithOpaque>((IntPtr)p);
byte* marshaledOpaqueData = (byte*)&y.opaque;
Assert.Equal(*opaqueData, *marshaledOpaqueData);
}
public struct StructWithIntField
{
public int value;
}
public struct StructWithByValArray
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)]
public StructWithIntField[] array;
}
public struct StructWithBoolArray
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
public bool[] array;
}
public struct StructWithDateArray
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
public DateTime[] array;
}
[StructLayout(LayoutKind.Auto)]
public struct SomeTestStruct_Auto
{
public int i;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct HasFixedBuffer
{
public short member;
public fixed byte buffer[2];
public short member2;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct NonBlittableContainingBuffer
{
public HasFixedBuffer bufferStruct;
public string str;
public IntPtr intPtr;
}
unsafe struct NonBlittableWithBlittableBuffer
{
public fixed int f[100];
public string s;
}
[StructLayout(LayoutKind.Explicit, Size = 1)]
public struct OpaqueStruct
{
}
public struct NonBlittableWithOpaque
{
public OpaqueStruct opaque;
public string str;
}
}
}
| |
// 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 XorDouble()
{
var test = new SimpleBinaryOpTest__XorDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// 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();
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__XorDouble
{
private const int VectorSize = 32;
private const int ElementCount = VectorSize / sizeof(Double);
private static Double[] _data1 = new Double[ElementCount];
private static Double[] _data2 = new Double[ElementCount];
private static Vector256<Double> _clsVar1;
private static Vector256<Double> _clsVar2;
private Vector256<Double> _fld1;
private Vector256<Double> _fld2;
private SimpleBinaryOpTest__DataTable<Double> _dataTable;
static SimpleBinaryOpTest__XorDouble()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__XorDouble()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); }
_dataTable = new SimpleBinaryOpTest__DataTable<Double>(_data1, _data2, new Double[ElementCount], VectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx.Xor(
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx.Xor(
Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx.Xor(
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx).GetMethod(nameof(Avx.Xor), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx).GetMethod(nameof(Avx.Xor), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx).GetMethod(nameof(Avx.Xor), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx.Xor(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr);
var result = Avx.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr));
var result = Avx.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr));
var result = Avx.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__XorDouble();
var result = Avx.Xor(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx.Xor(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Double> left, Vector256<Double> right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[ElementCount];
Double[] inArray2 = new Double[ElementCount];
Double[] outArray = new Double[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[ElementCount];
Double[] inArray2 = new Double[ElementCount];
Double[] outArray = new Double[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
if ((BitConverter.DoubleToInt64Bits(left[0]) ^ BitConverter.DoubleToInt64Bits(right[0])) != BitConverter.DoubleToInt64Bits(result[0]))
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if ((BitConverter.DoubleToInt64Bits(left[i]) ^ BitConverter.DoubleToInt64Bits(right[i])) != BitConverter.DoubleToInt64Bits(result[i]))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.Xor)}<Double>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
/*
Copyright 2019 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 ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.ADF.CATIDs;
using System.Runtime.InteropServices;
namespace PanZoom
{
[ClassInterface(ClassInterfaceType.None)]
[Guid("03079006-888A-4691-941A-7B16F35E2C1E")]
public class ZoomOut : ICommand, ITool
{
#region COM Registration Function(s)
[ComRegisterFunction()]
[ComVisible(false)]
static void RegisterFunction(Type registerType)
{
// Required for ArcGIS Component Category Registrar support
ArcGISCategoryRegistration(registerType);
//
// TODO: Add any COM registration code here
//
}
[ComUnregisterFunction()]
[ComVisible(false)]
static void UnregisterFunction(Type registerType)
{
// Required for ArcGIS Component Category Registrar support
ArcGISCategoryUnregistration(registerType);
//
// TODO: Add any COM unregistration code here
//
}
#region ArcGIS Component Category Registrar generated code
/// <summary>
/// Required method for ArcGIS Component Category registration -
/// Do not modify the contents of this method with the code editor.
/// </summary>
private static void ArcGISCategoryRegistration(Type registerType)
{
string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
ControlsCommands.Register(regKey);
}
/// <summary>
/// Required method for ArcGIS Component Category unregistration -
/// Do not modify the contents of this method with the code editor.
/// </summary>
private static void ArcGISCategoryUnregistration(Type registerType)
{
string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
ControlsCommands.Unregister(regKey);
}
#endregion
#endregion
[DllImport("gdi32.dll")]
static extern bool DeleteObject(IntPtr hObject);
private System.Drawing.Bitmap m_bitmap;
private IntPtr m_hBitmap;
private IHookHelper m_pHookHelper;
private INewEnvelopeFeedback m_feedBack;
private IPoint m_point;
private Boolean m_isMouseDown;
private System.Windows.Forms.Cursor m_zoomOutCur;
private System.Windows.Forms.Cursor m_moveZoomOutCur;
public ZoomOut()
{
//Load resources
string[] res = GetType().Assembly.GetManifestResourceNames();
if(res.GetLength(0) > 0)
{
m_bitmap = new System.Drawing.Bitmap(GetType().Assembly.GetManifestResourceStream(GetType(), "ZoomOut.bmp"));
if(m_bitmap != null)
{
m_bitmap.MakeTransparent(m_bitmap.GetPixel(1,1));
m_hBitmap = m_bitmap.GetHbitmap();
}
}
m_pHookHelper = new HookHelperClass ();
}
~ZoomOut()
{
if(m_hBitmap.ToInt32() != 0)
DeleteObject(m_hBitmap);
}
#region ICommand Members
public void OnClick()
{
}
public string Message
{
get
{
return "Zooms the display out by rectangle or single click";
}
}
public int Bitmap
{
get
{
return m_hBitmap.ToInt32();
}
}
public void OnCreate(object hook)
{
m_pHookHelper.Hook = hook;
m_zoomOutCur = new System.Windows.Forms.Cursor(GetType().Assembly.GetManifestResourceStream(GetType(), "ZoomOut.cur"));
m_moveZoomOutCur = new System.Windows.Forms.Cursor(GetType().Assembly.GetManifestResourceStream(GetType(), "MoveZoomOut.cur"));
}
public string Caption
{
get
{
return "Zoom Out";
}
}
public string Tooltip
{
get
{
return "Zoom Out";
}
}
public int HelpContextID
{
get
{
// TODO: Add ZoomOut.HelpContextID getter implementation
return 0;
}
}
public string Name
{
get
{
return "Sample_Pan/Zoom_Zoom Out";
}
}
public bool Checked
{
get
{
return false;
}
}
public bool Enabled
{
get
{
if(m_pHookHelper.FocusMap == null) return false;
return true;
}
}
public string HelpFile
{
get
{
// TODO: Add ZoomOut.HelpFile getter implementation
return null;
}
}
public string Category
{
get
{
return "Sample_Pan/Zoom";
}
}
#endregion
#region ITool Members
public void OnMouseDown(int button, int shift, int x, int y)
{
if(m_pHookHelper.ActiveView == null) return;
//If the active view is a page layout
if(m_pHookHelper.ActiveView is IPageLayout)
{
//Create a point in map coordinates
IPoint pPoint = (IPoint) m_pHookHelper.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(x, y);
//Get the map if the point is within a data frame
IMap pMap = m_pHookHelper.ActiveView.HitTestMap(pPoint);
if(pMap == null) return;
//Set the map to be the page layout's focus map
if(pMap != m_pHookHelper.FocusMap)
{
m_pHookHelper.ActiveView.FocusMap = pMap;
m_pHookHelper.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
}
}
//Create a point in map coordinates
IActiveView pActiveView = (IActiveView) m_pHookHelper.FocusMap;
m_point = pActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(x, y);
m_isMouseDown = true;
}
public void OnMouseMove(int button, int shift, int x, int y)
{
if(!m_isMouseDown) return;
//Get the focus map
IActiveView pActiveView = (IActiveView) m_pHookHelper.FocusMap;
//Start an envelope feedback
if(m_feedBack == null)
{
m_feedBack = new NewEnvelopeFeedbackClass();
m_feedBack.Display = pActiveView.ScreenDisplay;
m_feedBack.Start(m_point);
}
//Move the envelope feedback
m_feedBack.MoveTo(pActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(x, y));
}
public void OnMouseUp(int button, int shift, int x, int y)
{
if(!m_isMouseDown) return;
IEnvelope pEnvelope;
IEnvelope pFeedEnvelope;
double newWidth, newHeight;
//Get the focus map
IActiveView pActiveView = (IActiveView) m_pHookHelper.FocusMap;
//If an envelope has not been tracked
if(m_feedBack == null)
{
//Zoom out from the mouse click
pEnvelope = pActiveView.Extent;
pEnvelope.Expand(2, 2, true);
pEnvelope.CenterAt(m_point);
}
else
{
//Stop the envelope feedback
pFeedEnvelope = m_feedBack.Stop();
//Exit if the envelope height or width is 0
if(pFeedEnvelope.Width == 0 || pFeedEnvelope.Height == 0)
{
m_feedBack = null;
m_isMouseDown = false;
}
newWidth = pActiveView.Extent.Width * (pActiveView.Extent.Width / pFeedEnvelope.Width);
newHeight = pActiveView.Extent.Height * (pActiveView.Extent.Height / pFeedEnvelope.Height);
//Set the new extent coordinates
pEnvelope = new EnvelopeClass();
pEnvelope.PutCoords(pActiveView.Extent.XMin - ((pFeedEnvelope.XMin - pActiveView.Extent.XMin) * (pActiveView.Extent.Width / pFeedEnvelope.Width)),
pActiveView.Extent.YMin - ((pFeedEnvelope.YMin - pActiveView.Extent.YMin) * (pActiveView.Extent.Height / pFeedEnvelope.Height)),
(pActiveView.Extent.XMin - ((pFeedEnvelope.XMin - pActiveView.Extent.XMin) * (pActiveView.Extent.Width / pFeedEnvelope.Width))) + newWidth,
(pActiveView.Extent.YMin - ((pFeedEnvelope.YMin - pActiveView.Extent.YMin) * (pActiveView.Extent.Height / pFeedEnvelope.Height))) + newHeight);
}
//Set the new extent
pActiveView.Extent = pEnvelope;
//Refresh the active view
pActiveView.Refresh();
m_feedBack = null;
m_isMouseDown = false;
}
public void OnKeyDown(int keyCode, int shift)
{
if(m_isMouseDown)
{
if(keyCode == 27) //ESC key
{
m_feedBack = null;
m_isMouseDown = false;
m_pHookHelper.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewForeground, null, null);
}
}
}
public void OnKeyUp(int keyCode, int shift)
{
// TODO: Add ZoomOut.OnKeyUp implementation
}
public int Cursor
{
get
{
if(m_isMouseDown)
return m_moveZoomOutCur.Handle.ToInt32();
else
return m_zoomOutCur.Handle.ToInt32();
}
}
public bool OnContextMenu(int x, int y)
{
// TODO: Add ZoomOut.OnContextMenu implementation
return false;
}
public bool Deactivate()
{
return true;
}
public void Refresh(int hdc)
{
// TODO: Add ZoomOut.Refresh implementation
}
public void OnDblClick()
{
// TODO: Add ZoomOut.OnDblClick implementation
}
#endregion
}
}
| |
///////////////////////////////////////////////////////////////////////////////////////////////
//
// This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
// Copyright (c) 2005-2008, Jim Heising
// 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 Jim Heising nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;
using CallButler.Manager.Utils;
using CallButler.Manager.Forms;
using Utilities;
using WOSI.Utilities;
using Utilities.ContactManagement;
namespace CallButler.Manager.ViewControls
{
public partial class CallHistoryView : CallButler.Manager.ViewControls.ViewControlBase
{
bool _firstTime = true;
private string _currentSort;
private ContactManagerBase _contactManager;
public CallHistoryView()
{
InitializeComponent();
cboFilterBy.SelectedIndex = 0;
CurrentSort = this.bsCallHistory.Sort;
ContactManager = ContactManagerFactory.CreateContactManager(ContactType.Outlook);
ContactManager.OnContactManagerFailureEvent += new ContactManagerBase.ContactManagerFailureEventHandler(ContactManager_OnContactManagerFailureEvent);
SetupOutlook();
this.EnableHelpIcon = false;
}
void ContactManager_OnContactManagerFailureEvent(object source, Exception ex)
{
ToggleOutlookOptions(false);
}
private ContactManagerBase ContactManager
{
get
{
return _contactManager;
}
set
{
_contactManager = value;
}
}
private void ToggleOutlookOptions(bool visible)
{
btnImportOutlook.Enabled = visible;
dgCalls.Columns["ViewInOutlook"].Visible = visible;
}
private void SetupOutlook()
{
if (ContactManager.IsInstalled)
{
ToggleOutlookOptions(true);
}
else
{
ToggleOutlookOptions(false);
}
}
private bool FirstTime
{
get
{
return _firstTime;
}
set
{
_firstTime = value;
}
}
protected override void OnLoadData()
{
callHistoryDataset.Merge(ManagementInterfaceClient.ManagementInterface.GetCallHistory(ManagementInterfaceClient.AuthInfo));
//LoadMissingContacts();
}
private void LoadMissingContacts()
{
if (ContactManager.IsInstalled)
{
foreach (WOSI.CallButler.Data.CallButlerDataset.CallHistoryRow row in callHistoryDataset.CallHistory.Rows)
{
if (row.CallerDisplayName.Length == 0)
{
IContactItem item = ContactManager.SearchContact(row.CallerUsername);
if (ContactManager.IsInstalled == false)
{
break;
}
if (item != null)
{
row.CallerDisplayName = item.FullName;
}
}
}
}
}
private void dgCalls_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == callerUsernameDataGridViewTextBoxColumn.Index)
{
e.Value = WOSI.Utilities.StringUtils.FormatPhoneNumber((string)e.Value);
}
else if (e.ColumnIndex == ToUsername.Index && e.Value != DBNull.Value)
{
e.Value = WOSI.Utilities.StringUtils.FormatPhoneNumber((string)e.Value);
}
else if (e.ColumnIndex == callDurationDataGridViewTextBoxColumn.Index && e.Value != null)
{
if (e.Value is TimeSpan)
{
TimeSpan t = (TimeSpan)e.Value;
e.Value = string.Format("{0:d2}:{1:d2}", t.Minutes, t.Seconds);
}
}
}
private void btnSaveCallHistory_Click(object sender, EventArgs e)
{
SaveCallHistory();
}
private void SaveCallHistory()
{
if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
{
callHistoryDataset.CallHistory.WriteXml(saveFileDialog.FileName);
}
}
private void txtSearch_TextChanged(object sender, EventArgs e)
{
UpdateFilter();
}
private void cboFilterBy_SelectedIndexChanged(object sender, EventArgs e)
{
UpdateFilter();
}
private void UpdateFilter()
{
if (FirstTime || txtSearch.Text.Length == 0)
{
bsCallHistory.Filter = "";
}
else
{
string searchString = "CallerDisplayName LIKE '";
if (cboFilterBy.SelectedIndex == 1)
{
searchString = "CallerUsername LIKE '";
}
searchString += txtSearch.Text + "*'";
bsCallHistory.Filter = searchString;
}
}
private void txtSearch_Click(object sender, EventArgs e)
{
if (FirstTime)
{
FirstTime = false;
txtSearch.Text = String.Empty;
txtSearch.ForeColor = this.ForeColor;
}
}
private void btnClearCriteria_Click(object sender, EventArgs e)
{
txtSearch.Text = String.Empty;
}
private void btnPrintHistory_Click(object sender, EventArgs e)
{
DataRow[] rows = SelectProperGridRows(this.callHistoryDataset.CallHistory);
ReportPrinter p = new ReportPrinter("CallButlerDataset_CallHistory", rows, "CallButler.Manager.Reports.CallHistoryReport.rdlc", this);
p.OnPrintPageSelectionEvent += new ReportPrinter.PrintPageSelectionEventHandler(p_OnPrintPageSelectionEvent);
p.Print();
}
private void p_OnPrintPageSelectionEvent(object source, PrintPageEventArgs e)
{
ReportPrinter p = source as ReportPrinter;
if (p != null)
{
DataRow[] rows = GetSelectedGridRows();
p.DataSource = rows;
p.FinalizePrint(e);
}
}
private DataRow[] SelectProperGridRows(WOSI.CallButler.Data.CallButlerDataset.CallHistoryDataTable historyTable)
{
return historyTable.Select(this.bsCallHistory.Filter, CurrentSort);
}
private DataRow[] GetSelectedGridRows()
{
DataGridViewSelectedRowCollection selectedRows = this.dgCalls.SelectedRows;
WOSI.CallButler.Data.CallButlerDataset ds = new WOSI.CallButler.Data.CallButlerDataset();
ds.CallHistory.Columns.Add("OriginalIndex", typeof(int));
foreach (DataGridViewRow row in selectedRows)
{
DataRowView rv = row.DataBoundItem as DataRowView;
DataRow newRow = ds.CallHistory.LoadDataRow(rv.Row.ItemArray, true);
newRow["OriginalIndex"] = row.Index;
}
DataRow[] rows = SelectProperGridRows(ds.CallHistory);
return rows;
}
private string CurrentSort
{
get
{
return _currentSort;
}
set
{
_currentSort = value;
}
}
private void dgCalls_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
string text = dgCalls.Columns[e.ColumnIndex].DataPropertyName.ToString();
text += StringUtils.GetProperSortText(dgCalls.SortOrder);
CurrentSort = text;
}
private void btnImportOutlook_Click(object sender, EventArgs e)
{
LoadSelectedContacts();
}
private void LoadSelectedContacts()
{
if (ContactManager.IsInstalled)
{
WOSI.CallButler.Data.CallButlerDataset.CallHistoryRow[] rows = (WOSI.CallButler.Data.CallButlerDataset.CallHistoryRow[])GetSelectedGridRows();
foreach (WOSI.CallButler.Data.CallButlerDataset.CallHistoryRow row in rows)
{
IContactItem item = ContactManager.SearchContact(row.CallerUsername, row.CallerDisplayName);
if (item == null)
{
item = ContactItemFactory.CreateContactItem(ContactManager, row.CallerDisplayName, row.CallerUsername);
}
ContactManager.ShowContactForm(item);
if (row.Table.Columns["OriginalIndex"] != null)
{
WOSI.CallButler.Data.CallButlerDataset.CallHistoryRow cRow = GetUnderlyingRow(dgCalls.Rows[Convert.ToInt32(row["OriginalIndex"])]);
if (item != null)
{
cRow.CallerDisplayName = item.FullName;
}
}
}
}
}
private WOSI.CallButler.Data.CallButlerDataset.CallHistoryRow GetUnderlyingRow(DataGridViewRow row)
{
DataRowView rv = (DataRowView)row.DataBoundItem;
WOSI.CallButler.Data.CallButlerDataset.CallHistoryRow callRow = (WOSI.CallButler.Data.CallButlerDataset.CallHistoryRow)rv.Row;
return callRow;
}
private void ViewInContactManager(DataGridViewRow row)
{
WOSI.CallButler.Data.CallButlerDataset.CallHistoryRow callRow = GetUnderlyingRow(row);
IContactItem item = ContactManager.SearchContact(callRow.CallerUsername, callRow.CallerDisplayName);
if (item == null || (callRow.IsCallerUsernameNull() || callRow.CallerUsername.Length == 0) && (callRow.IsCallerDisplayNameNull() || callRow.CallerDisplayName.Length == 0))
{
if (MessageBox.Show(CallButler.Manager.Utils.PrivateLabelUtils.ReplaceProductName(Properties.LocalizedStrings.CallHistoryView_ContactNotFound), CallButler.Manager.Utils.PrivateLabelUtils.ReplaceProductName(Properties.LocalizedStrings.CallHistoryView_NoContactFound), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
item = ContactItemFactory.CreateContactItem(ContactManager);
item.FullName = callRow.CallerDisplayName;
item.BusinessTelephoneNumber = StringUtils.FormatPhoneNumber(callRow.CallerUsername);
ContactManager.ShowContactForm(item);
}
}
else
{
ContactManager.ShowContactForm(item);
}
/*if (item != null)
{
callRow.CallerDisplayName = item.FullName;
}*/
}
private void dgCalls_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (ContactManager.IsInstalled)
{
if (dgCalls.Columns[e.ColumnIndex].Name.Equals("ViewInOutlook"))
{
ViewInContactManager(dgCalls.Rows[e.RowIndex]);
}
}
}
private void btnClearAll_Click(object sender, EventArgs e)
{
if (MessageBox.Show(this, CallButler.Manager.Utils.PrivateLabelUtils.ReplaceProductName(Properties.LocalizedStrings.CallHistoryView_ConfirmClear), CallButler.Manager.Utils.PrivateLabelUtils.ReplaceProductName(Properties.LocalizedStrings.Common_ConfirmDelete), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
ManagementInterfaceClient.ManagementInterface.ClearCallHistory(ManagementInterfaceClient.AuthInfo);
callHistoryDataset.CallHistory.Clear();
}
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using tk2dRuntime.TileMap;
[System.Flags]
public enum tk2dTileFlags {
None = 0x00000000,
FlipX = 0x01000000,
FlipY = 0x02000000,
Rot90 = 0x04000000,
}
[ExecuteInEditMode]
[AddComponentMenu("2D Toolkit/TileMap/TileMap")]
/// <summary>
/// Tile Map
/// </summary>
public class tk2dTileMap : MonoBehaviour, tk2dRuntime.ISpriteCollectionForceBuild
{
/// <summary>
/// This is a link to the editor data object (tk2dTileMapEditorData).
/// It contains presets, and other data which isn't really relevant in game.
/// </summary>
public string editorDataGUID = "";
/// <summary>
/// Tile map data, stores shared parameters for tilemaps
/// </summary>
public tk2dTileMapData data;
/// <summary>
/// Tile map render and collider object
/// </summary>
public GameObject renderData;
/// <summary>
/// The sprite collection used by the tilemap
/// </summary>
[SerializeField]
private tk2dSpriteCollectionData spriteCollection = null;
public tk2dSpriteCollectionData Editor__SpriteCollection
{
get
{
return spriteCollection;
}
set
{
spriteCollection = value;
}
}
public tk2dSpriteCollectionData SpriteCollectionInst
{
get
{
if (spriteCollection != null)
return spriteCollection.inst;
else
return null;
}
}
[SerializeField]
int spriteCollectionKey;
/// <summary>Width of the tilemap</summary>
public int width = 128;
/// <summary>Height of the tilemap</summary>
public int height = 128;
/// <summary>X axis partition size for this tilemap</summary>
public int partitionSizeX = 32;
/// <summary>Y axis partition size for this tilemap</summary>
public int partitionSizeY = 32;
[SerializeField]
Layer[] layers;
[SerializeField]
ColorChannel colorChannel;
[SerializeField]
GameObject prefabsRoot;
[System.Serializable]
public class TilemapPrefabInstance {
public int x, y, layer;
public GameObject instance;
}
[SerializeField]
List<TilemapPrefabInstance> tilePrefabsList = new List<TilemapPrefabInstance>();
[SerializeField]
bool _inEditMode = false;
public bool AllowEdit { get { return _inEditMode; } }
// holds a path to a serialized mesh, uses this to work out dump directory for meshes
public string serializedMeshPath;
void Awake()
{
bool spriteCollectionKeyMatch = true;
if (SpriteCollectionInst && (SpriteCollectionInst.buildKey != spriteCollectionKey || SpriteCollectionInst.needMaterialInstance)) {
spriteCollectionKeyMatch = false;
}
if (Application.platform == RuntimePlatform.WindowsEditor ||
Application.platform == RuntimePlatform.OSXEditor)
{
if ((Application.isPlaying && _inEditMode == true) || !spriteCollectionKeyMatch)
{
// Switched to edit mode while still in edit mode, rebuild
EndEditMode();
}
else {
if (spriteCollection != null && data != null && renderData == null) {
Build(BuildFlags.ForceBuild);
}
}
}
else
{
if (_inEditMode == true)
{
Debug.LogError("Tilemap " + name + " is still in edit mode. Please fix." +
"Building overhead will be significant.");
EndEditMode();
}
else if (!spriteCollectionKeyMatch)
{
Build(BuildFlags.ForceBuild);
}
else if (spriteCollection != null && data != null && renderData == null) {
Build(BuildFlags.ForceBuild);
}
}
}
#if UNITY_EDITOR
void OnEnable() {
if (spriteCollection != null && data != null && renderData != null
&& SpriteCollectionInst != null && SpriteCollectionInst.needMaterialInstance) {
bool needBuild = false;
if (layers != null) {
foreach (tk2dRuntime.TileMap.Layer layer in layers) {
if (layer.spriteChannel != null && layer.spriteChannel.chunks != null) {
foreach (tk2dRuntime.TileMap.SpriteChunk chunk in layer.spriteChannel.chunks) {
if (chunk.gameObject != null && chunk.gameObject.GetComponent<Renderer>() != null) {
if (chunk.gameObject.GetComponent<Renderer>().sharedMaterial == null) {
needBuild = true;
break;
}
}
}
}
}
}
if (needBuild) {
Build(BuildFlags.ForceBuild);
}
}
}
#endif
void OnDestroy() {
if (layers != null) {
foreach (tk2dRuntime.TileMap.Layer layer in layers) {
layer.DestroyGameData(this);
}
}
if (renderData != null) {
tk2dUtil.DestroyImmediate(renderData);
}
}
#if UNITY_EDITOR
void OnDrawGizmos() {
if (data != null) {
Vector3 p0 = data.tileOrigin;
Vector3 p1 = new Vector3(p0.x + data.tileSize.x * width, p0.y + data.tileSize.y * height, 0.0f);
Gizmos.color = Color.clear;
Gizmos.matrix = transform.localToWorldMatrix;
Gizmos.DrawCube((p0 + p1) * 0.5f, (p1 - p0));
Gizmos.matrix = Matrix4x4.identity;
Gizmos.color = Color.white;
}
}
#endif
[System.Flags]
public enum BuildFlags {
Default = 0,
EditMode = 1,
ForceBuild = 2
};
/// <summary>
/// Builds the tilemap. Call this after using the SetTile functions to
/// rebuild the affected partitions. Build only rebuilds affected partitions
/// and is efficent enough to use at runtime if you don't use Unity colliders.
/// Avoid building tilemaps every frame if you use Unity colliders as it will
/// likely be too slow for runtime use.
/// </summary>
public void Build() { Build(BuildFlags.Default); }
/// <summary>
/// Like <see cref="T:Build"/> above, but forces a build of all partitions.
/// </summary>
public void ForceBuild() { Build(BuildFlags.ForceBuild); }
// Clears all spawned instances, but retains the renderData object
void ClearSpawnedInstances()
{
if (layers == null)
return;
BuilderUtil.HideTileMapPrefabs( this );
for (int layerIdx = 0; layerIdx < layers.Length; ++layerIdx)
{
Layer layer = layers[layerIdx];
for (int chunkIdx = 0; chunkIdx < layer.spriteChannel.chunks.Length; ++chunkIdx)
{
var chunk = layer.spriteChannel.chunks[chunkIdx];
if (chunk.gameObject == null)
continue;
var transform = chunk.gameObject.transform;
List<Transform> children = new List<Transform>();
for (int i = 0; i < transform.childCount; ++i)
children.Add(transform.GetChild(i));
for (int i = 0; i < children.Count; ++i)
tk2dUtil.DestroyImmediate(children[i].gameObject);
}
}
}
void SetPrefabsRootActive(bool active) {
if (prefabsRoot != null)
#if UNITY_3_5
prefabsRoot.SetActiveRecursively(active);
#else
tk2dUtil.SetActive(prefabsRoot, active);
#endif
}
public void Build(BuildFlags buildFlags)
{
#if UNITY_EDITOR || !UNITY_FLASH
// Sanitize tilePrefabs input, to avoid branches later
if (data != null && spriteCollection != null)
{
if (data.tilePrefabs == null)
data.tilePrefabs = new GameObject[SpriteCollectionInst.Count];
else if (data.tilePrefabs.Length != SpriteCollectionInst.Count)
System.Array.Resize(ref data.tilePrefabs, SpriteCollectionInst.Count);
// Fix up data if necessary
BuilderUtil.InitDataStore(this);
}
else
{
return;
}
// Sanitize sprite collection material ids
if (SpriteCollectionInst)
SpriteCollectionInst.InitMaterialIds();
bool forceBuild = (buildFlags & BuildFlags.ForceBuild) != 0;
// When invalid, everything needs to be rebuilt
if (SpriteCollectionInst && SpriteCollectionInst.buildKey != spriteCollectionKey)
forceBuild = true;
// Remember active layers
Dictionary<Layer, bool> layersActive = new Dictionary<Layer,bool>();
if (layers != null)
{
for (int layerIdx = 0; layerIdx < layers.Length; ++layerIdx)
{
Layer layer = layers[layerIdx];
if (layer != null && layer.gameObject != null)
{
#if UNITY_3_5
layersActive[layer] = layer.gameObject.active;
#else
layersActive[layer] = layer.gameObject.activeSelf;
#endif
}
}
}
if (forceBuild) {
ClearSpawnedInstances();
}
BuilderUtil.CreateRenderData(this, _inEditMode, layersActive);
RenderMeshBuilder.Build(this, _inEditMode, forceBuild);
if (!_inEditMode)
{
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
tk2dSpriteDefinition def = SpriteCollectionInst.FirstValidDefinition;
if (def != null && def.physicsEngine == tk2dSpriteDefinition.PhysicsEngine.Physics2D) {
ColliderBuilder2D.Build(this, forceBuild);
}
else
#endif
{
ColliderBuilder3D.Build(this, forceBuild);
}
BuilderUtil.SpawnPrefabs(this, forceBuild);
}
// Clear dirty flag on everything
foreach (var layer in layers)
layer.ClearDirtyFlag();
if (colorChannel != null)
colorChannel.ClearDirtyFlag();
// Update sprite collection key
if (SpriteCollectionInst)
spriteCollectionKey = SpriteCollectionInst.buildKey;
#endif
}
/// <summary>
/// Gets the tile coordinate at position. This can be used to obtain tile or color data explicitly from layers
/// Returns true if the position is within the tilemap bounds
/// </summary>
public bool GetTileAtPosition(Vector3 position, out int x, out int y)
{
float ox, oy;
bool b = GetTileFracAtPosition(position, out ox, out oy);
x = (int)ox;
y = (int)oy;
return b;
}
/// <summary>
/// Gets the tile coordinate at position. This can be used to obtain tile or color data explicitly from layers
/// The fractional value returned is the fraction into the current tile
/// Returns true if the position is within the tilemap bounds
/// </summary>
public bool GetTileFracAtPosition(Vector3 position, out float x, out float y)
{
switch (data.tileType)
{
case tk2dTileMapData.TileType.Rectangular:
{
Vector3 localPosition = transform.worldToLocalMatrix.MultiplyPoint(position);
x = (localPosition.x - data.tileOrigin.x) / data.tileSize.x;
y = (localPosition.y - data.tileOrigin.y) / data.tileSize.y;
return (x >= 0 && x < width && y >= 0 && y < height);
}
case tk2dTileMapData.TileType.Isometric:
{
if (data.tileSize.x == 0.0f)
break;
float tileAngle = Mathf.Atan2(data.tileSize.y, data.tileSize.x / 2.0f);
Vector3 localPosition = transform.worldToLocalMatrix.MultiplyPoint(position);
x = (localPosition.x - data.tileOrigin.x) / data.tileSize.x;
y = ((localPosition.y - data.tileOrigin.y) / (data.tileSize.y));
float fy = y * 0.5f;
int iy = (int)fy;
float fry = fy - iy;
float frx = x % 1.0f;
x = (int)x;
y = iy * 2;
if (frx > 0.5f)
{
if (fry > 0.5f && Mathf.Atan2(1.0f - fry, (frx - 0.5f) * 2) < tileAngle)
y += 1;
else if (fry < 0.5f && Mathf.Atan2(fry, (frx - 0.5f) * 2) < tileAngle)
y -= 1;
}
else if (frx < 0.5f)
{
if (fry > 0.5f && Mathf.Atan2(fry - 0.5f, frx * 2) > tileAngle)
{
y += 1;
x -= 1;
}
if (fry < 0.5f && Mathf.Atan2(fry, (0.5f - frx) * 2) < tileAngle)
{
y -= 1;
x -= 1;
}
}
return (x >= 0 && x < width && y >= 0 && y < height);
}
}
x = 0.0f;
y = 0.0f;
return false;
}
/// <summary>
/// Returns the tile position in world space
/// </summary>
public Vector3 GetTilePosition(int x, int y)
{
switch (data.tileType)
{
case tk2dTileMapData.TileType.Rectangular:
default:
{
Vector3 localPosition = new Vector3(
x * data.tileSize.x + data.tileOrigin.x,
y * data.tileSize.y + data.tileOrigin.y,
0);
return transform.localToWorldMatrix.MultiplyPoint(localPosition);
}
case tk2dTileMapData.TileType.Isometric:
{
Vector3 localPosition = new Vector3(
((float)x + (((y & 1) == 0) ? 0.0f : 0.5f)) * data.tileSize.x + data.tileOrigin.x,
y * data.tileSize.y + data.tileOrigin.y,
0);
return transform.localToWorldMatrix.MultiplyPoint(localPosition);
}
}
}
/// <summary>
/// Gets the tile at position. This can be used to obtain tile data, etc
/// -1 = no data or empty tile
/// </summary>
public int GetTileIdAtPosition(Vector3 position, int layer)
{
if (layer < 0 || layer >= layers.Length)
return -1;
int x, y;
if (!GetTileAtPosition(position, out x, out y))
return -1;
return layers[layer].GetTile(x, y);
}
/// <summary>
/// Returns the tile info chunk for the tile. Use this to store additional metadata
/// </summary>
public tk2dRuntime.TileMap.TileInfo GetTileInfoForTileId(int tileId)
{
return data.GetTileInfoForSprite(tileId);
}
/// <summary>
/// Gets the tile at position. This can be used to obtain tile data, etc
/// -1 = no data or empty tile
/// </summary>
public Color GetInterpolatedColorAtPosition(Vector3 position)
{
Vector3 localPosition = transform.worldToLocalMatrix.MultiplyPoint(position);
int x = (int)((localPosition.x - data.tileOrigin.x) / data.tileSize.x);
int y = (int)((localPosition.y - data.tileOrigin.y) / data.tileSize.y);
if (colorChannel == null || colorChannel.IsEmpty)
return Color.white;
if (x < 0 || x >= width ||
y < 0 || y >= height)
{
return colorChannel.clearColor;
}
int offset;
ColorChunk colorChunk = colorChannel.FindChunkAndCoordinate(x, y, out offset);
if (colorChunk.Empty)
{
return colorChannel.clearColor;
}
else
{
int colorChunkRowOffset = partitionSizeX + 1;
Color tileColorx0y0 = colorChunk.colors[offset];
Color tileColorx1y0 = colorChunk.colors[offset + 1];
Color tileColorx0y1 = colorChunk.colors[offset + colorChunkRowOffset];
Color tileColorx1y1 = colorChunk.colors[offset + colorChunkRowOffset + 1];
float wx = x * data.tileSize.x + data.tileOrigin.x;
float wy = y * data.tileSize.y + data.tileOrigin.y;
float ix = (localPosition.x - wx) / data.tileSize.x;
float iy = (localPosition.y - wy) / data.tileSize.y;
Color cy0 = Color.Lerp(tileColorx0y0, tileColorx1y0, ix);
Color cy1 = Color.Lerp(tileColorx0y1, tileColorx1y1, ix);
return Color.Lerp(cy0, cy1, iy);
}
}
// ISpriteCollectionBuilder
public bool UsesSpriteCollection(tk2dSpriteCollectionData spriteCollection)
{
return (this.spriteCollection != null) && (spriteCollection == this.spriteCollection || spriteCollection == this.spriteCollection.inst);
}
// We might need to end edit mode when running in game
public void EndEditMode()
{
_inEditMode = false;
SetPrefabsRootActive(true);
Build(BuildFlags.ForceBuild);
if (prefabsRoot != null) {
tk2dUtil.DestroyImmediate(prefabsRoot);
prefabsRoot = null;
}
}
#if UNITY_EDITOR
public void BeginEditMode()
{
if (layers == null) {
_inEditMode = true;
return;
}
if (!_inEditMode) {
_inEditMode = true;
// Destroy all children
// Only necessary when switching INTO edit mode
BuilderUtil.HideTileMapPrefabs(this);
SetPrefabsRootActive(false);
}
Build(BuildFlags.ForceBuild);
}
public bool AreSpritesInitialized()
{
return layers != null;
}
public bool HasColorChannel()
{
return (colorChannel != null && !colorChannel.IsEmpty);
}
public void CreateColorChannel()
{
colorChannel = new ColorChannel(width, height, partitionSizeX, partitionSizeY);
colorChannel.Create();
}
public void DeleteColorChannel()
{
colorChannel.Delete();
}
public void DeleteSprites(int layerId, int x0, int y0, int x1, int y1)
{
x0 = Mathf.Clamp(x0, 0, width - 1);
y0 = Mathf.Clamp(y0, 0, height - 1);
x1 = Mathf.Clamp(x1, 0, width - 1);
y1 = Mathf.Clamp(y1, 0, height - 1);
int numTilesX = x1 - x0 + 1;
int numTilesY = y1 - y0 + 1;
var layer = layers[layerId];
for (int y = 0; y < numTilesY; ++y)
{
for (int x = 0; x < numTilesX; ++x)
{
layer.SetTile(x0 + x, y0 + y, -1);
}
}
layer.OptimizeIncremental();
}
#endif
public void TouchMesh(Mesh mesh)
{
#if UNITY_EDITOR
tk2dUtil.SetDirty(mesh);
#endif
}
public void DestroyMesh(Mesh mesh)
{
#if UNITY_EDITOR
if (UnityEditor.AssetDatabase.GetAssetPath(mesh).Length != 0)
{
mesh.Clear();
UnityEditor.AssetDatabase.DeleteAsset(UnityEditor.AssetDatabase.GetAssetPath(mesh));
}
else
{
tk2dUtil.DestroyImmediate(mesh);
}
#else
tk2dUtil.DestroyImmediate(mesh);
#endif
}
public int GetTilePrefabsListCount() {
return tilePrefabsList.Count;
}
public List<TilemapPrefabInstance> TilePrefabsList {
get {
return tilePrefabsList;
}
}
public void GetTilePrefabsListItem(int index, out int x, out int y, out int layer, out GameObject instance) {
TilemapPrefabInstance item = tilePrefabsList[index];
x = item.x;
y = item.y;
layer = item.layer;
instance = item.instance;
}
public void SetTilePrefabsList(List<int> xs, List<int> ys, List<int> layers, List<GameObject> instances) {
int n = instances.Count;
tilePrefabsList = new List<TilemapPrefabInstance>(n);
for (int i = 0; i < n; ++i) {
TilemapPrefabInstance item = new TilemapPrefabInstance();
item.x = xs[i];
item.y = ys[i];
item.layer = layers[i];
item.instance = instances[i];
tilePrefabsList.Add(item);
}
}
/// <summary>
/// Gets or sets the layers.
/// </summary>
public Layer[] Layers
{
get { return layers; }
set { layers = value; }
}
/// <summary>
/// Gets or sets the color channel.
/// </summary>
public ColorChannel ColorChannel
{
get { return colorChannel; }
set { colorChannel = value; }
}
/// <summary>
/// Gets or sets the prefabs root.
/// </summary>
public GameObject PrefabsRoot
{
get { return prefabsRoot; }
set { prefabsRoot = value; }
}
/// <summary>Gets the tile on a layer at x, y</summary>
/// <returns>The tile - either a sprite Id or -1 if the tile is empty.</returns>
public int GetTile(int x, int y, int layer) {
if (layer < 0 || layer >= layers.Length)
return -1;
return layers[layer].GetTile(x, y);
}
/// <summary>Gets the tile flags on a layer at x, y</summary>
/// <returns>The tile flags - a combination of tk2dTileFlags</returns>
public tk2dTileFlags GetTileFlags(int x, int y, int layer) {
if (layer < 0 || layer >= layers.Length)
return tk2dTileFlags.None;
return layers[layer].GetTileFlags(x, y);
}
/// <summary>Sets the tile on a layer at x, y - either a sprite Id or -1 if the tile is empty.</summary>
public void SetTile(int x, int y, int layer, int tile) {
if (layer < 0 || layer >= layers.Length)
return;
layers[layer].SetTile(x, y, tile);
}
/// <summary>Sets the tile flags on a layer at x, y - a combination of tk2dTileFlags</summary>
public void SetTileFlags(int x, int y, int layer, tk2dTileFlags flags) {
if (layer < 0 || layer >= layers.Length)
return;
layers[layer].SetTileFlags(x, y, flags);
}
/// <summary>Clears the tile on a layer at x, y</summary>
public void ClearTile(int x, int y, int layer) {
if (layer < 0 || layer >= layers.Length)
return;
layers[layer].ClearTile(x, y);
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
using NPOI.SS.UserModel;
using NPOI.XSSF.Model;
using NPOI.OpenXmlFormats.Spreadsheet;
using NPOI.SS.Util;
using System;
using NPOI.SS.Formula.PTG;
using NPOI.SS.Formula;
using NPOI.SS;
using NPOI.Util;
using NPOI.SS.Formula.Eval;
using System.Globalization;
namespace NPOI.XSSF.UserModel
{
/**
* High level representation of a cell in a row of a spreadsheet.
* <p>
* Cells can be numeric, formula-based or string-based (text). The cell type
* specifies this. String cells cannot conatin numbers and numeric cells cannot
* contain strings (at least according to our model). Client apps should do the
* conversions themselves. Formula cells have the formula string, as well as
* the formula result, which can be numeric or string.
* </p>
* <p>
* Cells should have their number (0 based) before being Added to a row. Only
* cells that have values should be Added.
* </p>
*/
public class XSSFCell : ICell
{
private static String FALSE_AS_STRING = "0";
private static String TRUE_AS_STRING = "1";
/**
* the xml bean Containing information about the cell's location, value,
* data type, formatting, and formula
*/
private CT_Cell _cell;
/**
* the XSSFRow this cell belongs to
*/
private XSSFRow _row;
/**
* 0-based column index
*/
private int _cellNum;
/**
* Table of strings shared across this workbook.
* If two cells contain the same string, then the cell value is the same index into SharedStringsTable
*/
private SharedStringsTable _sharedStringSource;
/**
* Table of cell styles shared across all cells in a workbook.
*/
private StylesTable _stylesSource;
/**
* Construct a XSSFCell.
*
* @param row the parent row.
* @param cell the xml bean Containing information about the cell.
*/
public XSSFCell(XSSFRow row, CT_Cell cell)
{
_cell = cell;
_row = row;
if (cell.r != null)
{
_cellNum = new CellReference(cell.r).Col;
}
else
{
int prevNum = row.LastCellNum;
if (prevNum != -1)
{
_cellNum = (row as XSSFRow).GetCell(prevNum - 1, MissingCellPolicy.RETURN_NULL_AND_BLANK).ColumnIndex + 1;
}
}
_sharedStringSource = ((XSSFWorkbook)row.Sheet.Workbook).GetSharedStringSource();
_stylesSource = ((XSSFWorkbook)row.Sheet.Workbook).GetStylesSource();
}
/**
* @return table of strings shared across this workbook
*/
protected SharedStringsTable GetSharedStringSource()
{
return _sharedStringSource;
}
/**
* @return table of cell styles shared across this workbook
*/
protected StylesTable GetStylesSource()
{
return _stylesSource;
}
/**
* Returns the sheet this cell belongs to
*
* @return the sheet this cell belongs to
*/
public ISheet Sheet
{
get
{
return _row.Sheet;
}
}
/**
* Returns the row this cell belongs to
*
* @return the row this cell belongs to
*/
public IRow Row
{
get
{
return _row;
}
}
/**
* Get the value of the cell as a bool.
* <p>
* For strings, numbers, and errors, we throw an exception. For blank cells we return a false.
* </p>
* @return the value of the cell as a bool
* @throws InvalidOperationException if the cell type returned by {@link #CellType}
* is not CellType.Boolean, CellType.Blank or CellType.Formula
*/
public bool BooleanCellValue
{
get
{
CellType cellType = CellType;
switch (cellType)
{
case CellType.Blank:
return false;
case CellType.Boolean:
return _cell.IsSetV() && TRUE_AS_STRING.Equals(_cell.v);
case CellType.Formula:
//YK: should throw an exception if requesting bool value from a non-bool formula
return _cell.IsSetV() && TRUE_AS_STRING.Equals(_cell.v);
default:
throw TypeMismatch(CellType.Boolean, cellType, false);
}
}
}
/**
* Set a bool value for the cell
*
* @param value the bool value to Set this cell to. For formulas we'll Set the
* precalculated value, for bools we'll Set its value. For other types we
* will change the cell to a bool cell and Set its value.
*/
public void SetCellValue(bool value)
{
_cell.t = (ST_CellType.b);
_cell.v = (value ? TRUE_AS_STRING : FALSE_AS_STRING);
}
/**
* Get the value of the cell as a number.
* <p>
* For strings we throw an exception. For blank cells we return a 0.
* For formulas or error cells we return the precalculated value;
* </p>
* @return the value of the cell as a number
* @throws InvalidOperationException if the cell type returned by {@link #CellType} is CellType.String
* @exception NumberFormatException if the cell value isn't a parsable <code>double</code>.
* @see DataFormatter for turning this number into a string similar to that which Excel would render this number as.
*/
public double NumericCellValue
{
get
{
CellType cellType = CellType;
switch (cellType)
{
case CellType.Blank:
return 0.0;
case CellType.Formula:
case CellType.Numeric:
if (_cell.IsSetV())
{
if (string.IsNullOrEmpty(_cell.v))
return 0.0;
try
{
return Double.Parse(_cell.v, CultureInfo.InvariantCulture);
}
catch (FormatException)
{
throw TypeMismatch(CellType.Numeric, CellType.String, false);
}
}
else
{
return 0.0;
}
default:
throw TypeMismatch(CellType.Numeric, cellType, false);
}
}
}
/**
* Set a numeric value for the cell
*
* @param value the numeric value to Set this cell to. For formulas we'll Set the
* precalculated value, for numerics we'll Set its value. For other types we
* will change the cell to a numeric cell and Set its value.
*/
public void SetCellValue(double value)
{
if (Double.IsInfinity(value))
{
// Excel does not support positive/negative infInities,
// rather, it gives a #DIV/0! error in these cases.
_cell.t = (ST_CellType.e);
_cell.v = (FormulaError.DIV0.String);
}
else if (Double.IsNaN(value))
{
// Excel does not support Not-a-Number (NaN),
// instead it immediately generates an #NUM! error.
_cell.t = (ST_CellType.e);
_cell.v = (FormulaError.NUM.String);
}
else
{
_cell.t = (ST_CellType.n);
_cell.v = (value.ToString(CultureInfo.InvariantCulture));
}
}
/**
* Get the value of the cell as a string
* <p>
* For numeric cells we throw an exception. For blank cells we return an empty string.
* For formulaCells that are not string Formulas, we throw an exception
* </p>
* @return the value of the cell as a string
*/
public String StringCellValue
{
get
{
IRichTextString str = this.RichStringCellValue;
return str == null ? null : str.String;
}
}
/**
* Get the value of the cell as a XSSFRichTextString
* <p>
* For numeric cells we throw an exception. For blank cells we return an empty string.
* For formula cells we return the pre-calculated value if a string, otherwise an exception
* </p>
* @return the value of the cell as a XSSFRichTextString
*/
public IRichTextString RichStringCellValue
{
get
{
CellType cellType = CellType;
XSSFRichTextString rt;
switch (cellType)
{
case CellType.Blank:
rt = new XSSFRichTextString("");
break;
case CellType.String:
if (_cell.t == ST_CellType.inlineStr)
{
if (_cell.IsSetIs())
{
//string is expressed directly in the cell defInition instead of implementing the shared string table.
rt = new XSSFRichTextString(_cell.@is);
}
else if (_cell.IsSetV())
{
//cached result of a formula
rt = new XSSFRichTextString(_cell.v);
}
else
{
rt = new XSSFRichTextString("");
}
}
else if (_cell.t == ST_CellType.str)
{
//cached formula value
rt = new XSSFRichTextString(_cell.IsSetV() ? _cell.v : "");
}
else
{
if (_cell.IsSetV())
{
int idx = Int32.Parse(_cell.v);
rt = new XSSFRichTextString(_sharedStringSource.GetEntryAt(idx));
}
else
{
rt = new XSSFRichTextString("");
}
}
break;
case CellType.Formula:
CheckFormulaCachedValueType(CellType.String, GetBaseCellType(false));
rt = new XSSFRichTextString(_cell.IsSetV() ? _cell.v : "");
break;
default:
throw TypeMismatch(CellType.String, cellType, false);
}
rt.SetStylesTableReference(_stylesSource);
return rt;
}
}
private static void CheckFormulaCachedValueType(CellType expectedTypeCode, CellType cachedValueType)
{
if (cachedValueType != expectedTypeCode)
{
throw TypeMismatch(expectedTypeCode, cachedValueType, true);
}
}
/**
* Set a string value for the cell.
*
* @param str value to Set the cell to. For formulas we'll Set the formula
* cached string result, for String cells we'll Set its value. For other types we will
* change the cell to a string cell and Set its value.
* If value is null then we will change the cell to a Blank cell.
*/
public void SetCellValue(String str)
{
SetCellValue(str == null ? null : new XSSFRichTextString(str));
}
/**
* Set a string value for the cell.
*
* @param str value to Set the cell to. For formulas we'll Set the 'pre-Evaluated result string,
* for String cells we'll Set its value. For other types we will
* change the cell to a string cell and Set its value.
* If value is null then we will change the cell to a Blank cell.
*/
public void SetCellValue(IRichTextString str)
{
if (str == null || string.IsNullOrEmpty(str.String))
{
SetCellType(CellType.Blank);
return;
}
if (str.Length > SpreadsheetVersion.EXCEL2007.MaxTextLength)
{
throw new ArgumentException("The maximum length of cell contents (text) is 32,767 characters");
}
CellType cellType = CellType;
switch (cellType)
{
case CellType.Formula:
_cell.v = (str.String);
_cell.t= (ST_CellType.str);
break;
default:
if (_cell.t == ST_CellType.inlineStr)
{
//set the 'pre-Evaluated result
_cell.v = str.String;
}
else
{
_cell.t = ST_CellType.s;
XSSFRichTextString rt = (XSSFRichTextString)str;
rt.SetStylesTableReference(_stylesSource);
int sRef = _sharedStringSource.AddEntry(rt.GetCTRst());
_cell.v=sRef.ToString();
}
break;
}
}
/// <summary>
/// Return a formula for the cell, for example, <code>SUM(C4:E4)</code>
/// </summary>
public String CellFormula
{
get
{
CellType cellType = CellType;
if (cellType != CellType.Formula)
throw TypeMismatch(CellType.Formula, cellType, false);
CT_CellFormula f = _cell.f;
if (IsPartOfArrayFormulaGroup && f == null)
{
ICell cell = ((XSSFSheet)Sheet).GetFirstCellInArrayFormula(this);
return cell.CellFormula;
}
if (f.t == ST_CellFormulaType.shared)
{
return ConvertSharedFormula((int)f.si);
}
return f.Value;
}
set
{
SetCellFormula(value);
}
}
/// <summary>
/// Creates a non shared formula from the shared formula counterpart
/// </summary>
/// <param name="si">Shared Group Index</param>
/// <returns>non shared formula created for the given shared formula and this cell</returns>
private String ConvertSharedFormula(int si)
{
XSSFSheet sheet = (XSSFSheet)Sheet;
CT_CellFormula f = sheet.GetSharedFormula(si);
if (f == null) throw new InvalidOperationException(
"Master cell of a shared formula with sid=" + si + " was not found");
String sharedFormula = f.Value;
//Range of cells which the shared formula applies to
String sharedFormulaRange = f.@ref;
CellRangeAddress ref1 = CellRangeAddress.ValueOf(sharedFormulaRange);
int sheetIndex = sheet.Workbook.GetSheetIndex(sheet);
XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.Create(sheet.Workbook);
SharedFormula sf = new SharedFormula(SpreadsheetVersion.EXCEL2007);
Ptg[] ptgs = FormulaParser.Parse(sharedFormula, fpb, FormulaType.Cell, sheetIndex);
Ptg[] fmla = sf.ConvertSharedFormulas(ptgs,
RowIndex - ref1.FirstRow, ColumnIndex - ref1.FirstColumn);
return FormulaRenderer.ToFormulaString(fpb, fmla);
}
/**
* Sets formula for this cell.
* <p>
* Note, this method only Sets the formula string and does not calculate the formula value.
* To Set the precalculated value use {@link #setCellValue(double)} or {@link #setCellValue(String)}
* </p>
*
* @param formula the formula to Set, e.g. <code>"SUM(C4:E4)"</code>.
* If the argument is <code>null</code> then the current formula is Removed.
* @throws NPOI.ss.formula.FormulaParseException if the formula has incorrect syntax or is otherwise invalid
* @throws InvalidOperationException if the operation is not allowed, for example,
* when the cell is a part of a multi-cell array formula
*/
public void SetCellFormula(String formula)
{
if (IsPartOfArrayFormulaGroup)
{
NotifyArrayFormulaChanging();
}
SetFormula(formula, FormulaType.Cell);
}
internal void SetCellArrayFormula(String formula, CellRangeAddress range)
{
SetFormula(formula, FormulaType.Array);
CT_CellFormula cellFormula = _cell.f;
cellFormula.t = (ST_CellFormulaType.array);
cellFormula.@ref = (range.FormatAsString());
}
private void SetFormula(String formula, FormulaType formulaType)
{
IWorkbook wb = _row.Sheet.Workbook;
if (formula == null)
{
((XSSFWorkbook)wb).OnDeleteFormula(this);
if (_cell.IsSetF()) _cell.unsetF();
return;
}
IFormulaParsingWorkbook fpb = XSSFEvaluationWorkbook.Create(wb);
//validate through the FormulaParser
FormulaParser.Parse(formula, fpb, formulaType, wb.GetSheetIndex(this.Sheet));
CT_CellFormula f = new CT_CellFormula();
f.Value = formula;
_cell.f= (f);
if (_cell.IsSetV()) _cell.unsetV();
}
/// <summary>
/// Returns zero-based column index of this cell
/// </summary>
public int ColumnIndex
{
get
{
return this._cellNum;
}
}
/// <summary>
/// Returns zero-based row index of a row in the sheet that contains this cell
/// </summary>
public int RowIndex
{
get
{
return _row.RowNum;
}
}
/// <summary>
/// Returns an A1 style reference to the location of this cell
/// </summary>
/// <returns>A1 style reference to the location of this cell</returns>
public String GetReference()
{
String ref1 = _cell.r;
if (ref1 == null)
{
return new CellReference(this).FormatAsString();
}
return ref1;
}
/// <summary>
/// Return the cell's style.
/// </summary>
public ICellStyle CellStyle
{
get
{
XSSFCellStyle style = null;
if ((null != _stylesSource) && (_stylesSource.NumCellStyles > 0))
{
long idx = _cell.IsSetS() ? _cell.s : 0;
style = _stylesSource.GetStyleAt((int)idx);
}
return style;
}
set
{
if (value == null)
{
if (_cell.IsSetS()) _cell.unsetS();
}
else
{
XSSFCellStyle xStyle = (XSSFCellStyle)value;
xStyle.VerifyBelongsToStylesSource(_stylesSource);
long idx = _stylesSource.PutStyle(xStyle);
_cell.s = (uint)idx;
}
}
}
/// <summary>
/// Return the cell type.
/// </summary>
public CellType CellType
{
get
{
if (_cell.f != null || ((XSSFSheet)Sheet).IsCellInArrayFormulaContext(this))
{
return CellType.Formula;
}
return GetBaseCellType(true);
}
}
/// <summary>
/// Only valid for formula cells
/// </summary>
public CellType CachedFormulaResultType
{
get
{
if (_cell.f == null)
{
throw new InvalidOperationException("Only formula cells have cached results");
}
return GetBaseCellType(false);
}
}
/// <summary>
/// Detect cell type based on the "t" attribute of the CT_Cell bean
/// </summary>
/// <param name="blankCells"></param>
/// <returns></returns>
private CellType GetBaseCellType(bool blankCells)
{
switch (_cell.t)
{
case ST_CellType.b:
return CellType.Boolean;
case ST_CellType.n:
if (!_cell.IsSetV() && blankCells)
{
// ooxml does have a separate cell type of 'blank'. A blank cell Gets encoded as
// (either not present or) a numeric cell with no value Set.
// The formula Evaluator (and perhaps other clients of this interface) needs to
// distinguish blank values which sometimes Get translated into zero and sometimes
// empty string, depending on context
return CellType.Blank;
}
return CellType.Numeric;
case ST_CellType.e:
return CellType.Error;
case ST_CellType.s: // String is in shared strings
case ST_CellType.inlineStr: // String is inline in cell
case ST_CellType.str:
return CellType.String;
default:
throw new InvalidOperationException("Illegal cell type: " + this._cell.t);
}
}
/// <summary>
/// Get the value of the cell as a date.
/// </summary>
public DateTime DateCellValue
{
get
{
CellType cellType = CellType;
if (cellType == CellType.Blank)
{
return DateTime.MinValue;
}
double value = NumericCellValue;
bool date1904 = ((XSSFWorkbook)Sheet.Workbook).IsDate1904();
return DateUtil.GetJavaDate(value, date1904);
}
}
/// <summary>
/// Set a date value for the cell. Excel treats dates as numeric so you will need to format the cell as a date.
/// </summary>
/// <param name="value">the date value to Set this cell to. For formulas we'll set the precalculated value,
/// for numerics we'll Set its value. For other types we will change the cell to a numeric cell and Set its value. </param>
public void SetCellValue(DateTime value)
{
bool date1904 = ((XSSFWorkbook)Sheet.Workbook).IsDate1904();
SetCellValue(DateUtil.GetExcelDate(value, date1904));
}
/// <summary>
/// Returns the error message, such as #VALUE!
/// </summary>
public String ErrorCellString
{
get
{
CellType cellType = GetBaseCellType(true);
if (cellType != CellType.Error) throw TypeMismatch(CellType.Error, cellType, false);
return _cell.v;
}
}
/// <summary>
/// Get the value of the cell as an error code.
/// For strings, numbers, and bools, we throw an exception.
/// For blank cells we return a 0.
/// </summary>
public byte ErrorCellValue
{
get
{
String code = this.ErrorCellString;
if (code == null)
{
return 0;
}
return FormulaError.ForString(code).Code;
}
}
public void SetCellErrorValue(byte errorCode)
{
FormulaError error = FormulaError.ForInt(errorCode);
SetCellErrorValue(error);
}
/// <summary>
/// Set a error value for the cell
/// </summary>
/// <param name="error">the error value to Set this cell to.
/// For formulas we'll Set the precalculated value , for errors we'll set
/// its value. For other types we will change the cell to an error cell and Set its value.
/// </param>
public void SetCellErrorValue(FormulaError error)
{
_cell.t = (ST_CellType.e);
_cell.v = (error.String);
}
/// <summary>
/// Sets this cell as the active cell for the worksheet.
/// </summary>
public void SetAsActiveCell()
{
((XSSFSheet)Sheet).SetActiveCell(GetReference());
}
/// <summary>
/// Blanks this cell. Blank cells have no formula or value but may have styling.
/// This method erases all the data previously associated with this cell.
/// </summary>
private void SetBlank()
{
CT_Cell blank = new CT_Cell();
blank.r = (_cell.r);
if (_cell.IsSetS()) blank.s=(_cell.s);
_cell.Set(blank);
}
/// <summary>
/// Sets column index of this cell
/// </summary>
/// <param name="num"></param>
internal void SetCellNum(int num)
{
CheckBounds(num);
_cellNum = num;
String ref1 = new CellReference(RowIndex, ColumnIndex).FormatAsString();
_cell.r = (ref1);
}
/// <summary>
/// Set the cells type (numeric, formula or string)
/// </summary>
/// <param name="cellType"></param>
public void SetCellType(CellType cellType)
{
CellType prevType = CellType;
if (IsPartOfArrayFormulaGroup)
{
NotifyArrayFormulaChanging();
}
if (prevType == CellType.Formula && cellType != CellType.Formula)
{
((XSSFWorkbook)Sheet.Workbook).OnDeleteFormula(this);
}
switch (cellType)
{
case CellType.Blank:
SetBlank();
break;
case CellType.Boolean:
String newVal = ConvertCellValueToBoolean() ? TRUE_AS_STRING : FALSE_AS_STRING;
_cell.t= (ST_CellType.b);
_cell.v= (newVal);
break;
case CellType.Numeric:
_cell.t = (ST_CellType.n);
break;
case CellType.Error:
_cell.t = (ST_CellType.e);
break;
case CellType.String:
if (prevType != CellType.String)
{
String str = ConvertCellValueToString();
XSSFRichTextString rt = new XSSFRichTextString(str);
rt.SetStylesTableReference(_stylesSource);
int sRef = _sharedStringSource.AddEntry(rt.GetCTRst());
_cell.v= sRef.ToString();
}
_cell.t= (ST_CellType.s);
break;
case CellType.Formula:
if (!_cell.IsSetF())
{
CT_CellFormula f = new CT_CellFormula();
f.Value = "0";
_cell.f = (f);
if (_cell.IsSetT()) _cell.unsetT();
}
break;
default:
throw new ArgumentException("Illegal cell type: " + cellType);
}
if (cellType != CellType.Formula && _cell.IsSetF())
{
_cell.unsetF();
}
}
/// <summary>
/// Returns a string representation of the cell
/// </summary>
/// <returns>Formula cells return the formula string, rather than the formula result.
/// Dates are displayed in dd-MMM-yyyy format
/// Errors are displayed as #ERR<errIdx>
/// </returns>
public override String ToString()
{
switch (CellType)
{
case CellType.Blank:
return "";
case CellType.Boolean:
return BooleanCellValue ? "TRUE" : "FALSE";
case CellType.Error:
return ErrorEval.GetText(ErrorCellValue);
case CellType.Formula:
return CellFormula;
case CellType.Numeric:
if (DateUtil.IsCellDateFormatted(this))
{
FormatBase sdf = new SimpleDateFormat("dd-MMM-yyyy");
return sdf.Format(DateCellValue, CultureInfo.CurrentCulture);
}
return NumericCellValue.ToString();
case CellType.String:
return RichStringCellValue.ToString();
default:
return "Unknown Cell Type: " + CellType;
}
}
/**
* Returns the raw, underlying ooxml value for the cell
* <p>
* If the cell Contains a string, then this value is an index into
* the shared string table, pointing to the actual string value. Otherwise,
* the value of the cell is expressed directly in this element. Cells Containing formulas express
* the last calculated result of the formula in this element.
* </p>
*
* @return the raw cell value as Contained in the underlying CT_Cell bean,
* <code>null</code> for blank cells.
*/
public String GetRawValue()
{
return _cell.v;
}
/// <summary>
/// Used to help format error messages
/// </summary>
/// <param name="cellTypeCode"></param>
/// <returns></returns>
private static String GetCellTypeName(CellType cellTypeCode)
{
switch (cellTypeCode)
{
case CellType.Blank: return "blank";
case CellType.String: return "text";
case CellType.Boolean: return "bool";
case CellType.Error: return "error";
case CellType.Numeric: return "numeric";
case CellType.Formula: return "formula";
}
return "#unknown cell type (" + cellTypeCode + ")#";
}
/**
* Used to help format error messages
*/
private static Exception TypeMismatch(CellType expectedTypeCode, CellType actualTypeCode, bool IsFormulaCell)
{
String msg = "Cannot get a "
+ GetCellTypeName(expectedTypeCode) + " value from a "
+ GetCellTypeName(actualTypeCode) + " " + (IsFormulaCell ? "formula " : "") + "cell";
return new InvalidOperationException(msg);
}
/**
* @throws RuntimeException if the bounds are exceeded.
*/
private static void CheckBounds(int cellIndex)
{
SpreadsheetVersion v = SpreadsheetVersion.EXCEL2007;
int maxcol = SpreadsheetVersion.EXCEL2007.LastColumnIndex;
if (cellIndex < 0 || cellIndex > maxcol)
{
throw new ArgumentException("Invalid column index (" + cellIndex
+ "). Allowable column range for " + v.ToString() + " is (0.."
+ maxcol + ") or ('A'..'" + v.LastColumnName + "')");
}
}
/// <summary>
/// Returns cell comment associated with this cell
/// </summary>
public IComment CellComment
{
get
{
return Sheet.GetCellComment(_row.RowNum, ColumnIndex);
}
set
{
if (value == null)
{
RemoveCellComment();
return;
}
value.Row = (RowIndex);
value.Column = (ColumnIndex);
}
}
/// <summary>
/// Removes the comment for this cell, if there is one.
/// </summary>
public void RemoveCellComment() {
IComment comment = this.CellComment;
if (comment != null)
{
String ref1 = GetReference();
XSSFSheet sh = (XSSFSheet)Sheet;
sh.GetCommentsTable(false).RemoveComment(ref1);
sh.GetVMLDrawing(false).RemoveCommentShape(RowIndex, ColumnIndex);
}
}
/// <summary>
/// Get or set hyperlink associated with this cell
/// If the supplied hyperlink is null on setting, the hyperlink for this cell will be removed.
/// </summary>
public IHyperlink Hyperlink
{
get
{
return ((XSSFSheet)Sheet).GetHyperlink(_row.RowNum, _cellNum);
}
set
{
if (value == null)
{
RemoveHyperlink();
return;
}
XSSFHyperlink link = (XSSFHyperlink)value;
// Assign to us
link.SetCellReference(new CellReference(_row.RowNum, _cellNum).FormatAsString());
// Add to the lists
((XSSFSheet)Sheet).AddHyperlink(link);
}
}
/**
* Removes the hyperlink for this cell, if there is one.
*/
public void RemoveHyperlink()
{
((XSSFSheet)Sheet).RemoveHyperlink(_row.RowNum, _cellNum);
}
/**
* Returns the xml bean containing information about the cell's location (reference), value,
* data type, formatting, and formula
*
* @return the xml bean containing information about this cell
*/
internal CT_Cell GetCTCell()
{
return _cell;
}
/**
* Chooses a new bool value for the cell when its type is changing.<p/>
*
* Usually the caller is calling SetCellType() with the intention of calling
* SetCellValue(bool) straight afterwards. This method only exists to give
* the cell a somewhat reasonable value until the SetCellValue() call (if at all).
* TODO - perhaps a method like SetCellTypeAndValue(int, Object) should be introduced to avoid this
*/
private bool ConvertCellValueToBoolean()
{
CellType cellType = CellType;
if (cellType == CellType.Formula)
{
cellType = GetBaseCellType(false);
}
switch (cellType)
{
case CellType.Boolean:
return TRUE_AS_STRING.Equals(_cell.v);
case CellType.String:
int sstIndex = Int32.Parse(_cell.v);
XSSFRichTextString rt = new XSSFRichTextString(_sharedStringSource.GetEntryAt(sstIndex));
String text = rt.String;
return Boolean.Parse(text);
case CellType.Numeric:
return Double.Parse(_cell.v, CultureInfo.InvariantCulture) != 0;
case CellType.Error:
case CellType.Blank:
return false;
}
throw new RuntimeException("Unexpected cell type (" + cellType + ")");
}
private String ConvertCellValueToString()
{
CellType cellType = CellType;
switch (cellType)
{
case CellType.Blank:
return "";
case CellType.Boolean:
return TRUE_AS_STRING.Equals(_cell.v) ? "TRUE" : "FALSE";
case CellType.String:
int sstIndex = Int32.Parse(_cell.v);
XSSFRichTextString rt = new XSSFRichTextString(_sharedStringSource.GetEntryAt(sstIndex));
return rt.String;
case CellType.Numeric:
case CellType.Error:
return _cell.v;
case CellType.Formula:
// should really Evaluate, but HSSFCell can't call HSSFFormulaEvaluator
// just use cached formula result instead
break;
default:
throw new InvalidOperationException("Unexpected cell type (" + cellType + ")");
}
cellType = GetBaseCellType(false);
String textValue = _cell.v;
switch (cellType)
{
case CellType.Boolean:
if (TRUE_AS_STRING.Equals(textValue))
{
return "TRUE";
}
if (FALSE_AS_STRING.Equals(textValue))
{
return "FALSE";
}
throw new InvalidOperationException("Unexpected bool cached formula value '"
+ textValue + "'.");
case CellType.String:
case CellType.Numeric:
case CellType.Error:
return textValue;
}
throw new InvalidOperationException("Unexpected formula result type (" + cellType + ")");
}
public CellRangeAddress ArrayFormulaRange
{
get
{
XSSFCell cell = ((XSSFSheet)Sheet).GetFirstCellInArrayFormula(this);
if (cell == null)
{
throw new InvalidOperationException("Cell " + GetReference()
+ " is not part of an array formula.");
}
String formulaRef = cell._cell.f.@ref;
return CellRangeAddress.ValueOf(formulaRef);
}
}
public bool IsPartOfArrayFormulaGroup
{
get
{
return ((XSSFSheet)Sheet).IsCellInArrayFormulaContext(this);
}
}
/**
* The purpose of this method is to validate the cell state prior to modification
*
* @see #NotifyArrayFormulaChanging()
*/
internal void NotifyArrayFormulaChanging(String msg)
{
if (IsPartOfArrayFormulaGroup)
{
CellRangeAddress cra = this.ArrayFormulaRange;
if (cra.NumberOfCells > 1)
{
throw new InvalidOperationException(msg);
}
//un-register the Single-cell array formula from the parent XSSFSheet
Row.Sheet.RemoveArrayFormula(this);
}
}
/// <summary>
/// Called when this cell is modified.The purpose of this method is to validate the cell state prior to modification.
/// </summary>
/// <exception cref="InvalidOperationException">if modification is not allowed</exception>
internal void NotifyArrayFormulaChanging()
{
CellReference ref1 = new CellReference(this);
String msg = "Cell " + ref1.FormatAsString() + " is part of a multi-cell array formula. " +
"You cannot change part of an array.";
NotifyArrayFormulaChanging(msg);
}
#region ICell Members
public bool IsMergedCell
{
get {
return this.Sheet.IsMergedRegion(new CellRangeAddress(this.RowIndex, this.RowIndex, this.ColumnIndex, this.ColumnIndex));
}
}
#endregion
public ICell CopyCellTo(int targetIndex)
{
return CellUtil.CopyCell(this.Row, this.ColumnIndex, targetIndex);
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Media;
using Microsoft.PythonTools.Analysis;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Intellisense;
using Microsoft.PythonTools.Parsing;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.PythonTools.Refactoring {
using AP = AnalysisProtocol;
/// <summary>
/// Provides a view model for the ExtractMethodRequest class.
/// </summary>
sealed class ExtractMethodRequestView : INotifyPropertyChanged {
private readonly ExtractedMethodCreator _previewer;
private static readonly Regex Python2IdentifierRegex = new Regex("^[a-zA-Z_][a-zA-Z0-9_]*$");
private const string _defaultName = "method_name";
private string _name;
private readonly FontFamily _previewFontFamily;
private bool _isValid;
private readonly ReadOnlyCollection<ScopeWrapper> _targetScopes;
private readonly ScopeWrapper _defaultScope;
private readonly IServiceProvider _serviceProvider;
private ScopeWrapper _targetScope;
private ReadOnlyCollection<ClosureVariable> _closureVariables;
private string _previewText;
/// <summary>
/// Create an ExtractMethodRequestView with default values.
/// </summary>
public ExtractMethodRequestView(IServiceProvider serviceProvider, ExtractedMethodCreator previewer) {
_previewer = previewer;
_serviceProvider = serviceProvider;
var extraction = _previewer.LastExtraction;
AP.ScopeInfo lastClass = null;
for (int i = extraction.scopes.Length - 1; i >= 0; i--) {
if (extraction.scopes[i].type == "class") {
lastClass = extraction.scopes[i];
break;
}
}
var targetScopes = new List<ScopeWrapper>();
foreach (var scope in extraction.scopes) {
if (!(scope.type == "class") || scope == lastClass) {
var wrapper = new ScopeWrapper(scope);
if (scope == lastClass) {
_defaultScope = wrapper;
}
targetScopes.Add(wrapper);
}
}
_targetScopes = new ReadOnlyCollection<ScopeWrapper>(targetScopes);
if (_defaultScope == null && _targetScopes.Any()) {
_defaultScope = _targetScopes[0];
}
_previewFontFamily = new FontFamily(GetTextEditorFont());
PropertyChanged += ExtractMethodRequestView_PropertyChanged;
// Access properties rather than underlying variables to ensure dependent properties
// are also updated.
Name = _defaultName;
TargetScope = _defaultScope;
}
/// <summary>
/// Create an ExtractMethodRequestView with values taken from template.
/// </summary>
public ExtractMethodRequestView(IServiceProvider serviceProvider, ExtractedMethodCreator previewer, ExtractMethodRequest template)
: this(serviceProvider, previewer) {
// Access properties rather than underlying variables to ensure dependent properties
// are also updated.
Name = template.Name;
TargetScope = template.TargetScope;
foreach (var cv in ClosureVariables) {
cv.IsClosure = !template.Parameters.Contains(cv.Name);
}
}
/// <summary>
/// Returns an ExtractMethodRequestView with the values set from the view model.
/// </summary>
public ExtractMethodRequest GetRequest() {
if (IsValid) {
string[] parameters;
if (ClosureVariables != null) {
parameters = ClosureVariables.Where(cv => !cv.IsClosure).Select(cv => cv.Name).ToArray();
} else {
parameters = new string[0];
}
return new ExtractMethodRequest(TargetScope ?? _defaultScope,
Name ?? _defaultName,
parameters);
} else {
return null;
}
}
/// <summary>
/// The name of the new method which should be created
/// </summary>
public string Name {
get {
return _name;
}
set {
if (_name != value) {
_name = value;
OnPropertyChanged("Name");
}
}
}
/// <summary>
/// The font family to display preview text using.
/// </summary>
public FontFamily PreviewFontFamily {
get {
return _previewFontFamily;
}
}
/// <summary>
/// True if the name is a valid Python name; otherwise, false.
/// </summary>
public bool IsValid {
get {
return _isValid;
}
private set {
if (_isValid != value) {
_isValid = value;
OnPropertyChanged("IsValid");
}
}
}
/// <summary>
/// The target scope to extract the method to.
/// </summary>
public ScopeWrapper TargetScope {
get {
return _targetScope;
}
set {
if (_targetScope != value) {
_targetScope = value;
OnPropertyChanged("TargetScope");
List<ClosureVariable> closureVariables = new List<ClosureVariable>();
if (_targetScope != null) {
foreach (var variable in _previewer.LastExtraction.variables) {
if (_targetScope.Scope.variables.Contains(variable)) {
// we can either close over or pass these in as parameters, add them to the list
closureVariables.Add(new ClosureVariable(variable));
}
}
closureVariables.Sort();
}
ClosureVariables = new ReadOnlyCollection<ClosureVariable>(closureVariables);
}
}
}
/// <summary>
/// The set of potential scopes to extract the method to.
/// </summary>
public ReadOnlyCollection<ScopeWrapper> TargetScopes {
get {
return _targetScopes;
}
}
/// <summary>
/// The list of closure/parameter settings for the current TargetScope.
/// </summary>
public ReadOnlyCollection<ClosureVariable> ClosureVariables {
get {
return _closureVariables;
}
private set {
if (_closureVariables != value) {
if (_closureVariables != null) {
foreach (var cv in _closureVariables) {
cv.PropertyChanged -= ClosureVariable_PropertyChanged;
}
}
_closureVariables = value;
if (_closureVariables != null) {
foreach (var cv in ClosureVariables) {
cv.PropertyChanged += ClosureVariable_PropertyChanged;
}
}
OnPropertyChanged("ClosureVariables");
UpdatePreview();
}
}
}
/// <summary>
/// Receives our own property change events to update IsValid.
/// </summary>
void ExtractMethodRequestView_PropertyChanged(object sender, PropertyChangedEventArgs e) {
if (e.PropertyName != "IsValid") {
IsValid = (TargetScope != null) && IsValidPythonIdentifier(Name, _previewer.PythonVersion);
}
if (e.PropertyName != "PreviewText") {
UpdatePreview();
}
}
internal static bool IsValidPythonIdentifier(string identifier, PythonLanguageVersion pythonVersion) {
if (String.IsNullOrEmpty(identifier) || PythonKeywords.IsKeyword(identifier, pythonVersion)) {
return false;
}
//Python2 identifiers are only certain ASCII characters
if (pythonVersion < PythonLanguageVersion.V30) {
return Python2IdentifierRegex.IsMatch(identifier);
}
//Python3 identifiers can include unicode characters
if (!Tokenizer.IsIdentifierStartChar(identifier[0])) {
return false;
}
return identifier.Skip(1).All(Tokenizer.IsIdentifierChar);
}
/// <summary>
/// Propagate property change events from ClosureVariable.
/// </summary>
void ClosureVariable_PropertyChanged(object sender, PropertyChangedEventArgs e) {
OnPropertyChanged("ClosureVariables");
}
/// <summary>
/// Updates PreviewText based on the current settings.
/// </summary>
private void UpdatePreview() {
var info = GetRequest();
if (info != null) {
UpdatePreviewAsync(info).DoNotWait();
} else {
PreviewText = Strings.ExtractMethod_InvalidMethodName;
}
}
private async Task UpdatePreviewAsync(ExtractMethodRequest info) {
try {
var response = await _previewer.GetExtractionResult(info);
PreviewText = response.methodBody;
}
catch (Exception ex) {
Debug.Fail(ex.ToUnhandledExceptionMessage(GetType()));
PreviewText = Strings.ExtractMethod_FailedToGetPreview;
}
}
/// <summary>
/// An example of how the extracted method will appear.
/// </summary>
public string PreviewText {
get {
return _previewText;
}
private set {
if (_previewText != value) {
_previewText = value;
OnPropertyChanged("PreviewText");
}
}
}
/// <summary>
/// Returns the name of the font set by the user for editor windows.
/// </summary>
private string GetTextEditorFont() {
try {
var store = (IVsFontAndColorStorage)_serviceProvider.GetService(typeof(SVsFontAndColorStorage));
Guid textEditorCategory = new Guid(FontsAndColorsCategory.TextEditor);
if (store != null && store.OpenCategory(ref textEditorCategory,
(uint)(__FCSTORAGEFLAGS.FCSF_LOADDEFAULTS | __FCSTORAGEFLAGS.FCSF_READONLY)) == VSConstants.S_OK) {
try {
FontInfo[] info = new FontInfo[1];
store.GetFont(null, info);
if (info[0].bstrFaceName != null) {
return info[0].bstrFaceName;
}
}
finally {
store.CloseCategory();
}
}
}
catch { }
return "Consolas";
}
private void OnPropertyChanged(string propertyName) {
var evt = PropertyChanged;
if (evt != null) {
evt(this, new PropertyChangedEventArgs(propertyName));
}
}
/// <summary>
/// Raised when the value of a property changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Provides a view model for the closure/parameter state of a variable.
/// </summary>
public sealed class ClosureVariable : INotifyPropertyChanged, IComparable<ClosureVariable> {
private readonly string _name;
private readonly string _displayName;
private bool _isClosure;
public ClosureVariable(string name) {
_name = name;
_displayName = name.Replace("_", "__");
_isClosure = true;
}
/// <summary>
/// The name of the variable.
/// </summary>
public string Name {
get { return _name; }
}
/// <summary>
/// The name of the variable with
/// </summary>
public string DisplayName {
get { return _displayName; }
}
/// <summary>
/// True to close over the variable; otherwise, false to pass it as a parameter.
/// </summary>
public bool IsClosure {
get { return _isClosure; }
set {
if (_isClosure != value) {
_isClosure = value;
OnPropertyChanged("IsClosure");
}
}
}
private void OnPropertyChanged(string propertyName) {
var evt = PropertyChanged;
if (evt != null) {
evt(this, new PropertyChangedEventArgs(propertyName));
}
}
/// <summary>
/// Raised when the value of a property changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Compares two ClosureVariable instances by name.
/// </summary>
public int CompareTo(ClosureVariable other) {
return string.CompareOrdinal(Name, other?.Name ?? "");
}
}
}
class ScopeWrapper {
public readonly AP.ScopeInfo Scope;
public ScopeWrapper(AP.ScopeInfo scope) {
Scope = scope;
}
public string Name {
get {
return Scope.name;
}
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using CookComputing.XmlRpc;
using Newtonsoft.Json;
namespace XenAPI
{
public partial class Session : XenObject<Session>
{
public const int STANDARD_TIMEOUT = 24 * 60 * 60 * 1000;
/// <summary>
/// This string is used as the HTTP UserAgent for each request.
/// </summary>
public static string UserAgent = string.Format("XenAPI/{0}", Helper.APIVersionString(API_Version.LATEST));
/// <summary>
/// If null, no proxy is used, otherwise this proxy is used for each request.
/// </summary>
public static IWebProxy Proxy = null;
public API_Version APIVersion = API_Version.API_1_1;
public object Tag;
// Filled in after successful session_login_with_password for version 1.6 or newer connections
private bool _isLocalSuperuser = true;
private XenRef<Subject> _subject = null;
private string _userSid = null;
private string[] permissions = null;
private List<Role> roles = new List<Role>();
/// <summary>
/// Applies only to API 2.6 (ely) or 2.8 (inverness) and above.
/// </summary>
public Action<Session> XmlRpcToJsonRpcInvoker = SwitchToJsonRpcBackend;
#region Constructors
public Session(int timeout, string url)
{
proxy = XmlRpcProxyGen.Create<Proxy>();
proxy.Url = url;
proxy.NonStandard = XmlRpcNonStandard.All;
proxy.Timeout = timeout;
proxy.UseIndentation = false;
proxy.UserAgent = UserAgent;
proxy.KeepAlive = true;
proxy.Proxy = Proxy;
}
public Session(string url)
: this(STANDARD_TIMEOUT, url)
{
}
public Session(int timeout, string host, int port)
: this(timeout, GetUrl(host, port))
{
}
public Session(string host, int port)
: this(STANDARD_TIMEOUT, host, port)
{
}
public Session(string url, string opaqueRef)
: this(url)
{
opaque_ref = opaqueRef;
SetAPIVersion();
if (XmlRpcToJsonRpcInvoker != null)
XmlRpcToJsonRpcInvoker(this);
SetADDetails();
SetRbacPermissions();
}
/// <summary>
/// Create a new Session instance, using the given instance and timeout. The connection details and Xen-API session handle will be
/// copied from the given instance, but a new connection will be created. Use this if you want a duplicate connection to a host,
/// for example when you need to cancel an operation that is blocking the primary connection.
/// </summary>
/// <param name="session"></param>
/// <param name="timeout"></param>
public Session(Session session, int timeout)
: this(session.Url, timeout)
{
opaque_ref = session.opaque_ref;
APIVersion = session.APIVersion;
_isLocalSuperuser = session.IsLocalSuperuser;
_subject = session._subject;
_userSid = session._userSid;
}
#endregion
// Used after VDI.open_database
public static Session get_record(Session session, string _session)
{
Session newSession = new Session(session.proxy.Url);
newSession.opaque_ref = _session;
newSession.SetAPIVersion();
if (newSession.XmlRpcToJsonRpcInvoker != null)
newSession.XmlRpcToJsonRpcInvoker(newSession);
return newSession;
}
/// <summary>
/// Applies only to API 1.6 (george) and above.
/// </summary>
private void SetADDetails()
{
if (APIVersion < API_Version.API_1_6)
return;
_isLocalSuperuser = get_is_local_superuser();
if (IsLocalSuperuser)
return;
_subject = get_subject();
_userSid = get_auth_user_sid();
// Cache the details of this user to avoid making server calls later
// For example, some users get access to the pool through a group subject and will not be in the main cache
UserDetails.UpdateDetails(_userSid, this);
}
/// <summary>
/// Applies only to API 1.7 (midnight-ride) and above.
/// Older versions have no RBAC, only AD.
/// </summary>
private void SetRbacPermissions()
{
if (APIVersion < API_Version.API_1_7)
return;
// allRoles will contain every role on the server, permissions contains the subset of those that are available to this session.
permissions = Session.get_rbac_permissions(this, opaque_ref);
Dictionary<XenRef<Role>, Role> allRoles = Role.get_all_records(this);
// every Role object is either a single api call (a permission) or has subroles and contains permissions through its descendants.
// We take out the parent Roles (VM-Admin etc.) into the Session.Roles field
foreach (string s in permissions)
{
foreach (XenRef<Role> xr in allRoles.Keys)
{
Role r = allRoles[xr];
if (r.subroles.Count > 0 && r.name_label == s)
{
r.opaque_ref = xr.opaque_ref;
roles.Add(r);
break;
}
}
}
}
/// <summary>
/// Retrieves the current users details from the UserDetails map. These values are only updated when a new session is created.
/// </summary>
public virtual UserDetails CurrentUserDetails
{
get
{
return _userSid == null ? null : UserDetails.Sid_To_UserDetails[_userSid];
}
}
public override void UpdateFrom(Session update)
{
throw new Exception("The method or operation is not implemented.");
}
public override string SaveChanges(Session session, string _serverOpaqueRef, Session serverObject)
{
throw new Exception("The method or operation is not implemented.");
}
public Proxy proxy { get; private set; }
public JsonRpcClient JsonRpcClient { get; private set; }
[Obsolete("Use opaque_ref instead.")]
public string uuid
{
get { return opaque_ref; }
}
public string Url
{
get
{
if (JsonRpcClient != null)
return JsonRpcClient.Url;
else
return proxy.Url;
}
}
public string ConnectionGroupName
{
get
{
if (JsonRpcClient != null)
return JsonRpcClient.ConnectionGroupName;
else
return proxy.ConnectionGroupName;
}
set
{
if (JsonRpcClient != null)
JsonRpcClient.ConnectionGroupName = value;
else
proxy.ConnectionGroupName = value;
}
}
/// <summary>
/// Always true before API version 1.6.
/// </summary>
public virtual bool IsLocalSuperuser
{
get { return _isLocalSuperuser; }
}
/// <summary>
/// The OpaqueRef for the Subject under whose authority the current user is logged in;
/// may correspond to either a group or a user.
/// Null if IsLocalSuperuser is true.
/// </summary>
[JsonConverter(typeof(XenRefConverter<VDI>))]
public XenRef<Subject> Subject
{
get { return _subject; }
}
/// <summary>
/// The Active Directory SID of the currently logged-in user.
/// Null if IsLocalSuperuser is true.
/// </summary>
public string UserSid
{
get { return _userSid; }
}
/// <summary>
/// All permissions associated with the session at the time of log in. This is the list xapi uses until the session is logged out;
/// even if the permitted roles change on the server side, they don't apply until the next session.
/// </summary>
public string[] Permissions
{
get { return permissions; }
}
/// <summary>
/// All roles associated with the session at the time of log in. Do not rely on roles for determining what a user can do,
/// instead use Permissions. This list should only be used for UI purposes.
/// </summary>
[JsonConverter(typeof(XenRefListConverter<Role>))]
public List<Role> Roles
{
get { return roles; }
}
public void login_with_password(string username, string password)
{
if (JsonRpcClient != null)
opaque_ref = JsonRpcClient.session_login_with_password(username, password);
else
opaque_ref = proxy.session_login_with_password(username, password).parse();
SetAPIVersion();
if (XmlRpcToJsonRpcInvoker != null)
XmlRpcToJsonRpcInvoker(this);
}
public void login_with_password(string username, string password, string version)
{
try
{
if (JsonRpcClient != null)
opaque_ref = JsonRpcClient.session_login_with_password(username, password, version);
else
opaque_ref = proxy.session_login_with_password(username, password, version).parse();
SetAPIVersion();
if (XmlRpcToJsonRpcInvoker != null)
XmlRpcToJsonRpcInvoker(this);
SetADDetails();
SetRbacPermissions();
}
catch (Failure exn)
{
if (exn.ErrorDescription[0] == Failure.MESSAGE_PARAMETER_COUNT_MISMATCH)
{
// Call the 1.1 version instead.
login_with_password(username, password);
}
else
{
throw;
}
}
}
public void login_with_password(string username, string password, string version, string originator)
{
try
{
if (JsonRpcClient != null)
opaque_ref = JsonRpcClient.session_login_with_password(username, password, version, originator);
else
opaque_ref = proxy.session_login_with_password(username, password, version, originator).parse();
SetAPIVersion();
if (XmlRpcToJsonRpcInvoker != null)
XmlRpcToJsonRpcInvoker(this);
SetADDetails();
SetRbacPermissions();
}
catch (Failure exn)
{
if (exn.ErrorDescription[0] == Failure.MESSAGE_PARAMETER_COUNT_MISMATCH)
{
// Call the pre-2.0 version instead.
login_with_password(username, password, version);
}
else
{
throw;
}
}
}
public void login_with_password(string username, string password, API_Version version)
{
login_with_password(username, password, Helper.APIVersionString(version));
}
private void SetAPIVersion()
{
Dictionary<XenRef<Pool>, Pool> pools = Pool.get_all_records(this);
foreach (Pool pool in pools.Values)
{
Host host = Host.get_record(this, pool.master);
APIVersion = Helper.GetAPIVersion(host.API_version_major, host.API_version_minor);
break;
}
}
/// <summary>
/// Applies only to API 2.6 (ely) or 2.8 (inverness) and above.
/// </summary>
private static void SwitchToJsonRpcBackend(Session session)
{
session.JsonRpcClient = null;
bool isELy = session.APIVersion == API_Version.API_2_6;
bool isInvernessOrAbove = session.APIVersion >= API_Version.API_2_8;
if (isELy || isInvernessOrAbove)
{
session.JsonRpcClient = new JsonRpcClient(session.proxy.Url)
{
ConnectionGroupName = session.proxy.ConnectionGroupName,
Timeout = session.proxy.Timeout,
KeepAlive = session.proxy.KeepAlive,
UserAgent = session.proxy.UserAgent,
WebProxy = session.proxy.Proxy
};
if (isInvernessOrAbove)
session.JsonRpcClient.JsonRpcVersion = JsonRpcVersion.v2;
session.proxy = null;
}
}
public void slave_local_login_with_password(string username, string password)
{
if (JsonRpcClient != null)
opaque_ref = JsonRpcClient.session_slave_local_login_with_password(username, password);
else
opaque_ref = proxy.session_slave_local_login_with_password(username, password).parse();
//assume the latest API
APIVersion = API_Version.LATEST;
}
public void logout()
{
logout(this);
}
/// <summary>
/// Log out of the given session2, using this session for the connection.
/// </summary>
/// <param name="session2">The session to log out</param>
public void logout(Session session2)
{
logout(session2.opaque_ref);
session2.opaque_ref = null;
}
/// <summary>
/// Log out of the session with the given reference, using this session for the connection.
/// </summary>
/// <param name="_self">The session to log out</param>
public void logout(string _self)
{
if (_self == null)
return;
if (JsonRpcClient != null)
JsonRpcClient.session_logout(_self);
else
proxy.session_logout(_self).parse();
}
public void local_logout()
{
local_logout(this);
}
public void local_logout(Session session2)
{
local_logout(session2.opaque_ref);
session2.opaque_ref = null;
}
public void local_logout(string opaqueRef)
{
if (opaqueRef == null)
return;
if (JsonRpcClient != null)
JsonRpcClient.session_local_logout(opaqueRef);
else
proxy.session_local_logout(opaqueRef).parse();
}
public void change_password(string oldPassword, string newPassword)
{
change_password(this, oldPassword, newPassword);
}
/// <summary>
/// Change the password on the given session2, using this session for the connection.
/// </summary>
/// <param name="session2">The session to change</param>
/// <param name="oldPassword"></param>
/// <param name="newPassword"></param>
public void change_password(Session session2, string oldPassword, string newPassword)
{
if (JsonRpcClient != null)
JsonRpcClient.session_change_password(session2.opaque_ref, oldPassword, newPassword);
else
proxy.session_change_password(session2.opaque_ref, oldPassword, newPassword).parse();
}
public string get_this_host()
{
return get_this_host(this, opaque_ref);
}
public static string get_this_host(Session session, string _self)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.session_get_this_host(session.opaque_ref, _self ?? "");
else
return session.proxy.session_get_this_host(session.opaque_ref, _self ?? "").parse();
}
public string get_this_user()
{
return get_this_user(this, opaque_ref);
}
public static string get_this_user(Session session, string _self)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.session_get_this_user(session.opaque_ref, _self ?? "");
else
return session.proxy.session_get_this_user(session.opaque_ref, _self ?? "").parse();
}
public bool get_is_local_superuser()
{
return get_is_local_superuser(this, opaque_ref);
}
public static bool get_is_local_superuser(Session session, string _self)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.session_get_is_local_superuser(session.opaque_ref, _self ?? "");
else
return session.proxy.session_get_is_local_superuser(session.opaque_ref, _self ?? "").parse();
}
public static string[] get_rbac_permissions(Session session, string _self)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.session_get_rbac_permissions(session.opaque_ref, _self ?? "");
else
return session.proxy.session_get_rbac_permissions(session.opaque_ref, _self ?? "").parse();
}
public DateTime get_last_active()
{
return get_last_active(this, opaque_ref);
}
public static DateTime get_last_active(Session session, string _self)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.session_get_last_active(session.opaque_ref, _self ?? "");
else
return session.proxy.session_get_last_active(session.opaque_ref, _self ?? "").parse();
}
public bool get_pool()
{
return get_pool(this, opaque_ref);
}
public static bool get_pool(Session session, string _self)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.session_get_pool(session.opaque_ref, _self ?? "");
else
return session.proxy.session_get_pool(session.opaque_ref, _self ?? "").parse();
}
public XenRef<Subject> get_subject()
{
return get_subject(this, opaque_ref);
}
public static XenRef<Subject> get_subject(Session session, string _self)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.session_get_subject(session.opaque_ref, _self ?? "");
else
return new XenRef<Subject>(session.proxy.session_get_subject(session.opaque_ref, _self ?? "").parse());
}
public string get_auth_user_sid()
{
return get_auth_user_sid(this, opaque_ref);
}
public static string get_auth_user_sid(Session session, string _self)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.session_get_auth_user_sid(session.opaque_ref, _self ?? "");
else
return session.proxy.session_get_auth_user_sid(session.opaque_ref, _self ?? "").parse();
}
#region AD SID enumeration and bootout
public string[] get_all_subject_identifiers()
{
return get_all_subject_identifiers(this);
}
public static string[] get_all_subject_identifiers(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.session_get_all_subject_identifiers(session.opaque_ref);
else
return session.proxy.session_get_all_subject_identifiers(session.opaque_ref).parse();
}
public XenRef<Task> async_get_all_subject_identifiers()
{
return async_get_all_subject_identifiers(this);
}
public static XenRef<Task> async_get_all_subject_identifiers(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_session_get_all_subject_identifiers(session.opaque_ref);
else
return XenRef<Task>.Create(session.proxy.async_session_get_all_subject_identifiers(session.opaque_ref).parse());
}
public string logout_subject_identifier(string subject_identifier)
{
return logout_subject_identifier(this, subject_identifier);
}
public static string logout_subject_identifier(Session session, string subject_identifier)
{
if (session.JsonRpcClient != null)
{
session.JsonRpcClient.session_logout_subject_identifier(session.opaque_ref, subject_identifier);
return string.Empty;
}
else
return session.proxy.session_logout_subject_identifier(session.opaque_ref, subject_identifier).parse();
}
public XenRef<Task> async_logout_subject_identifier(string subject_identifier)
{
return async_logout_subject_identifier(this, subject_identifier);
}
public static XenRef<Task> async_logout_subject_identifier(Session session, string subject_identifier)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_session_logout_subject_identifier(session.opaque_ref, subject_identifier);
else
return XenRef<Task>.Create(session.proxy.async_session_logout_subject_identifier(session.opaque_ref, subject_identifier).parse());
}
#endregion
#region other_config stuff
public Dictionary<string, string> get_other_config()
{
return get_other_config(this, opaque_ref);
}
public static Dictionary<string, string> get_other_config(Session session, string _self)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.session_get_other_config(session.opaque_ref, _self ?? "");
else
return Maps.convert_from_proxy_string_string(session.proxy.session_get_other_config(session.opaque_ref, _self ?? "").parse());
}
public void set_other_config(Dictionary<string, string> _other_config)
{
set_other_config(this, opaque_ref, _other_config);
}
public static void set_other_config(Session session, string _self, Dictionary<string, string> _other_config)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.session_set_other_config(session.opaque_ref, _self ?? "", _other_config);
else
session.proxy.session_set_other_config(session.opaque_ref, _self ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
public void add_to_other_config(string _key, string _value)
{
add_to_other_config(this, opaque_ref, _key, _value);
}
public static void add_to_other_config(Session session, string _self, string _key, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.session_add_to_other_config(session.opaque_ref, _self ?? "", _key ?? "", _value ?? "");
else
session.proxy.session_add_to_other_config(session.opaque_ref, _self ?? "", _key ?? "", _value ?? "").parse();
}
public void remove_from_other_config(string _key)
{
remove_from_other_config(this, opaque_ref, _key);
}
public static void remove_from_other_config(Session session, string _self, string _key)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.session_remove_from_other_config(session.opaque_ref, _self ?? "", _key ?? "");
else
session.proxy.session_remove_from_other_config(session.opaque_ref, _self ?? "", _key ?? "").parse();
}
#endregion
static Session()
{
//ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;
}
private static string GetUrl(string hostname, int port)
{
return string.Format("{0}://{1}:{2}", port == 8080 || port == 80 ? "http" : "https", hostname, port);
}
private static bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
return true;
}
}
}
| |
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// 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 Moq;
using NakedFramework.Architecture.Adapter;
using NakedFramework.Architecture.Facet;
using NakedFramework.Architecture.Resolve;
using NakedFramework.Architecture.Spec;
using NakedFramework.Core.Resolve;
using NUnit.Framework;
namespace NakedFramework.Core.Test.Resolve;
[TestFixture]
public class ResolveStateTest {
private static void ExpectException(Action x) {
try {
x();
Assert.Fail();
}
catch (Exception) {
Assert.IsTrue(true);
}
}
private static void ExpectNoException(Action x) {
try {
x();
}
catch (Exception) {
Assert.Fail();
}
}
private static IResolveStateMachine NewSm() {
var mockAdapter = new Mock<INakedObjectAdapter>();
var testAdapter = mockAdapter.Object;
var mockSpecification = new Mock<IObjectSpec>();
var testSpecification = mockSpecification.Object;
var mockFacet = new Mock<ITestCallbackFacet>();
var testFacet = mockFacet.Object;
mockFacet.Setup(f => f.Invoke(null, null));
mockAdapter.Setup(a => a.Spec).Returns(testSpecification);
mockSpecification.Setup(s => s.GetFacet(null)).Returns(testFacet);
mockSpecification.Setup(s => s.GetFacet<ILoadingCallbackFacet>()).Returns(testFacet);
mockSpecification.Setup(s => s.GetFacet<ILoadedCallbackFacet>()).Returns(testFacet);
return new ResolveStateMachine(testAdapter, null);
}
private static IResolveStateMachine GhostSM() {
var sm = NewSm();
sm.Handle(Events.InitializePersistentEvent);
return sm;
}
private static IResolveStateMachine TransientSm() {
var sm = NewSm();
sm.Handle(Events.InitializeTransientEvent);
return sm;
}
private static IResolveStateMachine ResolvingPartSm() {
var sm = GhostSM();
sm.Handle(Events.StartPartResolvingEvent);
return sm;
}
private static IResolveStateMachine ResolvedPartSm() {
var sm = ResolvingPartSm();
sm.Handle(Events.EndPartResolvingEvent);
return sm;
}
private static IResolveStateMachine ResolvingSm() {
var sm = GhostSM();
sm.Handle(Events.StartResolvingEvent);
return sm;
}
private static IResolveStateMachine ResolvedSm() {
var sm = ResolvingSm();
sm.Handle(Events.EndResolvingEvent);
return sm;
}
private static IResolveStateMachine UpdatingSm() {
var sm = ResolvedSm();
sm.Handle(Events.StartUpdatingEvent);
return sm;
}
private static IResolveStateMachine SerializingPartResolvedSm() {
var sm = ResolvedPartSm();
sm.Handle(Events.StartSerializingEvent);
return sm;
}
private static IResolveStateMachine SerializingTransientSm() {
var sm = TransientSm();
sm.Handle(Events.StartSerializingEvent);
return sm;
}
private static IResolveStateMachine SerializingResolvedSm() {
var sm = ResolvedSm();
sm.Handle(Events.StartSerializingEvent);
return sm;
}
[Test]
public void InvalidChangesFromGhost() {
ExpectException(() => GhostSM().Handle(Events.InitializePersistentEvent));
ExpectException(() => GhostSM().Handle(Events.EndPartResolvingEvent));
ExpectException(() => GhostSM().Handle(Events.EndResolvingEvent));
ExpectException(() => GhostSM().Handle(Events.InitializeTransientEvent));
ExpectException(() => GhostSM().Handle(Events.InitializeAggregateEvent));
}
[Test]
public void InvalidChangesFromNew() {
ExpectException(() => NewSm().Handle(Events.EndPartResolvingEvent));
ExpectException(() => NewSm().Handle(Events.EndResolvingEvent));
ExpectException(() => NewSm().Handle(Events.StartResolvingEvent));
ExpectException(() => NewSm().Handle(Events.StartPartResolvingEvent));
ExpectException(() => NewSm().Handle(Events.DestroyEvent));
ExpectException(() => NewSm().Handle(Events.StartUpdatingEvent));
ExpectException(() => NewSm().Handle(Events.StartSerializingEvent));
}
[Test]
public void InvalidChangesFromPartResolved() {
ExpectException(() => ResolvedPartSm().Handle(Events.InitializePersistentEvent));
ExpectException(() => ResolvedPartSm().Handle(Events.EndPartResolvingEvent));
ExpectException(() => ResolvedPartSm().Handle(Events.EndResolvingEvent));
ExpectException(() => ResolvedPartSm().Handle(Events.InitializeTransientEvent));
}
[Test]
public void InvalidChangesFromResolved() {
ExpectException(() => ResolvedSm().Handle(Events.EndPartResolvingEvent));
ExpectException(() => ResolvedSm().Handle(Events.EndResolvingEvent));
ExpectException(() => ResolvedSm().Handle(Events.StartResolvingEvent));
ExpectException(() => ResolvedSm().Handle(Events.StartPartResolvingEvent));
ExpectException(() => ResolvedSm().Handle(Events.InitializeTransientEvent));
}
[Test]
public void InvalidChangesFromResolving() {
ExpectException(() => ResolvingSm().Handle(Events.InitializePersistentEvent));
ExpectException(() => ResolvingSm().Handle(Events.EndPartResolvingEvent));
ExpectException(() => ResolvingSm().Handle(Events.StartResolvingEvent));
ExpectException(() => ResolvingSm().Handle(Events.StartPartResolvingEvent));
ExpectException(() => ResolvingSm().Handle(Events.InitializeTransientEvent));
ExpectException(() => ResolvingSm().Handle(Events.StartUpdatingEvent));
ExpectException(() => ResolvingSm().Handle(Events.StartSerializingEvent));
ExpectException(() => ResolvingSm().Handle(Events.StartSerializingEvent));
ExpectException(() => ResolvingSm().Handle(Events.StartSerializingEvent));
ExpectException(() => ResolvingSm().Handle(Events.StartSerializingEvent));
ExpectException(() => ResolvingSm().Handle(Events.InitializeAggregateEvent));
}
[Test]
public void InvalidChangesFromResolvingPart() {
ExpectException(() => ResolvingPartSm().Handle(Events.InitializePersistentEvent));
ExpectException(() => ResolvingPartSm().Handle(Events.StartResolvingEvent));
ExpectException(() => ResolvingPartSm().Handle(Events.StartPartResolvingEvent));
ExpectException(() => ResolvingPartSm().Handle(Events.InitializeTransientEvent));
ExpectException(() => ResolvingPartSm().Handle(Events.DestroyEvent));
ExpectException(() => ResolvingPartSm().Handle(Events.StartUpdatingEvent));
ExpectException(() => ResolvingPartSm().Handle(Events.StartSerializingEvent));
ExpectException(() => ResolvingPartSm().Handle(Events.StartSerializingEvent));
ExpectException(() => ResolvingPartSm().Handle(Events.StartSerializingEvent));
ExpectException(() => ResolvingPartSm().Handle(Events.StartSerializingEvent));
ExpectException(() => ResolvingPartSm().Handle(Events.InitializeAggregateEvent));
}
[Test]
public void InvalidChangesFromSerializingPartResolved() {
ExpectException(() => SerializingPartResolvedSm().Handle(Events.InitializePersistentEvent));
ExpectException(() => SerializingPartResolvedSm().Handle(Events.EndResolvingEvent));
ExpectException(() => SerializingPartResolvedSm().Handle(Events.StartResolvingEvent));
ExpectException(() => SerializingPartResolvedSm().Handle(Events.StartPartResolvingEvent));
ExpectException(() => SerializingPartResolvedSm().Handle(Events.InitializeTransientEvent));
ExpectException(() => SerializingPartResolvedSm().Handle(Events.DestroyEvent));
ExpectException(() => SerializingPartResolvedSm().Handle(Events.StartUpdatingEvent));
ExpectException(() => SerializingPartResolvedSm().Handle(Events.StartSerializingEvent));
ExpectException(() => SerializingPartResolvedSm().Handle(Events.StartSerializingEvent));
ExpectException(() => SerializingPartResolvedSm().Handle(Events.StartSerializingEvent));
ExpectException(() => SerializingPartResolvedSm().Handle(Events.StartSerializingEvent));
ExpectException(() => SerializingPartResolvedSm().Handle(Events.InitializeAggregateEvent));
}
[Test]
public void InvalidChangesFromSerializingResolved() {
ExpectException(() => SerializingResolvedSm().Handle(Events.InitializePersistentEvent));
ExpectException(() => SerializingResolvedSm().Handle(Events.EndPartResolvingEvent));
ExpectException(() => SerializingResolvedSm().Handle(Events.StartResolvingEvent));
ExpectException(() => SerializingResolvedSm().Handle(Events.StartPartResolvingEvent));
ExpectException(() => SerializingResolvedSm().Handle(Events.InitializeTransientEvent));
ExpectException(() => SerializingResolvedSm().Handle(Events.DestroyEvent));
ExpectException(() => SerializingResolvedSm().Handle(Events.StartUpdatingEvent));
ExpectException(() => SerializingResolvedSm().Handle(Events.StartSerializingEvent));
ExpectException(() => SerializingResolvedSm().Handle(Events.StartSerializingEvent));
ExpectException(() => SerializingResolvedSm().Handle(Events.StartSerializingEvent));
ExpectException(() => SerializingResolvedSm().Handle(Events.StartSerializingEvent));
ExpectException(() => SerializingResolvedSm().Handle(Events.InitializeAggregateEvent));
}
[Test]
public void InvalidChangesFromSerializingTransient() {
ExpectException(() => SerializingTransientSm().Handle(Events.InitializePersistentEvent));
ExpectException(() => SerializingTransientSm().Handle(Events.EndPartResolvingEvent));
ExpectException(() => SerializingTransientSm().Handle(Events.EndResolvingEvent));
ExpectException(() => SerializingTransientSm().Handle(Events.StartResolvingEvent));
ExpectException(() => SerializingTransientSm().Handle(Events.StartPartResolvingEvent));
ExpectException(() => SerializingTransientSm().Handle(Events.DestroyEvent));
ExpectException(() => SerializingTransientSm().Handle(Events.StartUpdatingEvent));
ExpectException(() => SerializingTransientSm().Handle(Events.StartSerializingEvent));
ExpectException(() => SerializingTransientSm().Handle(Events.StartSerializingEvent));
ExpectException(() => SerializingTransientSm().Handle(Events.StartSerializingEvent));
ExpectException(() => SerializingTransientSm().Handle(Events.StartSerializingEvent));
ExpectException(() => SerializingTransientSm().Handle(Events.InitializeAggregateEvent));
}
[Test]
public void InvalidChangesFromTransient() {
ExpectException(() => TransientSm().Handle(Events.InitializePersistentEvent));
ExpectException(() => TransientSm().Handle(Events.EndPartResolvingEvent));
ExpectException(() => TransientSm().Handle(Events.StartPartResolvingEvent));
ExpectException(() => TransientSm().Handle(Events.InitializeTransientEvent));
ExpectException(() => TransientSm().Handle(Events.DestroyEvent));
ExpectException(() => TransientSm().Handle(Events.StartUpdatingEvent));
ExpectException(() => TransientSm().Handle(Events.InitializeAggregateEvent));
}
[Test]
public void InvalidChangesFromUpdating() {
ExpectException(() => UpdatingSm().Handle(Events.InitializePersistentEvent));
ExpectException(() => UpdatingSm().Handle(Events.EndPartResolvingEvent));
ExpectException(() => UpdatingSm().Handle(Events.StartResolvingEvent));
ExpectException(() => UpdatingSm().Handle(Events.StartPartResolvingEvent));
ExpectException(() => UpdatingSm().Handle(Events.InitializeTransientEvent));
ExpectException(() => UpdatingSm().Handle(Events.DestroyEvent));
ExpectException(() => UpdatingSm().Handle(Events.StartUpdatingEvent));
ExpectException(() => UpdatingSm().Handle(Events.StartSerializingEvent));
ExpectException(() => UpdatingSm().Handle(Events.StartSerializingEvent));
ExpectException(() => UpdatingSm().Handle(Events.StartSerializingEvent));
ExpectException(() => UpdatingSm().Handle(Events.StartSerializingEvent));
ExpectException(() => UpdatingSm().Handle(Events.InitializeAggregateEvent));
}
[Test]
public void ValidChangesFromGhost() {
ExpectNoException(() => GhostSM().Handle(Events.StartResolvingEvent));
ExpectNoException(() => GhostSM().Handle(Events.StartPartResolvingEvent));
ExpectNoException(() => GhostSM().Handle(Events.DestroyEvent));
ExpectNoException(() => GhostSM().Handle(Events.StartUpdatingEvent));
ExpectNoException(() => GhostSM().Handle(Events.StartSerializingEvent));
}
[Test]
public void ValidChangesFromNew() {
ExpectNoException(() => NewSm().Handle(Events.InitializePersistentEvent));
ExpectNoException(() => NewSm().Handle(Events.InitializeTransientEvent));
ExpectNoException(() => NewSm().Handle(Events.InitializeAggregateEvent));
}
[Test]
public void ValidChangesFromPartResolved() {
ExpectNoException(() => ResolvedPartSm().Handle(Events.StartResolvingEvent));
ExpectNoException(() => ResolvedPartSm().Handle(Events.StartPartResolvingEvent));
ExpectNoException(() => ResolvedPartSm().Handle(Events.DestroyEvent));
ExpectNoException(() => ResolvedPartSm().Handle(Events.StartUpdatingEvent));
ExpectNoException(() => ResolvedPartSm().Handle(Events.StartSerializingEvent));
ExpectNoException(() => ResolvedPartSm().Handle(Events.StartSetupEvent));
ExpectNoException(() => ResolvedPartSm().Handle(Events.StartPartSetupEvent));
}
[Test]
public void ValidChangesFromResolved() {
ExpectNoException(() => ResolvedSm().Handle(Events.ResetEvent));
ExpectNoException(() => ResolvedSm().Handle(Events.DestroyEvent));
ExpectNoException(() => ResolvedSm().Handle(Events.StartUpdatingEvent));
ExpectNoException(() => ResolvedSm().Handle(Events.StartSerializingEvent));
ExpectNoException(() => ResolvedSm().Handle(Events.StartSetupEvent));
ExpectNoException(() => ResolvedSm().Handle(Events.StartPartSetupEvent));
}
[Test]
public void ValidChangesFromResolving() {
ExpectNoException(() => ResolvingSm().Handle(Events.EndResolvingEvent));
ExpectNoException(() => ResolvingSm().Handle(Events.DestroyEvent));
}
[Test]
public void ValidChangesFromResolvingPart() {
ExpectNoException(() => ResolvingPartSm().Handle(Events.EndPartResolvingEvent));
ExpectNoException(() => ResolvingPartSm().Handle(Events.EndResolvingEvent));
}
[Test]
public void ValidChangesFromSerializingPartResolved() {
ExpectNoException(() => SerializingPartResolvedSm().Handle(Events.EndSerializingEvent));
}
[Test]
public void ValidChangesFromSerializingResolved() {
ExpectNoException(() => SerializingResolvedSm().Handle(Events.EndSerializingEvent));
}
[Test]
public void ValidChangesFromSerializingTransient() {
ExpectNoException(() => SerializingTransientSm().Handle(Events.EndSerializingEvent));
}
[Test]
public void ValidChangesFromTransient() {
ExpectNoException(() => TransientSm().Handle(Events.StartResolvingEvent));
ExpectNoException(() => TransientSm().Handle(Events.StartSerializingEvent));
ExpectNoException(() => TransientSm().Handle(Events.StartSetupEvent));
ExpectNoException(() => TransientSm().Handle(Events.StartPartSetupEvent));
}
[Test]
public void ValidChangesFromUpdating() {
ExpectNoException(() => UpdatingSm().Handle(Events.EndUpdatingEvent));
}
public interface ITestCallbackFacet : ILoadingCallbackFacet, ILoadedCallbackFacet { }
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Sql.LegacySdk;
using Microsoft.Azure.Management.Sql.LegacySdk.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Sql.LegacySdk
{
/// <summary>
/// Represents all the operations for operating on Azure SQL Server
/// communication links. Contains operations to: Create, Retrieve,
/// Update, and Delete.
/// </summary>
internal partial class ServerCommunicationLinkOperations : IServiceOperations<SqlManagementClient>, IServerCommunicationLinkOperations
{
/// <summary>
/// Initializes a new instance of the ServerCommunicationLinkOperations
/// class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ServerCommunicationLinkOperations(SqlManagementClient client)
{
this._client = client;
}
private SqlManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.SqlManagementClient.
/// </summary>
public SqlManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Begins creating a new or updating an existing Azure SQL Server
/// communication. To determine the status of the operation call
/// GetServerCommunicationLinkOperationStatus.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <param name='communicationLinkName'>
/// Required. The name of the Azure SQL Server communication link to be
/// operated on (Updated or created).
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for creating or updating a Server
/// communication link.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for long running Azure Sql server communication link
/// operation.
/// </returns>
public async Task<ServerCommunicationLinkCreateOrUpdateResponse> BeginCreateOrUpdateAsync(string resourceGroupName, string serverName, string communicationLinkName, ServerCommunicationLinkCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (communicationLinkName == null)
{
throw new ArgumentNullException("communicationLinkName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Properties == null)
{
throw new ArgumentNullException("parameters.Properties");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("communicationLinkName", communicationLinkName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "BeginCreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/communicationLinks/";
url = url + Uri.EscapeDataString(communicationLinkName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject serverCommunicationLinkCreateOrUpdateParametersValue = new JObject();
requestDoc = serverCommunicationLinkCreateOrUpdateParametersValue;
JObject propertiesValue = new JObject();
serverCommunicationLinkCreateOrUpdateParametersValue["properties"] = propertiesValue;
if (parameters.Properties.PartnerServer != null)
{
propertiesValue["partnerServer"] = parameters.Properties.PartnerServer;
}
if (parameters.Location != null)
{
serverCommunicationLinkCreateOrUpdateParametersValue["location"] = parameters.Location;
}
if (parameters.Tags != null)
{
JObject tagsDictionary = new JObject();
foreach (KeyValuePair<string, string> pair in parameters.Tags)
{
string tagsKey = pair.Key;
string tagsValue = pair.Value;
tagsDictionary[tagsKey] = tagsValue;
}
serverCommunicationLinkCreateOrUpdateParametersValue["tags"] = tagsDictionary;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ServerCommunicationLinkCreateOrUpdateResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created || statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ServerCommunicationLinkCreateOrUpdateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ErrorResponse errorInstance = new ErrorResponse();
result.Error = errorInstance;
JToken codeValue = responseDoc["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
errorInstance.Code = codeInstance;
}
JToken messageValue = responseDoc["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
errorInstance.Message = messageInstance;
}
JToken targetValue = responseDoc["target"];
if (targetValue != null && targetValue.Type != JTokenType.Null)
{
string targetInstance = ((string)targetValue);
errorInstance.Target = targetInstance;
}
ServerCommunicationLink serverCommunicationLinkInstance = new ServerCommunicationLink();
result.ServerCommunicationLink = serverCommunicationLinkInstance;
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
ServerCommunicationLinkProperties propertiesInstance = new ServerCommunicationLinkProperties();
serverCommunicationLinkInstance.Properties = propertiesInstance;
JToken stateValue = propertiesValue2["state"];
if (stateValue != null && stateValue.Type != JTokenType.Null)
{
string stateInstance = ((string)stateValue);
propertiesInstance.State = stateInstance;
}
JToken partnerServerValue = propertiesValue2["partnerServer"];
if (partnerServerValue != null && partnerServerValue.Type != JTokenType.Null)
{
string partnerServerInstance = ((string)partnerServerValue);
propertiesInstance.PartnerServer = partnerServerInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
serverCommunicationLinkInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
serverCommunicationLinkInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
serverCommunicationLinkInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
serverCommunicationLinkInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey2 = ((string)property.Name);
string tagsValue2 = ((string)property.Value);
serverCommunicationLinkInstance.Tags.Add(tagsKey2, tagsValue2);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Location"))
{
result.OperationStatusLink = httpResponse.Headers.GetValues("Location").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Retry-After"))
{
result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture);
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.Created)
{
result.Status = OperationStatus.Succeeded;
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Creates a new or updates an existing Azure SQL Server communication
/// link.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Database Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <param name='communicationLinkName'>
/// Required. The name of the Azure SQL Server communication link to be
/// operated on (Updated or created).
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for creating or updating a Server
/// communication link.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for long running Azure Sql server communication link
/// operation.
/// </returns>
public async Task<ServerCommunicationLinkCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, string serverName, string communicationLinkName, ServerCommunicationLinkCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
SqlManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("communicationLinkName", communicationLinkName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
ServerCommunicationLinkCreateOrUpdateResponse response = await client.CommunicationLinks.BeginCreateOrUpdateAsync(resourceGroupName, serverName, communicationLinkName, parameters, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
ServerCommunicationLinkCreateOrUpdateResponse result = await client.CommunicationLinks.GetServerCommunicationLinkOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
int delayInSeconds = response.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 30;
}
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == OperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await Task.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.CommunicationLinks.GetServerCommunicationLinkOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
delayInSeconds = result.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 15;
}
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Deletes the Azure SQL server communication link with the given name.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <param name='communicationLinkName'>
/// Required. The name of the Azure SQL server communication link to be
/// retrieved.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string serverName, string communicationLinkName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (communicationLinkName == null)
{
throw new ArgumentNullException("communicationLinkName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("communicationLinkName", communicationLinkName);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/communicationLinks/";
url = url + Uri.EscapeDataString(communicationLinkName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Returns information about an Azure SQL Server communication links.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <param name='communicationLinkName'>
/// Required. The name of the Azure SQL server communication link to be
/// retrieved.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a get server communication link request.
/// </returns>
public async Task<ServerCommunicationLinkGetResponse> GetAsync(string resourceGroupName, string serverName, string communicationLinkName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (communicationLinkName == null)
{
throw new ArgumentNullException("communicationLinkName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("communicationLinkName", communicationLinkName);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/communicationLinks/";
url = url + Uri.EscapeDataString(communicationLinkName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ServerCommunicationLinkGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ServerCommunicationLinkGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ServerCommunicationLink serverCommunicationLinkInstance = new ServerCommunicationLink();
result.ServerCommunicationLink = serverCommunicationLinkInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ServerCommunicationLinkProperties propertiesInstance = new ServerCommunicationLinkProperties();
serverCommunicationLinkInstance.Properties = propertiesInstance;
JToken stateValue = propertiesValue["state"];
if (stateValue != null && stateValue.Type != JTokenType.Null)
{
string stateInstance = ((string)stateValue);
propertiesInstance.State = stateInstance;
}
JToken partnerServerValue = propertiesValue["partnerServer"];
if (partnerServerValue != null && partnerServerValue.Type != JTokenType.Null)
{
string partnerServerInstance = ((string)partnerServerValue);
propertiesInstance.PartnerServer = partnerServerInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
serverCommunicationLinkInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
serverCommunicationLinkInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
serverCommunicationLinkInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
serverCommunicationLinkInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
serverCommunicationLinkInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets the status of an Azure Sql Server communication link create or
/// update operation.
/// </summary>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for long running Azure Sql server communication link
/// operation.
/// </returns>
public async Task<ServerCommunicationLinkCreateOrUpdateResponse> GetServerCommunicationLinkOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken)
{
// Validate
if (operationStatusLink == null)
{
throw new ArgumentNullException("operationStatusLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("operationStatusLink", operationStatusLink);
TracingAdapter.Enter(invocationId, this, "GetServerCommunicationLinkOperationStatusAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + operationStatusLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ServerCommunicationLinkCreateOrUpdateResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created || statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ServerCommunicationLinkCreateOrUpdateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ErrorResponse errorInstance = new ErrorResponse();
result.Error = errorInstance;
JToken codeValue = responseDoc["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
errorInstance.Code = codeInstance;
}
JToken messageValue = responseDoc["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
errorInstance.Message = messageInstance;
}
JToken targetValue = responseDoc["target"];
if (targetValue != null && targetValue.Type != JTokenType.Null)
{
string targetInstance = ((string)targetValue);
errorInstance.Target = targetInstance;
}
ServerCommunicationLink serverCommunicationLinkInstance = new ServerCommunicationLink();
result.ServerCommunicationLink = serverCommunicationLinkInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ServerCommunicationLinkProperties propertiesInstance = new ServerCommunicationLinkProperties();
serverCommunicationLinkInstance.Properties = propertiesInstance;
JToken stateValue = propertiesValue["state"];
if (stateValue != null && stateValue.Type != JTokenType.Null)
{
string stateInstance = ((string)stateValue);
propertiesInstance.State = stateInstance;
}
JToken partnerServerValue = propertiesValue["partnerServer"];
if (partnerServerValue != null && partnerServerValue.Type != JTokenType.Null)
{
string partnerServerInstance = ((string)partnerServerValue);
propertiesInstance.PartnerServer = partnerServerInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
serverCommunicationLinkInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
serverCommunicationLinkInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
serverCommunicationLinkInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
serverCommunicationLinkInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
serverCommunicationLinkInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.Created)
{
result.Status = OperationStatus.Succeeded;
}
if (statusCode == HttpStatusCode.OK)
{
result.Status = OperationStatus.Succeeded;
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Returns information about Azure SQL Server communication links.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Server communication
/// link request.
/// </returns>
public async Task<ServerCommunicationLinkListResponse> ListAsync(string resourceGroupName, string serverName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/communicationLinks";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ServerCommunicationLinkListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ServerCommunicationLinkListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
ServerCommunicationLink serverCommunicationLinkInstance = new ServerCommunicationLink();
result.ServerCommunicationLinks.Add(serverCommunicationLinkInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ServerCommunicationLinkProperties propertiesInstance = new ServerCommunicationLinkProperties();
serverCommunicationLinkInstance.Properties = propertiesInstance;
JToken stateValue = propertiesValue["state"];
if (stateValue != null && stateValue.Type != JTokenType.Null)
{
string stateInstance = ((string)stateValue);
propertiesInstance.State = stateInstance;
}
JToken partnerServerValue = propertiesValue["partnerServer"];
if (partnerServerValue != null && partnerServerValue.Type != JTokenType.Null)
{
string partnerServerInstance = ((string)partnerServerValue);
propertiesInstance.PartnerServer = partnerServerInstance;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
serverCommunicationLinkInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
serverCommunicationLinkInstance.Name = nameInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
serverCommunicationLinkInstance.Type = typeInstance;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
serverCommunicationLinkInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
serverCommunicationLinkInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
/*
* Procedurality v. 0.1 rev. 20070307
* Copyright 2007 Oddlabs ApS
*
*
* This file is part of Procedurality.
* Procedurality 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.
*
*
* Procedurality 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 Foobar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
using System;
namespace Procedurality
{
public class ErosionHydraulic
{
public static Channel erode1(Channel channel, Channel rain_map, float vaporization, int rain_freq, int iterations)
{
Channel water_map = new Channel(channel.width, channel.height).fill(0f);
Channel vapor_map = rain_map.copy().multiply(0.5f);
Channel water_map_diff = new Channel(channel.width, channel.height).fill(0f);
Console.Write("Hydraulic erosion 1: ");
for (int i = 0; i < iterations; i++) {
Console.Write(".");
// save frames
/*
if (channel.width > 128 && i%10 == 0) {
if (i < 10) {
channel.toLayer().saveAsPNG("erosion00" + i);
} else if (i < 100) {
channel.toLayer().saveAsPNG("erosion0" + i);
} else {
channel.toLayer().saveAsPNG("erosion" + i);
}
}
*/
// rain erodes the underlying terrain
if (i%rain_freq == 0) {
channel.channelSubtract(vapor_map);
water_map.channelAdd(rain_map);
}
// water and sediment transport
for (int y = 1; y < channel.height - 1; y++) {
for (int x = 1; x < channel.width - 1; x++) {
// calculate total heights and height differences
float h = channel.getPixel(x, y) + water_map.getPixel(x, y);
float h1 = channel.getPixel(x, y + 1) + water_map.getPixel(x, y + 1);
float h2 = channel.getPixel(x - 1, y) + water_map.getPixel(x - 1, y);
float h3 = channel.getPixel(x + 1, y) + water_map.getPixel(x + 1, y);
float h4 = channel.getPixel(x, y - 1) + water_map.getPixel(x, y - 1);
float h5 = channel.getPixel(x - 1, y + 1) + water_map.getPixel(x - 1, y + 1);
float h6 = channel.getPixel(x + 1, y + 1) + water_map.getPixel(x + 1, y + 1);
float h7 = channel.getPixel(x - 1, y - 1) + water_map.getPixel(x - 1, y - 1);
float h8 = channel.getPixel(x + 1, y - 1) + water_map.getPixel(x + 1, y - 1);
float d1 = h - h1;
float d2 = h - h2;
float d3 = h - h3;
float d4 = h - h4;
float d5 = h - h5;
float d6 = h - h6;
float d7 = h - h7;
float d8 = h - h8;
// calculate amount of water to transport
float total_height = 0;
float total_height_diff = 0;
int cells = 1;
if (d1 > 0) {
total_height_diff+= d1;
total_height+= h1;
cells++;
}
if (d2 > 0) {
total_height_diff+= d2;
total_height+= h2;
cells++;
}
if (d3 > 0) {
total_height_diff+= d3;
total_height+= h3;
cells++;
}
if (d4 > 0) {
total_height_diff+= d4;
total_height+= h4;
cells++;
}
if (d5 > 0) {
total_height_diff+= d5;
total_height+= h5;
cells++;
}
if (d6 > 0) {
total_height_diff+= d6;
total_height+= h6;
cells++;
}
if (d7 > 0) {
total_height_diff+= d7;
total_height+= h7;
cells++;
}
if (d8 > 0) {
total_height_diff+= d8;
total_height+= h8;
cells++;
}
if (cells == 1) {
continue;
}
float avr_height = total_height/cells;
float water_amount = Math.Min(water_map.getPixel(x, y), h - avr_height);
water_map_diff.putPixel(x, y, water_map_diff.getPixel(x, y) - water_amount);
float total_height_diff_inv = water_amount/total_height_diff;
// transport water
if (d1 > 0) {
water_map_diff.putPixel(x, y + 1, water_map_diff.getPixel(x, y + 1) + d1*total_height_diff_inv);
}
if (d2 > 0) {
water_map_diff.putPixel(x - 1, y, water_map_diff.getPixel(x - 1, y) + d2*total_height_diff_inv);
}
if (d3 > 0) {
water_map_diff.putPixel(x + 1, y, water_map_diff.getPixel(x + 1, y) + d3*total_height_diff_inv);
}
if (d4 > 0) {
water_map_diff.putPixel(x, y - 1, water_map_diff.getPixel(x, y - 1) + d4*total_height_diff_inv);
}
if (d5 > 0) {
water_map_diff.putPixel(x - 1, y + 1, water_map_diff.getPixel(x - 1, y + 1) + d5*total_height_diff_inv);
}
if (d6 > 0) {
water_map_diff.putPixel(x + 1, y + 1, water_map_diff.getPixel(x + 1, y + 1) + d6*total_height_diff_inv);
}
if (d7 > 0) {
water_map_diff.putPixel(x - 1, y - 1, water_map_diff.getPixel(x - 1, y - 1) + d7*total_height_diff_inv);
}
if (d8 > 0) {
water_map_diff.putPixel(x + 1, y - 1, water_map_diff.getPixel(x + 1, y - 1) + d8*total_height_diff_inv);
}
}
}
// apply changes to water_map
water_map.channelAddNoClip(water_map_diff);
water_map_diff.fill(0f);
// vaporize water
channel.channelAddNoClip(water_map.copy().channelSubtract(water_map.addClip(-vaporization)).multiply(0.5f));
}
// force evaporation of remaining water
//channel.channelAdd(water_map.multiply(0.5f));
Console.WriteLine("DONE");
return channel;
}
public static Channel erode2(Channel channel, Channel rain_map, float vaporization, int rain_freq, int iterations) {
Channel water_map = new Channel(channel.width, channel.height).fill(0f);
Channel vapor_map = rain_map.copy().multiply(0.5f);
Channel water_map_diff = new Channel(channel.width, channel.height).fill(0f);
Console.Write("Hydraulic erosion 2: ");
for (int i = 0; i < iterations; i++) {
Console.Write(".");
// save frames
/*
if (channel.width > 128 && i%10 == 0) {
if (i < 10) {
channel.toLayer().saveAsPNG("erosion00" + i);
} else if (i < 100) {
channel.toLayer().saveAsPNG("erosion0" + i);
} else {
channel.toLayer().saveAsPNG("erosion" + i);
}
}
*/
// rain erodes the underlying terrain
if (i%rain_freq == 0) {
channel.channelSubtract(vapor_map);
water_map.channelAdd(rain_map);
}
// water and sediment transport
for (int y = 1; y < channel.height - 1; y++) {
for (int x = 1; x < channel.width - 1; x++) {
// calculate total heights and height differences
float h = channel.getPixel(x, y) + water_map.getPixel(x, y);
float h1 = channel.getPixel(x, y + 1) + water_map.getPixel(x, y + 1);
float h2 = channel.getPixel(x - 1, y) + water_map.getPixel(x - 1, y);
float h3 = channel.getPixel(x + 1, y) + water_map.getPixel(x + 1, y);
float h4 = channel.getPixel(x, y - 1) + water_map.getPixel(x, y - 1);
float d1 = h - h1;
float d2 = h - h2;
float d3 = h - h3;
float d4 = h - h4;
// calculate amount of water to transport
float total_height = 0;
float total_height_diff = 0;
int cells = 1;
if (d1 > 0) {
total_height_diff+= d1;
total_height+= h1;
cells++;
}
if (d2 > 0) {
total_height_diff+= d2;
total_height+= h2;
cells++;
}
if (d3 > 0) {
total_height_diff+= d3;
total_height+= h3;
cells++;
}
if (d4 > 0) {
total_height_diff+= d4;
total_height+= h4;
cells++;
}
if (cells == 1) {
continue;
}
float avr_height = total_height/cells;
float water_amount = Math.Min(water_map.getPixel(x, y), h - avr_height);
water_map_diff.putPixel(x, y, water_map_diff.getPixel(x, y) - water_amount);
float total_height_diff_inv = water_amount/total_height_diff;
// transport water
if (d1 > 0) {
water_map_diff.putPixel(x, y + 1, water_map_diff.getPixel(x, y + 1) + d1*total_height_diff_inv);
}
if (d2 > 0) {
water_map_diff.putPixel(x - 1, y, water_map_diff.getPixel(x - 1, y) + d2*total_height_diff_inv);
}
if (d3 > 0) {
water_map_diff.putPixel(x + 1, y, water_map_diff.getPixel(x + 1, y) + d3*total_height_diff_inv);
}
if (d4 > 0) {
water_map_diff.putPixel(x, y - 1, water_map_diff.getPixel(x, y - 1) + d4*total_height_diff_inv);
}
}
}
// apply changes to water_map
water_map.channelAddNoClip(water_map_diff);
water_map_diff.fill(0f);
// vaporize water
channel.channelAddNoClip(water_map.copy().channelSubtract(water_map.addClip(-vaporization)).multiply(0.5f));
}
// force evaporation of remaining water
channel.channelAdd(water_map.multiply(0.5f));
Console.WriteLine("DONE");
return channel;
}
public static Channel erode3(Channel channel, Channel rain_map, float vaporization, int rain_freq, int iterations) {
Channel vapor_map = rain_map.copy().multiply(0.5f);
Channel height_map_diff = new Channel(channel.width, channel.height).fill(0f);
Channel water_map = new Channel(channel.width, channel.height).fill(0f);
Channel water_map_diff = new Channel(channel.width, channel.height).fill(0f);
Channel sediment_map = new Channel(channel.width, channel.height).fill(0f);
Channel sediment_map_diff = new Channel(channel.width, channel.height).fill(0f);
Console.Write("Hydraulic erosion 3: ");
for (int i = 0; i < iterations; i++) {
Console.Write(".");
// save frames
/*
if (channel.width > 128 && i%8 == 0) {
if (i < 10) {
channel.toLayer().saveAsPNG("erosion00" + i);
} else if (i < 100) {
channel.toLayer().saveAsPNG("erosion0" + i);
} else {
channel.toLayer().saveAsPNG("erosion" + i);
}
}
*/
// rain
if (i%rain_freq == 0) {
water_map.channelAdd(rain_map);
}
// water and sediment transport
for (int y = 1; y < channel.height - 1; y++) {
for (int x = 1; x < channel.width - 1; x++) {
// calculate total heights and height differences
float h = channel.getPixel(x, y) + water_map.getPixel(x, y);
float h1 = channel.getPixel(x, y + 1) + water_map.getPixel(x, y + 1) + sediment_map.getPixel(x, y + 1);
float h2 = channel.getPixel(x - 1, y) + water_map.getPixel(x - 1, y) + sediment_map.getPixel(x - 1, y);
float h3 = channel.getPixel(x + 1, y) + water_map.getPixel(x + 1, y) + sediment_map.getPixel(x + 1, y);
float h4 = channel.getPixel(x, y - 1) + water_map.getPixel(x, y - 1) + sediment_map.getPixel(x, y - 1);
float d1 = h - h1;
float d2 = h - h2;
float d3 = h - h3;
float d4 = h - h4;
// calculate amount of water and sediment to transport
float total_height = 0;
float total_height_diff = 0;
int cells = 1;
if (d1 > 0) {
total_height_diff+= d1;
total_height+= h1;
cells++;
}
if (d2 > 0) {
total_height_diff+= d2;
total_height+= h2;
cells++;
}
if (d3 > 0) {
total_height_diff+= d3;
total_height+= h3;
cells++;
}
if (d4 > 0) {
total_height_diff+= d4;
total_height+= h4;
cells++;
}
if (cells == 1) {
continue;
}
float avr_height = total_height/cells;
float water_amount = Math.Min(water_map.getPixel(x, y), h - avr_height);
water_map_diff.putPixel(x, y, water_map_diff.getPixel(x, y) - water_amount);
float water_inv = water_amount/total_height_diff;
float sediment_amount = sediment_map.getPixel(x, y);
sediment_map_diff.putPixel(x, y, sediment_map_diff.getPixel(x, y) - sediment_amount);
float sediment_inv = sediment_amount/total_height_diff;
float dissolve;
// transport water and sediment and dissolve more material
if (d1 > 0) {
water_map_diff.putPixel(x, y + 1, water_map_diff.getPixel(x, y + 1) + d1*water_inv);
dissolve = 10f*d1*water_amount;
sediment_map_diff.putPixel(x, y + 1, sediment_map_diff.getPixel(x, y + 1) + d1*sediment_inv + dissolve);
height_map_diff.putPixel(x, y + 1, height_map_diff.getPixel(x, y + 1) - dissolve);
}
if (d2 > 0) {
water_map_diff.putPixel(x - 1, y, water_map_diff.getPixel(x - 1, y) + d2*water_inv);
dissolve = 10f*d2*water_amount;
sediment_map_diff.putPixel(x - 1, y, sediment_map_diff.getPixel(x - 1, y) + d2*sediment_inv + dissolve);
height_map_diff.putPixel(x - 1, y, height_map_diff.getPixel(x - 1, y) - dissolve);
}
if (d3 > 0) {
water_map_diff.putPixel(x + 1, y, water_map_diff.getPixel(x + 1, y) + d3*water_inv);
dissolve = 10f*d3*water_amount;
sediment_map_diff.putPixel(x + 1, y, sediment_map_diff.getPixel(x + 1, y) + d3*sediment_inv + dissolve);
height_map_diff.putPixel(x + 1, y, height_map_diff.getPixel(x + 1, y) - dissolve);
}
if (d4 > 0) {
water_map_diff.putPixel(x, y - 1, water_map_diff.getPixel(x, y - 1) + d4*water_inv);
dissolve = 10f*d4*water_amount;
sediment_map_diff.putPixel(x, y - 1, sediment_map_diff.getPixel(x, y - 1) + d4*sediment_inv + dissolve);
height_map_diff.putPixel(x, y - 1, height_map_diff.getPixel(x, y - 1) - dissolve);
}
}
}
// apply changes to water map
water_map.channelAddNoClip(water_map_diff);
// apply changes to sediment map
sediment_map.channelAddNoClip(sediment_map_diff);
// apply changes to height map
channel.channelAddNoClip(height_map_diff);
// water vaporization
water_map.addClip(-vaporization);
// sedimentation
sediment_map_diff = sediment_map.copy().channelSubtract(water_map);
sediment_map.channelSubtract(sediment_map_diff);
channel.channelAddNoClip(sediment_map_diff);
// clear diff maps
water_map_diff.fill(0f);
height_map_diff.fill(0f);
sediment_map_diff.fill(0f);
}
// force evaporation of remaining water
//channel.channelAdd(water_map.multiply(0.5f));
Console.WriteLine("DONE");
return channel;
}
public static Channel erode4(Channel channel, float rain_amount, float vaporization, int rain_freq, int iterations) {
Channel water_map = new Channel(channel.width, channel.height).fill(0f);
Channel water_map_diff = new Channel(channel.width, channel.height).fill(0f);
Channel height_map_diff = new Channel(channel.width, channel.height).fill(0f);
Console.Write("Hydraulic erosion 4: ");
for (int i = 0; i < iterations; i++) {
Console.Write(".");
// save frames
/*
if (channel.width > 128 && i%10 == 0) {
if (i < 10) {
channel.toLayer().saveAsPNG("erosion00" + i);
} else if (i < 100) {
channel.toLayer().saveAsPNG("erosion0" + i);
} else {
channel.toLayer().saveAsPNG("erosion" + i);
}
}
*/
// rain erodes the underlying terrain
if (i%rain_freq == 0) {
water_map.channelAdd(channel.copy().multiply(rain_amount));
}
// water and sediment transport
for (int y = 1; y < channel.height - 1; y++) {
for (int x = 1; x < channel.width - 1; x++) {
// calculate total heights and height differences
float h = channel.getPixel(x, y) + water_map.getPixel(x, y);
float h1 = channel.getPixel(x, y + 1) + water_map.getPixel(x, y + 1);
float h2 = channel.getPixel(x - 1, y) + water_map.getPixel(x - 1, y);
float h3 = channel.getPixel(x + 1, y) + water_map.getPixel(x + 1, y);
float h4 = channel.getPixel(x, y - 1) + water_map.getPixel(x, y - 1);
float d1 = h - h1;
float d2 = h - h2;
float d3 = h - h3;
float d4 = h - h4;
// calculate amount of water to transport
float total_height = 0;
float total_height_diff = 0;
int cells = 1;
if (d1 > 0) {
total_height_diff+= d1;
total_height+= h1;
cells++;
}
if (d2 > 0) {
total_height_diff+= d2;
total_height+= h2;
cells++;
}
if (d3 > 0) {
total_height_diff+= d3;
total_height+= h3;
cells++;
}
if (d4 > 0) {
total_height_diff+= d4;
total_height+= h4;
cells++;
}
if (cells == 1) {
continue;
}
float avr_height = total_height/cells;
float water_amount = Math.Min(water_map.getPixel(x, y), h - avr_height);
water_map_diff.putPixel(x, y, water_map_diff.getPixel(x, y) - water_amount);
float total_height_diff_inv = water_amount/total_height_diff;
// transport water
if (d1 > 0) {
water_amount = d1*total_height_diff_inv;
water_map_diff.putPixel(x, y + 1, water_map_diff.getPixel(x, y + 1) + water_amount);
height_map_diff.putPixel(x, y + 1, height_map_diff.getPixel(x, y + 1) - 0.1f*water_amount);
}
if (d2 > 0) {
water_amount = d2*total_height_diff_inv;
water_map_diff.putPixel(x - 1, y, water_map_diff.getPixel(x - 1, y) + water_amount);
height_map_diff.putPixel(x - 1, y, height_map_diff.getPixel(x - 1, y) - 0.1f*water_amount);
}
if (d3 > 0) {
water_amount = d3*total_height_diff_inv;
water_map_diff.putPixel(x + 1, y, water_map_diff.getPixel(x + 1, y) + water_amount);
height_map_diff.putPixel(x + 1, y, height_map_diff.getPixel(x + 1, y) - 0.1f*water_amount);
}
if (d4 > 0) {
water_amount = d4*total_height_diff_inv;
water_map_diff.putPixel(x, y - 1, water_map_diff.getPixel(x, y - 1) + water_amount);
height_map_diff.putPixel(x, y - 1, height_map_diff.getPixel(x, y - 1) - 0.1f*water_amount);
}
}
}
// apply changes to water map
water_map.channelAddNoClip(water_map_diff);
water_map_diff.fill(0f);
// apply changes to height map
channel.channelAddNoClip(height_map_diff);
height_map_diff.fill(0f);
// vaporize water
channel.channelAddNoClip(water_map.copy().channelSubtract(water_map.addClip(-vaporization)).multiply(0.5f));
}
// force evaporation of remaining water
channel.channelAdd(water_map.multiply(0.5f));
Console.WriteLine("DONE");
return channel;
}
public static Channel erode5(Channel channel, Channel rain, float erosion_water, float erosion_flow, float evaporation, float water_threshold, float solulibility, int ipr, int iterations) {
Channel w = new Channel(channel.width, channel.height); // water map
Channel dw = new Channel(channel.width, channel.height); // delta water map
Channel s = new Channel(channel.width, channel.height); // sediment map
Channel ds = new Channel(channel.width, channel.height); // delta sediment map
Console.Write("Hydraulic erosion 5: ");
for (int i = 0; i < iterations; i++) {
Console.Write(".");
// save frames
/*
if (channel.width > 128 && i%10 == 0) {
if (i < 10) {
channel.toLayer().saveAsPNG("erosion00" + i);
} else if (i < 100) {
channel.toLayer().saveAsPNG("erosion0" + i);
} else {
channel.toLayer().saveAsPNG("erosion" + i);
}
}
*/
// water is added according to rain map
if (i%ipr == 0) {
w.channelAdd(rain);
}
// the presence of water dissolves material
channel.channelSubtract(w.copy().multiply(erosion_water));
s.channelAdd(w.copy().multiply(erosion_water));
// water and sediment are transported
float h, h1, h2, h3, h4, d1, d2, d3, d4, total_height, total_height_diff, total_height_diff_inv, avr_height, water_amount, sediment_amount;
int cells;
for (int y = 0; y < channel.height; y++) {
for (int x = 0; x < channel.width; x++) {
// water transport
// calculate total heights and height differences
h = channel.getPixel(x, y) + w.getPixel(x, y) + s.getPixel(x, y);
h1 = channel.getPixelWrap(x , y + 1) + w.getPixelWrap(x , y + 1) + s.getPixelWrap(x , y + 1);
h2 = channel.getPixelWrap(x - 1, y ) + w.getPixelWrap(x - 1, y ) + s.getPixelWrap(x - 1, y );
h3 = channel.getPixelWrap(x + 1, y ) + w.getPixelWrap(x + 1, y ) + s.getPixelWrap(x + 1, y );
h4 = channel.getPixelWrap(x , y - 1) + w.getPixelWrap(x , y - 1) + s.getPixelWrap(x , y - 1);
d1 = h - h1;
d2 = h - h2;
d3 = h - h3;
d4 = h - h4;
// calculate amount of water to transport
total_height = 0f;
total_height_diff = 0f;
cells = 1;
if (d1 > 0) {
total_height_diff+= d1;
total_height+= h1;
cells++;
}
if (d2 > 0) {
total_height_diff+= d2;
total_height+= h2;
cells++;
}
if (d3 > 0) {
total_height_diff+= d3;
total_height+= h3;
cells++;
}
if (d4 > 0) {
total_height_diff+= d4;
total_height+= h4;
cells++;
}
if (cells == 1) {
continue;
}
avr_height = total_height/cells;
water_amount = Math.Min(w.getPixel(x, y), h - avr_height);
dw.putPixel(x, y, dw.getPixel(x, y) - water_amount);
total_height_diff_inv = water_amount/total_height_diff;
// transport water
if (d1 > 0) {
dw.putPixelWrap(x, y + 1, dw.getPixelWrap(x, y + 1) + d1*total_height_diff_inv);
}
if (d2 > 0) {
dw.putPixelWrap(x - 1, y, dw.getPixelWrap(x - 1, y) + d2*total_height_diff_inv);
}
if (d3 > 0) {
dw.putPixelWrap(x + 1, y, dw.getPixelWrap(x + 1, y) + d3*total_height_diff_inv);
}
if (d4 > 0) {
dw.putPixelWrap(x, y - 1, dw.getPixelWrap(x, y - 1) + d4*total_height_diff_inv);
}
// sediment transport
/*
h = s.getPixel(x, y);
h1 = s.getPixelWrap(x , y + 1);
h2 = s.getPixelWrap(x - 1, y );
h3 = s.getPixelWrap(x + 1, y );
h4 = s.getPixelWrap(x , y - 1);
d1 = h - h1;
d2 = h - h2;
d3 = h - h3;
d4 = h - h4;
// calculate amount of sediment to transport
total_height = 0f;
total_height_diff = 0f;
cells = 1;
if (d1 > 0) {
total_height_diff+= d1;
total_height+= h1;
cells++;
}
if (d2 > 0) {
total_height_diff+= d2;
total_height+= h2;
cells++;
}
if (d3 > 0) {
total_height_diff+= d3;
total_height+= h3;
cells++;
}
if (d4 > 0) {
total_height_diff+= d4;
total_height+= h4;
cells++;
}
if (cells == 1) {
continue;
}
avr_height = total_height/cells;
sediment_amount = Math.Min(s.getPixel(x, y), h - avr_height);
ds.putPixel(x, y, ds.getPixel(x, y) - sediment_amount);
total_height_diff_inv = sediment_amount/total_height_diff;
// transport sediment
if (d1 > 0) {
ds.putPixelWrap(x, y + 1, ds.getPixelWrap(x, y + 1) + d1*total_height_diff_inv);
}
if (d2 > 0) {
ds.putPixelWrap(x - 1, y, ds.getPixelWrap(x - 1, y) + d2*total_height_diff_inv);
}
if (d3 > 0) {
ds.putPixelWrap(x + 1, y, ds.getPixelWrap(x + 1, y) + d3*total_height_diff_inv);
}
if (d4 > 0) {
ds.putPixelWrap(x, y - 1, ds.getPixelWrap(x, y - 1) + d4*total_height_diff_inv);
}
*/
}
}
// more sediment is dissolved according to amount of water flow
/*
channel.channelSubtract(dw.copy().fill(0f, Float.MIN_VALUE, 0f).multiply(erosion_flow));
s.channelAdd(dw.copy().fill(0f, Float.MIN_VALUE, 0f).multiply(erosion_flow));
*/
// apply water and sediment delta maps
w.channelAdd(dw);
//w.fill(0f, Float.MIN_VALUE, water_threshold); // remove water below threshold amount
s.channelAdd(ds);
dw.fill(0f);
ds.fill(0f);
// water evaporates
w.multiply(evaporation);
// sediment is deposited
for (int y = 0; y < channel.height; y++) {
for (int x = 0; x < channel.width; x++) {
float deposition = s.getPixel(x, y) - w.getPixel(x, y)*solulibility;
if (deposition > 0) {
s.putPixel(x, y, s.getPixel(x, y) - deposition);
channel.putPixel(x, y, channel.getPixel(x, y) + deposition);
}
}
}
}
Console.WriteLine("DONE");
return channel;
}
}
}
| |
// 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.ObjectModel;
using System.Diagnostics.Tracing;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Diagnostics;
using System.Security;
namespace System.Runtime
{
internal class ExceptionTrace
{
private const ushort FailFastEventLogCategory = 6;
private string _eventSourceName;
private readonly EtwDiagnosticTrace _diagnosticTrace;
public ExceptionTrace(string eventSourceName, EtwDiagnosticTrace diagnosticTrace)
{
Fx.Assert(diagnosticTrace != null, "'diagnosticTrace' MUST NOT be NULL.");
_eventSourceName = eventSourceName;
_diagnosticTrace = diagnosticTrace;
}
public void AsInformation(Exception exception)
{
//Traces an informational trace message
}
public void AsWarning(Exception exception)
{
//Traces a warning trace message
}
public Exception AsError(Exception exception)
{
// AggregateExceptions are automatically unwrapped.
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return AsError<Exception>(aggregateException);
}
// TargetInvocationExceptions are automatically unwrapped.
TargetInvocationException targetInvocationException = exception as TargetInvocationException;
if (targetInvocationException != null && targetInvocationException.InnerException != null)
{
return AsError(targetInvocationException.InnerException);
}
return TraceException(exception);
}
public Exception AsError(Exception exception, string eventSource)
{
// AggregateExceptions are automatically unwrapped.
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return AsError<Exception>(aggregateException, eventSource);
}
// TargetInvocationExceptions are automatically unwrapped.
TargetInvocationException targetInvocationException = exception as TargetInvocationException;
if (targetInvocationException != null && targetInvocationException.InnerException != null)
{
return AsError(targetInvocationException.InnerException, eventSource);
}
return TraceException(exception, eventSource);
}
public Exception AsError(TargetInvocationException targetInvocationException, string eventSource)
{
Fx.Assert(targetInvocationException != null, "targetInvocationException cannot be null.");
// If targetInvocationException contains any fatal exceptions, return it directly
// without tracing it or any inner exceptions.
if (Fx.IsFatal(targetInvocationException))
{
return targetInvocationException;
}
// A non-null inner exception could require further unwrapping in AsError.
Exception innerException = targetInvocationException.InnerException;
if (innerException != null)
{
return AsError(innerException, eventSource);
}
// A null inner exception is unlikely but possible.
// In this case, trace and return the targetInvocationException itself.
return TraceException<Exception>(targetInvocationException, eventSource);
}
public Exception AsError<TPreferredException>(AggregateException aggregateException)
{
return AsError<TPreferredException>(aggregateException, _eventSourceName);
}
/// <summary>
/// Extracts the first inner exception of type <typeparamref name="TPreferredException"/>
/// from the <see cref="AggregateException"/> if one is present.
/// </summary>
/// <remarks>
/// If no <typeparamref name="TPreferredException"/> inner exception is present, this
/// method returns the first inner exception. All inner exceptions will be traced,
/// including the one returned. The containing <paramref name="aggregateException"/>
/// will not be traced unless there are no inner exceptions.
/// </remarks>
/// <typeparam name="TPreferredException">The preferred type of inner exception to extract.
/// Use <c>typeof(Exception)</c> to extract the first exception regardless of type.</typeparam>
/// <param name="aggregateException">The <see cref="AggregateException"/> to examine.</param>
/// <param name="eventSource">The event source to trace.</param>
/// <returns>The extracted exception. It will not be <c>null</c>
/// but it may not be of type <typeparamref name="TPreferredException"/>.</returns>
public Exception AsError<TPreferredException>(AggregateException aggregateException, string eventSource)
{
Fx.Assert(aggregateException != null, "aggregateException cannot be null.");
// If aggregateException contains any fatal exceptions, return it directly
// without tracing it or any inner exceptions.
if (Fx.IsFatal(aggregateException))
{
return aggregateException;
}
// Collapse possibly nested graph into a flat list.
// Empty inner exception list is unlikely but possible via public api.
ReadOnlyCollection<Exception> innerExceptions = aggregateException.Flatten().InnerExceptions;
if (innerExceptions.Count == 0)
{
return TraceException(aggregateException, eventSource);
}
// Find the first inner exception, giving precedence to TPreferredException
Exception favoredException = null;
foreach (Exception nextInnerException in innerExceptions)
{
// AggregateException may wrap TargetInvocationException, so unwrap those as well
TargetInvocationException targetInvocationException = nextInnerException as TargetInvocationException;
Exception innerException = (targetInvocationException != null && targetInvocationException.InnerException != null)
? targetInvocationException.InnerException
: nextInnerException;
if (innerException is TPreferredException && favoredException == null)
{
favoredException = innerException;
}
// All inner exceptions are traced
TraceException(innerException, eventSource);
}
if (favoredException == null)
{
Fx.Assert(innerExceptions.Count > 0, "InnerException.Count is known to be > 0 here.");
favoredException = innerExceptions[0];
}
return favoredException;
}
public ArgumentException Argument(string paramName, string message)
{
return TraceException(new ArgumentException(message, paramName));
}
public ArgumentNullException ArgumentNull(string paramName)
{
return TraceException(new ArgumentNullException(paramName));
}
public ArgumentNullException ArgumentNull(string paramName, string message)
{
return TraceException(new ArgumentNullException(paramName, message));
}
public ArgumentException ArgumentNullOrEmpty(string paramName)
{
return Argument(paramName, InternalSR.ArgumentNullOrEmpty(paramName));
}
public ArgumentOutOfRangeException ArgumentOutOfRange(string paramName, object actualValue, string message)
{
return TraceException(new ArgumentOutOfRangeException(paramName, actualValue, message));
}
// When throwing ObjectDisposedException, it is highly recommended that you use this ctor
// [C#]
// public ObjectDisposedException(string objectName, string message);
// And provide null for objectName but meaningful and relevant message for message.
// It is recommended because end user really does not care or can do anything on the disposed object, commonly an internal or private object.
public ObjectDisposedException ObjectDisposed(string message)
{
// pass in null, not disposedObject.GetType().FullName as per the above guideline
return TraceException(new ObjectDisposedException(null, message));
}
public void TraceUnhandledException(Exception exception)
{
TraceCore.UnhandledException(_diagnosticTrace, exception != null ? exception.ToString() : string.Empty, exception);
}
public void TraceEtwException(Exception exception, EventLevel eventLevel)
{
switch (eventLevel)
{
case EventLevel.Error:
case EventLevel.Warning:
if (WcfEventSource.Instance.ThrowingEtwExceptionIsEnabled())
{
string serializedException = EtwDiagnosticTrace.ExceptionToTraceString(exception, int.MaxValue);
WcfEventSource.Instance.ThrowingEtwException(_eventSourceName, exception != null ? exception.ToString() : string.Empty, serializedException);
}
break;
case EventLevel.Critical:
if (WcfEventSource.Instance.UnhandledExceptionIsEnabled())
{
string serializedException = EtwDiagnosticTrace.ExceptionToTraceString(exception, int.MaxValue);
WcfEventSource.Instance.EtwUnhandledException(exception != null ? exception.ToString() : string.Empty, serializedException);
}
break;
default:
if (WcfEventSource.Instance.ThrowingExceptionVerboseIsEnabled())
{
string serializedException = EtwDiagnosticTrace.ExceptionToTraceString(exception, int.MaxValue);
WcfEventSource.Instance.ThrowingEtwExceptionVerbose(_eventSourceName, exception != null ? exception.ToString() : string.Empty, serializedException);
}
break;
}
}
private TException TraceException<TException>(TException exception)
where TException : Exception
{
return TraceException(exception, _eventSourceName);
}
[Fx.Tag.SecurityNote(Critical = "Calls 'System.Runtime.Interop.UnsafeNativeMethods.IsDebuggerPresent()' which is a P/Invoke method",
Safe = "Does not leak any resource, needed for debugging")]
[SecuritySafeCritical]
private TException TraceException<TException>(TException exception, string eventSource)
where TException : Exception
{
if (TraceCore.ThrowingExceptionIsEnabled(_diagnosticTrace))
{
TraceCore.ThrowingException(_diagnosticTrace, eventSource, exception != null ? exception.ToString() : string.Empty, exception);
}
BreakOnException(exception);
return exception;
}
[Fx.Tag.SecurityNote(Critical = "Calls into critical method UnsafeNativeMethods.IsDebuggerPresent and UnsafeNativeMethods.DebugBreak",
Safe = "Safe because it's a no-op in retail builds.")]
[SecuritySafeCritical]
private void BreakOnException(Exception exception)
{
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal void TraceFailFast(string message)
{
}
}
}
| |
namespace Spring.Expressions.Parser.antlr
{
/* ANTLR Translator Generator
* Project led by Terence Parr at http://www.jGuru.com
* Software rights: http://www.antlr.org/license.html
*/
//
// ANTLR C# Code Generator by Micheal Jordan
// Kunle Odutola : kunle UNDERSCORE odutola AT hotmail DOT com
// Anthony Oguntimehin
//
using IList = System.Collections.IList;
using IDictionary = System.Collections.IDictionary;
using ArrayList = System.Collections.ArrayList;
using Hashtable = System.Collections.Hashtable;
using IComparer = System.Collections.IComparer;
using StringBuilder = System.Text.StringBuilder;
using BitSet = antlr.collections.impl.BitSet;
/// <summary>
/// This token stream tracks the *entire* token stream coming from
/// a lexer, but does not pass on the whitespace (or whatever else
/// you want to discard) to the parser.
/// </summary>
/// <remarks>
/// <para>
/// This class can then be asked for the ith token in the input stream.
/// Useful for dumping out the input stream exactly after doing some
/// augmentation or other manipulations. Tokens are index from 0..n-1
/// </para>
/// <para>
/// You can insert stuff, replace, and delete chunks. Note that the
/// operations are done lazily--only if you convert the buffer to a
/// string. This is very efficient because you are not moving data around
/// all the time. As the buffer of tokens is converted to strings, the
/// toString() method(s) check to see if there is an operation at the
/// current index. If so, the operation is done and then normal string
/// rendering continues on the buffer. This is like having multiple Turing
/// machine instruction streams (programs) operating on a single input tape. :)
/// </para>
/// <para>
/// Since the operations are done lazily at toString-time, operations do not
/// screw up the token index values. That is, an insert operation at token
/// index i does not change the index values for tokens i+1..n-1.
/// </para>
/// <para>
/// Because operations never actually alter the buffer, you may always get
/// the original token stream back without undoing anything. Since
/// the instructions are queued up, you can easily simulate transactions and
/// roll back any changes if there is an error just by removing instructions.
/// For example,
/// </para>
/// <example>For example:
/// <code>
/// TokenStreamRewriteEngine rewriteEngine = new TokenStreamRewriteEngine(lexer);
/// JavaRecognizer parser = new JavaRecognizer(rewriteEngine);
/// ...
/// rewriteEngine.insertAfter("pass1", t, "foobar");}
/// rewriteEngine.insertAfter("pass2", u, "start");}
/// System.Console.Out.WriteLine(rewriteEngine.ToString("pass1"));
/// System.Console.Out.WriteLine(rewriteEngine.ToString("pass2"));
/// </code>
/// </example>
/// <para>
/// You can also have multiple "instruction streams" and get multiple
/// rewrites from a single pass over the input. Just name the instruction
/// streams and use that name again when printing the buffer. This could be
/// useful for generating a C file and also its header file--all from the
/// same buffer.
/// </para>
/// <para>
/// If you don't use named rewrite streams, a "default" stream is used.
/// </para>
/// <para>
/// Terence Parr, [email protected]
/// University of San Francisco
/// February 2004
/// </para>
/// </remarks>
public class TokenStreamRewriteEngine : TokenStream
{
public const int MIN_TOKEN_INDEX = 0;
protected class RewriteOperation
{
protected internal int index;
protected internal string text;
protected RewriteOperation(int index, string text)
{
this.index = index;
this.text = text;
}
/// <summary>
/// Execute the rewrite operation by possibly adding to the buffer.
/// </summary>
/// <param name="buf">rewrite buffer</param>
/// <returns>The index of the next token to operate on.</returns>
public virtual int execute(StringBuilder buf)
{
return index;
}
}
protected class InsertBeforeOp : RewriteOperation
{
public InsertBeforeOp(int index, string text) : base(index, text)
{
}
public override int execute(StringBuilder buf)
{
buf.Append(text);
return index;
}
}
protected class ReplaceOp : RewriteOperation
{
protected int lastIndex;
public ReplaceOp(int from, int to, string text) : base(from, text)
{
lastIndex = to;
}
public override int execute(StringBuilder buf)
{
if ( text != null )
{
buf.Append(text);
}
return lastIndex+1;
}
}
protected class DeleteOp : ReplaceOp
{
public DeleteOp(int from, int to) : base(from, to, null)
{
}
}
public const string DEFAULT_PROGRAM_NAME = "default";
public const int PROGRAM_INIT_SIZE = 100;
/// <summary>
/// Track the incoming list of tokens
/// </summary>
protected IList tokens;
/// <summary>
/// You may have multiple, named streams of rewrite operations.
/// I'm calling these things "programs."
/// Maps string (name) -> rewrite (List)
/// </summary>
protected IDictionary programs = null;
/// <summary>
/// Map string (program name) -> Integer index
/// </summary>
protected IDictionary lastRewriteTokenIndexes = null;
/// <summary>
/// track index of tokens
/// </summary>
protected int index = MIN_TOKEN_INDEX;
/// <summary>
/// Who do we suck tokens from?
/// </summary>
protected TokenStream stream;
/// <summary>
/// Which (whitespace) token(s) to throw out
/// </summary>
protected BitSet discardMask = new BitSet();
public TokenStreamRewriteEngine(TokenStream upstream) : this(upstream, 1000)
{
}
public TokenStreamRewriteEngine(TokenStream upstream, int initialSize)
{
stream = upstream;
tokens = new ArrayList(initialSize);
programs = new Hashtable();
programs[DEFAULT_PROGRAM_NAME] = new ArrayList(PROGRAM_INIT_SIZE);
lastRewriteTokenIndexes = new Hashtable();
}
public IToken nextToken() // throws TokenStreamException
{
TokenWithIndex t;
// suck tokens until end of stream or we find a non-discarded token
do
{
t = (TokenWithIndex) stream.nextToken();
if ( t != null )
{
t.setIndex(index); // what is t's index in list?
if ( t.Type != Token.EOF_TYPE )
{
tokens.Add(t); // track all tokens except EOF
}
index++; // move to next position
}
} while ( (t != null) && (discardMask.member(t.Type)) );
return t;
}
public void rollback(int instructionIndex)
{
rollback(DEFAULT_PROGRAM_NAME, instructionIndex);
}
/// <summary>
/// Rollback the instruction stream for a program so that
/// the indicated instruction (via instructionIndex) is no
/// longer in the stream.
/// </summary>
/// <remarks>
/// UNTESTED!
/// </remarks>
/// <param name="programName"></param>
/// <param name="instructionIndex"></param>
public void rollback(string programName, int instructionIndex)
{
ArrayList il = (ArrayList) programs[programName];
if ( il != null )
{
programs[programName] = il.GetRange(MIN_TOKEN_INDEX, (instructionIndex - MIN_TOKEN_INDEX));
}
}
public void deleteProgram()
{
deleteProgram(DEFAULT_PROGRAM_NAME);
}
/// <summary>
/// Reset the program so that no instructions exist
/// </summary>
/// <param name="programName"></param>
public void deleteProgram(string programName)
{
rollback(programName, MIN_TOKEN_INDEX);
}
/// <summary>
/// If op.index > lastRewriteTokenIndexes, just add to the end.
/// Otherwise, do linear
/// </summary>
/// <param name="op"></param>
protected void addToSortedRewriteList(RewriteOperation op)
{
addToSortedRewriteList(DEFAULT_PROGRAM_NAME, op);
}
protected void addToSortedRewriteList(string programName, RewriteOperation op)
{
ArrayList rewrites = (ArrayList) getProgram(programName);
// if at or beyond last op's index, just append
if ( op.index >= getLastRewriteTokenIndex(programName) )
{
rewrites.Add(op); // append to list of operations
// record the index of this operation for next time through
setLastRewriteTokenIndex(programName, op.index);
return;
}
// not after the last one, so must insert to ordered list
int pos = rewrites.BinarySearch(op, RewriteOperationComparer.Default);
if (pos < 0)
{
rewrites.Insert(-pos-1, op);
}
}
public void insertAfter(IToken t, string text)
{
insertAfter(DEFAULT_PROGRAM_NAME, t, text);
}
public void insertAfter(int index, string text)
{
insertAfter(DEFAULT_PROGRAM_NAME, index, text);
}
public void insertAfter(string programName, IToken t, string text)
{
insertAfter(programName,((TokenWithIndex) t).getIndex(), text);
}
public void insertAfter(string programName, int index, string text)
{
// to insert after, just insert before next index (even if past end)
insertBefore(programName, index+1, text);
}
public void insertBefore(IToken t, string text)
{
insertBefore(DEFAULT_PROGRAM_NAME, t, text);
}
public void insertBefore(int index, string text)
{
insertBefore(DEFAULT_PROGRAM_NAME, index, text);
}
public void insertBefore(string programName, IToken t, string text)
{
insertBefore(programName, ((TokenWithIndex) t).getIndex(), text);
}
public void insertBefore(string programName, int index, string text)
{
addToSortedRewriteList(programName, new InsertBeforeOp(index, text));
}
public void replace(int index, string text)
{
replace(DEFAULT_PROGRAM_NAME, index, index, text);
}
public void replace(int from, int to, string text)
{
replace(DEFAULT_PROGRAM_NAME, from, to, text);
}
public void replace(IToken indexT, string text)
{
replace(DEFAULT_PROGRAM_NAME, indexT, indexT, text);
}
public void replace(IToken from, IToken to, string text)
{
replace(DEFAULT_PROGRAM_NAME, from, to, text);
}
public void replace(string programName, int from, int to, string text)
{
addToSortedRewriteList(new ReplaceOp(from, to, text));
}
public void replace(string programName, IToken from, IToken to, string text)
{
replace(programName,
((TokenWithIndex) from).getIndex(),
((TokenWithIndex) to).getIndex(),
text);
}
public void delete(int index)
{
delete(DEFAULT_PROGRAM_NAME, index, index);
}
public void delete(int from, int to)
{
delete(DEFAULT_PROGRAM_NAME, from, to);
}
public void delete(IToken indexT)
{
delete(DEFAULT_PROGRAM_NAME, indexT, indexT);
}
public void delete(IToken from, IToken to)
{
delete(DEFAULT_PROGRAM_NAME, from, to);
}
public void delete(string programName, int from, int to)
{
replace(programName, from, to, null);
}
public void delete(string programName, IToken from, IToken to)
{
replace(programName, from, to, null);
}
public void discard(int ttype)
{
discardMask.add(ttype);
}
public TokenWithIndex getToken(int i)
{
return (TokenWithIndex) tokens[i];
}
public int getTokenStreamSize()
{
return tokens.Count;
}
public string ToOriginalString()
{
return ToOriginalString(MIN_TOKEN_INDEX, getTokenStreamSize()-1);
}
public string ToOriginalString(int start, int end)
{
StringBuilder buf = new StringBuilder();
for (int i = start; (i >= MIN_TOKEN_INDEX) && (i <= end) && (i < tokens.Count); i++)
{
buf.Append(getToken(i).getText());
}
return buf.ToString();
}
public override string ToString()
{
return ToString(MIN_TOKEN_INDEX, getTokenStreamSize());
}
public string ToString(string programName)
{
return ToString(programName, MIN_TOKEN_INDEX, getTokenStreamSize());
}
public string ToString(int start, int end)
{
return ToString(DEFAULT_PROGRAM_NAME, start, end);
}
public string ToString(string programName, int start, int end)
{
IList rewrites = (IList) programs[programName];
if (rewrites == null)
{
return null; // invalid program
}
StringBuilder buf = new StringBuilder();
// Index of first rewrite we have not done
int rewriteOpIndex = 0;
int tokenCursor = start;
while ( (tokenCursor >= MIN_TOKEN_INDEX) &&
(tokenCursor <= end) &&
(tokenCursor < tokens.Count) )
{
if (rewriteOpIndex < rewrites.Count)
{
RewriteOperation op = (RewriteOperation) rewrites[rewriteOpIndex];
while ( (tokenCursor == op.index) && (rewriteOpIndex < rewrites.Count) )
{
/*
Console.Out.WriteLine("execute op "+rewriteOpIndex+
" (type "+op.GetType().FullName+")"
+" at index "+op.index);
*/
tokenCursor = op.execute(buf);
rewriteOpIndex++;
if (rewriteOpIndex < rewrites.Count)
{
op = (RewriteOperation) rewrites[rewriteOpIndex];
}
}
}
if ( tokenCursor < end )
{
buf.Append(getToken(tokenCursor).getText());
tokenCursor++;
}
}
// now see if there are operations (append) beyond last token index
for (int opi = rewriteOpIndex; opi < rewrites.Count; opi++)
{
RewriteOperation op = (RewriteOperation) rewrites[opi];
op.execute(buf); // must be insertions if after last token
}
return buf.ToString();
}
public string ToDebugString()
{
return ToDebugString(MIN_TOKEN_INDEX, getTokenStreamSize());
}
public string ToDebugString(int start, int end)
{
StringBuilder buf = new StringBuilder();
for (int i = start; (i >= MIN_TOKEN_INDEX) && (i <= end) && (i < tokens.Count); i++)
{
buf.Append(getToken(i));
}
return buf.ToString();
}
public int getLastRewriteTokenIndex()
{
return getLastRewriteTokenIndex(DEFAULT_PROGRAM_NAME);
}
protected int getLastRewriteTokenIndex(string programName)
{
object i = lastRewriteTokenIndexes[programName];
if (i == null)
{
return -1;
}
return (int) i;
}
protected void setLastRewriteTokenIndex(string programName, int i)
{
lastRewriteTokenIndexes[programName] = (object) i;
}
protected IList getProgram(string name)
{
IList il = (IList) programs[name];
if ( il == null )
{
il = initializeProgram(name);
}
return il;
}
private IList initializeProgram(string name)
{
IList il = new ArrayList(PROGRAM_INIT_SIZE);
programs[name] = il;
return il;
}
public class RewriteOperationComparer : IComparer
{
public static readonly RewriteOperationComparer Default = new RewriteOperationComparer();
public virtual int Compare(object o1, object o2)
{
RewriteOperation rop1 = (RewriteOperation) o1;
RewriteOperation rop2 = (RewriteOperation) o2;
if (rop1.index < rop2.index) return -1;
if (rop1.index > rop2.index) return 1;
return 0;
}
}
}
}
| |
//***************************************************
//* This file was generated by tool
//* SharpKit
//* At: 29/08/2012 03:59:40 p.m.
//***************************************************
using SharpKit.JavaScript;
namespace Ext.dd
{
#region Registry
/// <inheritdocs />
/// <summary>
/// <p>Provides easy access to all drag drop components that are registered on a page. Items can be retrieved either
/// directly by DOM node id, or by passing in the drag drop event that occurred and looking up the event target.</p>
/// </summary>
[JsType(JsMode.Prototype, Export=false, OmitOptionalParameters=true)]
public partial class Registry : Ext.Base
{
/// <summary>
/// Defaults to: <c>"Ext.Base"</c>
/// </summary>
[JsProperty(Name="$className")]
private static JsString @className{get;set;}
/// <summary>
/// Defaults to: <c>{}</c>
/// </summary>
private static JsObject configMap{get;set;}
/// <summary>
/// Defaults to: <c>[]</c>
/// </summary>
private static JsArray initConfigList{get;set;}
/// <summary>
/// Defaults to: <c>{}</c>
/// </summary>
private static JsObject initConfigMap{get;set;}
/// <summary>
/// Defaults to: <c>true</c>
/// </summary>
private static bool isInstance{get;set;}
/// <summary>
/// Get the reference to the current class from which this object was instantiated. Unlike statics,
/// this.self is scope-dependent and it's meant to be used for dynamic inheritance. See statics
/// for a detailed comparison
/// <code><see cref="Ext.ExtContext.define">Ext.define</see>('My.Cat', {
/// statics: {
/// speciesName: 'Cat' // My.Cat.speciesName = 'Cat'
/// },
/// constructor: function() {
/// alert(this.self.speciesName); // dependent on 'this'
/// },
/// clone: function() {
/// return new this.self();
/// }
/// });
/// <see cref="Ext.ExtContext.define">Ext.define</see>('My.SnowLeopard', {
/// extend: 'My.Cat',
/// statics: {
/// speciesName: 'Snow Leopard' // My.SnowLeopard.speciesName = 'Snow Leopard'
/// }
/// });
/// var cat = new My.Cat(); // alerts 'Cat'
/// var snowLeopard = new My.SnowLeopard(); // alerts 'Snow Leopard'
/// var clone = snowLeopard.clone();
/// alert(<see cref="Ext.ExtContext.getClassName">Ext.getClassName</see>(clone)); // alerts 'My.SnowLeopard'
/// </code>
/// </summary>
protected static Class self{get;set;}
/// <summary>
/// Call the original method that was previously overridden with override
/// <code><see cref="Ext.ExtContext.define">Ext.define</see>('My.Cat', {
/// constructor: function() {
/// alert("I'm a cat!");
/// }
/// });
/// My.Cat.override({
/// constructor: function() {
/// alert("I'm going to be a cat!");
/// this.callOverridden();
/// alert("Meeeeoooowwww");
/// }
/// });
/// var kitty = new My.Cat(); // alerts "I'm going to be a cat!"
/// // alerts "I'm a cat!"
/// // alerts "Meeeeoooowwww"
/// </code>
/// <p>This method has been <strong>deprecated</strong> </p>
/// <p>as of 4.1. Use <see cref="Ext.Base.callParent">callParent</see> instead.</p>
/// </summary>
/// <param name="args"><p>The arguments, either an array or the <c>arguments</c> object
/// from the current method, for example: <c>this.callOverridden(arguments)</c></p>
/// </param>
/// <returns>
/// <span><see cref="Object">Object</see></span><div><p>Returns the result of calling the overridden method</p>
/// </div>
/// </returns>
protected static object callOverridden(object args=null){return null;}
/// <summary>
/// Call the "parent" method of the current method. That is the method previously
/// overridden by derivation or by an override (see Ext.define).
/// <code> <see cref="Ext.ExtContext.define">Ext.define</see>('My.Base', {
/// constructor: function (x) {
/// this.x = x;
/// },
/// statics: {
/// method: function (x) {
/// return x;
/// }
/// }
/// });
/// <see cref="Ext.ExtContext.define">Ext.define</see>('My.Derived', {
/// extend: 'My.Base',
/// constructor: function () {
/// this.callParent([21]);
/// }
/// });
/// var obj = new My.Derived();
/// alert(obj.x); // alerts 21
/// </code>
/// This can be used with an override as follows:
/// <code> <see cref="Ext.ExtContext.define">Ext.define</see>('My.DerivedOverride', {
/// override: 'My.Derived',
/// constructor: function (x) {
/// this.callParent([x*2]); // calls original My.Derived constructor
/// }
/// });
/// var obj = new My.Derived();
/// alert(obj.x); // now alerts 42
/// </code>
/// This also works with static methods.
/// <code> <see cref="Ext.ExtContext.define">Ext.define</see>('My.Derived2', {
/// extend: 'My.Base',
/// statics: {
/// method: function (x) {
/// return this.callParent([x*2]); // calls My.Base.method
/// }
/// }
/// });
/// alert(My.Base.method(10); // alerts 10
/// alert(My.Derived2.method(10); // alerts 20
/// </code>
/// Lastly, it also works with overridden static methods.
/// <code> <see cref="Ext.ExtContext.define">Ext.define</see>('My.Derived2Override', {
/// override: 'My.Derived2',
/// statics: {
/// method: function (x) {
/// return this.callParent([x*2]); // calls My.Derived2.method
/// }
/// }
/// });
/// alert(My.Derived2.method(10); // now alerts 40
/// </code>
/// </summary>
/// <param name="args"><p>The arguments, either an array or the <c>arguments</c> object
/// from the current method, for example: <c>this.callParent(arguments)</c></p>
/// </param>
/// <returns>
/// <span><see cref="Object">Object</see></span><div><p>Returns the result of calling the parent method</p>
/// </div>
/// </returns>
protected static object callParent(object args=null){return null;}
/// <summary>
/// </summary>
private static void configClass(){}
/// <summary>
/// Overrides: <see cref="Ext.AbstractComponent.destroy">Ext.AbstractComponent.destroy</see>, <see cref="Ext.AbstractPlugin.destroy">Ext.AbstractPlugin.destroy</see>, <see cref="Ext.layout.Layout.destroy">Ext.layout.Layout.destroy</see>
/// </summary>
private static void destroy(){}
/// <summary>
/// Parameters<li><span>name</span> : <see cref="Object">Object</see><div>
/// </div></li>
/// </summary>
/// <param name="name">
/// </param>
private static void getConfig(object name){}
/// <summary>
/// Returns the handle registered for a DOM Node by id
/// </summary>
/// <param name="id"><p>The DOM node or id to look up</p>
/// </param>
/// <returns>
/// <span><see cref="Object">Object</see></span><div><p>handle The custom handle data</p>
/// </div>
/// </returns>
public static object getHandle(object id){return null;}
/// <summary>
/// Returns the handle that is registered for the DOM node that is the target of the event
/// </summary>
/// <param name="e"><p>The event</p>
/// </param>
/// <returns>
/// <span><see cref="Object">Object</see></span><div><p>handle The custom handle data</p>
/// </div>
/// </returns>
public static object getHandleFromEvent(object e){return null;}
/// <summary>
/// Returns the initial configuration passed to constructor when instantiating
/// this class.
/// </summary>
/// <param name="name"><p>Name of the config option to return.</p>
/// </param>
/// <returns>
/// <span><see cref="Object">Object</see>/Mixed</span><div><p>The full config object or a single config value
/// when <c>name</c> parameter specified.</p>
/// </div>
/// </returns>
public static object getInitialConfig(object name=null){return null;}
/// <summary>
/// Returns a custom data object that is registered for a DOM node by id
/// </summary>
/// <param name="id"><p>The DOM node or id to look up</p>
/// </param>
/// <returns>
/// <span><see cref="Object">Object</see></span><div><p>data The custom data</p>
/// </div>
/// </returns>
public static object getTarget(object id){return null;}
/// <summary>
/// Returns a custom data object that is registered for the DOM node that is the target of the event
/// </summary>
/// <param name="e"><p>The event</p>
/// </param>
/// <returns>
/// <span><see cref="Object">Object</see></span><div><p>data The custom data</p>
/// </div>
/// </returns>
public static object getTargetFromEvent(object e){return null;}
/// <summary>
/// Parameters<li><span>config</span> : <see cref="Object">Object</see><div>
/// </div></li>
/// </summary>
/// <param name="config">
/// </param>
private static void hasConfig(object config){}
/// <summary>
/// Initialize configuration for this class. a typical example:
/// <code><see cref="Ext.ExtContext.define">Ext.define</see>('My.awesome.Class', {
/// // The default config
/// config: {
/// name: 'Awesome',
/// isAwesome: true
/// },
/// constructor: function(config) {
/// this.initConfig(config);
/// }
/// });
/// var awesome = new My.awesome.Class({
/// name: 'Super Awesome'
/// });
/// alert(awesome.getName()); // 'Super Awesome'
/// </code>
/// </summary>
/// <param name="config">
/// </param>
/// <returns>
/// <span><see cref="Ext.Base">Ext.Base</see></span><div><p>this</p>
/// </div>
/// </returns>
protected static Ext.Base initConfig(object config){return null;}
/// <summary>
/// Parameters<li><span>names</span> : <see cref="Object">Object</see><div>
/// </div></li><li><span>callback</span> : <see cref="Object">Object</see><div>
/// </div></li><li><span>scope</span> : <see cref="Object">Object</see><div>
/// </div></li>
/// </summary>
/// <param name="names">
/// </param>
/// <param name="callback">
/// </param>
/// <param name="scope">
/// </param>
private static void onConfigUpdate(object names, object callback, object scope){}
/// <summary>
/// Registers a drag drop element.
/// </summary>
/// <param name="element"><p>The id or DOM node to register</p>
/// </param>
/// <param name="data"><p>An custom data object that will be passed between the elements that are involved in drag
/// drop operations. You can populate this object with any arbitrary properties that your own code knows how to
/// interpret, plus there are some specific properties known to the Registry that should be populated in the data
/// object (if applicable):</p>
/// <ul><li><span>handles</span> : HTMLElement[]<div><p>Array of DOM nodes that trigger dragging for the element being registered.</p>
/// </div></li><li><span>isHandle</span> : <see cref="bool">Boolean</see><div><p>True if the element passed in triggers dragging itself, else false.</p>
/// </div></li></ul></param>
public static void register(object element, JsArray<Object> data){}
/// <summary>
/// Parameters<li><span>config</span> : <see cref="Object">Object</see><div>
/// </div></li><li><span>applyIfNotSet</span> : <see cref="Object">Object</see><div>
/// </div></li>
/// </summary>
/// <param name="config">
/// </param>
/// <param name="applyIfNotSet">
/// </param>
private static void setConfig(object config, object applyIfNotSet){}
/// <summary>
/// Get the reference to the class from which this object was instantiated. Note that unlike self,
/// this.statics() is scope-independent and it always returns the class from which it was called, regardless of what
/// this points to during run-time
/// <code><see cref="Ext.ExtContext.define">Ext.define</see>('My.Cat', {
/// statics: {
/// totalCreated: 0,
/// speciesName: 'Cat' // My.Cat.speciesName = 'Cat'
/// },
/// constructor: function() {
/// var statics = this.statics();
/// alert(statics.speciesName); // always equals to 'Cat' no matter what 'this' refers to
/// // equivalent to: My.Cat.speciesName
/// alert(this.self.speciesName); // dependent on 'this'
/// statics.totalCreated++;
/// },
/// clone: function() {
/// var cloned = new this.self; // dependent on 'this'
/// cloned.groupName = this.statics().speciesName; // equivalent to: My.Cat.speciesName
/// return cloned;
/// }
/// });
/// <see cref="Ext.ExtContext.define">Ext.define</see>('My.SnowLeopard', {
/// extend: 'My.Cat',
/// statics: {
/// speciesName: 'Snow Leopard' // My.SnowLeopard.speciesName = 'Snow Leopard'
/// },
/// constructor: function() {
/// this.callParent();
/// }
/// });
/// var cat = new My.Cat(); // alerts 'Cat', then alerts 'Cat'
/// var snowLeopard = new My.SnowLeopard(); // alerts 'Cat', then alerts 'Snow Leopard'
/// var clone = snowLeopard.clone();
/// alert(<see cref="Ext.ExtContext.getClassName">Ext.getClassName</see>(clone)); // alerts 'My.SnowLeopard'
/// alert(clone.groupName); // alerts 'Cat'
/// alert(My.Cat.totalCreated); // alerts 3
/// </code>
/// </summary>
/// <returns>
/// <span><see cref="Ext.Class">Ext.Class</see></span><div>
/// </div>
/// </returns>
protected static Class statics(){return null;}
/// <summary>
/// Unregister a drag drop element
/// </summary>
/// <param name="element"><p>The id or DOM node to unregister</p>
/// </param>
public static void unregister(object element){}
public Registry(RegistryConfig config){}
public Registry(){}
public Registry(params object[] args){}
}
#endregion
#region RegistryConfig
/// <inheritdocs />
[JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)]
public partial class RegistryConfig : Ext.BaseConfig
{
public RegistryConfig(params object[] args){}
}
#endregion
#region RegistryEvents
/// <inheritdocs />
[JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)]
public partial class RegistryEvents : Ext.BaseEvents
{
public RegistryEvents(params object[] args){}
}
#endregion
}
| |
/****************************************************************************
Tilde
Copyright (c) 2008 Tantalus Media Pty
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Tilde.Framework.Controller;
using Tilde.Framework.Model;
namespace Tilde.LuaDebugger
{
public partial class MainWindowComponents : UserControl
{
DebugManager mDebugger;
public MainWindowComponents(DebugManager debugger)
{
mDebugger = debugger;
InitializeComponent();
mDebugger.DebuggerConnecting += new DebuggerConnectingEventHandler(Debugger_DebuggerConnecting);
mDebugger.DebuggerConnected += new DebuggerConnectedEventHandler(Debugger_DebuggerConnected);
mDebugger.DebuggerDisconnecting += new DebuggerDisconnectingEventHandler(Debugger_DebuggerDisconnecting);
mDebugger.DebuggerDisconnected += new DebuggerDisconnectedEventHandler(Debugger_DebuggerDisconnected);
mDebugger.Manager.ActiveDocumentChanged += new ActiveDocumentChangedEventHandler(Manager_ActiveDocumentChanged);
UpdateMenuStatus();
}
void Debugger_DebuggerConnecting(DebugManager sender, Target target)
{
UpdateMenuStatus();
}
void Debugger_DebuggerDisconnecting(DebugManager sender, Target target)
{
target.StateUpdate -= new StateUpdateEventHandler(target_StateUpdate);
UpdateMenuStatus();
}
void Debugger_DebuggerConnected(DebugManager sender, Target target)
{
target.StateUpdate += new StateUpdateEventHandler(target_StateUpdate);
target.ExMessage += new ExMessageEventHandler(target_ExCommandResult);
UpdateMenuStatus();
}
void Debugger_DebuggerDisconnected(DebugManager sender)
{
UpdateMenuStatus();
}
void target_StateUpdate(Target sender, StateUpdateEventArgs args)
{
UpdateMenuStatus();
}
void target_ExCommandResult(Target sender, ExMessageEventArgs args)
{
if (args.Command == "StartProfile")
mDebugger.ShowStatusMessage("Lua Profile Started...");
else if (args.Command == "StopProfile")
mDebugger.ShowStatusMessage("Lua Profile Stopped!");
}
void Manager_ActiveDocumentChanged(object sender, Document document)
{
UpdateMenuStatus();
}
void UpdateMenuStatus()
{
bool isBreaked = (mDebugger.TargetStatus == TargetState.Breaked || mDebugger.TargetStatus == TargetState.Error);
bool isRunning = (mDebugger.TargetStatus == TargetState.Running);
btnConnect.Enabled = connectToolStripMenuItem.Enabled = (mDebugger.ConnectionStatus == ConnectionStatus.NotConnected);
btnDisconnect.Enabled = disconnectToolStripMenuItem.Enabled = (mDebugger.ConnectionStatus == ConnectionStatus.Connected || mDebugger.ConnectionStatus == ConnectionStatus.Connecting);
reconnectToolStripMenuItem.Enabled = (mDebugger.ConnectionStatus == ConnectionStatus.Connected);
btnStartProfile.Enabled = (mDebugger.ConnectionStatus == ConnectionStatus.Connected);
btnStopProfile.Enabled = (mDebugger.ConnectionStatus == ConnectionStatus.Connected);
btnRun.Enabled = isBreaked;
btnBreak.Enabled = isRunning;
runToolStripMenuItem.Enabled = isBreaked || mDebugger.ConnectionStatus == ConnectionStatus.Disconnecting || mDebugger.ConnectionStatus == ConnectionStatus.NotConnected;
stepToolStripMenuItem.Enabled = isBreaked;
stepIntoToolStripMenuItem.Enabled = isBreaked;
stepOutToolStripMenuItem.Enabled = isBreaked;
breakToolStripMenuItem.Enabled = isRunning;
buildAndRestartToolStripMenuItem.Enabled = !mDebugger.IsBuildInProgress;
cancelBuildToolStripMenuItem.Enabled = mDebugger.IsBuildInProgress;
}
private void connectToolStripMenuItem_Click(object sender, EventArgs e)
{
TargetConnectionDialog dlg = new TargetConnectionDialog(mDebugger);
if (dlg.ShowDialog() == DialogResult.OK)
{
mDebugger.Connect(dlg.Selection);
}
}
private void disconnectToolStripMenuItem_Click(object sender, EventArgs e)
{
mDebugger.Disconnect(false, true);
}
private void runToolStripMenuItem_Click(object sender, EventArgs e)
{
if (mDebugger.ConnectedTarget != null)
mDebugger.ConnectedTarget.Run(ExecutionMode.Go);
else
mDebugger.Run();
}
private void stepToolStripMenuItem_Click(object sender, EventArgs e)
{
if (mDebugger.ConnectedTarget != null)
mDebugger.ConnectedTarget.Run(ExecutionMode.StepOver);
}
private void stepIntoToolStripMenuItem_Click(object sender, EventArgs e)
{
if (mDebugger.ConnectedTarget != null)
mDebugger.ConnectedTarget.Run(ExecutionMode.StepInto);
}
private void stepOutToolStripMenuItem_Click(object sender, EventArgs e)
{
if (mDebugger.ConnectedTarget != null)
mDebugger.ConnectedTarget.Run(ExecutionMode.StepOut);
}
private void breakToolStripMenuItem_Click(object sender, EventArgs e)
{
if (mDebugger.ConnectedTarget != null)
mDebugger.ConnectedTarget.Run(ExecutionMode.Break);
}
private void reconnectToolStripMenuItem_Click(object sender, EventArgs e)
{
if(mDebugger.ConnectedTarget != null && mDebugger.ConnectionStatus == ConnectionStatus.Connected)
{
HostInfo currHost = mDebugger.ConnectedTarget.HostInfo;
mDebugger.Disconnect(false, false);
mDebugger.Connect(currHost);
}
}
private void btnStartProfile_Click(object sender, EventArgs e)
{
if (mDebugger.ConnectedTarget != null)
mDebugger.ConnectedTarget.ExCommand("StartProfile", null);
}
private void btnStopProfile_Click(object sender, EventArgs e)
{
if (mDebugger.ConnectedTarget != null)
mDebugger.ConnectedTarget.ExCommand("StopProfile", null);
}
private void notifyIcon_BalloonTipClicked(object sender, EventArgs e)
{
mDebugger.MainWindow.Activate();
}
private void notifyIcon_DoubleClick(object sender, EventArgs e)
{
mDebugger.MainWindow.Activate();
}
private void buildToolStripMenuItem_Click(object sender, EventArgs e)
{
mDebugger.Build();
}
private void buildAndRestartToolStripMenuItem_Click(object sender, EventArgs e)
{
mDebugger.BuildAndRun();
}
private void stopToolStripMenuItem_Click(object sender, EventArgs e)
{
mDebugger.StopTarget();
}
private void cancelBuildToolStripMenuItem_Click(object sender, EventArgs e)
{
mDebugger.CancelBuild();
}
}
}
| |
//
// 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.SiteRecovery;
using Microsoft.Azure.Management.SiteRecovery.Models;
namespace Microsoft.Azure.Management.SiteRecovery
{
public static partial class FabricOperationsExtensions
{
/// <summary>
/// Creates a Fabric
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='input'>
/// Required. Input to create fabric
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static LongRunningOperationResponse BeginCreating(this IFabricOperations operations, string fabricName, FabricCreationInput input, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IFabricOperations)s).BeginCreatingAsync(fabricName, input, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a Fabric
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='input'>
/// Required. Input to create fabric
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static Task<LongRunningOperationResponse> BeginCreatingAsync(this IFabricOperations operations, string fabricName, FabricCreationInput input, CustomRequestHeaders customRequestHeaders)
{
return operations.BeginCreatingAsync(fabricName, input, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Deletes a Fabric
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='input'>
/// Required. Fabric deletion input.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static LongRunningOperationResponse BeginDeleting(this IFabricOperations operations, string fabricName, FabricDeletionInput input, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IFabricOperations)s).BeginDeletingAsync(fabricName, input, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a Fabric
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='input'>
/// Required. Fabric deletion input.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static Task<LongRunningOperationResponse> BeginDeletingAsync(this IFabricOperations operations, string fabricName, FabricDeletionInput input, CustomRequestHeaders customRequestHeaders)
{
return operations.BeginDeletingAsync(fabricName, input, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Purges a Fabric
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static LongRunningOperationResponse BeginPurging(this IFabricOperations operations, string fabricName, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IFabricOperations)s).BeginPurgingAsync(fabricName, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Purges a Fabric
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static Task<LongRunningOperationResponse> BeginPurgingAsync(this IFabricOperations operations, string fabricName, CustomRequestHeaders customRequestHeaders)
{
return operations.BeginPurgingAsync(fabricName, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Performs reassociate gateway operation on a fabric.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='input'>
/// Required. Input to reassociate a gateway.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static LongRunningOperationResponse BeginReassociateGateway(this IFabricOperations operations, string fabricName, FailoverProcessServerRequest input, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IFabricOperations)s).BeginReassociateGatewayAsync(fabricName, input, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Performs reassociate gateway operation on a fabric.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='input'>
/// Required. Input to reassociate a gateway.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static Task<LongRunningOperationResponse> BeginReassociateGatewayAsync(this IFabricOperations operations, string fabricName, FailoverProcessServerRequest input, CustomRequestHeaders customRequestHeaders)
{
return operations.BeginReassociateGatewayAsync(fabricName, input, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Renews certificates of a Fabric
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static LongRunningOperationResponse BeginRenewCertificate(this IFabricOperations operations, string fabricName, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IFabricOperations)s).BeginRenewCertificateAsync(fabricName, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Renews certificates of a Fabric
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static Task<LongRunningOperationResponse> BeginRenewCertificateAsync(this IFabricOperations operations, string fabricName, CustomRequestHeaders customRequestHeaders)
{
return operations.BeginRenewCertificateAsync(fabricName, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Creates a fabric
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='input'>
/// Required. Input to create fabric
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static LongRunningOperationResponse Create(this IFabricOperations operations, string fabricName, FabricCreationInput input, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IFabricOperations)s).CreateAsync(fabricName, input, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a fabric
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='input'>
/// Required. Input to create fabric
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static Task<LongRunningOperationResponse> CreateAsync(this IFabricOperations operations, string fabricName, FabricCreationInput input, CustomRequestHeaders customRequestHeaders)
{
return operations.CreateAsync(fabricName, input, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Deletes a fabric
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='fabricDeletionInput'>
/// Required. Fabric deletion input.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static LongRunningOperationResponse Delete(this IFabricOperations operations, string fabricName, FabricDeletionInput fabricDeletionInput, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IFabricOperations)s).DeleteAsync(fabricName, fabricDeletionInput, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a fabric
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='fabricDeletionInput'>
/// Required. Fabric deletion input.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static Task<LongRunningOperationResponse> DeleteAsync(this IFabricOperations operations, string fabricName, FabricDeletionInput fabricDeletionInput, CustomRequestHeaders customRequestHeaders)
{
return operations.DeleteAsync(fabricName, fabricDeletionInput, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Get the server object by Id.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the fabric object
/// </returns>
public static FabricResponse Get(this IFabricOperations operations, string fabricName, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IFabricOperations)s).GetAsync(fabricName, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get the server object by Id.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the fabric object
/// </returns>
public static Task<FabricResponse> GetAsync(this IFabricOperations operations, string fabricName, CustomRequestHeaders customRequestHeaders)
{
return operations.GetAsync(fabricName, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <returns>
/// A standard service response for fabric long running operations.
/// </returns>
public static FabricOperationResponse GetCreateStatus(this IFabricOperations operations, string operationStatusLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IFabricOperations)s).GetCreateStatusAsync(operationStatusLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <returns>
/// A standard service response for fabric long running operations.
/// </returns>
public static Task<FabricOperationResponse> GetCreateStatusAsync(this IFabricOperations operations, string operationStatusLink)
{
return operations.GetCreateStatusAsync(operationStatusLink, CancellationToken.None);
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static LongRunningOperationResponse GetDeleteStatus(this IFabricOperations operations, string operationStatusLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IFabricOperations)s).GetDeleteStatusAsync(operationStatusLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static Task<LongRunningOperationResponse> GetDeleteStatusAsync(this IFabricOperations operations, string operationStatusLink)
{
return operations.GetDeleteStatusAsync(operationStatusLink, CancellationToken.None);
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static LongRunningOperationResponse GetPurgeStatus(this IFabricOperations operations, string operationStatusLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IFabricOperations)s).GetPurgeStatusAsync(operationStatusLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static Task<LongRunningOperationResponse> GetPurgeStatusAsync(this IFabricOperations operations, string operationStatusLink)
{
return operations.GetPurgeStatusAsync(operationStatusLink, CancellationToken.None);
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static ReassociateGatewayOperationResponse GetReassociateGatewayStatus(this IFabricOperations operations, string operationStatusLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IFabricOperations)s).GetReassociateGatewayStatusAsync(operationStatusLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static Task<ReassociateGatewayOperationResponse> GetReassociateGatewayStatusAsync(this IFabricOperations operations, string operationStatusLink)
{
return operations.GetReassociateGatewayStatusAsync(operationStatusLink, CancellationToken.None);
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <returns>
/// A standard service response for fabric long running operations.
/// </returns>
public static FabricOperationResponse GetRenewCertificateStatus(this IFabricOperations operations, string operationStatusLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IFabricOperations)s).GetRenewCertificateStatusAsync(operationStatusLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <returns>
/// A standard service response for fabric long running operations.
/// </returns>
public static Task<FabricOperationResponse> GetRenewCertificateStatusAsync(this IFabricOperations operations, string operationStatusLink)
{
return operations.GetRenewCertificateStatusAsync(operationStatusLink, CancellationToken.None);
}
/// <summary>
/// Get the list of all servers under the vault.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the list servers operation.
/// </returns>
public static FabricListResponse List(this IFabricOperations operations, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IFabricOperations)s).ListAsync(customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get the list of all servers under the vault.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the list servers operation.
/// </returns>
public static Task<FabricListResponse> ListAsync(this IFabricOperations operations, CustomRequestHeaders customRequestHeaders)
{
return operations.ListAsync(customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Purges a fabric
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static LongRunningOperationResponse Purge(this IFabricOperations operations, string fabricName, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IFabricOperations)s).PurgeAsync(fabricName, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Purges a fabric
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static Task<LongRunningOperationResponse> PurgeAsync(this IFabricOperations operations, string fabricName, CustomRequestHeaders customRequestHeaders)
{
return operations.PurgeAsync(fabricName, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Performs reassociate gateway operation on a fabric.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='input'>
/// Required. Input to reassociate a gateway.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static LongRunningOperationResponse ReassociateGateway(this IFabricOperations operations, string fabricName, FailoverProcessServerRequest input, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IFabricOperations)s).ReassociateGatewayAsync(fabricName, input, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Performs reassociate gateway operation on a fabric.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='input'>
/// Required. Input to reassociate a gateway.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static Task<LongRunningOperationResponse> ReassociateGatewayAsync(this IFabricOperations operations, string fabricName, FailoverProcessServerRequest input, CustomRequestHeaders customRequestHeaders)
{
return operations.ReassociateGatewayAsync(fabricName, input, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Renews certificates of a Fabric
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static LongRunningOperationResponse RenewCertificate(this IFabricOperations operations, string fabricName, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IFabricOperations)s).RenewCertificateAsync(fabricName, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Renews certificates of a Fabric
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IFabricOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static Task<LongRunningOperationResponse> RenewCertificateAsync(this IFabricOperations operations, string fabricName, CustomRequestHeaders customRequestHeaders)
{
return operations.RenewCertificateAsync(fabricName, customRequestHeaders, 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.Collections.Generic;
using System.Net.Test.Common;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Sockets.Tests
{
public class SocketOptionNameTest
{
private static bool SocketsReuseUnicastPortSupport
{
get
{
return Capability.SocketsReuseUnicastPortSupport().HasValue &&
Capability.SocketsReuseUnicastPortSupport().Value;
}
}
private static bool NoSocketsReuseUnicastPortSupport
{
get
{
return Capability.SocketsReuseUnicastPortSupport().HasValue &&
!Capability.SocketsReuseUnicastPortSupport().Value;
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(NoSocketsReuseUnicastPortSupport))]
public void ReuseUnicastPort_CreateSocketGetOption_NoSocketsReuseUnicastPortSupport_Throws()
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Assert.Throws<SocketException>(() =>
socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseUnicastPort));
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(SocketsReuseUnicastPortSupport))]
public void ReuseUnicastPort_CreateSocketGetOption_SocketsReuseUnicastPortSupport_OptionIsZero()
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var optionValue = (int)socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseUnicastPort);
Assert.Equal(0, optionValue);
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(NoSocketsReuseUnicastPortSupport))]
public void ReuseUnicastPort_CreateSocketSetOption_NoSocketsReuseUnicastPortSupport_Throws()
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Assert.Throws<SocketException>(() =>
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseUnicastPort, 1));
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(SocketsReuseUnicastPortSupport))]
public void ReuseUnicastPort_CreateSocketSetOptionToZeroAndGetOption_SocketsReuseUnicastPortSupport_OptionIsZero()
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseUnicastPort, 0);
int optionValue = (int)socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseUnicastPort);
Assert.Equal(0, optionValue);
}
// TODO: Issue #4887
// The socket option 'ReuseUnicastPost' only works on Windows 10 systems. In addition, setting the option
// is a no-op unless specialized network settings using PowerShell configuration are first applied to the
// machine. This is currently difficult to test in the CI environment. So, this ests will be disabled for now
[OuterLoop] // TODO: Issue #11345
[ActiveIssue(4887)]
public void ReuseUnicastPort_CreateSocketSetOptionToOneAndGetOption_SocketsReuseUnicastPortSupport_OptionIsOne()
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseUnicastPort, 1);
int optionValue = (int)socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseUnicastPort);
Assert.Equal(1, optionValue);
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void MulticastOption_CreateSocketSetGetOption_GroupAndInterfaceIndex_SetSucceeds_GetThrows()
{
int interfaceIndex = 0;
IPAddress groupIp = IPAddress.Parse("239.1.2.3");
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(groupIp, interfaceIndex));
Assert.Throws<SocketException>(() => socket.GetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership));
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task MulticastInterface_Set_AnyInterface_Succeeds()
{
// On all platforms, index 0 means "any interface"
await MulticastInterface_Set_Helper(0);
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[PlatformSpecific(PlatformID.Windows)] // see comment below
public async Task MulticastInterface_Set_Loopback_Succeeds()
{
// On Windows, we can apparently assume interface 1 is "loopback." On other platforms, this is not a
// valid assumption. We could maybe use NetworkInterface.LoopbackInterfaceIndex to get the index, but
// this would introduce a dependency on System.Net.NetworkInformation, which depends on System.Net.Sockets,
// which is what we're testing here.... So for now, we'll just assume "loopback == 1" and run this on
// Windows only.
await MulticastInterface_Set_Helper(1);
}
private async Task MulticastInterface_Set_Helper(int interfaceIndex)
{
IPAddress multicastAddress = IPAddress.Parse("239.1.2.3");
string message = "hello";
int port;
using (Socket receiveSocket = CreateBoundUdpSocket(out port),
sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
receiveSocket.ReceiveTimeout = 1000;
receiveSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(multicastAddress, interfaceIndex));
// https://github.com/Microsoft/BashOnWindows/issues/990
if (!PlatformDetection.IsWindowsSubsystemForLinux)
{
sendSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, IPAddress.HostToNetworkOrder(interfaceIndex));
}
var receiveBuffer = new byte[1024];
var receiveTask = receiveSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), SocketFlags.None);
for (int i = 0; i < TestSettings.UDPRedundancy; i++)
{
sendSocket.SendTo(Encoding.UTF8.GetBytes(message), new IPEndPoint(multicastAddress, port));
}
int bytesReceived = await receiveTask;
string receivedMessage = Encoding.UTF8.GetString(receiveBuffer, 0, bytesReceived);
Assert.Equal(receivedMessage, message);
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void MulticastInterface_Set_InvalidIndex_Throws()
{
int interfaceIndex = 31415;
using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
Assert.Throws<SocketException>(() =>
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, IPAddress.HostToNetworkOrder(interfaceIndex)));
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // In WSL, the connect() call fails immediately.
[InlineData(false)]
[InlineData(true)]
public void FailedConnect_GetSocketOption_SocketOptionNameError(bool simpleGet)
{
using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { Blocking = false })
{
// Fail a Connect
using (var server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
server.Bind(new IPEndPoint(IPAddress.Loopback, 0)); // bind but don't listen
Assert.ThrowsAny<Exception>(() => client.Connect(server.LocalEndPoint));
}
// Verify via Select that there's an error
const int FailedTimeout = 10 * 1000 * 1000; // 10 seconds
var errorList = new List<Socket> { client };
Socket.Select(null, null, errorList, FailedTimeout);
Assert.Equal(1, errorList.Count);
// Get the last error and validate it's what's expected
int errorCode;
if (simpleGet)
{
errorCode = (int)client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error);
}
else
{
byte[] optionValue = new byte[sizeof(int)];
client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error, optionValue);
errorCode = BitConverter.ToInt32(optionValue, 0);
}
Assert.Equal((int)SocketError.ConnectionRefused, errorCode);
// Then get it again
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
// The Windows implementation doesn't clear the error code after retrieved.
// https://github.com/dotnet/corefx/issues/8464
Assert.Equal(errorCode, (int)client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error));
}
else
{
// The Unix implementation matches the getsockopt and MSDN docs and clears the error code as part of retrieval.
Assert.Equal((int)SocketError.Success, (int)client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error));
}
}
}
// Create an Udp Socket and binds it to an available port
private static Socket CreateBoundUdpSocket(out int localPort)
{
Socket receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
// sending a message will bind the socket to an available port
string sendMessage = "dummy message";
int port = 54320;
IPAddress multicastAddress = IPAddress.Parse("239.1.1.1");
receiveSocket.SendTo(Encoding.UTF8.GetBytes(sendMessage), new IPEndPoint(multicastAddress, port));
localPort = (receiveSocket.LocalEndPoint as IPEndPoint).Port;
return receiveSocket;
}
}
}
| |
using UnityEngine;
using System;
using Cinemachine.Utility;
using UnityEngine.Serialization;
namespace Cinemachine
{
/// <summary>
/// A Cinemachine Virtual Camera Body component that constrains camera motion
/// to a CinemachinePath. The camera can move along the path.
///
/// This behaviour can operate in two modes: manual positioning, and Auto-Dolly positioning.
/// In Manual mode, the camera's position is specified by animating the Path Position field.
/// In Auto-Dolly mode, the Path Position field is animated automatically every frame by finding
/// the position on the path that's closest to the virtual camera's Follow target.
/// </summary>
[DocumentationSorting(7, DocumentationSortingAttribute.Level.UserRef)]
[AddComponentMenu("")] // Don't display in add component menu
[RequireComponent(typeof(CinemachinePipeline))]
[SaveDuringPlay]
public class CinemachineTrackedDolly : CinemachineComponentBase
{
/// <summary>The path to which the camera will be constrained. This must be non-null.</summary>
[Tooltip("The path to which the camera will be constrained. This must be non-null.")]
public CinemachinePathBase m_Path;
/// <summary>The position along the path at which the camera will be placed.
/// This can be animated directly, or set automatically by the Auto-Dolly feature
/// to get as close as possible to the Follow target.</summary>
[Tooltip("The position along the path at which the camera will be placed. This can be animated directly, or set automatically by the Auto-Dolly feature to get as close as possible to the Follow target. The value is interpreted according to the Position Units setting.")]
public float m_PathPosition;
/// <summary>How to interpret the Path Position</summary>
[Tooltip("How to interpret Path Position. If set to Path Units, values are as follows: 0 represents the first waypoint on the path, 1 is the second, and so on. Values in-between are points on the path in between the waypoints. If set to Distance, then Path Position represents distance along the path.")]
public CinemachinePathBase.PositionUnits m_PositionUnits = CinemachinePathBase.PositionUnits.PathUnits;
/// <summary>Where to put the camera realtive to the path postion. X is perpendicular to the path, Y is up, and Z is parallel to the path.</summary>
[Tooltip("Where to put the camera relative to the path position. X is perpendicular to the path, Y is up, and Z is parallel to the path. This allows the camera to be offset from the path itself (as if on a tripod, for example).")]
public Vector3 m_PathOffset = Vector3.zero;
/// <summary>How aggressively the camera tries to maintain the offset perpendicular to the path.
/// Small numbers are more responsive, rapidly translating the camera to keep the target's
/// x-axis offset. Larger numbers give a more heavy slowly responding camera.
/// Using different settings per axis can yield a wide range of camera behaviors</summary>
[Range(0f, 20f)]
[Tooltip("How aggressively the camera tries to maintain its position in a direction perpendicular to the path. Small numbers are more responsive, rapidly translating the camera to keep the target's x-axis offset. Larger numbers give a more heavy slowly responding camera. Using different settings per axis can yield a wide range of camera behaviors.")]
public float m_XDamping = 0f;
/// <summary>How aggressively the camera tries to maintain the offset in the path-local up direction.
/// Small numbers are more responsive, rapidly translating the camera to keep the target's
/// y-axis offset. Larger numbers give a more heavy slowly responding camera.
/// Using different settings per axis can yield a wide range of camera behaviors</summary>
[Range(0f, 20f)]
[Tooltip("How aggressively the camera tries to maintain its position in the path-local up direction. Small numbers are more responsive, rapidly translating the camera to keep the target's y-axis offset. Larger numbers give a more heavy slowly responding camera. Using different settings per axis can yield a wide range of camera behaviors.")]
public float m_YDamping = 0f;
/// <summary>How aggressively the camera tries to maintain the offset parallel to the path.
/// Small numbers are more responsive, rapidly translating the camera to keep the
/// target's z-axis offset. Larger numbers give a more heavy slowly responding camera.
/// Using different settings per axis can yield a wide range of camera behaviors</summary>
[Range(0f, 20f)]
[Tooltip("How aggressively the camera tries to maintain its position in a direction parallel to the path. Small numbers are more responsive, rapidly translating the camera to keep the target's z-axis offset. Larger numbers give a more heavy slowly responding camera. Using different settings per axis can yield a wide range of camera behaviors.")]
public float m_ZDamping = 1f;
/// <summary>Different ways to set the camera's up vector</summary>
[DocumentationSorting(7.1f, DocumentationSortingAttribute.Level.UserRef)]
public enum CameraUpMode
{
/// <summary>Leave the camera's up vector alone. It will be set according to the Brain's WorldUp.</summary>
Default,
/// <summary>Take the up vector from the path's up vector at the current point</summary>
Path,
/// <summary>Take the up vector from the path's up vector at the current point, but with the roll zeroed out</summary>
PathNoRoll,
/// <summary>Take the up vector from the Follow target's up vector</summary>
FollowTarget,
/// <summary>Take the up vector from the Follow target's up vector, but with the roll zeroed out</summary>
FollowTargetNoRoll,
};
/// <summary>How to set the virtual camera's Up vector. This will affect the screen composition.</summary>
[Tooltip("How to set the virtual camera's Up vector. This will affect the screen composition, because the camera Aim behaviours will always try to respect the Up direction.")]
public CameraUpMode m_CameraUp = CameraUpMode.Default;
[Range(0f, 20f)]
[Tooltip("How aggressively the camera tries to track the target rotation's X angle. Small numbers are more responsive. Larger numbers give a more heavy slowly responding camera.")]
public float m_PitchDamping = 0;
[Range(0f, 20f)]
[Tooltip("How aggressively the camera tries to track the target rotation's Y angle. Small numbers are more responsive. Larger numbers give a more heavy slowly responding camera.")]
public float m_YawDamping = 0;
[Range(0f, 20f)]
[Tooltip("How aggressively the camera tries to track the target rotation's Z angle. Small numbers are more responsive. Larger numbers give a more heavy slowly responding camera.")]
public float m_RollDamping = 0f;
/// <summary>Controls how automatic dollying occurs</summary>
[DocumentationSorting(7.2f, DocumentationSortingAttribute.Level.UserRef)]
[Serializable]
public struct AutoDolly
{
/// <summary>If checked, will enable automatic dolly, which chooses a path position
/// that is as close as possible to the Follow target.</summary>
[Tooltip("If checked, will enable automatic dolly, which chooses a path position that is as close as possible to the Follow target. Note: this can have significant performance impact")]
public bool m_Enabled;
/// <summary>Offset, in current position units, from the closest point on the path to the follow target.</summary>
[Tooltip("Offset, in current position units, from the closest point on the path to the follow target")]
public float m_PositionOffset;
/// <summary>Search up to how many waypoints on either side of the current position. Use 0 for Entire path</summary>
[Tooltip("Search up to how many waypoints on either side of the current position. Use 0 for Entire path.")]
public int m_SearchRadius;
/// <summary>We search between waypoints by dividing the segment into this many straight pieces.
/// The higher the number, the more accurate the result, but performance is
/// proportionally slower for higher numbers</summary>
[FormerlySerializedAs("m_StepsPerSegment")]
[Tooltip("We search between waypoints by dividing the segment into this many straight pieces. The higher the number, the more accurate the result, but performance is proportionally slower for higher numbers")]
public int m_SearchResolution;
/// <summary>Constructor with specific field values</summary>
public AutoDolly(bool enabled, float positionOffset, int searchRadius, int stepsPerSegment)
{
m_Enabled = enabled;
m_PositionOffset = positionOffset;
m_SearchRadius = searchRadius;
m_SearchResolution = stepsPerSegment;
}
};
/// <summary>Controls how automatic dollying occurs</summary>
[Tooltip("Controls how automatic dollying occurs. A Follow target is necessary to use this feature.")]
public AutoDolly m_AutoDolly = new AutoDolly(false, 0, 2, 5);
/// <summary>True if component is enabled and has a path</summary>
public override bool IsValid { get { return enabled && m_Path != null; } }
/// <summary>Get the Cinemachine Pipeline stage that this component implements.
/// Always returns the Body stage</summary>
public override CinemachineCore.Stage Stage { get { return CinemachineCore.Stage.Body; } }
/// <summary>Positions the virtual camera according to the transposer rules.</summary>
/// <param name="curState">The current camera state</param>
/// <param name="deltaTime">Used for damping. If less that 0, no damping is done.</param>
public override void MutateCameraState(ref CameraState curState, float deltaTime)
{
// Init previous frame state info
if (deltaTime < 0)
{
m_PreviousPathPosition = m_PathPosition;
m_PreviousCameraPosition = curState.RawPosition;
}
if (!IsValid)
return;
//UnityEngine.Profiling.Profiler.BeginSample("CinemachineTrackedDolly.MutateCameraState");
// Get the new ideal path base position
if (m_AutoDolly.m_Enabled && FollowTarget != null)
{
float prevPos = m_PreviousPathPosition;
if (m_PositionUnits == CinemachinePathBase.PositionUnits.Distance)
prevPos = m_Path.GetPathPositionFromDistance(prevPos);
// This works in path units
m_PathPosition = m_Path.FindClosestPoint(
FollowTarget.transform.position,
Mathf.FloorToInt(prevPos),
(deltaTime < 0 || m_AutoDolly.m_SearchRadius <= 0)
? -1 : m_AutoDolly.m_SearchRadius,
m_AutoDolly.m_SearchResolution);
if (m_PositionUnits == CinemachinePathBase.PositionUnits.Distance)
m_PathPosition = m_Path.GetPathDistanceFromPosition(m_PathPosition);
// Apply the path position offset
m_PathPosition += m_AutoDolly.m_PositionOffset;
}
float newPathPosition = m_PathPosition;
if (deltaTime >= 0)
{
// Normalize previous position to find the shortest path
float maxUnit = m_Path.MaxUnit(m_PositionUnits);
if (maxUnit > 0)
{
float prev = m_Path.NormalizeUnit(m_PreviousPathPosition, m_PositionUnits);
float next = m_Path.NormalizeUnit(newPathPosition, m_PositionUnits);
if (m_Path.Looped && Mathf.Abs(next - prev) > maxUnit / 2)
{
if (next > prev)
prev += maxUnit;
else
prev -= maxUnit;
}
m_PreviousPathPosition = prev;
newPathPosition = next;
}
// Apply damping along the path direction
float offset = m_PreviousPathPosition - newPathPosition;
offset = Damper.Damp(offset, m_ZDamping, deltaTime);
newPathPosition = m_PreviousPathPosition - offset;
}
m_PreviousPathPosition = newPathPosition;
Quaternion newPathOrientation = m_Path.EvaluateOrientationAtUnit(newPathPosition, m_PositionUnits);
// Apply the offset to get the new camera position
Vector3 newCameraPos = m_Path.EvaluatePositionAtUnit(newPathPosition, m_PositionUnits);
Vector3 offsetX = newPathOrientation * Vector3.right;
Vector3 offsetY = newPathOrientation * Vector3.up;
Vector3 offsetZ = newPathOrientation * Vector3.forward;
newCameraPos += m_PathOffset.x * offsetX;
newCameraPos += m_PathOffset.y * offsetY;
newCameraPos += m_PathOffset.z * offsetZ;
// Apply damping to the remaining directions
if (deltaTime >= 0)
{
Vector3 currentCameraPos = m_PreviousCameraPosition;
Vector3 delta = (currentCameraPos - newCameraPos);
Vector3 delta1 = Vector3.Dot(delta, offsetY) * offsetY;
Vector3 delta0 = delta - delta1;
delta0 = Damper.Damp(delta0, m_XDamping, deltaTime);
delta1 = Damper.Damp(delta1, m_YDamping, deltaTime);
newCameraPos = currentCameraPos - (delta0 + delta1);
}
curState.RawPosition = m_PreviousCameraPosition = newCameraPos;
// Set the orientation and up
Quaternion newOrientation
= GetTargetOrientationAtPathPoint(newPathOrientation, curState.ReferenceUp);
if (deltaTime < 0)
m_PreviousOrientation = newOrientation;
else
{
if (deltaTime >= 0)
{
Vector3 relative = (Quaternion.Inverse(m_PreviousOrientation)
* newOrientation).eulerAngles;
for (int i = 0; i < 3; ++i)
if (relative[i] > 180)
relative[i] -= 360;
relative = Damper.Damp(relative, AngularDamping, deltaTime);
newOrientation = m_PreviousOrientation * Quaternion.Euler(relative);
}
m_PreviousOrientation = newOrientation;
}
curState.RawOrientation = newOrientation;
curState.ReferenceUp = curState.RawOrientation * Vector3.up;
//UnityEngine.Profiling.Profiler.EndSample();
}
private Quaternion GetTargetOrientationAtPathPoint(Quaternion pathOrientation, Vector3 up)
{
switch (m_CameraUp)
{
default:
case CameraUpMode.Default: break;
case CameraUpMode.Path: return pathOrientation;
case CameraUpMode.PathNoRoll:
return Quaternion.LookRotation(pathOrientation * Vector3.forward, up);
case CameraUpMode.FollowTarget:
if (FollowTarget != null)
return FollowTarget.rotation;
break;
case CameraUpMode.FollowTargetNoRoll:
if (FollowTarget != null)
return Quaternion.LookRotation(FollowTarget.rotation * Vector3.forward, up);
break;
}
return Quaternion.LookRotation(transform.rotation * Vector3.forward, up);
}
private Vector3 AngularDamping
{
get
{
switch (m_CameraUp)
{
case CameraUpMode.PathNoRoll:
case CameraUpMode.FollowTargetNoRoll:
return new Vector3(m_PitchDamping, m_YawDamping, 0);
case CameraUpMode.Default:
return Vector3.zero;
default:
return new Vector3(m_PitchDamping, m_YawDamping, m_RollDamping);
}
}
}
private float m_PreviousPathPosition = 0;
Quaternion m_PreviousOrientation = Quaternion.identity;
private Vector3 m_PreviousCameraPosition = Vector3.zero;
}
}
| |
// Rectangle.java version 1.0b2p1
// Java Spatial Index Library
// Copyright (C) 2002 Infomatiq Limited
// Copyright (C) 2008 Aled Morris [email protected]
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// Ported to C# By Dror Gluska, April 9th, 2009
using System;
using System.Text;
namespace MagicalLifeAPI.DataTypes.R
{
public struct Dimension : IEquatable<Dimension>
{
public float Max { get; set; }
public float Min { get; set; }
public override bool Equals(object obj)
{
return obj is Dimension dimension && this == dimension;
}
public bool Equals(Dimension other)
{
return this == other;
}
public override int GetHashCode()
{
return 0;
}
public static bool operator ==(Dimension left, Dimension right)
{
return (Math.Abs(left.Max - right.Max) < 0.00001) && (Math.Abs(left.Min - right.Min) < 0.00001);
}
public static bool operator !=(Dimension left, Dimension right)
{
return !(left == right);
}
}
/// <summary>
/// Currently hardcoded to 3 dimensions, but could be extended.
/// </summary>
public class Rectangle : IEquatable<Rectangle>
{
/// <summary>
/// Number of dimensions in a rectangle. In theory this
/// could be extended to three or more dimensions.
/// </summary>
internal const int DIMENSIONS = 3;
/// <summary>
/// array containing the minimum value for each dimension; ie { min(x), min(y) }
/// </summary>
internal float[] max;
/// <summary>
/// array containing the maximum value for each dimension; ie { max(x), max(y) }
/// </summary>
internal float[] min;
/// <summary>
/// ctor
/// </summary>
/// <param name="x1">coordinate of any corner of the rectangle</param>
/// <param name="y1">coordinate of any corner of the rectangle</param>
/// <param name="x2">coordinate of the opposite corner</param>
/// <param name="y2">coordinate of the opposite corner</param>
/// <param name="z1">coordinate of any corner of the rectangle</param>
/// <param name="z2">coordinate of the opposite corner</param>
public Rectangle(float x1, float y1, float x2, float y2)
{
min = new float[DIMENSIONS];
max = new float[DIMENSIONS];
Set(x1, y1, x2, y2);
}
public Rectangle(Point2D a, Point2D b)
: this(a.X, a.Y, b.X, b.Y)
{
}
/// <summary>
/// ctor
/// </summary>
/// <param name="min">min array containing the minimum value for each dimension; ie { min(x), min(y) }</param>
/// <param name="max">max array containing the maximum value for each dimension; ie { max(x), max(y) }</param>
public Rectangle(float[] min, float[] max)
{
if (min.Length != DIMENSIONS || max.Length != DIMENSIONS)
{
throw new ArgumentException("Error in Rectangle constructor: " +
"min and max arrays must be of length " + DIMENSIONS + ".");
}
this.min = new float[DIMENSIONS];
this.max = new float[DIMENSIONS];
Set(min, max);
}
/// <summary>
/// Sets the size of the rectangle.
/// </summary>
/// <param name="x1">coordinate of any corner of the rectangle</param>
/// <param name="y1">coordinate of any corner of the rectangle</param>
/// <param name="x2">coordinate of the opposite corner</param>
/// <param name="y2">coordinate of the opposite corner</param>
/// <param name="z1">coordinate of any corner of the rectangle</param>
/// <param name="z2">coordinate of the opposite corner</param>
internal void Set(float x1, float y1, float x2, float y2)
{
min[0] = Math.Min(x1, x2);
min[1] = Math.Min(y1, y2);
max[0] = Math.Max(x1, x2);
max[1] = Math.Max(y1, y2);
}
/// <summary>
/// Retrieves dimensions from rectangle
/// <para>probable dimensions:</para>
/// <para>X = 0, Y = 1, Z = 2</para>
/// </summary>
public Dimension? Get(int dimension)
{
if ((min.Length >= dimension) && (max.Length >= dimension))
{
Dimension retval = new Dimension
{
Min = min[dimension],
Max = max[dimension]
};
return retval;
}
return null;
}
/// <summary>
/// Sets the size of the rectangle.
/// </summary>
/// <param name="min">min array containing the minimum value for each dimension; ie { min(x), min(y) }</param>
/// <param name="max">max array containing the maximum value for each dimension; ie { max(x), max(y) }</param>
internal void Set(float[] min, float[] max)
{
Array.Copy(min, 0, this.min, 0, DIMENSIONS);
Array.Copy(max, 0, this.max, 0, DIMENSIONS);
}
/// <summary>
/// Make a copy of this rectangle
/// </summary>
/// <returns>copy of this rectangle</returns>
internal Rectangle Copy()
{
return new Rectangle(min, max);
}
/// <summary>
/// Determine whether an edge of this rectangle overlies the equivalent
/// edge of the passed rectangle
/// </summary>
internal bool EdgeOverlaps(Rectangle r)
{
for (int i = 0; i < DIMENSIONS; i++)
{
if (min[i] == r.min[i] || max[i] == r.max[i])
{
return true;
}
}
return false;
}
/// <summary>
/// Determine whether this rectangle intersects the passed rectangle
/// </summary>
/// <param name="r">The rectangle that might intersect this rectangle</param>
/// <returns>true if the rectangles intersect, false if they do not intersect</returns>
internal bool Intersects(Rectangle r)
{
// Every dimension must intersect. If any dimension
// does not intersect, return false immediately.
for (int i = 0; i < DIMENSIONS; i++)
{
if (max[i] < r.min[i] || min[i] > r.max[i])
{
return false;
}
}
return true;
}
/// <summary>
/// Determine whether this rectangle contains the passed rectangle
/// </summary>
/// <param name="r">The rectangle that might be contained by this rectangle</param>
/// <returns>true if this rectangle contains the passed rectangle, false if it does not</returns>
internal bool Contains(Rectangle r)
{
for (int i = 0; i < DIMENSIONS; i++)
{
if (max[i] < r.max[i] || min[i] > r.min[i])
{
return false;
}
}
return true;
}
/// <summary>
/// Determine whether this rectangle is contained by the passed rectangle
/// </summary>
/// <param name="r">The rectangle that might contain this rectangle</param>
/// <returns>true if the passed rectangle contains this rectangle, false if it does not</returns>
internal bool ContainedBy(Rectangle r)
{
for (int i = 0; i < DIMENSIONS; i++)
{
if (max[i] > r.max[i] || min[i] < r.min[i])
{
return false;
}
}
return true;
}
/// <summary>
/// Return the distance between this rectangle and the passed point.
/// If the rectangle contains the point, the distance is zero.
/// </summary>
/// <param name="p">Point to find the distance to</param>
/// <returns>distance beween this rectangle and the passed point.</returns>
internal float Distance(Point p)
{
float distanceSquared = 0;
for (int i = 0; i < DIMENSIONS; i++)
{
float greatestMin = Math.Max(min[i], p.coordinates[i]);
float leastMax = Math.Min(max[i], p.coordinates[i]);
if (greatestMin > leastMax)
{
distanceSquared += ((greatestMin - leastMax) * (greatestMin - leastMax));
}
}
return (float)Math.Sqrt(distanceSquared);
}
/// <summary>
/// Return the distance between this rectangle and the passed rectangle.
/// If the rectangles overlap, the distance is zero.
/// </summary>
/// <param name="r">Rectangle to find the distance to</param>
/// <returns>distance between this rectangle and the passed rectangle</returns>
internal float Distance(Rectangle r)
{
float distanceSquared = 0;
for (int i = 0; i < DIMENSIONS; i++)
{
float greatestMin = Math.Max(min[i], r.min[i]);
float leastMax = Math.Min(max[i], r.max[i]);
if (greatestMin > leastMax)
{
distanceSquared += ((greatestMin - leastMax) * (greatestMin - leastMax));
}
}
return (float)Math.Sqrt(distanceSquared);
}
/// <summary>
/// Return the squared distance from this rectangle to the passed point
/// </summary>
/// <param name="dimension"></param>
/// <param name="point"></param>
internal float DistanceSquared(int dimension, float point)
{
float distanceSquared = 0;
float tempDistance = point - max[dimension];
for (int i = 0; i < 2; i++)
{
if (tempDistance > 0)
{
distanceSquared = (tempDistance * tempDistance);
break;
}
tempDistance = min[dimension] - point;
}
return distanceSquared;
}
/// <summary>
/// Return the furthest possible distance between this rectangle and
/// the passed rectangle.
/// </summary>
/// <param name="r"></param>
internal float FurthestDistance(Rectangle r)
{
//Find the distance between this rectangle and each corner of the
//passed rectangle, and use the maximum.
float distanceSquared = 0;
for (int i = 0; i < DIMENSIONS; i++)
{
distanceSquared += Math.Max(r.min[i], r.max[i]);
#warning possible didn't convert properly
//distanceSquared += Math.Max(distanceSquared(i, r.min[i]), distanceSquared(i, r.max[i]));
}
return (float)Math.Sqrt(distanceSquared);
}
/// <summary>
/// Calculate the area by which this rectangle would be enlarged if
/// added to the passed rectangle. Neither rectangle is altered.
/// </summary>
/// <param name="r">
/// Rectangle to union with this rectangle, in order to
/// compute the difference in area of the union and the
/// original rectangle
/// </param>
internal float Enlargement(Rectangle r)
{
float enlargedArea = (Math.Max(max[0], r.max[0]) - Math.Min(min[0], r.min[0])) *
(Math.Max(max[1], r.max[1]) - Math.Min(min[1], r.min[1]));
return enlargedArea - Area();
}
/// <summary>
/// Compute the area of this rectangle.
/// </summary>
/// <returns> The area of this rectangle</returns>
internal float Area()
{
return (max[0] - min[0]) * (max[1] - min[1]);
}
/// <summary>
/// Computes the union of this rectangle and the passed rectangle, storing
/// the result in this rectangle.
/// </summary>
/// <param name="r">Rectangle to add to this rectangle</param>
internal void Add(Rectangle r)
{
for (int i = 0; i < DIMENSIONS; i++)
{
if (r.min[i] < min[i])
{
min[i] = r.min[i];
}
if (r.max[i] > max[i])
{
max[i] = r.max[i];
}
}
}
/// <summary>
/// Find the union of this rectangle and the passed rectangle.
/// Neither rectangle is altered
/// </summary>
/// <param name="r">The rectangle to union with this rectangle</param>
internal Rectangle Union(Rectangle r)
{
Rectangle union = this.Copy();
union.Add(r);
return union;
}
internal bool CompareArrays(float[] a1, float[] a2)
{
if ((a1 == null) || (a2 == null))
{
return false;
}
if (a1.Length != a2.Length)
{
return false;
}
for (int i = 0; i < a1.Length; i++)
{
if (Math.Abs(a1[i] - a2[i]) > 0.000000001f)
{
return false;
}
}
return true;
}
/// <summary>
/// Determine whether this rectangle is equal to a given object.
/// Equality is determined by the bounds of the rectangle.
/// </summary>
/// <param name="obj">The object to compare with this rectangle</param>
/// <returns></returns>
public override bool Equals(object obj)
{
bool equals = false;
if (obj is Rectangle r && CompareArrays(r.min, min)
&& CompareArrays(r.max, max))
{
equals = true;
}
return equals;
}
public override int GetHashCode()
{
return this.ToString().GetHashCode();
}
/// <summary>
/// Determine whether this rectangle is the same as another object
/// <para>
/// Note that two rectangles can be equal but not the same object,
/// if they both have the same bounds.
/// </para>
/// </summary>
/// <param name="o">
/// Note that two rectangles can be equal but not the same object,
/// if they both have the same bounds.
/// </param>
/// <returns></returns>
internal bool SameObject(object o)
{
return base.Equals(o);
}
/// <summary>
/// Return a string representation of this rectangle, in the form
/// (1.2,3.4,5.6), (7.8, 9.10,11.12)
/// </summary>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
// min coordinates
sb.Append('(');
for (int i = 0; i < DIMENSIONS; i++)
{
if (i > 0)
{
sb.Append(", ");
}
sb.Append(min[i]);
}
sb.Append("), (");
// max coordinates
for (int i = 0; i < DIMENSIONS; i++)
{
if (i > 0)
{
sb.Append(", ");
}
sb.Append(max[i]);
}
sb.Append(')');
return sb.ToString();
}
public bool Equals(Rectangle other)
{
return CompareArrays(other.min, min)
&& CompareArrays(other.max, max);
}
}
}
| |
using System;
using System.Text;
namespace LiteNetLib.Utils
{
public class NetDataReader
{
protected byte[] _data;
protected int _position;
protected int _dataSize;
public byte[] Data
{
get { return _data; }
}
public int Position
{
get { return _position; }
}
public bool EndOfData
{
get { return _position == _dataSize; }
}
public int AvailableBytes
{
get { return _dataSize - _position; }
}
public void SetSource(byte[] source)
{
_data = source;
_position = 0;
_dataSize = source.Length;
}
public void SetSource(byte[] source, int offset)
{
_data = source;
_position = offset;
_dataSize = source.Length;
}
public void SetSource(byte[] source, int offset, int dataSize)
{
_data = source;
_position = offset;
_dataSize = dataSize;
}
public NetDataReader()
{
}
public NetDataReader(byte[] source)
{
SetSource(source);
}
public NetDataReader(byte[] source, int offset)
{
SetSource(source, offset);
}
public NetDataReader(byte[] source, int offset, int maxSize)
{
SetSource(source, offset, maxSize);
}
public NetEndPoint GetNetEndPoint()
{
string host = GetString(1000);
int port = GetInt();
return new NetEndPoint(host, port);
}
public byte GetByte()
{
byte res = _data[_position];
_position += 1;
return res;
}
public sbyte GetSByte()
{
var b = (sbyte)_data[_position];
_position++;
return b;
}
public bool[] GetBoolArray()
{
ushort size = BitConverter.ToUInt16(_data, _position);
_position += 2;
var arr = new bool[size];
for (int i = 0; i < size; i++)
{
arr[i] = GetBool();
}
return arr;
}
public ushort[] GetUShortArray()
{
ushort size = BitConverter.ToUInt16(_data, _position);
_position += 2;
var arr = new ushort[size];
for (int i = 0; i < size; i++)
{
arr[i] = GetUShort();
}
return arr;
}
public short[] GetShortArray()
{
ushort size = BitConverter.ToUInt16(_data, _position);
_position += 2;
var arr = new short[size];
for (int i = 0; i < size; i++)
{
arr[i] = GetShort();
}
return arr;
}
public long[] GetLongArray()
{
ushort size = BitConverter.ToUInt16(_data, _position);
_position += 2;
var arr = new long[size];
for (int i = 0; i < size; i++)
{
arr[i] = GetLong();
}
return arr;
}
public ulong[] GetULongArray()
{
ushort size = BitConverter.ToUInt16(_data, _position);
_position += 2;
var arr = new ulong[size];
for (int i = 0; i < size; i++)
{
arr[i] = GetULong();
}
return arr;
}
public int[] GetIntArray()
{
ushort size = BitConverter.ToUInt16(_data, _position);
_position += 2;
var arr = new int[size];
for (int i = 0; i < size; i++)
{
arr[i] = GetInt();
}
return arr;
}
public uint[] GetUIntArray()
{
ushort size = BitConverter.ToUInt16(_data, _position);
_position += 2;
var arr = new uint[size];
for (int i = 0; i < size; i++)
{
arr[i] = GetUInt();
}
return arr;
}
public float[] GetFloatArray()
{
ushort size = BitConverter.ToUInt16(_data, _position);
_position += 2;
var arr = new float[size];
for (int i = 0; i < size; i++)
{
arr[i] = GetFloat();
}
return arr;
}
public double[] GetDoubleArray()
{
ushort size = BitConverter.ToUInt16(_data, _position);
_position += 2;
var arr = new double[size];
for (int i = 0; i < size; i++)
{
arr[i] = GetDouble();
}
return arr;
}
public string[] GetStringArray(int maxLength)
{
ushort size = BitConverter.ToUInt16(_data, _position);
_position += 2;
var arr = new string[size];
for (int i = 0; i < size; i++)
{
arr[i] = GetString(maxLength);
}
return arr;
}
public bool GetBool()
{
bool res = _data[_position] > 0;
_position += 1;
return res;
}
public ushort GetUShort()
{
ushort result = BitConverter.ToUInt16(_data, _position);
_position += 2;
return result;
}
public short GetShort()
{
short result = BitConverter.ToInt16(_data, _position);
_position += 2;
return result;
}
public long GetLong()
{
long result = BitConverter.ToInt64(_data, _position);
_position += 8;
return result;
}
public ulong GetULong()
{
ulong result = BitConverter.ToUInt64(_data, _position);
_position += 8;
return result;
}
public int GetInt()
{
int result = BitConverter.ToInt32(_data, _position);
_position += 4;
return result;
}
public uint GetUInt()
{
uint result = BitConverter.ToUInt32(_data, _position);
_position += 4;
return result;
}
public float GetFloat()
{
float result = BitConverter.ToSingle(_data, _position);
_position += 4;
return result;
}
public double GetDouble()
{
double result = BitConverter.ToDouble(_data, _position);
_position += 8;
return result;
}
public string GetString(int maxLength)
{
int bytesCount = GetInt();
if (bytesCount <= 0 || bytesCount > maxLength*2)
{
return string.Empty;
}
int charCount = Encoding.UTF8.GetCharCount(_data, _position, bytesCount);
if (charCount > maxLength)
{
return string.Empty;
}
string result = Encoding.UTF8.GetString(_data, _position, bytesCount);
_position += bytesCount;
return result;
}
public byte[] GetBytes()
{
byte[] outgoingData = new byte[AvailableBytes];
Buffer.BlockCopy(_data, _position, outgoingData, 0, AvailableBytes);
_position = _data.Length;
return outgoingData;
}
public void GetBytes(byte[] destination)
{
Buffer.BlockCopy(_data, _position, destination, 0, AvailableBytes);
_position = _data.Length;
}
public void GetBytes(byte[] destination, int lenght)
{
Buffer.BlockCopy(_data, _position, destination, 0, lenght);
_position += lenght;
}
public void Clear()
{
_position = 0;
_dataSize = 0;
_data = null;
}
}
}
| |
using System;
using System.Collections;
#if !SILVERLIGHT
using System.Collections.Concurrent;
#else
using TvdP.Collections;
#endif
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
namespace AutoMapper
{
internal delegate object LateBoundMethod(object target, object[] arguments);
internal delegate object LateBoundPropertyGet(object target);
internal delegate object LateBoundFieldGet(object target);
internal delegate void LateBoundFieldSet(object target, object value);
internal delegate void LateBoundPropertySet(object target, object value);
internal delegate void LateBoundValueTypeFieldSet(ref object target, object value);
internal delegate void LateBoundValueTypePropertySet(ref object target, object value);
internal delegate object LateBoundCtor();
internal delegate object LateBoundParamsCtor(params object[] parameters);
internal static class DelegateFactory
{
private static readonly ConcurrentDictionary<Type, LateBoundCtor> _ctorCache = new ConcurrentDictionary<Type, LateBoundCtor>();
public static LateBoundMethod CreateGet(MethodInfo method)
{
ParameterExpression instanceParameter = Expression.Parameter(typeof(object), "target");
ParameterExpression argumentsParameter = Expression.Parameter(typeof(object[]), "arguments");
MethodCallExpression call = Expression.Call(
Expression.Convert(instanceParameter, method.DeclaringType),
method,
CreateParameterExpressions(method, argumentsParameter));
Expression<LateBoundMethod> lambda = Expression.Lambda<LateBoundMethod>(
Expression.Convert(call, typeof(object)),
instanceParameter,
argumentsParameter);
return lambda.Compile();
}
public static LateBoundPropertyGet CreateGet(PropertyInfo property)
{
ParameterExpression instanceParameter = Expression.Parameter(typeof(object), "target");
MemberExpression member = Expression.Property(Expression.Convert(instanceParameter, property.DeclaringType), property);
Expression<LateBoundPropertyGet> lambda = Expression.Lambda<LateBoundPropertyGet>(
Expression.Convert(member, typeof(object)),
instanceParameter
);
return lambda.Compile();
}
public static LateBoundFieldGet CreateGet(FieldInfo field)
{
ParameterExpression instanceParameter = Expression.Parameter(typeof(object), "target");
MemberExpression member = Expression.Field(Expression.Convert(instanceParameter, field.DeclaringType), field);
Expression<LateBoundFieldGet> lambda = Expression.Lambda<LateBoundFieldGet>(
Expression.Convert(member, typeof(object)),
instanceParameter
);
return lambda.Compile();
}
public static LateBoundFieldSet CreateSet(FieldInfo field)
{
var sourceType = field.DeclaringType;
var method = CreateDynamicMethod(field, sourceType);
var gen = method.GetILGenerator();
gen.Emit(OpCodes.Ldarg_0); // Load input to stack
gen.Emit(OpCodes.Castclass, sourceType); // Cast to source type
gen.Emit(OpCodes.Ldarg_1); // Load value to stack
gen.Emit(OpCodes.Unbox_Any, field.FieldType); // Unbox the value to its proper value type
gen.Emit(OpCodes.Stfld, field); // Set the value to the input field
gen.Emit(OpCodes.Ret);
var callback = (LateBoundFieldSet)method.CreateDelegate(typeof(LateBoundFieldSet));
return callback;
}
public static LateBoundPropertySet CreateSet(PropertyInfo property)
{
var sourceType = property.DeclaringType;
var setter = property.GetSetMethod(true);
var method = CreateDynamicMethod(property, sourceType);
var gen = method.GetILGenerator();
gen.Emit(OpCodes.Ldarg_0); // Load input to stack
gen.Emit(OpCodes.Castclass, sourceType); // Cast to source type
gen.Emit(OpCodes.Ldarg_1); // Load value to stack
gen.Emit(OpCodes.Unbox_Any, property.PropertyType); // Unbox the value to its proper value type
gen.Emit(OpCodes.Callvirt, setter); // Call the setter method
gen.Emit(OpCodes.Ret);
var result = (LateBoundPropertySet)method.CreateDelegate(typeof(LateBoundPropertySet));
return result;
}
public static LateBoundValueTypePropertySet CreateValueTypeSet(PropertyInfo property)
{
var sourceType = property.DeclaringType;
var setter = property.GetSetMethod(true);
var method = CreateValueTypeDynamicMethod(property, sourceType);
var gen = method.GetILGenerator();
method.InitLocals = true;
gen.Emit(OpCodes.Ldarg_0); // Load input to stack
gen.Emit(OpCodes.Ldind_Ref);
gen.Emit(OpCodes.Unbox_Any, sourceType); // Unbox the source to its correct type
gen.Emit(OpCodes.Stloc_0); // Store the unboxed input on the stack
gen.Emit(OpCodes.Ldloca_S, 0);
gen.Emit(OpCodes.Ldarg_1); // Load value to stack
gen.Emit(OpCodes.Castclass, property.PropertyType); // Unbox the value to its proper value type
gen.Emit(OpCodes.Call, setter); // Call the setter method
gen.Emit(OpCodes.Ret);
var result = (LateBoundValueTypePropertySet)method.CreateDelegate(typeof(LateBoundValueTypePropertySet));
return result;
}
public static LateBoundCtor CreateCtor(Type type)
{
LateBoundCtor ctor = _ctorCache.GetOrAdd(type, t =>
{
var ctorExpression = Expression.Lambda<LateBoundCtor>(Expression.Convert(Expression.New(type), typeof(object)));
return ctorExpression.Compile();
});
return ctor;
}
private static DynamicMethod CreateValueTypeDynamicMethod(MemberInfo member, Type sourceType)
{
#if !SILVERLIGHT
if (sourceType.IsInterface)
return new DynamicMethod("Set" + member.Name, null, new[] { typeof(object).MakeByRefType(), typeof(object) }, sourceType.Assembly.ManifestModule, true);
return new DynamicMethod("Set" + member.Name, null, new[] { typeof(object).MakeByRefType(), typeof(object) }, sourceType, true);
#else
if (sourceType.IsInterface)
return new DynamicMethod("Set" + member.Name, null, new[] { typeof(object).MakeByRefType(), typeof(object) });
return new DynamicMethod("Set" + member.Name, null, new[] { typeof(object).MakeByRefType(), typeof(object) });
#endif
}
private static DynamicMethod CreateDynamicMethod(MemberInfo member, Type sourceType)
{
#if !SILVERLIGHT
if (sourceType.IsInterface)
return new DynamicMethod("Set" + member.Name, null, new[] { typeof(object), typeof(object) }, sourceType.Assembly.ManifestModule, true);
return new DynamicMethod("Set" + member.Name, null, new[] { typeof(object), typeof(object) }, sourceType, true);
#else
if (sourceType.IsInterface)
return new DynamicMethod("Set" + member.Name, null, new[] { typeof(object), typeof(object) });
return new DynamicMethod("Set" + member.Name, null, new[] { typeof(object), typeof(object) });
#endif
}
private static Expression[] CreateParameterExpressions(MethodInfo method, Expression argumentsParameter)
{
return method.GetParameters().Select((parameter, index) =>
Expression.Convert(
Expression.ArrayIndex(argumentsParameter, Expression.Constant(index)),
parameter.ParameterType)).ToArray();
}
public static LateBoundParamsCtor CreateCtor(ConstructorInfo constructorInfo, IEnumerable<ConstructorParameterMap> ctorParams)
{
ParameterExpression paramsExpr = Expression.Parameter(typeof(object[]), "parameters");
var convertExprs = ctorParams
.Select((ctorParam, i) => Expression.Convert(
Expression.ArrayIndex(paramsExpr, Expression.Constant(i)),
ctorParam.Parameter.ParameterType))
.ToArray();
NewExpression newExpression = Expression.New(constructorInfo, convertExprs);
var lambda = Expression.Lambda<LateBoundParamsCtor>(newExpression, paramsExpr);
return lambda.Compile();
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace applicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for ExpressRouteCircuitAuthorizationsOperations.
/// </summary>
public static partial class ExpressRouteCircuitAuthorizationsOperationsExtensions
{
/// <summary>
/// Deletes the specified authorization from the specified express route
/// circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
public static void Delete(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName)
{
operations.DeleteAsync(resourceGroupName, circuitName, authorizationName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified authorization from the specified express route
/// circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, circuitName, authorizationName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets the specified authorization from the specified express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
public static ExpressRouteCircuitAuthorization Get(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName)
{
return operations.GetAsync(resourceGroupName, circuitName, authorizationName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the specified authorization from the specified express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ExpressRouteCircuitAuthorization> GetAsync(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, circuitName, authorizationName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates an authorization in the specified express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='authorizationParameters'>
/// Parameters supplied to the create or update express route circuit
/// authorization operation.
/// </param>
public static ExpressRouteCircuitAuthorization CreateOrUpdate(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, circuitName, authorizationName, authorizationParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates an authorization in the specified express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='authorizationParameters'>
/// Parameters supplied to the create or update express route circuit
/// authorization operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ExpressRouteCircuitAuthorization> CreateOrUpdateAsync(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, circuitName, authorizationName, authorizationParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all authorizations in an express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the circuit.
/// </param>
public static IPage<ExpressRouteCircuitAuthorization> List(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName)
{
return operations.ListAsync(resourceGroupName, circuitName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all authorizations in an express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the circuit.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ExpressRouteCircuitAuthorization>> ListAsync(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, circuitName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified authorization from the specified express route
/// circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
public static void BeginDelete(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName)
{
operations.BeginDeleteAsync(resourceGroupName, circuitName, authorizationName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified authorization from the specified express route
/// circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, circuitName, authorizationName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Creates or updates an authorization in the specified express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='authorizationParameters'>
/// Parameters supplied to the create or update express route circuit
/// authorization operation.
/// </param>
public static ExpressRouteCircuitAuthorization BeginCreateOrUpdate(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, circuitName, authorizationName, authorizationParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates an authorization in the specified express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='authorizationParameters'>
/// Parameters supplied to the create or update express route circuit
/// authorization operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ExpressRouteCircuitAuthorization> BeginCreateOrUpdateAsync(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, circuitName, authorizationName, authorizationParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all authorizations in an express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<ExpressRouteCircuitAuthorization> ListNext(this IExpressRouteCircuitAuthorizationsOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all authorizations in an express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ExpressRouteCircuitAuthorization>> ListNextAsync(this IExpressRouteCircuitAuthorizationsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/struct.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 Google.Protobuf.WellKnownTypes {
/// <summary>Holder for reflection information generated from google/protobuf/struct.proto</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class StructReflection {
#region Descriptor
/// <summary>File descriptor for google/protobuf/struct.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static StructReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Chxnb29nbGUvcHJvdG9idWYvc3RydWN0LnByb3RvEg9nb29nbGUucHJvdG9i",
"dWYihAEKBlN0cnVjdBIzCgZmaWVsZHMYASADKAsyIy5nb29nbGUucHJvdG9i",
"dWYuU3RydWN0LkZpZWxkc0VudHJ5GkUKC0ZpZWxkc0VudHJ5EgsKA2tleRgB",
"IAEoCRIlCgV2YWx1ZRgCIAEoCzIWLmdvb2dsZS5wcm90b2J1Zi5WYWx1ZToC",
"OAEi6gEKBVZhbHVlEjAKCm51bGxfdmFsdWUYASABKA4yGi5nb29nbGUucHJv",
"dG9idWYuTnVsbFZhbHVlSAASFgoMbnVtYmVyX3ZhbHVlGAIgASgBSAASFgoM",
"c3RyaW5nX3ZhbHVlGAMgASgJSAASFAoKYm9vbF92YWx1ZRgEIAEoCEgAEi8K",
"DHN0cnVjdF92YWx1ZRgFIAEoCzIXLmdvb2dsZS5wcm90b2J1Zi5TdHJ1Y3RI",
"ABIwCgpsaXN0X3ZhbHVlGAYgASgLMhouZ29vZ2xlLnByb3RvYnVmLkxpc3RW",
"YWx1ZUgAQgYKBGtpbmQiMwoJTGlzdFZhbHVlEiYKBnZhbHVlcxgBIAMoCzIW",
"Lmdvb2dsZS5wcm90b2J1Zi5WYWx1ZSobCglOdWxsVmFsdWUSDgoKTlVMTF9W",
"QUxVRRAAQoEBChNjb20uZ29vZ2xlLnByb3RvYnVmQgtTdHJ1Y3RQcm90b1AB",
"WjFnaXRodWIuY29tL2dvbGFuZy9wcm90b2J1Zi9wdHlwZXMvc3RydWN0O3N0",
"cnVjdHBioAEBogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93blR5",
"cGVzYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(new[] {typeof(global::Google.Protobuf.WellKnownTypes.NullValue), }, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Struct), global::Google.Protobuf.WellKnownTypes.Struct.Parser, new[]{ "Fields" }, null, null, new pbr::GeneratedClrTypeInfo[] { null, }),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Value), global::Google.Protobuf.WellKnownTypes.Value.Parser, new[]{ "NullValue", "NumberValue", "StringValue", "BoolValue", "StructValue", "ListValue" }, new[]{ "Kind" }, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.ListValue), global::Google.Protobuf.WellKnownTypes.ListValue.Parser, new[]{ "Values" }, null, null, null)
}));
}
#endregion
}
#region Enums
/// <summary>
/// `NullValue` is a singleton enumeration to represent the null value for the
/// `Value` type union.
///
/// The JSON representation for `NullValue` is JSON `null`.
/// </summary>
public enum NullValue {
/// <summary>
/// Null value.
/// </summary>
[pbr::OriginalName("NULL_VALUE")] NullValue = 0,
}
#endregion
#region Messages
/// <summary>
/// `Struct` represents a structured data value, consisting of fields
/// which map to dynamically typed values. In some languages, `Struct`
/// might be supported by a native representation. For example, in
/// scripting languages like JS a struct is represented as an
/// object. The details of that representation are described together
/// with the proto support for the language.
///
/// The JSON representation for `Struct` is JSON object.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Struct : pb::IMessage<Struct> {
private static readonly pb::MessageParser<Struct> _parser = new pb::MessageParser<Struct>(() => new Struct());
public static pb::MessageParser<Struct> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Protobuf.WellKnownTypes.StructReflection.Descriptor.MessageTypes[0]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public Struct() {
OnConstruction();
}
partial void OnConstruction();
public Struct(Struct other) : this() {
fields_ = other.fields_.Clone();
}
public Struct Clone() {
return new Struct(this);
}
/// <summary>Field number for the "fields" field.</summary>
public const int FieldsFieldNumber = 1;
private static readonly pbc::MapField<string, global::Google.Protobuf.WellKnownTypes.Value>.Codec _map_fields_codec
= new pbc::MapField<string, global::Google.Protobuf.WellKnownTypes.Value>.Codec(pb::FieldCodec.ForString(10), pb::FieldCodec.ForMessage(18, global::Google.Protobuf.WellKnownTypes.Value.Parser), 10);
private readonly pbc::MapField<string, global::Google.Protobuf.WellKnownTypes.Value> fields_ = new pbc::MapField<string, global::Google.Protobuf.WellKnownTypes.Value>();
/// <summary>
/// Unordered map of dynamically typed values.
/// </summary>
public pbc::MapField<string, global::Google.Protobuf.WellKnownTypes.Value> Fields {
get { return fields_; }
}
public override bool Equals(object other) {
return Equals(other as Struct);
}
public bool Equals(Struct other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!Fields.Equals(other.Fields)) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
hash ^= Fields.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
fields_.WriteTo(output, _map_fields_codec);
}
public int CalculateSize() {
int size = 0;
size += fields_.CalculateSize(_map_fields_codec);
return size;
}
public void MergeFrom(Struct other) {
if (other == null) {
return;
}
fields_.Add(other.fields_);
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
fields_.AddEntriesFrom(input, _map_fields_codec);
break;
}
}
}
}
}
/// <summary>
/// `Value` represents a dynamically typed value which can be either
/// null, a number, a string, a boolean, a recursive struct value, or a
/// list of values. A producer of value is expected to set one of that
/// variants, absence of any variant indicates an error.
///
/// The JSON representation for `Value` is JSON value.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Value : pb::IMessage<Value> {
private static readonly pb::MessageParser<Value> _parser = new pb::MessageParser<Value>(() => new Value());
public static pb::MessageParser<Value> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Protobuf.WellKnownTypes.StructReflection.Descriptor.MessageTypes[1]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public Value() {
OnConstruction();
}
partial void OnConstruction();
public Value(Value other) : this() {
switch (other.KindCase) {
case KindOneofCase.NullValue:
NullValue = other.NullValue;
break;
case KindOneofCase.NumberValue:
NumberValue = other.NumberValue;
break;
case KindOneofCase.StringValue:
StringValue = other.StringValue;
break;
case KindOneofCase.BoolValue:
BoolValue = other.BoolValue;
break;
case KindOneofCase.StructValue:
StructValue = other.StructValue.Clone();
break;
case KindOneofCase.ListValue:
ListValue = other.ListValue.Clone();
break;
}
}
public Value Clone() {
return new Value(this);
}
/// <summary>Field number for the "null_value" field.</summary>
public const int NullValueFieldNumber = 1;
/// <summary>
/// Represents a null value.
/// </summary>
public global::Google.Protobuf.WellKnownTypes.NullValue NullValue {
get { return kindCase_ == KindOneofCase.NullValue ? (global::Google.Protobuf.WellKnownTypes.NullValue) kind_ : 0; }
set {
kind_ = value;
kindCase_ = KindOneofCase.NullValue;
}
}
/// <summary>Field number for the "number_value" field.</summary>
public const int NumberValueFieldNumber = 2;
/// <summary>
/// Represents a double value.
/// </summary>
public double NumberValue {
get { return kindCase_ == KindOneofCase.NumberValue ? (double) kind_ : 0D; }
set {
kind_ = value;
kindCase_ = KindOneofCase.NumberValue;
}
}
/// <summary>Field number for the "string_value" field.</summary>
public const int StringValueFieldNumber = 3;
/// <summary>
/// Represents a string value.
/// </summary>
public string StringValue {
get { return kindCase_ == KindOneofCase.StringValue ? (string) kind_ : ""; }
set {
kind_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
kindCase_ = KindOneofCase.StringValue;
}
}
/// <summary>Field number for the "bool_value" field.</summary>
public const int BoolValueFieldNumber = 4;
/// <summary>
/// Represents a boolean value.
/// </summary>
public bool BoolValue {
get { return kindCase_ == KindOneofCase.BoolValue ? (bool) kind_ : false; }
set {
kind_ = value;
kindCase_ = KindOneofCase.BoolValue;
}
}
/// <summary>Field number for the "struct_value" field.</summary>
public const int StructValueFieldNumber = 5;
/// <summary>
/// Represents a structured value.
/// </summary>
public global::Google.Protobuf.WellKnownTypes.Struct StructValue {
get { return kindCase_ == KindOneofCase.StructValue ? (global::Google.Protobuf.WellKnownTypes.Struct) kind_ : null; }
set {
kind_ = value;
kindCase_ = value == null ? KindOneofCase.None : KindOneofCase.StructValue;
}
}
/// <summary>Field number for the "list_value" field.</summary>
public const int ListValueFieldNumber = 6;
/// <summary>
/// Represents a repeated `Value`.
/// </summary>
public global::Google.Protobuf.WellKnownTypes.ListValue ListValue {
get { return kindCase_ == KindOneofCase.ListValue ? (global::Google.Protobuf.WellKnownTypes.ListValue) kind_ : null; }
set {
kind_ = value;
kindCase_ = value == null ? KindOneofCase.None : KindOneofCase.ListValue;
}
}
private object kind_;
/// <summary>Enum of possible cases for the "kind" oneof.</summary>
public enum KindOneofCase {
None = 0,
NullValue = 1,
NumberValue = 2,
StringValue = 3,
BoolValue = 4,
StructValue = 5,
ListValue = 6,
}
private KindOneofCase kindCase_ = KindOneofCase.None;
public KindOneofCase KindCase {
get { return kindCase_; }
}
public void ClearKind() {
kindCase_ = KindOneofCase.None;
kind_ = null;
}
public override bool Equals(object other) {
return Equals(other as Value);
}
public bool Equals(Value other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (NullValue != other.NullValue) return false;
if (NumberValue != other.NumberValue) return false;
if (StringValue != other.StringValue) return false;
if (BoolValue != other.BoolValue) return false;
if (!object.Equals(StructValue, other.StructValue)) return false;
if (!object.Equals(ListValue, other.ListValue)) return false;
if (KindCase != other.KindCase) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (kindCase_ == KindOneofCase.NullValue) hash ^= NullValue.GetHashCode();
if (kindCase_ == KindOneofCase.NumberValue) hash ^= NumberValue.GetHashCode();
if (kindCase_ == KindOneofCase.StringValue) hash ^= StringValue.GetHashCode();
if (kindCase_ == KindOneofCase.BoolValue) hash ^= BoolValue.GetHashCode();
if (kindCase_ == KindOneofCase.StructValue) hash ^= StructValue.GetHashCode();
if (kindCase_ == KindOneofCase.ListValue) hash ^= ListValue.GetHashCode();
hash ^= (int) kindCase_;
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (kindCase_ == KindOneofCase.NullValue) {
output.WriteRawTag(8);
output.WriteEnum((int) NullValue);
}
if (kindCase_ == KindOneofCase.NumberValue) {
output.WriteRawTag(17);
output.WriteDouble(NumberValue);
}
if (kindCase_ == KindOneofCase.StringValue) {
output.WriteRawTag(26);
output.WriteString(StringValue);
}
if (kindCase_ == KindOneofCase.BoolValue) {
output.WriteRawTag(32);
output.WriteBool(BoolValue);
}
if (kindCase_ == KindOneofCase.StructValue) {
output.WriteRawTag(42);
output.WriteMessage(StructValue);
}
if (kindCase_ == KindOneofCase.ListValue) {
output.WriteRawTag(50);
output.WriteMessage(ListValue);
}
}
public int CalculateSize() {
int size = 0;
if (kindCase_ == KindOneofCase.NullValue) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) NullValue);
}
if (kindCase_ == KindOneofCase.NumberValue) {
size += 1 + 8;
}
if (kindCase_ == KindOneofCase.StringValue) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(StringValue);
}
if (kindCase_ == KindOneofCase.BoolValue) {
size += 1 + 1;
}
if (kindCase_ == KindOneofCase.StructValue) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(StructValue);
}
if (kindCase_ == KindOneofCase.ListValue) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ListValue);
}
return size;
}
public void MergeFrom(Value other) {
if (other == null) {
return;
}
switch (other.KindCase) {
case KindOneofCase.NullValue:
NullValue = other.NullValue;
break;
case KindOneofCase.NumberValue:
NumberValue = other.NumberValue;
break;
case KindOneofCase.StringValue:
StringValue = other.StringValue;
break;
case KindOneofCase.BoolValue:
BoolValue = other.BoolValue;
break;
case KindOneofCase.StructValue:
StructValue = other.StructValue;
break;
case KindOneofCase.ListValue:
ListValue = other.ListValue;
break;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
kind_ = input.ReadEnum();
kindCase_ = KindOneofCase.NullValue;
break;
}
case 17: {
NumberValue = input.ReadDouble();
break;
}
case 26: {
StringValue = input.ReadString();
break;
}
case 32: {
BoolValue = input.ReadBool();
break;
}
case 42: {
global::Google.Protobuf.WellKnownTypes.Struct subBuilder = new global::Google.Protobuf.WellKnownTypes.Struct();
if (kindCase_ == KindOneofCase.StructValue) {
subBuilder.MergeFrom(StructValue);
}
input.ReadMessage(subBuilder);
StructValue = subBuilder;
break;
}
case 50: {
global::Google.Protobuf.WellKnownTypes.ListValue subBuilder = new global::Google.Protobuf.WellKnownTypes.ListValue();
if (kindCase_ == KindOneofCase.ListValue) {
subBuilder.MergeFrom(ListValue);
}
input.ReadMessage(subBuilder);
ListValue = subBuilder;
break;
}
}
}
}
}
/// <summary>
/// `ListValue` is a wrapper around a repeated field of values.
///
/// The JSON representation for `ListValue` is JSON array.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class ListValue : pb::IMessage<ListValue> {
private static readonly pb::MessageParser<ListValue> _parser = new pb::MessageParser<ListValue>(() => new ListValue());
public static pb::MessageParser<ListValue> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Protobuf.WellKnownTypes.StructReflection.Descriptor.MessageTypes[2]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public ListValue() {
OnConstruction();
}
partial void OnConstruction();
public ListValue(ListValue other) : this() {
values_ = other.values_.Clone();
}
public ListValue Clone() {
return new ListValue(this);
}
/// <summary>Field number for the "values" field.</summary>
public const int ValuesFieldNumber = 1;
private static readonly pb::FieldCodec<global::Google.Protobuf.WellKnownTypes.Value> _repeated_values_codec
= pb::FieldCodec.ForMessage(10, global::Google.Protobuf.WellKnownTypes.Value.Parser);
private readonly pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Value> values_ = new pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Value>();
/// <summary>
/// Repeated field of dynamically typed values.
/// </summary>
public pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Value> Values {
get { return values_; }
}
public override bool Equals(object other) {
return Equals(other as ListValue);
}
public bool Equals(ListValue other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!values_.Equals(other.values_)) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
hash ^= values_.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
values_.WriteTo(output, _repeated_values_codec);
}
public int CalculateSize() {
int size = 0;
size += values_.CalculateSize(_repeated_values_codec);
return size;
}
public void MergeFrom(ListValue other) {
if (other == null) {
return;
}
values_.Add(other.values_);
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
values_.AddEntriesFrom(input, _repeated_values_codec);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Security.Cryptography.X509Certificates;
namespace LumiSoft.Net
{
/// <summary>
/// Holds IP bind info.
/// </summary>
public class IPBindInfo
{
private string m_HostName = "";
private BindInfoProtocol m_Protocol = BindInfoProtocol.TCP;
private IPEndPoint m_pEndPoint = null;
private SslMode m_SslMode = SslMode.None;
private X509Certificate2 m_pCertificate = null;
private object m_Tag = null;
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="hostName">Host name.</param>
/// <param name="protocol">Bind protocol.</param>
/// <param name="ip">IP address to listen.</param>
/// <param name="port">Port to listen.</param>
/// <exception cref="ArgumentNullException">Is raised when <b>ip</b> is null.</exception>
public IPBindInfo(string hostName,BindInfoProtocol protocol,IPAddress ip,int port)
{
if(ip == null){
throw new ArgumentNullException("ip");
}
m_HostName = hostName;
m_Protocol = protocol;
m_pEndPoint = new IPEndPoint(ip,port);
}
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="hostName">Host name.</param>
/// <param name="ip">IP address to listen.</param>
/// <param name="port">Port to listen.</param>
/// <param name="sslMode">Specifies SSL mode.</param>
/// <param name="sslCertificate">Certificate to use for SSL connections.</param>
/// <exception cref="ArgumentNullException">Is raised when <b>ip</b> is null.</exception>
public IPBindInfo(string hostName,IPAddress ip,int port,SslMode sslMode,X509Certificate2 sslCertificate) : this(hostName,BindInfoProtocol.TCP,ip,port,sslMode,sslCertificate)
{
}
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="hostName">Host name.</param>
/// <param name="protocol">Bind protocol.</param>
/// <param name="ip">IP address to listen.</param>
/// <param name="port">Port to listen.</param>
/// <param name="sslMode">Specifies SSL mode.</param>
/// <param name="sslCertificate">Certificate to use for SSL connections.</param>
/// <exception cref="ArgumentNullException">Is raised when <b>ip</b> is null.</exception>
/// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception>
public IPBindInfo(string hostName,BindInfoProtocol protocol,IPAddress ip,int port,SslMode sslMode,X509Certificate2 sslCertificate)
{
if(ip == null){
throw new ArgumentNullException("ip");
}
m_HostName = hostName;
m_Protocol = protocol;
m_pEndPoint = new IPEndPoint(ip,port);
m_SslMode = sslMode;
m_pCertificate = sslCertificate;
if((sslMode == SslMode.SSL || sslMode == SslMode.TLS) && sslCertificate == null){
throw new ArgumentException("SSL requested, but argument 'sslCertificate' is not provided.");
}
}
#region override method Equals
/// <summary>
/// Compares the current instance with another object of the same type.
/// </summary>
/// <param name="obj">An object to compare with this instance.</param>
/// <returns>Returns true if two objects are equal.</returns>
public override bool Equals(object obj)
{
if(obj == null){
return false;
}
if(!(obj is IPBindInfo)){
return false;
}
IPBindInfo bInfo = (IPBindInfo)obj;
if(bInfo.HostName != m_HostName){
return false;
}
if(bInfo.Protocol != m_Protocol){
return false;
}
if(!bInfo.EndPoint.Equals(m_pEndPoint)){
return false;
}
if(bInfo.SslMode != m_SslMode){
return false;
}
if(!X509Certificate.Equals(bInfo.Certificate,m_pCertificate)){
return false;
}
return true;
}
#endregion
#region override method GetHashCode
/// <summary>
/// Returns the hash code.
/// </summary>
/// <returns>Returns the hash code.</returns>
public override int GetHashCode()
{
return base.GetHashCode();
}
#endregion
#region Properties Implementation
/// <summary>
/// Gets host name.
/// </summary>
public string HostName
{
get{ return m_HostName; }
}
/// <summary>
/// Gets protocol.
/// </summary>
public BindInfoProtocol Protocol
{
get{ return m_Protocol; }
}
/// <summary>
/// Gets IP end point.
/// </summary>
public IPEndPoint EndPoint
{
get{ return m_pEndPoint; }
}
/// <summary>
/// Gets IP address.
/// </summary>
public IPAddress IP
{
get{ return m_pEndPoint.Address; }
}
/// <summary>
/// Gets port.
/// </summary>
public int Port
{
get{ return m_pEndPoint.Port; }
}
/// <summary>
/// Gets SSL mode.
/// </summary>
public SslMode SslMode
{
get{ return m_SslMode; }
}
/// <summary>
/// Gets SSL certificate.
/// </summary>
[Obsolete("Use property Certificate instead.")]
public X509Certificate2 SSL_Certificate
{
get{ return m_pCertificate; }
}
/// <summary>
/// Gets SSL certificate.
/// </summary>
public X509Certificate2 Certificate
{
get{ return m_pCertificate; }
}
/// <summary>
/// Gets or sets user data. This is used internally don't use it !!!.
/// </summary>
public object Tag
{
get{ return m_Tag; }
set{ m_Tag = value; }
}
#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.Buffers;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Slices.Tests
{
public class SlicesTests
{
[Fact]
public void ByteSpanEmptyCreateArrayTest()
{
var empty = Span<byte>.Empty;
var array = empty.ToArray();
Assert.Equal(0, array.Length);
}
[Fact]
public void ByteReadOnlySpanEmptyCreateArrayTest()
{
var empty = ReadOnlySpan<byte>.Empty;
var array = empty.ToArray();
Assert.Equal(0, array.Length);
}
[Fact]
public unsafe void ByteSpanEqualsTestsTwoDifferentInstancesOfBuffersWithOneValueDifferent()
{
const int bufferLength = 128;
byte[] buffer1 = new byte[bufferLength];
byte[] buffer2 = new byte[bufferLength];
for (int i = 0; i < bufferLength; i++)
{
buffer1[i] = (byte)(bufferLength + 1 - i);
buffer2[i] = (byte)(bufferLength + 1 - i);
}
fixed (byte* buffer1pinned = buffer1)
fixed (byte* buffer2pinned = buffer2)
{
Span<byte> b1 = new Span<byte>(buffer1pinned, bufferLength);
Span<byte> b2 = new Span<byte>(buffer2pinned, bufferLength);
for (int i = 0; i < bufferLength; i++)
{
for (int diffPosition = i; diffPosition < bufferLength; diffPosition++)
{
buffer1[diffPosition] = unchecked((byte)(buffer1[diffPosition] + 1));
Assert.False(b1.Slice(i).SequenceEqual(b2.Slice(i)));
}
}
}
}
[Fact]
public unsafe void ByteReadOnlySpanEqualsTestsTwoDifferentInstancesOfBuffersWithOneValueDifferent()
{
const int bufferLength = 128;
byte[] buffer1 = new byte[bufferLength];
byte[] buffer2 = new byte[bufferLength];
for (int i = 0; i < bufferLength; i++)
{
buffer1[i] = (byte)(bufferLength + 1 - i);
buffer2[i] = (byte)(bufferLength + 1 - i);
}
fixed (byte* buffer1pinned = buffer1)
fixed (byte* buffer2pinned = buffer2)
{
ReadOnlySpan<byte> b1 = new ReadOnlySpan<byte>(buffer1pinned, bufferLength);
ReadOnlySpan<byte> b2 = new ReadOnlySpan<byte>(buffer2pinned, bufferLength);
for (int i = 0; i < bufferLength; i++)
{
for (int diffPosition = i; diffPosition < bufferLength; diffPosition++)
{
buffer1[diffPosition] = unchecked((byte)(buffer1[diffPosition] + 1));
Assert.False(b1.Slice(i).SequenceEqual(b2.Slice(i)));
}
}
}
}
[Theory]
[InlineData(new byte[0], 0, 0)]
[InlineData(new byte[1] { 0 }, 0, 0)]
[InlineData(new byte[1] { 0 }, 0, 1)]
[InlineData(new byte[2] { 0, 0 }, 0, 2)]
[InlineData(new byte[2] { 0, 0 }, 0, 1)]
[InlineData(new byte[2] { 0, 0 }, 1, 1)]
[InlineData(new byte[2] { 0, 0 }, 2, 0)]
[InlineData(new byte[3] { 0, 0, 0 }, 0, 3)]
[InlineData(new byte[3] { 0, 0, 0 }, 0, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 1, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 1, 1)]
public void ByteSpanCtorWithRangeValidCases(byte[] bytes, int start, int length)
{
Span<byte> span = new Span<byte>(bytes, start, length);
}
[Theory]
[InlineData(new byte[0], 0, 0)]
[InlineData(new byte[1] { 0 }, 0, 0)]
[InlineData(new byte[1] { 0 }, 0, 1)]
[InlineData(new byte[2] { 0, 0 }, 0, 2)]
[InlineData(new byte[2] { 0, 0 }, 0, 1)]
[InlineData(new byte[2] { 0, 0 }, 1, 1)]
[InlineData(new byte[2] { 0, 0 }, 2, 0)]
[InlineData(new byte[3] { 0, 0, 0 }, 0, 3)]
[InlineData(new byte[3] { 0, 0, 0 }, 0, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 1, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 1, 1)]
public void ByteReadOnlySpanCtorWithRangeValidCases(byte[] bytes, int start, int length)
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(bytes, start, length);
}
[Fact]
public void ByteSpanCtorWithRangeThrowsArgumentExceptionOnNull()
{
Assert.Throws<ArgumentNullException>(() => { Span<byte> span = new Span<byte>(null, 0, 0); });
}
[Fact]
public void ByteReadOnlySpanCtorWithRangeThrowsArgumentExceptionOnNull()
{
Assert.Throws<ArgumentNullException>(() => { ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(null, 0, 0); });
}
[Theory]
[InlineData(new byte[0], 1, 0)]
[InlineData(new byte[0], 1, -1)]
[InlineData(new byte[0], 0, 1)]
[InlineData(new byte[0], -1, 0)]
[InlineData(new byte[0], 5, 5)]
[InlineData(new byte[1] { 0 }, 0, 2)]
[InlineData(new byte[1] { 0 }, 1, 1)]
[InlineData(new byte[1] { 0 }, -1, 2)]
[InlineData(new byte[2] { 0, 0 }, 0, 3)]
[InlineData(new byte[2] { 0, 0 }, 1, 2)]
[InlineData(new byte[2] { 0, 0 }, 2, 1)]
[InlineData(new byte[2] { 0, 0 }, 3, 0)]
[InlineData(new byte[2] { 0, 0 }, 1, -1)]
[InlineData(new byte[2] { 0, 0 }, 2, int.MaxValue)]
[InlineData(new byte[2] { 0, 0 }, int.MinValue, int.MinValue)]
[InlineData(new byte[2] { 0, 0 }, int.MaxValue, int.MaxValue)]
[InlineData(new byte[2] { 0, 0 }, int.MinValue, int.MaxValue)]
[InlineData(new byte[3] { 0, 0, 0 }, 1, 3)]
[InlineData(new byte[3] { 0, 0, 0 }, 2, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 15, 0)]
public void ByteSpanCtorWithRangeThrowsArgumentOutOfRangeException(byte[] bytes, int start, int length)
{
Assert.Throws<ArgumentOutOfRangeException>(() => { Span<byte> span = new Span<byte>(bytes, start, length); });
}
[Theory]
[InlineData(new byte[0], 0, 0)]
[InlineData(new byte[1] { 0 }, 0, 0)]
[InlineData(new byte[1] { 0 }, 0, 1)]
[InlineData(new byte[2] { 0, 0 }, 0, 2)]
[InlineData(new byte[2] { 0, 0 }, 0, 1)]
[InlineData(new byte[2] { 0, 0 }, 1, 1)]
[InlineData(new byte[2] { 0, 0 }, 2, 0)]
[InlineData(new byte[3] { 0, 0, 0 }, 0, 3)]
[InlineData(new byte[3] { 0, 0, 0 }, 0, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 1, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 1, 1)]
public void ByteSpanSliceWithRangeValidCases(byte[] bytes, int start, int length)
{
Span<byte> span = new Span<byte>(bytes, start, length);
}
[Theory]
[InlineData(new byte[0], 1, 0)]
[InlineData(new byte[0], 1, -1)]
[InlineData(new byte[0], 0, 1)]
[InlineData(new byte[0], -1, 0)]
[InlineData(new byte[0], 5, 5)]
[InlineData(new byte[1] { 0 }, 0, 2)]
[InlineData(new byte[1] { 0 }, 1, 1)]
[InlineData(new byte[1] { 0 }, -1, 2)]
[InlineData(new byte[2] { 0, 0 }, 0, 3)]
[InlineData(new byte[2] { 0, 0 }, 1, 2)]
[InlineData(new byte[2] { 0, 0 }, 2, 1)]
[InlineData(new byte[2] { 0, 0 }, 3, 0)]
[InlineData(new byte[2] { 0, 0 }, 1, -1)]
[InlineData(new byte[2] { 0, 0 }, 2, int.MaxValue)]
[InlineData(new byte[2] { 0, 0 }, int.MinValue, int.MinValue)]
[InlineData(new byte[2] { 0, 0 }, int.MaxValue, int.MaxValue)]
[InlineData(new byte[2] { 0, 0 }, int.MinValue, int.MaxValue)]
[InlineData(new byte[3] { 0, 0, 0 }, 1, 3)]
[InlineData(new byte[3] { 0, 0, 0 }, 2, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 15, 0)]
public void ByteSpanSliceWithRangeThrowsArgumentOutOfRangeException1(byte[] bytes, int start, int length)
{
var span = new Span<byte>(bytes);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
Span<byte> slice = span.Slice(start, length);
});
}
[Theory]
[InlineData(new byte[0], 0)]
[InlineData(new byte[1] { 0 }, 0)]
[InlineData(new byte[1] { 0 }, 1)]
[InlineData(new byte[2] { 0, 0 }, 0)]
[InlineData(new byte[2] { 0, 0 }, 1)]
[InlineData(new byte[2] { 0, 0 }, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 0)]
[InlineData(new byte[3] { 0, 0, 0 }, 1)]
[InlineData(new byte[3] { 0, 0, 0 }, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 3)]
public void ByteSpanSliceWithStartRangeValidCases(byte[] bytes, int start)
{
Span<byte> span = new Span<byte>(bytes).Slice(start);
}
[Theory]
[InlineData(new byte[0], int.MinValue)]
[InlineData(new byte[0], -1)]
[InlineData(new byte[0], 1)]
[InlineData(new byte[0], int.MaxValue)]
[InlineData(new byte[1] { 0 }, int.MinValue)]
[InlineData(new byte[1] { 0 }, -1)]
[InlineData(new byte[1] { 0 }, 2)]
[InlineData(new byte[1] { 0 }, int.MaxValue)]
[InlineData(new byte[2] { 0, 0 }, int.MinValue)]
[InlineData(new byte[2] { 0, 0 }, -1)]
[InlineData(new byte[2] { 0, 0 }, 3)]
[InlineData(new byte[2] { 0, 0 }, int.MaxValue)]
public void ByteSpanSliceWithStartRangeThrowsArgumentOutOfRangeException(byte[] bytes, int start)
{
var span = new Span<byte>(bytes);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
Span<byte> slice = span.Slice(start);
});
}
public void ByteReadOnlySpanCtorWithRangeThrowsArgumentOutOfRangeException(byte[] bytes, int start, int length)
{
Assert.Throws<ArgumentOutOfRangeException>(() => { ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(bytes, start, length); });
}
[Fact]
public void SetSpan()
{
var destination = new Span<byte>(new byte[100]);
var source = new Span<byte>(new byte[] { 1, 2, 3 });
source.CopyTo(destination);
for (int i = 0; i < source.Length; i++)
{
Assert.Equal(source[i], destination[i]);
}
}
[Fact]
public void SetArray()
{
var destination = new Span<byte>(new byte[100]);
var source = new byte[] { 1, 2, 3 };
source.CopyTo(destination);
for (int i = 0; i < source.Length; i++)
{
Assert.Equal(source[i], destination[i]);
}
}
[Fact]
public void CovariantSlicesNotSupported1()
{
object[] array = new string[10];
Assert.Throws<ArrayTypeMismatchException>(() => { var slice = new Span<object>(array); });
}
[Fact]
public void CovariantSlicesNotSupported2()
{
object[] array = new string[10];
Assert.Throws<ArrayTypeMismatchException>(() => { var slice = array.Slice(0); });
}
[Fact]
public void CovariantSlicesNotSupported3()
{
object[] array = new string[10];
Assert.Throws<ArrayTypeMismatchException>(() => { var slice = new Span<object>(array, 0, 10); });
}
}
}
| |
/*
* REST API Documentation for the MOTI School Bus Application
*
* The School Bus application tracks that inspections are performed in a timely fashion. For each school bus the application tracks information about the bus (including data from ICBC, NSC, etc.), it's past and next inspection dates and results, contacts, and the inspector responsible for next inspecting the bus.
*
* OpenAPI spec version: v1
*
*
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace SchoolBusAPI.ViewModels
{
/// <summary>
///
/// </summary>
[DataContract]
public partial class UserViewModel : IEquatable<UserViewModel>
{
/// <summary>
/// Default constructor, required by entity framework
/// </summary>
public UserViewModel()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="UserViewModel" /> class.
/// </summary>
/// <param name="Id">Id (required).</param>
/// <param name="Active">Active (required).</param>
/// <param name="GivenName">GivenName.</param>
/// <param name="Surname">Surname.</param>
/// <param name="Initials">Initials.</param>
/// <param name="Email">Email.</param>
public UserViewModel(int Id, bool Active, string GivenName = null, string Surname = null, string Initials = null, string Email = null)
{
this.Id = Id;
this.Active = Active;
this.GivenName = GivenName;
this.Surname = Surname;
this.Initials = Initials;
this.Email = Email;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id")]
public int Id { get; set; }
/// <summary>
/// Gets or Sets Active
/// </summary>
[DataMember(Name="active")]
public bool Active { get; set; }
/// <summary>
/// Gets or Sets GivenName
/// </summary>
[DataMember(Name="givenName")]
public string GivenName { get; set; }
/// <summary>
/// Gets or Sets Surname
/// </summary>
[DataMember(Name="surname")]
public string Surname { get; set; }
/// <summary>
/// Gets or Sets Initials
/// </summary>
[DataMember(Name="initials")]
public string Initials { get; set; }
/// <summary>
/// Gets or Sets Email
/// </summary>
[DataMember(Name="email")]
public string Email { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class UserViewModel {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Active: ").Append(Active).Append("\n");
sb.Append(" GivenName: ").Append(GivenName).Append("\n");
sb.Append(" Surname: ").Append(Surname).Append("\n");
sb.Append(" Initials: ").Append(Initials).Append("\n");
sb.Append(" Email: ").Append(Email).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) { return false; }
if (ReferenceEquals(this, obj)) { return true; }
if (obj.GetType() != GetType()) { return false; }
return Equals((UserViewModel)obj);
}
/// <summary>
/// Returns true if UserViewModel instances are equal
/// </summary>
/// <param name="other">Instance of UserViewModel to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(UserViewModel other)
{
if (ReferenceEquals(null, other)) { return false; }
if (ReferenceEquals(this, other)) { return true; }
return
(
this.Id == other.Id ||
this.Id.Equals(other.Id)
) &&
(
this.Active == other.Active ||
this.Active.Equals(other.Active)
) &&
(
this.GivenName == other.GivenName ||
this.GivenName != null &&
this.GivenName.Equals(other.GivenName)
) &&
(
this.Surname == other.Surname ||
this.Surname != null &&
this.Surname.Equals(other.Surname)
) &&
(
this.Initials == other.Initials ||
this.Initials != null &&
this.Initials.Equals(other.Initials)
) &&
(
this.Email == other.Email ||
this.Email != null &&
this.Email.Equals(other.Email)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
hash = hash * 59 + this.Id.GetHashCode();
// Suitable nullity checks
if (this.GivenName != null)
{
hash = hash * 59 + this.GivenName.GetHashCode();
}
if (this.Surname != null)
{
hash = hash * 59 + this.Surname.GetHashCode();
}
if (this.Initials != null)
{
hash = hash * 59 + this.Initials.GetHashCode();
}
if (this.Email != null)
{
hash = hash * 59 + this.Email.GetHashCode();
}
return hash;
}
}
#region Operators
public static bool operator ==(UserViewModel left, UserViewModel right)
{
return Equals(left, right);
}
public static bool operator !=(UserViewModel left, UserViewModel right)
{
return !Equals(left, right);
}
#endregion Operators
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions.ObjectExtensions;
using osu.Framework.Graphics;
using osu.Framework.Logging;
using osu.Game.Beatmaps;
using osu.Game.Database;
using osu.Game.Online.API;
using osu.Game.Online.Rooms;
using osu.Game.Online.Rooms.RoomStatuses;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Users;
using osu.Game.Utils;
namespace osu.Game.Online.Multiplayer
{
public abstract class MultiplayerClient : Component, IMultiplayerClient, IMultiplayerRoomServer
{
/// <summary>
/// Invoked when any change occurs to the multiplayer room.
/// </summary>
public event Action? RoomUpdated;
public event Action<MultiplayerRoomUser>? UserJoined;
public event Action<MultiplayerRoomUser>? UserLeft;
public event Action<MultiplayerRoomUser>? UserKicked;
/// <summary>
/// Invoked when the multiplayer server requests the current beatmap to be loaded into play.
/// </summary>
public event Action? LoadRequested;
/// <summary>
/// Invoked when the multiplayer server requests gameplay to be started.
/// </summary>
public event Action? MatchStarted;
/// <summary>
/// Invoked when the multiplayer server has finished collating results.
/// </summary>
public event Action? ResultsReady;
/// <summary>
/// Whether the <see cref="MultiplayerClient"/> is currently connected.
/// This is NOT thread safe and usage should be scheduled.
/// </summary>
public abstract IBindable<bool> IsConnected { get; }
/// <summary>
/// The joined <see cref="MultiplayerRoom"/>.
/// </summary>
public MultiplayerRoom? Room { get; private set; }
/// <summary>
/// The users in the joined <see cref="Room"/> which are participating in the current gameplay loop.
/// </summary>
public IBindableList<int> CurrentMatchPlayingUserIds => PlayingUserIds;
protected readonly BindableList<int> PlayingUserIds = new BindableList<int>();
public readonly Bindable<PlaylistItem?> CurrentMatchPlayingItem = new Bindable<PlaylistItem?>();
/// <summary>
/// The <see cref="MultiplayerRoomUser"/> corresponding to the local player, if available.
/// </summary>
public MultiplayerRoomUser? LocalUser => Room?.Users.SingleOrDefault(u => u.User?.Id == API.LocalUser.Value.Id);
/// <summary>
/// Whether the <see cref="LocalUser"/> is the host in <see cref="Room"/>.
/// </summary>
public bool IsHost
{
get
{
var localUser = LocalUser;
return localUser != null && Room?.Host != null && localUser.Equals(Room.Host);
}
}
[Resolved]
protected IAPIProvider API { get; private set; } = null!;
[Resolved]
protected RulesetStore Rulesets { get; private set; } = null!;
[Resolved]
private UserLookupCache userLookupCache { get; set; } = null!;
protected Room? APIRoom { get; private set; }
[BackgroundDependencyLoader]
private void load()
{
IsConnected.BindValueChanged(connected =>
{
// clean up local room state on server disconnect.
if (!connected.NewValue && Room != null)
{
Logger.Log("Connection to multiplayer server was lost.", LoggingTarget.Runtime, LogLevel.Important);
LeaveRoom();
}
});
}
private readonly TaskChain joinOrLeaveTaskChain = new TaskChain();
private CancellationTokenSource? joinCancellationSource;
/// <summary>
/// Joins the <see cref="MultiplayerRoom"/> for a given API <see cref="Room"/>.
/// </summary>
/// <param name="room">The API <see cref="Room"/>.</param>
/// <param name="password">An optional password to use for the join operation.</param>
public async Task JoinRoom(Room room, string? password = null)
{
var cancellationSource = joinCancellationSource = new CancellationTokenSource();
await joinOrLeaveTaskChain.Add(async () =>
{
if (Room != null)
throw new InvalidOperationException("Cannot join a multiplayer room while already in one.");
Debug.Assert(room.RoomID.Value != null);
// Join the server-side room.
var joinedRoom = await JoinRoom(room.RoomID.Value.Value, password ?? room.Password.Value).ConfigureAwait(false);
Debug.Assert(joinedRoom != null);
// Populate users.
Debug.Assert(joinedRoom.Users != null);
await Task.WhenAll(joinedRoom.Users.Select(PopulateUser)).ConfigureAwait(false);
// Update the stored room (must be done on update thread for thread-safety).
await scheduleAsync(() =>
{
Room = joinedRoom;
APIRoom = room;
foreach (var user in joinedRoom.Users)
updateUserPlayingState(user.UserID, user.State);
OnRoomJoined();
}, cancellationSource.Token).ConfigureAwait(false);
// Update room settings.
await updateLocalRoomSettings(joinedRoom.Settings, cancellationSource.Token).ConfigureAwait(false);
}, cancellationSource.Token).ConfigureAwait(false);
}
/// <summary>
/// Fired when the room join sequence is complete
/// </summary>
protected virtual void OnRoomJoined()
{
}
/// <summary>
/// Joins the <see cref="MultiplayerRoom"/> with a given ID.
/// </summary>
/// <param name="roomId">The room ID.</param>
/// <param name="password">An optional password to use when joining the room.</param>
/// <returns>The joined <see cref="MultiplayerRoom"/>.</returns>
protected abstract Task<MultiplayerRoom> JoinRoom(long roomId, string? password = null);
public Task LeaveRoom()
{
// The join may have not completed yet, so certain tasks that either update the room or reference the room should be cancelled.
// This includes the setting of Room itself along with the initial update of the room settings on join.
joinCancellationSource?.Cancel();
// Leaving rooms is expected to occur instantaneously whilst the operation is finalised in the background.
// However a few members need to be reset immediately to prevent other components from entering invalid states whilst the operation hasn't yet completed.
// For example, if a room was left and the user immediately pressed the "create room" button, then the user could be taken into the lobby if the value of Room is not reset in time.
var scheduledReset = scheduleAsync(() =>
{
APIRoom = null;
Room = null;
CurrentMatchPlayingItem.Value = null;
PlayingUserIds.Clear();
RoomUpdated?.Invoke();
});
return joinOrLeaveTaskChain.Add(async () =>
{
await scheduledReset.ConfigureAwait(false);
await LeaveRoomInternal().ConfigureAwait(false);
});
}
protected abstract Task LeaveRoomInternal();
/// <summary>
/// Change the current <see cref="MultiplayerRoom"/> settings.
/// </summary>
/// <remarks>
/// A room must be joined for this to have any effect.
/// </remarks>
/// <param name="name">The new room name, if any.</param>
/// <param name="password">The new password, if any.</param>
/// <param name="matchType">The type of the match, if any.</param>
/// <param name="item">The new room playlist item, if any.</param>
public Task ChangeSettings(Optional<string> name = default, Optional<string> password = default, Optional<MatchType> matchType = default, Optional<PlaylistItem> item = default)
{
if (Room == null)
throw new InvalidOperationException("Must be joined to a match to change settings.");
// A dummy playlist item filled with the current room settings (except mods).
var existingPlaylistItem = new PlaylistItem
{
Beatmap =
{
Value = new BeatmapInfo
{
OnlineBeatmapID = Room.Settings.BeatmapID,
MD5Hash = Room.Settings.BeatmapChecksum
}
},
RulesetID = Room.Settings.RulesetID
};
return ChangeSettings(new MultiplayerRoomSettings
{
Name = name.GetOr(Room.Settings.Name),
Password = password.GetOr(Room.Settings.Password),
BeatmapID = item.GetOr(existingPlaylistItem).BeatmapID,
BeatmapChecksum = item.GetOr(existingPlaylistItem).Beatmap.Value.MD5Hash,
RulesetID = item.GetOr(existingPlaylistItem).RulesetID,
MatchType = matchType.GetOr(Room.Settings.MatchType),
RequiredMods = item.HasValue ? item.Value.AsNonNull().RequiredMods.Select(m => new APIMod(m)).ToList() : Room.Settings.RequiredMods,
AllowedMods = item.HasValue ? item.Value.AsNonNull().AllowedMods.Select(m => new APIMod(m)).ToList() : Room.Settings.AllowedMods,
});
}
/// <summary>
/// Toggles the <see cref="LocalUser"/>'s ready state.
/// </summary>
/// <exception cref="InvalidOperationException">If a toggle of ready state is not valid at this time.</exception>
public async Task ToggleReady()
{
var localUser = LocalUser;
if (localUser == null)
return;
switch (localUser.State)
{
case MultiplayerUserState.Idle:
await ChangeState(MultiplayerUserState.Ready).ConfigureAwait(false);
return;
case MultiplayerUserState.Ready:
await ChangeState(MultiplayerUserState.Idle).ConfigureAwait(false);
return;
default:
throw new InvalidOperationException($"Cannot toggle ready when in {localUser.State}");
}
}
/// <summary>
/// Toggles the <see cref="LocalUser"/>'s spectating state.
/// </summary>
/// <exception cref="InvalidOperationException">If a toggle of the spectating state is not valid at this time.</exception>
public async Task ToggleSpectate()
{
var localUser = LocalUser;
if (localUser == null)
return;
switch (localUser.State)
{
case MultiplayerUserState.Idle:
case MultiplayerUserState.Ready:
await ChangeState(MultiplayerUserState.Spectating).ConfigureAwait(false);
return;
case MultiplayerUserState.Spectating:
await ChangeState(MultiplayerUserState.Idle).ConfigureAwait(false);
return;
default:
throw new InvalidOperationException($"Cannot toggle spectate when in {localUser.State}");
}
}
public abstract Task TransferHost(int userId);
public abstract Task KickUser(int userId);
public abstract Task ChangeSettings(MultiplayerRoomSettings settings);
public abstract Task ChangeState(MultiplayerUserState newState);
public abstract Task ChangeBeatmapAvailability(BeatmapAvailability newBeatmapAvailability);
/// <summary>
/// Change the local user's mods in the currently joined room.
/// </summary>
/// <param name="newMods">The proposed new mods, excluding any required by the room itself.</param>
public Task ChangeUserMods(IEnumerable<Mod> newMods) => ChangeUserMods(newMods.Select(m => new APIMod(m)).ToList());
public abstract Task ChangeUserMods(IEnumerable<APIMod> newMods);
public abstract Task SendMatchRequest(MatchUserRequest request);
public abstract Task StartMatch();
Task IMultiplayerClient.RoomStateChanged(MultiplayerRoomState state)
{
if (Room == null)
return Task.CompletedTask;
Scheduler.Add(() =>
{
if (Room == null)
return;
Debug.Assert(APIRoom != null);
Room.State = state;
switch (state)
{
case MultiplayerRoomState.Open:
APIRoom.Status.Value = new RoomStatusOpen();
break;
case MultiplayerRoomState.Playing:
APIRoom.Status.Value = new RoomStatusPlaying();
break;
case MultiplayerRoomState.Closed:
APIRoom.Status.Value = new RoomStatusEnded();
break;
}
RoomUpdated?.Invoke();
}, false);
return Task.CompletedTask;
}
async Task IMultiplayerClient.UserJoined(MultiplayerRoomUser user)
{
if (Room == null)
return;
await PopulateUser(user).ConfigureAwait(false);
Scheduler.Add(() =>
{
if (Room == null)
return;
// for sanity, ensure that there can be no duplicate users in the room user list.
if (Room.Users.Any(existing => existing.UserID == user.UserID))
return;
Room.Users.Add(user);
UserJoined?.Invoke(user);
RoomUpdated?.Invoke();
});
}
Task IMultiplayerClient.UserLeft(MultiplayerRoomUser user) =>
handleUserLeft(user, UserLeft);
Task IMultiplayerClient.UserKicked(MultiplayerRoomUser user)
{
if (LocalUser == null)
return Task.CompletedTask;
if (user.Equals(LocalUser))
LeaveRoom();
return handleUserLeft(user, UserKicked);
}
private Task handleUserLeft(MultiplayerRoomUser user, Action<MultiplayerRoomUser>? callback)
{
if (Room == null)
return Task.CompletedTask;
Scheduler.Add(() =>
{
if (Room == null)
return;
Room.Users.Remove(user);
PlayingUserIds.Remove(user.UserID);
callback?.Invoke(user);
RoomUpdated?.Invoke();
}, false);
return Task.CompletedTask;
}
Task IMultiplayerClient.HostChanged(int userId)
{
if (Room == null)
return Task.CompletedTask;
Scheduler.Add(() =>
{
if (Room == null)
return;
Debug.Assert(APIRoom != null);
var user = Room.Users.FirstOrDefault(u => u.UserID == userId);
Room.Host = user;
APIRoom.Host.Value = user?.User;
RoomUpdated?.Invoke();
}, false);
return Task.CompletedTask;
}
Task IMultiplayerClient.SettingsChanged(MultiplayerRoomSettings newSettings)
{
updateLocalRoomSettings(newSettings);
return Task.CompletedTask;
}
Task IMultiplayerClient.UserStateChanged(int userId, MultiplayerUserState state)
{
if (Room == null)
return Task.CompletedTask;
Scheduler.Add(() =>
{
if (Room == null)
return;
Room.Users.Single(u => u.UserID == userId).State = state;
updateUserPlayingState(userId, state);
RoomUpdated?.Invoke();
}, false);
return Task.CompletedTask;
}
Task IMultiplayerClient.MatchUserStateChanged(int userId, MatchUserState state)
{
if (Room == null)
return Task.CompletedTask;
Scheduler.Add(() =>
{
if (Room == null)
return;
Room.Users.Single(u => u.UserID == userId).MatchState = state;
RoomUpdated?.Invoke();
}, false);
return Task.CompletedTask;
}
Task IMultiplayerClient.MatchRoomStateChanged(MatchRoomState state)
{
if (Room == null)
return Task.CompletedTask;
Scheduler.Add(() =>
{
if (Room == null)
return;
Room.MatchState = state;
RoomUpdated?.Invoke();
}, false);
return Task.CompletedTask;
}
public Task MatchEvent(MatchServerEvent e)
{
// not used by any match types just yet.
return Task.CompletedTask;
}
Task IMultiplayerClient.UserBeatmapAvailabilityChanged(int userId, BeatmapAvailability beatmapAvailability)
{
if (Room == null)
return Task.CompletedTask;
Scheduler.Add(() =>
{
var user = Room?.Users.SingleOrDefault(u => u.UserID == userId);
// errors here are not critical - beatmap availability state is mostly for display.
if (user == null)
return;
user.BeatmapAvailability = beatmapAvailability;
RoomUpdated?.Invoke();
}, false);
return Task.CompletedTask;
}
public Task UserModsChanged(int userId, IEnumerable<APIMod> mods)
{
if (Room == null)
return Task.CompletedTask;
Scheduler.Add(() =>
{
var user = Room?.Users.SingleOrDefault(u => u.UserID == userId);
// errors here are not critical - user mods are mostly for display.
if (user == null)
return;
user.Mods = mods;
RoomUpdated?.Invoke();
}, false);
return Task.CompletedTask;
}
Task IMultiplayerClient.LoadRequested()
{
if (Room == null)
return Task.CompletedTask;
Scheduler.Add(() =>
{
if (Room == null)
return;
LoadRequested?.Invoke();
}, false);
return Task.CompletedTask;
}
Task IMultiplayerClient.MatchStarted()
{
if (Room == null)
return Task.CompletedTask;
Scheduler.Add(() =>
{
if (Room == null)
return;
MatchStarted?.Invoke();
}, false);
return Task.CompletedTask;
}
Task IMultiplayerClient.ResultsReady()
{
if (Room == null)
return Task.CompletedTask;
Scheduler.Add(() =>
{
if (Room == null)
return;
ResultsReady?.Invoke();
}, false);
return Task.CompletedTask;
}
/// <summary>
/// Populates the <see cref="User"/> for a given <see cref="MultiplayerRoomUser"/>.
/// </summary>
/// <param name="multiplayerUser">The <see cref="MultiplayerRoomUser"/> to populate.</param>
protected async Task PopulateUser(MultiplayerRoomUser multiplayerUser) => multiplayerUser.User ??= await userLookupCache.GetUserAsync(multiplayerUser.UserID).ConfigureAwait(false);
/// <summary>
/// Updates the local room settings with the given <see cref="MultiplayerRoomSettings"/>.
/// </summary>
/// <remarks>
/// This updates both the joined <see cref="MultiplayerRoom"/> and the respective API <see cref="Room"/>.
/// </remarks>
/// <param name="settings">The new <see cref="MultiplayerRoomSettings"/> to update from.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to cancel the update.</param>
private Task updateLocalRoomSettings(MultiplayerRoomSettings settings, CancellationToken cancellationToken = default) => scheduleAsync(() =>
{
if (Room == null)
return;
Debug.Assert(APIRoom != null);
// Update a few properties of the room instantaneously.
Room.Settings = settings;
APIRoom.Name.Value = Room.Settings.Name;
APIRoom.Password.Value = Room.Settings.Password;
// The current item update is delayed until an online beatmap lookup (below) succeeds.
// In-order for the client to not display an outdated beatmap, the current item is forcefully cleared here.
CurrentMatchPlayingItem.Value = null;
RoomUpdated?.Invoke();
GetOnlineBeatmapSet(settings.BeatmapID, cancellationToken).ContinueWith(set => Schedule(() =>
{
if (cancellationToken.IsCancellationRequested)
return;
updatePlaylist(settings, set.Result);
}), TaskContinuationOptions.OnlyOnRanToCompletion);
}, cancellationToken);
private void updatePlaylist(MultiplayerRoomSettings settings, BeatmapSetInfo beatmapSet)
{
if (Room == null || !Room.Settings.Equals(settings))
return;
Debug.Assert(APIRoom != null);
var beatmap = beatmapSet.Beatmaps.Single(b => b.OnlineBeatmapID == settings.BeatmapID);
beatmap.MD5Hash = settings.BeatmapChecksum;
var ruleset = Rulesets.GetRuleset(settings.RulesetID).CreateInstance();
var mods = settings.RequiredMods.Select(m => m.ToMod(ruleset));
var allowedMods = settings.AllowedMods.Select(m => m.ToMod(ruleset));
// Try to retrieve the existing playlist item from the API room.
var playlistItem = APIRoom.Playlist.FirstOrDefault(i => i.ID == settings.PlaylistItemId);
if (playlistItem != null)
updateItem(playlistItem);
else
{
// An existing playlist item does not exist, so append a new one.
updateItem(playlistItem = new PlaylistItem());
APIRoom.Playlist.Add(playlistItem);
}
CurrentMatchPlayingItem.Value = playlistItem;
void updateItem(PlaylistItem item)
{
item.ID = settings.PlaylistItemId;
item.Beatmap.Value = beatmap;
item.Ruleset.Value = ruleset.RulesetInfo;
item.RequiredMods.Clear();
item.RequiredMods.AddRange(mods);
item.AllowedMods.Clear();
item.AllowedMods.AddRange(allowedMods);
}
}
/// <summary>
/// Retrieves a <see cref="BeatmapSetInfo"/> from an online source.
/// </summary>
/// <param name="beatmapId">The beatmap set ID.</param>
/// <param name="cancellationToken">A token to cancel the request.</param>
/// <returns>The <see cref="BeatmapSetInfo"/> retrieval task.</returns>
protected abstract Task<BeatmapSetInfo> GetOnlineBeatmapSet(int beatmapId, CancellationToken cancellationToken = default);
/// <summary>
/// For the provided user ID, update whether the user is included in <see cref="CurrentMatchPlayingUserIds"/>.
/// </summary>
/// <param name="userId">The user's ID.</param>
/// <param name="state">The new state of the user.</param>
private void updateUserPlayingState(int userId, MultiplayerUserState state)
{
bool wasPlaying = PlayingUserIds.Contains(userId);
bool isPlaying = state >= MultiplayerUserState.WaitingForLoad && state <= MultiplayerUserState.FinishedPlay;
if (isPlaying == wasPlaying)
return;
if (isPlaying)
PlayingUserIds.Add(userId);
else
PlayingUserIds.Remove(userId);
}
private Task scheduleAsync(Action action, CancellationToken cancellationToken = default)
{
var tcs = new TaskCompletionSource<bool>();
Scheduler.Add(() =>
{
if (cancellationToken.IsCancellationRequested)
{
tcs.SetCanceled();
return;
}
try
{
action();
tcs.SetResult(true);
}
catch (Exception ex)
{
tcs.SetException(ex);
}
});
return tcs.Task;
}
}
}
| |
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.Util.Shopping.v201809;
using Google.Api.Ads.AdWords.v201809;
using System;
using System.Collections.Generic;
namespace Google.Api.Ads.AdWords.Examples.CSharp.v201809
{
/// <summary>
/// This code example adds a Shopping campaign.
/// </summary>
public class AddShoppingCampaign : ExampleBase
{
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description
{
get { return "This code example adds a Shopping campaign."; }
}
/// <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)
{
AddShoppingCampaign codeExample = new AddShoppingCampaign();
Console.WriteLine(codeExample.Description);
try
{
long budgetId = long.Parse("INSERT_BUDGET_ID_HERE");
long merchantId = long.Parse("INSERT_MERCHANT_ID_HERE");
bool createDefaultPartition = false;
codeExample.Run(new AdWordsUser(), budgetId, merchantId, createDefaultPartition);
}
catch (Exception e)
{
Console.WriteLine("An exception occurred while running this code example. {0}",
ExampleUtilities.FormatException(e));
}
}
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="user">The AdWords user.</param>
/// <param name="budgetId">The budget id.</param>
/// <param name="merchantId">The Merchant Center account ID.</param>
/// <param name="createDefaultPartition">If set to true, a default
/// partition will be created. If running the AddProductPartition.cs
/// example right after this example, make sure this stays set to
/// false.</param>
public void Run(AdWordsUser user, long budgetId, long merchantId,
bool createDefaultPartition)
{
try
{
Campaign campaign = CreateCampaign(user, budgetId, merchantId);
Console.WriteLine("Campaign with name '{0}' and ID '{1}' was added.", campaign.name,
campaign.id);
AdGroup adGroup = CreateAdGroup(user, campaign.id);
Console.WriteLine("Ad group with name '{0}' and ID '{1}' was added.", adGroup.name,
adGroup.id);
AdGroupAd adGroupAd = CreateProductAd(user, adGroup.id);
Console.WriteLine("Product ad with ID {0}' was added.", adGroupAd.ad.id);
if (createDefaultPartition)
{
CreateDefaultPartitionTree(user, adGroup.id);
}
}
catch (Exception e)
{
throw new System.ApplicationException("Failed to create shopping campaign.", e);
}
}
/// <summary>
/// Creates the default partition.
/// </summary>
/// <param name="user">The AdWords user.</param>
/// <param name="adGroupId">The ad group ID.</param>
private void CreateDefaultPartitionTree(AdWordsUser user, long adGroupId)
{
using (AdGroupCriterionService adGroupCriterionService =
(AdGroupCriterionService) user.GetService(AdWordsService.v201809
.AdGroupCriterionService))
{
// Build a new ProductPartitionTree using an empty set of criteria.
ProductPartitionTree partitionTree =
ProductPartitionTree.CreateAdGroupTree(adGroupId, new List<AdGroupCriterion>());
partitionTree.Root.AsBiddableUnit().CpcBid = 1000000;
try
{
// Make the mutate request, using the operations returned by the
// ProductPartitionTree.
AdGroupCriterionOperation[] mutateOperations =
partitionTree.GetMutateOperations();
if (mutateOperations.Length == 0)
{
Console.WriteLine(
"Skipping the mutate call because the original tree and the " +
"current tree are logically identical.");
}
else
{
adGroupCriterionService.mutate(mutateOperations);
}
// The request was successful, so create a new ProductPartitionTree based on
// the updated state of the ad group.
partitionTree = ProductPartitionTree.DownloadAdGroupTree(user, adGroupId);
Console.WriteLine("Final tree: {0}", partitionTree);
}
catch (Exception e)
{
throw new System.ApplicationException(
"Failed to set shopping product partition.", e);
}
}
}
/// <summary>
/// Creates the Product Ad.
/// </summary>
/// <param name="user">The AdWords user.</param>
/// <param name="adGroupId">The ad group ID.</param>
/// <returns>The Product Ad.</returns>
private static AdGroupAd CreateProductAd(AdWordsUser user, long adGroupId)
{
using (AdGroupAdService adGroupAdService =
(AdGroupAdService) user.GetService(AdWordsService.v201809.AdGroupAdService))
{
// Create product ad.
ProductAd productAd = new ProductAd();
// Create ad group ad.
AdGroupAd adGroupAd = new AdGroupAd
{
adGroupId = adGroupId,
ad = productAd
};
// Create operation.
AdGroupAdOperation operation = new AdGroupAdOperation
{
operand = adGroupAd,
@operator = Operator.ADD
};
// Make the mutate request.
AdGroupAdReturnValue retval = adGroupAdService.mutate(new AdGroupAdOperation[]
{
operation
});
return retval.value[0];
}
}
/// <summary>
/// Creates the ad group in a Shopping campaign.
/// </summary>
/// <param name="user">The AdWords user.</param>
/// <param name="campaignId">The campaign ID.</param>
/// <returns>The ad group.</returns>
private static AdGroup CreateAdGroup(AdWordsUser user, long campaignId)
{
using (AdGroupService adGroupService =
(AdGroupService) user.GetService(AdWordsService.v201809.AdGroupService))
{
// Create ad group.
AdGroup adGroup = new AdGroup
{
campaignId = campaignId,
name = "Ad Group #" + ExampleUtilities.GetRandomString()
};
// Create operation.
AdGroupOperation operation = new AdGroupOperation
{
operand = adGroup,
@operator = Operator.ADD
};
// Make the mutate request.
AdGroupReturnValue retval = adGroupService.mutate(new AdGroupOperation[]
{
operation
});
return retval.value[0];
}
}
/// <summary>
/// Creates the shopping campaign.
/// </summary>
/// <param name="user">The AdWords user.</param>
/// <param name="budgetId">The budget id.</param>
/// <param name="merchantId">The Merchant Center id.</param>
/// <returns>The Shopping campaign.</returns>
private static Campaign CreateCampaign(AdWordsUser user, long budgetId, long merchantId)
{
using (CampaignService campaignService =
(CampaignService) user.GetService(AdWordsService.v201809.CampaignService))
{
// Create campaign.
Campaign campaign = new Campaign
{
name = "Shopping campaign #" + ExampleUtilities.GetRandomString(),
// The advertisingChannelType is what makes this a Shopping campaign.
advertisingChannelType = AdvertisingChannelType.SHOPPING,
// Recommendation: Set the campaign to PAUSED when creating it to prevent
// the ads from immediately serving. Set to ENABLED once you've added
// targeting and the ads are ready to serve.
status = CampaignStatus.PAUSED,
// Set shared budget (required).
budget = new Budget
{
budgetId = budgetId
}
};
// Set bidding strategy (required).
BiddingStrategyConfiguration biddingStrategyConfiguration =
new BiddingStrategyConfiguration
{
biddingStrategyType = BiddingStrategyType.MANUAL_CPC
};
campaign.biddingStrategyConfiguration = biddingStrategyConfiguration;
// All Shopping campaigns need a ShoppingSetting.
ShoppingSetting shoppingSetting = new ShoppingSetting
{
salesCountry = "US",
campaignPriority = 0,
merchantId = merchantId,
// Set to "true" to enable Local Inventory Ads in your campaign.
enableLocal = true
};
campaign.settings = new Setting[]
{
shoppingSetting
};
// Create operation.
CampaignOperation campaignOperation = new CampaignOperation
{
operand = campaign,
@operator = Operator.ADD
};
// Make the mutate request.
CampaignReturnValue retval = campaignService.mutate(new CampaignOperation[]
{
campaignOperation
});
return retval.value[0];
}
}
}
}
| |
namespace DeadCode.WME.StringTableMgr
{
partial class SettingsForm
{
/// <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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SettingsForm));
this.TxtProjectFile = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.BtnBrowseProject = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.TxtStringTable = new System.Windows.Forms.TextBox();
this.BtnBrowseTable = new System.Windows.Forms.Button();
this.label3 = new System.Windows.Forms.Label();
this.ProgScan = new System.Windows.Forms.ProgressBar();
this.LblProgress = new System.Windows.Forms.Label();
this.TxtLog = new System.Windows.Forms.TextBox();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.BtnScan = new System.Windows.Forms.Button();
this.BtnManage = new System.Windows.Forms.Button();
this.BtnSave = new System.Windows.Forms.Button();
this.CheckBackup = new System.Windows.Forms.CheckBox();
this.LinkAbout = new System.Windows.Forms.LinkLabel();
this.tableLayoutPanel1.SuspendLayout();
this.SuspendLayout();
//
// TxtProjectFile
//
this.TxtProjectFile.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.TxtProjectFile.Location = new System.Drawing.Point(15, 25);
this.TxtProjectFile.Name = "TxtProjectFile";
this.TxtProjectFile.Size = new System.Drawing.Size(312, 20);
this.TxtProjectFile.TabIndex = 2;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 9);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(59, 13);
this.label1.TabIndex = 0;
this.label1.Text = "&Project file:";
//
// BtnBrowseProject
//
this.BtnBrowseProject.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.BtnBrowseProject.Location = new System.Drawing.Point(333, 23);
this.BtnBrowseProject.Name = "BtnBrowseProject";
this.BtnBrowseProject.Size = new System.Drawing.Size(25, 23);
this.BtnBrowseProject.TabIndex = 3;
this.BtnBrowseProject.Text = "...";
this.BtnBrowseProject.UseVisualStyleBackColor = true;
this.BtnBrowseProject.Click += new System.EventHandler(this.OnBrowseProject);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(12, 48);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(63, 13);
this.label2.TabIndex = 4;
this.label2.Text = "String t&able:";
//
// TxtStringTable
//
this.TxtStringTable.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.TxtStringTable.Location = new System.Drawing.Point(15, 64);
this.TxtStringTable.Name = "TxtStringTable";
this.TxtStringTable.Size = new System.Drawing.Size(312, 20);
this.TxtStringTable.TabIndex = 5;
//
// BtnBrowseTable
//
this.BtnBrowseTable.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.BtnBrowseTable.Location = new System.Drawing.Point(333, 62);
this.BtnBrowseTable.Name = "BtnBrowseTable";
this.BtnBrowseTable.Size = new System.Drawing.Size(25, 23);
this.BtnBrowseTable.TabIndex = 6;
this.BtnBrowseTable.Text = "...";
this.BtnBrowseTable.UseVisualStyleBackColor = true;
this.BtnBrowseTable.Click += new System.EventHandler(this.OnBrowseTable);
//
// label3
//
this.label3.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.label3.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.label3.Location = new System.Drawing.Point(15, 111);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(343, 2);
this.label3.TabIndex = 8;
//
// ProgScan
//
this.ProgScan.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.ProgScan.Location = new System.Drawing.Point(15, 151);
this.ProgScan.Name = "ProgScan";
this.ProgScan.Size = new System.Drawing.Size(343, 23);
this.ProgScan.TabIndex = 10;
//
// LblProgress
//
this.LblProgress.AutoSize = true;
this.LblProgress.Location = new System.Drawing.Point(12, 177);
this.LblProgress.Name = "LblProgress";
this.LblProgress.Size = new System.Drawing.Size(0, 13);
this.LblProgress.TabIndex = 11;
//
// TxtLog
//
this.TxtLog.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.TxtLog.Location = new System.Drawing.Point(12, 193);
this.TxtLog.MaxLength = 0;
this.TxtLog.Multiline = true;
this.TxtLog.Name = "TxtLog";
this.TxtLog.ReadOnly = true;
this.TxtLog.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.TxtLog.Size = new System.Drawing.Size(346, 151);
this.TxtLog.TabIndex = 12;
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tableLayoutPanel1.ColumnCount = 3;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33.33333F));
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33.33333F));
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33.33333F));
this.tableLayoutPanel1.Controls.Add(this.BtnScan, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.BtnManage, 1, 0);
this.tableLayoutPanel1.Controls.Add(this.BtnSave, 2, 0);
this.tableLayoutPanel1.Location = new System.Drawing.Point(15, 116);
this.tableLayoutPanel1.Margin = new System.Windows.Forms.Padding(0);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 1;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel1.Size = new System.Drawing.Size(343, 29);
this.tableLayoutPanel1.TabIndex = 9;
//
// BtnScan
//
this.BtnScan.Dock = System.Windows.Forms.DockStyle.Fill;
this.BtnScan.Location = new System.Drawing.Point(0, 3);
this.BtnScan.Margin = new System.Windows.Forms.Padding(0, 3, 3, 3);
this.BtnScan.Name = "BtnScan";
this.BtnScan.Size = new System.Drawing.Size(111, 23);
this.BtnScan.TabIndex = 0;
this.BtnScan.Text = "S&can project";
this.BtnScan.UseVisualStyleBackColor = true;
this.BtnScan.Click += new System.EventHandler(this.OnScanProject);
//
// BtnManage
//
this.BtnManage.Dock = System.Windows.Forms.DockStyle.Fill;
this.BtnManage.Location = new System.Drawing.Point(117, 3);
this.BtnManage.Name = "BtnManage";
this.BtnManage.Size = new System.Drawing.Size(108, 23);
this.BtnManage.TabIndex = 1;
this.BtnManage.Text = "&Manage strings";
this.BtnManage.UseVisualStyleBackColor = true;
this.BtnManage.Click += new System.EventHandler(this.OnManageStrings);
//
// BtnSave
//
this.BtnSave.Dock = System.Windows.Forms.DockStyle.Fill;
this.BtnSave.Location = new System.Drawing.Point(231, 3);
this.BtnSave.Margin = new System.Windows.Forms.Padding(3, 3, 0, 3);
this.BtnSave.Name = "BtnSave";
this.BtnSave.Size = new System.Drawing.Size(112, 23);
this.BtnSave.TabIndex = 2;
this.BtnSave.Text = "&Save changes";
this.BtnSave.UseVisualStyleBackColor = true;
this.BtnSave.Click += new System.EventHandler(this.OnSaveChanges);
//
// CheckBackup
//
this.CheckBackup.AutoSize = true;
this.CheckBackup.Location = new System.Drawing.Point(15, 90);
this.CheckBackup.Name = "CheckBackup";
this.CheckBackup.Size = new System.Drawing.Size(101, 17);
this.CheckBackup.TabIndex = 7;
this.CheckBackup.Text = "&Backup old files";
this.CheckBackup.UseVisualStyleBackColor = true;
//
// LinkAbout
//
this.LinkAbout.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.LinkAbout.AutoSize = true;
this.LinkAbout.Location = new System.Drawing.Point(314, 7);
this.LinkAbout.Name = "LinkAbout";
this.LinkAbout.Size = new System.Drawing.Size(44, 13);
this.LinkAbout.TabIndex = 1;
this.LinkAbout.TabStop = true;
this.LinkAbout.Text = "About...";
this.LinkAbout.Click += new System.EventHandler(this.OnAbout);
//
// SettingsForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(370, 356);
this.Controls.Add(this.LinkAbout);
this.Controls.Add(this.CheckBackup);
this.Controls.Add(this.tableLayoutPanel1);
this.Controls.Add(this.TxtLog);
this.Controls.Add(this.LblProgress);
this.Controls.Add(this.ProgScan);
this.Controls.Add(this.label3);
this.Controls.Add(this.BtnBrowseTable);
this.Controls.Add(this.TxtStringTable);
this.Controls.Add(this.label2);
this.Controls.Add(this.BtnBrowseProject);
this.Controls.Add(this.label1);
this.Controls.Add(this.TxtProjectFile);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "SettingsForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "WME String Table Manager";
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.OnFormClosed);
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.OnFormClosing);
this.Load += new System.EventHandler(this.OnLoad);
this.tableLayoutPanel1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox TxtProjectFile;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button BtnBrowseProject;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox TxtStringTable;
private System.Windows.Forms.Button BtnBrowseTable;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.ProgressBar ProgScan;
private System.Windows.Forms.Label LblProgress;
private System.Windows.Forms.TextBox TxtLog;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.Button BtnScan;
private System.Windows.Forms.Button BtnManage;
private System.Windows.Forms.Button BtnSave;
private System.Windows.Forms.CheckBox CheckBackup;
private System.Windows.Forms.LinkLabel LinkAbout;
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// This controller is driven by being directly connected to a
/// data group, allowing it to react to the music.
/// </summary>
[AddComponentMenu("Visualizer Studio/Controllers/Frequency Controller")]
public class VisFrequencyController : VisBaseController, IVisDataGroupTarget
{
#region Defaults Static Class
/// <summary>
/// This internal class holds all of the defaults of the VisFrequencyController class.
/// </summary>
public new static class Defaults
{
public const VisDataValueType subValueType = VisDataValueType.Sum;
public const VisDataValueType finalValueType = VisDataValueType.Average;
}
#endregion
#region IVisDataGroupTarget Implementation
/// <summary>
/// This is the data group that this controller is targeting.
/// </summary>
//[HideInInspector()]
[SerializeField()]
private VisDataGroup dataGroup = null;
/// <summary>
/// This is the name of the last data group that was set to this base modifier
/// </summary>
[HideInInspector()]
[SerializeField()]
private string m_szLastDataGroupName = null;
/// <summary>
/// This property gets/sets the target data group for this controller.
/// </summary>
public VisDataGroup DataGroup
{
get { return dataGroup; }
set
{
dataGroup = value;
if (dataGroup != null)
m_szLastDataGroupName = dataGroup.dataGroupName;
else
m_szLastDataGroupName = null;
}
}
/// <summary>
/// This gets the name of the last data group that was set to this target.
/// </summary>
public string LastDataGroupName
{
get { return m_szLastDataGroupName; }
}
#endregion
#region Public Member Variables
/// <summary>
/// This is the value type to pull from all of the sub data
/// groups on the target data group. Such as the Maximum
/// of each sub data group values.
/// </summary>
//[HideInInspector()]
public VisDataValueType subValueType = Defaults.subValueType;
/// <summary>
/// This is the final value type to pull from the result of the
/// sub data groups. Such as, the Average (final value type)
/// of the Maximums (sub value type).
/// </summary>
//[HideInInspector()]
public VisDataValueType finalValueType = Defaults.finalValueType;
#endregion
#region Init/Deinit Functions
/// <summary>
/// This function resets this controller to default values
/// </summary>
public override void Reset()
{
base.Reset();
subValueType = Defaults.subValueType;
finalValueType = Defaults.finalValueType;
}
/// <summary>
/// The main start function.
/// </summary>
public override void Start()
{
base.Start();
if (base.Manager == null)
Debug.LogError("This controller must have a VisManager assigned to it in order to function.");
if (dataGroup == null)
Debug.LogError("This controller must have a VisDataGroup assigned to it in order to function. Please double check the spelling of the target data group.");
}
#endregion
#region VisBaseController Implementation
/// <summary>
/// This function returns the current value for this controller.
/// TO IMPLEMENT A CUSTOM CONTROLLER, override this function
/// to return the current target value.
/// </summary>
/// <returns>
/// The custom controller value.
/// </returns>
public override float GetCustomControllerValue()
{
if (dataGroup != null)
{
return dataGroup.GetValue(finalValueType, subValueType);
}
return base.GetCustomControllerValue();
}
#endregion
#region Debug Functions
/// <summary>
/// This displays the debug information of this controller.
/// </summary>
/// <param name="x">
/// The x location to display this data group.
/// </param>
/// <param name="y">
/// The y location to display this data group.
/// </param>
/// <param name="barWidth">
/// This is the width in pixels of the debug bars.
/// </param>
/// <param name="barHeight">
/// This is the height in pixels of the debug bars.
/// </param>
/// <param name="separation">
/// This is the separation in pixels of the debug bars.
/// </param>
/// <param name="debugTexture">
/// This is the texture used to display the debug information.
/// </param>
/// <returns>
/// This is the rect of the of the debug information that was displayed.
/// </returns>
public override Rect DisplayDebugGUI(int x, int y, int barWidth, int barHeight, int separation, Texture debugTexture)
{
if (debugTexture != null)
{
int labelWidth = 150;
int labelHeight = 20;
int padding = 5;
int frameWidth = Mathf.Max(barWidth, labelWidth) + padding * 2;
int frameHeight = padding * 2 + labelHeight * 5 + barHeight;
Rect frameRect = new Rect(x - padding, y - padding, frameWidth, frameHeight);
GUI.BeginGroup(frameRect);
GUI.color = new Color(0, 0, 0, 0.5f);
GUI.DrawTexture(new Rect(0, 0, frameRect.width, frameRect.height), debugTexture);
GUI.color = Color.white;
GUI.Label(new Rect(padding, padding, labelWidth, labelHeight + 3), "Controller: \"" + controllerName + "\"");
GUI.Label(new Rect(padding, padding + labelHeight, labelWidth, labelHeight + 3), "Data Group: \"" + (dataGroup != null ? dataGroup.dataGroupName : "NONE") + "\"");
GUI.Label(new Rect(padding, padding + labelHeight * 2, labelWidth, labelHeight + 3), "Sub Type: \"" + subValueType + "\"");
GUI.Label(new Rect(padding, padding + labelHeight * 3, labelWidth, labelHeight + 3), "Final Type: \"" + finalValueType + "\"");
GUI.Label(new Rect(padding, padding + labelHeight * 4, labelWidth, labelHeight + 3), "VALUE: " + GetCurrentValue().ToString("F4"));
float perc = ((m_fValue - MinValue) / (MaxValue - MinValue)) * 0.975f + 0.025f;
if (dataGroup != null)
GUI.color = dataGroup.debugColor;
GUI.DrawTexture(new Rect(padding, padding + labelHeight * 5, (int)(((float)barWidth)*perc), barHeight), debugTexture);
GUI.color = Color.white;
GUI.DrawTexture(new Rect(0, 0, frameWidth, 1), debugTexture);
GUI.DrawTexture(new Rect(0, frameHeight - 1, frameWidth, 1), debugTexture);
GUI.DrawTexture(new Rect(0, 0, 1, frameHeight), debugTexture);
GUI.DrawTexture(new Rect(frameWidth - 1, 0, 1, frameHeight), debugTexture);
GUI.EndGroup();
return frameRect;
}
return new Rect(0,0,0,0);
}
#endregion
}
| |
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using System.Collections;
namespace UIWidgets {
/// <summary>
/// SlideBlock axis.
/// </summary>
public enum SlideBlockAxis
{
LeftToRight = 0,
TopToBottom = 1,
RightToLeft = 2,
BottomToTop = 3,
}
/// <summary>
/// SlideBlock.
/// </summary>
[AddComponentMenu("UI/UIWidgets/SlideBlock")]
public class SlideBlock : MonoBehaviour, IBeginDragHandler, IEndDragHandler, IDragHandler {
/// <summary>
/// AnimationCurve.
/// </summary>
[SerializeField]
[Tooltip("Requirements: start value should be less than end value; Recommended start value = 0; end value = 1;")]
public AnimationCurve Curve = AnimationCurve.EaseInOut(0, 0, 1, 1);
/// <summary>
/// Direction.
/// </summary>
public SlideBlockAxis Direction = SlideBlockAxis.LeftToRight;
[SerializeField]
bool isOpen;
/// <summary>
/// Gets or sets a value indicating whether this instance is open.
/// </summary>
/// <value><c>true</c> if this instance is open; otherwise, <c>false</c>.</value>
public bool IsOpen {
get {
return isOpen;
}
set {
isOpen = value;
ResetPosition();
}
}
[SerializeField]
bool scrollRectSupport;
/// <summary>
/// Process children ScrollRect's drag events.
/// </summary>
/// <value><c>true</c> if scroll rect support; otherwise, <c>false</c>.</value>
public bool ScrollRectSupport {
get {
return scrollRectSupport;
}
set {
if (scrollRectSupport)
{
GetComponentsInChildren<ScrollRect>().ForEach(RemoveHandleEvents);
}
scrollRectSupport = value;
if (scrollRectSupport)
{
GetComponentsInChildren<ScrollRect>().ForEach(AddHandleEvents);
}
}
}
[SerializeField]
GameObject optionalHandle;
/// <summary>
/// Gets or sets the optional handle.
/// </summary>
/// <value>The optional handle.</value>
public GameObject OptionalHandle {
get {
return optionalHandle;
}
set {
if (optionalHandle!=null)
{
RemoveHandleEvents(optionalHandle);
}
optionalHandle = value;
if (optionalHandle!=null)
{
AddHandleEvents(optionalHandle);
}
}
}
/// <summary>
/// Use unscaled time.
/// </summary>
[SerializeField]
public bool UnscaledTime = false;
/// <summary>
/// OnOpen event.
/// </summary>
public UnityEvent OnOpen = new UnityEvent();
/// <summary>
/// OnClose event.
/// </summary>
public UnityEvent OnClose = new UnityEvent();
RectTransform rectTransform;
/// <summary>
/// Gets the RectTransform.
/// </summary>
/// <value>RectTransform.</value>
protected RectTransform RectTransform {
get {
if (rectTransform==null)
{
rectTransform = transform as RectTransform;
}
return rectTransform;
}
}
/// <summary>
/// Position on Start().
/// </summary>
Vector2 closePosition;
/// <summary>
/// The current animation.
/// </summary>
IEnumerator currentAnimation;
float size;
string GetWarning()
{
var keys = Curve.keys;
if (keys[0].value >= keys[keys.Length - 1].value)
{
return string.Format("Curve requirements: start value (current: {0}) should be less than end value (current: {1}).", keys[0].value, keys[keys.Length - 1].value);
}
return string.Empty;
}
void Start()
{
var warning = GetWarning();
if (warning!=string.Empty)
{
Debug.LogWarning(warning, this);
}
closePosition = RectTransform.anchoredPosition;
size = (IsHorizontal()) ? RectTransform.rect.width : RectTransform.rect.height;
if (IsOpen)
{
if (SlideBlockAxis.LeftToRight==Direction)
{
closePosition = new Vector2(closePosition.x - size, closePosition.y);
}
if (SlideBlockAxis.RightToLeft==Direction)
{
closePosition = new Vector2(closePosition.x + size, closePosition.y);
}
else if (SlideBlockAxis.TopToBottom==Direction)
{
closePosition = new Vector2(closePosition.x, closePosition.y - size);
}
else if (SlideBlockAxis.BottomToTop==Direction)
{
closePosition = new Vector2(closePosition.x, closePosition.y + size);
}
}
OptionalHandle = optionalHandle;
ScrollRectSupport = scrollRectSupport;
}
void AddScrollRectHandle()
{
GetComponentsInChildren<ScrollRect>().ForEach(AddHandleEvents);
}
void RemoveScrollRectHandle()
{
GetComponentsInChildren<ScrollRect>().ForEach(RemoveHandleEvents);
}
void AddHandleEvents(Component handleComponent)
{
AddHandleEvents(handleComponent.gameObject);
}
void AddHandleEvents(GameObject handleObject)
{
var handle = handleObject.GetComponent<SlideBlockHandle>();
if (handle==null)
{
handle = handleObject.AddComponent<SlideBlockHandle>();
}
handle.BeginDragEvent.AddListener(OnBeginDrag);
handle.DragEvent.AddListener(OnDrag);
handle.EndDragEvent.AddListener(OnEndDrag);
}
void RemoveHandleEvents(Component handleComponent)
{
RemoveHandleEvents(handleComponent.gameObject);
}
void RemoveHandleEvents(GameObject handleObject)
{
var handle = handleObject.GetComponent<SlideBlockHandle>();
if (handle!=null)
{
handle.BeginDragEvent.RemoveListener(OnBeginDrag);
handle.DragEvent.RemoveListener(OnDrag);
handle.EndDragEvent.RemoveListener(OnEndDrag);
}
}
void ResetPosition()
{
if (isOpen)
{
size = (IsHorizontal()) ? RectTransform.rect.width : RectTransform.rect.height;
if (SlideBlockAxis.LeftToRight==Direction)
{
RectTransform.anchoredPosition = new Vector2(closePosition.x + size, RectTransform.anchoredPosition.y);
}
else if (SlideBlockAxis.RightToLeft==Direction)
{
RectTransform.anchoredPosition = new Vector2(closePosition.x - size, RectTransform.anchoredPosition.y);
}
else if (SlideBlockAxis.TopToBottom==Direction)
{
RectTransform.anchoredPosition = new Vector2(RectTransform.anchoredPosition.x, closePosition.y - size);
}
else if (SlideBlockAxis.BottomToTop==Direction)
{
RectTransform.anchoredPosition = new Vector2(RectTransform.anchoredPosition.x, closePosition.y + size);
}
}
else
{
RectTransform.anchoredPosition = closePosition;
}
}
/// <summary>
/// Toggle this instance.
/// </summary>
public void Toggle()
{
if (IsOpen)
{
Close();
}
else
{
Open();
}
}
/// <summary>
/// Called by a BaseInputModule before a drag is started.
/// </summary>
/// <param name="eventData">Event data.</param>
public void OnBeginDrag(PointerEventData eventData)
{
size = (IsHorizontal()) ? RectTransform.rect.width : RectTransform.rect.height;
}
/// <summary>
/// Called by a BaseInputModule when a drag is ended.
/// </summary>
/// <param name="eventData">Event data.</param>
public void OnEndDrag(PointerEventData eventData)
{
var pos = (IsHorizontal())
? RectTransform.anchoredPosition.x - closePosition.x
: RectTransform.anchoredPosition.y - closePosition.y;
if (pos==0f)
{
isOpen = false;
OnClose.Invoke();
return ;
}
var sign = IsReverse() ? -1 : +1;
if (pos==(size * sign))
{
isOpen = true;
OnOpen.Invoke();
return ;
}
var k = pos / (size * sign);
if (k >= 0.5f)
{
isOpen = false;
Open();
}
else
{
isOpen = true;
Close();
}
}
/// <summary>
/// When draging is occuring this will be called every time the cursor is moved.
/// </summary>
/// <param name="eventData">Event data.</param>
public void OnDrag(PointerEventData eventData)
{
if (currentAnimation!=null)
{
StopCoroutine(currentAnimation);
}
Vector2 p1;
RectTransformUtility.ScreenPointToLocalPointInRectangle(RectTransform, eventData.position, eventData.pressEventCamera, out p1);
Vector2 p2;
RectTransformUtility.ScreenPointToLocalPointInRectangle(RectTransform, eventData.position - eventData.delta, eventData.pressEventCamera, out p2);
var delta = p1 - p2;
if (SlideBlockAxis.LeftToRight==Direction)
{
var x = Mathf.Clamp(RectTransform.anchoredPosition.x + delta.x, closePosition.x, closePosition.x + size);
RectTransform.anchoredPosition = new Vector2(x, RectTransform.anchoredPosition.y);
}
else if (SlideBlockAxis.RightToLeft==Direction)
{
var x = Mathf.Clamp(RectTransform.anchoredPosition.x + delta.x, closePosition.x - size, closePosition.x);
RectTransform.anchoredPosition = new Vector2(x, RectTransform.anchoredPosition.y);
}
else if (SlideBlockAxis.TopToBottom==Direction)
{
var y = Mathf.Clamp(RectTransform.anchoredPosition.y + delta.y, closePosition.y - size, closePosition.y);
RectTransform.anchoredPosition = new Vector2(RectTransform.anchoredPosition.x, y);
}
else if (SlideBlockAxis.BottomToTop==Direction)
{
var y = Mathf.Clamp(RectTransform.anchoredPosition.y + delta.y, closePosition.y, closePosition.y + size);
RectTransform.anchoredPosition = new Vector2(RectTransform.anchoredPosition.x, y);
}
}
/// <summary>
/// Open this instance.
/// </summary>
public void Open()
{
if (IsOpen)
{
return ;
}
Animate();
}
/// <summary>
/// Close this instance.
/// </summary>
public void Close()
{
if (!IsOpen)
{
return ;
}
Animate();
}
bool IsHorizontal()
{
return SlideBlockAxis.LeftToRight==Direction || SlideBlockAxis.RightToLeft==Direction;
}
bool IsReverse()
{
return SlideBlockAxis.RightToLeft==Direction || SlideBlockAxis.TopToBottom==Direction;
}
void Animate()
{
if (currentAnimation!=null)
{
StopCoroutine(currentAnimation);
}
var animationLength = Curve.keys[Curve.keys.Length - 1].time;
size = IsHorizontal() ? RectTransform.rect.width : RectTransform.rect.height;
var startPosition = IsHorizontal() ? RectTransform.anchoredPosition.x : RectTransform.anchoredPosition.y;
var pos = startPosition - (IsHorizontal() ? closePosition.x : closePosition.y);
var sign = IsReverse() ? -1 : +1;
var movement = isOpen ? (size*sign) : (size * sign) - pos;
var acceleration = (movement==0f) ? 1f : size / movement;
if (IsReverse())
{
acceleration *= -1;
}
currentAnimation = RunAnimation(animationLength, startPosition, movement, acceleration);
StartCoroutine(currentAnimation);
}
IEnumerator RunAnimation(float animationLength, float startPosition, float movement, float acceleration)
{
float delta;
var direction = isOpen ? -1 : +1;
var startTime = (UnscaledTime ? Time.unscaledTime : Time.time);
do
{
delta = ((UnscaledTime ? Time.unscaledTime : Time.time) - startTime) * acceleration;
var value = Curve.Evaluate(delta);
if (IsHorizontal())
{
RectTransform.anchoredPosition = new Vector2(startPosition + (value * movement * direction), RectTransform.anchoredPosition.y);
}
else
{
RectTransform.anchoredPosition = new Vector2(RectTransform.anchoredPosition.x, startPosition + (value * movement * direction));
}
yield return null;
}
while (delta < animationLength);
isOpen = !isOpen;
ResetPosition();
if (IsOpen)
{
OnOpen.Invoke();
}
else
{
OnClose.Invoke();
}
}
}
}
| |
using System;
using System.Collections.ObjectModel;
using System.Drawing;
using OpenQA.Selenium;
using OpenQA.Selenium.Interactions.Internal;
using OpenQA.Selenium.Internal;
using Tellurium.MvcPages.SeleniumUtils.Exceptions;
using Tellurium.MvcPages.Utils;
namespace Tellurium.MvcPages.SeleniumUtils
{
public class StableWebElement: IStableWebElement
{
private readonly ISearchContext parent;
private IWebElement element;
private readonly By locator;
private readonly SearchApproachType searchApproach;
public StableWebElement(ISearchContext parent, IWebElement element, By locator, SearchApproachType searchApproach)
{
this.parent = parent;
this.element = element;
this.locator = locator;
this.searchApproach = searchApproach;
}
public void RegenerateElement()
{
var stableParent = parent as IStableWebElement;
if (stableParent != null && stableParent.IsStale())
{
stableParent.RegenerateElement();
}
try
{
switch (searchApproach)
{
case SearchApproachType.First:
this.element = this.parent.FindElement(locator);
break;
case SearchApproachType.FirstAccessible:
this.element = this.parent.FindFirstAccessibleElement(locator);
break;
default:
throw new ArgumentOutOfRangeException(nameof(searchApproach));
}
}
catch(Exception ex)
{
throw new CannotFindElementByException(locator, parent, ex);
}
}
public bool IsStale()
{
try
{
//INFO: If element is stale accessing any property should throw exception
// ReSharper disable once UnusedVariable
var tagName =this.element.TagName;
return false;
}
catch (StaleElementReferenceException )
{
return true;
}
}
public string GetDescription()
{
var stableParent = parent as IStableWebElement;
var parentDescription = stableParent != null ? stableParent.GetDescription() : null;
var thisDescription = $"'{this.locator}'";
return parentDescription == null ? thisDescription : $"{thisDescription} inside {parentDescription}";
}
public IWebElement Unwrap()
{
if (IsStale())
{
RegenerateElement();
}
return element;
}
internal T Execute<T>(Func<T> function)
{
T result = default (T);
Execute(() => { result = function(); });
return result;
}
private void Execute(Action action)
{
var success = RetryHelper.Retry(3, () =>
{
try
{
action();
return true;
}
catch (StaleElementReferenceException)
{
RegenerateElement();
return false;
}
});
if (success == false)
{
throw new WebElementNotFoundException("Element is no longer accessible");
}
}
public IWebElement FindElement(By by)
{
return Execute(() => element.FindElement(by));
}
public ReadOnlyCollection<IWebElement> FindElements(By by)
{
return Execute(() => element.FindElements(by));
}
public void Clear()
{
Execute(() => element.Clear());
}
public void SendKeys(string text)
{
Execute(() => element.SendKeys(text));
}
public void Submit()
{
Execute(() => element.Submit());
}
public void Click()
{
Execute(() => element.Click());
}
public string GetAttribute(string attributeName)
{
return Execute(() => element.GetAttribute(attributeName));
}
public string GetProperty(string propertyName)
{
return Execute(() => element.GetProperty(propertyName));
}
public string GetCssValue(string propertyName)
{
return Execute(() => element.GetCssValue(propertyName));
}
public string TagName { get { return Execute(() => element.TagName); } }
public string Text { get { return Execute(() => element.Text); } }
public bool Enabled { get { return Execute(() => element.Enabled); } }
public bool Selected { get { return Execute(() => element.Selected); } }
public Point Location { get { return Execute(() => element.Location); } }
public Size Size { get { return Execute(() => element.Size); } }
public bool Displayed { get { return Execute(() => element.Displayed); } }
public Point LocationOnScreenOnceScrolledIntoView
{
get { return Execute(() => element.As<ILocatable>().LocationOnScreenOnceScrolledIntoView); }
}
public ICoordinates Coordinates
{
get { return Execute(() => element.As<ILocatable>().Coordinates); }
}
public Screenshot GetScreenshot()
{
return Execute(() => element.As<ITakesScreenshot>().GetScreenshot());
}
public IWebElement WrappedElement => Unwrap();
public IWebDriver WrappedDriver
{
get
{
if (element is IWrapsDriver driverWrapper)
{
return driverWrapper.WrappedDriver;
}
throw new NotSupportedException($"Element {this.GetDescription()} does not have information about driver");
}
}
}
public interface IStableWebElement : IWebElement, ILocatable, ITakesScreenshot, IWrapsElement, IWrapsDriver
{
void RegenerateElement();
bool IsStale();
string GetDescription();
}
internal static class GenericHelpers
{
public static TInterface As<TInterface>(this IWebElement element) where TInterface : class
{
var typed = element as TInterface;
if (typed == null)
{
var errorMessage = $"Underlying element does not support this operation. It should implement {typeof(TInterface).FullName} interface";
throw new NotSupportedException(errorMessage);
}
return typed;
}
}
internal static class StableElementExtensions
{
public static IStableWebElement FindStableElement(this ISearchContext context, By by)
{
var element = context.FindElement(by);
return new StableWebElement(context, element, by, SearchApproachType.First);
}
public static IStableWebElement TryFindStableElement(this ISearchContext context, By by)
{
var element = context.TryFindElement(by);
if (element == null)
{
return null;
}
return new StableWebElement(context, element, by, SearchApproachType.First);
}
}
public enum SearchApproachType
{
First,
FirstAccessible
}
}
| |
using System;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.Models;
using Umbraco.Core.Models.EntityBase;
using umbraco.BusinessLogic;
using umbraco.DataLayer;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Linq;
namespace umbraco.cms.businesslogic.media
{
/// <summary>
/// A media represents a physical file and metadata on the file.
///
/// By inheriting the Content class it has a generic datafields which enables custumization
/// </summary>
[Obsolete("Obsolete, Use Umbraco.Core.Models.Media", false)]
public class Media : Content
{
#region Constants and static members
protected internal IMedia MediaItem;
#endregion
#region Constructors
/// <summary>
/// Contructs a media object given the Id
/// </summary>
/// <param name="id">Identifier</param>
public Media(int id) : base(id) { }
/// <summary>
/// Contructs a media object given the Id
/// </summary>
/// <param name="id">Identifier</param>
public Media(Guid id) : base(id) { }
public Media(int id, bool noSetup) : base(id, noSetup) { }
public Media(Guid id, bool noSetup) : base(id, noSetup) { }
internal Media(IUmbracoEntity entity, bool noSetup = true)
: base(entity)
{
if (noSetup == false)
setupNode();
}
internal Media(IMedia media) : base(media)
{
SetupNode(media);
}
#endregion
#region Static Methods
/// <summary>
/// -
/// </summary>
public static Guid _objectType = new Guid(Constants.ObjectTypes.Media);
/// <summary>
/// Creates a new Media
/// </summary>
/// <param name="Name">The name of the media</param>
/// <param name="dct">The type of the media</param>
/// <param name="u">The user creating the media</param>
/// <param name="ParentId">The id of the folder under which the media is created</param>
/// <returns></returns>
[Obsolete("Obsolete, Use Umbraco.Core.Services.MediaService.CreateMedia()", false)]
public static Media MakeNew(string Name, MediaType dct, BusinessLogic.User u, int ParentId)
{
var e = new NewEventArgs();
OnNewing(e);
if (e.Cancel)
{
return null;
}
var media = ApplicationContext.Current.Services.MediaService.CreateMediaWithIdentity(Name, ParentId, dct.Alias, u.Id);
//The media object will only have the 'WasCancelled' flag set to 'True' if the 'Creating' event has been cancelled
if (((Entity)media).WasCancelled)
return null;
var tmp = new Media(media);
tmp.OnNew(e);
return tmp;
}
/// <summary>
/// Retrieve a list of all toplevel medias and folders
/// </summary>
/// <returns></returns>
[Obsolete("Obsolete, Use Umbraco.Core.Services.MediaService.GetRootMedia()", false)]
public static Media[] GetRootMedias()
{
var children = ApplicationContext.Current.Services.MediaService.GetRootMedia();
return children.Select(x => new Media(x)).ToArray();
}
[Obsolete("Obsolete, Use Umbraco.Core.Services.MediaService.GetChildren()", false)]
public static List<Media> GetChildrenForTree(int nodeId)
{
var children = ApplicationContext.Current.Services.MediaService.GetChildren(nodeId);
return children.Select(x => new Media(x)).ToList();
}
[Obsolete("Obsolete, Use Umbraco.Core.Services.MediaService.GetMediaOfMediaType()", false)]
public static IEnumerable<Media> GetMediaOfMediaType(int mediaTypeId)
{
var children = ApplicationContext.Current.Services.MediaService.GetMediaOfMediaType(mediaTypeId);
return children.Select(x => new Media(x)).ToList();
}
/// <summary>
/// Deletes all medias of the given type, used when deleting a mediatype
///
/// Use with care.
/// </summary>
/// <param name="dt"></param>
[Obsolete("Obsolete, Use Umbraco.Core.Services.MediaService.DeleteMediaOfType()", false)]
public static void DeleteFromType(MediaType dt)
{
ApplicationContext.Current.Services.MediaService.DeleteMediaOfType(dt.Id);
}
#endregion
#region Public Properties
public override int sortOrder
{
get
{
return MediaItem == null ? base.sortOrder : MediaItem.SortOrder;
}
set
{
if (MediaItem == null)
{
base.sortOrder = value;
}
else
{
MediaItem.SortOrder = value;
}
}
}
public override int Level
{
get
{
return MediaItem == null ? base.Level : MediaItem.Level;
}
set
{
if (MediaItem == null)
{
base.Level = value;
}
else
{
MediaItem.Level = value;
}
}
}
public override int ParentId
{
get
{
return MediaItem == null ? base.ParentId : MediaItem.ParentId;
}
}
public override string Path
{
get
{
return MediaItem == null ? base.Path : MediaItem.Path;
}
set
{
if (MediaItem == null)
{
base.Path = value;
}
else
{
MediaItem.Path = value;
}
}
}
[Obsolete("Obsolete, Use Name property on Umbraco.Core.Models.Content", false)]
public override string Text
{
get
{
return MediaItem.Name;
}
set
{
value = value.Trim();
MediaItem.Name = value;
}
}
/// <summary>
/// Retrieve a list of all medias underneath the current
/// </summary>
[Obsolete("Obsolete, Use Umbraco.Core.Services.MediaService.GetChildren()", false)]
public new Media[] Children
{
get
{
//return refactored optimized method
//return Media.GetChildrenForTree(this.Id).ToArray();
var children = ApplicationContext.Current.Services.MediaService.GetChildren(Id).OrderBy(c => c.SortOrder);
return children.Select(x => new Media(x)).ToArray();
}
}
#endregion
#region Public methods
public override XmlNode ToXml(XmlDocument xd, bool Deep)
{
if (IsTrashed == false)
{
return base.ToXml(xd, Deep);
}
return null;
}
/// <summary>
/// Overrides the moving of a <see cref="Media"/> object to a new location by changing its parent id.
/// </summary>
public override void Move(int newParentId)
{
MoveEventArgs e = new MoveEventArgs();
base.FireBeforeMove(e);
if (!e.Cancel)
{
var current = User.GetCurrent();
int userId = current == null ? 0 : current.Id;
ApplicationContext.Current.Services.MediaService.Move(MediaItem, newParentId, userId);
}
base.FireAfterMove(e);
}
/// <summary>
/// Used to persist object changes to the database. In Version3.0 it's just a stub for future compatibility
/// </summary>
[Obsolete("Obsolete, Use Umbraco.Core.Services.MediaService.Save()", false)]
public override void Save()
{
var e = new SaveEventArgs();
FireBeforeSave(e);
foreach (var property in GenericProperties)
{
MediaItem.SetValue(property.PropertyType.Alias, property.Value);
}
if (!e.Cancel)
{
var current = User.GetCurrent();
int userId = current == null ? 0 : current.Id;
ApplicationContext.Current.Services.MediaService.Save(MediaItem, userId);
base.VersionDate = MediaItem.UpdateDate;
base.Save();
FireAfterSave(e);
}
}
/// <summary>
/// Moves the media to the trash
/// </summary>
[Obsolete("Obsolete, Use Umbraco.Core.Services.MediaService.MoveToRecycleBin()", false)]
public override void delete()
{
MoveToTrash();
}
/// <summary>
/// With either move the media to the trash or permanently remove it from the database.
/// </summary>
/// <param name="deletePermanently">flag to set whether or not to completely remove it from the database or just send to trash</param>
[Obsolete("Obsolete, Use Umbraco.Core.Services.MediaService.Delete() or Umbraco.Core.Services.MediaService.MoveToRecycleBin()", false)]
public void delete(bool deletePermanently)
{
if (!deletePermanently)
{
MoveToTrash();
}
else
{
DeletePermanently();
}
}
[Obsolete("Obsolete, Use Umbraco.Core.Services.MediaService.GetDescendants()", false)]
public override IEnumerable GetDescendants()
{
var descendants = ApplicationContext.Current.Services.MediaService.GetDescendants(Id);
return descendants.Select(x => new Media(x));
}
#endregion
#region Protected methods
protected override void setupNode()
{
if (Id == -1 || Id == -21)
{
base.setupNode();
return;
}
var media = Version == Guid.Empty
? ApplicationContext.Current.Services.MediaService.GetById(Id)
: ApplicationContext.Current.Services.MediaService.GetByVersion(Version);
if (media == null)
throw new ArgumentException(string.Format("No Media exists with id '{0}'", Id));
SetupNode(media);
}
[Obsolete("Obsolete, This method is no longer used")]
protected void PopulateMediaFromReader(IRecordsReader dr)
{
var hc = dr.GetInt("children") > 0;
SetupMediaForTree(dr.GetGuid("uniqueId")
, dr.GetShort("level")
, dr.GetInt("parentId")
, dr.GetInt("nodeUser")
, dr.GetString("path")
, dr.GetString("text")
, dr.GetDateTime("createDate")
, dr.GetString("icon")
, hc
, dr.GetString("alias")
, dr.GetString("thumbnail")
, dr.GetString("description")
, null
, dr.GetInt("contentTypeId")
, dr.GetBoolean("isContainer"));
}
#endregion
#region Private methods
private void SetupNode(IMedia media)
{
MediaItem = media;
//Also need to set the ContentBase item to this one so all the propery values load from it
ContentBase = MediaItem;
//Setting private properties from IContentBase replacing CMSNode.setupNode() / CMSNode.PopulateCMSNodeFromReader()
base.PopulateCMSNodeFromUmbracoEntity(MediaItem, _objectType);
//If the version is empty we update with the latest version from the current IContent.
if (Version == Guid.Empty)
Version = MediaItem.Version;
}
[Obsolete("Obsolete, This method is no longer needed", false)]
private void SetupMediaForTree(Guid uniqueId, int level, int parentId, int user, string path,
string text, DateTime createDate, string icon, bool hasChildren, string contentTypeAlias, string contentTypeThumb,
string contentTypeDesc, int? masterContentType, int contentTypeId, bool isContainer)
{
SetupNodeForTree(uniqueId, _objectType, level, parentId, user, path, text, createDate, hasChildren);
ContentType = new ContentType(contentTypeId, contentTypeAlias, icon, contentTypeThumb, masterContentType, isContainer);
ContentTypeIcon = icon;
}
/// <summary>
/// Used internally to permanently delete the data from the database
/// </summary>
/// <returns>returns true if deletion isn't cancelled</returns>
[Obsolete("Obsolete, Use Umbraco.Core.Services.MediaService.Delete()", false)]
private bool DeletePermanently()
{
DeleteEventArgs e = new DeleteEventArgs();
FireBeforeDelete(e);
if (!e.Cancel)
{
if (MediaItem != null)
{
ApplicationContext.Current.Services.MediaService.Delete(MediaItem);
}
else
{
var media = ApplicationContext.Current.Services.MediaService.GetById(Id);
ApplicationContext.Current.Services.MediaService.Delete(media);
}
base.delete();
FireAfterDelete(e);
}
return !e.Cancel;
}
/// <summary>
/// Used internally to move the node to the recyle bin
/// </summary>
/// <returns>Returns true if the move was not cancelled</returns>
[Obsolete("Obsolete, Use Umbraco.Core.Services.MediaService.MoveToRecycleBin()", false)]
private bool MoveToTrash()
{
MoveToTrashEventArgs e = new MoveToTrashEventArgs();
FireBeforeMoveToTrash(e);
if (!e.Cancel)
{
if (MediaItem != null)
{
ApplicationContext.Current.Services.MediaService.MoveToRecycleBin(MediaItem);
}
else
{
var media = ApplicationContext.Current.Services.MediaService.GetById(Id);
ApplicationContext.Current.Services.MediaService.MoveToRecycleBin(media);
}
//Move((int)RecycleBin.RecycleBinType.Media);
//TODO: Now that we've moved it to trash, we need to move the actual files so they are no longer accessible
//from the original URL.
FireAfterMoveToTrash(e);
}
return !e.Cancel;
}
#endregion
#region Events
/// <summary>
/// The save event handler
/// </summary>
public delegate void SaveEventHandler(Media sender, SaveEventArgs e);
/// <summary>
/// The new event handler
/// </summary>
public delegate void NewEventHandler(Media sender, NewEventArgs e);
/// <summary>
/// The delete event handler
/// </summary>
public delegate void DeleteEventHandler(Media sender, DeleteEventArgs e);
/// <summary>
/// Occurs when [before save].
/// </summary>
public new static event SaveEventHandler BeforeSave;
/// <summary>
/// Raises the <see cref="E:BeforeSave"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected new virtual void FireBeforeSave(SaveEventArgs e)
{
if (BeforeSave != null)
BeforeSave(this, e);
}
/// <summary>
/// Occurs when [after save].
/// </summary>
public new static event SaveEventHandler AfterSave;
/// <summary>
/// Raises the <see cref="E:AfterSave"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected new virtual void FireAfterSave(SaveEventArgs e)
{
if (AfterSave != null)
AfterSave(this, e);
}
/// <summary>
/// Occurs when [new].
/// </summary>
public static event NewEventHandler New;
/// <summary>
/// Raises the <see cref="E:New"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void OnNew(NewEventArgs e)
{
if (New != null)
New(this, e);
}
public static event EventHandler<NewEventArgs> Newing;
protected static void OnNewing(NewEventArgs e)
{
if (Newing != null)
{
Newing(null, e);
}
}
/// <summary>
/// Occurs when [before delete].
/// </summary>
public new static event DeleteEventHandler BeforeDelete;
/// <summary>
/// Raises the <see cref="E:BeforeDelete"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected new virtual void FireBeforeDelete(DeleteEventArgs e)
{
if (BeforeDelete != null)
BeforeDelete(this, e);
}
/// <summary>
/// Occurs when [after delete].
/// </summary>
public new static event DeleteEventHandler AfterDelete;
/// <summary>
/// Raises the <see cref="E:AfterDelete"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected new virtual void FireAfterDelete(DeleteEventArgs e)
{
if (AfterDelete != null)
AfterDelete(this, e);
}
/// <summary>
/// The Move to trash event handler
/// </summary>
public delegate void MoveToTrashEventHandler(Media sender, MoveToTrashEventArgs e);
/// <summary>
/// Occurs when [before delete].
/// </summary>
public static event MoveToTrashEventHandler BeforeMoveToTrash;
/// <summary>
/// Raises the <see cref="E:BeforeDelete"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void FireBeforeMoveToTrash(MoveToTrashEventArgs e)
{
if (BeforeMoveToTrash != null)
BeforeMoveToTrash(this, e);
}
/// <summary>
/// Occurs when [after move to trash].
/// </summary>
public static event MoveToTrashEventHandler AfterMoveToTrash;
/// <summary>
/// Fires the after move to trash.
/// </summary>
/// <param name="e">The <see cref="umbraco.cms.businesslogic.MoveToTrashEventArgs"/> instance containing the event data.</param>
protected virtual void FireAfterMoveToTrash(MoveToTrashEventArgs e)
{
if (AfterMoveToTrash != null)
AfterMoveToTrash(this, e);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Orleans.Runtime.Scheduler
{
internal class WorkerPool : IDisposable
{
private Semaphore threadLimitingSemaphore;
private readonly HashSet<WorkerPoolThread> pool;
private readonly WorkerPoolThread systemThread;
private readonly OrleansTaskScheduler scheduler;
private readonly object lockable;
private bool running;
private int runningThreadCount;
private int createThreadCount;
private SafeTimer longTurnTimer;
internal readonly int MaxActiveThreads;
internal readonly TimeSpan MaxWorkQueueWait;
internal readonly bool EnableWorkerThreadInjection;
internal bool ShouldInjectWorkerThread { get { return EnableWorkerThreadInjection && runningThreadCount < WorkerPoolThread.MAX_THREAD_COUNT_TO_REPLACE; } }
internal WorkerPool(OrleansTaskScheduler sched, int maxActiveThreads, bool enableWorkerThreadInjection)
{
scheduler = sched;
MaxActiveThreads = maxActiveThreads;
EnableWorkerThreadInjection = enableWorkerThreadInjection;
MaxWorkQueueWait = TimeSpan.FromMilliseconds(50);
if (EnableWorkerThreadInjection)
{
threadLimitingSemaphore = new Semaphore(maxActiveThreads, maxActiveThreads);
}
pool = new HashSet<WorkerPoolThread>();
createThreadCount = 0;
lockable = new object();
for (createThreadCount = 0; createThreadCount < MaxActiveThreads; createThreadCount++)
{
var t = new WorkerPoolThread(this, scheduler, createThreadCount);
pool.Add(t);
}
createThreadCount++;
systemThread = new WorkerPoolThread(this, scheduler, createThreadCount, true);
running = false;
runningThreadCount = 0;
longTurnTimer = null;
}
internal void Start()
{
running = true;
systemThread.Start();
foreach (WorkerPoolThread t in pool)
t.Start();
if (EnableWorkerThreadInjection)
longTurnTimer = new SafeTimer(obj => CheckForLongTurns(), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
}
internal void Stop()
{
running = false;
if (longTurnTimer != null)
{
longTurnTimer.Dispose();
longTurnTimer = null;
}
WorkerPoolThread[] threads;
lock (lockable)
{
threads = pool.ToArray<WorkerPoolThread>();
}
foreach (WorkerPoolThread thread in threads)
thread.Stop();
systemThread.Stop();
}
internal void TakeCpu()
{
// maintain the threadLimitingSemaphore ONLY if thread injection is enabled.
if (EnableWorkerThreadInjection)
threadLimitingSemaphore.WaitOne();
}
internal void PutCpu()
{
if (EnableWorkerThreadInjection)
threadLimitingSemaphore.Release();
}
internal void RecordRunningThread()
{
// maintain the runningThreadCount ONLY if thread injection is enabled.
if (EnableWorkerThreadInjection)
Interlocked.Increment(ref runningThreadCount);
}
internal void RecordIdlingThread()
{
if (EnableWorkerThreadInjection)
Interlocked.Decrement(ref runningThreadCount);
}
internal bool CanExit()
{
lock (lockable)
{
if (running && (pool.Count <= MaxActiveThreads + 2))
return false;
}
return true;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification = "tnew continues to execute after this method call returned")]
internal void RecordLeavingThread(WorkerPoolThread t)
{
bool restart = false;
lock (lockable)
{
pool.Remove(t);
if (running && (pool.Count < MaxActiveThreads + 2))
restart = true;
if (!restart) return;
createThreadCount++;
var tnew = new WorkerPoolThread(this, scheduler, createThreadCount);
tnew.Start();
}
}
internal void CreateNewThread()
{
lock (lockable)
{
createThreadCount++;
var t = new WorkerPoolThread(this, scheduler, createThreadCount);
pool.Add(t);
t.Start();
}
}
public void Dispose()
{
if (threadLimitingSemaphore != null)
{
threadLimitingSemaphore.Dispose();
threadLimitingSemaphore = null;
}
GC.SuppressFinalize(this);
}
private void CheckForLongTurns()
{
List<WorkerPoolThread> currentPool;
lock (lockable)
{
currentPool = pool.ToList();
}
foreach (var thread in currentPool)
thread.CheckForLongTurns();
}
internal bool DoHealthCheck()
{
bool ok = true;
// Note that we want to make sure we run DoHealthCheck on each thread even if one of them fails, so we can't just use &&= because of short-circuiting
lock (lockable)
{
foreach (WorkerPoolThread thread in pool)
if (!thread.DoHealthCheck())
ok = false;
}
if (!systemThread.DoHealthCheck())
ok = false;
return ok;
}
public void DumpStatus(StringBuilder sb)
{
List<WorkerPoolThread> threads;
lock (lockable)
{
sb.AppendFormat("WorkerPool MaxActiveThreads={0} MaxWorkQueueWait={1} {2}", MaxActiveThreads, MaxWorkQueueWait, running ? "" : "STOPPED").AppendLine();
sb.AppendFormat(" PoolSize={0} ActiveThreads={1}", pool.Count + 1, runningThreadCount).AppendLine();
threads = pool.ToList();
}
sb.AppendLine("System Thread:");
systemThread.DumpStatus(sb);
sb.AppendLine("Worker Threads:");
foreach (var workerThread in threads)
workerThread.DumpStatus(sb);
}
}
}
| |
#region License
/* The MIT License
*
* Copyright (c) 2011 Red Badger Consulting
*
* 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
//-------------------------------------------------------------------------------------------------
// <auto-generated>
// Marked as auto-generated so StyleCop will ignore BDD style tests
// </auto-generated>
//-------------------------------------------------------------------------------------------------
#pragma warning disable 169
// ReSharper disable InconsistentNaming
// ReSharper disable UnusedMember.Global
// ReSharper disable UnusedMember.Local
namespace RedBadger.Xpf.Specs.Controls.TextBlockSpecs
{
using Machine.Specifications;
using Moq;
using RedBadger.Xpf.Controls;
using RedBadger.Xpf.Graphics;
using RedBadger.Xpf.Media;
using It = Machine.Specifications.It;
public abstract class a_TextBlock
{
protected static Mock<IDrawingContext> DrawingContext;
protected static Mock<RootElement> RootElement;
protected static Mock<ISpriteFont> SpriteFont;
protected static TextBlock TextBlock;
private Establish context = () =>
{
var renderer = new Mock<IRenderer>();
DrawingContext = new Mock<IDrawingContext>();
renderer.Setup(r => r.GetDrawingContext(Moq.It.IsAny<IElement>())).Returns(DrawingContext.Object);
RootElement = new Mock<RootElement>(new Rect(new Size(100, 100)), renderer.Object) { CallBase = true };
SpriteFont = new Mock<ISpriteFont>();
TextBlock = new TextBlock(SpriteFont.Object);
RootElement.Object.Content = TextBlock;
};
}
public abstract class a_Measured_and_Arranged_TextBlock : a_TextBlock
{
private Establish context = () => RootElement.Object.Update();
}
[Subject(typeof(TextBlock), "Foreground")]
public class when_foreground_is_not_specified : a_TextBlock
{
private Because of = () => RootElement.Object.Update();
private It should_default_to_black =
() =>
DrawingContext.Verify(
drawingContext =>
drawingContext.DrawText(
SpriteFont.Object,
Moq.It.IsAny<string>(),
Moq.It.IsAny<Point>(),
Moq.It.Is<SolidColorBrush>(value => value.Color == Colors.Black)));
}
[Subject(typeof(TextBlock), "Foreground")]
public class when_foreground_is_specified : a_TextBlock
{
private static readonly SolidColorBrush expectedForeground = new SolidColorBrush(Colors.White);
private Because of = () =>
{
TextBlock.Foreground = expectedForeground;
RootElement.Object.Update();
RootElement.Object.Draw();
};
private It should_use_the_color_specified =
() =>
DrawingContext.Verify(
drawingContext =>
drawingContext.DrawText(
SpriteFont.Object, Moq.It.IsAny<string>(), Moq.It.IsAny<Point>(), expectedForeground));
}
[Subject(typeof(TextBlock), "Background")]
public class when_textblock_background_is_not_specified : a_TextBlock
{
private Because of = () =>
{
RootElement.Object.Update();
RootElement.Object.Draw();
};
private It should_not_render_a_background =
() =>
DrawingContext.Verify(
drawingContext => drawingContext.DrawRectangle(Moq.It.IsAny<Rect>(), Moq.It.IsAny<Brush>()),
Times.Never());
}
[Subject(typeof(TextBlock), "Background")]
public class when_textblock_background_is_specified : a_TextBlock
{
private static SolidColorBrush expectedBackground;
private static Thickness margin;
private Establish context = () =>
{
expectedBackground = new SolidColorBrush(Colors.Blue);
TextBlock.Width = 10;
TextBlock.Height = 5;
margin = new Thickness(1, 2, 3, 4);
TextBlock.Margin = margin;
};
private Because of = () =>
{
TextBlock.Background = expectedBackground;
RootElement.Object.Update();
RootElement.Object.Draw();
};
private It should_render_the_background_in_the_right_place = () =>
{
var area = new Rect(0, 0, TextBlock.ActualWidth, TextBlock.ActualHeight);
DrawingContext.Verify(
drawingContext =>
drawingContext.DrawRectangle(Moq.It.Is<Rect>(rect => rect.Equals(area)), Moq.It.IsAny<Brush>()));
};
private It should_render_with_the_specified_background_color =
() =>
DrawingContext.Verify(
drawingContext => drawingContext.DrawRectangle(Moq.It.IsAny<Rect>(), expectedBackground));
}
[Subject(typeof(TextBlock), "Padding")]
public class when_padding_is_specified : a_TextBlock
{
private static readonly Size expectedDesiredSize = new Size(50, 70);
private static readonly Point expectedDrawPosition = new Point(10, 20);
private static readonly Thickness padding = new Thickness(10, 20, 30, 40);
private static readonly Size stringSize = new Size(10, 10);
private Establish context = () =>
{
TextBlock.HorizontalAlignment = HorizontalAlignment.Left;
TextBlock.VerticalAlignment = VerticalAlignment.Top;
SpriteFont.Setup(font => font.MeasureString(Moq.It.IsAny<string>())).Returns(stringSize);
};
private Because of = () =>
{
TextBlock.Padding = padding;
RootElement.Object.Update();
RootElement.Object.Draw();
};
private It should_increase_the_desired_size = () => TextBlock.DesiredSize.ShouldEqual(expectedDesiredSize);
private It should_take_padding_into_account_when_drawing =
() =>
DrawingContext.Verify(
drawingContext =>
drawingContext.DrawText(
SpriteFont.Object, Moq.It.IsAny<string>(), expectedDrawPosition, Moq.It.IsAny<Brush>()));
}
public abstract class a_TextBlock_With_Content : a_TextBlock
{
protected const string Space = " ";
protected const string Word = "word";
protected static readonly Size SentenceSize = new Size(310, 10);
private const string Sentence =
Word + Space + Word + Space + Word + Space + Word + Space + Word + Space + Word + Space + Word;
private Establish context = () =>
{
SpriteFont.Setup(font => font.MeasureString(Sentence)).Returns(SentenceSize);
SpriteFont.Setup(font => font.MeasureString(Word)).Returns(new Size(40, 10));
SpriteFont.Setup(font => font.MeasureString(Space)).Returns(new Size(5, 10));
TextBlock.Text = Sentence;
};
}
[Subject(typeof(TextBlock), "Padding")]
public class when_padding_is_changed : a_Measured_and_Arranged_TextBlock
{
private Because of = () => TextBlock.Padding = new Thickness(10, 20, 30, 40);
private It should_invalidate_arrange = () => TextBlock.IsArrangeValid.ShouldBeFalse();
private It should_invalidate_measure = () => TextBlock.IsMeasureValid.ShouldBeFalse();
}
[Subject(typeof(TextBlock))]
public class when_text_is_changed : a_Measured_and_Arranged_TextBlock
{
private Because of = () => TextBlock.Text = "new value";
private It should_invalidate_arrange = () => TextBlock.IsArrangeValid.ShouldBeFalse();
private It should_invalidate_measure = () => TextBlock.IsMeasureValid.ShouldBeFalse();
}
[Subject(typeof(TextBlock), "Wrapping")]
public class when_text_wrapping_is_changed : a_Measured_and_Arranged_TextBlock
{
private Because of = () => TextBlock.Wrapping = TextWrapping.Wrap;
private It should_invalidate_arrange = () => TextBlock.IsArrangeValid.ShouldBeFalse();
private It should_invalidate_measure = () => TextBlock.IsMeasureValid.ShouldBeFalse();
}
[Subject(typeof(TextBlock), "Wrapping")]
public class when_wrapping_is_not_required : a_TextBlock_With_Content
{
private Because of = () => RootElement.Object.Update();
private It should_not_wrap = () => TextBlock.DesiredSize.Height.ShouldEqual(SentenceSize.Height);
}
[Subject(typeof(TextBlock), "Wrapping")]
public class when_wrapping_is_required : a_TextBlock_With_Content
{
private const string NewLine = "\n";
private const string WrappedSentence =
Word + Space + Word + NewLine + Word + Space + Word + NewLine + Word + Space + Word + NewLine + Word;
private static readonly Size wrappedSentenceSize = new Size(85, 30);
private Establish context =
() => SpriteFont.Setup(font => font.MeasureString(WrappedSentence)).Returns(wrappedSentenceSize);
private Because of = () =>
{
TextBlock.Wrapping = TextWrapping.Wrap;
RootElement.Object.Update();
};
private It should_wrap = () => TextBlock.DesiredSize.Height.ShouldEqual(wrappedSentenceSize.Height);
}
[Subject(typeof(TextBlock), "Wrapping")]
public class when_changing_text : a_TextBlock_With_Content
{
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoadSoftDelete.Business.ERLevel
{
/// <summary>
/// G11Level111111ReChild (editable child object).<br/>
/// This is a generated base class of <see cref="G11Level111111ReChild"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="G10Level11111"/> collection.
/// </remarks>
[Serializable]
public partial class G11Level111111ReChild : BusinessBase<G11Level111111ReChild>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Level_1_1_1_1_1_1_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Level_1_1_1_1_1_1_Child_NameProperty = RegisterProperty<string>(p => p.Level_1_1_1_1_1_1_Child_Name, "Level_1_1_1_1_1_1 Child Name");
/// <summary>
/// Gets or sets the Level_1_1_1_1_1_1 Child Name.
/// </summary>
/// <value>The Level_1_1_1_1_1_1 Child Name.</value>
public string Level_1_1_1_1_1_1_Child_Name
{
get { return GetProperty(Level_1_1_1_1_1_1_Child_NameProperty); }
set { SetProperty(Level_1_1_1_1_1_1_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="G11Level111111ReChild"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="G11Level111111ReChild"/> object.</returns>
internal static G11Level111111ReChild NewG11Level111111ReChild()
{
return DataPortal.CreateChild<G11Level111111ReChild>();
}
/// <summary>
/// Factory method. Loads a <see cref="G11Level111111ReChild"/> object, based on given parameters.
/// </summary>
/// <param name="cQarentID2">The CQarentID2 parameter of the G11Level111111ReChild to fetch.</param>
/// <returns>A reference to the fetched <see cref="G11Level111111ReChild"/> object.</returns>
internal static G11Level111111ReChild GetG11Level111111ReChild(int cQarentID2)
{
return DataPortal.FetchChild<G11Level111111ReChild>(cQarentID2);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="G11Level111111ReChild"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
private G11Level111111ReChild()
{
// Prevent direct creation
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="G11Level111111ReChild"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="G11Level111111ReChild"/> object from the database, based on given criteria.
/// </summary>
/// <param name="cQarentID2">The CQarent ID2.</param>
protected void Child_Fetch(int cQarentID2)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("GetG11Level111111ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@CQarentID2", cQarentID2).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, cQarentID2);
OnFetchPre(args);
Fetch(cmd);
OnFetchPost(args);
}
}
}
private void Fetch(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
if (dr.Read())
{
Fetch(dr);
}
BusinessRules.CheckRules();
}
}
/// <summary>
/// Loads a <see cref="G11Level111111ReChild"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Level_1_1_1_1_1_1_Child_NameProperty, dr.GetString("Level_1_1_1_1_1_1_Child_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="G11Level111111ReChild"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(G10Level11111 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddG11Level111111ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_ID", parent.Level_1_1_1_1_1_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_1_Child_Name", ReadProperty(Level_1_1_1_1_1_1_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
}
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="G11Level111111ReChild"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(G10Level11111 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateG11Level111111ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_ID", parent.Level_1_1_1_1_1_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_1_Child_Name", ReadProperty(Level_1_1_1_1_1_1_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
}
}
/// <summary>
/// Self deletes the <see cref="G11Level111111ReChild"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(G10Level11111 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("DeleteG11Level111111ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_ID", parent.Level_1_1_1_1_1_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
}
#endregion
#region Pseudo Events
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
#region Copyright (c) Roni Schuetz - All Rights Reserved
// * --------------------------------------------------------------------- *
// * Roni Schuetz *
// * Copyright (c) 2008 All Rights reserved *
// * *
// * indeXus.Net Shared Cache high-performance, distributed caching and *
// * replicated caching system, generic in nature, but intended to *
// * speeding up dynamic web and / or win applications by alleviating *
// * database load. *
// * *
// * This Software is written by Roni Schuetz (schuetz AT gmail DOT com) *
// * *
// * This library is free software; you can redistribute it and/or *
// * modify it under the terms of the GNU Lesser General Public License *
// * as published by the Free Software Foundation; either version 2.1 *
// * of the License, or (at your option) any later version. *
// * *
// * This library is distributed in the hope that it will be useful, *
// * but WITHOUT ANY WARRANTY; without even the implied warranty of *
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
// * Lesser General Public License for more details. *
// * *
// * You should have received a copy of the GNU Lesser General Public *
// * License along with this library; if not, write to the Free *
// * Software Foundation, Inc., 59 Temple Place, Suite 330, *
// * Boston, MA 02111-1307 USA *
// * *
// * THIS COPYRIGHT NOTICE MAY NOT BE REMOVED FROM THIS FILE. *
// * --------------------------------------------------------------------- *
#endregion
// *************************************************************************
//
// Name: Listener.cs
//
// Created: 21-01-2007 SharedCache.com, rschuetz
// Modified: 21-01-2007 SharedCache.com, rschuetz : Creation
// Modified: 15-07-2007 SharedCache.com, rschuetz : added Sync log
// Modified: 15-07-2007 SharedCache.com, rschuetz : added on some methods the check if in App.Config Logging is enabled
// Modified: 31-12-2007 SharedCache.com, rschuetz : applied on all Log methods the checked if LoggingEnable == 1
// Modified: 06-01-2008 SharedCache.com, rschuetz : removed checked for LoggingEnable on MemoryFatalException, while systems are using configuration option -1 on the key: CacheAmountOfObject they need to be informed in any case that the cache is full.
// Modified: 06-01-2008 SharedCache.com, rschuetz : introduce to Force Method, this enables log writting in any case even if LoggingEnable = 0;
// Modified: 24-02-2008 SharedCache.com, rschuetz : updated logging part for tracking, instead of using appsetting we use precompiler definition #if TRACE
// *************************************************************************
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Reflection;
using NLog;
namespace MergeSystem.Indexus.WinServiceCommon.Handler
{
/// <summary>
/// LogHandler uses to log information with NLog.
/// </summary>
public class LogHandler
{
private static string LogNameError = "General";
private static string LogNameTraffic = "Traffic";
private static string LogNameTracking = "Tracking";
private static string LogNameSync = "Sync";
private static string LogNameMemory = "Memory";
private static Logger error = LogManager.GetLogger(LogNameError);
private static Logger traffic = LogManager.GetLogger(LogNameTraffic);
private static Logger tracking = LogManager.GetLogger(LogNameTracking);
private static Logger sync = LogManager.GetLogger(LogNameSync);
private static Logger memory = LogManager.GetLogger(LogNameMemory);
#region Sync
/// <summary>
/// Logging Message and Exception around synchronizing data
/// </summary>
/// <param name="msg">The MSG. A <see cref="T:System.String"/> Object.</param>
/// <param name="ex">The ex. A <see cref="T:System.Exception"/> Object.</param>
[System.Diagnostics.DebuggerStepThrough]
public static void SyncDebugException(string msg, Exception ex)
{
{
sync.DebugException(msg, ex);
}
}
/// <summary>
/// Logging Message and Exception around synchronizing data
/// </summary>
/// <param name="msg">The MSG. A <see cref="T:System.String"/> Object.</param>
[System.Diagnostics.DebuggerStepThrough]
public static void SyncDebug(string msg)
{
{
sync.Debug(msg);
}
}
/// <summary>
/// Logging information around synchronizing data
/// </summary>
/// <param name="msg">The MSG. A <see cref="T:System.String"/> Object.</param>
[System.Diagnostics.DebuggerStepThrough]
public static void SyncInfo(string msg)
{
{
sync.Info(msg);
}
}
/// <summary>
/// Logging Fatal Error Message around synchronizing data
/// </summary>
/// <param name="msg">The MSG. A <see cref="T:System.String"/> Object.</param>
[System.Diagnostics.DebuggerStepThrough]
public static void SyncFatal(string msg)
{
{
sync.Fatal(msg);
}
}
/// <summary>
/// Logging Fatal Error Message and Exception around synchronizing data
/// </summary>
/// <param name="msg">The MSG. A <see cref="T:System.String"/> Object.</param>
/// <param name="ex">The ex. A <see cref="T:System.Exception"/> Object.</param>
[System.Diagnostics.DebuggerStepThrough]
public static void SyncFatalException(string msg, Exception ex)
{
{
sync.FatalException(msg, ex);
}
}
#endregion Sync
#region Error Log
/// <summary>
/// Force a message, undepend of the Configuration.
/// </summary>
/// <param name="msg">a <see cref="string"/> message</param>
[System.Diagnostics.DebuggerStepThrough]
public static void Force(string msg)
{
error.Info(msg);
}
/// <summary>
/// Debugs the specified MSG.
/// </summary>
/// <param name="msg">The MSG. A <see cref="T:System.String"/> Object.</param>
/// <param name="ex">The ex. A <see cref="T:System.Exception"/> Object.</param>
[System.Diagnostics.DebuggerStepThrough]
public static void Debug(string msg, Exception ex)
{
{
error.DebugException(System.Environment.MachineName + ": " + msg, ex);
}
}
/// <summary>
/// Debugs the specified MSG.
/// </summary>
/// <param name="msg">The MSG. A <see cref="T:System.String"/> Object.</param>
[System.Diagnostics.DebuggerStepThrough]
public static void Debug(string msg)
{
{
error.Debug(System.Environment.MachineName + ": " + msg);
}
}
/// <summary>
/// Infoes the specified MSG.
/// </summary>
/// <param name="msg">The MSG. A <see cref="T:System.String"/> Object.</param>
/// <param name="ex">The ex. A <see cref="T:System.Exception"/> Object.</param>
[System.Diagnostics.DebuggerStepThrough]
public static void Info(string msg, Exception ex)
{
{
error.InfoException(System.Environment.MachineName + ": " + msg, ex);
}
}
/// <summary>
/// Infoes the specified MSG.
/// </summary>
/// <param name="msg">The MSG. A <see cref="T:System.String"/> Object.</param>
[System.Diagnostics.DebuggerStepThrough]
public static void Info(string msg)
{
{
error.Info(System.Environment.MachineName + ": " + msg);
}
}
/// <summary>
/// Fatals the specified MSG.
/// </summary>
/// <param name="msg">The MSG. A <see cref="T:System.String"/> Object.</param>
/// <param name="ex">The ex. A <see cref="T:System.Exception"/> Object.</param>
[System.Diagnostics.DebuggerStepThrough]
public static void Fatal(string msg, Exception ex)
{
error.FatalException(System.Environment.MachineName + ": " + msg, ex);
}
/// <summary>
/// Fatals the specified MSG.
/// </summary>
/// <param name="msg">The MSG. A <see cref="T:System.String"/> Object.</param>
[System.Diagnostics.DebuggerStepThrough]
public static void Fatal(string msg)
{
error.Fatal(System.Environment.MachineName + ": " + msg);
}
/// <summary>
/// Errors the specified MSG.
/// </summary>
/// <param name="msg">The MSG. A <see cref="T:System.String"/> Object.</param>
/// <param name="ex">The ex. A <see cref="T:System.Exception"/> Object.</param>
[System.Diagnostics.DebuggerStepThrough]
public static void Error(string msg, Exception ex)
{
{
error.ErrorException(System.Environment.MachineName + "; " + msg, ex);
}
}
/// <summary>
/// Errors the specified MSG.
/// </summary>
/// <param name="msg">The MSG. A <see cref="T:System.String"/> Object.</param>
[System.Diagnostics.DebuggerStepThrough]
public static void Error(string msg)
{
{
error.Error(System.Environment.MachineName + ": " + msg);
}
}
/// <summary>
/// Errors the specified ex.
/// </summary>
/// <param name="ex">The ex. A <see cref="T:System.Exception"/> Object.</param>
[System.Diagnostics.DebuggerStepThrough]
public static void Error(Exception ex)
{
{
Error(System.Environment.MachineName, ex);
}
}
#endregion Error Log
#region Traffic
/***************************************************************************************/
/// <summary>
/// Traffic exceptions.
/// </summary>
/// <param name="msg">The MSG.</param>
/// <param name="ex">The ex.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]
[System.Diagnostics.DebuggerStepThrough]
public static void TrafficException(string msg, Exception ex)
{
traffic.LogException(LogLevel.Error, System.Environment.MachineName + ": " + msg.Replace('\n', '0'), ex);
}
/// <summary>
/// Adding Traffic messages to log
/// </summary>
/// <param name="msg">The MSG.</param>
[System.Diagnostics.DebuggerStepThrough]
public static void Traffic(string msg)
{
traffic.Log(LogLevel.Info, System.Environment.MachineName + ": " + msg);
}
#endregion Traffic
#region Tracking
/***************************************************************************************/
/// <summary>
/// Tracking exception and a message.
/// </summary>
/// <param name="msg">The MSG.</param>
/// <param name="ex">The ex.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]
[System.Diagnostics.DebuggerStepThrough]
public static void TrackingException(string msg, Exception ex)
{
#if TRACE
{
tracking.LogException(LogLevel.Error, System.Environment.MachineName + ": " + msg.Replace('\n', '0'), ex);
}
#endif
}
/// <summary>
/// Trackings the specified MSG.
/// </summary>
/// <param name="msg">The MSG.</param>
[System.Diagnostics.DebuggerStepThrough]
public static void Tracking(string msg)
{
#if TRACE
{
tracking.Log(LogLevel.Debug, System.Environment.MachineName + ": " + msg);
}
#endif
}
#endregion Tracking
#region Memory
/// <summary>
/// Logs the Memory fatal message.
/// </summary>
/// <param name="msg">The MSG.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]
[System.Diagnostics.DebuggerStepThrough]
public static void MemoryFatalException(string msg)
{
{
SystemManagement.Cpu.LogCpuData();
SystemManagement.Memory.LogMemoryData();
memory.FatalException(msg, new Exception(msg));
}
}
/// <summary>
/// Logs the Memory fatal exception.
/// </summary>
/// <param name="msg">The MSG.</param>
/// <param name="ex">The ex.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]
[System.Diagnostics.DebuggerStepThrough]
public static void MemoryFatalException(string msg, Exception ex)
{
SystemManagement.Cpu.LogCpuData();
SystemManagement.Memory.LogMemoryData();
memory.FatalException(msg, ex);
}
/// <summary>
/// Memories the debug.
/// </summary>
/// <param name="msg">The MSG.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]
[System.Diagnostics.DebuggerStepThrough]
public static void MemoryDebug(string msg)
{
{
SystemManagement.Cpu.LogCpuData();
SystemManagement.Memory.LogMemoryData();
memory.Debug(msg);
}
}
#endregion Memory
}
}
| |
namespace CNSirindar.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class InitialCreate : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.TblAsignacionesBloques",
c => new
{
AsignacionBloqueId = c.Int(nullable: false, identity: true),
DeportistaId = c.Int(nullable: false),
DeporteId = c.Int(nullable: false),
BloqueId = c.Int(),
FechaAlta = c.DateTime(),
FechaModificacion = c.DateTime(),
EsActivo = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.AsignacionBloqueId)
.ForeignKey("dbo.TblBloques", t => t.BloqueId)
.ForeignKey("dbo.TblDeportes", t => t.DeporteId, cascadeDelete: true)
.ForeignKey("dbo.TblDeportistas", t => t.DeportistaId, cascadeDelete: true)
.Index(t => t.DeportistaId)
.Index(t => t.DeporteId)
.Index(t => t.BloqueId);
CreateTable(
"dbo.TblBloques",
c => new
{
BloqueId = c.Int(nullable: false, identity: true),
Nombre = c.String(nullable: false, maxLength: 100),
KilocaloriasTotales = c.Int(),
FechaAlta = c.DateTime(),
FechaModificacion = c.DateTime(),
EsActivo = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.BloqueId);
CreateTable(
"dbo.TblGrupos",
c => new
{
GrupoId = c.Int(nullable: false, identity: true),
Nombre = c.String(nullable: false),
Porcentaje = c.Int(nullable: false),
Gramos = c.Int(nullable: false),
Kilocalorias = c.Int(nullable: false),
Equivalencias = c.String(nullable: false, maxLength: 500),
BloqueId = c.Int(nullable: false),
GrupoAlimenticioId = c.Int(nullable: false),
FechaAlta = c.DateTime(),
FechaModificacion = c.DateTime(),
EsActivo = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.GrupoId)
.ForeignKey("dbo.TblBloques", t => t.BloqueId, cascadeDelete: true)
.ForeignKey("dbo.TblGruposAlimenticios", t => t.GrupoAlimenticioId, cascadeDelete: true)
.Index(t => t.BloqueId)
.Index(t => t.GrupoAlimenticioId);
CreateTable(
"dbo.TblGruposAlimenticios",
c => new
{
GrupoAlimenticioId = c.Int(nullable: false, identity: true),
Grupo = c.String(nullable: false),
FechaAlta = c.DateTime(),
FechaModificacion = c.DateTime(),
EsActivo = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.GrupoAlimenticioId);
CreateTable(
"dbo.TblDeportes",
c => new
{
DeporteId = c.Int(nullable: false, identity: true),
Nombre = c.String(maxLength: 50),
TipoEnergia = c.Int(nullable: false),
ClasificacionDeporteId = c.Int(nullable: false),
FechaAlta = c.DateTime(),
FechaModificacion = c.DateTime(),
EsActivo = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.DeporteId)
.ForeignKey("dbo.TblClasificacionesDeportes", t => t.ClasificacionDeporteId, cascadeDelete: true)
.Index(t => t.ClasificacionDeporteId);
CreateTable(
"dbo.TblClasificacionesDeportes",
c => new
{
ClasificacionDeporteId = c.Int(nullable: false, identity: true),
Descripcion = c.String(nullable: false, maxLength: 50),
Abreviatura = c.String(nullable: false, maxLength: 5),
FechaAlta = c.DateTime(),
FechaModificacion = c.DateTime(),
EsActivo = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.ClasificacionDeporteId);
CreateTable(
"dbo.TblDeportesDeportistas",
c => new
{
DeporteDeportistaId = c.Int(nullable: false, identity: true),
DeportistaId = c.Int(nullable: false),
DeporteId = c.Int(nullable: false),
IniciaEntrenamiento = c.Time(precision: 7),
FinalizaEntrenamiento = c.Time(precision: 7),
FechaAlta = c.DateTime(),
FechaModificacion = c.DateTime(),
EsActivo = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.DeporteDeportistaId)
.ForeignKey("dbo.TblDeportes", t => t.DeporteId, cascadeDelete: true)
.ForeignKey("dbo.TblDeportistas", t => t.DeportistaId, cascadeDelete: true)
.Index(t => t.DeportistaId)
.Index(t => t.DeporteId);
CreateTable(
"dbo.TblDeportistas",
c => new
{
DeportistaId = c.Int(nullable: false, identity: true),
DependenciaId = c.Int(nullable: false),
Matricula = c.String(nullable: false, maxLength: 10),
Status = c.Int(nullable: false),
FechaRegistro = c.DateTime(),
Nombre = c.String(nullable: false),
Apellidos = c.String(nullable: false),
FechaNacimiento = c.DateTime(storeType: "date"),
Genero = c.Int(nullable: false),
FechaAlta = c.DateTime(),
FechaModificacion = c.DateTime(),
EsActivo = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.DeportistaId)
.ForeignKey("dbo.TblDependencias", t => t.DependenciaId, cascadeDelete: true)
.Index(t => t.DependenciaId);
CreateTable(
"dbo.TblAsistencias",
c => new
{
AsistenciaId = c.Int(nullable: false, identity: true),
HoraAsistencia = c.DateTime(nullable: false),
DeportistaId = c.Int(nullable: false),
HorarioId = c.Int(nullable: false),
FechaAlta = c.DateTime(),
FechaModificacion = c.DateTime(),
EsActivo = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.AsistenciaId)
.ForeignKey("dbo.TblDeportistas", t => t.DeportistaId, cascadeDelete: true)
.ForeignKey("dbo.TblHorarios", t => t.HorarioId, cascadeDelete: true)
.Index(t => t.DeportistaId)
.Index(t => t.HorarioId);
CreateTable(
"dbo.TblHorarios",
c => new
{
HorarioId = c.Int(nullable: false, identity: true),
Nombre = c.Int(nullable: false),
Inicia = c.Time(nullable: false, precision: 7),
Finaliza = c.Time(nullable: false, precision: 7),
FechaAlta = c.DateTime(),
FechaModificacion = c.DateTime(),
EsActivo = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.HorarioId);
CreateTable(
"dbo.TblCantidadComidas",
c => new
{
DeportistaId = c.Int(nullable: false),
Cantidad = c.Int(nullable: false),
FechaAlta = c.DateTime(),
FechaModificacion = c.DateTime(),
EsActivo = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.DeportistaId)
.ForeignKey("dbo.TblDeportistas", t => t.DeportistaId)
.Index(t => t.DeportistaId);
CreateTable(
"dbo.TblDependencias",
c => new
{
DependenciaId = c.Int(nullable: false, identity: true),
Nombre = c.String(nullable: false, maxLength: 50),
Clave = c.String(nullable: false, maxLength: 10),
FechaAlta = c.DateTime(),
FechaModificacion = c.DateTime(),
EsActivo = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.DependenciaId);
CreateTable(
"dbo.TblEntrenadores",
c => new
{
EntrenadorId = c.Int(nullable: false, identity: true),
Nombre = c.String(nullable: false),
Apellidos = c.String(nullable: false),
FechaNacimiento = c.DateTime(storeType: "date"),
Genero = c.Int(nullable: false),
FechaAlta = c.DateTime(),
FechaModificacion = c.DateTime(),
EsActivo = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.EntrenadorId);
CreateTable(
"dbo.EntrenadorDependencias",
c => new
{
Entrenador_EntrenadorId = c.Int(nullable: false),
Dependencia_DependenciaId = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.Entrenador_EntrenadorId, t.Dependencia_DependenciaId })
.ForeignKey("dbo.TblEntrenadores", t => t.Entrenador_EntrenadorId, cascadeDelete: true)
.ForeignKey("dbo.TblDependencias", t => t.Dependencia_DependenciaId, cascadeDelete: true)
.Index(t => t.Entrenador_EntrenadorId)
.Index(t => t.Dependencia_DependenciaId);
CreateTable(
"dbo.EntrenadorDeportes",
c => new
{
Entrenador_EntrenadorId = c.Int(nullable: false),
Deporte_DeporteId = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.Entrenador_EntrenadorId, t.Deporte_DeporteId })
.ForeignKey("dbo.TblEntrenadores", t => t.Entrenador_EntrenadorId, cascadeDelete: true)
.ForeignKey("dbo.TblDeportes", t => t.Deporte_DeporteId, cascadeDelete: true)
.Index(t => t.Entrenador_EntrenadorId)
.Index(t => t.Deporte_DeporteId);
}
public override void Down()
{
DropForeignKey("dbo.TblDeportesDeportistas", "DeportistaId", "dbo.TblDeportistas");
DropForeignKey("dbo.EntrenadorDeportes", "Deporte_DeporteId", "dbo.TblDeportes");
DropForeignKey("dbo.EntrenadorDeportes", "Entrenador_EntrenadorId", "dbo.TblEntrenadores");
DropForeignKey("dbo.EntrenadorDependencias", "Dependencia_DependenciaId", "dbo.TblDependencias");
DropForeignKey("dbo.EntrenadorDependencias", "Entrenador_EntrenadorId", "dbo.TblEntrenadores");
DropForeignKey("dbo.TblDeportistas", "DependenciaId", "dbo.TblDependencias");
DropForeignKey("dbo.TblCantidadComidas", "DeportistaId", "dbo.TblDeportistas");
DropForeignKey("dbo.TblAsistencias", "HorarioId", "dbo.TblHorarios");
DropForeignKey("dbo.TblAsistencias", "DeportistaId", "dbo.TblDeportistas");
DropForeignKey("dbo.TblAsignacionesBloques", "DeportistaId", "dbo.TblDeportistas");
DropForeignKey("dbo.TblDeportesDeportistas", "DeporteId", "dbo.TblDeportes");
DropForeignKey("dbo.TblDeportes", "ClasificacionDeporteId", "dbo.TblClasificacionesDeportes");
DropForeignKey("dbo.TblAsignacionesBloques", "DeporteId", "dbo.TblDeportes");
DropForeignKey("dbo.TblGrupos", "GrupoAlimenticioId", "dbo.TblGruposAlimenticios");
DropForeignKey("dbo.TblGrupos", "BloqueId", "dbo.TblBloques");
DropForeignKey("dbo.TblAsignacionesBloques", "BloqueId", "dbo.TblBloques");
DropIndex("dbo.EntrenadorDeportes", new[] { "Deporte_DeporteId" });
DropIndex("dbo.EntrenadorDeportes", new[] { "Entrenador_EntrenadorId" });
DropIndex("dbo.EntrenadorDependencias", new[] { "Dependencia_DependenciaId" });
DropIndex("dbo.EntrenadorDependencias", new[] { "Entrenador_EntrenadorId" });
DropIndex("dbo.TblCantidadComidas", new[] { "DeportistaId" });
DropIndex("dbo.TblAsistencias", new[] { "HorarioId" });
DropIndex("dbo.TblAsistencias", new[] { "DeportistaId" });
DropIndex("dbo.TblDeportistas", new[] { "DependenciaId" });
DropIndex("dbo.TblDeportesDeportistas", new[] { "DeporteId" });
DropIndex("dbo.TblDeportesDeportistas", new[] { "DeportistaId" });
DropIndex("dbo.TblDeportes", new[] { "ClasificacionDeporteId" });
DropIndex("dbo.TblGrupos", new[] { "GrupoAlimenticioId" });
DropIndex("dbo.TblGrupos", new[] { "BloqueId" });
DropIndex("dbo.TblAsignacionesBloques", new[] { "BloqueId" });
DropIndex("dbo.TblAsignacionesBloques", new[] { "DeporteId" });
DropIndex("dbo.TblAsignacionesBloques", new[] { "DeportistaId" });
DropTable("dbo.EntrenadorDeportes");
DropTable("dbo.EntrenadorDependencias");
DropTable("dbo.TblEntrenadores");
DropTable("dbo.TblDependencias");
DropTable("dbo.TblCantidadComidas");
DropTable("dbo.TblHorarios");
DropTable("dbo.TblAsistencias");
DropTable("dbo.TblDeportistas");
DropTable("dbo.TblDeportesDeportistas");
DropTable("dbo.TblClasificacionesDeportes");
DropTable("dbo.TblDeportes");
DropTable("dbo.TblGruposAlimenticios");
DropTable("dbo.TblGrupos");
DropTable("dbo.TblBloques");
DropTable("dbo.TblAsignacionesBloques");
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
function initializeMeshRoadEditor()
{
echo(" % - Initializing Mesh Road Editor");
exec( "./meshRoadEditor.cs" );
exec( "./meshRoadEditorGui.gui" );
exec( "./meshRoadEditorToolbar.gui");
exec( "./meshRoadEditorGui.cs" );
MeshRoadEditorGui.setVisible( false );
MeshRoadEditorOptionsWindow.setVisible( false );
MeshRoadEditorToolbar.setVisible( false );
MeshRoadEditorTreeWindow.setVisible( false );
EditorGui.add( MeshRoadEditorGui );
EditorGui.add( MeshRoadEditorOptionsWindow );
EditorGui.add( MeshRoadEditorToolbar );
EditorGui.add( MeshRoadEditorTreeWindow );
new ScriptObject( MeshRoadEditorPlugin )
{
superClass = "EditorPlugin";
editorGui = MeshRoadEditorGui;
};
%map = new ActionMap();
%map.bindCmd( keyboard, "backspace", "MeshRoadEditorGui.deleteNode();", "" );
%map.bindCmd( keyboard, "1", "MeshRoadEditorGui.prepSelectionMode();", "" );
%map.bindCmd( keyboard, "2", "ToolsPaletteArray->MeshRoadEditorMoveMode.performClick();", "" );
%map.bindCmd( keyboard, "3", "ToolsPaletteArray->MeshRoadEditorRotateMode.performClick();", "" );
%map.bindCmd( keyboard, "4", "ToolsPaletteArray->MeshRoadEditorScaleMode.performClick();", "" );
%map.bindCmd( keyboard, "5", "ToolsPaletteArray->MeshRoadEditorAddRoadMode.performClick();", "" );
%map.bindCmd( keyboard, "=", "ToolsPaletteArray->MeshRoadEditorInsertPointMode.performClick();", "" );
%map.bindCmd( keyboard, "numpadadd", "ToolsPaletteArray->MeshRoadEditorInsertPointMode.performClick();", "" );
%map.bindCmd( keyboard, "-", "ToolsPaletteArray->MeshRoadEditorRemovePointMode.performClick();", "" );
%map.bindCmd( keyboard, "numpadminus", "ToolsPaletteArray->MeshRoadEditorRemovePointMode.performClick();", "" );
%map.bindCmd( keyboard, "z", "MeshRoadEditorShowSplineBtn.performClick();", "" );
%map.bindCmd( keyboard, "x", "MeshRoadEditorWireframeBtn.performClick();", "" );
%map.bindCmd( keyboard, "v", "MeshRoadEditorShowRoadBtn.performClick();", "" );
MeshRoadEditorPlugin.map = %map;
MeshRoadEditorPlugin.initSettings();
}
function destroyMeshRoadEditor()
{
}
function MeshRoadEditorPlugin::onWorldEditorStartup( %this )
{
// Add ourselves to the window menu.
%accel = EditorGui.addToEditorsMenu( "Mesh Road Editor", "", MeshRoadEditorPlugin );
// Add ourselves to the ToolsToolbar
%tooltip = "Mesh Road Editor (" @ %accel @ ")";
EditorGui.addToToolsToolbar( "MeshRoadEditorPlugin", "MeshRoadEditorPalette", expandFilename("tools/worldEditor/images/toolbar/mesh-road-editor"), %tooltip );
//connect editor windows
GuiWindowCtrl::attach( MeshRoadEditorOptionsWindow, MeshRoadEditorTreeWindow);
// Add ourselves to the Editor Settings window
exec( "./meshRoadEditorSettingsTab.gui" );
ESettingsWindow.addTabPage( EMeshRoadEditorSettingsPage );
}
function MeshRoadEditorPlugin::onActivated( %this )
{
%this.readSettings();
ToolsPaletteArray->MeshRoadEditorAddRoadMode.performClick();
EditorGui.bringToFront( MeshRoadEditorGui );
MeshRoadEditorGui.setVisible( true );
MeshRoadEditorGui.makeFirstResponder( true );
MeshRoadEditorOptionsWindow.setVisible( true );
MeshRoadEditorToolbar.setVisible( true );
MeshRoadEditorTreeWindow.setVisible( true );
MeshRoadTreeView.open(ServerMeshRoadSet,true);
%this.map.push();
// Store this on a dynamic field
// in order to restore whatever setting
// the user had before.
%this.prevGizmoAlignment = GlobalGizmoProfile.alignment;
// The DecalEditor always uses Object alignment.
GlobalGizmoProfile.alignment = "Object";
// Set the status bar here until all tool have been hooked up
EditorGuiStatusBar.setInfo("Mesh road editor.");
EditorGuiStatusBar.setSelection("");
Parent::onActivated(%this);
}
function MeshRoadEditorPlugin::onDeactivated( %this )
{
%this.writeSettings();
MeshRoadEditorGui.setVisible( false );
MeshRoadEditorOptionsWindow.setVisible( false );
MeshRoadEditorToolbar.setVisible( false );
MeshRoadEditorTreeWindow.setVisible( false );
%this.map.pop();
// Restore the previous Gizmo
// alignment settings.
GlobalGizmoProfile.alignment = %this.prevGizmoAlignment;
Parent::onDeactivated(%this);
}
function MeshRoadEditorPlugin::onEditMenuSelect( %this, %editMenu )
{
%hasSelection = false;
if( isObject( MeshRoadEditorGui.road ) )
%hasSelection = true;
%editMenu.enableItem( 3, false ); // Cut
%editMenu.enableItem( 4, false ); // Copy
%editMenu.enableItem( 5, false ); // Paste
%editMenu.enableItem( 6, %hasSelection ); // Delete
%editMenu.enableItem( 8, false ); // Deselect
}
function MeshRoadEditorPlugin::handleDelete( %this )
{
MeshRoadEditorGui.deleteNode();
}
function MeshRoadEditorPlugin::handleEscape( %this )
{
return MeshRoadEditorGui.onEscapePressed();
}
function MeshRoadEditorPlugin::isDirty( %this )
{
return MeshRoadEditorGui.isDirty;
}
function MeshRoadEditorPlugin::onSaveMission( %this, %missionFile )
{
if( MeshRoadEditorGui.isDirty )
{
MissionGroup.save( %missionFile );
MeshRoadEditorGui.isDirty = false;
}
}
//-----------------------------------------------------------------------------
// Settings
//-----------------------------------------------------------------------------
function MeshRoadEditorPlugin::initSettings( %this )
{
EditorSettings.beginGroup( "MeshRoadEditor", true );
EditorSettings.setDefaultValue( "DefaultWidth", "10" );
EditorSettings.setDefaultValue( "DefaultDepth", "5" );
EditorSettings.setDefaultValue( "DefaultNormal", "0 0 1" );
EditorSettings.setDefaultValue( "HoverSplineColor", "255 0 0 255" );
EditorSettings.setDefaultValue( "SelectedSplineColor", "0 255 0 255" );
EditorSettings.setDefaultValue( "HoverNodeColor", "255 255 255 255" ); //<-- Not currently used
EditorSettings.setDefaultValue( "TopMaterialName", "DefaultRoadMaterialTop" );
EditorSettings.setDefaultValue( "BottomMaterialName", "DefaultRoadMaterialOther" );
EditorSettings.setDefaultValue( "SideMaterialName", "DefaultRoadMaterialOther" );
EditorSettings.endGroup();
}
function MeshRoadEditorPlugin::readSettings( %this )
{
EditorSettings.beginGroup( "MeshRoadEditor", true );
MeshRoadEditorGui.DefaultWidth = EditorSettings.value("DefaultWidth");
MeshRoadEditorGui.DefaultDepth = EditorSettings.value("DefaultDepth");
MeshRoadEditorGui.DefaultNormal = EditorSettings.value("DefaultNormal");
MeshRoadEditorGui.HoverSplineColor = EditorSettings.value("HoverSplineColor");
MeshRoadEditorGui.SelectedSplineColor = EditorSettings.value("SelectedSplineColor");
MeshRoadEditorGui.HoverNodeColor = EditorSettings.value("HoverNodeColor");
MeshRoadEditorGui.topMaterialName = EditorSettings.value("TopMaterialName");
MeshRoadEditorGui.bottomMaterialName = EditorSettings.value("BottomMaterialName");
MeshRoadEditorGui.sideMaterialName = EditorSettings.value("SideMaterialName");
EditorSettings.endGroup();
}
function MeshRoadEditorPlugin::writeSettings( %this )
{
EditorSettings.beginGroup( "MeshRoadEditor", true );
EditorSettings.setValue( "DefaultWidth", MeshRoadEditorGui.DefaultWidth );
EditorSettings.setValue( "DefaultDepth", MeshRoadEditorGui.DefaultDepth );
EditorSettings.setValue( "DefaultNormal", MeshRoadEditorGui.DefaultNormal );
EditorSettings.setValue( "HoverSplineColor", MeshRoadEditorGui.HoverSplineColor );
EditorSettings.setValue( "SelectedSplineColor", MeshRoadEditorGui.SelectedSplineColor );
EditorSettings.setValue( "HoverNodeColor", MeshRoadEditorGui.HoverNodeColor );
EditorSettings.setValue( "TopMaterialName", MeshRoadEditorGui.topMaterialName );
EditorSettings.setValue( "BottomMaterialName", MeshRoadEditorGui.bottomMaterialName );
EditorSettings.setValue( "SideMaterialName", MeshRoadEditorGui.sideMaterialName );
EditorSettings.endGroup();
}
| |
// 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 0.14.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Compute
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
public static partial class VirtualMachinesOperationsExtensions
{
/// <summary>
/// Captures the VM by copying virtual hard disks of the VM and outputs a
/// template that can be used to create similar VMs.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Capture Virtual Machine operation.
/// </param>
public static VirtualMachineCaptureResult Capture(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachineCaptureParameters parameters)
{
return Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).CaptureAsync(resourceGroupName, vmName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Captures the VM by copying virtual hard disks of the VM and outputs a
/// template that can be used to create similar VMs.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Capture Virtual Machine operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualMachineCaptureResult> CaptureAsync( this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachineCaptureParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
var _result = await operations.CaptureWithHttpMessagesAsync(resourceGroupName, vmName, parameters, null, cancellationToken).ConfigureAwait(false);
return _result.Body;
}
/// <summary>
/// Captures the VM by copying virtual hard disks of the VM and outputs a
/// template that can be used to create similar VMs.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Capture Virtual Machine operation.
/// </param>
public static VirtualMachineCaptureResult BeginCapture(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachineCaptureParameters parameters)
{
return Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).BeginCaptureAsync(resourceGroupName, vmName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Captures the VM by copying virtual hard disks of the VM and outputs a
/// template that can be used to create similar VMs.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Capture Virtual Machine operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualMachineCaptureResult> BeginCaptureAsync( this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachineCaptureParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
var _result = await operations.BeginCaptureWithHttpMessagesAsync(resourceGroupName, vmName, parameters, null, cancellationToken).ConfigureAwait(false);
return _result.Body;
}
/// <summary>
/// The operation to create or update a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Create Virtual Machine operation.
/// </param>
public static VirtualMachine CreateOrUpdate(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachine parameters)
{
return Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).CreateOrUpdateAsync(resourceGroupName, vmName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to create or update a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Create Virtual Machine operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualMachine> CreateOrUpdateAsync( this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachine parameters, CancellationToken cancellationToken = default(CancellationToken))
{
var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, vmName, parameters, null, cancellationToken).ConfigureAwait(false);
return _result.Body;
}
/// <summary>
/// The operation to create or update a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Create Virtual Machine operation.
/// </param>
public static VirtualMachine BeginCreateOrUpdate(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachine parameters)
{
return Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, vmName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to create or update a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Create Virtual Machine operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualMachine> BeginCreateOrUpdateAsync( this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachine parameters, CancellationToken cancellationToken = default(CancellationToken))
{
var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, vmName, parameters, null, cancellationToken).ConfigureAwait(false);
return _result.Body;
}
/// <summary>
/// The operation to delete a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void Delete(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).DeleteAsync(resourceGroupName, vmName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to delete a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync( this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to delete a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void BeginDelete(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).BeginDeleteAsync(resourceGroupName, vmName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to delete a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync( this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to get a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='expand'>
/// The expand expression to apply on the operation. Possible values for this
/// parameter include: 'instanceView'
/// </param>
public static VirtualMachine Get(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, InstanceViewTypes? expand = default(InstanceViewTypes?))
{
return Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).GetAsync(resourceGroupName, vmName, expand), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to get a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='expand'>
/// The expand expression to apply on the operation. Possible values for this
/// parameter include: 'instanceView'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualMachine> GetAsync( this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, InstanceViewTypes? expand = default(InstanceViewTypes?), CancellationToken cancellationToken = default(CancellationToken))
{
var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, vmName, expand, null, cancellationToken).ConfigureAwait(false);
return _result.Body;
}
/// <summary>
/// Shuts down the Virtual Machine and releases the compute resources. You are
/// not billed for the compute resources that this Virtual Machine uses.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void Deallocate(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).DeallocateAsync(resourceGroupName, vmName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Shuts down the Virtual Machine and releases the compute resources. You are
/// not billed for the compute resources that this Virtual Machine uses.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeallocateAsync( this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeallocateWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Shuts down the Virtual Machine and releases the compute resources. You are
/// not billed for the compute resources that this Virtual Machine uses.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void BeginDeallocate(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).BeginDeallocateAsync(resourceGroupName, vmName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Shuts down the Virtual Machine and releases the compute resources. You are
/// not billed for the compute resources that this Virtual Machine uses.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeallocateAsync( this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginDeallocateWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Sets the state of the VM as Generalized.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void Generalize(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).GeneralizeAsync(resourceGroupName, vmName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Sets the state of the VM as Generalized.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GeneralizeAsync( this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GeneralizeWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to list virtual machines under a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
public static IPage<VirtualMachine> List(this IVirtualMachinesOperations operations, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).ListAsync(resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to list virtual machines under a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<VirtualMachine>> ListAsync( this IVirtualMachinesOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false);
return _result.Body;
}
/// <summary>
/// Gets the list of Virtual Machines in the subscription. Use nextLink
/// property in the response to get the next page of Virtual Machines. Do
/// this till nextLink is not null to fetch all the Virtual Machines.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<VirtualMachine> ListAll(this IVirtualMachinesOperations operations)
{
return Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).ListAllAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the list of Virtual Machines in the subscription. Use nextLink
/// property in the response to get the next page of Virtual Machines. Do
/// this till nextLink is not null to fetch all the Virtual Machines.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<VirtualMachine>> ListAllAsync( this IVirtualMachinesOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return _result.Body;
}
/// <summary>
/// Lists all available virtual machine sizes it can be resized to for a
/// virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static IPage<VirtualMachineSize> ListAvailableSizes(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
return Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).ListAvailableSizesAsync(resourceGroupName, vmName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all available virtual machine sizes it can be resized to for a
/// virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<VirtualMachineSize>> ListAvailableSizesAsync( this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
var _result = await operations.ListAvailableSizesWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false);
return _result.Body;
}
/// <summary>
/// The operation to power off (stop) a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void PowerOff(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).PowerOffAsync(resourceGroupName, vmName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to power off (stop) a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PowerOffAsync( this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PowerOffWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to power off (stop) a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void BeginPowerOff(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).BeginPowerOffAsync(resourceGroupName, vmName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to power off (stop) a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginPowerOffAsync( this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginPowerOffWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to restart a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void Restart(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).RestartAsync(resourceGroupName, vmName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to restart a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task RestartAsync( this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.RestartWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to restart a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void BeginRestart(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).BeginRestartAsync(resourceGroupName, vmName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to restart a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginRestartAsync( this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginRestartWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to start a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void Start(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).StartAsync(resourceGroupName, vmName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to start a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task StartAsync( this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.StartWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to start a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void BeginStart(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).BeginStartAsync(resourceGroupName, vmName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to start a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginStartAsync( this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginStartWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to redeploy a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void Redeploy(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).RedeployAsync(resourceGroupName, vmName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to redeploy a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task RedeployAsync( this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.RedeployWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to redeploy a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void BeginRedeploy(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).BeginRedeployAsync(resourceGroupName, vmName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to redeploy a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginRedeployAsync( this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginRedeployWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to list virtual machines under a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<VirtualMachine> ListNext(this IVirtualMachinesOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to list virtual machines under a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<VirtualMachine>> ListNextAsync( this IVirtualMachinesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false);
return _result.Body;
}
/// <summary>
/// Gets the list of Virtual Machines in the subscription. Use nextLink
/// property in the response to get the next page of Virtual Machines. Do
/// this till nextLink is not null to fetch all the Virtual Machines.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<VirtualMachine> ListAllNext(this IVirtualMachinesOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).ListAllNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the list of Virtual Machines in the subscription. Use nextLink
/// property in the response to get the next page of Virtual Machines. Do
/// this till nextLink is not null to fetch all the Virtual Machines.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<VirtualMachine>> ListAllNextAsync( this IVirtualMachinesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false);
return _result.Body;
}
/// <summary>
/// Lists all available virtual machine sizes it can be resized to for a
/// virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<VirtualMachineSize> ListAvailableSizesNext(this IVirtualMachinesOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).ListAvailableSizesNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all available virtual machine sizes it can be resized to for a
/// virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<VirtualMachineSize>> ListAvailableSizesNextAsync( this IVirtualMachinesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
var _result = await operations.ListAvailableSizesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false);
return _result.Body;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace CodeGen
{
public static class OutputEffectType
{
const string stdInfinity = "std::numeric_limits<float>::infinity()";
public static void OutputEnum(Effects.Property enumProperty, Formatter output)
{
OutputVersionConditional(enumProperty.WinVer, output);
output.WriteLine("[version(VERSION)]");
output.WriteLine("typedef enum " + enumProperty.TypeNameIdl);
output.WriteLine("{");
output.Indent();
for (int i = 0; i < enumProperty.EnumFields.FieldsList.Count; ++i)
{
var enumValue = enumProperty.EnumFields.FieldsList[i];
if (i != (enumProperty.EnumFields.FieldsList.Count - 1))
{
output.WriteLine(enumValue.Name + " = " + i.ToString() + ",");
}
else
{
output.WriteLine(enumValue.Name + " = " + i.ToString());
}
}
output.Unindent();
output.WriteLine("} " + enumProperty.TypeNameIdl + ";");
EndVersionConditional(enumProperty.WinVer, output);
}
public static void OutputCommonEnums(List<Effects.Effect> effects, Formatter output)
{
OutputDataTypes.OutputLeadingComment(output);
output.WriteLine("namespace Microsoft.Graphics.Canvas.Effects");
output.WriteLine("{");
output.Indent();
bool isFirstOutput = true;
foreach (var effect in effects)
{
foreach (var property in effect.Properties)
{
// Check if property represent enum that is common to some group of effects
if (property.Type == "enum" && property.EnumFields.IsRepresentative && property.ShouldProject)
{
var registeredEffects = effects.Where(EffectGenerator.IsEffectEnabled);
// Check if any registred property need this enum
if (registeredEffects.Any(e => e.Properties.Any(p => p.TypeNameIdl == property.TypeNameIdl)))
{
if (isFirstOutput)
{
isFirstOutput = false;
}
else
{
output.WriteLine();
}
OutputEnum(property, output);
}
}
}
}
output.Unindent();
output.WriteLine("}");
}
public static void OutputEffectIdl(Effects.Effect effect, Formatter output)
{
OutputDataTypes.OutputLeadingComment(output);
OutputVersionConditional(effect, output);
output.WriteLine("namespace Microsoft.Graphics.Canvas.Effects");
output.WriteLine("{");
output.Indent();
// Output all enums specific to this effect
foreach (var property in effect.Properties)
{
if (property.Type == "enum" &&
property.EnumFields.Usage == Effects.EnumValues.UsageType.UsedByOneEffect &&
property.ShouldProject)
{
OutputEnum(property, output);
output.WriteLine();
}
}
output.WriteLine("runtimeclass " + effect.ClassName + ";");
output.WriteLine();
output.WriteLine("[version(VERSION), uuid(" + effect.Uuid + "), exclusiveto(" + effect.ClassName + ")]");
output.WriteLine("interface " + effect.InterfaceName + " : IInspectable");
output.WriteIndent();
output.WriteLine("requires Microsoft.Graphics.Canvas.ICanvasImage");
output.WriteLine("{");
output.Indent();
foreach (var property in effect.Properties)
{
// Property with type string describes
// name/author/category/description of effect but not input type
if (property.Type == "string" || property.IsHidden)
continue;
output.WriteLine("[propget]");
if (property.IsArray)
{
output.WriteLine("HRESULT " + property.Name + "([out] UINT32* valueCount, [out, size_is(, *valueCount), retval] " + property.TypeNameIdl + "** valueElements);");
}
else
{
output.WriteLine("HRESULT " + property.Name + "([out, retval] " + property.TypeNameIdl + "* value);");
}
output.WriteLine();
output.WriteLine("[propput]");
if (property.IsArray)
{
output.WriteLine("HRESULT " + property.Name + "([in] UINT32 valueCount, [in, size_is(valueCount)] " + property.TypeNameIdl + "* valueElements);");
}
else
{
output.WriteLine("HRESULT " + property.Name + "([in] " + property.TypeNameIdl + " value);");
}
output.WriteLine();
}
if (EffectHasVariableNumberOfInputs(effect))
{
output.WriteLine("[propget]");
output.WriteLine("HRESULT Sources([out, retval] Windows.Foundation.Collections.IVector<IGRAPHICSEFFECTSOURCE*>** value);");
output.WriteLine();
}
else
{
for (int i = 0; i < effect.Inputs.InputsList.Count; ++i)
{
var input = effect.Inputs.InputsList[i];
output.WriteLine("[propget]");
output.WriteLine("HRESULT " + input.Name + "([out, retval] IGRAPHICSEFFECTSOURCE** source);");
output.WriteLine();
output.WriteLine("[propput]");
output.WriteLine("HRESULT " + input.Name + "([in] IGRAPHICSEFFECTSOURCE* source);");
output.WriteLine();
}
}
output.Unindent();
output.WriteLine("};");
output.WriteLine();
output.WriteLine("[version(VERSION), activatable(VERSION)]");
output.WriteLine("runtimeclass " + effect.ClassName);
output.WriteLine("{");
output.Indent();
output.WriteLine("[default] interface " + effect.InterfaceName + ";");
output.WriteLine("interface IGRAPHICSEFFECT;");
output.Unindent();
output.WriteLine("}");
output.Unindent();
output.WriteLine("}");
EndVersionConditional(effect, output);
}
public static void OutputEffectHeader(Effects.Effect effect, Formatter output)
{
OutputDataTypes.OutputLeadingComment(output);
output.WriteLine("#pragma once");
output.WriteLine();
OutputVersionConditional(effect, output);
output.WriteLine("namespace ABI { namespace Microsoft { namespace Graphics { namespace Canvas { namespace Effects ");
output.WriteLine("{");
output.Indent();
output.WriteLine("using namespace ::Microsoft::WRL;");
output.WriteLine("using namespace ABI::Microsoft::Graphics::Canvas;");
output.WriteLine();
output.WriteLine("class " + effect.ClassName + " : public RuntimeClass<");
output.Indent();
output.WriteLine(effect.InterfaceName + ",");
output.WriteLine("MixIn<" + effect.ClassName + ", CanvasEffect>>,");
output.WriteLine("public CanvasEffect");
output.Unindent();
output.WriteLine("{");
output.Indent();
output.WriteLine("InspectableClass(RuntimeClass_Microsoft_Graphics_Canvas_Effects_" + effect.ClassName + ", BaseTrust);");
output.WriteLine();
output.Unindent();
output.WriteLine("public:");
output.Indent();
output.WriteLine(effect.ClassName + "();");
output.WriteLine();
foreach (var property in effect.Properties)
{
// Property with type string describes
// name/author/category/description of effect but not input type
if (property.Type == "string" || property.IsHidden)
continue;
var propertyMacro = property.IsArray ? "EFFECT_ARRAY_PROPERTY" : "EFFECT_PROPERTY";
output.WriteLine(propertyMacro + "(" + property.Name + ", " + property.TypeNameCpp + ");");
}
if (EffectHasVariableNumberOfInputs(effect))
{
output.WriteLine("EFFECT_SOURCES_PROPERTY();");
}
else
{
for (int i = 0; i < effect.Inputs.InputsList.Count; ++i)
{
var input = effect.Inputs.InputsList[i];
output.WriteLine("EFFECT_PROPERTY(" + input.Name + ", IGraphicsEffectSource*);");
}
}
bool hasPropertyMapping = effect.Properties.Any(IsGeneratablePropertyMapping);
bool hasHandCodedPropertyMapping = effect.Properties.Any(p => p.IsHandCoded);
if (hasPropertyMapping || hasHandCodedPropertyMapping)
{
output.WriteLine();
if (hasPropertyMapping)
output.WriteLine("EFFECT_PROPERTY_MAPPING();");
if (hasHandCodedPropertyMapping)
output.WriteLine("EFFECT_PROPERTY_MAPPING_HANDCODED();");
}
output.Unindent();
output.WriteLine("};");
output.Unindent();
output.WriteLine("}}}}}");
EndVersionConditional(effect, output);
}
public static void OutputEffectCpp(Effects.Effect effect, Formatter output)
{
OutputDataTypes.OutputLeadingComment(output);
bool isInputSizeFixed = !EffectHasVariableNumberOfInputs(effect);
int inputsCount = isInputSizeFixed ? effect.Inputs.InputsList.Count : 0;
output.WriteLine("#include \"pch.h\"");
output.WriteLine("#include \"" + effect.ClassName + ".h\"");
output.WriteLine();
OutputVersionConditional(effect, output);
output.WriteLine("namespace ABI { namespace Microsoft { namespace Graphics { namespace Canvas { namespace Effects");
output.WriteLine("{");
output.Indent();
output.WriteLine(effect.ClassName + "::" + effect.ClassName + "()");
output.WriteIndent();
output.WriteLine(": CanvasEffect("
+ GetEffectCLSID(effect) + ", "
+ (effect.Properties.Count(p => !p.IsHandCoded) - 4) + ", "
+ inputsCount + ", "
+ isInputSizeFixed.ToString().ToLower() + ")");
output.WriteLine("{");
output.Indent();
output.WriteLine("// Set default values");
foreach (var property in effect.Properties)
{
WritePropertyInitialization(output, property);
}
output.Unindent();
output.WriteLine("}");
output.WriteLine();
foreach (var property in effect.Properties)
{
WritePropertyImplementation(effect, output, property);
}
if (EffectHasVariableNumberOfInputs(effect))
{
output.WriteLine("IMPLEMENT_EFFECT_SOURCES_PROPERTY(" + effect.ClassName + ")");
output.WriteLine();
}
else
{
for (int i = 0; i < effect.Inputs.InputsList.Count; ++i)
{
var input = effect.Inputs.InputsList[i];
output.WriteLine("IMPLEMENT_EFFECT_SOURCE_PROPERTY(" + effect.ClassName + ",");
output.Indent();
output.WriteLine(input.Name + ",");
output.WriteLine(i.ToString() + ")");
output.Unindent();
output.WriteLine();
}
}
WritePropertyMapping(effect, output);
output.WriteLine("ActivatableClass(" + effect.ClassName + ");");
output.Unindent();
output.WriteLine("}}}}}");
EndVersionConditional(effect, output);
}
private static string GetEffectCLSID(Effects.Effect effect)
{
if (effect.Overrides != null && !string.IsNullOrEmpty(effect.Overrides.CLSIDOverride))
{
return effect.Overrides.CLSIDOverride;
}
else
{
return "CLSID_D2D1" + EffectGenerator.FormatClassName(effect.Properties[0].Value);
}
}
private static void WritePropertyInitialization(Formatter output, Effects.Property property)
{
// Property with type string describes
// name/author/category/description of effect but not input type
if (property.Type == "string" || property.IsHandCoded)
return;
string defaultValue = property.Properties.Find(internalProperty => internalProperty.Name == "Default").Value;
string setFunction = property.IsArray ? "SetArrayProperty" : "SetBoxedProperty";
output.WriteLine(setFunction + "<" + property.TypeNameBoxed + ">(" + property.NativePropertyName + ", " + FormatPropertyValue(property, defaultValue) + ");");
}
private static void WritePropertyImplementation(Effects.Effect effect, Formatter output, Effects.Property property)
{
// Property with type string describes
// name/author/category/description of effect but not input type
if (property.Type == "string" || property.IsHandCoded || property.IsHidden)
return;
var min = property.Properties.Find(internalProperty => internalProperty.Name == "Min");
var max = property.Properties.Find(internalProperty => internalProperty.Name == "Max");
bool isWithUnsupported = (property.ExcludedEnumIndexes != null) && (property.ExcludedEnumIndexes.Count != 0);
string customConversion = null;
if (property.ConvertRadiansToDegrees)
{
customConversion = "ConvertRadiansToDegrees";
}
else if (property.Name == "AlphaMode")
{
customConversion = "ConvertAlphaMode";
}
bool isValidation = ((min != null) || (max != null) || isWithUnsupported) && (customConversion == null);
string implementMacro = property.IsArray ? "IMPLEMENT_EFFECT_ARRAY_PROPERTY" : "IMPLEMENT_EFFECT_PROPERTY";
if (isValidation)
{
implementMacro += "_WITH_VALIDATION";
}
output.WriteLine(implementMacro + "(" + effect.ClassName + ",");
output.Indent();
output.WriteLine(property.Name + ",");
output.WriteLine((customConversion ?? property.TypeNameBoxed) + ",");
if (!property.IsArray)
{
output.WriteLine(property.TypeNameCpp + ",");
}
if (isValidation)
{
output.WriteLine(property.NativePropertyName + ",");
var validationChecks = new List<string>();
if (min != null)
{
AddValidationChecks(validationChecks, property, min.Value, ">=");
}
if (max != null)
{
AddValidationChecks(validationChecks, property, max.Value, "<=");
}
if (isWithUnsupported)
{
foreach (var index in property.ExcludedEnumIndexes)
{
validationChecks.Add("value != static_cast<" + property.TypeNameCpp + ">(" + index + ")");
}
}
output.WriteLine("(" + string.Join(") && (", validationChecks) + "))");
}
else
{
output.WriteLine(property.NativePropertyName + ")");
}
output.Unindent();
output.WriteLine();
}
static void AddValidationChecks(List<string> validationChecks, Effects.Property property, string minOrMax, string comparisonOperator)
{
if (property.Type.StartsWith("vector"))
{
// Expand out a separate "value.X >= limit" check for each component of the vector.
int componentIndex = 0;
foreach (var componentMinOrMax in SplitVectorValue(minOrMax))
{
var componentName = "XYZW"[componentIndex++];
validationChecks.Add("value." + componentName + " " + comparisonOperator + " " + componentMinOrMax);
}
}
else
{
// Simple "value >= limit" check.
validationChecks.Add("value " + comparisonOperator + " " + FormatPropertyValue(property, minOrMax));
}
}
static string FormatPropertyValue(Effects.Property property, string value)
{
if (property.Type == "enum")
{
if (property.EnumFields.D2DEnum != null)
{
bool valueFound = false;
foreach (EnumValue v in property.EnumFields.D2DEnum.Values)
{
if (v.ValueExpression == value)
{
value = v.NativeName;
valueFound = true;
break;
}
}
System.Diagnostics.Debug.Assert(valueFound);
}
else if (property.IsHidden)
{
value = property.NativePropertyName.Replace("PROP_", "") + "_" + property.EnumFields.FieldsList[Int32.Parse(value)].Name.ToUpper();
}
else
{
value = property.TypeNameCpp + "::" + property.EnumFields.FieldsList[Int32.Parse(value)].Name;
}
}
else if (property.Type.StartsWith("matrix") || property.Type.StartsWith("vector"))
{
var values = SplitVectorValue(value);
if (property.TypeNameCpp == "Color")
{
values = ConvertVectorToColor(values);
}
else if (property.TypeNameCpp == "Rect")
{
values = ConvertVectorToRect(values);
}
value = property.TypeNameCpp + "{ " + string.Join(", ", values) + " }";
}
else if (property.Type == "float")
{
if (!value.Contains('.'))
{
value += ".0";
}
value += "f";
}
else if (property.Type == "bool")
{
value = "static_cast<boolean>(" + value + ")";
}
else if (property.IsArray)
{
value = "{ " + value + " }";
}
return value;
}
static IEnumerable<string> SplitVectorValue(string value)
{
// Convert "( 1.0, 2.0, 3 )" to "1.0f", "2.0f", "3"
return value.TrimStart('(')
.TrimEnd(')')
.Replace(" ", "")
.Replace("inf", stdInfinity)
.Split(',')
.Select(v => v.Contains('.') ? v + 'f' : v);
}
static IEnumerable<string> ConvertVectorToColor(IEnumerable<string> values)
{
// Convert 0-1 range to 0-255.
var colorValues = from value in values
select StringToFloat(value) * 255;
// Add an alpha component if the input was a 3-component vector.
if (colorValues.Count() < 4)
{
colorValues = colorValues.Concat(new float[] { 255 });
}
// Rearrange RGBA to ARGB.
var rgb = colorValues.Take(3);
var a = colorValues.Skip(3);
return from value in a.Concat(rgb)
select value.ToString();
}
static string FloatToString(float value)
{
if(float.IsInfinity(value))
{
return (value < 0 ? "-" : "") + stdInfinity;
}
else
{
return value.ToString();
}
}
static IEnumerable<string> ConvertVectorToRect(IEnumerable<string> values)
{
// This is in left/top/right/bottom format.
var rectValues = values.Select(StringToFloat).ToArray();
// Convert to x/y/w/h.
rectValues[2] -= rectValues[0];
rectValues[3] -= rectValues[1];
return from value in rectValues
select FloatToString(value);
}
static float StringToFloat(string value)
{
if (value == stdInfinity)
{
return float.PositiveInfinity;
}
else if (value == "-" + stdInfinity)
{
return float.NegativeInfinity;
}
else
{
return float.Parse(value.Replace("f", ""));
}
}
private static void WritePropertyMapping(Effects.Effect effect, Formatter output)
{
var query = from property in effect.Properties
where IsGeneratablePropertyMapping(property)
select new
{
Name = property.Name,
Index = property.NativePropertyName,
Mapping = GetPropertyMapping(property)
};
var properties = query.ToList();
if (properties.Any())
{
output.WriteLine("IMPLEMENT_EFFECT_PROPERTY_MAPPING(" + effect.ClassName + ",");
output.Indent();
int maxNameLength = properties.Select(property => property.Name.Length).Max();
int maxIndexLength = properties.Select(property => property.Index.Length).Max();
int maxMappingLength = properties.Select(property => property.Mapping.Length).Max();
foreach (var property in properties)
{
string nameAlignment = new string(' ', maxNameLength - property.Name.Length);
string indexAlignment = new string(' ', maxIndexLength - property.Index.Length);
string mappingAlignment = new string(' ', maxMappingLength - property.Mapping.Length);
string suffix = property.Equals(properties.Last()) ? ")" : ",";
output.WriteLine("{ L\"" + property.Name + "\", " + nameAlignment +
property.Index + ", " + indexAlignment +
property.Mapping + mappingAlignment + " }" + suffix);
}
output.Unindent();
output.WriteLine();
}
}
private static string GetPropertyMapping(Effects.Property property)
{
if (property.ConvertRadiansToDegrees)
{
return "GRAPHICS_EFFECT_PROPERTY_MAPPING_RADIANS_TO_DEGREES";
}
else if (property.Name == "AlphaMode")
{
return "GRAPHICS_EFFECT_PROPERTY_MAPPING_COLORMATRIX_ALPHA_MODE";
}
else if (property.TypeNameCpp == "Color")
{
return "GRAPHICS_EFFECT_PROPERTY_MAPPING_COLOR_TO_VECTOR" + property.Type.Single(char.IsDigit);
}
else if (property.TypeNameCpp == "Rect")
{
return "GRAPHICS_EFFECT_PROPERTY_MAPPING_RECT_TO_VECTOR4";
}
else
{
return "GRAPHICS_EFFECT_PROPERTY_MAPPING_DIRECT";
}
}
private static bool IsGeneratablePropertyMapping(Effects.Property property)
{
return property.Type != "string" && !property.IsHidden && !property.IsHandCoded;
}
static bool EffectHasVariableNumberOfInputs(Effects.Effect effect)
{
return effect.Inputs.Maximum == "0xFFFFFFFF";
}
private static void OutputVersionConditional(Effects.Effect effect, Formatter output)
{
if (effect.Overrides != null)
{
OutputVersionConditional(effect.Overrides.WinVer, output);
}
}
private static void EndVersionConditional(Effects.Effect effect, Formatter output)
{
if (effect.Overrides != null)
{
EndVersionConditional(effect.Overrides.WinVer, output);
}
}
private static void OutputVersionConditional(string winVer, Formatter output)
{
if (!string.IsNullOrEmpty(winVer))
{
output.WriteLine(string.Format("#if (defined {0}) && (WINVER >= {0})", winVer));
output.WriteLine();
}
}
private static void EndVersionConditional(string winVer, Formatter output)
{
if (!string.IsNullOrEmpty(winVer))
{
output.WriteLine();
output.WriteLine(string.Format("#endif // {0}", winVer));
}
}
}
}
| |
using UnityEngine;
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using ForieroEngine.MIDIUnified;
using ForieroEngine.MIDIUnified.Midi;
using System.Text.RegularExpressions;
public partial class MidiSeqKaraokeScript : MonoBehaviour, IMidiEvents
{
public class Bar
{
public float time;
public float ticks;
public float timeDuration;
public float ticksDuration;
public int timeSignatureNumerator;
public int timeSignatureDenominator;
public int majorMinor;
public int sharpsFlats;
public float tempo;
public int[] eventPos;
public bool[] endOfTrack;
}
public List<Bar> bars = new List<Bar> ();
void UpdateBars ()
{
for (int i = 0; i < tracks.Count; i++) {
while (tracks [i] [eventPos [i]].AbsoluteTime <= ticks) {
if (endOfTrack [i])
break;
midiEvent = tracks [i] [eventPos [i]];
switch (midiEvent.CommandCode) {
case MidiCommandCode.MetaEvent:
metaEvent = (midiEvent as MetaEvent);
switch (metaEvent.MetaEventType) {
case MetaEventType.KeySignature:
keyMajorMinor = (metaEvent as KeySignatureEvent).MajorMinor;
Debug.Log ("MAJOR or MINOR: " + keyMajorMinor);
keySharpsFlats = (metaEvent as KeySignatureEvent).SharpsFlats;
Debug.Log ("SIGNATURE : " + keySharpsFlats);
break;
case MetaEventType.SequenceTrackName:
Debug.Log ("TrackName : " + (metaEvent as TextEvent).Text);
break;
case MetaEventType.SetTempo:
TempoEvent tempoEvent = (midiEvent as TempoEvent);
tempoOriginal = (float)tempoEvent.Tempo;
if (!tempoCustom)
tempo = tempoOriginal;
break;
case MetaEventType.SmpteOffset:
break;
case MetaEventType.TextEvent:
break;
case MetaEventType.TimeSignature:
TimeSignatureEvent signatureEvent = (midiEvent as TimeSignatureEvent);
timeSignatureNumerator = signatureEvent.Numerator;
_timeSignatureDenominator = signatureEvent.Denominator;
timeSignatureDenominator = (int)Mathf.Pow (2, _timeSignatureDenominator);
break;
case MetaEventType.EndTrack:
break;
}
break;
}
if (eventPos [i] >= tracks [i].Count - 1) {
endOfTrack [i] = true;
bool endOfFile = true;
for (int k = 0; k < tracks.Count; k++) {
if (!endOfTrack [k]) {
endOfFile = false;
break;
}
}
if (endOfFile) {
state = State.Finished;
ticks = ticks - lastDeltaTicks;
totalTime = time - lastDeltaTime;
Bar lastBar = bars.Last ();
lastBar.timeDuration = time - lastBar.time;
lastBar.ticksDuration = ticks - lastBar.ticks;
return;
}
break;
}
eventPos [i] = eventPos [i] == tracks [i].Count - 1 ? eventPos [i] : eventPos [i] + 1;
}
}
if (beatCount != (int)(ticks / PPQN / (4f / timeSignatureDenominator)) + 1) {
beat = beatCount % (int)timeSignatureNumerator + 1;
beatCount = (int)(ticks / PPQN / (4f / timeSignatureDenominator)) + 1;
if (beat == 1) {
Bar bar = new Bar () {
time = this.time,
ticks = this.ticks,
tempo = this.tempo,
timeSignatureNumerator = this.timeSignatureNumerator,
timeSignatureDenominator = this.timeSignatureDenominator,
majorMinor = this.keyMajorMinor,
sharpsFlats = this.keySharpsFlats
};
if (bars.Count > 0) {
Bar lastBar = bars.Last ();
lastBar.timeDuration = time - lastDeltaTime - lastBar.time;
lastBar.ticksDuration = ticks - lastDeltaTicks - lastBar.ticks;
}
bar.eventPos = new int[eventPos.Length];
bar.endOfTrack = new bool[endOfTrack.Length];
for (int i = 0; i < bar.eventPos.Length; i++) {
bar.eventPos [i] = GetTrackEventPosFromAbsoluteTicks (i, ticks - 100);
bar.endOfTrack [i] = endOfTrack [i];
}
bars.Add (bar);
}
}
deltaTime = deltaTimeResolution;
periodResolution = PPQN * 1000f * deltaTime * MicrosecondsPerMillisecond;
//ticksPerClock = PPQN / PPQNMinValue;
deltaTicks = (fractionalTicks + periodResolution) / tempoTicks;
fractionalTicks += periodResolution - deltaTicks * tempoTicks;
ticks += deltaTicks;
time += deltaTime;
lastTime = time;
lastDeltaTime = deltaTime;
lastDeltaTicks = deltaTicks;
}
public void SetBar (int aBarNr, bool play, bool pickUpBar = true)
{
if (midiFile != null) {
Debug.Log (state.ToString ());
State stateSetBar = state;
audioMusic.Pause ();
audioVocals.Pause ();
CancelPickUpBarCounting ();
state = State.None;
ResetSequencer ();
// if(midiOut){
// MidiOut.AllPedalsOff();
// MidiOut.AllSoundOff();
// }
if (aBarNr <= 0) {
time = lastTime = 0;
ticks = 0;
if (audioMusic.clip)
audioMusic.time = 0;
if (audioVocals.clip)
audioVocals.time = 0;
if (stateSetBar == State.Playing) {
Play (pickUpBar);
} else {
if (play) {
Play (pickUpBar);
} else {
Pause ();
}
}
} else {
bar = aBarNr;
time = lastTime = bars [aBarNr].time;
ticks = bars [aBarNr].ticks;
if (audioMusic.clip)
audioMusic.time = time;
if (audioVocals.clip)
audioVocals.time = time;
for (int i = 0; i < bars [aBarNr].eventPos.Length; i++) {
eventPos [i] = bars [aBarNr].eventPos [i];
endOfTrack [i] = bars [aBarNr].endOfTrack [i];
}
for (int i = 0; i < words.Count; i++) {
if (words [i].absoluteStartTime >= ticks) {
wordPos = wordOffsetPos = i - 1;
break;
}
}
for (int i = 0; i < sentences.Count; i++) {
if (sentences [i].absoluteStartTime >= ticks) {
sentencePos = i - 1;
break;
}
}
for (int i = 0; i < verses.Count; i++) {
if (verses [i].absoluteStartTime >= ticks) {
versePos = i - 1;
break;
}
}
if (stateSetBar == State.Playing) {
Play (pickUpBar);
} else {
if (play) {
Play (pickUpBar);
} else {
Pause ();
}
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using ErrorCode = Interop.NCrypt.ErrorCode;
namespace Microsoft.Win32.SafeHandles
{
/// <summary>
/// Base class for NCrypt handles which need to support being pseudo-duplicated. This class is not for
/// external use (instead applications should consume the concrete subclasses of this class).
/// </summary>
/// <remarks>
/// Since NCrypt handles do not have a native DuplicateHandle type call, we need to do manual
/// reference counting in managed code whenever we hand out an extra reference to one of these handles.
/// This class wraps up the logic to correctly duplicate and free these handles to simulate a native
/// duplication.
///
/// Each open handle object can be thought of as being in one of three states:
/// 1. Owner - created via the marshaler, traditional style safe handle. Notably, only one owner
/// handle exists for a given native handle.
/// 2. Duplicate - points at a handle in the Holder state. Releasing a handle in the duplicate state
/// results only in decrementing the reference count of the holder, not in a release
/// of the native handle.
/// 3. Holder - holds onto a native handle and is referenced by handles in the duplicate state.
/// When all duplicate handles are closed, the holder handle releases the native
/// handle. A holder handle will never be finalized, since this results in a race
/// between the finalizers of the duplicate handles and the holder handle. Instead,
/// it relies upon all of the duplicate handles to be finalized and decrement the
/// ref count to zero. Instances of a holder handle should never be referenced by
/// anything but a duplicate handle.
/// </remarks>
public abstract class SafeNCryptHandle : SafeHandle
{
private enum OwnershipState
{
/// <summary>
/// The safe handle owns the native handle outright. This must be value 0, as this is the
/// state the marshaler will place the handle in when marshaling back a SafeHandle
/// </summary>
Owner = 0,
/// <summary>
/// The safe handle does not own the native handle, but points to a Holder which does
/// </summary>
Duplicate,
/// <summary>
/// The safe handle owns the native handle, but shares it with other Duplicate handles
/// </summary>
Holder
}
private OwnershipState _ownershipState;
/// <summary>
/// If the handle is a Duplicate, this points at the safe handle which actually owns the native handle.
/// </summary>
private SafeNCryptHandle _holder;
protected SafeNCryptHandle() : base(IntPtr.Zero, true)
{
return;
}
/// <summary>
/// Wrapper for the _holder field which ensures that we're in a consistent state
/// </summary>
private SafeNCryptHandle Holder
{
get
{
Debug.Assert((_ownershipState == OwnershipState.Duplicate && _holder != null) ||
(_ownershipState != OwnershipState.Duplicate && _holder == null));
Debug.Assert(_holder == null || _holder._ownershipState == OwnershipState.Holder);
return _holder;
}
set
{
#if DEBUG
Debug.Assert(value.IsValidOpenState);
#endif
Debug.Assert(_ownershipState != OwnershipState.Duplicate);
Debug.Assert(value._ownershipState == OwnershipState.Holder);
_holder = value;
_ownershipState = OwnershipState.Duplicate;
}
}
#if DEBUG
/// <summary>
/// Ensure the state of the handle is consistent for an open handle
/// </summary>
private bool IsValidOpenState
{
get
{
switch (_ownershipState)
{
// Owner handles do not have a holder
case OwnershipState.Owner:
return Holder == null && !IsInvalid && !IsClosed;
// Duplicate handles have valid open holders with the same raw handle value
case OwnershipState.Duplicate:
bool acquiredHolder = false;
try
{
IntPtr holderRawHandle = IntPtr.Zero;
if (Holder != null)
{
Holder.DangerousAddRef(ref acquiredHolder);
holderRawHandle = Holder.DangerousGetHandle();
}
bool holderValid = Holder != null &&
!Holder.IsInvalid &&
!Holder.IsClosed &&
holderRawHandle != IntPtr.Zero &&
holderRawHandle == handle;
return holderValid && !IsInvalid && !IsClosed;
}
finally
{
if (acquiredHolder)
{
Holder.DangerousRelease();
}
}
// Holder handles do not have a holder
case OwnershipState.Holder:
return Holder == null && !IsInvalid && !IsClosed;
// Unknown ownership state
default:
return false;
}
}
}
#endif
/// <summary>
/// Duplicate a handle
/// </summary>
/// <remarks>
/// #NCryptHandleDuplicationAlgorithm
///
/// Duplicating a handle performs different operations depending upon the state of the handle:
///
/// * Owner - Allocate two new handles, a holder and a duplicate.
/// - Suppress finalization on the holder
/// - Transition into the duplicate state
/// - Use the new holder as the holder for both this handle and the duplicate
/// - Increment the reference count on the holder
///
/// * Duplicate - Allocate a duplicate handle
/// - Increment the reference count of our holder
/// - Assign the duplicate's holder to be our holder
///
/// * Holder - Specifically disallowed. Holders should only ever be referenced by duplicates,
/// so duplication will occur on the duplicate rather than the holder handle.
/// </remarks>
internal T Duplicate<T>() where T : SafeNCryptHandle, new()
{
#if DEBUG
Debug.Assert(IsValidOpenState);
#endif
Debug.Assert(_ownershipState != OwnershipState.Holder);
Debug.Assert(typeof(T) == this.GetType());
if (_ownershipState == OwnershipState.Owner)
{
return DuplicateOwnerHandle<T>();
}
else
{
// If we're not an owner handle, and we're being duplicated then we must be a duplicate handle.
return DuplicateDuplicatedHandle<T>();
}
}
/// <summary>
/// Duplicate a safe handle which is already duplicated.
///
/// See code:Microsoft.Win32.SafeHandles.SafeNCryptHandle#NCryptHandleDuplicationAlgorithm for
/// details about the algorithm.
/// </summary>
private T DuplicateDuplicatedHandle<T>() where T : SafeNCryptHandle, new()
{
#if DEBUG
Debug.Assert(IsValidOpenState);
#endif
Debug.Assert(_ownershipState == OwnershipState.Duplicate);
Debug.Assert(typeof(T) == this.GetType());
bool addedRef = false;
T duplicate = new T();
// We need to do this operation in a CER, since we need to make sure that if the AddRef occurs
// that the duplicated handle will always point back to the Holder, otherwise the Holder will leak
// since it will never have its ref count reduced to zero.
try { }
finally
{
Holder.DangerousAddRef(ref addedRef);
duplicate.SetHandle(Holder.DangerousGetHandle());
duplicate.Holder = Holder; // Transitions to OwnershipState.Duplicate
}
return duplicate;
}
/// <summary>
/// Duplicate a safe handle which is currently the exclusive owner of a native handle
///
/// See code:Microsoft.Win32.SafeHandles.SafeNCryptHandle#NCryptHandleDuplicationAlgorithm for
/// details about the algorithm.
/// </summary>
private T DuplicateOwnerHandle<T>() where T : SafeNCryptHandle, new()
{
#if DEBUG
Debug.Assert(IsValidOpenState);
#endif
Debug.Assert(_ownershipState == OwnershipState.Owner);
Debug.Assert(typeof(T) == this.GetType());
bool addRef = false;
T holder = new T();
T duplicate = new T();
// We need to do this operation in a CER in order to ensure that everybody's state stays consistent
// with the current view of the world. If the state of the various handles gets out of sync, then
// we'll end up leaking since reference counts will not be set up properly.
try { }
finally
{
// Setup a holder safe handle to ref count the native handle
holder._ownershipState = OwnershipState.Holder;
holder.SetHandle(DangerousGetHandle());
GC.SuppressFinalize(holder);
// Transition into the duplicate state, referencing the holder. The initial reference count
// on the holder will refer to the original handle so there is no need to AddRef here.
Holder = holder; // Transitions to OwnershipState.Duplicate
// The duplicate handle will also reference the holder
holder.DangerousAddRef(ref addRef);
duplicate.SetHandle(holder.DangerousGetHandle());
duplicate.Holder = holder; // Transitions to OwnershipState.Duplicate
}
return duplicate;
}
public override bool IsInvalid
{
get { return handle == IntPtr.Zero || handle == new IntPtr(-1); }
}
/// <summary>
/// Release the handle
/// </summary>
/// <remarks>
/// Similar to duplication, releasing a handle performs different operations based upon the state
/// of the handle.
///
/// * Owner - Simply call the release P/Invoke method
/// * Duplicate - Decrement the reference count of the current holder
/// * Holder - Call the release P/Invoke. Note that ReleaseHandle on a holder implies a reference
/// count of zero.
/// </remarks>
protected override bool ReleaseHandle()
{
if (_ownershipState == OwnershipState.Duplicate)
{
Holder.DangerousRelease();
return true;
}
else
{
return ReleaseNativeHandle();
}
}
/// <summary>
/// Perform the actual release P/Invoke
/// </summary>
protected abstract bool ReleaseNativeHandle();
/// <summary>
/// Since all NCrypt handles are released the same way, no sense in writing the same code three times.
/// </summary>
internal bool ReleaseNativeWithNCryptFreeObject()
{
ErrorCode errorCode = Interop.NCrypt.NCryptFreeObject(handle);
bool success = (errorCode == ErrorCode.ERROR_SUCCESS);
Debug.Assert(success);
return success;
}
}
/// <summary>
/// Safe handle representing an NCRYPT_KEY_HANDLE
/// </summary>
public sealed class SafeNCryptKeyHandle : SafeNCryptHandle
{
internal SafeNCryptKeyHandle Duplicate()
{
return Duplicate<SafeNCryptKeyHandle>();
}
protected override bool ReleaseNativeHandle()
{
return ReleaseNativeWithNCryptFreeObject();
}
}
/// <summary>
/// Safe handle representing an NCRYPT_PROV_HANDLE
/// </summary>
public sealed class SafeNCryptProviderHandle : SafeNCryptHandle
{
internal SafeNCryptProviderHandle Duplicate()
{
return Duplicate<SafeNCryptProviderHandle>();
}
internal void SetHandleValue(IntPtr newHandleValue)
{
Debug.Assert(newHandleValue != IntPtr.Zero);
Debug.Assert(!IsClosed);
Debug.Assert(handle == IntPtr.Zero);
SetHandle(newHandleValue);
}
protected override bool ReleaseNativeHandle()
{
return ReleaseNativeWithNCryptFreeObject();
}
}
/// <summary>
/// Safe handle representing an NCRYPT_SECRET_HANDLE
/// </summary>
public sealed class SafeNCryptSecretHandle : SafeNCryptHandle
{
protected override bool ReleaseNativeHandle()
{
return ReleaseNativeWithNCryptFreeObject();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Net.Mime;
using System.Runtime.ExceptionServices;
using System.Text;
namespace System.Net.Mail
{
internal static class CheckCommand
{
private static readonly AsyncCallback s_onReadLine = new AsyncCallback(OnReadLine);
private static readonly AsyncCallback s_onWrite = new AsyncCallback(OnWrite);
internal static IAsyncResult BeginSend(SmtpConnection conn, AsyncCallback callback, object state)
{
MultiAsyncResult multiResult = new MultiAsyncResult(conn, callback, state);
multiResult.Enter();
IAsyncResult writeResult = conn.BeginFlush(s_onWrite, multiResult);
if (writeResult.CompletedSynchronously)
{
conn.EndFlush(writeResult);
multiResult.Leave();
}
SmtpReplyReader reader = conn.Reader.GetNextReplyReader();
multiResult.Enter();
//this actually does a read on the stream.
IAsyncResult result = reader.BeginReadLine(s_onReadLine, multiResult);
if (result.CompletedSynchronously)
{
LineInfo info = reader.EndReadLine(result);
if (!(multiResult.Result is Exception))
multiResult.Result = info;
multiResult.Leave();
}
multiResult.CompleteSequence();
return multiResult;
}
internal static object EndSend(IAsyncResult result, out string response)
{
object commandResult = MultiAsyncResult.End(result);
if (commandResult is Exception e)
{
ExceptionDispatchInfo.Throw(e);
}
LineInfo info = (LineInfo)commandResult;
response = info.Line;
return info.StatusCode;
}
private static void OnReadLine(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
MultiAsyncResult multiResult = (MultiAsyncResult)result.AsyncState;
try
{
SmtpConnection conn = (SmtpConnection)multiResult.Context;
LineInfo info = conn.Reader.CurrentReader.EndReadLine(result);
if (!(multiResult.Result is Exception))
multiResult.Result = info;
multiResult.Leave();
}
catch (Exception e)
{
multiResult.Leave(e);
}
}
}
private static void OnWrite(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
MultiAsyncResult multiResult = (MultiAsyncResult)result.AsyncState;
try
{
SmtpConnection conn = (SmtpConnection)multiResult.Context;
conn.EndFlush(result);
multiResult.Leave();
}
catch (Exception e)
{
multiResult.Leave(e);
}
}
}
internal static SmtpStatusCode Send(SmtpConnection conn, out string response)
{
conn.Flush();
SmtpReplyReader reader = conn.Reader.GetNextReplyReader();
LineInfo info = reader.ReadLine();
response = info.Line;
reader.Close();
return info.StatusCode;
}
}
internal static class ReadLinesCommand
{
private static readonly AsyncCallback s_onReadLines = new AsyncCallback(OnReadLines);
private static readonly AsyncCallback s_onWrite = new AsyncCallback(OnWrite);
internal static IAsyncResult BeginSend(SmtpConnection conn, AsyncCallback callback, object state)
{
MultiAsyncResult multiResult = new MultiAsyncResult(conn, callback, state);
multiResult.Enter();
IAsyncResult writeResult = conn.BeginFlush(s_onWrite, multiResult);
if (writeResult.CompletedSynchronously)
{
conn.EndFlush(writeResult);
multiResult.Leave();
}
SmtpReplyReader reader = conn.Reader.GetNextReplyReader();
multiResult.Enter();
IAsyncResult readLinesResult = reader.BeginReadLines(s_onReadLines, multiResult);
if (readLinesResult.CompletedSynchronously)
{
LineInfo[] lines = conn.Reader.CurrentReader.EndReadLines(readLinesResult);
if (!(multiResult.Result is Exception))
multiResult.Result = lines;
multiResult.Leave();
}
multiResult.CompleteSequence();
return multiResult;
}
internal static LineInfo[] EndSend(IAsyncResult result)
{
object commandResult = MultiAsyncResult.End(result);
if (commandResult is Exception e)
{
ExceptionDispatchInfo.Throw(e);
}
return (LineInfo[])commandResult;
}
private static void OnReadLines(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
MultiAsyncResult multiResult = (MultiAsyncResult)result.AsyncState;
try
{
SmtpConnection conn = (SmtpConnection)multiResult.Context;
LineInfo[] lines = conn.Reader.CurrentReader.EndReadLines(result);
if (!(multiResult.Result is Exception))
multiResult.Result = lines;
multiResult.Leave();
}
catch (Exception e)
{
multiResult.Leave(e);
}
}
}
private static void OnWrite(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
MultiAsyncResult multiResult = (MultiAsyncResult)result.AsyncState;
try
{
SmtpConnection conn = (SmtpConnection)multiResult.Context;
conn.EndFlush(result);
multiResult.Leave();
}
catch (Exception e)
{
multiResult.Leave(e);
}
}
}
internal static LineInfo[] Send(SmtpConnection conn)
{
conn.Flush();
return conn.Reader.GetNextReplyReader().ReadLines();
}
}
internal static class AuthCommand
{
internal static IAsyncResult BeginSend(SmtpConnection conn, string type, string message, AsyncCallback callback, object state)
{
PrepareCommand(conn, type, message);
return ReadLinesCommand.BeginSend(conn, callback, state);
}
internal static IAsyncResult BeginSend(SmtpConnection conn, string message, AsyncCallback callback, object state)
{
PrepareCommand(conn, message);
return ReadLinesCommand.BeginSend(conn, callback, state);
}
private static LineInfo CheckResponse(LineInfo[] lines)
{
if (lines == null || lines.Length == 0)
{
throw new SmtpException(SR.SmtpAuthResponseInvalid);
}
System.Diagnostics.Debug.Assert(lines.Length == 1, "Did not expect more than one line response for auth command");
return lines[0];
}
internal static LineInfo EndSend(IAsyncResult result)
{
return CheckResponse(ReadLinesCommand.EndSend(result));
}
private static void PrepareCommand(SmtpConnection conn, string type, string message)
{
conn.BufferBuilder.Append(SmtpCommands.Auth);
conn.BufferBuilder.Append(type);
conn.BufferBuilder.Append((byte)' ');
conn.BufferBuilder.Append(message);
conn.BufferBuilder.Append(SmtpCommands.CRLF);
}
private static void PrepareCommand(SmtpConnection conn, string message)
{
conn.BufferBuilder.Append(message);
conn.BufferBuilder.Append(SmtpCommands.CRLF);
}
internal static LineInfo Send(SmtpConnection conn, string type, string message)
{
PrepareCommand(conn, type, message);
return CheckResponse(ReadLinesCommand.Send(conn));
}
internal static LineInfo Send(SmtpConnection conn, string message)
{
PrepareCommand(conn, message);
return CheckResponse(ReadLinesCommand.Send(conn));
}
}
internal static class DataCommand
{
internal static IAsyncResult BeginSend(SmtpConnection conn, AsyncCallback callback, object state)
{
PrepareCommand(conn);
return CheckCommand.BeginSend(conn, callback, state);
}
private static void CheckResponse(SmtpStatusCode statusCode, string serverResponse)
{
switch (statusCode)
{
case SmtpStatusCode.StartMailInput:
{
return;
}
case SmtpStatusCode.LocalErrorInProcessing:
case SmtpStatusCode.TransactionFailed:
default:
{
if ((int)statusCode < 400)
{
throw new SmtpException(SR.net_webstatus_ServerProtocolViolation, serverResponse);
}
throw new SmtpException(statusCode, serverResponse, true);
}
}
}
internal static void EndSend(IAsyncResult result)
{
string response;
SmtpStatusCode statusCode = (SmtpStatusCode)CheckCommand.EndSend(result, out response);
CheckResponse(statusCode, response);
}
private static void PrepareCommand(SmtpConnection conn)
{
if (conn.IsStreamOpen)
{
throw new InvalidOperationException(SR.SmtpDataStreamOpen);
}
conn.BufferBuilder.Append(SmtpCommands.Data);
}
internal static void Send(SmtpConnection conn)
{
PrepareCommand(conn);
string response;
SmtpStatusCode statusCode = CheckCommand.Send(conn, out response);
CheckResponse(statusCode, response);
}
}
internal static class DataStopCommand
{
private static void CheckResponse(SmtpStatusCode statusCode, string serverResponse)
{
switch (statusCode)
{
case SmtpStatusCode.Ok:
{
return;
}
case SmtpStatusCode.ExceededStorageAllocation:
case SmtpStatusCode.TransactionFailed:
case SmtpStatusCode.LocalErrorInProcessing:
case SmtpStatusCode.InsufficientStorage:
default:
{
if ((int)statusCode < 400)
{
throw new SmtpException(SR.net_webstatus_ServerProtocolViolation, serverResponse);
}
throw new SmtpException(statusCode, serverResponse, true);
}
}
}
private static void PrepareCommand(SmtpConnection conn)
{
if (conn.IsStreamOpen)
{
throw new InvalidOperationException(SR.SmtpDataStreamOpen);
}
conn.BufferBuilder.Append(SmtpCommands.DataStop);
}
internal static void Send(SmtpConnection conn)
{
PrepareCommand(conn);
string response;
SmtpStatusCode statusCode = CheckCommand.Send(conn, out response);
CheckResponse(statusCode, response);
}
}
internal static class EHelloCommand
{
internal static IAsyncResult BeginSend(SmtpConnection conn, string domain, AsyncCallback callback, object state)
{
PrepareCommand(conn, domain);
return ReadLinesCommand.BeginSend(conn, callback, state);
}
private static string[] CheckResponse(LineInfo[] lines)
{
if (lines == null || lines.Length == 0)
{
throw new SmtpException(SR.SmtpEhloResponseInvalid);
}
if (lines[0].StatusCode != SmtpStatusCode.Ok)
{
if ((int)lines[0].StatusCode < 400)
{
throw new SmtpException(SR.net_webstatus_ServerProtocolViolation, lines[0].Line);
}
throw new SmtpException(lines[0].StatusCode, lines[0].Line, true);
}
string[] extensions = new string[lines.Length - 1];
for (int i = 1; i < lines.Length; i++)
{
extensions[i - 1] = lines[i].Line;
}
return extensions;
}
internal static string[] EndSend(IAsyncResult result)
{
return CheckResponse(ReadLinesCommand.EndSend(result));
}
private static void PrepareCommand(SmtpConnection conn, string domain)
{
if (conn.IsStreamOpen)
{
throw new InvalidOperationException(SR.SmtpDataStreamOpen);
}
conn.BufferBuilder.Append(SmtpCommands.EHello);
conn.BufferBuilder.Append(domain);
conn.BufferBuilder.Append(SmtpCommands.CRLF);
}
internal static string[] Send(SmtpConnection conn, string domain)
{
PrepareCommand(conn, domain);
return CheckResponse(ReadLinesCommand.Send(conn));
}
}
internal static class HelloCommand
{
internal static IAsyncResult BeginSend(SmtpConnection conn, string domain, AsyncCallback callback, object state)
{
PrepareCommand(conn, domain);
return CheckCommand.BeginSend(conn, callback, state);
}
private static void CheckResponse(SmtpStatusCode statusCode, string serverResponse)
{
switch (statusCode)
{
case SmtpStatusCode.Ok:
{
return;
}
default:
{
if ((int)statusCode < 400)
{
throw new SmtpException(SR.net_webstatus_ServerProtocolViolation, serverResponse);
}
throw new SmtpException(statusCode, serverResponse, true);
}
}
}
internal static void EndSend(IAsyncResult result)
{
string response;
SmtpStatusCode statusCode = (SmtpStatusCode)CheckCommand.EndSend(result, out response);
CheckResponse(statusCode, response);
}
private static void PrepareCommand(SmtpConnection conn, string domain)
{
if (conn.IsStreamOpen)
{
throw new InvalidOperationException(SR.SmtpDataStreamOpen);
}
conn.BufferBuilder.Append(SmtpCommands.Hello);
conn.BufferBuilder.Append(domain);
conn.BufferBuilder.Append(SmtpCommands.CRLF);
}
internal static void Send(SmtpConnection conn, string domain)
{
PrepareCommand(conn, domain);
string response;
SmtpStatusCode statusCode = CheckCommand.Send(conn, out response);
CheckResponse(statusCode, response);
}
}
internal static class StartTlsCommand
{
internal static IAsyncResult BeginSend(SmtpConnection conn, AsyncCallback callback, object state)
{
PrepareCommand(conn);
return CheckCommand.BeginSend(conn, callback, state);
}
private static void CheckResponse(SmtpStatusCode statusCode, string response)
{
switch (statusCode)
{
case SmtpStatusCode.ServiceReady:
{
return;
}
case SmtpStatusCode.ClientNotPermitted:
default:
{
if ((int)statusCode < 400)
{
throw new SmtpException(SR.net_webstatus_ServerProtocolViolation, response);
}
throw new SmtpException(statusCode, response, true);
}
}
}
internal static void EndSend(IAsyncResult result)
{
string response;
SmtpStatusCode statusCode = (SmtpStatusCode)CheckCommand.EndSend(result, out response);
CheckResponse(statusCode, response);
}
private static void PrepareCommand(SmtpConnection conn)
{
if (conn.IsStreamOpen)
{
throw new InvalidOperationException(SR.SmtpDataStreamOpen);
}
conn.BufferBuilder.Append(SmtpCommands.StartTls);
conn.BufferBuilder.Append(SmtpCommands.CRLF);
}
internal static void Send(SmtpConnection conn)
{
PrepareCommand(conn);
string response;
SmtpStatusCode statusCode = CheckCommand.Send(conn, out response);
CheckResponse(statusCode, response);
}
}
internal static class MailCommand
{
internal static IAsyncResult BeginSend(SmtpConnection conn, byte[] command, MailAddress from,
bool allowUnicode, AsyncCallback callback, object state)
{
PrepareCommand(conn, command, from, allowUnicode);
return CheckCommand.BeginSend(conn, callback, state);
}
private static void CheckResponse(SmtpStatusCode statusCode, string response)
{
switch (statusCode)
{
case SmtpStatusCode.Ok:
{
return;
}
case SmtpStatusCode.ExceededStorageAllocation:
case SmtpStatusCode.LocalErrorInProcessing:
case SmtpStatusCode.InsufficientStorage:
default:
{
if ((int)statusCode < 400)
{
throw new SmtpException(SR.net_webstatus_ServerProtocolViolation, response);
}
throw new SmtpException(statusCode, response, true);
}
}
}
internal static void EndSend(IAsyncResult result)
{
string response;
SmtpStatusCode statusCode = (SmtpStatusCode)CheckCommand.EndSend(result, out response);
CheckResponse(statusCode, response);
}
private static void PrepareCommand(SmtpConnection conn, byte[] command, MailAddress from, bool allowUnicode)
{
if (conn.IsStreamOpen)
{
throw new InvalidOperationException(SR.SmtpDataStreamOpen);
}
conn.BufferBuilder.Append(command);
string fromString = from.GetSmtpAddress(allowUnicode);
conn.BufferBuilder.Append(fromString, allowUnicode);
if (allowUnicode)
{
conn.BufferBuilder.Append(" BODY=8BITMIME SMTPUTF8");
}
conn.BufferBuilder.Append(SmtpCommands.CRLF);
}
internal static void Send(SmtpConnection conn, byte[] command, MailAddress from, bool allowUnicode)
{
PrepareCommand(conn, command, from, allowUnicode);
string response;
SmtpStatusCode statusCode = CheckCommand.Send(conn, out response);
CheckResponse(statusCode, response);
}
}
internal static class RecipientCommand
{
internal static IAsyncResult BeginSend(SmtpConnection conn, string to, AsyncCallback callback, object state)
{
PrepareCommand(conn, to);
return CheckCommand.BeginSend(conn, callback, state);
}
private static bool CheckResponse(SmtpStatusCode statusCode, string response)
{
switch (statusCode)
{
case SmtpStatusCode.Ok:
case SmtpStatusCode.UserNotLocalWillForward:
{
return true;
}
case SmtpStatusCode.MailboxUnavailable:
case SmtpStatusCode.UserNotLocalTryAlternatePath:
case SmtpStatusCode.ExceededStorageAllocation:
case SmtpStatusCode.MailboxNameNotAllowed:
case SmtpStatusCode.MailboxBusy:
case SmtpStatusCode.InsufficientStorage:
{
return false;
}
default:
{
if ((int)statusCode < 400)
{
throw new SmtpException(SR.net_webstatus_ServerProtocolViolation, response);
}
throw new SmtpException(statusCode, response, true);
}
}
}
internal static bool EndSend(IAsyncResult result, out string response)
{
SmtpStatusCode statusCode = (SmtpStatusCode)CheckCommand.EndSend(result, out response);
return CheckResponse(statusCode, response);
}
private static void PrepareCommand(SmtpConnection conn, string to)
{
if (conn.IsStreamOpen)
{
throw new InvalidOperationException(SR.SmtpDataStreamOpen);
}
conn.BufferBuilder.Append(SmtpCommands.Recipient);
conn.BufferBuilder.Append(to, true); // Unicode validation was done prior
conn.BufferBuilder.Append(SmtpCommands.CRLF);
}
internal static bool Send(SmtpConnection conn, string to, out string response)
{
PrepareCommand(conn, to);
SmtpStatusCode statusCode = CheckCommand.Send(conn, out response);
return CheckResponse(statusCode, response);
}
}
internal static class SmtpCommands
{
internal static readonly byte[] Auth = Encoding.ASCII.GetBytes("AUTH ");
internal static readonly byte[] CRLF = Encoding.ASCII.GetBytes("\r\n");
internal static readonly byte[] Data = Encoding.ASCII.GetBytes("DATA\r\n");
internal static readonly byte[] DataStop = Encoding.ASCII.GetBytes("\r\n.\r\n");
internal static readonly byte[] EHello = Encoding.ASCII.GetBytes("EHLO ");
internal static readonly byte[] Expand = Encoding.ASCII.GetBytes("EXPN ");
internal static readonly byte[] Hello = Encoding.ASCII.GetBytes("HELO ");
internal static readonly byte[] Help = Encoding.ASCII.GetBytes("HELP");
internal static readonly byte[] Mail = Encoding.ASCII.GetBytes("MAIL FROM:");
internal static readonly byte[] Noop = Encoding.ASCII.GetBytes("NOOP\r\n");
internal static readonly byte[] Quit = Encoding.ASCII.GetBytes("QUIT\r\n");
internal static readonly byte[] Recipient = Encoding.ASCII.GetBytes("RCPT TO:");
internal static readonly byte[] Reset = Encoding.ASCII.GetBytes("RSET\r\n");
internal static readonly byte[] Send = Encoding.ASCII.GetBytes("SEND FROM:");
internal static readonly byte[] SendAndMail = Encoding.ASCII.GetBytes("SAML FROM:");
internal static readonly byte[] SendOrMail = Encoding.ASCII.GetBytes("SOML FROM:");
internal static readonly byte[] Turn = Encoding.ASCII.GetBytes("TURN\r\n");
internal static readonly byte[] Verify = Encoding.ASCII.GetBytes("VRFY ");
internal static readonly byte[] StartTls = Encoding.ASCII.GetBytes("STARTTLS");
}
internal struct LineInfo
{
private readonly string _line;
private readonly SmtpStatusCode _statusCode;
internal LineInfo(SmtpStatusCode statusCode, string line)
{
_statusCode = statusCode;
_line = line;
}
internal string Line
{
get
{
return _line;
}
}
internal SmtpStatusCode StatusCode
{
get
{
return _statusCode;
}
}
}
}
| |
/*
* Copyright (C) Sony Computer Entertainment America LLC.
* All Rights Reserved.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using Sce.Atf.Adaptation;
using Sce.Atf.Dom;
using Sce.Sled.Shared;
using Sce.Sled.Shared.Services;
namespace Sce.Sled.Lua.Dom
{
public sealed class SledLuaVarWatchListType : SledLuaVarBaseListType<ISledLuaVarBaseType>
{
protected override string Description
{
get { return "Lua Watched Variables"; }
}
protected override string[] TheColumnNames
{
get { return SledLuaVarBaseType.WatchColumnNames; }
}
protected override AttributeInfo NameAttributeInfo
{
get { return SledLuaSchema.SledLuaVarWatchListType.nameAttribute; }
}
protected override ChildInfo VariablesChildInfo
{
// Intentional
get { throw new NotImplementedException(); }
}
public override IList<ISledLuaVarBaseType> Variables
{
get
{
var variables = new List<ISledLuaVarBaseType>();
variables.AddRange(Globals);
variables.AddRange(Locals);
variables.AddRange(Upvalues);
variables.AddRange(EnvVars);
return variables;
}
}
private IList<SledLuaVarGlobalType> Globals
{
get { return GetChildList<SledLuaVarGlobalType>(SledLuaSchema.SledLuaVarWatchListType.GlobalsChild); }
}
private IList<SledLuaVarLocalType> Locals
{
get { return GetChildList<SledLuaVarLocalType>(SledLuaSchema.SledLuaVarWatchListType.LocalsChild); }
}
private IList<SledLuaVarUpvalueType> Upvalues
{
get { return GetChildList<SledLuaVarUpvalueType>(SledLuaSchema.SledLuaVarWatchListType.UpvaluesChild); }
}
private IList<SledLuaVarEnvType> EnvVars
{
get { return GetChildList<SledLuaVarEnvType>(SledLuaSchema.SledLuaVarWatchListType.EnvVarsChild); }
}
public void Clear()
{
Globals.Clear();
Locals.Clear();
Upvalues.Clear();
EnvVars.Clear();
m_dictCustomWatches.Clear();
}
public void Add(ISledLuaVarBaseType luaVar)
{
if (luaVar == null)
return;
m_dictCustomWatches[luaVar] = WatchedVariableService.ReceivingWatchedCustomVariables;
if (luaVar.DomNode.Is<SledLuaVarGlobalType>())
Globals.Add(luaVar.DomNode.As<SledLuaVarGlobalType>());
else if (luaVar.DomNode.Is<SledLuaVarLocalType>())
Locals.Add(luaVar.DomNode.As<SledLuaVarLocalType>());
else if (luaVar.DomNode.Is<SledLuaVarUpvalueType>())
Upvalues.Add(luaVar.DomNode.As<SledLuaVarUpvalueType>());
else if (luaVar.DomNode.Is<SledLuaVarEnvType>())
EnvVars.Add(luaVar.DomNode.As<SledLuaVarEnvType>());
}
public void AddToItem(ISledLuaVarBaseType root, ISledLuaVarBaseType luaVar, bool bHierarchical)
{
if (!bHierarchical)
{
m_dictCustomWatches[luaVar] = WatchedVariableService.ReceivingWatchedCustomVariables;
AddTo(root, luaVar);
return;
}
// Figure out where to place the item
var insert = FindInsertion(root, luaVar);
if (insert == null)
return;
m_dictCustomWatches[luaVar] = WatchedVariableService.ReceivingWatchedCustomVariables;
AddTo(insert, luaVar);
}
public void Remove(ISledLuaVarBaseType luaVar)
{
if (luaVar == null)
return;
m_dictCustomWatches.Remove(luaVar);
luaVar.DomNode.RemoveFromParent();
}
public bool IsCustomWatchedVariable(ISledLuaVarBaseType luaVar)
{
bool result;
m_dictCustomWatches.TryGetValue(luaVar, out result);
return result;
}
#region Add/Insertion Helpers
private static void AddTo(ISledLuaVarBaseType adder, ISledLuaVarBaseType addee)
{
if (addee.DomNode.Type == SledLuaSchema.SledLuaVarGlobalType.Type)
AddGlobal(adder, addee);
else if (addee.DomNode.Type == SledLuaSchema.SledLuaVarLocalType.Type)
AddLocal(adder, addee);
else if (addee.DomNode.Type == SledLuaSchema.SledLuaVarUpvalueType.Type)
AddUpvalue(adder, addee);
else if (addee.DomNode.Type == SledLuaSchema.SledLuaVarEnvType.Type)
AddEnvironment(adder, addee);
}
private static void AddGlobal(ISledLuaVarBaseType adder, ISledLuaVarBaseType addee)
{
var parent = adder.DomNode.As<SledLuaVarGlobalType>();
parent.Globals.Add(addee.DomNode.As<SledLuaVarGlobalType>());
}
private static void AddLocal(ISledLuaVarBaseType adder, ISledLuaVarBaseType addee)
{
var parent = adder.DomNode.As<SledLuaVarLocalType>();
parent.Locals.Add(addee.DomNode.As<SledLuaVarLocalType>());
}
private static void AddUpvalue(ISledLuaVarBaseType adder, ISledLuaVarBaseType addee)
{
var parent = adder.DomNode.As<SledLuaVarUpvalueType>();
parent.Upvalues.Add(addee.DomNode.As<SledLuaVarUpvalueType>());
}
private static void AddEnvironment(ISledLuaVarBaseType adder, ISledLuaVarBaseType addee)
{
var parent = adder.DomNode.As<SledLuaVarEnvType>();
parent.EnvVars.Add(addee.DomNode.As<SledLuaVarEnvType>());
}
private static ISledLuaVarBaseType FindInsertion(ISledLuaVarBaseType adder, ISledLuaVarBaseType addee)
{
try
{
var adderPiecesCount = adder.TargetHierarchy.Count + 1;
var pieces = new List<string>();
{
pieces.AddRange(addee.TargetHierarchy.Select(kv => kv.Name));
pieces.Add(addee.DisplayName);
}
// Do we even need to try and find this item?
return
pieces.Count <= (adderPiecesCount + 1)
? adder
: FindInsertionHelper(adder, adderPiecesCount, pieces);
}
catch (Exception ex)
{
SledOutDevice.OutLine(
SledMessageType.Error,
"[SledLuaVarWatchList] Exception finding insertion " +
"point with adder \"{0}\" and addee \"{1}\": {2}",
adder.Name, addee.Name, ex.Message);
return null;
}
}
private static ISledLuaVarBaseType FindInsertionHelper(ISledLuaVarBaseType adder, int adderPiecesCount, List<string> pieces)
{
ISledLuaVarBaseType insert = null;
var lstVariables = adder.Variables.ToList();
for (var i = adderPiecesCount; i < (pieces.Count - 1); ++i)
{
var iPos = -1;
var count = lstVariables.Count;
for (var j = 0; j < count; j++)
{
if (string.Compare(lstVariables[j].DisplayName, pieces[i], StringComparison.Ordinal) != 0)
continue;
iPos = j;
break;
}
if (iPos == -1)
return null;
insert = lstVariables[iPos];
lstVariables = insert.Variables.ToList();
}
return insert;
}
#endregion
private ISledLuaWatchedVariableService WatchedVariableService
{
get { return m_watchedVariableService ?? (m_watchedVariableService = SledServiceInstance.Get<ISledLuaWatchedVariableService>()); }
}
private ISledLuaWatchedVariableService m_watchedVariableService;
private readonly Dictionary<ISledLuaVarBaseType, bool> m_dictCustomWatches =
new Dictionary<ISledLuaVarBaseType, bool>();
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using QuantConnect.Data.Market;
using QuantConnect.Orders;
using QuantConnect.Orders.Fees;
using QuantConnect.Orders.Fills;
using QuantConnect.Orders.Slippage;
using QuantConnect.Securities;
using QuantConnect.Securities.Equity;
using QuantConnect.Securities.Option;
using QuantConnect.Util;
namespace QuantConnect.Brokerages
{
/// <summary>
/// Provides a default implementation of <see cref="IBrokerageModel"/> that allows all orders and uses
/// the default transaction models
/// </summary>
public class DefaultBrokerageModel : IBrokerageModel
{
/// <summary>
/// The default markets for the backtesting brokerage
/// </summary>
public static readonly IReadOnlyDictionary<SecurityType, string> DefaultMarketMap = new Dictionary<SecurityType, string>
{
{SecurityType.Base, Market.USA},
{SecurityType.Equity, Market.USA},
{SecurityType.Option, Market.USA},
{SecurityType.Future, Market.USA},
{SecurityType.Forex, Market.FXCM},
{SecurityType.Cfd, Market.FXCM},
{SecurityType.Crypto, Market.GDAX}
}.ToReadOnlyDictionary();
/// <summary>
/// Gets or sets the account type used by this model
/// </summary>
public virtual AccountType AccountType
{
get;
private set;
}
/// <summary>
/// Gets a map of the default markets to be used for each security type
/// </summary>
public virtual IReadOnlyDictionary<SecurityType, string> DefaultMarkets
{
get { return DefaultMarketMap; }
}
/// <summary>
/// Initializes a new instance of the <see cref="DefaultBrokerageModel"/> class
/// </summary>
/// <param name="accountType">The type of account to be modelled, defaults to
/// <see cref="QuantConnect.AccountType.Margin"/></param>
public DefaultBrokerageModel(AccountType accountType = AccountType.Margin)
{
AccountType = accountType;
}
/// <summary>
/// Returns true if the brokerage could accept this order. This takes into account
/// order type, security type, and order size limits.
/// </summary>
/// <remarks>
/// For example, a brokerage may have no connectivity at certain times, or an order rate/size limit
/// </remarks>
/// <param name="security">The security being ordered</param>
/// <param name="order">The order to be processed</param>
/// <param name="message">If this function returns false, a brokerage message detailing why the order may not be submitted</param>
/// <returns>True if the brokerage could process the order, false otherwise</returns>
public virtual bool CanSubmitOrder(Security security, Order order, out BrokerageMessageEvent message)
{
message = null;
return true;
}
/// <summary>
/// Returns true if the brokerage would allow updating the order as specified by the request
/// </summary>
/// <param name="security">The security of the order</param>
/// <param name="order">The order to be updated</param>
/// <param name="request">The requested update to be made to the order</param>
/// <param name="message">If this function returns false, a brokerage message detailing why the order may not be updated</param>
/// <returns>True if the brokerage would allow updating the order, false otherwise</returns>
public virtual bool CanUpdateOrder(Security security, Order order, UpdateOrderRequest request, out BrokerageMessageEvent message)
{
message = null;
return true;
}
/// <summary>
/// Returns true if the brokerage would be able to execute this order at this time assuming
/// market prices are sufficient for the fill to take place. This is used to emulate the
/// brokerage fills in backtesting and paper trading. For example some brokerages may not perform
/// executions during extended market hours. This is not intended to be checking whether or not
/// the exchange is open, that is handled in the Security.Exchange property.
/// </summary>
/// <param name="security">The security being traded</param>
/// <param name="order">The order to test for execution</param>
/// <returns>True if the brokerage would be able to perform the execution, false otherwise</returns>
public virtual bool CanExecuteOrder(Security security, Order order)
{
return true;
}
/// <summary>
/// Applies the split to the specified order ticket
/// </summary>
/// <remarks>
/// This default implementation will update the orders to maintain a similar market value
/// </remarks>
/// <param name="tickets">The open tickets matching the split event</param>
/// <param name="split">The split event data</param>
public virtual void ApplySplit(List<OrderTicket> tickets, Split split)
{
// by default we'll just update the orders to have the same notional value
var splitFactor = split.SplitFactor;
tickets.ForEach(ticket => ticket.Update(new UpdateOrderFields
{
Quantity = (int?) (ticket.Quantity/splitFactor),
LimitPrice = ticket.OrderType.IsLimitOrder() ? ticket.Get(OrderField.LimitPrice)*splitFactor : (decimal?) null,
StopPrice = ticket.OrderType.IsStopOrder() ? ticket.Get(OrderField.StopPrice)*splitFactor : (decimal?) null
}));
}
/// <summary>
/// Gets the brokerage's leverage for the specified security
/// </summary>
/// <param name="security">The security's whose leverage we seek</param>
/// <returns>The leverage for the specified security</returns>
public virtual decimal GetLeverage(Security security)
{
if (AccountType == AccountType.Cash)
{
return 1m;
}
switch (security.Type)
{
case SecurityType.Equity:
return 2m;
case SecurityType.Forex:
case SecurityType.Cfd:
return 50m;
case SecurityType.Crypto:
return 1m;
case SecurityType.Base:
case SecurityType.Commodity:
case SecurityType.Option:
case SecurityType.Future:
default:
return 1m;
}
}
/// <summary>
/// Gets a new fill model that represents this brokerage's fill behavior
/// </summary>
/// <param name="security">The security to get fill model for</param>
/// <returns>The new fill model for this brokerage</returns>
public virtual IFillModel GetFillModel(Security security)
{
return new ImmediateFillModel();
}
/// <summary>
/// Gets a new fee model that represents this brokerage's fee structure
/// </summary>
/// <param name="security">The security to get a fee model for</param>
/// <returns>The new fee model for this brokerage</returns>
public virtual IFeeModel GetFeeModel(Security security)
{
switch (security.Type)
{
case SecurityType.Base:
case SecurityType.Forex:
case SecurityType.Cfd:
case SecurityType.Crypto:
return new ConstantFeeModel(0m);
case SecurityType.Equity:
case SecurityType.Option:
case SecurityType.Future:
return new InteractiveBrokersFeeModel();
case SecurityType.Commodity:
default:
return new ConstantFeeModel(0m);
}
}
/// <summary>
/// Gets a new slippage model that represents this brokerage's fill slippage behavior
/// </summary>
/// <param name="security">The security to get a slippage model for</param>
/// <returns>The new slippage model for this brokerage</returns>
public virtual ISlippageModel GetSlippageModel(Security security)
{
switch (security.Type)
{
case SecurityType.Base:
case SecurityType.Equity:
return new ConstantSlippageModel(0);
case SecurityType.Forex:
case SecurityType.Cfd:
case SecurityType.Crypto:
return new ConstantSlippageModel(0);
case SecurityType.Commodity:
case SecurityType.Option:
case SecurityType.Future:
default:
return new ConstantSlippageModel(0);
}
}
/// <summary>
/// Gets a new settlement model for the security
/// </summary>
/// <param name="security">The security to get a settlement model for</param>
/// <param name="accountType">The account type</param>
/// <returns>The settlement model for this brokerage</returns>
public virtual ISettlementModel GetSettlementModel(Security security, AccountType accountType)
{
if (accountType == AccountType.Cash)
{
switch (security.Type)
{
case SecurityType.Equity:
return new DelayedSettlementModel(Equity.DefaultSettlementDays, Equity.DefaultSettlementTime);
case SecurityType.Option:
return new DelayedSettlementModel(Option.DefaultSettlementDays, Option.DefaultSettlementTime);
}
}
return new ImmediateSettlementModel();
}
}
}
| |
namespace Foo.App.ManagedPlayer
{
partial class MainForm
{
/// <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.toolStripContainer1 = new System.Windows.Forms.ToolStripContainer();
this.lvSongs = new System.Windows.Forms.ListView();
this.clhPlaying = new System.Windows.Forms.ColumnHeader();
this.clhFilename = new System.Windows.Forms.ColumnHeader();
this.tool = new System.Windows.Forms.Panel();
this.btnForward = new System.Windows.Forms.Button();
this.btnRewind = new System.Windows.Forms.Button();
this.btnPlayPause = new System.Windows.Forms.Button();
this.tbPosition = new System.Windows.Forms.TrackBar();
this.menu = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.tsmOpen = new System.Windows.Forms.ToolStripMenuItem();
this.tsmAddFiles = new System.Windows.Forms.ToolStripMenuItem();
this.tsmAddFolder = new System.Windows.Forms.ToolStripMenuItem();
this.tsmRemove = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator();
this.tsmExit = new System.Windows.Forms.ToolStripMenuItem();
this.folderBrowser = new System.Windows.Forms.FolderBrowserDialog();
this.fileBrowser = new System.Windows.Forms.OpenFileDialog();
this.soundPlayer = new Foo.Media.SoundPlayer();
this.toolStripContainer1.ContentPanel.SuspendLayout();
this.toolStripContainer1.TopToolStripPanel.SuspendLayout();
this.toolStripContainer1.SuspendLayout();
this.tool.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.tbPosition)).BeginInit();
this.menu.SuspendLayout();
this.SuspendLayout();
//
// toolStripContainer1
//
//
// toolStripContainer1.ContentPanel
//
this.toolStripContainer1.ContentPanel.Controls.Add(this.lvSongs);
this.toolStripContainer1.ContentPanel.Controls.Add(this.tool);
this.toolStripContainer1.ContentPanel.Size = new System.Drawing.Size(341, 443);
this.toolStripContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.toolStripContainer1.Location = new System.Drawing.Point(0, 0);
this.toolStripContainer1.Name = "toolStripContainer1";
this.toolStripContainer1.Size = new System.Drawing.Size(341, 467);
this.toolStripContainer1.TabIndex = 0;
this.toolStripContainer1.Text = "tscMain";
//
// toolStripContainer1.TopToolStripPanel
//
this.toolStripContainer1.TopToolStripPanel.Controls.Add(this.menu);
//
// lvSongs
//
this.lvSongs.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.clhPlaying,
this.clhFilename});
this.lvSongs.Dock = System.Windows.Forms.DockStyle.Fill;
this.lvSongs.FullRowSelect = true;
this.lvSongs.Location = new System.Drawing.Point(0, 0);
this.lvSongs.Name = "lvSongs";
this.lvSongs.ShowGroups = false;
this.lvSongs.Size = new System.Drawing.Size(341, 330);
this.lvSongs.TabIndex = 1;
this.lvSongs.UseCompatibleStateImageBehavior = false;
this.lvSongs.View = System.Windows.Forms.View.Details;
this.lvSongs.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.lvSongs_MouseDoubleClick);
this.lvSongs.KeyUp += new System.Windows.Forms.KeyEventHandler(this.lvSongs_KeyUp);
//
// clhPlaying
//
this.clhPlaying.Text = "";
this.clhPlaying.Width = 20;
//
// clhFilename
//
this.clhFilename.Text = "Filename";
this.clhFilename.Width = 307;
//
// tool
//
this.tool.Controls.Add(this.btnForward);
this.tool.Controls.Add(this.btnRewind);
this.tool.Controls.Add(this.btnPlayPause);
this.tool.Controls.Add(this.tbPosition);
this.tool.Dock = System.Windows.Forms.DockStyle.Bottom;
this.tool.Location = new System.Drawing.Point(0, 330);
this.tool.Name = "tool";
this.tool.Size = new System.Drawing.Size(341, 113);
this.tool.TabIndex = 0;
//
// btnForward
//
this.btnForward.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Right)));
this.btnForward.Location = new System.Drawing.Point(214, 54);
this.btnForward.Name = "btnForward";
this.btnForward.Size = new System.Drawing.Size(75, 23);
this.btnForward.TabIndex = 3;
this.btnForward.Text = "Forward";
this.btnForward.UseVisualStyleBackColor = true;
this.btnForward.Click += new System.EventHandler(this.btnForward_Click);
//
// btnRewind
//
this.btnRewind.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.btnRewind.Location = new System.Drawing.Point(52, 54);
this.btnRewind.Name = "btnRewind";
this.btnRewind.Size = new System.Drawing.Size(75, 23);
this.btnRewind.TabIndex = 2;
this.btnRewind.Text = "Rewind";
this.btnRewind.UseVisualStyleBackColor = true;
this.btnRewind.Click += new System.EventHandler(this.btnRewind_Click);
//
// btnPlayPause
//
this.btnPlayPause.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.btnPlayPause.Location = new System.Drawing.Point(133, 43);
this.btnPlayPause.Name = "btnPlayPause";
this.btnPlayPause.Size = new System.Drawing.Size(75, 45);
this.btnPlayPause.TabIndex = 1;
this.btnPlayPause.Text = "Play";
this.btnPlayPause.UseVisualStyleBackColor = true;
this.btnPlayPause.Click += new System.EventHandler(this.btnPlayPause_Click);
//
// tbPosition
//
this.tbPosition.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tbPosition.Location = new System.Drawing.Point(12, 6);
this.tbPosition.Name = "tbPosition";
this.tbPosition.Size = new System.Drawing.Size(317, 45);
this.tbPosition.TabIndex = 0;
this.tbPosition.TickStyle = System.Windows.Forms.TickStyle.None;
this.tbPosition.Scroll += new System.EventHandler(this.tbPosition_Scroll);
//
// menu
//
this.menu.Dock = System.Windows.Forms.DockStyle.None;
this.menu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem});
this.menu.Location = new System.Drawing.Point(0, 0);
this.menu.Name = "menu";
this.menu.Size = new System.Drawing.Size(341, 24);
this.menu.TabIndex = 0;
this.menu.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tsmOpen,
this.tsmAddFiles,
this.tsmAddFolder,
this.tsmRemove,
this.toolStripMenuItem1,
this.tsmExit});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(35, 20);
this.fileToolStripMenuItem.Text = "File";
//
// tsmOpen
//
this.tsmOpen.Name = "tsmOpen";
this.tsmOpen.Size = new System.Drawing.Size(152, 22);
this.tsmOpen.Text = "Open";
this.tsmOpen.Click += new System.EventHandler(this.tsmOpen_Click);
//
// tsmAddFiles
//
this.tsmAddFiles.Name = "tsmAddFiles";
this.tsmAddFiles.Size = new System.Drawing.Size(152, 22);
this.tsmAddFiles.Text = "Add Files";
this.tsmAddFiles.Click += new System.EventHandler(this.tsmAddFiles_Click);
//
// tsmAddFolder
//
this.tsmAddFolder.Name = "tsmAddFolder";
this.tsmAddFolder.Size = new System.Drawing.Size(152, 22);
this.tsmAddFolder.Text = "Add Folder";
this.tsmAddFolder.Click += new System.EventHandler(this.tsmAddFolder_Click);
//
// tsmRemove
//
this.tsmRemove.Name = "tsmRemove";
this.tsmRemove.Size = new System.Drawing.Size(152, 22);
this.tsmRemove.Text = "Remove";
this.tsmRemove.Click += new System.EventHandler(this.tsmRemove_Click);
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
this.toolStripMenuItem1.Size = new System.Drawing.Size(149, 6);
//
// tsmExit
//
this.tsmExit.Name = "tsmExit";
this.tsmExit.Size = new System.Drawing.Size(152, 22);
this.tsmExit.Text = "Exit";
this.tsmExit.Click += new System.EventHandler(this.tsmExit_Click);
//
// fileBrowser
//
this.fileBrowser.Filter = "Music files (*.mp3,*.wma,*.wav)|*.mp3;*.wma;*.wav |All files (*.*)|*.*";
this.fileBrowser.Multiselect = true;
//
// soundPlayer
//
this.soundPlayer.PositionChanged += new System.EventHandler(this.soundPlayer_PositionChanged);
this.soundPlayer.StateChanged += new System.EventHandler(this.soundPlayer_StateChanged);
this.soundPlayer.LengthChanged += new System.EventHandler(this.soundPlayer_LengthChanged);
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(341, 467);
this.Controls.Add(this.toolStripContainer1);
this.MainMenuStrip = this.menu;
this.MinimumSize = new System.Drawing.Size(349, 501);
this.Name = "MainForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "The Managed Player";
this.toolStripContainer1.ContentPanel.ResumeLayout(false);
this.toolStripContainer1.TopToolStripPanel.ResumeLayout(false);
this.toolStripContainer1.TopToolStripPanel.PerformLayout();
this.toolStripContainer1.ResumeLayout(false);
this.toolStripContainer1.PerformLayout();
this.tool.ResumeLayout(false);
this.tool.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.tbPosition)).EndInit();
this.menu.ResumeLayout(false);
this.menu.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ToolStripContainer toolStripContainer1;
private System.Windows.Forms.MenuStrip menu;
private System.Windows.Forms.ListView lvSongs;
private System.Windows.Forms.Panel tool;
private System.Windows.Forms.Button btnForward;
private System.Windows.Forms.Button btnRewind;
private System.Windows.Forms.Button btnPlayPause;
private System.Windows.Forms.TrackBar tbPosition;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem tsmOpen;
private System.Windows.Forms.ToolStripMenuItem tsmAddFiles;
private System.Windows.Forms.ToolStripMenuItem tsmAddFolder;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem tsmExit;
private System.Windows.Forms.FolderBrowserDialog folderBrowser;
private System.Windows.Forms.OpenFileDialog fileBrowser;
private System.Windows.Forms.ToolStripMenuItem tsmRemove;
private System.Windows.Forms.ColumnHeader clhPlaying;
private System.Windows.Forms.ColumnHeader clhFilename;
private Foo.Media.SoundPlayer soundPlayer;
}
}
| |
// 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 System.Runtime.InteropServices;
namespace System
{
internal static class PlatformApis
{
private enum Platform
{
Unknown = 0,
Linux = 2,
Darwin = 3,
FreeBSD = 4
}
private static partial class NativeMethods
{
public static class Darwin
{
private const int CTL_KERN = 1;
private const int KERN_OSRELEASE = 2;
public unsafe static string GetKernelRelease()
{
const uint BUFFER_LENGTH = 32;
var name = stackalloc int[2];
name[0] = CTL_KERN;
name[1] = KERN_OSRELEASE;
var buf = stackalloc byte[(int)BUFFER_LENGTH];
var len = stackalloc uint[1];
*len = BUFFER_LENGTH;
try
{
// If the buffer isn't big enough, it seems sysctl still returns 0 and just sets len to the
// necessary buffer size. This appears to be contrary to the man page, but it's easy to detect
// by simply checking len against the buffer length.
if (sysctl(name, 2, buf, len, IntPtr.Zero, 0) == 0 && *len < BUFFER_LENGTH)
{
return Marshal.PtrToStringAnsi((IntPtr)buf, (int)*len);
}
}
catch (Exception ex)
{
throw new PlatformNotSupportedException("Error reading Darwin Kernel Version", ex);
}
throw new PlatformNotSupportedException("Unknown error reading Darwin Kernel Version");
}
[DllImport("libc")]
private unsafe static extern int sysctl(
int* name,
uint namelen,
byte* oldp,
uint* oldlenp,
IntPtr newp,
uint newlen);
}
}
private class DistroInfo
{
public string Id;
public string VersionId;
}
private static readonly Lazy<Platform> _platform = new Lazy<Platform>(DetermineOSPlatform);
private static readonly Lazy<DistroInfo> _distroInfo = new Lazy<DistroInfo>(LoadDistroInfo);
public static string GetOSName()
{
switch (GetOSPlatform())
{
case Platform.Linux:
return GetDistroId() ?? "Linux";
case Platform.Darwin:
return "Mac OS X";
case Platform.FreeBSD:
return "FreeBSD";
default:
return "Unknown";
}
}
public static string GetOSVersion()
{
switch (GetOSPlatform())
{
case Platform.Linux:
return GetDistroVersionId() ?? string.Empty;
case Platform.Darwin:
return GetDarwinVersion() ?? string.Empty;
case Platform.FreeBSD:
return GetFreeBSDVersion() ?? string.Empty;
default:
return string.Empty;
}
}
private static string GetDarwinVersion()
{
Version version;
var kernelRelease = NativeMethods.Darwin.GetKernelRelease();
if (!Version.TryParse(kernelRelease, out version) || version.Major < 5)
{
// 10.0 covers all versions prior to Darwin 5
// Similarly, if the version is not a valid version number, but we have still detected that it is Darwin, we just assume
// it is OS X 10.0
return "10.0";
}
else
{
// Mac OS X 10.1 mapped to Darwin 5.x, and the mapping continues that way
// So just subtract 4 from the Darwin version.
// https://en.wikipedia.org/wiki/Darwin_%28operating_system%29
return $"10.{version.Major - 4}";
}
}
private static string GetFreeBSDVersion()
{
// This is same as sysctl kern.version
// FreeBSD 11.0-RELEASE-p1 FreeBSD 11.0-RELEASE-p1 #0 r306420: Thu Sep 29 01:43:23 UTC 2016 [email protected]:/usr/obj/usr/src/sys/GENERIC
// What we want is major release as minor releases should be compatible.
String version = RuntimeInformation.OSDescription;
try
{
// second token up to first dot
return RuntimeInformation.OSDescription.Split()[1].Split('.')[0];
}
catch
{
}
return string.Empty;
}
private static Platform GetOSPlatform()
{
return _platform.Value;
}
private static string GetDistroId()
{
return _distroInfo.Value?.Id;
}
private static string GetDistroVersionId()
{
return _distroInfo.Value?.VersionId;
}
private static DistroInfo LoadDistroInfo()
{
DistroInfo result = null;
// Sample os-release file:
// NAME="Ubuntu"
// VERSION = "14.04.3 LTS, Trusty Tahr"
// ID = ubuntu
// ID_LIKE = debian
// PRETTY_NAME = "Ubuntu 14.04.3 LTS"
// VERSION_ID = "14.04"
// HOME_URL = "http://www.ubuntu.com/"
// SUPPORT_URL = "http://help.ubuntu.com/"
// BUG_REPORT_URL = "http://bugs.launchpad.net/ubuntu/"
// We use ID and VERSION_ID
if (File.Exists("/etc/os-release"))
{
var lines = File.ReadAllLines("/etc/os-release");
result = new DistroInfo();
foreach (var line in lines)
{
if (line.StartsWith("ID=", StringComparison.Ordinal))
{
result.Id = line.Substring(3).Trim('"', '\'');
}
else if (line.StartsWith("VERSION_ID=", StringComparison.Ordinal))
{
result.VersionId = line.Substring(11).Trim('"', '\'');
}
}
}
else if (File.Exists("/etc/redhat-release"))
{
var lines = File.ReadAllLines("/etc/redhat-release");
if (lines.Length >= 1)
{
string line = lines[0];
if (line.StartsWith("Red Hat Enterprise Linux Server release 6.") ||
line.StartsWith("CentOS release 6."))
{
result = new DistroInfo();
result.Id = "rhel";
result.VersionId = "6";
}
}
}
if (result != null)
{
result = NormalizeDistroInfo(result);
}
return result;
}
// For some distros, we don't want to use the full version from VERSION_ID. One example is
// Red Hat Enterprise Linux, which includes a minor version in their VERSION_ID but minor
// versions are backwards compatable.
//
// In this case, we'll normalized RIDs like 'rhel.7.2' and 'rhel.7.3' to a generic
// 'rhel.7'. This brings RHEL in line with other distros like CentOS or Debian which
// don't put minor version numbers in their VERSION_ID fields because all minor versions
// are backwards compatible.
private static DistroInfo NormalizeDistroInfo(DistroInfo distroInfo)
{
// Handle if VersionId is null by just setting the index to -1.
int lastVersionNumberSeparatorIndex = distroInfo.VersionId?.IndexOf('.') ?? -1;
if (lastVersionNumberSeparatorIndex != -1 && distroInfo.Id == "alpine")
{
// For Alpine, the version reported has three components, so we need to find the second version separator
lastVersionNumberSeparatorIndex = distroInfo.VersionId.IndexOf('.', lastVersionNumberSeparatorIndex + 1);
}
if (lastVersionNumberSeparatorIndex != -1 && (distroInfo.Id == "rhel" || distroInfo.Id == "alpine"))
{
distroInfo.VersionId = distroInfo.VersionId.Substring(0, lastVersionNumberSeparatorIndex);
}
return distroInfo;
}
private static Platform DetermineOSPlatform()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
return Platform.Linux;
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
return Platform.Darwin;
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.Create("FREEBSD")))
{
return Platform.FreeBSD;
}
return Platform.Unknown;
}
}
}
| |
// <copyright file="DummyClient.cs" company="Google Inc.">
// Copyright (C) 2014 Google Inc. 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.
// </copyright>
#if (UNITY_ANDROID || (UNITY_IPHONE && !NO_GPGS))
namespace GooglePlayGames.BasicApi
{
using System;
using GooglePlayGames.BasicApi.Multiplayer;
using GooglePlayGames.OurUtils;
using UnityEngine.SocialPlatforms;
/// <summary>
/// Dummy client used in Editor.
/// </summary>
/// <remarks>Google Play Game Services are not supported in the Editor
/// environment, so this client is used as a placeholder.
/// </remarks>
public class DummyClient : IPlayGamesClient
{
/// <summary>
/// Starts the authentication process.
/// </summary>
/// <remarks> If silent == true, no UIs will be shown
/// (if UIs are needed, it will fail rather than show them). If silent == false,
/// this may show UIs, consent dialogs, etc.
/// At the end of the process, callback will be invoked to notify of the result.
/// Once the callback returns true, the user is considered to be authenticated
/// forever after.
/// </remarks>
/// <param name="callback">Callback when completed.</param>
/// <param name="silent">If set to <c>true</c> silent.</param>
public void Authenticate(Action<bool, string> callback, bool silent)
{
LogUsage();
if (callback != null)
{
callback(false, "Not implemented on this platform");
}
}
/// <summary>
/// Returns whether or not user is authenticated.
/// </summary>
/// <returns>true if authenticated</returns>
/// <c>false</c>
public bool IsAuthenticated()
{
LogUsage();
return false;
}
/// <summary>
/// Signs the user out.
/// </summary>
public void SignOut()
{
LogUsage();
}
/// <summary>
/// Retrieves an id token, which can be verified server side, if they are logged in.
/// </summary>
/// <param name="idTokenCallback">The callback invoked with the token</param>
/// <returns>The identifier token.</returns>
public string GetIdToken()
{
LogUsage();
return null;
}
/// <summary>
/// Returns the authenticated user's ID. Note that this value may change if a user signs
/// on and signs in with a different account.
/// </summary>
/// <returns>The user identifier.</returns>
public string GetUserId()
{
LogUsage();
return "DummyID";
}
public string GetServerAuthCode()
{
LogUsage();
return null;
}
/// <summary>
/// Gets the user's email.
/// </summary>
/// <remarks>The email address returned is selected by the user from the accounts present
/// on the device. There is no guarantee this uniquely identifies the player.
/// For unique identification use the id property of the local player.
/// The user can also choose to not select any email address, meaning it is not
/// available.</remarks>
/// <returns>The user email or null if not authenticated or the permission is
/// not available.</returns>
public string GetUserEmail()
{
return string.Empty;
}
/// <summary>
/// Gets the player stats.
/// </summary>
/// <param name="callback">Callback for response.</param>
public void GetPlayerStats(Action<CommonStatusCodes, PlayerStats> callback)
{
LogUsage();
callback(CommonStatusCodes.ApiNotConnected, new PlayerStats());
}
/// <summary>
/// Returns a human readable name for the user, if they are logged in.
/// </summary>
/// <returns>The user display name.</returns>
public string GetUserDisplayName()
{
LogUsage();
return "Player";
}
/// <summary>
/// Returns the user's avatar url, if they are logged in and have an avatar.
/// </summary>
/// <returns>The user image URL.</returns>
public string GetUserImageUrl()
{
LogUsage();
return null;
}
/// <summary>
/// Loads the players specified.
/// </summary>
/// <remarks> This is mainly used by the leaderboard
/// APIs to get the information of a high scorer.
/// </remarks>
/// <param name="userIds">User identifiers.</param>
/// <param name="callback">Callback to invoke when completed.</param>
public void LoadUsers(string[] userIds, Action<IUserProfile[]> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(null);
}
}
/// <summary>
/// Loads the achievements for the current player.
/// </summary>
/// <param name="callback">Callback to invoke when completed.</param>
public void LoadAchievements(Action<Achievement[]> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(null);
}
}
/// <summary>
/// Returns the achievement corresponding to the passed achievement identifier.
/// </summary>
/// <returns>The achievement.</returns>
/// <param name="achId">Achievement identifier.</param>
public Achievement GetAchievement(string achId)
{
LogUsage();
return null;
}
/// <summary>
/// Unlocks the achievement.
/// </summary>
/// <param name="achId">Achievement identifier.</param>
/// <param name="callback">Callback to invoke when complete.</param>
public void UnlockAchievement(string achId, Action<bool> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(false);
}
}
/// <summary>
/// Reveals the achievement.
/// </summary>
/// <param name="achId">Achievement identifier.</param>
/// <param name="callback">Callback to invoke when complete.</param>
public void RevealAchievement(string achId, Action<bool> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(false);
}
}
/// <summary>
/// Increments the achievement.
/// </summary>
/// <param name="achId">Achievement identifier.</param>
/// <param name="steps">Steps to increment by..</param>
/// <param name="callback">Callback to invoke when complete.</param>
public void IncrementAchievement(string achId, int steps, Action<bool> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(false);
}
}
/// <summary>
/// Set an achievement to have at least the given number of steps completed.
/// </summary>
/// <remarks>
/// Calling this method while the achievement already has more steps than
/// the provided value is a no-op. Once the achievement reaches the
/// maximum number of steps, the achievement is automatically unlocked,
/// and any further mutation operations are ignored.
/// </remarks>
/// <param name="achId">Achievement identifier.</param>
/// <param name="steps">Steps to increment to at least.</param>
/// <param name="callback">Callback to invoke when complete.</param>
public void SetStepsAtLeast(string achId, int steps, Action<bool> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(false);
}
}
/// <summary>
/// Shows the achievements UI
/// </summary>
/// <param name="callback">Callback to invoke when complete.</param>
public void ShowAchievementsUI(Action<UIStatus> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(UIStatus.VersionUpdateRequired);
}
}
/// <summary>
/// Shows the leaderboard UI
/// </summary>
/// <param name="leaderboardId">Leaderboard identifier.</param>
/// <param name="span">Timespan to display.</param>
/// <param name="callback">Callback to invoke when complete.</param>
public void ShowLeaderboardUI(
string leaderboardId,
LeaderboardTimeSpan span,
Action<UIStatus> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(UIStatus.VersionUpdateRequired);
}
}
/// <summary>
/// Returns the max number of scores returned per call.
/// </summary>
/// <returns>The max results.</returns>
public int LeaderboardMaxResults()
{
return 25;
}
/// <summary>
/// Loads the score data for the given leaderboard.
/// </summary>
/// <param name="leaderboardId">Leaderboard identifier.</param>
/// <param name="start">Start indicating the top scores or player centric</param>
/// <param name="rowCount">Row count.</param>
/// <param name="collection">Collection to display.</param>
/// <param name="timeSpan">Time span.</param>
/// <param name="callback">Callback to invoke when complete.</param>
public void LoadScores(
string leaderboardId,
LeaderboardStart start,
int rowCount,
LeaderboardCollection collection,
LeaderboardTimeSpan timeSpan,
Action<LeaderboardScoreData> callback)
{
LogUsage();
if (callback != null)
{
callback(new LeaderboardScoreData(
leaderboardId,
ResponseStatus.LicenseCheckFailed));
}
}
/// <summary>
/// Loads the more scores for the leaderboard.
/// </summary>
/// <remarks>The token is accessed
/// by calling LoadScores() with a positive row count.
/// </remarks>
/// <param name="token">Token used to start loading scores.</param>
/// <param name="rowCount">Max number of scores to return.
/// This can be limited by the SDK.</param>
/// <param name="callback">Callback to invoke when complete.</param>
public void LoadMoreScores(
ScorePageToken token,
int rowCount,
Action<LeaderboardScoreData> callback)
{
LogUsage();
if (callback != null)
{
callback(new LeaderboardScoreData(
token.LeaderboardId,
ResponseStatus.LicenseCheckFailed));
}
}
/// <summary>
/// Submits the score.
/// </summary>
/// <param name="leaderboardId">Leaderboard identifier.</param>
/// <param name="score">Score to submit.</param>
/// <param name="callback">Callback to invoke when complete.</param>
public void SubmitScore(string leaderboardId, long score, Action<bool> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(false);
}
}
/// <summary>
/// Submits the score for the currently signed-in player
/// to the leaderboard associated with a specific id
/// and metadata (such as something the player did to earn the score).
/// </summary>
/// <param name="leaderboardId">Leaderboard identifier.</param>
/// <param name="score">Score value to submit.</param>
/// <param name="metadata">Metadata about the score.</param>
/// <param name="callback">Callback upon completion.</param>
public void SubmitScore(
string leaderboardId,
long score,
string metadata,
Action<bool> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(false);
}
}
/// <summary>
/// Returns a real-time multiplayer client.
/// </summary>
/// <seealso cref="GooglePlayGames.Multiplayer.IRealTimeMultiplayerClient"></seealso>
/// <returns>The rtmp client.</returns>
public IRealTimeMultiplayerClient GetRtmpClient()
{
LogUsage();
return null;
}
/// <summary>
/// Returns a turn-based multiplayer client.
/// </summary>
/// <returns>The tbmp client.</returns>
public ITurnBasedMultiplayerClient GetTbmpClient()
{
LogUsage();
return null;
}
/// <summary>
/// Gets the saved game client.
/// </summary>
/// <returns>The saved game client.</returns>
public SavedGame.ISavedGameClient GetSavedGameClient()
{
LogUsage();
return null;
}
/// <summary>
/// Gets the events client.
/// </summary>
/// <returns>The events client.</returns>
public GooglePlayGames.BasicApi.Events.IEventsClient GetEventsClient()
{
LogUsage();
return null;
}
/// <summary>
/// Gets the quests client.
/// </summary>
/// <returns>The quests client.</returns>
public GooglePlayGames.BasicApi.Quests.IQuestsClient GetQuestsClient()
{
LogUsage();
return null;
}
/// <summary>
/// Gets the video client.
/// </summary>
/// <returns>The video client.</returns>
public GooglePlayGames.BasicApi.Video.IVideoClient GetVideoClient()
{
LogUsage();
return null;
}
/// <summary>
/// Registers the invitation delegate.
/// </summary>
/// <param name="invitationDelegate">Invitation delegate.</param>
public void RegisterInvitationDelegate(InvitationReceivedDelegate invitationDelegate)
{
LogUsage();
}
/// <summary>
/// Gets the invitation from notification.
/// </summary>
/// <returns>The invitation from notification.</returns>
public Invitation GetInvitationFromNotification()
{
LogUsage();
return null;
}
/// <summary>
/// Determines whether this instance has invitation from notification.
/// </summary>
/// <returns><c>true</c> if this instance has invitation from notification; otherwise, <c>false</c>.</returns>
public bool HasInvitationFromNotification()
{
LogUsage();
return false;
}
/// <summary>
/// Load friends of the authenticated user
/// </summary>
/// <param name="callback">Callback invoked when complete. bool argument
/// indicates success.</param>
public void LoadFriends(Action<bool> callback)
{
LogUsage();
callback(false);
}
/// <summary>
/// Gets the friends.
/// </summary>
/// <returns>The friends.</returns>
public IUserProfile[] GetFriends()
{
LogUsage();
return new IUserProfile[0];
}
/// <summary>
/// Gets the Android API client. Returns null on non-Android players.
/// </summary>
/// <returns>The API client.</returns>
public IntPtr GetApiClient()
{
LogUsage();
return IntPtr.Zero;
}
/// <summary>
/// Logs the usage.
/// </summary>
private static void LogUsage()
{
Logger.d("Received method call on DummyClient - using stub implementation.");
}
}
}
#endif
| |
/*
Copyright 2012 Michael Edwards
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.
*/
//-CRE-
using System;
using Glass.Mapper.Sc.DataMappers;
using Glass.Mapper.Sc.Fields;
using NSubstitute;
using NUnit.Framework;
using Sitecore.Data;
using Sitecore.FakeDb;
using Sitecore.Resources.Media;
namespace Glass.Mapper.Sc.FakeDb.DataMappers
{
[TestFixture]
public class SitecoreFieldFileMapperFixture
{
#region Method - GetField
[Test]
public void GetViewValue_FieldPointsAtFile_ReturnFileObject()
{
//Assign
var templateId = ID.NewID;
var fieldId = ID.NewID;
var targetId = ID.NewID;
var expected = "/~/media/C10794CE624F4F72A2B914336F3FB582.ashx";
var mediaId = new ID("{C10794CE-624F-4F72-A2B9-14336F3FB582}");
using (Db database = new Db
{
new DbTemplate(templateId)
{
{"Field", ""}
},
new Sitecore.FakeDb.DbItem("Target", targetId, templateId),
new DbItem("Media", mediaId)
})
{
Sitecore.Resources.Media.MediaProvider mediaProvider =
Substitute.For<Sitecore.Resources.Media.MediaProvider>();
mediaProvider
.GetMediaUrl(
Arg.Is<Sitecore.Data.Items.MediaItem>(
i => i.ID == mediaId)
)
.Returns(expected);
using (new Sitecore.FakeDb.Resources.Media.MediaProviderSwitcher(mediaProvider))
{
var fieldValue =
"<file mediaid=\"{C10794CE-624F-4F72-A2B9-14336F3FB582}\" src=\"~/media/C10794CE624F4F72A2B914336F3FB582.ashx\" />";
var item = database.GetItem("/sitecore/content/Target");
var field = item.Fields["Field"];
var mapper = new SitecoreFieldFileMapper();
using (new ItemEditing(item, true))
{
field.Value = fieldValue;
}
//Act
var result = mapper.GetField(field, null, null) as File;
//Assert
Assert.AreEqual(mediaId.Guid, result.Id);
Assert.AreEqual(expected, result.Src);
}
}
}
[Test]
public void GetViewValue_FieldEmpty_ReturnEmptyValues()
{
//Assign
var templateId = ID.NewID;
var fieldId = ID.NewID;
var targetId = ID.NewID;
var mediaId = new ID("{C10794CE-624F-4F72-A2B9-14336F3FB582}");
using (Db database = new Db
{
new DbTemplate(templateId)
{
{"Field", ""}
},
new Sitecore.FakeDb.DbItem("Target", targetId, templateId),
new DbItem("Media", mediaId)
})
{
var fieldValue = string.Empty;
var item = database.GetItem("/sitecore/content/Target");
var field = item.Fields["Field"];
var mapper = new SitecoreFieldFileMapper();
using (new ItemEditing(item, true))
{
field.Value = fieldValue;
}
//Act
var result = mapper.GetField(field, null, null) as File;
//Assert
Assert.AreEqual(Guid.Empty, result.Id);
Assert.AreEqual(null, result.Src);
}
}
#endregion
#region Method - SetField
[Test]
public void SetField_FileObjectPass_FieldPopulated()
{
//Assign
var templateId = ID.NewID;
var fieldId = ID.NewID;
var targetId = ID.NewID;
var mediaId = new ID("{C10794CE-624F-4F72-A2B9-14336F3FB582}");
using (Db database = new Db
{
new DbTemplate(templateId)
{
{"Field", ""}
},
new Sitecore.FakeDb.DbItem("Target", targetId, templateId),
new DbItem("Media", mediaId)
})
{
var expected =
"<file mediaid=\"{C10794CE-624F-4F72-A2B9-14336F3FB582}\" src=\"~/media/Test.ashx\" />";
var item = database.GetItem("/sitecore/content/Target");
var field = item.Fields["Field"];
var mapper = new SitecoreFieldFileMapper();
var file = new File()
{
Id = new Guid("{C10794CE-624F-4F72-A2B9-14336F3FB582}")
};
using (new ItemEditing(item, true))
{
field.Value = string.Empty;
}
Sitecore.Resources.Media.MediaProvider mediaProvider = Substitute.For<Sitecore.Resources.Media.MediaProvider>();
mediaProvider
.GetMediaUrl(Arg.Is<Sitecore.Data.Items.MediaItem>(i => i.ID == mediaId), Arg.Any<MediaUrlOptions>())
.Returns("~/media/Test.ashx");
using (new Sitecore.FakeDb.Resources.Media.MediaProviderSwitcher(mediaProvider))
{
//Act
using (new ItemEditing(item, true))
{
mapper.SetField(field, file, null, null);
}
//Assert
}
AssertHtml.AreHtmlElementsEqual(expected, item["Field"], "file");
}
}
[Test]
public void SetField_FileNull_FileIsEmpty()
{
//Assign
var templateId = ID.NewID;
var fieldId = ID.NewID;
var targetId = ID.NewID;
using (Db database = new Db
{
new DbTemplate(templateId)
{
{"Field", ""}
},
new Sitecore.FakeDb.DbItem("Target", targetId, templateId),
})
{
var expected = string.Empty;
var item = database.GetItem("/sitecore/content/Target");
var field = item.Fields["Field"];
var mapper = new SitecoreFieldFileMapper();
var file = (File) null;
using (new ItemEditing(item, true))
{
field.Value = string.Empty;
}
//Act
using (new ItemEditing(item, true))
{
mapper.SetField(field, file, null, null);
}
//Assert
Assert.AreEqual(expected, item["Field"]);
}
}
[Test]
public void SetField_FileEmptyGuid_FieldLinkRemoved()
{
//Assign
var templateId = ID.NewID;
var fieldId = ID.NewID;
var targetId = ID.NewID;
using (Db database = new Db
{
new DbTemplate(templateId)
{
{"Field", ""}
},
new Sitecore.FakeDb.DbItem("Target", targetId, templateId),
new Sitecore.FakeDb.DbItem("File", new ID("{C10794CE-624F-4F72-A2B9-14336F3FB582}"), templateId),
})
{
var fieldValue =
"<file mediaid=\"{C10794CE-624F-4F72-A2B9-14336F3FB582}\" src=\"~/media/C10794CE624F4F72A2B914336F3FB582.ashx\" />";
var expected = string.Empty;
var item = database.GetItem("/sitecore/content/Target");
var field = item.Fields["Field"];
var mapper = new SitecoreFieldFileMapper();
var file = new File()
{
Id = Guid.Empty
};
using (new ItemEditing(item, true))
{
field.Value = fieldValue;
}
//Act
using (new ItemEditing(item, true))
{
mapper.SetField(field, file, null, null);
}
//Assert
Assert.AreEqual(expected, item["Field"]);
}
}
[Test]
public void SetField_FileContainsMissinfMedia_ExpectionThrown()
{
//Assign
var templateId = ID.NewID;
var fieldId = ID.NewID;
var targetId = ID.NewID;
using (Db database = new Db
{
new DbTemplate(templateId)
{
{"Field", ""}
},
new Sitecore.FakeDb.DbItem("Target", targetId, templateId),
})
{
var expected = string.Empty;
var item = database.GetItem("/sitecore/content/Target");
var field = item.Fields["Field"];
var mapper = new SitecoreFieldFileMapper();
var file = new File()
{
Id = Guid.NewGuid()
};
using (new ItemEditing(item, true))
{
field.Value = string.Empty;
}
//Act
using (new ItemEditing(item, true))
{
Assert.Throws<MapperException>(() =>
{
mapper.SetField(field, file, null, null);
});
}
//Assert
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO;
using System.IO.Ports;
//using System.Diagnostics;
namespace T5CANLib.CAN
{
/// <summary>
/// EasySync232Device is an implementation of ICANDevice for the Lawicel EasySync232 device
/// (www.EasySync232.com).
///
/// All incomming messages are published to registered ICANListeners.
/// </summary>
public class EasySync232Device : ICANDevice, IDisposable
{
// ReceiveState m_rxstate;
SerialPort m_port = new SerialPort();
//static uint m_deviceHandle = 0;
Thread m_readThread;
Object m_synchObject = new Object();
bool m_endThread = false;
private bool m_DoLogging = false;
private string m_startuppath = @"C:\Program files\Dilemma\CarPCControl";
private int m_baudrate = 57600;
private string m_portnumber = "COM1";
//private bool m_frameAvailable = false;
override public void setPortNumber(string portnumber)
{
Portnumber = portnumber;
}
public string Portnumber
{
get { return m_portnumber; }
set
{
m_portnumber = value;
if (m_port.IsOpen)
{
m_port.Close();
m_port.PortName = m_portnumber;
m_port.Open();
}
else
{
m_port.PortName = m_portnumber;
}
}
}
public int Baudrate
{
get { return m_baudrate; }
set
{
m_baudrate = value;
if (m_port.IsOpen)
{
m_port.Close();
m_port.BaudRate = m_baudrate;
m_port.Open();
}
else
{
m_port.BaudRate = m_baudrate;
}
}
}
public string Startuppath
{
get { return m_startuppath; }
set { m_startuppath = value; }
}
public bool DoLogging
{
get { return m_DoLogging; }
set { m_DoLogging = value; }
}
/// <summary>
/// Constructor for EasySync232Device.
/// </summary>
public EasySync232Device()
{
m_port.ErrorReceived += new SerialErrorReceivedEventHandler(m_port_ErrorReceived);
m_port.PinChanged += new SerialPinChangedEventHandler(m_port_PinChanged);
m_port.DataReceived += new SerialDataReceivedEventHandler(m_port_DataReceived);
m_port.WriteTimeout = 100;
m_port.ReadTimeout = 100;
m_port.NewLine = "\r";
//m_port.ReceivedBytesThreshold = 1;
/* m_readThread = new Thread(readMessages);
try
{
m_readThread.Priority = ThreadPriority.Normal; // realtime enough
}
catch (Exception E)
{
Console.WriteLine(E.Message);
}*/
}
void m_port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
/*if (e.EventType == SerialData.Chars)
{
int bytesavailable = m_port.BytesToRead;
for (int i = 0; i < bytesavailable; i++)
{
byte rxbyte = (byte)m_port.ReadByte();
switch (m_rxstate)
{
}
}
//m_frameAvailable = true;
}*/
}
void m_port_PinChanged(object sender, SerialPinChangedEventArgs e)
{
}
void m_port_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
{
}
/// <summary>
/// Destructor for EasySync232Device.
/// </summary>
~EasySync232Device()
{
lock (m_synchObject)
{
m_endThread = true;
}
close();
}
public enum FlushFlags : byte
{
FLUSH_WAIT = 0,
FLUSH_DONTWAIT = 1,
FLUSH_EMPTY_INQUEUE = 2
}
public override void Delete()
{
}
public void Dispose()
{
}
public override float GetADCValue(uint channel)
{
return 0F;
}
// not supported by lawicel
public override float GetThermoValue()
{
return 0F;
}
override public int GetNumberOfAdapters()
{
return 1;
}
override public void EnableLogging(string path2log)
{
m_DoLogging = true;
m_startuppath = path2log;
}
override public void DisableLogging()
{
m_DoLogging = false;
}
override public void clearReceiveBuffer()
{
if (m_port.IsOpen)
{
m_port.DiscardInBuffer();
}
}
override public void clearTransmitBuffer()
{
if (m_port.IsOpen)
{
m_port.DiscardOutBuffer();
}
}
// int thrdcnt = 0;
/// <summary>
/// readMessages is the "run" method of this class. It reads all incomming messages
/// and publishes them to registered ICANListeners.
/// </summary>
public void readMessages()
{
//int readResult = 0;
LAWICEL.CANMsg r_canMsg = new LAWICEL.CANMsg();
CANMessage canMessage = new CANMessage();
while (true)
{
lock (m_synchObject)
{
if (m_endThread)
{
m_endThread = false;
return;
}
}
if (m_port.IsOpen)
{
// read the status?
string line = string.Empty;
m_port.Write("\r");
m_port.Write("A\r"); // poll for all pending CAN messages
//Console.WriteLine("Polled for frames");
Thread.Sleep(0);
bool endofFrames = false;
while(!endofFrames)
{
try
{
if (m_port.BytesToRead > 0)
{
line = m_port.ReadLine();
Console.Write("RX: ");
for (int tel = 0; tel < line.Length; tel++)
{
byte b = (byte)line[tel];
Console.Write(b.ToString("X2") + " " );
}
Console.WriteLine("") ;
Thread.Sleep(0);
if (line.Length > 0)
{
if (line[0] == '\x07' || line[0] == '\r' || line[0] == 'A')
{
//Console.WriteLine("End of messages");
endofFrames = true;
}
else
{
//t00C8C6003E0000000000
//Console.WriteLine("line: " + line + " len: " + line.Length.ToString());
if (line.Length == 21)
{
// three bytes identifier
r_canMsg.id = (uint)Convert.ToInt32(line.Substring(1, 3), 16);
r_canMsg.len = (byte)Convert.ToInt32(line.Substring(4, 1), 16);
ulong data = 0;
// add all the bytes
data |= (ulong)(byte)Convert.ToInt32(line.Substring(5, 2), 16);
data |= (ulong)(byte)Convert.ToInt32(line.Substring(7, 2), 16) << 1 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(9, 2), 16) << 2 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(11, 2), 16) << 3 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(13, 2), 16) << 4 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(15, 2), 16) << 5 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(17, 2), 16) << 6 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(19, 2), 16) << 7 * 8;
r_canMsg.data = data;
canMessage.setID(r_canMsg.id);
canMessage.setLength(r_canMsg.len);
canMessage.setTimeStamp(r_canMsg.timestamp);
canMessage.setFlags(r_canMsg.flags);
canMessage.setData(r_canMsg.data);
if (m_DoLogging)
{
DumpCanMsg(r_canMsg, false);
}
lock (m_listeners)
{
foreach (ICANListener listener in m_listeners)
{
listener.handleMessage(canMessage);
}
}
}
}
}
}
}
catch (Exception E)
{
//Console.WriteLine("Failed to read frames from CANbus: " + E.Message);
}
Thread.Sleep(0);
}
}
Thread.Sleep(1);
}
}
private string GetCharString(int value)
{
char c = Convert.ToChar(value);
string charstr = c.ToString();
if (c == 0x0d) charstr = "<CR>";
else if (c == 0x0a) charstr = "<LF>";
else if (c == 0x00) charstr = "<NULL>";
else if (c == 0x01) charstr = "<SOH>";
else if (c == 0x02) charstr = "<STX>";
else if (c == 0x03) charstr = "<ETX>";
else if (c == 0x04) charstr = "<EOT>";
else if (c == 0x05) charstr = "<ENQ>";
else if (c == 0x06) charstr = "<ACK>";
else if (c == 0x07) charstr = "<BEL>";
else if (c == 0x08) charstr = "<BS>";
else if (c == 0x09) charstr = "<TAB>";
else if (c == 0x0B) charstr = "<VT>";
else if (c == 0x0C) charstr = "<FF>";
else if (c == 0x0E) charstr = "<SO>";
else if (c == 0x0F) charstr = "<SI>";
else if (c == 0x10) charstr = "<DLE>";
else if (c == 0x11) charstr = "<DC1>";
else if (c == 0x12) charstr = "<DC2>";
else if (c == 0x13) charstr = "<DC3>";
else if (c == 0x14) charstr = "<DC4>";
else if (c == 0x15) charstr = "<NACK>";
else if (c == 0x16) charstr = "<SYN>";
else if (c == 0x17) charstr = "<ETB>";
else if (c == 0x18) charstr = "<CAN>";
else if (c == 0x19) charstr = "<EM>";
else if (c == 0x1A) charstr = "<SUB>";
else if (c == 0x1B) charstr = "<ESC>";
else if (c == 0x1C) charstr = "<FS>";
else if (c == 0x1D) charstr = "<GS>";
else if (c == 0x1E) charstr = "<RS>";
else if (c == 0x1F) charstr = "<US>";
else if (c == 0x7F) charstr = "<DEL>";
return charstr;
}
private void DumpCanMsg(LAWICEL.CANMsg r_canMsg, bool IsTransmit)
{
DateTime dt = DateTime.Now;
try
{
using (StreamWriter sw = new StreamWriter(Path.Combine(m_startuppath, dt.Year.ToString("D4") + dt.Month.ToString("D2") + dt.Day.ToString("D2") + "-CanTrace.log"), true))
{
if (IsTransmit)
{
// get the byte transmitted
int transmitvalue = (int)(r_canMsg.data & 0x000000000000FF00);
transmitvalue /= 256;
sw.WriteLine(dt.ToString("dd/MM/yyyy HH:mm:ss") + " TX: id=" + r_canMsg.id.ToString("D2") + " len= " + r_canMsg.len.ToString("X8") + " data=" + r_canMsg.data.ToString("X16") + " " + r_canMsg.flags.ToString("X2") + " character = " + GetCharString(transmitvalue) + "\t ts: " + r_canMsg.timestamp.ToString("X16") + " flags: " + r_canMsg.flags.ToString("X2"));
}
else
{
// get the byte received
int receivevalue = (int)(r_canMsg.data & 0x0000000000FF0000);
receivevalue /= (256 * 256);
sw.WriteLine(dt.ToString("dd/MM/yyyy HH:mm:ss") + " RX: id=" + r_canMsg.id.ToString("D2") + " len= " + r_canMsg.len.ToString("X8") + " data=" + r_canMsg.data.ToString("X16") + " " + r_canMsg.flags.ToString("X2") + " character = " + GetCharString(receivevalue) + "\t ts: " + r_canMsg.timestamp.ToString("X16") + " flags: " + r_canMsg.flags.ToString("X2"));
}
}
}
catch (Exception E)
{
Console.WriteLine("Failed to write to logfile: " + E.Message);
}
}
/// <summary>
/// The open method tries to connect to both busses to see if one of them is connected and
/// active. The first strategy is to listen for any CAN message. If this fails there is a
/// check to see if the application is started after an interrupted flash session. This is
/// done by sending a message to set address and length (only for P-bus).
/// </summary>
/// <returns>OpenResult.OK is returned on success. Otherwise OpenResult.OpenError is
/// returned.</returns>
override public OpenResult open()
{
Console.WriteLine("Opening port: " + m_portnumber + " in EasySync232");
if (m_port.IsOpen)
{
Console.WriteLine("Port was open, closing first");
m_port.Write("\r");
m_port.Write("C\r");
Thread.Sleep(100);
m_port.Close();
}
m_port.BaudRate = m_baudrate;
m_port.PortName = m_portnumber;
m_port.Handshake = Handshake.None;
Console.WriteLine("Opening comport");
try
{
m_port.Open();
if (m_port.IsOpen)
{
try
{
Console.WriteLine("Setting CAN bitrate");
m_port.Write("\r");
Thread.Sleep(1);
//m_port.Write("s004037\r"); // set CAN baudrate to 615 kb/s 0x40:0x37 can232
//m_port.Write("s014929\r"); // set CAN baudrate to 615 kb/s home calc
//m_port.Write("s019D01\r"); // set CAN baudrate to 615 kb/s through calculcator
m_port.Write("s00B907\r"); // 631.6 kb (easysync info)
//m_port.Write("s00BA07\r"); // 600.0 kb (easysync info)
// now open the CAN channel
Thread.Sleep(100);
if ((byte)m_port.ReadByte() == 0x07) // error
{
Console.WriteLine("Failed to set CAN bitrate to 615 Kb/s");
}
Console.WriteLine("Opening CAN channel");
m_port.Write("\r");
Thread.Sleep(1);
m_port.Write("O\r");
Thread.Sleep(100);
if ((byte)m_port.ReadByte() == 0x07) // error
{
Console.WriteLine("Failed to open CAN channel");
return OpenResult.OpenError;
}
// need to check is channel opened!!!
Console.WriteLine("Creating new reader thread");
m_port.Write("E\r"); // clear buffers (ECHO command)
m_readThread = new Thread(readMessages);
try
{
m_readThread.Priority = ThreadPriority.Normal; // realtime enough
}
catch (Exception E)
{
Console.WriteLine(E.Message);
}
if (m_readThread.ThreadState == ThreadState.Unstarted)
m_readThread.Start();
return OpenResult.OK;
}
catch (Exception E)
{
Console.WriteLine("Failed to set canbaudrate: " + E.Message);
}
try
{
m_port.Close();
}
catch (Exception cE)
{
Console.WriteLine("Failed to close comport: " + cE.Message);
}
return OpenResult.OpenError;
}
}
catch (Exception oE)
{
Console.WriteLine("Failed to open comport: " + oE.Message);
}
return OpenResult.OpenError;
}
/// <summary>
/// The close method closes the EasySync232 device.
/// </summary>
/// <returns>CloseResult.OK on success, otherwise CloseResult.CloseError.</returns>
override public CloseResult close()
{
Console.WriteLine("Close called in EasySync232Device");
if (m_readThread != null)
{
if (m_readThread.ThreadState != ThreadState.Stopped && m_readThread.ThreadState != ThreadState.StopRequested)
{
lock (m_synchObject)
{
m_endThread = true;
}
// m_readThread.Abort();
}
}
Console.WriteLine("Thread ended");
if (m_port.IsOpen)
{
Console.WriteLine("Thread Closing port (1)");
m_port.Write("\r");
m_port.Write("C\r");
Thread.Sleep(100);
Console.WriteLine("Thread Closing port (2)");
m_port.Close();
Console.WriteLine("Thread Closing port (3)");
return CloseResult.OK;
}
return CloseResult.CloseError;
}
/// <summary>
/// isOpen checks if the device is open.
/// </summary>
/// <returns>true if the device is open, otherwise false.</returns>
override public bool isOpen()
{
return m_port.IsOpen;
}
/// <summary>
/// sendMessage send a CANMessage.
/// </summary>
/// <param name="a_message">A CANMessage.</param>
/// <returns>true on success, othewise false.</returns>
override public bool sendMessage(CANMessage a_message)
{
LAWICEL.CANMsg msg = new LAWICEL.CANMsg();
msg.id = a_message.getID();
msg.len = a_message.getLength();
msg.flags = a_message.getFlags();
msg.data = a_message.getData();
if (m_DoLogging)
{
DumpCanMsg(msg, true);
}
if (m_port.IsOpen)
{
m_port.Write("\r");
string txstring = "t";
txstring += msg.id.ToString("X3");
txstring += "8"; // always 8 bytes to transmit
for (int t = 0; t < 8; t++)
{
byte b = (byte)(((msg.data >> t * 8) & 0x0000000000000000FF));
txstring += b.ToString("X2");
}
txstring += "\r";
m_port.Write(txstring);
// Console.WriteLine("Send: " + txstring);
return true;
}
return false;
/*
int writeResult;
writeResult = LAWICEL.canusb_Write(m_deviceHandle, ref msg);
if (writeResult == LAWICEL.ERROR_CANUSB_OK)
return true;
else
return false;
*/
}
/// <summary>
/// waitForMessage waits for a specific CAN message give by a CAN id.
/// </summary>
/// <param name="a_canID">The CAN id to listen for</param>
/// <param name="timeout">Listen timeout</param>
/// <param name="r_canMsg">The CAN message with a_canID that we where listening for.</param>
/// <returns>The CAN id for the message we where listening for, otherwise 0.</returns>
private uint waitForMessage(uint a_canID, uint timeout, out LAWICEL.CANMsg r_canMsg)
{
CANMessage canMessage = new CANMessage();
string line = string.Empty;
int readResult = 0;
int nrOfWait = 0;
while (nrOfWait < timeout)
{
m_port.Write("\r");
m_port.Write("P\r");
bool endofFrames = false;
while (!endofFrames)
{
Console.WriteLine("reading line");
line = m_port.ReadLine();
Console.WriteLine("line: " + line + " len: " + line.Length.ToString());
if (line[0] == '\x07' || line[0] == '\r' || line[0] == 'A')
{
endofFrames = true;
}
else
{
if (line.Length == 14)
{
// three bytes identifier
r_canMsg = new LAWICEL.CANMsg();
r_canMsg.id = (uint)Convert.ToInt32(line.Substring(1, 3), 16);
r_canMsg.len = (byte)Convert.ToInt32(line.Substring(4, 1), 16);
ulong data = 0;
// add all the bytes
data |= (ulong)(byte)Convert.ToInt32(line.Substring(5, 2), 16) << 7 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(7, 2), 16) << 6 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(9, 2), 16) << 5 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(11, 2), 16) << 4 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(13, 2), 16) << 3 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(15, 2), 16) << 2 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(17, 2), 16) << 1 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(19, 2), 16);
r_canMsg.data = data;
canMessage.setID(r_canMsg.id);
canMessage.setLength(r_canMsg.len);
//canMessage.setTimeStamp(0);
canMessage.setFlags(0);
canMessage.setData(r_canMsg.data);
if (m_DoLogging)
{
DumpCanMsg(r_canMsg, false);
}
if (r_canMsg.id != a_canID)
continue;
return (uint)r_canMsg.id;
}
}
}
Thread.Sleep(1);
nrOfWait++;
}
r_canMsg = new LAWICEL.CANMsg();
return 0;
}
/// <summary>
/// waitAnyMessage waits for any message to be received.
/// </summary>
/// <param name="timeout">Listen timeout</param>
/// <param name="r_canMsg">The CAN message that was first received</param>
/// <returns>The CAN id for the message received, otherwise 0.</returns>
private uint waitAnyMessage(uint timeout, out LAWICEL.CANMsg r_canMsg)
{
CANMessage canMessage = new CANMessage();
string line = string.Empty;
int readResult = 0;
int nrOfWait = 0;
while (nrOfWait < timeout)
{
m_port.Write("\r");
m_port.Write("P\r");
bool endofFrames = false;
while (!endofFrames)
{
Console.WriteLine("reading line");
line = m_port.ReadLine();
Console.WriteLine("line: " + line + " len: " + line.Length.ToString());
if (line[0] == '\x07' || line[0] == '\r' || line[0] == 'A')
{
endofFrames = true;
}
else
{
if (line.Length == 14)
{
// three bytes identifier
r_canMsg = new LAWICEL.CANMsg();
r_canMsg.id = (uint)Convert.ToInt32(line.Substring(1, 3), 16);
r_canMsg.len = (byte)Convert.ToInt32(line.Substring(4, 1), 16);
ulong data = 0;
// add all the bytes
data |= (ulong)(byte)Convert.ToInt32(line.Substring(5, 2), 16) << 7 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(7, 2), 16) << 6 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(9, 2), 16) << 5 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(11, 2), 16) << 4 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(13, 2), 16) << 3 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(15, 2), 16) << 2 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(17, 2), 16) << 1 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(19, 2), 16);
r_canMsg.data = data;
canMessage.setID(r_canMsg.id);
canMessage.setLength(r_canMsg.len);
//canMessage.setTimeStamp(r_canMsg.timestamp);
canMessage.setFlags(0);
canMessage.setData(r_canMsg.data);
if (m_DoLogging)
{
DumpCanMsg(r_canMsg, false);
}
return (uint)r_canMsg.id;
}
}
}
Thread.Sleep(1);
nrOfWait++;
}
r_canMsg = new LAWICEL.CANMsg();
return 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.IO;
using System.Net.Sockets;
namespace System.Net
{
/// <summary>
/// <para>
/// The FtpDataStream class implements the FTP data connection.
/// </para>
/// </summary>
internal class FtpDataStream : Stream, ICloseEx
{
private FtpWebRequest _request;
private NetworkStream _networkStream;
private bool _writeable;
private bool _readable;
private bool _isFullyRead = false;
private bool _closing = false;
private const int DefaultCloseTimeout = -1;
internal FtpDataStream(NetworkStream networkStream, FtpWebRequest request, TriState writeOnly)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this);
_readable = true;
_writeable = true;
if (writeOnly == TriState.True)
{
_readable = false;
}
else if (writeOnly == TriState.False)
{
_writeable = false;
}
_networkStream = networkStream;
_request = request;
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
((ICloseEx)this).CloseEx(CloseExState.Normal);
else
((ICloseEx)this).CloseEx(CloseExState.Abort | CloseExState.Silent);
}
finally
{
base.Dispose(disposing);
}
}
//TODO: Add this to FxCopBaseline.cs once https://github.com/dotnet/roslyn/issues/15728 is fixed
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2002:DoNotLockOnObjectsWithWeakIdentity")]
void ICloseEx.CloseEx(CloseExState closeState)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"state = {closeState}");
lock (this)
{
if (_closing == true)
return;
_closing = true;
_writeable = false;
_readable = false;
}
try
{
try
{
if ((closeState & CloseExState.Abort) == 0)
_networkStream.Close(DefaultCloseTimeout);
else
_networkStream.Close(0);
}
finally
{
_request.DataStreamClosed(closeState);
}
}
catch (Exception exception)
{
bool doThrow = true;
WebException webException = exception as WebException;
if (webException != null)
{
FtpWebResponse response = webException.Response as FtpWebResponse;
if (response != null)
{
if (!_isFullyRead
&& response.StatusCode == FtpStatusCode.ConnectionClosed)
doThrow = false;
}
}
if (doThrow)
if ((closeState & CloseExState.Silent) == 0)
throw;
}
}
private void CheckError()
{
if (_request.Aborted)
{
throw ExceptionHelper.RequestAbortedException;
}
}
public override bool CanRead
{
get
{
return _readable;
}
}
public override bool CanSeek
{
get
{
return _networkStream.CanSeek;
}
}
public override bool CanWrite
{
get
{
return _writeable;
}
}
public override long Length
{
get
{
return _networkStream.Length;
}
}
public override long Position
{
get
{
return _networkStream.Position;
}
set
{
_networkStream.Position = value;
}
}
public override long Seek(long offset, SeekOrigin origin)
{
CheckError();
try
{
return _networkStream.Seek(offset, origin);
}
catch
{
CheckError();
throw;
}
}
public override int Read(byte[] buffer, int offset, int size)
{
CheckError();
int readBytes;
try
{
readBytes = _networkStream.Read(buffer, offset, size);
}
catch
{
CheckError();
throw;
}
if (readBytes == 0)
{
_isFullyRead = true;
Close();
}
return readBytes;
}
public override void Write(byte[] buffer, int offset, int size)
{
CheckError();
try
{
_networkStream.Write(buffer, offset, size);
}
catch
{
CheckError();
throw;
}
}
private void AsyncReadCallback(IAsyncResult ar)
{
LazyAsyncResult userResult = (LazyAsyncResult)ar.AsyncState;
try
{
try
{
int readBytes = _networkStream.EndRead(ar);
if (readBytes == 0)
{
_isFullyRead = true;
Close(); // This should block for pipeline completion
}
userResult.InvokeCallback(readBytes);
}
catch (Exception exception)
{
// Complete with error. If already completed rethrow on the worker thread
if (!userResult.IsCompleted)
userResult.InvokeCallback(exception);
}
}
catch { }
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, Object state)
{
CheckError();
LazyAsyncResult userResult = new LazyAsyncResult(this, state, callback);
try
{
_networkStream.BeginRead(buffer, offset, size, new AsyncCallback(AsyncReadCallback), userResult);
}
catch
{
CheckError();
throw;
}
return userResult;
}
public override int EndRead(IAsyncResult ar)
{
try
{
object result = ((LazyAsyncResult)ar).InternalWaitForCompletion();
if (result is Exception)
throw (Exception)result;
return (int)result;
}
finally
{
CheckError();
}
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, Object state)
{
CheckError();
try
{
return _networkStream.BeginWrite(buffer, offset, size, callback, state);
}
catch
{
CheckError();
throw;
}
}
public override void EndWrite(IAsyncResult asyncResult)
{
try
{
_networkStream.EndWrite(asyncResult);
}
finally
{
CheckError();
}
}
public override void Flush()
{
_networkStream.Flush();
}
public override void SetLength(long value)
{
_networkStream.SetLength(value);
}
public override bool CanTimeout
{
get
{
return _networkStream.CanTimeout;
}
}
public override int ReadTimeout
{
get
{
return _networkStream.ReadTimeout;
}
set
{
_networkStream.ReadTimeout = value;
}
}
public override int WriteTimeout
{
get
{
return _networkStream.WriteTimeout;
}
set
{
_networkStream.WriteTimeout = value;
}
}
internal void SetSocketTimeoutOption(int timeout)
{
_networkStream.ReadTimeout = timeout;
_networkStream.WriteTimeout = timeout;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Roslyn.Test.PdbUtilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection.Metadata;
using Xunit;
using Resources = Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests.Resources;
using System.Reflection;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class WinMdTests : ExpressionCompilerTestBase
{
/// <summary>
/// Handle runtime assemblies rather than Windows.winmd
/// (compile-time assembly) since those are the assemblies
/// loaded in the debuggee.
/// </summary>
[WorkItem(981104)]
[ConditionalFact(typeof(OSVersionWin8))]
public void Win8RuntimeAssemblies()
{
var source =
@"class C
{
static void M(Windows.Storage.StorageFolder f, Windows.Foundation.Collections.PropertySet p)
{
}
}";
var compilation0 = CreateCompilationWithMscorlib(
source,
options: TestOptions.DebugDll,
assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(),
references: WinRtRefs);
var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections");
Assert.True(runtimeAssemblies.Length >= 2);
byte[] exeBytes;
byte[] pdbBytes;
ImmutableArray<MetadataReference> references;
compilation0.EmitAndGetReferences(out exeBytes, out pdbBytes, out references);
var runtime = CreateRuntimeInstance(
ExpressionCompilerUtilities.GenerateUniqueName(),
ImmutableArray.Create(MscorlibRef).Concat(runtimeAssemblies), // no reference to Windows.winmd
exeBytes,
new SymReader(pdbBytes));
var context = CreateMethodContext(runtime, "C.M");
string error;
var testData = new CompilationTestData();
context.CompileExpression("(p == null) ? f : null", out error, testData);
Assert.Null(error);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0005
IL_0003: ldnull
IL_0004: ret
IL_0005: ldarg.0
IL_0006: ret
}");
}
[ConditionalFact(typeof(OSVersionWin8))]
public void Win8RuntimeAssemblies_ExternAlias()
{
var source =
@"extern alias X;
class C
{
static void M(X::Windows.Storage.StorageFolder f)
{
}
}";
var compilation0 = CreateCompilationWithMscorlib(
source,
options: TestOptions.DebugDll,
assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(),
references: WinRtRefs.Select(r => r.Display == "Windows" ? r.WithAliases(new[] { "X" }) : r));
var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage");
Assert.True(runtimeAssemblies.Length >= 1);
byte[] exeBytes;
byte[] pdbBytes;
ImmutableArray<MetadataReference> references;
compilation0.EmitAndGetReferences(out exeBytes, out pdbBytes, out references);
var runtime = CreateRuntimeInstance(
ExpressionCompilerUtilities.GenerateUniqueName(),
ImmutableArray.Create(MscorlibRef).Concat(runtimeAssemblies), // no reference to Windows.winmd
exeBytes,
new SymReader(pdbBytes));
var context = CreateMethodContext(runtime, "C.M");
string error;
var testData = new CompilationTestData();
context.CompileExpression("X::Windows.Storage.FileProperties.PhotoOrientation.Unspecified", out error, testData);
Assert.Null(error);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: ret
}");
}
[Fact]
public void Win8OnWin8()
{
CompileTimeAndRuntimeAssemblies(
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()),
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows_Data)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows_Storage)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()),
"Windows.Storage");
}
[Fact]
public void Win8OnWin10()
{
CompileTimeAndRuntimeAssemblies(
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()),
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Data)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Storage)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()),
"Windows.Storage");
}
[WorkItem(1108135)]
[Fact]
public void Win10OnWin10()
{
CompileTimeAndRuntimeAssemblies(
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Data)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Storage)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()),
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()),
"Windows");
}
private void CompileTimeAndRuntimeAssemblies(
ImmutableArray<MetadataReference> compileReferences,
ImmutableArray<MetadataReference> runtimeReferences,
string storageAssemblyName)
{
var source =
@"class C
{
static void M(LibraryA.A a, LibraryB.B b, Windows.Data.Text.TextSegment t, Windows.Storage.StorageFolder f)
{
}
}";
var runtime = CreateRuntime(source, compileReferences, runtimeReferences);
var context = CreateMethodContext(runtime, "C.M");
string error;
var testData = new CompilationTestData();
context.CompileExpression("(object)a ?? (object)b ?? (object)t ?? f", out error, testData);
Assert.Null(error);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldarg.0
IL_0001: dup
IL_0002: brtrue.s IL_0010
IL_0004: pop
IL_0005: ldarg.1
IL_0006: dup
IL_0007: brtrue.s IL_0010
IL_0009: pop
IL_000a: ldarg.2
IL_000b: dup
IL_000c: brtrue.s IL_0010
IL_000e: pop
IL_000f: ldarg.3
IL_0010: ret
}");
testData = new CompilationTestData();
var result = context.CompileExpression("default(Windows.Storage.StorageFolder)", out error, testData);
Assert.Null(error);
var methodData = testData.GetMethodData("<>x.<>m0");
methodData.VerifyIL(
@"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldnull
IL_0001: ret
}");
// Check return type is from runtime assembly.
var assemblyReference = AssemblyMetadata.CreateFromImage(result.Assembly).GetReference();
var compilation = CSharpCompilation.Create(
assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(),
references: runtimeReferences.Concat(ImmutableArray.Create<MetadataReference>(assemblyReference)));
var assembly = ImmutableArray.CreateRange(result.Assembly);
using (var metadata = ModuleMetadata.CreateFromImage(ImmutableArray.CreateRange(assembly)))
{
var reader = metadata.MetadataReader;
var typeDef = reader.GetTypeDef("<>x");
var methodHandle = reader.GetMethodDefHandle(typeDef, "<>m0");
var module = (PEModuleSymbol)compilation.GetMember("<>x").ContainingModule;
var metadataDecoder = new MetadataDecoder(module);
SignatureHeader signatureHeader;
BadImageFormatException metadataException;
var parameters = metadataDecoder.GetSignatureForMethod(methodHandle, out signatureHeader, out metadataException);
Assert.Equal(parameters.Length, 5);
var actualReturnType = parameters[0].Type;
Assert.Equal(actualReturnType.TypeKind, TypeKind.Class); // not error
var expectedReturnType = compilation.GetMember("Windows.Storage.StorageFolder");
Assert.Equal(expectedReturnType, actualReturnType);
Assert.Equal(storageAssemblyName, actualReturnType.ContainingAssembly.Name);
}
}
/// <summary>
/// Assembly-qualified name containing "ContentType=WindowsRuntime",
/// and referencing runtime assembly.
/// </summary>
[WorkItem(1116143)]
[ConditionalFact(typeof(OSVersionWin8))]
public void AssemblyQualifiedName()
{
var source =
@"class C
{
static void M(Windows.Storage.StorageFolder f, Windows.Foundation.Collections.PropertySet p)
{
}
}";
var runtime = CreateRuntime(
source,
ImmutableArray.CreateRange(WinRtRefs),
ImmutableArray.Create(MscorlibRef).Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections")));
var context = CreateMethodContext(
runtime,
"C.M");
var aliases = ImmutableArray.Create(
VariableAlias("s", "Windows.Storage.StorageFolder, Windows.Storage, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"),
VariableAlias("d", "Windows.Foundation.DateTime, Windows.Foundation, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"));
string error;
var testData = new CompilationTestData();
context.CompileExpression(
"(object)s.Attributes ?? d.UniversalTime",
DkmEvaluationFlags.TreatAsExpression,
aliases,
out error,
testData);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 55 (0x37)
.maxstack 2
IL_0000: ldstr ""s""
IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_000a: castclass ""Windows.Storage.StorageFolder""
IL_000f: callvirt ""Windows.Storage.FileAttributes Windows.Storage.StorageFolder.Attributes.get""
IL_0014: box ""Windows.Storage.FileAttributes""
IL_0019: dup
IL_001a: brtrue.s IL_0036
IL_001c: pop
IL_001d: ldstr ""d""
IL_0022: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_0027: unbox.any ""Windows.Foundation.DateTime""
IL_002c: ldfld ""long Windows.Foundation.DateTime.UniversalTime""
IL_0031: box ""long""
IL_0036: ret
}");
}
[WorkItem(1117084)]
[Fact]
public void OtherFrameworkAssembly()
{
var source =
@"class C
{
static void M(Windows.UI.Xaml.FrameworkElement f)
{
}
}";
var runtime = CreateRuntime(
source,
ImmutableArray.CreateRange(WinRtRefs),
ImmutableArray.Create(MscorlibRef).Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Foundation", "Windows.UI", "Windows.UI.Xaml")));
var context = CreateMethodContext(runtime, "C.M");
string error;
ResultProperties resultProperties;
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
var testData = new CompilationTestData();
var result = context.CompileExpression(
"f.RenderSize",
DkmEvaluationFlags.TreatAsExpression,
NoAliases,
DebuggerDiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData);
var expectedAssemblyIdentity = WinRtRefs.Single(r => r.Display == "System.Runtime.WindowsRuntime.dll").GetAssemblyIdentity();
Assert.Equal(expectedAssemblyIdentity, missingAssemblyIdentities.Single());
}
[WorkItem(1154988)]
[ConditionalFact(typeof(OSVersionWin8))]
public void WinMdAssemblyReferenceRequiresRedirect()
{
var source =
@"class C : Windows.UI.Xaml.Controls.UserControl
{
static void M(C c)
{
}
}";
var runtime = CreateRuntime(source,
ImmutableArray.Create(WinRtRefs),
ImmutableArray.Create(MscorlibRef).Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.UI", "Windows.UI.Xaml")));
string errorMessage;
var testData = new CompilationTestData();
ExpressionCompilerTestHelpers.CompileExpressionWithRetry(
runtime.Modules.SelectAsArray(m => m.MetadataBlock),
"c.Dispatcher",
ImmutableArray<Alias>.Empty,
(metadataBlocks, _) =>
{
return CreateMethodContext(runtime, "C.M");
},
(AssemblyIdentity assembly, out uint size) =>
{
// Compilation should succeed without retry if we redirect assembly refs correctly.
// Throwing so that we don't loop forever (as we did before fix)...
throw ExceptionUtilities.Unreachable;
},
out errorMessage,
out testData);
Assert.Null(errorMessage);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: callvirt ""Windows.UI.Core.CoreDispatcher Windows.UI.Xaml.DependencyObject.Dispatcher.get""
IL_0006: ret
}");
}
private RuntimeInstance CreateRuntime(
string source,
ImmutableArray<MetadataReference> compileReferences,
ImmutableArray<MetadataReference> runtimeReferences)
{
var compilation0 = CreateCompilationWithMscorlib(
source,
options: TestOptions.DebugDll,
assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(),
references: compileReferences);
byte[] exeBytes;
byte[] pdbBytes;
ImmutableArray<MetadataReference> references;
compilation0.EmitAndGetReferences(out exeBytes, out pdbBytes, out references);
return CreateRuntimeInstance(
ExpressionCompilerUtilities.GenerateUniqueName(),
runtimeReferences.AddIntrinsicAssembly(),
exeBytes,
new SymReader(pdbBytes));
}
private static byte[] ToVersion1_3(byte[] bytes)
{
return ExpressionCompilerTestHelpers.ToVersion1_3(bytes);
}
private static byte[] ToVersion1_4(byte[] bytes)
{
return ExpressionCompilerTestHelpers.ToVersion1_4(bytes);
}
}
}
| |
using Bridge.Contract;
using Bridge.Contract.Constants;
using ICSharpCode.NRefactory.CSharp;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
using System.Linq;
namespace Bridge.Translator
{
public class ArrayCreateBlock : ConversionBlock
{
public ArrayCreateBlock(IEmitter emitter, ArrayCreateExpression arrayCreateExpression)
: base(emitter, arrayCreateExpression)
{
this.Emitter = emitter;
this.ArrayCreateExpression = arrayCreateExpression;
}
public ArrayCreateBlock(IEmitter emitter, ArrayCreateExpression arrayCreateExpression, ArrayCreateResolveResult arrayCreateResolveResult)
: base(emitter, null)
{
this.Emitter = emitter;
this.ArrayCreateExpression = arrayCreateExpression;
this.ArrayCreateResolveResult = arrayCreateResolveResult;
}
public ArrayCreateExpression ArrayCreateExpression
{
get;
set;
}
public ArrayCreateResolveResult ArrayCreateResolveResult
{
get;
set;
}
protected override Expression GetExpression()
{
return this.ArrayCreateExpression;
}
protected override void EmitConversionExpression()
{
this.VisitArrayCreateExpression();
}
protected void VisitArrayCreateExpression()
{
ArrayCreateExpression arrayCreateExpression = this.ArrayCreateExpression;
var rr = this.ArrayCreateResolveResult ?? (this.Emitter.Resolver.ResolveNode(arrayCreateExpression, this.Emitter) as ArrayCreateResolveResult);
var at = (ArrayType)rr.Type;
var rank = arrayCreateExpression.Arguments.Count;
if (arrayCreateExpression.Initializer.IsNull && rank == 1)
{
string typedArrayName = null;
if (this.Emitter.AssemblyInfo.UseTypedArrays && (typedArrayName = Helpers.GetTypedArrayName(at.ElementType)) != null)
{
this.Write(JS.Types.System.Array.INIT);
this.WriteOpenParentheses();
this.Write("new ", typedArrayName, "(");
if (this.ArrayCreateResolveResult != null)
{
AttributeCreateBlock.WriteResolveResult(this.ArrayCreateResolveResult.SizeArguments.First(), this);
}
else
{
arrayCreateExpression.Arguments.First().AcceptVisitor(this.Emitter);
}
this.Write(")");
this.Write(", ");
this.Write(BridgeTypes.ToJsName(at.ElementType, this.Emitter));
this.Write(")");
}
else
{
this.Write(JS.Types.System.Array.INIT);
this.WriteOpenParentheses();
if (this.ArrayCreateResolveResult != null)
{
AttributeCreateBlock.WriteResolveResult(this.ArrayCreateResolveResult.SizeArguments.First(), this);
}
else
{
arrayCreateExpression.Arguments.First().AcceptVisitor(this.Emitter);
}
this.WriteComma();
var def = Inspector.GetDefaultFieldValue(at.ElementType, arrayCreateExpression.Type);
if (def == at.ElementType || def is RawValue)
{
this.WriteFunction();
this.WriteOpenCloseParentheses();
this.BeginBlock();
this.WriteReturn(true);
if (def is RawValue)
{
this.Write(def.ToString());
}
else
{
this.Write(Inspector.GetStructDefaultValue(at.ElementType, this.Emitter));
}
this.WriteSemiColon();
this.WriteNewLine();
this.EndBlock();
}
else
{
this.WriteScript(def);
}
this.Write(", ");
this.Write(BridgeTypes.ToJsName(at.ElementType, this.Emitter));
this.Write(")");
}
return;
}
if (at.Dimensions > 1)
{
this.Write(JS.Types.System.Array.CREATE);
this.WriteOpenParentheses();
var def = Inspector.GetDefaultFieldValue(at.ElementType, arrayCreateExpression.Type);
var defaultInitializer = new PrimitiveExpression(def, "?");
if (def == at.ElementType || def is RawValue)
{
this.WriteFunction();
this.WriteOpenCloseParentheses();
this.BeginBlock();
this.WriteReturn(true);
if (def is RawValue)
{
this.Write(def.ToString());
}
else
{
this.Write(Inspector.GetStructDefaultValue(at.ElementType, this.Emitter));
}
this.WriteSemiColon();
this.WriteNewLine();
this.EndBlock();
}
else if (defaultInitializer.Value is IType)
{
this.Write(Inspector.GetStructDefaultValue((IType) defaultInitializer.Value, this.Emitter));
}
else if (defaultInitializer.Value is RawValue)
{
this.Write(defaultInitializer.Value.ToString());
}
else
{
defaultInitializer.AcceptVisitor(this.Emitter);
}
this.WriteComma();
}
else
{
this.Write(JS.Types.System.Array.INIT);
this.WriteOpenParentheses();
}
if (rr.InitializerElements != null && rr.InitializerElements.Count > 0)
{
string typedArrayName = null;
bool isTyped = this.Emitter.AssemblyInfo.UseTypedArrays && (typedArrayName = Helpers.GetTypedArrayName(at.ElementType)) != null;
if (isTyped)
{
this.Write("new ", typedArrayName, "(");
}
this.WriteOpenBracket();
if (this.ArrayCreateResolveResult != null)
{
bool needComma = false;
foreach (ResolveResult item in this.ArrayCreateResolveResult.InitializerElements)
{
if (needComma)
{
this.WriteComma();
}
needComma = true;
AttributeCreateBlock.WriteResolveResult(item, this);
}
}
else
{
var elements = arrayCreateExpression.Initializer.Elements;
new ExpressionListBlock(this.Emitter, elements, null, null, 0).Emit();
}
this.WriteCloseBracket();
if (isTyped)
{
this.Write(")");
}
}
else if (at.Dimensions > 1)
{
this.Write("null");
}
else
{
this.Write("[]");
}
this.Write(", ");
this.Write(BridgeTypes.ToJsName(at.ElementType, this.Emitter));
if (at.Dimensions > 1)
{
this.Emitter.Comma = true;
for (int i = 0; i < rr.SizeArguments.Count; i++)
{
var a = rr.SizeArguments[i];
this.EnsureComma(false);
if (a.IsCompileTimeConstant)
{
this.Write(a.ConstantValue);
}
else if (this.ArrayCreateResolveResult != null)
{
AttributeCreateBlock.WriteResolveResult(this.ArrayCreateResolveResult.SizeArguments[i], this);
}
else if (arrayCreateExpression.Arguments.Count > i)
{
var arg = arrayCreateExpression.Arguments.ElementAt(i);
if (arg != null)
{
arg.AcceptVisitor(this.Emitter);
}
}
this.Emitter.Comma = true;
}
}
this.Write(")");
this.Emitter.Comma = false;
}
}
}
| |
/********************************************************************************************
Copyright (c) Microsoft Corporation
All rights reserved.
Microsoft Public License:
This license governs use of the accompanying software. If you use the software, you
accept this license. If you do not accept the license, do not use the software.
1. Definitions
The terms "reproduce," "reproduction," "derivative works," and "distribution" have the
same meaning here as under U.S. copyright law.
A "contribution" is the original software, or any additions or changes to the software.
A "contributor" is any person that distributes its contribution under this license.
"Licensed patents" are a contributor's patent claims that read directly on its contribution.
2. Grant of Rights
(A) Copyright Grant- Subject to the terms of this license, including the license conditions
and limitations in section 3, each contributor grants you a non-exclusive, worldwide,
royalty-free copyright license to reproduce its contribution, prepare derivative works of
its contribution, and distribute its contribution or any derivative works that you create.
(B) Patent Grant- Subject to the terms of this license, including the license conditions
and limitations in section 3, each contributor grants you a non-exclusive, worldwide,
royalty-free license under its licensed patents to make, have made, use, sell, offer for
sale, import, and/or otherwise dispose of its contribution in the software or derivative
works of the contribution in the software.
3. Conditions and Limitations
(A) No Trademark License- This license does not grant you rights to use any contributors'
name, logo, or trademarks.
(B) If you bring a patent claim against any contributor over patents that you claim are
infringed by the software, your patent license from such contributor to the software ends
automatically.
(C) If you distribute any portion of the software, you must retain all copyright, patent,
trademark, and attribution notices that are present in the software.
(D) If you distribute any portion of the software in source code form, you may do so only
under this license by including a complete copy of this license with your distribution.
If you distribute any portion of the software in compiled or object code form, you may only
do so under a license that complies with this license.
(E) The software is licensed "as-is." You bear the risk of using it. The contributors give
no express warranties, guarantees or conditions. You may have additional consumer rights
under your local laws which this license cannot change. To the extent permitted under your
local laws, the contributors exclude the implied warranties of merchantability, fitness for
a particular purpose and non-infringement.
********************************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
//#define ConfigTrace
using Microsoft.VisualStudio.Shell.Interop;
using MSBuild = Microsoft.Build.Evaluation;
using MSBuildExecution = Microsoft.Build.Execution;
using MSBuildConstruction = Microsoft.Build.Construction;
namespace Microsoft.VisualStudio.Project
{
public class ProjectConfig :
IVsCfg,
IVsProjectCfg,
IVsProjectCfg2,
IVsProjectFlavorCfg,
IVsDebuggableProjectCfg,
ISpecifyPropertyPages,
IVsSpecifyProjectDesignerPages,
IVsCfgBrowseObject
{
#region constants
internal const string Debug = "Debug";
internal const string Release = "Release";
internal const string AnyCPU = "AnyCPU";
#endregion
#region fields
private ProjectNode project;
private string configName;
private MSBuildExecution.ProjectInstance currentConfig;
private List<OutputGroup> outputGroups;
private IProjectConfigProperties configurationProperties;
private IVsProjectFlavorCfg flavoredCfg;
private BuildableProjectConfig buildableCfg;
#endregion
#region properties
public ProjectNode ProjectMgr
{
get
{
return this.project;
}
}
public string ConfigName
{
get
{
return this.configName;
}
set
{
this.configName = value;
}
}
public virtual object ConfigurationProperties
{
get
{
if(this.configurationProperties == null)
{
this.configurationProperties = new ProjectConfigProperties(this);
}
return this.configurationProperties;
}
}
protected IList<OutputGroup> OutputGroups
{
get
{
if(null == this.outputGroups)
{
// Initialize output groups
this.outputGroups = new List<OutputGroup>();
// Get the list of group names from the project.
// The main reason we get it from the project is to make it easier for someone to modify
// it by simply overriding that method and providing the correct MSBuild target(s).
IList<KeyValuePair<string, string>> groupNames = project.GetOutputGroupNames();
if(groupNames != null)
{
// Populate the output array
foreach(KeyValuePair<string, string> group in groupNames)
{
OutputGroup outputGroup = CreateOutputGroup(project, group);
this.outputGroups.Add(outputGroup);
}
}
}
return this.outputGroups;
}
}
#endregion
#region ctors
public ProjectConfig(ProjectNode project, string configuration)
{
this.project = project;
this.configName = configuration;
// Because the project can be aggregated by a flavor, we need to make sure
// we get the outer most implementation of that interface (hence: project --> IUnknown --> Interface)
IntPtr projectUnknown = Marshal.GetIUnknownForObject(this.ProjectMgr);
try
{
IVsProjectFlavorCfgProvider flavorCfgProvider = (IVsProjectFlavorCfgProvider)Marshal.GetTypedObjectForIUnknown(projectUnknown, typeof(IVsProjectFlavorCfgProvider));
ErrorHandler.ThrowOnFailure(flavorCfgProvider.CreateProjectFlavorCfg(this, out flavoredCfg));
if(flavoredCfg == null)
throw new COMException();
}
finally
{
if(projectUnknown != IntPtr.Zero)
Marshal.Release(projectUnknown);
}
// if the flavored object support XML fragment, initialize it
IPersistXMLFragment persistXML = flavoredCfg as IPersistXMLFragment;
if(null != persistXML)
{
this.project.LoadXmlFragment(persistXML, this.DisplayName);
}
}
#endregion
#region methods
protected virtual OutputGroup CreateOutputGroup(ProjectNode project, KeyValuePair<string, string> group)
{
OutputGroup outputGroup = new OutputGroup(group.Key, group.Value, project, this);
return outputGroup;
}
public void PrepareBuild(bool clean)
{
project.PrepareBuild(this.configName, clean);
}
public virtual string GetConfigurationProperty(string propertyName, bool resetCache)
{
MSBuildExecution.ProjectPropertyInstance property = GetMsBuildProperty(propertyName, resetCache);
if (property == null)
return null;
return property.EvaluatedValue;
}
public virtual void SetConfigurationProperty(string propertyName, string propertyValue)
{
if(!this.project.QueryEditProjectFile(false))
{
throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
}
string condition = String.Format(CultureInfo.InvariantCulture, ConfigProvider.configString, this.ConfigName);
SetPropertyUnderCondition(propertyName, propertyValue, condition);
// property cache will need to be updated
this.currentConfig = null;
// Signal the output groups that something is changed
foreach(OutputGroup group in this.OutputGroups)
{
group.InvalidateGroup();
}
this.project.SetProjectFileDirty(true);
return;
}
/// <summary>
/// Emulates the behavior of SetProperty(name, value, condition) on the old MSBuild object model.
/// This finds a property group with the specified condition (or creates one if necessary) then sets the property in there.
/// </summary>
private void SetPropertyUnderCondition(string propertyName, string propertyValue, string condition)
{
string conditionTrimmed = (condition == null) ? String.Empty : condition.Trim();
if (conditionTrimmed.Length == 0)
{
this.project.BuildProject.SetProperty(propertyName, propertyValue);
return;
}
// New OM doesn't have a convenient equivalent for setting a property with a particular property group condition.
// So do it ourselves.
MSBuildConstruction.ProjectPropertyGroupElement newGroup = null;
foreach (MSBuildConstruction.ProjectPropertyGroupElement group in this.project.BuildProject.Xml.PropertyGroups)
{
if (String.Equals(group.Condition.Trim(), conditionTrimmed, StringComparison.OrdinalIgnoreCase))
{
newGroup = group;
break;
}
}
if (newGroup == null)
{
newGroup = this.project.BuildProject.Xml.AddPropertyGroup(); // Adds after last existing PG, else at start of project
newGroup.Condition = condition;
}
foreach (MSBuildConstruction.ProjectPropertyElement property in newGroup.PropertiesReversed) // If there's dupes, pick the last one so we win
{
if (String.Equals(property.Name, propertyName, StringComparison.OrdinalIgnoreCase) && property.Condition.Length == 0)
{
property.Value = propertyValue;
return;
}
}
newGroup.AddProperty(propertyName, propertyValue);
}
/// <summary>
/// If flavored, and if the flavor config can be dirty, ask it if it is dirty
/// </summary>
/// <param name="storageType">Project file or user file</param>
/// <returns>0 = not dirty</returns>
internal int IsFlavorDirty(_PersistStorageType storageType)
{
int isDirty = 0;
if(this.flavoredCfg != null && this.flavoredCfg is IPersistXMLFragment)
{
ErrorHandler.ThrowOnFailure(((IPersistXMLFragment)this.flavoredCfg).IsFragmentDirty((uint)storageType, out isDirty));
}
return isDirty;
}
/// <summary>
/// If flavored, ask the flavor if it wants to provide an XML fragment
/// </summary>
/// <param name="flavor">Guid of the flavor</param>
/// <param name="storageType">Project file or user file</param>
/// <param name="fragment">Fragment that the flavor wants to save</param>
/// <returns>HRESULT</returns>
internal int GetXmlFragment(Guid flavor, _PersistStorageType storageType, out string fragment)
{
fragment = null;
int hr = VSConstants.S_OK;
if(this.flavoredCfg != null && this.flavoredCfg is IPersistXMLFragment)
{
Guid flavorGuid = flavor;
hr = ((IPersistXMLFragment)this.flavoredCfg).Save(ref flavorGuid, (uint)storageType, out fragment, 1);
}
return hr;
}
#endregion
#region IVsSpecifyPropertyPages
public void GetPages(CAUUID[] pages)
{
this.GetCfgPropertyPages(pages);
}
#endregion
#region IVsSpecifyProjectDesignerPages
/// <summary>
/// Implementation of the IVsSpecifyProjectDesignerPages. It will retun the pages that are configuration dependent.
/// </summary>
/// <param name="pages">The pages to return.</param>
/// <returns>VSConstants.S_OK</returns>
public virtual int GetProjectDesignerPages(CAUUID[] pages)
{
this.GetCfgPropertyPages(pages);
return VSConstants.S_OK;
}
#endregion
#region IVsCfg methods
/// <summary>
/// The display name is a two part item
/// first part is the config name, 2nd part is the platform name
/// </summary>
public virtual int get_DisplayName(out string name)
{
name = DisplayName;
return VSConstants.S_OK;
}
private string DisplayName
{
get
{
string name;
string[] platform = new string[1];
uint[] actual = new uint[1];
name = this.configName;
// currently, we only support one platform, so just add it..
IVsCfgProvider provider;
ErrorHandler.ThrowOnFailure(project.GetCfgProvider(out provider));
ErrorHandler.ThrowOnFailure(((IVsCfgProvider2)provider).GetPlatformNames(1, platform, actual));
if(!string.IsNullOrEmpty(platform[0]))
{
name += "|" + platform[0];
}
return name;
}
}
public virtual int get_IsDebugOnly(out int fDebug)
{
fDebug = 0;
if(this.configName == "Debug")
{
fDebug = 1;
}
return VSConstants.S_OK;
}
public virtual int get_IsReleaseOnly(out int fRelease)
{
CCITracing.TraceCall();
fRelease = 0;
if(this.configName == "Release")
{
fRelease = 1;
}
return VSConstants.S_OK;
}
#endregion
#region IVsProjectCfg methods
public virtual int EnumOutputs(out IVsEnumOutputs eo)
{
CCITracing.TraceCall();
eo = null;
return VSConstants.E_NOTIMPL;
}
public virtual int get_BuildableProjectCfg(out IVsBuildableProjectCfg pb)
{
CCITracing.TraceCall();
if(buildableCfg == null)
buildableCfg = new BuildableProjectConfig(this);
pb = buildableCfg;
return VSConstants.S_OK;
}
public virtual int get_CanonicalName(out string name)
{
return ((IVsCfg)this).get_DisplayName(out name);
}
public virtual int get_IsPackaged(out int pkgd)
{
CCITracing.TraceCall();
pkgd = 0;
return VSConstants.S_OK;
}
public virtual int get_IsSpecifyingOutputSupported(out int f)
{
CCITracing.TraceCall();
f = 1;
return VSConstants.S_OK;
}
public virtual int get_Platform(out Guid platform)
{
CCITracing.TraceCall();
platform = Guid.Empty;
return VSConstants.E_NOTIMPL;
}
public virtual int get_ProjectCfgProvider(out IVsProjectCfgProvider p)
{
CCITracing.TraceCall();
p = null;
IVsCfgProvider cfgProvider = null;
this.project.GetCfgProvider(out cfgProvider);
if(cfgProvider != null)
{
p = cfgProvider as IVsProjectCfgProvider;
}
return (null == p) ? VSConstants.E_NOTIMPL : VSConstants.S_OK;
}
public virtual int get_RootURL(out string root)
{
CCITracing.TraceCall();
root = null;
return VSConstants.S_OK;
}
public virtual int get_TargetCodePage(out uint target)
{
CCITracing.TraceCall();
target = (uint)System.Text.Encoding.Default.CodePage;
return VSConstants.S_OK;
}
public virtual int get_UpdateSequenceNumber(ULARGE_INTEGER[] li)
{
if (li == null)
{
throw new ArgumentNullException("li");
}
CCITracing.TraceCall();
li[0] = new ULARGE_INTEGER();
li[0].QuadPart = 0;
return VSConstants.S_OK;
}
public virtual int OpenOutput(string name, out IVsOutput output)
{
CCITracing.TraceCall();
output = null;
return VSConstants.E_NOTIMPL;
}
#endregion
#region IVsDebuggableProjectCfg methods
/// <summary>
/// Called by the vs shell to start debugging (managed or unmanaged).
/// Override this method to support other debug engines.
/// </summary>
/// <param name="grfLaunch">A flag that determines the conditions under which to start the debugger. For valid grfLaunch values, see __VSDBGLAUNCHFLAGS</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code</returns>
public virtual int DebugLaunch(uint grfLaunch)
{
CCITracing.TraceCall();
try
{
VsDebugTargetInfo info = new VsDebugTargetInfo();
info.cbSize = (uint)Marshal.SizeOf(info);
info.dlo = Microsoft.VisualStudio.Shell.Interop.DEBUG_LAUNCH_OPERATION.DLO_CreateProcess;
// On first call, reset the cache, following calls will use the cached values
string property = GetConfigurationProperty("StartProgram", true);
if(string.IsNullOrEmpty(property))
{
info.bstrExe = this.project.GetOutputAssembly(this.ConfigName);
}
else
{
info.bstrExe = property;
}
property = GetConfigurationProperty("WorkingDirectory", false);
if(string.IsNullOrEmpty(property))
{
info.bstrCurDir = Path.GetDirectoryName(info.bstrExe);
}
else
{
info.bstrCurDir = property;
}
property = GetConfigurationProperty("CmdArgs", false);
if(!string.IsNullOrEmpty(property))
{
info.bstrArg = property;
}
property = GetConfigurationProperty("RemoteDebugMachine", false);
if(property != null && property.Length > 0)
{
info.bstrRemoteMachine = property;
}
info.fSendStdoutToOutputWindow = 0;
property = GetConfigurationProperty("EnableUnmanagedDebugging", false);
if(property != null && string.Compare(property, "true", StringComparison.OrdinalIgnoreCase) == 0)
{
//Set the unmanged debugger
//TODO change to vsconstant when it is available in VsConstants (guidNativeOnlyEng was the old name, maybe it has got a new name)
info.clsidCustom = new Guid("{3B476D35-A401-11D2-AAD4-00C04F990171}");
}
else
{
//Set the managed debugger
info.clsidCustom = VSConstants.CLSID_ComPlusOnlyDebugEngine;
}
info.grfLaunch = grfLaunch;
VsShellUtilities.LaunchDebugger(this.project.Site, info);
}
catch(Exception e)
{
Trace.WriteLine("Exception : " + e.Message);
return Marshal.GetHRForException(e);
}
return VSConstants.S_OK;
}
/// <summary>
/// Determines whether the debugger can be launched, given the state of the launch flags.
/// </summary>
/// <param name="flags">Flags that determine the conditions under which to launch the debugger.
/// For valid grfLaunch values, see __VSDBGLAUNCHFLAGS or __VSDBGLAUNCHFLAGS2.</param>
/// <param name="fCanLaunch">true if the debugger can be launched, otherwise false</param>
/// <returns>S_OK if the method succeeds, otherwise an error code</returns>
public virtual int QueryDebugLaunch(uint flags, out int fCanLaunch)
{
CCITracing.TraceCall();
string assembly = this.project.GetAssemblyName(this.ConfigName);
fCanLaunch = (assembly != null && assembly.ToUpperInvariant().EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) ? 1 : 0;
if(fCanLaunch == 0)
{
string property = GetConfigurationProperty("StartProgram", true);
fCanLaunch = (property != null && property.Length > 0) ? 1 : 0;
}
return VSConstants.S_OK;
}
#endregion
#region IVsProjectCfg2 Members
public virtual int OpenOutputGroup(string szCanonicalName, out IVsOutputGroup ppIVsOutputGroup)
{
ppIVsOutputGroup = null;
// Search through our list of groups to find the one they are looking forgroupName
foreach(OutputGroup group in OutputGroups)
{
string groupName;
group.get_CanonicalName(out groupName);
if(String.Compare(groupName, szCanonicalName, StringComparison.OrdinalIgnoreCase) == 0)
{
ppIVsOutputGroup = group;
break;
}
}
return (ppIVsOutputGroup != null) ? VSConstants.S_OK : VSConstants.E_FAIL;
}
public virtual int OutputsRequireAppRoot(out int pfRequiresAppRoot)
{
pfRequiresAppRoot = 0;
return VSConstants.E_NOTIMPL;
}
public virtual int get_CfgType(ref Guid iidCfg, out IntPtr ppCfg)
{
// Delegate to the flavored configuration (to enable a flavor to take control)
// Since we can be asked for Configuration we don't support, avoid throwing and return the HRESULT directly
int hr = flavoredCfg.get_CfgType(ref iidCfg, out ppCfg);
return hr;
}
public virtual int get_IsPrivate(out int pfPrivate)
{
pfPrivate = 0;
return VSConstants.S_OK;
}
public virtual int get_OutputGroups(uint celt, IVsOutputGroup[] rgpcfg, uint[] pcActual)
{
// Are they only asking for the number of groups?
if(celt == 0)
{
if((null == pcActual) || (0 == pcActual.Length))
{
throw new ArgumentNullException("pcActual");
}
pcActual[0] = (uint)OutputGroups.Count;
return VSConstants.S_OK;
}
// Check that the array of output groups is not null
if((null == rgpcfg) || (rgpcfg.Length == 0))
{
throw new ArgumentNullException("rgpcfg");
}
// Fill the array with our output groups
uint count = 0;
foreach(OutputGroup group in OutputGroups)
{
if(rgpcfg.Length > count && celt > count && group != null)
{
rgpcfg[count] = group;
++count;
}
}
if(pcActual != null && pcActual.Length > 0)
pcActual[0] = count;
// If the number asked for does not match the number returned, return S_FALSE
return (count == celt) ? VSConstants.S_OK : VSConstants.S_FALSE;
}
public virtual int get_VirtualRoot(out string pbstrVRoot)
{
pbstrVRoot = null;
return VSConstants.E_NOTIMPL;
}
#endregion
#region IVsCfgBrowseObject
/// <summary>
/// Maps back to the configuration corresponding to the browse object.
/// </summary>
/// <param name="cfg">The IVsCfg object represented by the browse object</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
public virtual int GetCfg(out IVsCfg cfg)
{
cfg = this;
return VSConstants.S_OK;
}
/// <summary>
/// Maps back to the hierarchy or project item object corresponding to the browse object.
/// </summary>
/// <param name="hier">Reference to the hierarchy object.</param>
/// <param name="itemid">Reference to the project item.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
public virtual int GetProjectItem(out IVsHierarchy hier, out uint itemid)
{
if(this.project == null || this.project.NodeProperties == null)
{
throw new InvalidOperationException();
}
return this.project.NodeProperties.GetProjectItem(out hier, out itemid);
}
#endregion
#region helper methods
/// <summary>
/// Splits the canonical configuration name into platform and configuration name.
/// </summary>
/// <param name="canonicalName">The canonicalName name.</param>
/// <param name="configName">The name of the configuration.</param>
/// <param name="platformName">The name of the platform.</param>
/// <returns>true if successfull.</returns>
internal static bool TrySplitConfigurationCanonicalName(string canonicalName, out string configName, out string platformName)
{
configName = String.Empty;
platformName = String.Empty;
if(String.IsNullOrEmpty(canonicalName))
{
return false;
}
string[] splittedCanonicalName = canonicalName.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
if(splittedCanonicalName == null || (splittedCanonicalName.Length != 1 && splittedCanonicalName.Length != 2))
{
return false;
}
configName = splittedCanonicalName[0];
if(splittedCanonicalName.Length == 2)
{
platformName = splittedCanonicalName[1];
}
return true;
}
private MSBuildExecution.ProjectPropertyInstance GetMsBuildProperty(string propertyName, bool resetCache)
{
if (resetCache || this.currentConfig == null)
{
// Get properties for current configuration from project file and cache it
this.project.SetConfiguration(this.ConfigName);
this.project.BuildProject.ReevaluateIfNecessary();
// Create a snapshot of the evaluated project in its current state
this.currentConfig = this.project.BuildProject.CreateProjectInstance();
// Restore configuration
project.SetCurrentConfiguration();
}
if (this.currentConfig == null)
throw new Exception("Failed to retrieve properties");
// return property asked for
return this.currentConfig.GetProperty(propertyName);
}
/// <summary>
/// Retrieves the configuration dependent property pages.
/// </summary>
/// <param name="pages">The pages to return.</param>
private void GetCfgPropertyPages(CAUUID[] pages)
{
// We do not check whether the supportsProjectDesigner is set to true on the ProjectNode.
// We rely that the caller knows what to call on us.
if(pages == null)
{
throw new ArgumentNullException("pages");
}
if(pages.Length == 0)
{
throw new ArgumentException(SR.GetString(SR.InvalidParameter, CultureInfo.CurrentUICulture), "pages");
}
// Retrive the list of guids from hierarchy properties.
// Because a flavor could modify that list we must make sure we are calling the outer most implementation of IVsHierarchy
string guidsList = String.Empty;
IVsHierarchy hierarchy = this.project.InteropSafeIVsHierarchy;
object variant = null;
ErrorHandler.ThrowOnFailure(hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID2.VSHPROPID_CfgPropertyPagesCLSIDList, out variant), new int[] { VSConstants.DISP_E_MEMBERNOTFOUND, VSConstants.E_NOTIMPL });
guidsList = (string)variant;
Guid[] guids = Utilities.GuidsArrayFromSemicolonDelimitedStringOfGuids(guidsList);
if(guids == null || guids.Length == 0)
{
pages[0] = new CAUUID();
pages[0].cElems = 0;
}
else
{
pages[0] = PackageUtilities.CreateCAUUIDFromGuidArray(guids);
}
}
#endregion
#region IVsProjectFlavorCfg Members
/// <summary>
/// This is called to let the flavored config let go
/// of any reference it may still be holding to the base config
/// </summary>
/// <returns></returns>
int IVsProjectFlavorCfg.Close()
{
// This is used to release the reference the flavored config is holding
// on the base config, but in our scenario these 2 are the same object
// so we have nothing to do here.
return VSConstants.S_OK;
}
/// <summary>
/// Actual implementation of get_CfgType.
/// When not flavored or when the flavor delegate to use
/// we end up creating the requested config if we support it.
/// </summary>
/// <param name="iidCfg">IID representing the type of config object we should create</param>
/// <param name="ppCfg">Config object that the method created</param>
/// <returns>HRESULT</returns>
int IVsProjectFlavorCfg.get_CfgType(ref Guid iidCfg, out IntPtr ppCfg)
{
ppCfg = IntPtr.Zero;
// See if this is an interface we support
if(iidCfg == typeof(IVsDebuggableProjectCfg).GUID)
ppCfg = Marshal.GetComInterfaceForObject(this, typeof(IVsDebuggableProjectCfg));
else if(iidCfg == typeof(IVsBuildableProjectCfg).GUID)
{
IVsBuildableProjectCfg buildableConfig;
this.get_BuildableProjectCfg(out buildableConfig);
ppCfg = Marshal.GetComInterfaceForObject(buildableConfig, typeof(IVsBuildableProjectCfg));
}
// If not supported
if(ppCfg == IntPtr.Zero)
return VSConstants.E_NOINTERFACE;
return VSConstants.S_OK;
}
#endregion
}
//=============================================================================
// NOTE: advises on out of proc build execution to maximize
// future cross-platform targeting capabilities of the VS tools.
[ComVisible(true)]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Buildable")]
public class BuildableProjectConfig : IVsBuildableProjectCfg
{
#region fields
ProjectConfig config = null;
EventSinkCollection callbacks = new EventSinkCollection();
#endregion
#region ctors
public BuildableProjectConfig(ProjectConfig config)
{
this.config = config;
}
#endregion
#region IVsBuildableProjectCfg methods
public virtual int AdviseBuildStatusCallback(IVsBuildStatusCallback callback, out uint cookie)
{
CCITracing.TraceCall();
cookie = callbacks.Add(callback);
return VSConstants.S_OK;
}
public virtual int get_ProjectCfg(out IVsProjectCfg p)
{
CCITracing.TraceCall();
p = config;
return VSConstants.S_OK;
}
public virtual int QueryStartBuild(uint options, int[] supported, int[] ready)
{
CCITracing.TraceCall();
if(supported != null && supported.Length > 0)
supported[0] = 1;
if(ready != null && ready.Length > 0)
ready[0] = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1;
return VSConstants.S_OK;
}
public virtual int QueryStartClean(uint options, int[] supported, int[] ready)
{
CCITracing.TraceCall();
config.PrepareBuild(false);
if(supported != null && supported.Length > 0)
supported[0] = 1;
if(ready != null && ready.Length > 0)
ready[0] = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1;
return VSConstants.S_OK;
}
public virtual int QueryStartUpToDateCheck(uint options, int[] supported, int[] ready)
{
CCITracing.TraceCall();
config.PrepareBuild(false);
if(supported != null && supported.Length > 0)
supported[0] = 0; // TODO:
if(ready != null && ready.Length > 0)
ready[0] = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1;
return VSConstants.S_OK;
}
public virtual int QueryStatus(out int done)
{
CCITracing.TraceCall();
done = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1;
return VSConstants.S_OK;
}
public virtual int StartBuild(IVsOutputWindowPane pane, uint options)
{
CCITracing.TraceCall();
config.PrepareBuild(false);
// Current version of MSBuild wish to be called in an STA
uint flags = VSConstants.VS_BUILDABLEPROJECTCFGOPTS_REBUILD;
// If we are not asked for a rebuild, then we build the default target (by passing null)
this.Build(options, pane, ((options & flags) != 0) ? MsBuildTarget.Rebuild : null);
return VSConstants.S_OK;
}
public virtual int StartClean(IVsOutputWindowPane pane, uint options)
{
CCITracing.TraceCall();
config.PrepareBuild(true);
// Current version of MSBuild wish to be called in an STA
this.Build(options, pane, MsBuildTarget.Clean);
return VSConstants.S_OK;
}
public virtual int StartUpToDateCheck(IVsOutputWindowPane pane, uint options)
{
CCITracing.TraceCall();
return VSConstants.E_NOTIMPL;
}
public virtual int Stop(int fsync)
{
CCITracing.TraceCall();
return VSConstants.S_OK;
}
public virtual int UnadviseBuildStatusCallback(uint cookie)
{
CCITracing.TraceCall();
callbacks.RemoveAt(cookie);
return VSConstants.S_OK;
}
public virtual int Wait(uint ms, int fTickWhenMessageQNotEmpty)
{
CCITracing.TraceCall();
return VSConstants.E_NOTIMPL;
}
#endregion
#region helpers
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private bool NotifyBuildBegin()
{
int shouldContinue = 1;
foreach (IVsBuildStatusCallback cb in callbacks)
{
try
{
ErrorHandler.ThrowOnFailure(cb.BuildBegin(ref shouldContinue));
if (shouldContinue == 0)
{
return false;
}
}
catch (Exception e)
{
// If those who ask for status have bugs in their code it should not prevent the build/notification from happening
Debug.Fail(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.BuildEventError, CultureInfo.CurrentUICulture), e.Message));
}
}
return true;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void NotifyBuildEnd(MSBuildResult result, string buildTarget)
{
int success = ((result == MSBuildResult.Successful) ? 1 : 0);
foreach (IVsBuildStatusCallback cb in callbacks)
{
try
{
ErrorHandler.ThrowOnFailure(cb.BuildEnd(success));
}
catch (Exception e)
{
// If those who ask for status have bugs in their code it should not prevent the build/notification from happening
Debug.Fail(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.BuildEventError, CultureInfo.CurrentUICulture), e.Message));
}
finally
{
// We want to refresh the references if we are building with the Build or Rebuild target or if the project was opened for browsing only.
bool shouldRepaintReferences = (buildTarget == null || buildTarget == MsBuildTarget.Build || buildTarget == MsBuildTarget.Rebuild);
// Now repaint references if that is needed.
// We hardly rely here on the fact the ResolveAssemblyReferences target has been run as part of the build.
// One scenario to think at is when an assembly reference is renamed on disk thus becomming unresolvable,
// but msbuild can actually resolve it.
// Another one if the project was opened only for browsing and now the user chooses to build or rebuild.
if (shouldRepaintReferences && (result == MSBuildResult.Successful))
{
this.RefreshReferences();
}
}
}
}
private void Build(uint options, IVsOutputWindowPane output, string target)
{
if (!this.NotifyBuildBegin())
{
return;
}
try
{
config.ProjectMgr.BuildAsync(options, this.config.ConfigName, output, target, (result, buildTarget) => this.NotifyBuildEnd(result, buildTarget));
}
catch(Exception e)
{
Trace.WriteLine("Exception : " + e.Message);
ErrorHandler.ThrowOnFailure(output.OutputStringThreadSafe("Unhandled Exception:" + e.Message + "\n"));
this.NotifyBuildEnd(MSBuildResult.Failed, target);
throw;
}
finally
{
ErrorHandler.ThrowOnFailure(output.FlushToTaskList());
}
}
/// <summary>
/// Refreshes references and redraws them correctly.
/// </summary>
private void RefreshReferences()
{
// Refresh the reference container node for assemblies that could be resolved.
IReferenceContainer referenceContainer = this.config.ProjectMgr.GetReferenceContainer();
foreach(ReferenceNode referenceNode in referenceContainer.EnumReferences())
{
referenceNode.RefreshReference();
}
}
#endregion
}
}
| |
#region PDFsharp - A .NET library for processing PDF
//
// Authors:
// Klaus Potzesny
//
// Copyright (c) 2005-2016 empira Software GmbH, Cologne Area (Germany)
//
// http://www.pdfsharp.com
// http://sourceforge.net/projects/pdfsharp
//
// 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
namespace PdfSharp.Drawing.BarCodes
{
/// <summary>
/// Represents an OMR code.
/// </summary>
public class CodeOmr : BarCode
{
/// <summary>
/// initializes a new OmrCode with the given data.
/// </summary>
public CodeOmr(string text, XSize size, CodeDirection direction)
: base(text, size, direction)
{ }
/// <summary>
/// Renders the OMR code.
/// </summary>
protected internal override void Render(XGraphics gfx, XBrush brush, XFont font, XPoint position)
{
XGraphicsState state = gfx.Save();
switch (Direction)
{
case CodeDirection.RightToLeft:
gfx.RotateAtTransform(180, position);
break;
case CodeDirection.TopToBottom:
gfx.RotateAtTransform(90, position);
break;
case CodeDirection.BottomToTop:
gfx.RotateAtTransform(-90, position);
break;
}
//XPoint pt = center - size / 2;
XPoint pt = position - CodeBase.CalcDistance(AnchorType.TopLeft, Anchor, Size);
uint value;
uint.TryParse(Text, out value);
#if true
// HACK: Project Wallenwein: set LK
value |= 1;
_synchronizeCode = true;
#endif
if (_synchronizeCode)
{
XRect rect = new XRect(pt.X, pt.Y, _makerThickness, Size.Height);
gfx.DrawRectangle(brush, rect);
pt.X += 2 * _makerDistance;
}
for (int idx = 0; idx < 32; idx++)
{
if ((value & 1) == 1)
{
XRect rect = new XRect(pt.X + idx * _makerDistance, pt.Y, _makerThickness, Size.Height);
gfx.DrawRectangle(brush, rect);
}
value = value >> 1;
}
gfx.Restore(state);
}
/// <summary>
/// Gets or sets a value indicating whether a synchronize mark is rendered.
/// </summary>
public bool SynchronizeCode
{
get { return _synchronizeCode; }
set { _synchronizeCode = value; }
}
bool _synchronizeCode;
/// <summary>
/// Gets or sets the distance of the markers.
/// </summary>
public double MakerDistance
{
get { return _makerDistance; }
set { _makerDistance = value; }
}
double _makerDistance = 12; // 1/6"
/// <summary>
/// Gets or sets the thickness of the makers.
/// </summary>
public double MakerThickness
{
get { return _makerThickness; }
set { _makerThickness = value; }
}
double _makerThickness = 1;
///// <summary>
///// Renders the mark at the given position.
///// </summary>
///// <param name="position">The mark position to render.</param>
//private void RenderMark(int position)
//{
// double yPos = TopLeft.Y + UpperDistance + position * ToUnit(markDistance).Centimeter;
// //Center mark
// double xPos = TopLeft.X + Width / 2 - this.MarkWidth / 2;
// Gfx.DrawLine(pen, xPos, yPos, xPos + MarkWidth, yPos);
//}
///// <summary>
///// Distance of the marks. Default is 2/6 inch.
///// </summary>
//public MarkDistance MarkDistance
//{
// get { return markDistance; }
// set { markDistance = value; }
//}
//private MarkDistance markDistance = MarkDistance.Inch2_6;
///// <summary>
///// Converts a mark distance to an XUnit object.
///// </summary>
///// <param name="markDistance">The mark distance to convert.</param>
///// <returns>The converted mark distance.</returns>
//public static XUnit ToUnit(MarkDistance markDistance)
//{
// switch (markDistance)
// {
// case MarkDistance.Inch1_6:
// return XUnit.FromInch(1.0 / 6.0);
// case MarkDistance.Inch2_6:
// return XUnit.FromInch(2.0 / 6.0);
// case MarkDistance.Inch2_8:
// return XUnit.FromInch(2.0 / 8.0);
// default:
// throw new ArgumentOutOfRangeException("markDistance");
// }
//}
///// <summary>
///// The upper left point of the reading zone.
///// </summary>
//public XPoint TopLeft
//{
// get
// {
// XPoint topLeft = center;
// topLeft.X -= Width;
// double height = upperDistance + lowerDistance;
// height += (data.Marks.Length - 1) * ToUnit(MarkDistance).Centimeter;
// topLeft.Y -= height / 2;
// return topLeft;
// }
//}
///// <summary>
///// the upper distance from position to the first mark.
///// The default value is 8 / 6 inch.
///// </summary>
//double UpperDistance
//{
// get { return upperDistance; }
// set { upperDistance = value; }
//}
//private double upperDistance = XUnit.FromInch(8.0 / 6.0).Centimeter;
///// <summary>
///// The lower distance from the last possible mark to the end of the reading zone.
///// The default value is
///// </summary>
//double LowerDistance
//{
// get { return lowerDistance; }
// set { lowerDistance = value; }
//}
//private double lowerDistance = XUnit.FromInch(2.0 / 6.0).Centimeter;
///// <summary>
///// Gets or sets the width of the reading zone.
///// Default and minimum is 3/12 inch.
///// </summary>
//public double Width
//{
// get { return width; }
// set { width = value; }
//}
//double width = XUnit.FromInch(3.0 / 12.0).Centimeter;
///// <summary>
///// Gets or sets the mark width. Default is 1/2 * width.
///// </summary>
//public XUnit MarkWidth
//{
// get
// {
// if (markWidth > 0)
// return markWidth;
// else
// return width / 2;
// }
// set { markWidth = value; }
//}
//XUnit markWidth;
///// <summary>
///// Gets or sets the width of the mark line. Default is 1pt.
///// </summary>
//public XUnit MarkLineWidth
//{
// get { return markLineWidth; }
// set { markLineWidth = value; }
//}
//XUnit markLineWidth = 1;
/// <summary>
/// Determines whether the specified string can be used as Text for the OMR code.
/// </summary>
protected override void CheckCode(string text)
{ }
}
}
| |
/*
* 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 Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.ServiceAuth;
using OpenSim.Framework.Console;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Server.Base;
using OpenSim.Server.Handlers.Base;
using OpenSim.Services.Interfaces;
using System;
using System.IO;
namespace OpenSim.Server.Handlers.Asset
{
public class AssetServiceConnector : ServiceConnector
{
private IAssetService m_AssetService;
private string m_ConfigName = "AssetService";
public AssetServiceConnector(IConfigSource config, IHttpServer server, string configName) :
base(config, server, configName)
{
if (configName != String.Empty)
m_ConfigName = configName;
IConfig serverConfig = config.Configs[m_ConfigName];
if (serverConfig == null)
throw new Exception(String.Format("No section '{0}' in config file", m_ConfigName));
string assetService = serverConfig.GetString("LocalServiceModule",
String.Empty);
if (assetService == String.Empty)
throw new Exception("No LocalServiceModule in config file");
Object[] args = new Object[] { config, m_ConfigName };
m_AssetService =
ServerUtils.LoadPlugin<IAssetService>(assetService, args);
if (m_AssetService == null)
throw new Exception(String.Format("Failed to load AssetService from {0}; config is {1}", assetService, m_ConfigName));
bool allowDelete = serverConfig.GetBoolean("AllowRemoteDelete", false);
bool allowDeleteAllTypes = serverConfig.GetBoolean("AllowRemoteDeleteAllTypes", false);
string redirectURL = serverConfig.GetString("RedirectURL", string.Empty);
AllowedRemoteDeleteTypes allowedRemoteDeleteTypes;
if (!allowDelete)
{
allowedRemoteDeleteTypes = AllowedRemoteDeleteTypes.None;
}
else
{
if (allowDeleteAllTypes)
allowedRemoteDeleteTypes = AllowedRemoteDeleteTypes.All;
else
allowedRemoteDeleteTypes = AllowedRemoteDeleteTypes.MapTile;
}
IServiceAuth auth = ServiceAuth.Create(config, m_ConfigName);
server.AddStreamHandler(new AssetServerGetHandler(m_AssetService, auth, redirectURL));
server.AddStreamHandler(new AssetServerPostHandler(m_AssetService, auth));
server.AddStreamHandler(new AssetServerDeleteHandler(m_AssetService, allowedRemoteDeleteTypes, auth));
server.AddStreamHandler(new AssetsExistHandler(m_AssetService));
MainConsole.Instance.Commands.AddCommand("Assets", false,
"show asset",
"show asset <ID>",
"Show asset information",
HandleShowAsset);
MainConsole.Instance.Commands.AddCommand("Assets", false,
"delete asset",
"delete asset <ID>",
"Delete asset from database",
HandleDeleteAsset);
MainConsole.Instance.Commands.AddCommand("Assets", false,
"dump asset",
"dump asset <ID>",
"Dump asset to a file",
"The filename is the same as the ID given.",
HandleDumpAsset);
}
void HandleDeleteAsset(string module, string[] args)
{
if (args.Length < 3)
{
MainConsole.Instance.Output("Syntax: delete asset <ID>");
return;
}
AssetBase asset = m_AssetService.Get(args[2]);
if (asset == null || asset.Data.Length == 0)
{
MainConsole.Instance.OutputFormat("Could not find asset with ID {0}", args[2]);
return;
}
if (!m_AssetService.Delete(asset.ID))
MainConsole.Instance.OutputFormat("ERROR: Could not delete asset {0} {1}", asset.ID, asset.Name);
else
MainConsole.Instance.OutputFormat("Deleted asset {0} {1}", asset.ID, asset.Name);
}
void HandleDumpAsset(string module, string[] args)
{
if (args.Length < 3)
{
MainConsole.Instance.Output("Usage is dump asset <ID>");
return;
}
UUID assetId;
string rawAssetId = args[2];
if (!UUID.TryParse(rawAssetId, out assetId))
{
MainConsole.Instance.OutputFormat("ERROR: {0} is not a valid ID format", rawAssetId);
return;
}
AssetBase asset = m_AssetService.Get(assetId.ToString());
if (asset == null)
{
MainConsole.Instance.OutputFormat("ERROR: No asset found with ID {0}", assetId);
return;
}
string fileName = rawAssetId;
if (!ConsoleUtil.CheckFileDoesNotExist(MainConsole.Instance, fileName))
return;
using (FileStream fs = new FileStream(fileName, FileMode.CreateNew))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
bw.Write(asset.Data);
}
}
MainConsole.Instance.OutputFormat("Asset dumped to file {0}", fileName);
}
void HandleShowAsset(string module, string[] args)
{
if (args.Length < 3)
{
MainConsole.Instance.Output("Syntax: show asset <ID>");
return;
}
AssetBase asset = m_AssetService.Get(args[2]);
if (asset == null || asset.Data.Length == 0)
{
MainConsole.Instance.Output("Asset not found");
return;
}
int i;
MainConsole.Instance.OutputFormat("Name: {0}", asset.Name);
MainConsole.Instance.OutputFormat("Description: {0}", asset.Description);
MainConsole.Instance.OutputFormat("Type: {0} (type number = {1})", (AssetType)asset.Type, asset.Type);
MainConsole.Instance.OutputFormat("Content-type: {0}", asset.Metadata.ContentType);
MainConsole.Instance.OutputFormat("Size: {0} bytes", asset.Data.Length);
MainConsole.Instance.OutputFormat("Temporary: {0}", asset.Temporary ? "yes" : "no");
MainConsole.Instance.OutputFormat("Flags: {0}", asset.Metadata.Flags);
for (i = 0 ; i < 5 ; i++)
{
int off = i * 16;
if (asset.Data.Length <= off)
break;
int len = 16;
if (asset.Data.Length < off + len)
len = asset.Data.Length - off;
byte[] line = new byte[len];
Array.Copy(asset.Data, off, line, 0, len);
string text = BitConverter.ToString(line);
MainConsole.Instance.Output(String.Format("{0:x4}: {1}", off, text));
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using System.Threading;
using System.Runtime.ExceptionServices;
using Xunit;
namespace System.Data.SqlClient.ManualTesting.Tests
{
public class ConnectionPool
{
private readonly string _nwnd9Tcp = null;
private readonly string _nwnd9TcpMars = null;
private readonly string _nwnd9Np = null;
private readonly string _nwnd9NpMars = null;
private readonly string _nwnd10Tcp = null;
private readonly string _nwnd10TcpMars = null;
private readonly string _nwnd10Np = null;
private readonly string _nwnd10NpMars = null;
public ConnectionPool()
{
PrepareConnectionStrings(DataTestClass.SQL2005_Northwind, out _nwnd9Tcp, out _nwnd9TcpMars, out _nwnd9Np, out _nwnd9NpMars);
PrepareConnectionStrings(DataTestClass.SQL2008_Northwind, out _nwnd10Tcp, out _nwnd10TcpMars, out _nwnd10Np, out _nwnd10NpMars);
}
[Fact]
public void ConnectionPool_Nwnd9()
{
RunDataTestForSingleConnString(_nwnd9Tcp, _nwnd9Np, false);
}
[Fact]
public void ConnectionPool_Nwnd9Mars()
{
RunDataTestForSingleConnString(_nwnd9TcpMars, _nwnd9NpMars, false);
}
[Fact]
public void ConnectionPool_Nwnd10()
{
RunDataTestForSingleConnString(_nwnd10Tcp, _nwnd10Np, true);
}
[Fact]
public void ConnectionPool_Nwnd10Mars()
{
RunDataTestForSingleConnString(_nwnd10TcpMars, _nwnd10NpMars, true);
}
private static void RunDataTestForSingleConnString(string tcpConnectionString, string npConnectionString, bool serverIsKatmaiOrLater)
{
BasicConnectionPoolingTest(tcpConnectionString);
ClearAllPoolsTest(tcpConnectionString);
KillConnectionTest(tcpConnectionString);
ReclaimEmancipatedOnOpenTest(tcpConnectionString);
}
/// <summary>
/// Tests that using the same connection string results in the same pool\internal connection and a different string results in a different pool\internal connection
/// </summary>
/// <param name="connectionString"></param>
private static void BasicConnectionPoolingTest(string connectionString)
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
InternalConnectionWrapper internalConnection = new InternalConnectionWrapper(connection);
ConnectionPoolWrapper connectionPool = new ConnectionPoolWrapper(connection);
connection.Close();
SqlConnection connection2 = new SqlConnection(connectionString);
connection2.Open();
Assert.True(internalConnection.IsInternalConnectionOf(connection2), "New connection does not use same internal connection");
Assert.True(connectionPool.ContainsConnection(connection2), "New connection is in a different pool");
connection2.Close();
SqlConnection connection3 = new SqlConnection(connectionString + ";App=SqlConnectionPoolUnitTest;");
connection3.Open();
Assert.False(internalConnection.IsInternalConnectionOf(connection3), "Connection with different connection string uses same internal connection");
Assert.False(connectionPool.ContainsConnection(connection3), "Connection with different connection string uses same connection pool");
connection3.Close();
connectionPool.Cleanup();
SqlConnection connection4 = new SqlConnection(connectionString);
connection4.Open();
Assert.True(internalConnection.IsInternalConnectionOf(connection4), "New connection does not use same internal connection");
Assert.True(connectionPool.ContainsConnection(connection4), "New connection is in a different pool");
connection4.Close();
}
/// <summary>
/// Tests if killing the connection using the InternalConnectionWrapper is working
/// </summary>
/// <param name="connectionString"></param>
private static void KillConnectionTest(string connectionString)
{
InternalConnectionWrapper wrapper = null;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
wrapper = new InternalConnectionWrapper(connection);
using (SqlCommand command = new SqlCommand("SELECT 5;", connection))
{
CompareScalarResults(5, command.ExecuteScalar());
}
wrapper.KillConnection();
}
using (SqlConnection connection2 = new SqlConnection(connectionString))
{
connection2.Open();
Assert.False(wrapper.IsInternalConnectionOf(connection2), "New connection has internal connection that was just killed");
using (SqlCommand command = new SqlCommand("SELECT 5;", connection2))
{
CompareScalarResults(5, command.ExecuteScalar());
}
}
}
/// <summary>
/// Tests if clearing all of the pools does actually remove the pools
/// </summary>
/// <param name="connectionString"></param>
private static void ClearAllPoolsTest(string connectionString)
{
SqlConnection.ClearAllPools();
Assert.True(0 == ConnectionPoolWrapper.AllConnectionPools().Length, "Pools exist after clearing all pools");
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
ConnectionPoolWrapper pool = new ConnectionPoolWrapper(connection);
connection.Close();
ConnectionPoolWrapper[] allPools = ConnectionPoolWrapper.AllConnectionPools();
Assert.True(1 == allPools.Length, "Incorrect number of pools exist");
Assert.True(allPools[0].Equals(pool), "Saved pool is not in the list of all pools");
Assert.True(1 == pool.ConnectionCount, "Saved pool has incorrect number of connections");
SqlConnection.ClearAllPools();
Assert.True(0 == ConnectionPoolWrapper.AllConnectionPools().Length, "Pools exist after clearing all pools");
Assert.True(0 == pool.ConnectionCount, "Saved pool has incorrect number of connections");
}
/// <summary>
/// Checks if an 'emancipated' internal connection is reclaimed when a new connection is opened AND we hit max pool size
/// NOTE: 'emancipated' means that the internal connection's SqlConnection has fallen out of scope and has no references, but was not explicitly disposed\closed
/// </summary>
/// <param name="connectionString"></param>
private static void ReclaimEmancipatedOnOpenTest(string connectionString)
{
string newConnectionString = connectionString + ";Max Pool Size=1";
SqlConnection.ClearAllPools();
InternalConnectionWrapper internalConnection = CreateEmancipatedConnection(newConnectionString);
ConnectionPoolWrapper connectionPool = internalConnection.ConnectionPool;
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.True(1 == connectionPool.ConnectionCount, "Wrong number of connections in the pool");
Assert.True(0 == connectionPool.FreeConnectionCount, "Wrong number of free connections in the pool");
using (SqlConnection connection = new SqlConnection(newConnectionString))
{
connection.Open();
Assert.True(internalConnection.IsInternalConnectionOf(connection), "Connection has wrong internal connection");
Assert.True(connectionPool.ContainsConnection(connection), "Connection is in wrong connection pool");
}
}
private static void ReplacementConnectionUsesSemaphoreTest(string connectionString)
{
string newConnectionString = (new SqlConnectionStringBuilder(connectionString) { MaxPoolSize = 2, ConnectTimeout = 5 }).ConnectionString;
SqlConnection.ClearAllPools();
SqlConnection liveConnection = new SqlConnection(newConnectionString);
SqlConnection deadConnection = new SqlConnection(newConnectionString);
liveConnection.Open();
deadConnection.Open();
InternalConnectionWrapper deadConnectionInternal = new InternalConnectionWrapper(deadConnection);
InternalConnectionWrapper liveConnectionInternal = new InternalConnectionWrapper(liveConnection);
deadConnectionInternal.KillConnection();
deadConnection.Close();
liveConnection.Close();
Task<InternalConnectionWrapper>[] tasks = new Task<InternalConnectionWrapper>[3];
Barrier syncBarrier = new Barrier(tasks.Length);
Func<InternalConnectionWrapper> taskFunction = (() => ReplacementConnectionUsesSemaphoreTask(newConnectionString, syncBarrier));
for (int i = 0; i < tasks.Length; i++)
{
tasks[i] = Task.Factory.StartNew<InternalConnectionWrapper>(taskFunction);
}
bool taskWithLiveConnection = false;
bool taskWithNewConnection = false;
bool taskWithCorrectException = false;
Task waitAllTask = Task.Factory.ContinueWhenAll(tasks, (completedTasks) =>
{
foreach (var item in completedTasks)
{
if (item.Status == TaskStatus.Faulted)
{
// One task should have a timeout exception
if ((!taskWithCorrectException) && (item.Exception.InnerException is InvalidOperationException) && (item.Exception.InnerException.Message.StartsWith(SystemDataResourceManager.Instance.ADP_PooledOpenTimeout)))
taskWithCorrectException = true;
else if (!taskWithCorrectException)
{
// Rethrow the unknown exception
ExceptionDispatchInfo exceptionInfo = ExceptionDispatchInfo.Capture(item.Exception);
exceptionInfo.Throw();
}
}
else if (item.Status == TaskStatus.RanToCompletion)
{
// One task should get the live connection
if (item.Result.Equals(liveConnectionInternal))
{
if (!taskWithLiveConnection)
taskWithLiveConnection = true;
}
else if (!item.Result.Equals(deadConnectionInternal) && !taskWithNewConnection)
taskWithNewConnection = true;
}
else
Console.WriteLine("ERROR: Task in unknown state: {0}", item.Status);
}
});
waitAllTask.Wait();
Assert.True(taskWithLiveConnection && taskWithNewConnection && taskWithCorrectException, string.Format("Tasks didn't finish as expected.\nTask with live connection: {0}\nTask with new connection: {1}\nTask with correct exception: {2}\n", taskWithLiveConnection, taskWithNewConnection, taskWithCorrectException));
}
private static InternalConnectionWrapper ReplacementConnectionUsesSemaphoreTask(string connectionString, Barrier syncBarrier)
{
InternalConnectionWrapper internalConnection = null;
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
internalConnection = new InternalConnectionWrapper(connection);
}
catch
{
syncBarrier.SignalAndWait();
throw;
}
syncBarrier.SignalAndWait();
}
return internalConnection;
}
private static InternalConnectionWrapper CreateEmancipatedConnection(string connectionString)
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
return new InternalConnectionWrapper(connection);
}
private static void CompareScalarResults(int expected, object actual)
{
Assert.True(expected.Equals(actual), string.Format("Expected scalar value {0}, but instead receieved {1}.", expected, actual));
}
private static void PrepareConnectionStrings(string originalString, out string tcpString, out string tcpMarsString, out string npString, out string npMarsString)
{
SqlConnectionStringBuilder connBuilder = new SqlConnectionStringBuilder(originalString);
DataSourceBuilder sourceBuilder = new DataSourceBuilder(connBuilder.DataSource);
sourceBuilder.Protocol = null;
// TCP
connBuilder.DataSource = sourceBuilder.ToString();
connBuilder.MultipleActiveResultSets = false;
tcpString = connBuilder.ConnectionString;
// TCP + MARS
connBuilder.MultipleActiveResultSets = true;
tcpMarsString = connBuilder.ConnectionString;
// Named Pipes
sourceBuilder.Port = null;
connBuilder.DataSource = "np:" + sourceBuilder.ToString();
connBuilder.MultipleActiveResultSets = false;
npString = connBuilder.ConnectionString;
// Named Pipes + MARS
connBuilder.MultipleActiveResultSets = true;
npMarsString = connBuilder.ConnectionString;
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.IO.Ports;
//using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
namespace EnOcean
{
public enum PacketType { RESERVED = 0, RADIO_ERP1 = 1, RESPONSE, RADIO_SUB_TEL, EVENT, COMMON_COMMAND, SMART_ACK_COMMAND, REMOTE_MAN_COMMAND, RESERVED_ENOCEAN, RADIO_MESSAGE, RADIO_ERP2 };
public enum TelegramType { UNKNOWN=0, TT_4BS = 0xA5, TT_ADT = 0xA6, TT_VLD = 0xC2, TT_1BS = 0xD5}
public class EnOceanOptionalData
{
private IList<byte> list;
public int getSize()
{
return list.Count;
}
public EnOceanOptionalData(IList<byte> list)
{
this.list = list;
}
public PacketType getType()
{
if (list == null || list.Count == 0)
return PacketType.RESERVED;
return (PacketType)list[0];
}
public UInt32 getDestination()
{
UInt32 dest = list[1];
dest = (dest * 256) + list[2];
dest = (dest * 256) + list[3];
dest = (dest * 256) + list[4];
return dest;
}
}
public class EnOceanPacket
{
public DateTime recieved = DateTime.UtcNow;
private IList<byte> data;
private IList<byte> optData;
private PacketType type;
private Byte[] rawPacket;
public Byte[] GetData()
{
var f = new Byte[this.data.Count];
this.data.CopyTo(f, 0);
return f;
}
public EnOceanOptionalData Get_OptionalData()
{
return new EnOceanOptionalData(this.optData);
}
public TelegramType getTelegramType()
{
if (data == null || data.Count == 0)
return TelegramType.UNKNOWN;
return (TelegramType)data[0];
}
public PacketType getType()
{
return type;
}
static public EnOceanPacket MakePacket_CO_RD_VERSION()
{
var pkt = new EnOceanPacket(PacketType.COMMON_COMMAND, new byte[] { 0x03 }, null);
pkt.BuildPacket();
return pkt;
}
public Byte[] BuildPacket()
{
if (optData == null)
optData = new byte[0];
var ms = new MemoryStream();
var bw = new BinaryWriter(ms);
bw.Write((byte)0x55); // Sync byte
bw.Write((byte)(data.Count >> 8));
bw.Write((byte)(data.Count & 0xFF));
bw.Write((byte)optData.Count); // optData length
bw.Write((byte)type); // Packet Type
bw.Write(EnOceanChecksum.CalcCRC8(ms.GetBuffer(), 4, 1));
foreach (var b in data)
bw.Write(b);
foreach (var b in optData)
bw.Write(b);
bw.Write(EnOceanChecksum.CalcCRC8(ms.GetBuffer(), (int)(ms.Length - 6), 6));
this.rawPacket = ms.GetBuffer();
Array.Resize<byte>(ref rawPacket, (int)ms.Length);
return this.rawPacket;
}
public EnOceanPacket(byte pkt_type, IList<byte> data, IList<byte> optData)
{
this.data = data;
this.optData = optData;
this.type = (PacketType)pkt_type;
}
public EnOceanPacket(PacketType pkt_type, IList<byte> data, IList<byte> optData)
{
this.data = data;
this.optData = optData;
this.type = pkt_type;
}
static public EnOceanPacket Parse(byte pkt_type, IList<byte> data, IList<byte> optData)
{
return new EnOceanPacket(pkt_type, data, optData);
}
internal UInt32 getSource()
{
int srcPos = 2;
if (getTelegramType() == TelegramType.TT_4BS)
srcPos = 5;
UInt32 src = data[srcPos];
src = (src * 256) + data[srcPos+1];
src = (src * 256) + data[srcPos+2];
src = (src * 256) + data[srcPos+3];
return src;
}
}
public class EnOceanChecksum
{
static byte[] u8CRC8Table = {
0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15,
0x38, 0x3f, 0x36, 0x31, 0x24, 0x23, 0x2a, 0x2d,
0x70, 0x77, 0x7e, 0x79, 0x6c, 0x6b, 0x62, 0x65,
0x48, 0x4f, 0x46, 0x41, 0x54, 0x53, 0x5a, 0x5d,
0xe0, 0xe7, 0xee, 0xe9, 0xfc, 0xfb, 0xf2, 0xf5,
0xd8, 0xdf, 0xd6, 0xd1, 0xc4, 0xc3, 0xca, 0xcd,
0x90, 0x97, 0x9e, 0x99, 0x8c, 0x8b, 0x82, 0x85,
0xa8, 0xaf, 0xa6, 0xa1, 0xb4, 0xb3, 0xba, 0xbd,
0xc7, 0xc0, 0xc9, 0xce, 0xdb, 0xdc, 0xd5, 0xd2,
0xff, 0xf8, 0xf1, 0xf6, 0xe3, 0xe4, 0xed, 0xea,
0xb7, 0xb0, 0xb9, 0xbe, 0xab, 0xac, 0xa5, 0xa2,
0x8f, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9d, 0x9a,
0x27, 0x20, 0x29, 0x2e, 0x3b, 0x3c, 0x35, 0x32,
0x1f, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0d, 0x0a,
0x57, 0x50, 0x59, 0x5e, 0x4b, 0x4c, 0x45, 0x42,
0x6f, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7d, 0x7a,
0x89, 0x8e, 0x87, 0x80, 0x95, 0x92, 0x9b, 0x9c,
0xb1, 0xb6, 0xbf, 0xb8, 0xad, 0xaa, 0xa3, 0xa4,
0xf9, 0xfe, 0xf7, 0xf0, 0xe5, 0xe2, 0xeb, 0xec,
0xc1, 0xc6, 0xcf, 0xc8, 0xdd, 0xda, 0xd3, 0xd4,
0x69, 0x6e, 0x67, 0x60, 0x75, 0x72, 0x7b, 0x7c,
0x51, 0x56, 0x5f, 0x58, 0x4d, 0x4a, 0x43, 0x44,
0x19, 0x1e, 0x17, 0x10, 0x05, 0x02, 0x0b, 0x0c,
0x21, 0x26, 0x2f, 0x28, 0x3d, 0x3a, 0x33, 0x34,
0x4e, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5c, 0x5b,
0x76, 0x71, 0x78, 0x7f, 0x6A, 0x6d, 0x64, 0x63,
0x3e, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2c, 0x2b,
0x06, 0x01, 0x08, 0x0f, 0x1a, 0x1d, 0x14, 0x13,
0xae, 0xa9, 0xa0, 0xa7, 0xb2, 0xb5, 0xbc, 0xbb,
0x96, 0x91, 0x98, 0x9f, 0x8a, 0x8D, 0x84, 0x83,
0xde, 0xd9, 0xd0, 0xd7, 0xc2, 0xc5, 0xcc, 0xcb,
0xe6, 0xe1, 0xe8, 0xef, 0xfa, 0xfd, 0xf4, 0xf3
};
static byte proccrc8(byte u8CRC, byte u8Data)
{
return u8CRC8Table[u8CRC ^ u8Data];
}
static public byte CalcCRC8(IList<byte> data, int len = 0, int offset = 0)
{
if (len == 0)
len = data.Count - offset;
byte u8CRC = 0;
for (int i = offset; i < offset + len; i++)
u8CRC = proccrc8(u8CRC, data[i]);
//Console.WriteLine("CRC8 = 0x{0:x}", u8CRC);
return u8CRC;
}
}
public class EnOceanFrameLayer : IDisposable
{
SerialPort serialPort;
Thread commThreadHandle;
Boolean commActive;
ConcurrentQueue<EnOceanPacket> rxPacketQueue = new ConcurrentQueue<EnOceanPacket>();
EventWaitHandle rxCommThreadWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset);
object commLock = new object();
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// dispose managed resources
serialPort.Close();
serialPort = null;
}
// free native resources
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public EnOceanFrameLayer()
{
// Queue.Synchronized()
// Queue<PacketEvent>
// PacketEventHandler += (EnOceanPacket p) => { Console.WriteLine(" PKT HANDLER"); }; // TESTING
PacketEventHandler += (EnOceanPacket p) =>
{
// Console.WriteLine(" PKT HANDLER 2");
foreach (var listener in PacketListeners)
{
if (listener.handler(p))
{
listener.succeeded = true;
listener.waitHandle.Set();
}
}
};
}
void recvHackThread()
{
Console.WriteLine("Starting Linux recv hack thread");
byte[] rxBuf = new byte[64];
while (commActive)
{
try {
int readBytes = serialPort.Read(rxBuf, 0, 64);
if (readBytes >0) {
var tBuf = rxBuf.Take(readBytes);
// Console.WriteLine("Got {0} bytes", readBytes);
//byte[] rBuf = new byte[sp.BytesToRead];
//int bytesRead = sp.Read(rBuf, 0, rBuf.Length);
lock(receiveBuffer) {
receiveBuffer.InsertRange(receiveBuffer.Count, tBuf);
receiveIdx += readBytes;
}
}
processReceiveBuffer();
} catch (TimeoutException e) {
// Do nothing
} catch (Exception e) {
Console.WriteLine("E hack : {0}", e);
}
}
Console.WriteLine("Ending Linux recv comm thread");
}
void commThread()
{
Console.WriteLine("Starting communications thread");
while (commActive)
{
if (rxCommThreadWaitHandle.WaitOne(250))
{
AGAIN:
EnOceanPacket qp;
if (rxPacketQueue.TryDequeue(out qp))
{
if (PacketEventHandler != null)
PacketEventHandler(qp);
goto AGAIN;
}
}
// SendFrame(verGet);
}
Console.WriteLine("Ending comm thread");
}
public class PacketListener : IDisposable
{
public PacketListener(IReceiveHandler pHandler)
{
this.handler = pHandler;
succeeded = false;
packet = null;
waitHandle = new EventWaitHandle(false, EventResetMode.AutoReset);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// dispose managed resources
waitHandle.Close();
waitHandle = null;
}
// free native resources
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public IReceiveHandler handler;
public Boolean succeeded;
public EnOceanPacket packet;
public EventWaitHandle waitHandle;
}
List<PacketListener> PacketListeners = new List<PacketListener>();
public delegate bool IReceiveHandler(EnOceanPacket packet);
public bool Send(EnOceanPacket packet, IReceiveHandler handler, int retries = 3, int timeout = 1000)
{
var rawPacket = packet.BuildPacket();
var pl = new PacketListener(handler);
PacketListeners.Add(pl);
AGAIN:
// TESTING
SendFrame(rawPacket);
pl.waitHandle.WaitOne(timeout);
if (pl.succeeded)
{
PacketListeners.Remove(pl);
return true;
}
else
{
if (retries-- > 0)
goto AGAIN;
PacketListeners.Remove(pl);
return false;
// Packet not what he wanted.. wait for next!
}
}
public bool SendFrame(byte[] frame)
{
serialPort.Write(frame, 0, frame.Length);
return false;
}
byte CalculateFrameChecksum(byte[] frameData)
{
byte chksum = 0xff;
for (int i = 1; i < frameData.Length - 1; i++)
{
chksum ^= frameData[i];
}
return chksum;
}
public bool Open(string portName)
{
serialPort = new SerialPort(portName, 57600);
bool useRecvEvent = true;
int p = (int) Environment.OSVersion.Platform;
if ((p == 4) || (p == 6) || (p == 128)) {
Console.WriteLine ("Running on Unix");
useRecvEvent = false;
}
if (useRecvEvent)
serialPort.DataReceived += new SerialDataReceivedEventHandler(onCommDataReceived);
try
{
serialPort.Open();
if (!useRecvEvent) {
serialPort.ReadTimeout = 50;
var hackThread = new Thread(new ThreadStart(recvHackThread));
hackThread.Start();
}
commThreadHandle = new Thread(new ThreadStart(commThread));
commThreadHandle.Start();
}
catch (Exception e)
{
Console.WriteLine("Error opening port: {0}", e);
if (useRecvEvent)
serialPort.DataReceived -= new SerialDataReceivedEventHandler(onCommDataReceived);
commActive = false;
return false;
}
commActive = true;
return serialPort.IsOpen;
}
public bool Close()
{
if (commThreadHandle != null)
{
commActive = false;
commThreadHandle.Join();
commThreadHandle = null;
}
if (serialPort != null)
{
serialPort.Close();
serialPort = null;
return true;
}
return false;
}
List<byte> receiveBuffer = new List<byte>();
int receiveIdx = 0;
void onCommDataReceived(
object sender,
SerialDataReceivedEventArgs args)
{
SerialPort sp = (SerialPort)sender;
byte[] rBuf = new byte[sp.BytesToRead];
int bytesRead = sp.Read(rBuf, 0, rBuf.Length);
lock(receiveBuffer) {
receiveBuffer.InsertRange(receiveBuffer.Count, rBuf);
receiveIdx += bytesRead;
}
processReceiveBuffer();
/* Console.WriteLine("Data Received: {0} bytes", bytesRead);
foreach (var b in receiveBuffer)
{
Console.Write("0x{0:X2} ", b);
}
Console.WriteLine();
*/
}
void processReceiveBuffer() {
AGAIN:
while (receiveBuffer.Count > 0 && receiveBuffer[0] != 0x55)
receiveBuffer.RemoveAt(0);
if (receiveBuffer.Count < 6)
{
return;
}
receiveBuffer.RemoveAt(0); // Remove SYNC byte 0x55
byte hdrCrc8 = EnOceanChecksum.CalcCRC8(receiveBuffer, 4);
if (hdrCrc8 != receiveBuffer[4])
{
Console.WriteLine("CRC ERROR FOR PACKET HDR - or not a sync start\n");
goto AGAIN;
}
UInt16 pktLen = receiveBuffer[0];
pktLen *= 256;
pktLen += receiveBuffer[1];
Byte optLen = receiveBuffer[2];
Byte pktType = receiveBuffer[3];
if ((pktLen + optLen + 6) > receiveBuffer.Count)
{
// Not enough data yet.. push back header..
Console.WriteLine(" ABANDON FOR LATER - NOT ENOUGH DATA");
receiveBuffer.Insert(0, 0x55);
return;
}
List<byte> pktHdr = receiveBuffer.GetRange(0, 5);
receiveBuffer.RemoveRange(0, 5); // Remove hdr
Byte dtaCrc = EnOceanChecksum.CalcCRC8(receiveBuffer, pktLen + optLen);
if (dtaCrc == receiveBuffer[optLen + pktLen])
{
// Console.WriteLine(" ----- MATCH DATA CRC OK");
receiveBuffer.RemoveAt(receiveBuffer.Count - 1); // Remove checksum - we have checked it already
List<byte> payload = receiveBuffer.GetRange(0, pktLen);
List<byte> optPayload = receiveBuffer.GetRange(pktLen, optLen);
Console.WriteLine("Dispatching validated packet of {0} bytes and {1} bytes", payload.Count, optPayload.Count);
EnOceanPacket parsedPkt = EnOceanPacket.Parse(pktHdr[3], payload, optPayload);
rxPacketQueue.Enqueue(parsedPkt);
rxCommThreadWaitHandle.Set(); // Notify rx thread
receiveBuffer.RemoveRange(0, optLen + pktLen);
goto AGAIN;
}
}
public delegate void PacketEvent(EnOceanPacket pkt);
public PacketEvent PacketEventHandler;
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using InTheHand.Net.Sockets;
using InTheHand.Net;
using System.Net.Sockets;
namespace IrDAServiceClient
{
public partial class Form1 : Form
{
#if NETCF
internal static class MessageBox
{
internal static void Show(Control ownerIgnored, string text)
{
System.Windows.Forms.MessageBox.Show(text);
}
}
#endif
readonly string NewLine
#if NETCF
= "\r\n";
#else
= Environment.NewLine;
#endif
//--------------------------------------------------------------
//--------------------------------------------------------------
public Form1()
{
InitializeComponent();
}
//--------------------------------------------------------------
IrDAClient m_cli;
IrDADeviceInfo[] m_devices;
System.Net.Sockets.NetworkStream m_strm;
System.IO.StreamWriter m_wtr;
Encoding m_encoding;
bool m_connecting;
bool m_disconnecting;
//--------------------------------------------------------------
private void newIrdaClient()
{
m_connecting = false;
m_disconnecting = true;
UiInvoke(this.labelState, delegate { this.labelState.Text = "Disconnecting..."; });
if (m_wtr != null) {
m_wtr.Close();
// Closing the writer should have closed this too.
System.Diagnostics.Debug.Assert(!m_cli.Connected);
// But we'll close anyway...
}
m_cli.Close();
m_cli = new IrDAClient();
UiInvoke(this.labelState, delegate { this.labelState.Text = "Disconnected."; });
}
private static void UiInvoke(Control labelState, EventHandler uiUpdate)
{
if (labelState.InvokeRequired) {
labelState.Invoke(uiUpdate);
} else {
uiUpdate(labelState, new EventArgs());
}
}
//--------------------------------------------------------------
private void Form1_Load(object sender, EventArgs e)
{
comboBoxProtocolMode.DataSource = new IrProtocol[]{
// Want to exclude .None, so don't use: Enum.GetValues(typeof(IrProtocol));
IrProtocol.TinyTP, IrProtocol.IrCOMM, IrProtocol.IrLMP,
};
comboBoxProtocolMode.SelectedIndex = 0;
//
comboBoxWellKnowServices.BeginUpdate();
comboBoxWellKnowServices.Items.Clear();
foreach (WellKnownIrdaSvc svcCur in WellKnownIrdaSvc.s_wellknownServices) {
comboBoxWellKnowServices.Items.Add(svcCur);
}//for
comboBoxWellKnowServices.EndUpdate();
//
#if NETCF
// Encoding IA5 isn't supported on my PPC.
comboBoxEncoding.SelectedIndex = 3;
#else
comboBoxEncoding.SelectedIndex = 0;
#endif
//
labelState.Text = "Disconnected";
labelSendPduLength.Text = "";
//
m_cli = new IrDAClient();
}
#if ! PocketPC
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
#else
private void Form1_Closing(object sender, CancelEventArgs e)
#endif
{
m_disconnecting = true;
if (m_wtr != null) {
m_wtr.Close();
// Closing the writer should have closed this too.
System.Diagnostics.Debug.Assert(!m_cli.Connected);
// But we'll close anyway...
}
m_cli.Close();
}
//--------------------------------------------------------------
private void buttonDiscover_Click(object sender, EventArgs e)
{
// DiscoverDevices is fast on IrDA so no need for background running.
m_devices = m_cli.DiscoverDevices();
listBoxDevices.BeginUpdate();
listBoxDevices.Items.Clear();
foreach (IrDADeviceInfo curDev in m_devices) {
string text;
if (Environment.OSVersion.Platform == PlatformID.WinCE) {
text = "" + curDev.DeviceName.PadRight(22) + curDev.DeviceAddress
+ " " + curDev.Hints;
} else {
text = "" + curDev.DeviceName + "\t" + curDev.DeviceAddress
+ "\t" + curDev.Hints;
}
listBoxDevices.Items.Add(text);
}//for
listBoxDevices.EndUpdate();
if (listBoxDevices.Items.Count > 0) {
listBoxDevices.SelectedIndex = 0;
}
}
private void buttonDisconnect_Click(object sender, EventArgs e)
{
if (m_connecting) {
// During asynchronous Connect let the disconnect button be used
// to cancel the connect attempt. We must not delete the extant
// IrDAClient until the connect attempt has completed (so don't
// use newIrdaClient()). It will instead be called in the
// EndConnect callback when the cancel is actioned.
m_cli.Close();
} else {
m_disconnecting = true;
//labelState.Text = "Disconnecting...";
newIrdaClient();
//labelState.Text = "Disconnected";
}
}
private void buttonConnect_Click(object sender, EventArgs e)
{
if (m_cli.Connected) {
MessageBox.Show(this, "Already connected.");
return;
}
if (m_connecting) {
#if ! PocketPC
Console.Beep();
#endif
return;
}
//----------------------------------------------
// Gather input from user controls
//----------------------------------------------
int index = listBoxDevices.SelectedIndex;
if (index == -1) {
MessageBox.Show(this, "Please choose a device to connect to.");
return;
}
IrDADeviceInfo selectedDevice = m_devices[index];
//
String serviceName = textBoxServiceName.Text;
if (serviceName.Length == 0) {
MessageBox.Show(this, "Please enter a Service Name to connect to.");
return;
}
//
IrProtocol selectedMode = (IrProtocol)comboBoxProtocolMode.SelectedItem;
if (selectedMode == IrProtocol.IrLMP) {
m_cli.Client.SetSocketOption(
IrDASocketOptionLevel.IrLmp, IrDASocketOptionName.IrLptMode,
1); // NETCF doesn't have Boolean overload.
} else if (selectedMode == IrProtocol.IrCOMM) {
m_cli.Client.SetSocketOption(
IrDASocketOptionLevel.IrLmp, IrDASocketOptionName.NineWireMode,
1);
}
//
try {
m_encoding = Encoding.GetEncoding(comboBoxEncoding.Text);
} catch (ArgumentException) {
MessageBox.Show(this, "Unknown Encoding.");
newIrdaClient();
return;
}
#if NETCF
catch(PlatformNotSupportedException){
MessageBox.Show(this, "Encoding not supported on this platform.");
newIrdaClient();
return;
}
#endif
//
IrDAEndPoint ep = new IrDAEndPoint(selectedDevice.DeviceAddress, serviceName);
//----------------------------------------------
// Prepare the UI
//----------------------------------------------
textBoxReceive.Text = null; //.Clear()
//----------------------------------------------
// Connect etc
//----------------------------------------------
m_disconnecting = false;
labelState.Text = "Connecting...";
try {
#if NON_ASYNC_CONNECT
m_cli.Connect(ep);
DoneConnect(selectedMode);
#else
AsyncCallback cbk = new AsyncCallback(ConnectCallback);
m_connecting = true;
m_cli.BeginConnect(ep, cbk, selectedMode);
#endif
} catch (System.Net.Sockets.SocketException sex) {
String msg = "Connect failed: "
#if ! PocketPC
+ sex.SocketErrorCode.ToString()
#endif
+ " (" + sex.ErrorCode.ToString("D") + "); "
+ sex.Message;
MessageBox.Show(this, msg);
labelState.Text = msg;
newIrdaClient();
return;
}
}
void ConnectCallback(IAsyncResult ar)
{
EventHandler uiUpdate;
try {
m_cli.EndConnect(ar);
m_connecting = false;
// Using goto is ok in error handling situations...
goto connectSuccess;
} catch (NullReferenceException) {
// Close() on IrDAClient sets its socket to null, so EndConnect throws...
//System.Diagnostics.Debug.Assert(nrex.Message == "foo");
uiUpdate = delegate {
labelState.Text = "Connect cancelled.";
};
} catch (ObjectDisposedException) {
// Just before the client's internal socket instance is set to null
// (see the catch above) is is Disposes so catch the resultant error.
uiUpdate = delegate {
labelState.Text = "Connect cancelled.";
};
} catch (System.Net.Sockets.SocketException sex) {
uiUpdate = delegate {
String msg = "Connect failed: "
#if ! PocketPC
+ sex.SocketErrorCode.ToString()
#endif
+ " (" + sex.ErrorCode.ToString("D") + ")"
+ NewLine + " '" + sex.Message + "'";
if (Environment.OSVersion.Platform != PlatformID.WinCE) {
// On NETCF Socket.LocalEndPoint is null if connect failed! :-(
// Check if experiencing XP bug...
const byte MinLsapSel = 1;
const byte MaxLsapSel = 0x6F; // 111
IrDAEndPoint epLocal = (IrDAEndPoint)m_cli.Client.LocalEndPoint;
int lsapSel = GetNumericalLsapSel(epLocal);
System.Diagnostics.Debug.Assert(lsapSel != -1, "lsapSel != -1, should alway be numeric in this case");
if ((lsapSel < MinLsapSel || lsapSel > MaxLsapSel) && lsapSel != -1) {
msg += NewLine + NewLine + string.Format(
"Note: the local machine is using an illegal port number (LSAP-Sel): {0}=0x{0:X2}!", lsapSel);
// See "Illegal maximum LSAP Selectors used" at
// http://www.alanjmcf.me.uk/comms/infrared/Apparent%20bugs%20in%20Windows%20IrDA.html
}
}
MessageBox.Show(this, msg);
labelState.Text = msg;
};
}
// Dropped out of one of the exception handlers, exit after updating...
//UI thread-safe
if (labelState.InvokeRequired) {
labelState.Invoke(uiUpdate);
} else {
uiUpdate(labelState, null);
}
newIrdaClient();
return;
//-------------------------------
// Successful Connection.
connectSuccess:
IrProtocol selectedMode = (IrProtocol)ar.AsyncState;
DoneConnect(selectedMode);
}
private int GetNumericalLsapSel(IrDAEndPoint epLocal)
{
const string NumericalPrefix = "LSAP-SEL";
string svcName = epLocal.ServiceName;
if (!svcName.StartsWith(NumericalPrefix, StringComparison.Ordinal)) {
return -1;
}
string numStr = svcName.Substring(NumericalPrefix.Length);
byte num = byte.Parse(numStr);
return num;
}
private void DoneConnect(IrProtocol selectedMode)
{
m_strm = m_cli.GetStream();
m_wtr = new System.IO.StreamWriter(m_strm, m_encoding);
//----------------------------------------------
// Update the UI
//----------------------------------------------
EventHandler uiUpdate = delegate {
labelState.Text = "Connected";
//==
//try {
// IrDAEndPoint lep = (IrDAEndPoint)GetLocalEndPoint(m_cli.Client, new IrDAEndPoint(IrDAAddress.None, "prototype"));
// labelState.Text += "; lep=" + lep;
//} catch (SocketException sex) {
// labelState.Text += "; " + sex.ErrorCode + "from GLEP.";
//}
//==
// Display the maximum send size where relevant.
if (selectedMode == IrProtocol.IrLMP) {
object objValue = m_cli.Client.GetSocketOption(
IrDASocketOptionLevel.IrLmp, IrDASocketOptionName.SendPduLength);
int sendPduLength = (int)objValue;
labelSendPduLength.Text = sendPduLength.ToString();
} else {
labelSendPduLength.Text = "N/A";
}
#if NETCF
this.tabControl1.SelectedIndex = 1;
#endif
textBoxSend.Focus();
};
//UI thread-safe
if (labelState.InvokeRequired) {
labelState.Invoke(uiUpdate);
} else {
uiUpdate(this, new EventArgs());
}
//----------------------------------------------
// Start the receive thread.
//----------------------------------------------
System.Threading.ThreadPool.QueueUserWorkItem(receiveThreadFn);
}
private void comboBoxWKS_SelectedIndexChanged(object sender, EventArgs e)
{
WellKnownIrdaSvc svc = (WellKnownIrdaSvc)comboBoxWellKnowServices.SelectedItem;
if (svc == null) {
System.Diagnostics.Debug.Fail("huh?");
return;
}
textBoxServiceName.Text = svc.serviceName;
//
if (svc.protocolType != IrProtocol.None) {
#if DEBUG
// Ensure that the items in the combobox and in the field in the
// data items are of the same type.
Type protoType = comboBoxProtocolMode.SelectedItem.GetType();
System.Diagnostics.Debug.Assert(protoType == svc.protocolType.GetType());
#endif
// Set it
comboBoxProtocolMode.SelectedItem = svc.protocolType;
#if DEBUG
// Check that the set took effect (and there aren't say particular
// items missing from the combobox).
object itemRaw = comboBoxProtocolMode.SelectedItem;
IrProtocol item = (IrProtocol)itemRaw; // Safe due to the Assert above.
System.Diagnostics.Debug.Assert(item == svc.protocolType);
#endif
}//if
}
private void buttonSend_Click(object sender, EventArgs e)
{
if (m_wtr == null
|| m_wtr.BaseStream == null
|| !m_wtr.BaseStream.CanWrite) {
MessageBox.Show(this, "Not connected.");
} else {
// Assume v.25ter, so use a CR.
String str = textBoxSend.Text + "\r";
try {
m_wtr.Write(str);
m_wtr.Flush();
} catch (System.IO.IOException ioex) {
SocketException sex = ioex.InnerException as SocketException;
if (sex != null) {
receiveAppend("!! Send SocketException: "
#if ! PocketPC
+ sex.SocketErrorCode.ToString()
#endif
+ " (" + sex.ErrorCode.ToString("D")
+ "); " + ioex.Message);
} else {
receiveAppend("!! Send IOException: " + ioex.Message);
}
newIrdaClient();
}
}
}
void receiveThreadFn(object state) { receiveThreadFn(); }
void receiveThreadFn()
{
if (!m_cli.Connected
|| m_strm == null
|| !m_strm.CanRead) {
#if ! PocketPC
Console.Beep();
#endif
return;
}
System.IO.StreamReader rdr = new System.IO.StreamReader(m_strm, m_encoding);
char[] buf = new char[100];
try {
while (true) {
// We don't use ReadLine because we then don't get to see the
// CR and LF characters. And we often get the series \r\r\n
// which should appear as one new line, but would appear as two
// if we did textBox.Append("\n") each ReadLine.
int numRead = rdr.Read(buf, 0, buf.Length);
if (numRead == 0) {
break;
}
String str = new String(buf, 0, numRead);
receiveAppend(str);
}//while
} catch (System.IO.IOException ioex) {
if (!m_disconnecting) {
SocketException sex = ioex.InnerException as SocketException;
if (sex != null) {
receiveAppend("!! SocketException: "
#if ! PocketPC
+ sex.SocketErrorCode.ToString()
#endif
+ " (" + sex.ErrorCode.ToString("D")
+ "); " + ioex.Message);
} else {
receiveAppend("!! IOException: " + ioex.Message);
}
}
}
newIrdaClient();
}
delegate void ReceiveAppendCallback(String str);
// UI thread-safe updating.
void receiveAppend(String str)
{
if (this.textBoxReceive.InvokeRequired) {
ReceiveAppendCallback d = new ReceiveAppendCallback(receiveAppend);
this.Invoke(d, new object[] { str });
} else {
textBoxReceive.Text += str; //.AppendText()
// This doesn't work. Do we need to give focus, or not set ReadOnly
// or ...?
ScrollToEnd(textBoxReceive);
}
}
private void menuItemQuit_Click(object sender, EventArgs e)
{
this.Close();
}
[System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "SendMessage")]
private static extern int SendMessageWin32(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);
[System.Runtime.InteropServices.DllImport("coredll.dll", EntryPoint = "SendMessage")]
private static extern int SendMessageWinCE(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);
void ScrollToEnd(TextBox textBox)
{
const int WM_VSCROLL = 0x115;
const int SB_BOTTOM = 7;
// Scroll to the bottom, but don't move the caret position.
// In our case, we aren't worried about the caret position, but instead
// because we're ReadOnly setting .SelectionStart has no effect.
if (Environment.OSVersion.Platform == PlatformID.WinCE) {
SendMessageWinCE(textBox.Handle, WM_VSCROLL, (IntPtr)SB_BOTTOM, IntPtr.Zero);
} else if (Environment.OSVersion.Platform == PlatformID.Win32Windows) {
SendMessageWin32(textBox.Handle, WM_VSCROLL, (IntPtr)SB_BOTTOM, IntPtr.Zero);
}
}
void TestLsapSelRange(string serviceName, bool leaveOpen)
{
#if NETCF
this.tabControl1.SelectedIndex = 1;
#endif
textBoxReceive.Text = "Test LsapSel range";
Application.DoEvents();
//
IrDAClient cliX = new IrDAClient();
IrDADeviceInfo[] devices = cliX.DiscoverDevices(1);
if (devices.Length == 0) {
textBoxReceive.Text += "No device in range.";
return;
}
IrDAEndPoint ep = new IrDAEndPoint(devices[0].DeviceAddress, "OBEX");
//
for (int i = 0; i < 120; ++i) {
try {
textBoxReceive.Text += " | ";
IrDAClient cli = new IrDAClient();
cli.Connect(ep);
textBoxReceive.Text += GetNumericalLsapSel((IrDAEndPoint)cli.Client.LocalEndPoint);
Application.DoEvents();
if (!leaveOpen) {
cli.Dispose();
}
} catch (SocketException sex) {
textBoxReceive.Text += "SEX: " + sex.ErrorCode;
}
}//for
textBoxReceive.Text += " | END";
}
private void menuItemLSR_OC_Click(object sender, EventArgs e)
{
TestLsapSelRange("OBEX", false);
}
private void menuItemLSR_OO_Click(object sender, EventArgs e)
{
TestLsapSelRange("OBEX", true);
}
private void menuItemLSR_NC_Click(object sender, EventArgs e)
{
TestLsapSelRange("NotExist", false);
}
private void menuItemLSR_NO_Click(object sender, EventArgs e)
{
TestLsapSelRange("NotExist", true);
}
#if NETCF
[System.Runtime.InteropServices.DllImport("ws2.dll", EntryPoint = "getsockname"/*"@376"*/, SetLastError = true)]
public static extern int getsockname(IntPtr s, byte[] name, ref int namelen);
// NOT WORKING
// NOT WORKING// NOT WORKING// NOT WORKING// NOT WORKING
// NOT WORKING
// NOT WORKING
// NOT WORKING
// Fails with 10038
System.Net.EndPoint GetLocalEndPoint(Socket socket, System.Net.EndPoint prototype)
{
System.Net.SocketAddress sa = prototype.Serialize();
byte[] buf = new byte[sa.Size];
IntPtr handle = socket.Handle;
int len = buf.Length;
int ret = getsockname(handle, buf, ref len);
if (ret == -1) {
int gle = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
throw new SocketException(gle);
}
System.Diagnostics.Debug.Assert(len == buf.Length, "length out == length in");
for (int i = 0; i < buf.Length; ++i) {
byte cur = buf[i];
sa[i] = cur;
}
System.Net.EndPoint ep = prototype.Create(sa);
return ep;
}
#endif
}//class
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel;
namespace Signum.Utilities
{
public class ConsoleSwitch<K, V> : IEnumerable<KeyValuePair<string, WithDescription<V>>>
where K : notnull
where V : class
{
readonly Dictionary<string, WithDescription<V>> dictionary = new Dictionary<string, WithDescription<V>>(StringComparer.InvariantCultureIgnoreCase);
readonly Dictionary<int, string> separators = new Dictionary<int, string>();
readonly string welcomeMessage;
public ConsoleSwitch()
: this(ConsoleMessage.SelectOneOfTheFollowingOptions.NiceToString())
{
}
public ConsoleSwitch(string welcomeMessage)
{
this.welcomeMessage = welcomeMessage;
}
//Separator
public void Add(string value)
{
separators.AddOrThrow(dictionary.Keys.Count, value, "Already a separator on {0}");
}
public void Add(K key, V value)
{
dictionary.AddOrThrow(key.ToString()!, new WithDescription<V>(value), "Key {0} already in ConsoleSwitch");
}
public void Add(K key, V value, string description)
{
dictionary.AddOrThrow(key.ToString()!, new WithDescription<V>(value, description), "Key {0} already in ConsoleSwitch");
}
public V? Choose(int? numberOfOptions = null)
{
var tuple = ChooseTuple(numberOfOptions);
if (tuple == null)
return null;
return tuple.Value;
}
public WithDescription<V>? ChooseTuple(int? numberOfOptions = null)
{
Console.WriteLine(welcomeMessage);
var noOfOptsPerScreen = numberOfOptions ?? dictionary.Count;
PrintOptions(0, noOfOptsPerScreen);
var noOfOptsPrinted = noOfOptsPerScreen;
do
{
var input = Console.ReadLine().Trim();
if (input == "+")
{
if (noOfOptsPrinted >= dictionary.Count)
continue;
PrintOptions(noOfOptsPrinted, noOfOptsPerScreen);
}
else
{
if (string.IsNullOrWhiteSpace(input))
return null;
var val = TryGetValue(input);
if (val != null)
return val;
SafeConsole.WriteLineColor(ConsoleColor.Red, "Plase choose a valid option!");
noOfOptsPrinted = 0;
PrintOptions(noOfOptsPrinted, noOfOptsPerScreen);
}
noOfOptsPrinted += noOfOptsPerScreen;
} while (true);
}
void PrintOptions(int skip, int take)
{
var keys = dictionary.Keys.ToList();
var max = Math.Min(keys.Count, skip + take);
for (int i = skip; i < max; i++)
{
var key = keys[i];
string? value = separators.TryGetC(i);
if (value.HasText())
{
Console.WriteLine();
Console.WriteLine(value);
}
SafeConsole.WriteColor(ConsoleColor.White, " " + keys[i]);
Console.WriteLine(" - " + dictionary[key].Description);
}
if (skip + take >= dictionary.Count) return;
SafeConsole.WriteColor(ConsoleColor.White, " +");
Console.WriteLine(" - " + ConsoleMessage.More.NiceToString());
}
public V[]? ChooseMultiple(string[]? args = null)
{
return ChooseMultiple(ConsoleMessage.EnterYoutSelectionsSeparatedByComma.NiceToString(), args);
}
public V[]? ChooseMultiple(string endMessage, string[]? args = null)
{
var array = ChooseMultipleWithDescription(endMessage, args);
if (array == null)
return null;
return array.Select(a => a.Value).ToArray();
}
public WithDescription<V>[]? ChooseMultipleWithDescription(string[]? args = null)
{
return ChooseMultipleWithDescription(ConsoleMessage.EnterYoutSelectionsSeparatedByComma.NiceToString(), args);
}
public WithDescription<V>[]? ChooseMultipleWithDescription(string endMessage, string[]? args = null)
{
if (args != null)
return args.ToString(" ").SplitNoEmpty(',').SelectMany(GetValuesRange).ToArray();
retry:
try
{
Console.WriteLine(welcomeMessage);
PrintOptions(0, this.dictionary.Count);
Console.WriteLine(endMessage);
string line = Console.ReadLine();
if (string.IsNullOrEmpty(line))
{
Console.Clear();
return null;
}
Console.WriteLine();
return line.SplitNoEmpty(',').SelectMany(GetValuesRange).ToArray();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
goto retry;
}
}
IEnumerable<WithDescription<V>> GetValuesRange(string line)
{
if (line.Contains('-'))
{
int? from = line.Before('-')?.Let(s => s.HasText() ? GetIndex(s.Trim()) : (int?)null);
int? to = line.After('-')?.Let(s => s.HasText() ? GetIndex(s.Trim()) : (int?)null);
if (from == null && to == null)
return Enumerable.Empty<WithDescription<V>>();
if (from == null && to.HasValue)
return dictionary.Keys.Take(to.Value + 1).Select(s => dictionary.GetOrThrow(s));
if (from.HasValue && to == null)
return dictionary.Keys.Skip(from.Value).Select(s => dictionary.GetOrThrow(s));
#pragma warning disable CS8629 // Nullable value type may be null. CSBUG
return dictionary.Keys.Skip(from.Value).Take((to.Value + 1) - from.Value).Select(s => dictionary.GetOrThrow(s));
#pragma warning restore CS8629 // Nullable value type may be null.
}
else
{
return new[] { GetValue(line.Trim()) };
}
}
int GetIndex(string value)
{
int index = dictionary.Keys.IndexOf(value);
if (index == -1)
throw new KeyNotFoundException(ConsoleMessage.NoOptionWithKey0Found.NiceToString().FormatWith(value));
return index;
}
WithDescription<V>? TryGetValue(string input)
{
var exact = dictionary.TryGetC(input);
if (exact != null)
return exact;
var sd = new StringDistance();
var best = dictionary.Keys.WithMin(a => sd.LevenshteinDistance(input.ToLowerInvariant(), a.ToLowerInvariant()));
if (sd.LevenshteinDistance(input.ToLowerInvariant(), best.ToLowerInvariant()) <= 2)
{
if (SafeConsole.Ask($"Did you mean '{best}'?"))
return dictionary.GetOrThrow(best);
}
return null;
}
WithDescription<V> GetValue(string input)
{
var result = TryGetValue(input);
if (result == null)
throw new KeyNotFoundException(ConsoleMessage.NoOptionWithKey0Found.NiceToString(input));
return result;
}
public IEnumerator<KeyValuePair<string, WithDescription<V>>> GetEnumerator()
{
return dictionary.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public enum ConsoleMessage
{
[Description("Enter your selection (nothing to exit): ")]
EnterYourSelection,
[Description("Enter your selections separated by comma or hyphen (nothing to exit): ")]
EnterYoutSelectionsSeparatedByComma,
[Description("No option with key {0} found")]
NoOptionWithKey0Found,
[Description("Select one of the following options:")]
SelectOneOfTheFollowingOptions,
[Description("more...")]
More
}
public class WithDescription<T>
where T : class
{
public T Value { get; private set; }
public string Description { get; private set; }
public WithDescription(T value)
: this(value, DefaultDescription(value))
{
}
public WithDescription(T value, string description)
{
this.Value = value;
this.Description = description;
}
static string DefaultDescription(object value)
{
if (value is Delegate d)
return d.Method.Name.SpacePascal(true);
if (value is Enum e)
return e.NiceToString();
if (value == null)
return "[No Name]";
return value.ToString()!;
}
}
public static class ConsoleSwitchExtensions
{
public static T? ChooseConsole<T>(this IEnumerable<T> collection, Func<T, string>? getString = null, string? message = null) where T : class {
var cs = new ConsoleSwitch<int, T>(message ?? ConsoleMessage.SelectOneOfTheFollowingOptions.NiceToString());
cs.Load(collection.ToList(), getString);
return cs.Choose();
}
public static T[]? ChooseConsoleMultiple<T>(this IEnumerable<T> collection, Func<T, string>? getString = null, string? message = null) where T : class
{
var cs = new ConsoleSwitch<int, T>(message ?? ConsoleMessage.SelectOneOfTheFollowingOptions.NiceToString());
cs.Load(collection.ToList(), getString);
return cs.ChooseMultiple();
}
public static ConsoleSwitch<int, T> Load<T>(this ConsoleSwitch<int, T> cs, List<T> collection, Func<T, string>? getString = null) where T : class
{
for (int i = 0; i < collection.Count; i++)
{
var item = collection[i];
if (getString != null)
cs.Add(i, item, getString(item));
else
cs.Add(i, item);
}
return cs;
}
}
}
| |
/*
* 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.Text;
using OpenMetaverse;
namespace OpenSim.Framework.Serialization
{
/// <summary>
/// Constants for the archiving module
/// </summary>
public class ArchiveConstants
{
/// <value>
/// The location of the archive control file
/// </value>
public const string CONTROL_FILE_PATH = "archive.xml";
/// <value>
/// Path for the assets held in an archive
/// </value>
public const string ASSETS_PATH = "assets/";
/// <value>
/// Path for the inventory data
/// </value>
public const string INVENTORY_PATH = "inventory/";
/// <value>
/// Path for regions in a multi-region archive
/// </value>
public const string REGIONS_PATH = "regions/";
/// <value>
/// Path for the prims file
/// </value>
public const string OBJECTS_PATH = "objects/";
/// <value>
/// Path for terrains. Technically these may be assets, but I think it's quite nice to split them out.
/// </value>
public const string TERRAINS_PATH = "terrains/";
/// <value>
/// Path for region settings.
/// </value>
public const string SETTINGS_PATH = "settings/";
/// <value>
/// Path for region settings.
/// </value>
public const string LANDDATA_PATH = "landdata/";
/// <value>
/// Path for user profiles
/// </value>
public const string USERS_PATH = "userprofiles/";
/// <value>
/// The character the separates the uuid from extension information in an archived asset filename
/// </value>
public const string ASSET_EXTENSION_SEPARATOR = "_";
/// <value>
/// Used to separate components in an inventory node name
/// </value>
public const string INVENTORY_NODE_NAME_COMPONENT_SEPARATOR = "__";
/// <summary>
/// Template used for creating filenames in OpenSim Archives.
/// </summary>
public const string OAR_OBJECT_FILENAME_TEMPLATE = "{0}_{1:000}-{2:000}-{3:000}__{4}.xml";
/// <value>
/// Extensions used for asset types in the archive
/// </value>
public static readonly IDictionary<sbyte, string> ASSET_TYPE_TO_EXTENSION = new Dictionary<sbyte, string>();
public static readonly IDictionary<string, sbyte> EXTENSION_TO_ASSET_TYPE = new Dictionary<string, sbyte>();
static ArchiveConstants()
{
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.Animation] = ASSET_EXTENSION_SEPARATOR + "animation.bvh";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.Bodypart] = ASSET_EXTENSION_SEPARATOR + "bodypart.txt";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.CallingCard] = ASSET_EXTENSION_SEPARATOR + "callingcard.txt";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.Clothing] = ASSET_EXTENSION_SEPARATOR + "clothing.txt";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.Folder] = ASSET_EXTENSION_SEPARATOR + "folder.txt"; // Not sure if we'll ever see this
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.Gesture] = ASSET_EXTENSION_SEPARATOR + "gesture.txt";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.ImageJPEG] = ASSET_EXTENSION_SEPARATOR + "image.jpg";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.ImageTGA] = ASSET_EXTENSION_SEPARATOR + "image.tga";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.Landmark] = ASSET_EXTENSION_SEPARATOR + "landmark.txt";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.LostAndFoundFolder] = ASSET_EXTENSION_SEPARATOR + "lostandfoundfolder.txt"; // Not sure if we'll ever see this
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.LSLBytecode] = ASSET_EXTENSION_SEPARATOR + "bytecode.lso";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.LSLText] = ASSET_EXTENSION_SEPARATOR + "script.lsl";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.Mesh] = ASSET_EXTENSION_SEPARATOR + "mesh.llmesh";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.Notecard] = ASSET_EXTENSION_SEPARATOR + "notecard.txt";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.Object] = ASSET_EXTENSION_SEPARATOR + "object.xml";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.RootFolder] = ASSET_EXTENSION_SEPARATOR + "rootfolder.txt"; // Not sure if we'll ever see this
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.Simstate] = ASSET_EXTENSION_SEPARATOR + "simstate.bin"; // Not sure if we'll ever see this
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.SnapshotFolder] = ASSET_EXTENSION_SEPARATOR + "snapshotfolder.txt"; // Not sure if we'll ever see this
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.Sound] = ASSET_EXTENSION_SEPARATOR + "sound.ogg";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.SoundWAV] = ASSET_EXTENSION_SEPARATOR + "sound.wav";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.Texture] = ASSET_EXTENSION_SEPARATOR + "texture.jp2";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.TextureTGA] = ASSET_EXTENSION_SEPARATOR + "texture.tga";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.TrashFolder] = ASSET_EXTENSION_SEPARATOR + "trashfolder.txt"; // Not sure if we'll ever see this
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "animation.bvh"] = (sbyte)AssetType.Animation;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "bodypart.txt"] = (sbyte)AssetType.Bodypart;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "callingcard.txt"] = (sbyte)AssetType.CallingCard;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "clothing.txt"] = (sbyte)AssetType.Clothing;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "folder.txt"] = (sbyte)AssetType.Folder;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "gesture.txt"] = (sbyte)AssetType.Gesture;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "image.jpg"] = (sbyte)AssetType.ImageJPEG;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "image.tga"] = (sbyte)AssetType.ImageTGA;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "landmark.txt"] = (sbyte)AssetType.Landmark;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "lostandfoundfolder.txt"] = (sbyte)AssetType.LostAndFoundFolder;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "bytecode.lso"] = (sbyte)AssetType.LSLBytecode;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "script.lsl"] = (sbyte)AssetType.LSLText;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "mesh.llmesh"] = (sbyte)AssetType.Mesh;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "notecard.txt"] = (sbyte)AssetType.Notecard;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "object.xml"] = (sbyte)AssetType.Object;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "rootfolder.txt"] = (sbyte)AssetType.RootFolder;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "simstate.bin"] = (sbyte)AssetType.Simstate;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "snapshotfolder.txt"] = (sbyte)AssetType.SnapshotFolder;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "sound.ogg"] = (sbyte)AssetType.Sound;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "sound.wav"] = (sbyte)AssetType.SoundWAV;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "texture.jp2"] = (sbyte)AssetType.Texture;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "texture.tga"] = (sbyte)AssetType.TextureTGA;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "trashfolder.txt"] = (sbyte)AssetType.TrashFolder;
}
public static string CreateOarLandDataPath(LandData ld)
{
return string.Format("{0}{1}.xml", ArchiveConstants.LANDDATA_PATH, ld.GlobalID);
}
/// <summary>
/// Create the filename used to store an object in an OpenSim Archive.
/// </summary>
/// <param name="objectName"></param>
/// <param name="uuid"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static string CreateOarObjectFilename(string objectName, UUID uuid, Vector3 pos)
{
return string.Format(
OAR_OBJECT_FILENAME_TEMPLATE, objectName,
Math.Round(pos.X), Math.Round(pos.Y), Math.Round(pos.Z),
uuid);
}
/// <summary>
/// Create the path used to store an object in an OpenSim Archives.
/// </summary>
/// <param name="objectName"></param>
/// <param name="uuid"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static string CreateOarObjectPath(string objectName, UUID uuid, Vector3 pos)
{
return OBJECTS_PATH + CreateOarObjectFilename(objectName, uuid, pos);
}
/// <summary>
/// Extract a plain path from an IAR path
/// </summary>
/// <param name="iarPath"></param>
/// <returns></returns>
public static string ExtractPlainPathFromIarPath(string iarPath)
{
List<string> plainDirs = new List<string>();
string[] iarDirs = iarPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string iarDir in iarDirs)
{
if (!iarDir.Contains(ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR))
plainDirs.Add(iarDir);
int i = iarDir.LastIndexOf(ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR);
plainDirs.Add(iarDir.Remove(i));
}
return string.Join("/", plainDirs.ToArray());
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web.Mvc;
namespace Cats.Models.Hubs.ViewModels
{
public class ReceiveViewModel
{
#region List of Things used in the recieve view model
//todo:separation of concern
// private IUnitOfWork _Repository = new UnitOfWork();
private UserProfile _UserProfile = null;
/// <summary>
/// Lists of important Lookups,
/// </summary>
///
private List<Unit> _units;
public List<Unit> Units
{
get
{
//TODO://Refactor
//if (_units == null)
//{
// _units = _Repository.UnitRepository.GetAll().OrderBy(o => o.Name).ToList();
//}
return _units;
}
}
public List<CommodityGrade> CommodityGrades { get; set; }
public List<Commodity> Commodities { get; set; }
public List<Transporter> Transporters { get; set; }
public List<CommodityType> CommodityTypes { get; set; }
public List<CommoditySource> CommoditySources { get; set; }
public List<Donor> Donors { get; set; }
public List<Store> Stores { get; set; }
public List<Program> Programs { get; set; }
public List<Hub> Hubs { get; set; }
private List<AdminUnitItem> _stacks;
public List<AdminUnitItem> Stacks
{
get
{
return _stacks;
/*
//TODO:Make sure constractor stacks variable brings same data with the same logic
if (this.StoreID != 0)
{
var store = new Store();
foreach (var store1 in Stores.Where(store1 => store1.StoreID == StoreID))
{
store = store1;
}
var stacks = new List<AdminUnitItem>();
foreach (var i in store.Stacks)
{
stacks.Add(new AdminUnitItem { Name = i.ToString(), Id = i });
}
return stacks;
}
return new List<AdminUnitItem>();
return _stacks;*/
}
set { _stacks = value; }
}
#endregion
/// <summary>
/// parameterless constructor, which is hidden so that this object is not constructed with out the user being specified,
/// </summary>
public ReceiveViewModel()
{
}
/// <summary>
/// constructor with the testable repositories and the user
/// the user is required because we need to decide what wareshouses to display for her.
/// </summary>
public ReceiveViewModel(List<Commodity> commodities, List<CommodityGrade> commodityGrades, List<Transporter> transporters, List<CommodityType> commodityTypes,
List<CommoditySource> commoditySources, List<Program> programs, List<Donor> donors, List<Hub> hubs, UserProfile user,List<Unit> units )
{
_UserProfile = user;
InitalizeViewModel(commodities, commodityGrades, transporters, commodityTypes,
commoditySources, programs, donors, hubs, user, units);
}
/// <summary>
/// Initalizes the view model.
/// </summary>
private void InitalizeViewModel(List<Commodity> commodities, List<CommodityGrade> commodityGrades, List<Transporter> transporters, List<CommodityType> commodityTypes,
List<CommoditySource> commoditySources, List<Program> programs, List<Donor> donors, List<Hub> hubs, UserProfile user, List<Unit> units)
{
_UserProfile = user;
ReceiveID = null;
IsEditMode = false;
ReceiptDate = DateTime.Now;
InitializeEditLists(commodities, commodityGrades, transporters, commodityTypes,
commoditySources, programs, donors, hubs, user, units);
ReceiveDetails = new List<ReceiveDetailViewModel>();
ReceiveDetails.Add(new ReceiveDetailViewModel());
}
/// <summary>
/// Initializes the edit lists.
/// </summary>
public void InitializeEditLists(List<Commodity> commodities, List<CommodityGrade> commodityGrades, List<Transporter> transporters, List<CommodityType> commodityTypes,
List<CommoditySource> commoditySources, List<Program> programs, List<Donor> donors, List<Hub> hubs, UserProfile user, List<Unit> units)
{
//_UserProfile = user;
Commodities = commodities;// _Repository.Commodity.GetAll().DefaultIfEmpty().OrderBy(o => o.Name).ToList();
CommodityGrades = commodityGrades;// _Repository.CommodityGrade.GetAll().DefaultIfEmpty().OrderBy(o => o.Name).ToList();
Transporters = transporters;// _Repository.Transporter.GetAll().DefaultIfEmpty().OrderBy(o => o.Name).ToList();
CommoditySources = commoditySources;// _Repository.CommoditySource.GetAll().DefaultIfEmpty().OrderBy(o => o.Name).ToList();
CommodityTypes = commodityTypes;// _Repository.CommodityType.GetAll().DefaultIfEmpty().OrderBy(o => o.Name).ToList();
Stores = user.DefaultHubObj.Stores.DefaultIfEmpty().ToList();
Programs = programs;// _Repository.Program.GetAll().DefaultIfEmpty().OrderBy(o => o.Name).ToList();
Donors = donors;// _Repository.Donor.GetAll().DefaultIfEmpty().OrderBy(o => o.Name).ToList();
//=========================Old Comment============================================
//_Repository.Hub.GetOthersWithDifferentOwner(user.DefaultHub); //
//remove the users current ware house from the list not to allow receive from HUBX to HUBX
//==========================end old comment=======================================
Hubs = hubs;// _Repository.Hub.GetAllWithoutId(user.DefaultHub.HubID).DefaultIfEmpty().OrderBy(o => o.Name).ToList();
_units = units;
}
/// <summary>
/// Gets or sets the receive ID.
/// </summary>
/// <value>
/// The receive ID.
/// </value>
[Key]
public Guid? ReceiveID { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this instance is edit mode.
/// </summary>
/// <value>
/// <c>true</c> if this instance is edit mode; otherwise, <c>false</c>.
/// </value>
public bool IsEditMode { get; set; }
public bool ContinueAdding { get; set; }
/// <summary>
/// Gets or sets the SI number.
/// </summary>
/// <value>
/// The SI number.
/// </value>
[Required(ErrorMessage = "SI Number is required")]
public string SINumber { get; set; }
/// <summary>
/// Gets or sets the GRN.
/// </summary>
/// <value>
/// The GRN.
/// </value>
[Required]
[Key]
[RegularExpression("[0-9]*", ErrorMessage = "Only numbers allowed for GRN")]
[StringLength(7, ErrorMessage = "Length Must be less than or equal to 7")]
[Remote("NotUnique", "Receive", AdditionalFields = "ReceiveID")]
public string GRN { get; set; }
/// <summary>
/// Gets or sets the hub ID.
/// </summary>
/// <value>
/// The hub ID.
/// </value>
public int HubID { get; set; }
/// <summary>
/// Gets or sets the store ID.
/// </summary>
/// <value>
/// The store ID.
/// </value>
[Required(ErrorMessage = "Store is required")]
public int StoreID { get; set; }
/// <summary>
/// Gets or sets the stack number.
/// </summary>
/// <value>
/// The stack number.
/// </value>
[Required(ErrorMessage = "Stack number is required")]
public int StackNumber { get; set; }
/// <summary>
/// Gets or sets the commodity type ID.
/// </summary>
/// <value>
/// The commodity type ID.
/// </value>
[Required(ErrorMessage = "Commodity type is required")]
public int CommodityTypeID { get; set; }
/// <summary>
/// Gets or sets the source donor ID.
/// </summary>
/// <value>
/// The source donor ID.
/// </value>
public int? SourceDonorID { get; set; }
/// <summary>
/// Gets or sets the responsible donor ID.
/// </summary>
/// <value>
/// The responsible donor ID.
/// </value>
[Required(ErrorMessage = "Donor is required")]
public int? ResponsibleDonorID { get; set; }
/// <summary>
/// Gets or sets the program ID.
/// </summary>
/// <value>
/// The program ID.
/// </value>
[Required(ErrorMessage = "Program is required")]
public int ProgramID { get; set; }
/// <summary>
/// Gets or sets the transporter ID.
/// </summary>
/// <value>
/// The transporter ID.
/// </value>
[Required(ErrorMessage = "Transporter is required")]
public int TransporterID { get; set; }
/// <summary>
/// Gets or sets the user profile ID.
/// </summary>
/// <value>
/// The user profile ID.
/// </value>
public int UserProfileID { get; set; }
/// <summary>
/// Gets or sets the created date.
/// </summary>
/// <value>
/// The created date.
/// </value>
public DateTime CreatedDate { get; set; }
/// <summary>
/// Gets or sets the receipt date.
/// </summary>
/// <value>
/// The receipt date.
/// </value>
[Required(ErrorMessage = "Reciept date is required")]
[DateStart(ErrorMessage = "The Receipt Date Can not be in the Future")]
public DateTime ReceiptDate { get; set; }
/// <summary>
/// Gets or sets the plate no_ prime.
/// </summary>
/// <value>
/// The plate no_ prime.
/// </value>
[Required(ErrorMessage = "Prime plate number is required")]
[StringLength(50)]
public string PlateNo_Prime { get; set; }
/// <summary>
/// Gets or sets the plate no_ trailer.
/// </summary>
/// <value>
/// The plate no_ trailer.
/// </value>
[StringLength(50)]
public string PlateNo_Trailer { get; set; }
/// <summary>
/// Gets or sets the name of the driver.
/// </summary>
/// <value>
/// The name of the driver.
/// </value>
///
//[RegularExpression("[a-zA-Z\\s]*", ErrorMessage = "Only letters are allowed for Driver name")]
[Required(ErrorMessage = "Driver name is required")]
[Display(Name = "Delivered By (Driver Name)")]
[StringLength(50)]
[UIHint("AmharicTextBox")]
public string DriverName { get; set; }
/// <summary>
/// Gets or sets the weight before unloading.
/// </summary>
/// <value>
/// The weight before unloading.
/// </value>
public decimal? WeightBeforeUnloading { get; set; }
/// <summary>
/// Gets or sets the weight after unloading.
/// </summary>
/// <value>
/// The weight after unloading.
/// </value>
public decimal? WeightAfterUnloading { get; set; }
/// <summary>
/// Gets or sets the way bill no.
/// </summary>
/// <value>
/// The way bill no.
/// </value>
[Required(ErrorMessage = "Waybill number is requied")]
[StringLength(50)]
public string WayBillNo { get; set; }
/// <summary>
/// Gets or sets the project number.
/// </summary>
/// <value>
/// The project number.
/// </value>
[Required(ErrorMessage = "Project code is required")]
[Display(Name = "Project Code")]
public string ProjectNumber { get; set; }
/// <summary>
/// Gets or sets the commodity source ID.
/// </summary>
/// <value>
/// The commodity source ID.
/// </value>
[Required(ErrorMessage = "Commodity source is required")]
public int CommoditySourceID { get; set; }
//TODO:Make sure to set value on commoditySoureText during mapping
public string CommoditySourceText { get; set; }
//public string CommoditySourceText{
// get { return _Repository.CommoditySource.FindById(CommoditySourceID).Name; }
//}
//TODO:Make sure to put SourceHubText during mapping
public string SourceHubText { get; set; }
//public string SourceHubText
//{
// get {
// if (SourceHubID != null)
// return _Repository.Hub.FindById(SourceHubID.Value).HubNameWithOwner;
// return "";
// }
//}
/// <summary>
/// Gets or sets the ticket number.
/// </summary>
/// <value>
/// The ticket number.
/// </value>
[StringLength(10)]
public string TicketNumber { get; set; }
/// <summary>
/// Gets or sets the name of the vessel.
/// </summary>
/// <value>
/// The name of the vessel.
/// </value>
[StringLength(50)]
public string VesselName { get; set; }
/// <summary>
/// Gets or sets the remark.
/// </summary>
/// <value>
/// The remark.
/// </value>
[Display(Name = "Remark")]
[StringLength(4000)]
[UIHint("AmharicTextArea")]
public string Remark { get; set; }
/// <summary>
/// Gets or sets the received by store man.
/// </summary>
/// <value>
/// The received by store man.
/// </value>
[Required(ErrorMessage = "Name of store man is required")]
[Display(Name = "Received By Store Man")]
[StringLength(50)]
[UIHint("AmharicTextBox")]
public string ReceivedByStoreMan { get; set; }
public bool ChangeStoreManPermanently { set; get; }
/// <summary>
/// Gets or sets the name of the port.
/// </summary>
/// <value>
/// The name of the port.
/// </value>
[Display(Name = "Port Name")]
public string PortName { get; set; }
/// <summary>
/// Gets or sets the receive details.
/// </summary>
/// <value>
/// The receive details.
/// </value>
public List<ReceiveDetailViewModel> ReceiveDetails { get; set; }
//[Required]
//[StringLength(10000,MinimumLength= 3,ErrorMessage= "please insert atleast one commodity")]
/// <summary>
/// Gets or sets the JSON inserted commodities.
/// </summary>
/// <value>
/// The JSON inserted commodities.
/// </value>
public string JSONInsertedCommodities { get; set; }
/// <summary>
/// Gets or sets the JSON deleted commodities.
/// </summary>
/// <value>
/// The JSON deleted commodities.
/// </value>
public string JSONDeletedCommodities { get; set; }
/// <summary>
/// Gets or sets the JSON updated commodities.
/// </summary>
/// <value>
/// The JSON updated commodities.
/// </value>
public string JSONUpdatedCommodities { get; set; }
/// <summary>
/// Gets or sets the JSON prev.
/// </summary>
/// <value>
/// The JSON prev.
/// </value>
///
[Required]
//[StringLength(Int32.MaxValue,ErrorMessage = "Please add atleast one commodity to save this Reciept",MinimumLength = 2)]
public string JSONPrev { get; set; }
[StringLength(50)]
[Required]
public String PurchaseOrder { get; set; }
[StringLength(50)]
[Required]
public String SupplierName { get; set; }
[Required]
public Int32? SourceHubID { get; set; }
/// <summary>
/// Generates the receive model.
/// </summary>
/// <param name="receive">The receive.</param>
/// <param name="user">The user.</param>
/// <returns></returns>
public static ReceiveViewModel GenerateReceiveModel(Receive receive, List<Commodity> commodities, List<CommodityGrade> commodityGrades, List<Transporter> transporters, List<CommodityType> commodityTypes,
List<CommoditySource> commoditySources, List<Program> programs, List<Donor> donors, List<Hub> hubs, UserProfile user,List<Unit> units )
{
ReceiveViewModel model = new ReceiveViewModel();
model._UserProfile = user;
model.InitalizeViewModel(commodities, commodityGrades, transporters, commodityTypes,
commoditySources, programs, donors, hubs, user,units);
model.IsEditMode = true;
model.ReceiveID = receive.ReceiveID;
model.DriverName = receive.DriverName;
model.GRN = receive.GRN;
model.PlateNo_Prime = receive.PlateNo_Prime;
model.PlateNo_Trailer = receive.PlateNo_Trailer;
model.TransporterID = receive.TransporterID;
model.HubID = receive.HubID;
ReceiveDetail receiveDetail = receive.ReceiveDetails.FirstOrDefault();//p=>p.QuantityInMT>0);
Transaction receiveDetailtransaction = null;
if (receiveDetail != null)
foreach (Transaction transaction in receiveDetail.TransactionGroup.Transactions)
{
var negTransaction = receiveDetail.TransactionGroup.Transactions.FirstOrDefault(p => p.QuantityInMT < 0);
if (negTransaction != null)
model.SourceHubID = negTransaction.Account.EntityID;
receiveDetailtransaction = transaction;
break;
}
if (receiveDetailtransaction != null)
{
model.SINumber = receiveDetailtransaction.ShippingInstruction != null ? receiveDetailtransaction.ShippingInstruction.Value : "";
model.ProjectNumber = receiveDetailtransaction.ProjectCode != null ? receiveDetailtransaction.ProjectCode.Value : "";
model.ProgramID = receiveDetailtransaction.Program != null ? receiveDetailtransaction.Program.ProgramID : default(int);
model.StoreID = receiveDetailtransaction.Store != null ? receiveDetailtransaction.Store.StoreID : default(int);
model.StackNumber = receiveDetailtransaction.Stack.HasValue ? receiveDetailtransaction.Stack.Value : default(int);
}
else
{
model.SINumber = "";
model.ProjectNumber = "";
model.ProgramID = default(int);
model.StoreID = default(int);
model.StackNumber = default(int);
}
model.ReceiptDate = receive.ReceiptDate;
model.WayBillNo = receive.WayBillNo;
model.CommodityTypeID = receive.CommodityTypeID;
model.ResponsibleDonorID = receive.ResponsibleDonorID;
model.SourceDonorID = receive.SourceDonorID;
model.CommoditySourceID = receive.CommoditySourceID;
model.TicketNumber = receive.WeightBridgeTicketNumber;
model.WeightBeforeUnloading = receive.WeightBeforeUnloading;
model.WeightAfterUnloading = receive.WeightAfterUnloading;
model.VesselName = receive.VesselName;
model.PortName = receive.PortName;
model.ReceiptAllocationID = receive.ReceiptAllocationID;
model.PurchaseOrder = receive.PurchaseOrder;
model.SupplierName = receive.SupplierName;
model.Remark = receive.Remark;
model.ReceivedByStoreMan = receive.ReceivedByStoreMan;
model.ReceiveDetails =Cats.Models.Hubs.ReceiveDetailViewModel.GenerateReceiveDetailModels(receive.ReceiveDetails);
return model;
}
/// <summary>
/// Generates the receive.
/// </summary>
/// <returns></returns>
public Receive GenerateReceive()
{
Receive receive = new Receive()
{
CreatedDate = DateTime.Now,
ReceiptDate = this.ReceiptDate,
DriverName = this.DriverName,
GRN = this.GRN,
PlateNo_Prime = this.PlateNo_Prime,
PlateNo_Trailer = this.PlateNo_Trailer,
TransporterID = this.TransporterID,
HubID = this.HubID,
CommodityTypeID = this.CommodityTypeID,
WayBillNo = this.WayBillNo,
ResponsibleDonorID = this.ResponsibleDonorID,
SourceDonorID = this.SourceDonorID,
CommoditySourceID = this.CommoditySourceID,
WeightBridgeTicketNumber = this.TicketNumber,
WeightBeforeUnloading = this.WeightBeforeUnloading,
WeightAfterUnloading = this.WeightAfterUnloading,
ReceivedByStoreMan = this.ReceivedByStoreMan,
VesselName = this.VesselName,
PortName = this.PortName,
PurchaseOrder = this.PurchaseOrder,
SupplierName = this.SupplierName,
ReceiptAllocationID = this.ReceiptAllocationID,
Remark = this.Remark,
};
if (this.ReceiveID.HasValue)
{
receive.ReceiveID = this.ReceiveID.Value;
}
else
{
receive.ReceiveID = Guid.NewGuid();
}
return receive;
}
public Guid? ReceiptAllocationID { get; set; }
}
}
| |
/*
* Copyright 2010 www.wojilu.com
*
* 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.CodeDom.Compiler;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Text;
using Microsoft.CSharp;
using wojilu.Data;
using wojilu.ORM;
using wojilu.IO;
namespace wojilu.Reflection {
internal class CodeDomPropertyAccessor {
private static IDictionary _accessorList;
private static Hashtable _concreteFactoryList = new Hashtable();
private static readonly ILog logger = LogManager.GetLogger( typeof( CodeDomPropertyAccessor ) );
public static void Init( MetaList metaList ) {
GetAccessorList( metaList );
}
public static IPropertyAccessor GetAccessor( String typeFullName, String propertyName, MetaList metaList ) {
return (GetAccessorList( metaList )[getAccessorName( typeFullName, propertyName )] as IPropertyAccessor);
}
public static IDictionary GetAccessorList( MetaList metaList ) {
if (_accessorList == null) {
IDictionary classList = metaList.ClassList;
IDictionary asmList = metaList.AssemblyList;
Assembly assembly = CompileCode( GetAccessorCode( classList ), asmList );
_accessorList = (assembly.CreateInstance( "wojilu.Reflection.CodeDomAccessorUtil" ) as IAccessorUtil).GetAccessorList();
foreach (DictionaryEntry entry in classList) {
String typeFullName = entry.Key.ToString();
IConcreteFactory factory = assembly.CreateInstance( getConcreteFactoryName( typeFullName ) ) as IConcreteFactory;
_concreteFactoryList[typeFullName] = factory;
}
}
return _accessorList;
}
public static String GetAccessorCode( IDictionary classList ) {
StringBuilder builder = new StringBuilder();
builder.Append( "\n\nusing System;\n" );
builder.Append( "using System.Collections;\n" );
builder.Append( "using System.Collections.Generic;\n" );
builder.Append( "namespace wojilu.Reflection {\n" );
StringBuilder clsBuilder = new StringBuilder();
StringBuilder utilBuilder = new StringBuilder();
utilBuilder.Append( "[Serializable]\n" );
utilBuilder.Append( "public class CodeDomAccessorUtil : IAccessorUtil {\n" );
utilBuilder.Append( "\tprivate IDictionary _list;\n" );
utilBuilder.Append( "\tpublic IDictionary GetAccessorList() {\n" );
utilBuilder.Append( "\t\tif( _list == null ) {\n" );
utilBuilder.Append( "\t\t_list = new Hashtable();\n" );
foreach (DictionaryEntry entry in classList) {
String str = entry.Key.ToString();
EntityInfo info = entry.Value as EntityInfo;
Type type = info.Type;
clsBuilder.Append( "\t[Serializable]\n" );
clsBuilder.Append( "\tpublic class " );
clsBuilder.Append( str.Replace( ".", "" ) );
clsBuilder.Append( "Factory : IConcreteFactory {\n" );
//clsBuilder.Append( "\t\tpublic ObjectBase New() {\n" );
clsBuilder.Append( "\t\tpublic IEntity New() {\n" );
if ((type.GetConstructors().Length < 0) || (type.GetConstructor( Type.EmptyTypes ) == null)) {
clsBuilder.Append( "\t\t\treturn null;\n" );
}
else {
clsBuilder.AppendFormat( "\t\t\treturn new {0}();\n", str );
}
clsBuilder.Append( "\t\t}\n" );
clsBuilder.Append( "\t}\n" );
foreach (EntityPropertyInfo ep in info.PropertyListAll) {
if (ep.Name == "OID") {
continue;
}
String acname = getAccessorName( str, ep.Name );
builder.Append( "\n" );
builder.Append( "[Serializable]\n" );
builder.AppendFormat( "public class {0} : IPropertyAccessor ", acname );
builder.Append( "{\n" );
builder.Append( "\tpublic Object Get(Object target) {\n" );
if (ep.Property.CanRead) {
builder.AppendFormat( "\t\t{0} data = ({0})target;\n", str );
builder.AppendFormat( "\t\treturn data.{0};\n", ep.Name );
}
else {
builder.AppendFormat( "\t\tthrow new Exception( \"the current property {0}.{1} can't read. \" );\n", ep.ParentEntityInfo.FullName, ep.Name );
}
builder.Append( "\t}\n\n" );
builder.Append( "\tpublic void Set( Object target, Object val ) {\n" );
if (ep.Property.CanWrite) {
builder.AppendFormat( String.Format( "\t\t{0} data = ({0})target;\n", str ), new object[0] );
String ptname = ReflectionUtil.getPropertyTypeName( ep.Property );
builder.AppendFormat( String.Format( "\t\tdata.{0} = ({1})val;\n", ep.Name, ptname ), new object[0] );
}
builder.Append( "\t}\n" );
builder.Append( "}\n" );
utilBuilder.AppendFormat( "\t\t_list[\"{0}\"] = new {0}();\n", acname );
}
}
utilBuilder.Append( "\t}\n" );
utilBuilder.Append( "\treturn _list;\n" );
utilBuilder.Append( "}\n" );
utilBuilder.Append( "}\n" );
builder.Append( utilBuilder );
builder.Append( clsBuilder );
builder.Append( "}" );
return builder.ToString();
}
public static Assembly CompileCode( String code, IDictionary asmList ) {
//logger.Info( code );
CodeDomProvider provider = new CSharpCodeProvider();
CompilerParameters options = new CompilerParameters();
options.GenerateExecutable = false;
options.CompilerOptions = "/optimize";
if (strUtil.HasText( DbConfig.Instance.MetaDLL )) {
options.GenerateInMemory = false;
options.OutputAssembly = Path.Combine( PathTool.GetBinDirectory(), "_wojilu.accessor.dll" );
}
else {
options.GenerateInMemory = true;
}
Hashtable tblReferencedAsms = new Hashtable();
Assembly executingAssembly = Assembly.GetExecutingAssembly();
tblReferencedAsms[executingAssembly.FullName] = executingAssembly.Location;
logger.Info( executingAssembly.FullName + "__" + executingAssembly.Location );
addReferencedAsms( tblReferencedAsms, executingAssembly.GetReferencedAssemblies() );
foreach (DictionaryEntry entry in asmList) {
Assembly asm = entry.Value as Assembly;
tblReferencedAsms[asm.FullName] = asm.Location;
logger.Info( asm.FullName + "__" + asm.Location );
addReferencedAsms( tblReferencedAsms, asm.GetReferencedAssemblies() );
}
foreach (DictionaryEntry entry in tblReferencedAsms) {
options.ReferencedAssemblies.Add( entry.Value.ToString() );
}
CompilerResults results = provider.CompileAssemblyFromSource( options, new String[] { code } );
if (results.Errors.Count > 0) {
StringBuilder builder = new StringBuilder();
foreach (CompilerError error in results.Errors) {
builder.Append( error.ErrorText );
builder.Append( "\n" );
}
logger.Fatal( code );
throw new Exception( builder.ToString() );
}
return results.CompiledAssembly;
}
private static void addReferencedAsms( Hashtable tblReferencedAsms, AssemblyName[] assemblyName ) {
foreach (AssemblyName name in assemblyName) {
if (tblReferencedAsms[name.FullName] == null) {
Assembly assembly = Assembly.Load( name );
tblReferencedAsms[name.FullName] = assembly.Location;
logger.Info( name.FullName + "__" + assembly.Location );
}
}
}
private static String getAccessorName( String typeFullName, String propertyName ) {
return String.Format( "{0}_{1}", typeFullName.Replace( ".", "" ), propertyName );
}
private static String getConcreteFactoryName( String typeFullName ) {
return String.Format( "wojilu.Reflection.{0}Factory", typeFullName.Replace( ".", "" ) );
}
public static Hashtable GetFactoryList() {
return _concreteFactoryList;
}
}
}
| |
using J2N.Text;
using Lucene.Net.Util;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using BytesRef = Lucene.Net.Util.BytesRef;
using Directory = Lucene.Net.Store.Directory;
namespace Lucene.Net.Codecs.Lucene3x
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using FieldInfos = Lucene.Net.Index.FieldInfos;
using IndexFileNames = Lucene.Net.Index.IndexFileNames;
using IOContext = Lucene.Net.Store.IOContext;
using IOUtils = Lucene.Net.Util.IOUtils;
using Term = Lucene.Net.Index.Term;
/// <summary>
/// This stores a monotonically increasing set of <c>Term, TermInfo</c> pairs in a
/// Directory. Pairs are accessed either by <see cref="Term"/> or by ordinal position the
/// set.
/// <para/>
/// @lucene.experimental
/// </summary>
[Obsolete("(4.0) this class has been replaced by FormatPostingsTermsDictReader, except for reading old segments.")]
internal sealed class TermInfosReader : IDisposable
{
private readonly Directory directory;
private readonly string segment;
private readonly FieldInfos fieldInfos;
private readonly DisposableThreadLocal<ThreadResources> threadResources = new DisposableThreadLocal<ThreadResources>();
private readonly SegmentTermEnum origEnum;
private readonly long size;
private readonly TermInfosReaderIndex index;
private readonly int indexLength;
private readonly int totalIndexInterval;
private const int DEFAULT_CACHE_SIZE = 1024;
// Just adds term's ord to TermInfo
public sealed class TermInfoAndOrd : TermInfo
{
internal readonly long termOrd;
public TermInfoAndOrd(TermInfo ti, long termOrd)
: base(ti)
{
Debug.Assert(termOrd >= 0);
this.termOrd = termOrd;
}
}
private class CloneableTerm : DoubleBarrelLRUCache.CloneableKey
{
internal Term term;
public CloneableTerm(Term t)
{
this.term = t;
}
public override bool Equals(object other)
{
CloneableTerm t = (CloneableTerm)other;
return this.term.Equals(t.term);
}
public override int GetHashCode()
{
return term.GetHashCode();
}
public override object Clone()
{
return new CloneableTerm(term);
}
}
private readonly DoubleBarrelLRUCache<CloneableTerm, TermInfoAndOrd> termsCache = new DoubleBarrelLRUCache<CloneableTerm, TermInfoAndOrd>(DEFAULT_CACHE_SIZE);
/// <summary>
/// Per-thread resources managed by ThreadLocal.
/// </summary>
private sealed class ThreadResources
{
internal SegmentTermEnum termEnum;
}
internal TermInfosReader(Directory dir, string seg, FieldInfos fis, IOContext context, int indexDivisor)
{
bool success = false;
if (indexDivisor < 1 && indexDivisor != -1)
{
throw new ArgumentException("indexDivisor must be -1 (don't load terms index) or greater than 0: got " + indexDivisor);
}
try
{
directory = dir;
segment = seg;
fieldInfos = fis;
origEnum = new SegmentTermEnum(directory.OpenInput(IndexFileNames.SegmentFileName(segment, "", Lucene3xPostingsFormat.TERMS_EXTENSION), context), fieldInfos, false);
size = origEnum.size;
if (indexDivisor != -1)
{
// Load terms index
totalIndexInterval = origEnum.indexInterval * indexDivisor;
string indexFileName = IndexFileNames.SegmentFileName(segment, "", Lucene3xPostingsFormat.TERMS_INDEX_EXTENSION);
SegmentTermEnum indexEnum = new SegmentTermEnum(directory.OpenInput(indexFileName, context), fieldInfos, true);
try
{
index = new TermInfosReaderIndex(indexEnum, indexDivisor, dir.FileLength(indexFileName), totalIndexInterval);
indexLength = index.Length;
}
finally
{
indexEnum.Dispose();
}
}
else
{
// Do not load terms index:
totalIndexInterval = -1;
index = null;
indexLength = -1;
}
success = true;
}
finally
{
// With lock-less commits, it's entirely possible (and
// fine) to hit a FileNotFound exception above. In
// this case, we want to explicitly close any subset
// of things that were opened so that we don't have to
// wait for a GC to do so.
if (!success)
{
Dispose();
}
}
}
public int SkipInterval => origEnum.skipInterval;
public int MaxSkipLevels => origEnum.maxSkipLevels;
public void Dispose()
{
IOUtils.Dispose(origEnum, threadResources);
}
/// <summary>
/// Returns the number of term/value pairs in the set.
/// <para/>
/// NOTE: This was size() in Lucene.
/// </summary>
internal long Count => size;
private ThreadResources GetThreadResources()
{
ThreadResources resources = threadResources.Get();
if (resources == null)
{
resources = new ThreadResources();
resources.termEnum = Terms();
threadResources.Set(resources);
}
return resources;
}
private static readonly IComparer<BytesRef> legacyComparer = BytesRef.UTF8SortedAsUTF16Comparer;
private int CompareAsUTF16(Term term1, Term term2)
{
if (term1.Field.Equals(term2.Field, StringComparison.Ordinal))
{
return legacyComparer.Compare(term1.Bytes, term2.Bytes);
}
else
{
return term1.Field.CompareToOrdinal(term2.Field);
}
}
/// <summary>
/// Returns the <see cref="TermInfo"/> for a <see cref="Term"/> in the set, or <c>null</c>. </summary>
internal TermInfo Get(Term term)
{
return Get(term, false);
}
/// <summary>
/// Returns the <see cref="TermInfo"/> for a <see cref="Term"/> in the set, or <c>null</c>. </summary>
private TermInfo Get(Term term, bool mustSeekEnum)
{
if (size == 0)
{
return null;
}
EnsureIndexIsRead();
TermInfoAndOrd tiOrd = termsCache.Get(new CloneableTerm(term));
ThreadResources resources = GetThreadResources();
if (!mustSeekEnum && tiOrd != null)
{
return tiOrd;
}
return SeekEnum(resources.termEnum, term, tiOrd, true);
}
public void CacheCurrentTerm(SegmentTermEnum enumerator)
{
termsCache.Put(new CloneableTerm(enumerator.Term()), new TermInfoAndOrd(enumerator.termInfo, enumerator.position));
}
internal static Term DeepCopyOf(Term other)
{
return new Term(other.Field, BytesRef.DeepCopyOf(other.Bytes));
}
internal TermInfo SeekEnum(SegmentTermEnum enumerator, Term term, bool useCache)
{
if (useCache)
{
return SeekEnum(enumerator, term, termsCache.Get(new CloneableTerm(DeepCopyOf(term))), useCache);
}
else
{
return SeekEnum(enumerator, term, null, useCache);
}
}
internal TermInfo SeekEnum(SegmentTermEnum enumerator, Term term, TermInfoAndOrd tiOrd, bool useCache)
{
if (size == 0)
{
return null;
}
// optimize sequential access: first try scanning cached enum w/o seeking
if (enumerator.Term() != null && ((enumerator.Prev() != null && CompareAsUTF16(term, enumerator.Prev()) > 0) || CompareAsUTF16(term, enumerator.Term()) >= 0)) // term is at or past current
{
int enumOffset = (int)(enumerator.position / totalIndexInterval) + 1;
if (indexLength == enumOffset || index.CompareTo(term, enumOffset) < 0) // but before end of block
{
// no need to seek
TermInfo ti;
int numScans = enumerator.ScanTo(term);
if (enumerator.Term() != null && CompareAsUTF16(term, enumerator.Term()) == 0)
{
ti = enumerator.termInfo;
if (numScans > 1)
{
// we only want to put this TermInfo into the cache if
// scanEnum skipped more than one dictionary entry.
// this prevents RangeQueries or WildcardQueries to
// wipe out the cache when they iterate over a large numbers
// of terms in order
if (tiOrd == null)
{
if (useCache)
{
termsCache.Put(new CloneableTerm(DeepCopyOf(term)), new TermInfoAndOrd(ti, enumerator.position));
}
}
else
{
Debug.Assert(SameTermInfo(ti, tiOrd, enumerator));
Debug.Assert(enumerator.position == tiOrd.termOrd);
}
}
}
else
{
ti = null;
}
return ti;
}
}
// random-access: must seek
int indexPos;
if (tiOrd != null)
{
indexPos = (int)(tiOrd.termOrd / totalIndexInterval);
}
else
{
// Must do binary search:
indexPos = index.GetIndexOffset(term);
}
index.SeekEnum(enumerator, indexPos);
enumerator.ScanTo(term);
TermInfo ti_;
if (enumerator.Term() != null && CompareAsUTF16(term, enumerator.Term()) == 0)
{
ti_ = enumerator.termInfo;
if (tiOrd == null)
{
if (useCache)
{
termsCache.Put(new CloneableTerm(DeepCopyOf(term)), new TermInfoAndOrd(ti_, enumerator.position));
}
}
else
{
Debug.Assert(SameTermInfo(ti_, tiOrd, enumerator));
Debug.Assert(enumerator.position == tiOrd.termOrd);
}
}
else
{
ti_ = null;
}
return ti_;
}
// called only from asserts
private bool SameTermInfo(TermInfo ti1, TermInfo ti2, SegmentTermEnum enumerator)
{
if (ti1.DocFreq != ti2.DocFreq)
{
return false;
}
if (ti1.FreqPointer != ti2.FreqPointer)
{
return false;
}
if (ti1.ProxPointer != ti2.ProxPointer)
{
return false;
}
// skipOffset is only valid when docFreq >= skipInterval:
if (ti1.DocFreq >= enumerator.skipInterval && ti1.SkipOffset != ti2.SkipOffset)
{
return false;
}
return true;
}
private void EnsureIndexIsRead()
{
if (index == null)
{
throw new InvalidOperationException("terms index was not loaded when this reader was created");
}
}
/// <summary>
/// Returns the position of a <see cref="Term"/> in the set or -1. </summary>
internal long GetPosition(Term term)
{
if (size == 0)
{
return -1;
}
EnsureIndexIsRead();
int indexOffset = index.GetIndexOffset(term);
SegmentTermEnum enumerator = GetThreadResources().termEnum;
index.SeekEnum(enumerator, indexOffset);
while (CompareAsUTF16(term, enumerator.Term()) > 0 && enumerator.Next())
{
}
if (CompareAsUTF16(term, enumerator.Term()) == 0)
{
return enumerator.position;
}
else
{
return -1;
}
}
/// <summary>
/// Returns an enumeration of all the <see cref="Term"/>s and <see cref="TermInfo"/>s in the set. </summary>
public SegmentTermEnum Terms()
{
return (SegmentTermEnum)origEnum.Clone();
}
/// <summary>
/// Returns an enumeration of terms starting at or after the named term. </summary>
public SegmentTermEnum Terms(Term term)
{
Get(term, true);
return (SegmentTermEnum)GetThreadResources().termEnum.Clone();
}
internal long RamBytesUsed()
{
return index == null ? 0 : index.RamBytesUsed();
}
}
}
| |
using System;
using System.Globalization;
using System.Xml;
using JetBrains.Annotations;
using Orchard.Comments.Models;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Drivers;
using Orchard.ContentManagement.Aspects;
using Orchard.Services;
using Orchard.Localization;
using Orchard.Comments.Services;
using Orchard.UI.Notify;
namespace Orchard.Comments.Drivers {
[UsedImplicitly]
public class CommentPartDriver : ContentPartDriver<CommentPart> {
private readonly IContentManager _contentManager;
private readonly IWorkContextAccessor _workContextAccessor;
private readonly IClock _clock;
private readonly ICommentService _commentService;
private readonly IOrchardServices _orchardServices;
protected override string Prefix { get { return "Comments"; } }
public Localizer T { get; set; }
public CommentPartDriver(
IContentManager contentManager,
IWorkContextAccessor workContextAccessor,
IClock clock,
ICommentService commentService,
IOrchardServices orchardServices) {
_contentManager = contentManager;
_workContextAccessor = workContextAccessor;
_clock = clock;
_commentService = commentService;
_orchardServices = orchardServices;
T = NullLocalizer.Instance;
}
protected override DriverResult Display(CommentPart part, string displayType, dynamic shapeHelper) {
return Combined(
ContentShape("Parts_Comment", () => shapeHelper.Parts_Comment()),
ContentShape("Parts_Comment_SummaryAdmin", () => shapeHelper.Parts_Comment_SummaryAdmin())
);
}
// GET
protected override DriverResult Editor(CommentPart part, dynamic shapeHelper) {
if (UI.Admin.AdminFilter.IsApplied(_workContextAccessor.GetContext().HttpContext.Request.RequestContext)) {
return ContentShape("Parts_Comment_AdminEdit",
() => shapeHelper.EditorTemplate(TemplateName: "Parts.Comment.AdminEdit", Model: part, Prefix: Prefix));
}
else {
return ContentShape("Parts_Comment_Edit",
() => shapeHelper.EditorTemplate(TemplateName: "Parts.Comment", Model: part, Prefix: Prefix));
}
}
// POST
protected override DriverResult Editor(CommentPart part, IUpdateModel updater, dynamic shapeHelper) {
updater.TryUpdateModel(part, Prefix, null, null);
var workContext = _workContextAccessor.GetContext();
// applying moderate/approve actions
var httpContext = workContext.HttpContext;
var name = httpContext.Request.Form["submit.Save"];
if (!string.IsNullOrEmpty(name) && String.Equals(name, "moderate", StringComparison.OrdinalIgnoreCase)) {
if (_orchardServices.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment"))) {
_commentService.UnapproveComment(part.Id);
_orchardServices.Notifier.Information(T("Comment successfully moderated."));
return Editor(part, shapeHelper);
}
}
if (!string.IsNullOrEmpty(name) && String.Equals(name, "approve", StringComparison.OrdinalIgnoreCase)) {
if (_orchardServices.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't approve comment"))) {
_commentService.ApproveComment(part.Id);
_orchardServices.Notifier.Information(T("Comment approved."));
return Editor(part, shapeHelper);
}
}
if (!string.IsNullOrEmpty(name) && String.Equals(name, "delete", StringComparison.OrdinalIgnoreCase)) {
if (_orchardServices.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't delete comment"))) {
_commentService.DeleteComment(part.Id);
_orchardServices.Notifier.Information(T("Comment successfully deleted."));
return Editor(part, shapeHelper);
}
}
// if editing from the admin, don't update the owner or the status
if (!string.IsNullOrEmpty(name) && String.Equals(name, "save", StringComparison.OrdinalIgnoreCase)) {
_orchardServices.Notifier.Information(T("Comment saved."));
return Editor(part, shapeHelper);
}
part.CommentDateUtc = _clock.UtcNow;
if (!String.IsNullOrEmpty(part.SiteName) && !part.SiteName.StartsWith("http://") && !part.SiteName.StartsWith("https://")) {
part.SiteName = "http://" + part.SiteName;
}
var currentUser = workContext.CurrentUser;
part.UserName = (currentUser != null ? currentUser.UserName : null);
if (currentUser != null) part.Author = currentUser.UserName;
var moderateComments = workContext.CurrentSite.As<CommentSettingsPart>().Record.ModerateComments;
part.Status = moderateComments ? CommentStatus.Pending : CommentStatus.Approved;
var commentedOn = _contentManager.Get<ICommonPart>(part.CommentedOn);
// prevent users from commenting on a closed thread by hijacking the commentedOn property
var commentsPart = commentedOn.As<CommentsPart>();
if (!commentsPart.CommentsActive) {
_orchardServices.TransactionManager.Cancel();
return Editor(part, shapeHelper);
}
if (commentedOn != null && commentedOn.Container != null) {
part.CommentedOnContainer = commentedOn.Container.ContentItem.Id;
}
commentsPart.Record.CommentPartRecords.Add(part.Record);
return Editor(part, shapeHelper);
}
protected override void Importing(CommentPart part, ContentManagement.Handlers.ImportContentContext context) {
var author = context.Attribute(part.PartDefinition.Name, "Author");
if (author != null) {
part.Record.Author = author;
}
var siteName = context.Attribute(part.PartDefinition.Name, "SiteName");
if (siteName != null) {
part.Record.SiteName = siteName;
}
var userName = context.Attribute(part.PartDefinition.Name, "UserName");
if (userName != null) {
part.Record.UserName = userName;
}
var email = context.Attribute(part.PartDefinition.Name, "Email");
if (email != null) {
part.Record.Email = email;
}
var position = context.Attribute(part.PartDefinition.Name, "Position");
if (position != null) {
part.Record.Position = decimal.Parse(position, CultureInfo.InvariantCulture);
}
var status = context.Attribute(part.PartDefinition.Name, "Status");
if (status != null) {
part.Record.Status = (CommentStatus)Enum.Parse(typeof(CommentStatus), status);
}
var commentDate = context.Attribute(part.PartDefinition.Name, "CommentDateUtc");
if (commentDate != null) {
part.Record.CommentDateUtc = XmlConvert.ToDateTime(commentDate, XmlDateTimeSerializationMode.Utc);
}
var text = context.Attribute(part.PartDefinition.Name, "CommentText");
if (text != null) {
part.Record.CommentText = text;
}
var commentedOn = context.Attribute(part.PartDefinition.Name, "CommentedOn");
if (commentedOn != null) {
var contentItem = context.GetItemFromSession(commentedOn);
if (contentItem != null) {
part.Record.CommentedOn = contentItem.Id;
}
contentItem.As<CommentsPart>().Record.CommentPartRecords.Add(part.Record);
}
var repliedOn = context.Attribute(part.PartDefinition.Name, "RepliedOn");
if (repliedOn != null) {
var contentItem = context.GetItemFromSession(repliedOn);
if (contentItem != null) {
part.Record.RepliedOn = contentItem.Id;
}
contentItem.As<CommentsPart>().Record.CommentPartRecords.Add(part.Record);
}
var commentedOnContainer = context.Attribute(part.PartDefinition.Name, "CommentedOnContainer");
if (commentedOnContainer != null) {
var container = context.GetItemFromSession(commentedOnContainer);
if (container != null) {
part.Record.CommentedOnContainer = container.Id;
}
}
}
protected override void Exporting(CommentPart part, ContentManagement.Handlers.ExportContentContext context) {
context.Element(part.PartDefinition.Name).SetAttributeValue("Author", part.Record.Author);
context.Element(part.PartDefinition.Name).SetAttributeValue("SiteName", part.Record.SiteName);
context.Element(part.PartDefinition.Name).SetAttributeValue("UserName", part.Record.UserName);
context.Element(part.PartDefinition.Name).SetAttributeValue("Email", part.Record.Email);
context.Element(part.PartDefinition.Name).SetAttributeValue("Position", part.Record.Position.ToString(CultureInfo.InvariantCulture));
context.Element(part.PartDefinition.Name).SetAttributeValue("Status", part.Record.Status.ToString());
if (part.Record.CommentDateUtc != null) {
context.Element(part.PartDefinition.Name)
.SetAttributeValue("CommentDateUtc", XmlConvert.ToString(part.Record.CommentDateUtc.Value, XmlDateTimeSerializationMode.Utc));
}
context.Element(part.PartDefinition.Name).SetAttributeValue("CommentText", part.Record.CommentText);
var commentedOn = _contentManager.Get(part.Record.CommentedOn);
if (commentedOn != null) {
var commentedOnIdentity = _contentManager.GetItemMetadata(commentedOn).Identity;
context.Element(part.PartDefinition.Name).SetAttributeValue("CommentedOn", commentedOnIdentity.ToString());
}
var commentedOnContainer = _contentManager.Get(part.Record.CommentedOnContainer);
if (commentedOnContainer != null) {
var commentedOnContainerIdentity = _contentManager.GetItemMetadata(commentedOnContainer).Identity;
context.Element(part.PartDefinition.Name).SetAttributeValue("CommentedOnContainer", commentedOnContainerIdentity.ToString());
}
if (part.Record.RepliedOn.HasValue) {
var repliedOn = _contentManager.Get(part.Record.RepliedOn.Value);
if (repliedOn != null) {
var repliedOnIdentity = _contentManager.GetItemMetadata(repliedOn).Identity;
context.Element(part.PartDefinition.Name).SetAttributeValue("RepliedOn", repliedOnIdentity.ToString());
}
}
}
}
}
| |
using Android.Content;
using Android.OS;
using Android.Util;
using Android.Views;
using Android.Webkit;
namespace ObservableScrollView
{
public class ObservableWebView : WebView, IScrollable
{
// Fields that should be saved onSaveInstanceState
private int _mPrevScrollY;
private int _mScrollY;
// Fields that don't need to be saved onSaveInstanceState
private IObservableScrollViewCallbacks _mCallbacks;
private ObservableScrollState _mScrollState;
private bool _mFirstScroll;
private bool _mDragging;
private bool _mIntercepted;
private MotionEvent _mPrevMoveEvent;
private ViewGroup _mTouchInterceptionViewGroup;
public ObservableWebView(Context context)
: base(context)
{
}
public ObservableWebView(Context context, IAttributeSet attrs)
: base(context, attrs)
{
}
public ObservableWebView(Context context, IAttributeSet attrs, int defStyle)
: base(context, attrs, defStyle)
{
}
protected override void OnRestoreInstanceState(IParcelable state)
{
ObservableScrollSavedState ss = state as ObservableScrollSavedState;
if (ss != null)
{
_mPrevScrollY = ss.PrevScrollY;
_mScrollY = ss.ScrollY;
base.OnRestoreInstanceState(ss.SuperState);
}
}
protected override IParcelable OnSaveInstanceState()
{
IParcelable superState = base.OnSaveInstanceState();
ObservableScrollSavedState ss = new ObservableScrollSavedState(superState)
{
PrevScrollY = _mPrevScrollY,
ScrollY = _mScrollY
};
return ss;
}
protected override void OnScrollChanged(int l, int t, int oldl, int oldt)
{
base.OnScrollChanged(l, t, oldl, oldt);
if (_mCallbacks != null)
{
_mScrollY = t;
_mCallbacks.OnScrollChanged(t, _mFirstScroll, _mDragging);
if (_mFirstScroll)
{
_mFirstScroll = false;
}
if (_mPrevScrollY < t)
{
_mScrollState = ObservableScrollState.Up;
}
else if (t < _mPrevScrollY)
{
_mScrollState = ObservableScrollState.Down;
}
else
{
_mScrollState = ObservableScrollState.Stop;
}
_mPrevScrollY = t;
}
}
public override bool OnInterceptTouchEvent(MotionEvent ev)
{
if (_mCallbacks != null)
{
switch (ev.ActionMasked)
{
case MotionEventActions.Down:
// Whether or not motion events are consumed by children,
// flag initializations which are related to ACTION_DOWN events should be executed.
// Because if the ACTION_DOWN is consumed by children and only ACTION_MOVEs are
// passed to parent (this view), the flags will be invalid.
// Also, applications might implement initialization codes to onDownMotionEvent,
// so call it here.
_mFirstScroll = _mDragging = true;
_mCallbacks.OnDownMotionEvent();
break;
}
}
return base.OnInterceptTouchEvent(ev);
}
public override bool OnTouchEvent(MotionEvent ev)
{
if (_mCallbacks != null)
{
switch (ev.ActionMasked)
{
case MotionEventActions.Down:
break;
case MotionEventActions.Up:
case MotionEventActions.Cancel:
_mIntercepted = false;
_mDragging = false;
_mCallbacks.OnUpOrCancelMotionEvent(_mScrollState);
break;
case MotionEventActions.Move:
if (_mPrevMoveEvent == null)
{
_mPrevMoveEvent = ev;
}
float diffY = ev.GetY() - _mPrevMoveEvent.GetY();
_mPrevMoveEvent = MotionEvent.ObtainNoHistory(ev);
if (GetCurrentScrollY() - diffY <= 0)
{
// Can't scroll anymore.
if (_mIntercepted)
{
// Already dispatched ACTION_DOWN event to parents, so stop here.
return false;
}
// Apps can set the interception target other than the direct parent.
ViewGroup parent;
if (_mTouchInterceptionViewGroup == null)
{
parent = (ViewGroup)Parent;
}
else
{
parent = _mTouchInterceptionViewGroup;
}
// Get offset to parents. If the parent is not the direct parent,
// we should aggregate offsets from all of the parents.
float offsetX = 0;
float offsetY = 0;
for (View v = this; v != null && v != parent; v = (View)v.Parent)
{
offsetX += v.Left - v.ScrollX;
offsetY += v.Top - v.ScrollY;
}
MotionEvent eventNoHistory = MotionEvent.ObtainNoHistory(ev);
eventNoHistory.OffsetLocation(offsetX, offsetY);
if (parent.OnInterceptTouchEvent(eventNoHistory))
{
_mIntercepted = true;
// If the parent wants to intercept ACTION_MOVE events,
// we pass ACTION_DOWN event to the parent
// as if these touch events just have began now.
eventNoHistory.Action = MotionEventActions.Down;
// Return this onTouchEvent() first and set ACTION_DOWN event for parent
// to the queue, to keep events sequence.
Post(() => parent.DispatchTouchEvent(eventNoHistory));
return false;
}
// Even when this can't be scrolled anymore,
// simply returning false here may cause subView's click,
// so delegate it to base.
return base.OnTouchEvent(ev);
}
break;
}
}
return base.OnTouchEvent(ev);
}
public void SetScrollViewCallbacks(IObservableScrollViewCallbacks listener)
{
_mCallbacks = listener;
}
public void SetTouchInterceptionViewGroup(ViewGroup viewGroup)
{
_mTouchInterceptionViewGroup = viewGroup;
}
public void ScrollVerticallyTo(int y)
{
ScrollTo(0, y);
}
public int GetCurrentScrollY()
{
return _mScrollY;
}
}
}
| |
namespace Checkers
{
partial class frmAbout
{
/// <summary>
/// Disposes of the resources (other than memory) used by the <see cref="T:System.Windows.Forms.Form"/>.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
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(frmAbout));
this.lblVersion = new System.Windows.Forms.Label();
this.picLogo = new System.Windows.Forms.PictureBox();
this.panAbout = new System.Windows.Forms.Panel();
this.lnkWebLink = new System.Windows.Forms.LinkLabel();
this.lblWebTitle = new System.Windows.Forms.Label();
this.lblAuthor = new System.Windows.Forms.Label();
this.picDescription = new System.Windows.Forms.Panel();
this.lblDescription = new System.Windows.Forms.Label();
this.lblTitle = new System.Windows.Forms.Label();
this.btnClose = new System.Windows.Forms.Button();
this.lblRevision = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.picLogo)).BeginInit();
this.panAbout.SuspendLayout();
this.picDescription.SuspendLayout();
this.SuspendLayout();
//
// lblVersion
//
this.lblVersion.AutoSize = true;
this.lblVersion.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblVersion.Location = new System.Drawing.Point(12, 220);
this.lblVersion.Name = "lblVersion";
this.lblVersion.Size = new System.Drawing.Size(45, 13);
this.lblVersion.TabIndex = 3;
this.lblVersion.Text = "Version:";
this.lblVersion.Resize += new System.EventHandler(this.lblVersion_Resize);
//
// picLogo
//
this.picLogo.Image = ((System.Drawing.Image)(resources.GetObject("picLogo.Image")));
this.picLogo.Location = new System.Drawing.Point(12, 8);
this.picLogo.Name = "picLogo";
this.picLogo.Size = new System.Drawing.Size(32, 32);
this.picLogo.TabIndex = 10;
this.picLogo.TabStop = false;
//
// panAbout
//
this.panAbout.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(70)))), ((int)(((byte)(89)))), ((int)(((byte)(117)))));
this.panAbout.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("panAbout.BackgroundImage")));
this.panAbout.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.panAbout.Controls.Add(this.lnkWebLink);
this.panAbout.Controls.Add(this.lblWebTitle);
this.panAbout.Controls.Add(this.lblAuthor);
this.panAbout.Controls.Add(this.picDescription);
this.panAbout.Location = new System.Drawing.Point(12, 48);
this.panAbout.Name = "panAbout";
this.panAbout.Size = new System.Drawing.Size(284, 160);
this.panAbout.TabIndex = 2;
//
// lnkWebLink
//
this.lnkWebLink.ActiveLinkColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(228)))), ((int)(((byte)(164)))));
this.lnkWebLink.AutoSize = true;
this.lnkWebLink.BackColor = System.Drawing.Color.Transparent;
this.lnkWebLink.DisabledLinkColor = System.Drawing.Color.FromArgb(((int)(((byte)(136)))), ((int)(((byte)(136)))), ((int)(((byte)(136)))));
this.lnkWebLink.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.484F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel, ((byte)(0)));
this.lnkWebLink.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(154)))), ((int)(((byte)(175)))), ((int)(((byte)(162)))));
this.lnkWebLink.LinkBehavior = System.Windows.Forms.LinkBehavior.AlwaysUnderline;
this.lnkWebLink.LinkColor = System.Drawing.Color.FromArgb(((int)(((byte)(154)))), ((int)(((byte)(175)))), ((int)(((byte)(162)))));
this.lnkWebLink.Location = new System.Drawing.Point(184, 136);
this.lnkWebLink.Name = "lnkWebLink";
this.lnkWebLink.Size = new System.Drawing.Size(95, 15);
this.lnkWebLink.TabIndex = 3;
this.lnkWebLink.TabStop = true;
this.lnkWebLink.Text = "joeyespo.com";
this.lnkWebLink.VisitedLinkColor = System.Drawing.Color.FromArgb(((int)(((byte)(154)))), ((int)(((byte)(175)))), ((int)(((byte)(162)))));
this.lnkWebLink.MouseLeave += new System.EventHandler(this.lnkWebLink_MouseLeave);
this.lnkWebLink.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkWebLink_LinkClicked);
this.lnkWebLink.MouseEnter += new System.EventHandler(this.lnkWebLink_MouseEnter);
//
// lblWebTitle
//
this.lblWebTitle.AutoSize = true;
this.lblWebTitle.BackColor = System.Drawing.Color.Transparent;
this.lblWebTitle.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.484F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel, ((byte)(0)));
this.lblWebTitle.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(154)))), ((int)(((byte)(175)))), ((int)(((byte)(162)))));
this.lblWebTitle.Location = new System.Drawing.Point(136, 118);
this.lblWebTitle.Name = "lblWebTitle";
this.lblWebTitle.Size = new System.Drawing.Size(145, 15);
this.lblWebTitle.TabIndex = 2;
this.lblWebTitle.Text = "Visit my site for more:";
//
// lblAuthor
//
this.lblAuthor.BackColor = System.Drawing.Color.Transparent;
this.lblAuthor.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(154)))), ((int)(((byte)(175)))), ((int)(((byte)(162)))));
this.lblAuthor.Location = new System.Drawing.Point(12, 80);
this.lblAuthor.Name = "lblAuthor";
this.lblAuthor.Size = new System.Drawing.Size(264, 15);
this.lblAuthor.TabIndex = 1;
this.lblAuthor.Text = "Designed and Coded by Joe Esposito";
this.lblAuthor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// picDescription
//
this.picDescription.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(35)))), ((int)(((byte)(44)))), ((int)(((byte)(58)))));
this.picDescription.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("picDescription.BackgroundImage")));
this.picDescription.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.picDescription.Controls.Add(this.lblDescription);
this.picDescription.Location = new System.Drawing.Point(8, 8);
this.picDescription.Name = "picDescription";
this.picDescription.Size = new System.Drawing.Size(268, 64);
this.picDescription.TabIndex = 0;
//
// lblDescription
//
this.lblDescription.BackColor = System.Drawing.Color.Transparent;
this.lblDescription.ForeColor = System.Drawing.SystemColors.ControlLight;
this.lblDescription.Location = new System.Drawing.Point(4, 8);
this.lblDescription.Name = "lblDescription";
this.lblDescription.Size = new System.Drawing.Size(256, 48);
this.lblDescription.TabIndex = 0;
this.lblDescription.Text = "[ Description ]";
this.lblDescription.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// lblTitle
//
this.lblTitle.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblTitle.Location = new System.Drawing.Point(48, 20);
this.lblTitle.Name = "lblTitle";
this.lblTitle.Size = new System.Drawing.Size(248, 16);
this.lblTitle.TabIndex = 0;
this.lblTitle.Text = "[ Title ]";
this.lblTitle.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// btnClose
//
this.btnClose.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnClose.Location = new System.Drawing.Point(208, 220);
this.btnClose.Name = "btnClose";
this.btnClose.Size = new System.Drawing.Size(84, 32);
this.btnClose.TabIndex = 1;
this.btnClose.Text = "&Close";
//
// lblRevision
//
this.lblRevision.AutoSize = true;
this.lblRevision.ForeColor = System.Drawing.SystemColors.GrayText;
this.lblRevision.Location = new System.Drawing.Point(68, 220);
this.lblRevision.Name = "lblRevision";
this.lblRevision.Size = new System.Drawing.Size(51, 13);
this.lblRevision.TabIndex = 4;
this.lblRevision.Text = "Revision:";
//
// frmAbout
//
this.AcceptButton = this.btnClose;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.btnClose;
this.ClientSize = new System.Drawing.Size(306, 264);
this.Controls.Add(this.lblVersion);
this.Controls.Add(this.lblRevision);
this.Controls.Add(this.picLogo);
this.Controls.Add(this.panAbout);
this.Controls.Add(this.lblTitle);
this.Controls.Add(this.btnClose);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "frmAbout";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "About";
this.Load += new System.EventHandler(this.frmAbout_Load);
((System.ComponentModel.ISupportInitialize)(this.picLogo)).EndInit();
this.panAbout.ResumeLayout(false);
this.panAbout.PerformLayout();
this.picDescription.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private System.Windows.Forms.Label lblVersion;
private System.Windows.Forms.PictureBox picLogo;
private System.Windows.Forms.Panel panAbout;
private System.Windows.Forms.LinkLabel lnkWebLink;
private System.Windows.Forms.Label lblWebTitle;
private System.Windows.Forms.Label lblAuthor;
private System.Windows.Forms.Panel picDescription;
private System.Windows.Forms.Label lblDescription;
private System.Windows.Forms.Label lblTitle;
private System.Windows.Forms.Button btnClose;
private System.Windows.Forms.Label lblRevision;
}
}
| |
using System.Linq;
using System.Threading.Tasks;
using SfAttendance.Server.Entities;
using SfAttendance.Server.Extensions;
using SfAttendance.Server.Services.Abstract;
using SfAttendance.Server.ViewModels.AccountViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Logging;
namespace SfAttendance.Server.Controllers.api
{
[Authorize]
[Route("api/[controller]")]
public class AccountController : BaseController
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ISmsSender _smsSender;
private readonly ILogger _logger;
public AccountController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
ISmsSender smsSender,
ILoggerFactory loggerFactory)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_smsSender = smsSender;
_logger = loggerFactory.CreateLogger<AccountController>();
}
[HttpPost("login")]
[AllowAnonymous]
public async Task<IActionResult> Login([FromBody]LoginViewModel model)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
var user = await _userManager.FindByEmailAsync(model.Email);
var roles = await _userManager.GetRolesAsync(user);
_logger.LogInformation(1, "User logged in.");
return AppUtils.SignIn(user, roles);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(SendCode), new { RememberMe = model.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning(2, "User account locked out.");
return BadRequest("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return BadRequest(ModelState.GetModelErrors());
}
}
[HttpPost("register")]
[AllowAnonymous]
public async Task<IActionResult> Register([FromBody]RegisterViewModel model, string returnUrl = null)
{
var currentUser = new ApplicationUser
{
UserName = model.Email,
Email = model.Email,
FirstName = model.Firstname,
LastName = model.Lastname
};
var result = await _userManager.CreateAsync(currentUser, model.Password);
if (result.Succeeded)
{
// Add to roles
var roleAddResult = await _userManager.AddToRoleAsync(currentUser, "User");
if (roleAddResult.Succeeded)
{
var code = await _userManager.GenerateEmailConfirmationTokenAsync(currentUser);
var host = Request.Scheme + "://" + Request.Host;
var callbackUrl = host + "?userId=" + currentUser.Id + "&emailConfirmCode=" + code;
var confirmationLink = "<a class='btn-primary' href=\"" + callbackUrl + "\">Confirm email address</a>";
_logger.LogInformation(3, "User created a new account with password.");
//await _emailSender.SendEmailAsync(MailType.Register, new EmailModel { To = model.Email }, confirmationLink);
return Json(new { });
}
}
AddErrors(result);
// If we got this far, something failed, redisplay form
return BadRequest(ModelState.GetModelErrors());
}
[HttpPost("logout")]
public async Task<IActionResult> LogOff()
{
await _signInManager.SignOutAsync();
_logger.LogInformation(4, "User logged out.");
return Ok();
}
[HttpGet("ExternalLogin")]
[AllowAnonymous]
public IActionResult ExternalLogin(string provider, string returnUrl = null)
{
// Request a redirect to the external login provider.
var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return Challenge(properties, provider);
}
[HttpGet("ExternalLoginCallback")]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
if (remoteError != null)
{
return Render(ExternalLoginStatus.Error);
}
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return Render(ExternalLoginStatus.Invalid);
}
// Sign in the user with this external login provider if the user already has a login.
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
if (result.Succeeded)
{
_logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider);
return Render(ExternalLoginStatus.Ok); // Everything Ok, login user
}
if (result.RequiresTwoFactor)
{
return Render(ExternalLoginStatus.TwoFactor);
}
if (result.IsLockedOut)
{
return Render(ExternalLoginStatus.Lockout);
}
else
{
// If the user does not have an account, then ask the user to create an account.
// ViewData["ReturnUrl"] = returnUrl;
// ViewData["LoginProvider"] = info.LoginProvider;
// var email = info.Principal.FindFirstValue(ClaimTypes.Email);
// return RedirectToAction("Index", "Home", new ExternalLoginCreateAccountViewModel { Email = email });
return Render(ExternalLoginStatus.CreateAccount);
}
}
[HttpPost("ExternalLoginCreateAccount")]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ExternalLoginCreateAccount([FromBody]ExternalLoginConfirmationViewModel model, string returnUrl = null)
{
// Get the information about the user from the external login provider
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return BadRequest("External login information cannot be accessed, try again.");
}
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user);
if (result.Succeeded)
{
result = await _userManager.AddLoginAsync(user, info);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider);
return Ok(); // Everything ok
}
}
return BadRequest(new[] { "Email already exists" });
}
[HttpGet("ConfirmEmail")]
[AllowAnonymous]
public async Task<IActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return View("Error");
}
var result = await _userManager.ConfirmEmailAsync(user, code);
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
[HttpGet("ForgotPassword")]
[AllowAnonymous]
public IActionResult ForgotPassword()
{
return View();
}
[HttpPost("ForgotPassword")]
[AllowAnonymous]
public async Task<IActionResult> ForgotPassword([FromBody]ForgotPasswordViewModel model)
{
var currentUser = await _userManager.FindByNameAsync(model.Email);
if (currentUser == null || !(await _userManager.IsEmailConfirmedAsync(currentUser)))
{
// Don't reveal that the user does not exist or is not confirmed
return View("ForgotPasswordConfirmation");
}
// For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
var code = await _userManager.GeneratePasswordResetTokenAsync(currentUser);
var host = Request.Scheme + "://" + Request.Host;
var callbackUrl = host + "?userId=" + currentUser.Id + "&passwordResetCode=" + code;
var confirmationLink = "<a class='btn-primary' href=\"" + callbackUrl + "\">Reset your password</a>";
await _emailSender.SendEmailAsync(MailType.ForgetPassword, new EmailModel { To = model.Email }, confirmationLink);
return Json(new { });
}
[HttpPost("resetpassword")]
[AllowAnonymous]
public async Task<IActionResult> ResetPassword([FromBody]ResetPasswordViewModel model)
{
var user = await _userManager.FindByNameAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return Ok("Reset confirmed");
}
var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password);
if (result.Succeeded)
{
return Ok("Reset confirmed"); ;
}
AddErrors(result);
return BadRequest(ModelState.GetModelErrors());
}
[HttpGet("SendCode")]
[AllowAnonymous]
public async Task<ActionResult> SendCode(string returnUrl = null, bool rememberMe = false)
{
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return BadRequest("Error");
}
var userFactors = await _userManager.GetValidTwoFactorProvidersAsync(user);
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
[HttpPost("SendCode")]
[AllowAnonymous]
public async Task<IActionResult> SendCode([FromBody]SendCodeViewModel model)
{
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return BadRequest("Error");
}
// Generate the token and send it
var code = await _userManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider);
if (string.IsNullOrWhiteSpace(code))
{
return BadRequest("Error");
}
var message = "Your security code is: " + code;
if (model.SelectedProvider == "Email")
{
await _emailSender.SendEmailAsync(MailType.SecurityCode, new EmailModel { }, null);
//await _emailSender.SendEmailAsync(Email, await _userManager.GetEmailAsync(user), "Security Code", message);
}
else if (model.SelectedProvider == "Phone")
{
await _smsSender.SendSmsTwillioAsync(await _userManager.GetPhoneNumberAsync(user), message);
}
return RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
}
[HttpGet("VerifyCode")]
[AllowAnonymous]
public async Task<IActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null)
{
// Require that the user has already logged in via username/password or external login
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return BadRequest("Error");
}
return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
[HttpPost("VerifyCode")]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyCode(VerifyCodeViewModel model)
{
// The following code protects for brute force attacks against the two factor codes.
// If a user enters incorrect codes for a specified amount of time then the user account
// will be locked out for a specified amount of time.
var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser);
if (result.Succeeded)
{
return RedirectToLocal(model.ReturnUrl);
}
if (result.IsLockedOut)
{
_logger.LogWarning(7, "User account locked out.");
return View("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid code.");
return View(model);
}
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
private Task<ApplicationUser> GetCurrentUserAsync()
{
return _userManager.GetUserAsync(HttpContext.User);
}
private IActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction(nameof(HomeController.Index), "Home");
}
}
private IActionResult Render(ExternalLoginStatus status)
{
return RedirectToAction("Index", "Home", new { externalLoginStatus = (int)status });
}
#endregion
}
}
| |
/*
* [The "BSD licence"]
* Copyright (c) 2005-2008 Terence Parr
* All rights reserved.
*
* Conversion to C#:
* Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 Antlr.Runtime
{
using ConditionalAttribute = System.Diagnostics.ConditionalAttribute;
/** <summary>
* A lexer is recognizer that draws input symbols from a character stream.
* lexer grammars result in a subclass of this object. A Lexer object
* uses simplified match() and error recovery mechanisms in the interest
* of speed.
* </summary>
*/
public abstract class Lexer : BaseRecognizer, ITokenSource
{
/** <summary>Where is the lexer drawing characters from?</summary> */
protected ICharStream input;
public Lexer()
{
}
public Lexer( ICharStream input )
{
this.input = input;
}
public Lexer( ICharStream input, RecognizerSharedState state )
: base(state)
{
this.input = input;
}
#region Properties
public string Text
{
/** <summary>Return the text matched so far for the current token or any text override.</summary> */
get
{
if ( state.text != null )
{
return state.text;
}
return input.Substring( state.tokenStartCharIndex, CharIndex - state.tokenStartCharIndex );
}
/** <summary>Set the complete text of this token; it wipes any previous changes to the text.</summary> */
set
{
state.text = value;
}
}
public int Line
{
get
{
return input.Line;
}
set
{
input.Line = value;
}
}
public int CharPositionInLine
{
get
{
return input.CharPositionInLine;
}
set
{
input.CharPositionInLine = value;
}
}
#endregion
public override void Reset()
{
base.Reset(); // reset all recognizer state variables
// wack Lexer state variables
if ( input != null )
{
input.Seek( 0 ); // rewind the input
}
if ( state == null )
{
return; // no shared state work to do
}
state.token = null;
state.type = TokenTypes.Invalid;
state.channel = TokenChannels.Default;
state.tokenStartCharIndex = -1;
state.tokenStartCharPositionInLine = -1;
state.tokenStartLine = -1;
state.text = null;
}
/** <summary>Return a token from this source; i.e., match a token on the char stream.</summary> */
public virtual IToken NextToken()
{
for ( ; ; )
{
state.token = null;
state.channel = TokenChannels.Default;
state.tokenStartCharIndex = input.Index;
state.tokenStartCharPositionInLine = input.CharPositionInLine;
state.tokenStartLine = input.Line;
state.text = null;
if ( input.LA( 1 ) == CharStreamConstants.EndOfFile )
{
return GetEndOfFileToken();
}
try
{
ParseNextToken();
if ( state.token == null )
{
Emit();
}
else if ( state.token == Tokens.Skip )
{
continue;
}
return state.token;
}
catch (MismatchedRangeException mre)
{
ReportError(mre);
// MatchRange() routine has already called recover()
}
catch (MismatchedTokenException mte)
{
ReportError(mte);
// Match() routine has already called recover()
}
catch ( RecognitionException re )
{
ReportError( re );
Recover( re ); // throw out current char and try again
}
}
}
/** Returns the EOF token (default), if you need
* to return a custom token instead override this method.
*/
public virtual IToken GetEndOfFileToken()
{
IToken eof = new CommonToken((ICharStream)input, CharStreamConstants.EndOfFile, TokenChannels.Default, input.Index, input.Index);
eof.Line = Line;
eof.CharPositionInLine = CharPositionInLine;
return eof;
}
/** <summary>
* Instruct the lexer to skip creating a token for current lexer rule
* and look for another token. nextToken() knows to keep looking when
* a lexer rule finishes with token set to SKIP_TOKEN. Recall that
* if token==null at end of any token rule, it creates one for you
* and emits it.
* </summary>
*/
public virtual void Skip()
{
state.token = Tokens.Skip;
}
/** <summary>This is the lexer entry point that sets instance var 'token'</summary> */
public abstract void mTokens();
public virtual ICharStream CharStream
{
get
{
return input;
}
/** <summary>Set the char stream and reset the lexer</summary> */
set
{
input = null;
Reset();
input = value;
}
}
public override string SourceName
{
get
{
return input.SourceName;
}
}
/** <summary>
* Currently does not support multiple emits per nextToken invocation
* for efficiency reasons. Subclass and override this method and
* nextToken (to push tokens into a list and pull from that list rather
* than a single variable as this implementation does).
* </summary>
*/
public virtual void Emit( IToken token )
{
state.token = token;
}
/** <summary>
* The standard method called to automatically emit a token at the
* outermost lexical rule. The token object should point into the
* char buffer start..stop. If there is a text override in 'text',
* use that to set the token's text. Override this method to emit
* custom Token objects.
* </summary>
*
* <remarks>
* If you are building trees, then you should also override
* Parser or TreeParser.getMissingSymbol().
* </remarks>
*/
public virtual IToken Emit()
{
IToken t = new CommonToken( input, state.type, state.channel, state.tokenStartCharIndex, CharIndex - 1 );
t.Line = state.tokenStartLine;
t.Text = state.text;
t.CharPositionInLine = state.tokenStartCharPositionInLine;
Emit( t );
return t;
}
public virtual void Match( string s )
{
int i = 0;
while ( i < s.Length )
{
if ( input.LA( 1 ) != s[i] )
{
if ( state.backtracking > 0 )
{
state.failed = true;
return;
}
MismatchedTokenException mte = new MismatchedTokenException(s[i], input, TokenNames);
Recover( mte );
throw mte;
}
i++;
input.Consume();
state.failed = false;
}
}
public virtual void MatchAny()
{
input.Consume();
}
public virtual void Match( int c )
{
if ( input.LA( 1 ) != c )
{
if ( state.backtracking > 0 )
{
state.failed = true;
return;
}
MismatchedTokenException mte = new MismatchedTokenException(c, input, TokenNames);
Recover( mte ); // don't really recover; just consume in lexer
throw mte;
}
input.Consume();
state.failed = false;
}
public virtual void MatchRange( int a, int b )
{
if ( input.LA( 1 ) < a || input.LA( 1 ) > b )
{
if ( state.backtracking > 0 )
{
state.failed = true;
return;
}
MismatchedRangeException mre = new MismatchedRangeException(a, b, input);
Recover( mre );
throw mre;
}
input.Consume();
state.failed = false;
}
/** <summary>What is the index of the current character of lookahead?</summary> */
public virtual int CharIndex
{
get
{
return input.Index;
}
}
public override void ReportError( RecognitionException e )
{
/** TODO: not thought about recovery in lexer yet.
*
// if we've already reported an error and have not matched a token
// yet successfully, don't report any errors.
if ( errorRecovery ) {
//System.err.print("[SPURIOUS] ");
return;
}
errorRecovery = true;
*/
DisplayRecognitionError( this.TokenNames, e );
}
public override string GetErrorMessage( RecognitionException e, string[] tokenNames )
{
string msg = null;
if ( e is MismatchedTokenException )
{
MismatchedTokenException mte = (MismatchedTokenException)e;
msg = "mismatched character " + GetCharErrorDisplay( e.Character ) + " expecting " + GetCharErrorDisplay( mte.Expecting );
}
else if ( e is NoViableAltException )
{
NoViableAltException nvae = (NoViableAltException)e;
// for development, can add "decision=<<"+nvae.grammarDecisionDescription+">>"
// and "(decision="+nvae.decisionNumber+") and
// "state "+nvae.stateNumber
msg = "no viable alternative at character " + GetCharErrorDisplay( e.Character );
}
else if ( e is EarlyExitException )
{
EarlyExitException eee = (EarlyExitException)e;
// for development, can add "(decision="+eee.decisionNumber+")"
msg = "required (...)+ loop did not match anything at character " + GetCharErrorDisplay( e.Character );
}
else if ( e is MismatchedNotSetException )
{
MismatchedNotSetException mse = (MismatchedNotSetException)e;
msg = "mismatched character " + GetCharErrorDisplay( e.Character ) + " expecting set " + mse.Expecting;
}
else if ( e is MismatchedSetException )
{
MismatchedSetException mse = (MismatchedSetException)e;
msg = "mismatched character " + GetCharErrorDisplay( e.Character ) + " expecting set " + mse.Expecting;
}
else if ( e is MismatchedRangeException )
{
MismatchedRangeException mre = (MismatchedRangeException)e;
msg = "mismatched character " + GetCharErrorDisplay( e.Character ) + " expecting set " +
GetCharErrorDisplay( mre.A ) + ".." + GetCharErrorDisplay( mre.B );
}
else
{
msg = base.GetErrorMessage( e, tokenNames );
}
return msg;
}
public virtual string GetCharErrorDisplay( int c )
{
string s = ( (char)c ).ToString();
switch ( c )
{
case TokenTypes.EndOfFile:
s = "<EOF>";
break;
case '\n':
s = "\\n";
break;
case '\t':
s = "\\t";
break;
case '\r':
s = "\\r";
break;
}
return "'" + s + "'";
}
/** <summary>
* Lexers can normally match any char in it's vocabulary after matching
* a token, so do the easy thing and just kill a character and hope
* it all works out. You can instead use the rule invocation stack
* to do sophisticated error recovery if you are in a fragment rule.
* </summary>
*/
public virtual void Recover( RecognitionException re )
{
//System.out.println("consuming char "+(char)input.LA(1)+" during recovery");
//re.printStackTrace();
input.Consume();
}
[Conditional("ANTLR_TRACE")]
public virtual void TraceIn( string ruleName, int ruleIndex )
{
string inputSymbol = ( (char)input.LT( 1 ) ) + " line=" + Line + ":" + CharPositionInLine;
base.TraceIn( ruleName, ruleIndex, inputSymbol );
}
[Conditional("ANTLR_TRACE")]
public virtual void TraceOut( string ruleName, int ruleIndex )
{
string inputSymbol = ( (char)input.LT( 1 ) ) + " line=" + Line + ":" + CharPositionInLine;
base.TraceOut( ruleName, ruleIndex, inputSymbol );
}
protected virtual void ParseNextToken()
{
mTokens();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using System.Threading;
using TestLibrary;
using Console = Internal.Console;
public class Program
{
public static class NativeMethods
{
[DllImport("NativeCallableDll")]
public static extern int CallManagedProc(IntPtr callbackProc, int n);
}
private delegate int IntNativeMethodInvoker();
private delegate void NativeMethodInvoker();
public static int Main(string[] args)
{
try
{
TestNativeCallableValid();
NegativeTest_ViaDelegate();
NegativeTest_NonBlittable();
NegativeTest_GenericArguments();
NativeCallableViaUnmanagedCalli();
if (args.Length != 0 && args[0].Equals("calli"))
{
NegativeTest_ViaCalli();
}
}
catch (Exception e)
{
Console.WriteLine($"Test Failure: {e}");
return 101;
}
return 100;
}
[NativeCallable]
public static int ManagedDoubleCallback(int n)
{
return DoubleImpl(n);
}
private static int DoubleImpl(int n)
{
return 2 * n;
}
public static void TestNativeCallableValid()
{
Console.WriteLine($"{nameof(NativeCallableAttribute)} function");
/*
void TestNativeCallable()
{
.locals init ([0] native int ptr)
IL_0000: nop
IL_0001: ldftn int32 ManagedDoubleCallback(int32)
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldc.i4 <n> local
IL_000e: call bool NativeMethods::CallManagedProc(native int, int)
IL_0013: ret
}
*/
DynamicMethod testNativeCallable = new DynamicMethod("TestNativeCallable", typeof(int), null, typeof(Program).Module);
ILGenerator il = testNativeCallable.GetILGenerator();
il.DeclareLocal(typeof(IntPtr));
il.Emit(OpCodes.Nop);
// Get native function pointer of the callback
il.Emit(OpCodes.Ldftn, typeof(Program).GetMethod(nameof(ManagedDoubleCallback)));
il.Emit(OpCodes.Stloc_0);
il.Emit(OpCodes.Ldloc_0);
int n = 12345;
il.Emit(OpCodes.Ldc_I4, n);
il.Emit(OpCodes.Call, typeof(NativeMethods).GetMethod("CallManagedProc"));
il.Emit(OpCodes.Ret);
var testNativeMethod = (IntNativeMethodInvoker)testNativeCallable.CreateDelegate(typeof(IntNativeMethodInvoker));
int expected = DoubleImpl(n);
Assert.AreEqual(expected, testNativeMethod());
}
public static void NegativeTest_ViaDelegate()
{
Console.WriteLine($"{nameof(NativeCallableAttribute)} function as delegate");
// Try invoking method directly
try
{
CallAsDelegate();
Assert.Fail($"Invalid to call {nameof(ManagedDoubleCallback)} as delegate");
}
catch (NotSupportedException)
{
}
// Local function to delay exception thrown during JIT
void CallAsDelegate()
{
Func<int, int> invoker = ManagedDoubleCallback;
invoker(0);
}
}
[NativeCallable]
public static int CallbackMethodNonBlittable(bool x1)
{
Assert.Fail($"Functions with attribute {nameof(NativeCallableAttribute)} cannot have non-blittable arguments");
return -1;
}
public static void NegativeTest_NonBlittable()
{
Console.WriteLine($"{nameof(NativeCallableAttribute)} function with non-blittable arguments");
/*
void TestNativeCallableNonBlittable()
{
.locals init ([0] native int ptr)
IL_0000: nop
IL_0001: ldftn int32 CallbackMethodNonBlittable(bool)
IL_0007: stloc.0
IL_0008: ret
}
*/
DynamicMethod testNativeCallable = new DynamicMethod("TestNativeCallableNonBlittable", null, null, typeof(Program).Module);
ILGenerator il = testNativeCallable.GetILGenerator();
il.DeclareLocal(typeof(IntPtr));
il.Emit(OpCodes.Nop);
// Get native function pointer of the callback
il.Emit(OpCodes.Ldftn, typeof(Program).GetMethod(nameof(CallbackMethodNonBlittable)));
il.Emit(OpCodes.Stloc_0);
il.Emit(OpCodes.Ret);
var testNativeMethod = (NativeMethodInvoker)testNativeCallable.CreateDelegate(typeof(NativeMethodInvoker));
// Try invoking method
try
{
testNativeMethod();
Assert.Fail($"Function {nameof(CallbackMethodNonBlittable)} has non-blittable types");
}
catch (NotSupportedException)
{
}
}
[NativeCallable]
public static int CallbackMethodGeneric<T>(T arg)
{
Assert.Fail($"Functions with attribute {nameof(NativeCallableAttribute)} cannot have generic arguments");
return -1;
}
public static void NegativeTest_GenericArguments()
{
/*
void TestNativeCallableGenericArguments()
{
.locals init ([0] native int ptr)
IL_0000: nop
IL_0001: ldftn int32 CallbackMethodGeneric(T)
IL_0007: stloc.0
IL_0008: ret
}
*/
DynamicMethod testNativeCallable = new DynamicMethod("TestNativeCallableGenericArguments", null, null, typeof(Program).Module);
ILGenerator il = testNativeCallable.GetILGenerator();
il.DeclareLocal(typeof(IntPtr));
il.Emit(OpCodes.Nop);
// Get native function pointer of the callback
il.Emit(OpCodes.Ldftn, typeof(Program).GetMethod(nameof(CallbackMethodGeneric)));
il.Emit(OpCodes.Stloc_0);
il.Emit(OpCodes.Ret);
var testNativeMethod = (NativeMethodInvoker)testNativeCallable.CreateDelegate(typeof(NativeMethodInvoker));
// Try invoking method
try
{
testNativeMethod();
Assert.Fail($"Function {nameof(CallbackMethodGeneric)} has generic types");
}
catch (InvalidProgramException)
{
}
}
[NativeCallable]
public static void CallbackViaCalli(int val)
{
Assert.Fail($"Functions with attribute {nameof(NativeCallableAttribute)} cannot be called via calli");
}
public static void NegativeTest_ViaCalli()
{
Console.WriteLine($"{nameof(NativeCallableAttribute)} function via calli instruction. The CLR _will_ crash.");
/*
void TestNativeCallableViaCalli()
{
.locals init (native int V_0)
IL_0000: nop
IL_0001: ldftn void CallbackViaCalli(int32)
IL_0007: stloc.0
IL_0008: ldc.i4 1234
IL_000d: ldloc.0
IL_000e: calli void(int32)
IL_0013: nop
IL_0014: ret
}
*/
DynamicMethod testNativeCallable = new DynamicMethod("TestNativeCallableViaCalli", null, null, typeof(Program).Module);
ILGenerator il = testNativeCallable.GetILGenerator();
il.DeclareLocal(typeof(IntPtr));
il.Emit(OpCodes.Nop);
// Get native function pointer of the callback
il.Emit(OpCodes.Ldftn, typeof(Program).GetMethod(nameof(CallbackViaCalli)));
il.Emit(OpCodes.Stloc_0);
il.Emit(OpCodes.Ldc_I4, 1234);
il.Emit(OpCodes.Ldloc_0);
il.EmitCalli(OpCodes.Calli, CallingConventions.Standard, null, new Type[] { typeof(int) }, null);
il.Emit(OpCodes.Nop);
il.Emit(OpCodes.Ret);
NativeMethodInvoker testNativeMethod = (NativeMethodInvoker)testNativeCallable.CreateDelegate(typeof(NativeMethodInvoker));
// It is not possible to catch the resulting ExecutionEngineException exception.
// To observe the crashing behavior set a breakpoint in the ReversePInvokeBadTransition() function
// located in src/vm/dllimportcallback.cpp.
testNativeMethod();
}
[NativeCallable(CallingConvention = CallingConvention.StdCall)]
public static int CallbackViaUnmanagedCalli(int val)
{
return DoubleImpl(val);
}
public static void NativeCallableViaUnmanagedCalli()
{
Console.WriteLine($"{nameof(NativeCallableAttribute)} function via calli instruction with unmanaged calling convention.");
/*
void TestNativeCallableViaCalli()
{
.locals init (native int V_0)
IL_0000: nop
IL_0001: ldftn int CallbackViaUnmanagedCalli(int32)
IL_0007: stloc.0
IL_0008: ldc.i4 1234
IL_000d: ldloc.0
IL_000e: calli int32 stdcall(int32)
IL_0014: ret
}
*/
DynamicMethod testNativeCallable = new DynamicMethod("TestNativeCallableViaUnmanagedCalli", typeof(int), null, typeof(Program).Module);
ILGenerator il = testNativeCallable.GetILGenerator();
il.DeclareLocal(typeof(IntPtr));
il.Emit(OpCodes.Nop);
// Get native function pointer of the callback
il.Emit(OpCodes.Ldftn, typeof(Program).GetMethod(nameof(CallbackViaUnmanagedCalli)));
il.Emit(OpCodes.Stloc_0);
int n = 1234;
il.Emit(OpCodes.Ldc_I4, n);
il.Emit(OpCodes.Ldloc_0);
il.EmitCalli(OpCodes.Calli, CallingConvention.StdCall, typeof(int), new Type[] { typeof(int) });
il.Emit(OpCodes.Ret);
IntNativeMethodInvoker testNativeMethod = (IntNativeMethodInvoker)testNativeCallable.CreateDelegate(typeof(IntNativeMethodInvoker));
int expected = DoubleImpl(n);
Assert.AreEqual(expected, testNativeMethod());
}
}
| |
// 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 OLEDB.Test.ModuleCore;
namespace System.Xml.Tests
{
internal class VerifyNameTests3 : CTestCase
{
public override void AddChildren()
{
AddChild(new CVariation(v16) { Attribute = new Variation("15.Test for VerifyNCName(\ud801\r\udc01)") { Params = new object[] { 15, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("6.Test for VerifyNCName(abcd\ralfafkjha)") { Params = new object[] { 6, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("8.Test for VerifyNCName(abcd\tdef)") { Params = new object[] { 8, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("9.Test for VerifyNCName( \b)") { Params = new object[] { 9, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("10.Test for VerifyNCName(\ud801\udc01)") { Params = new object[] { 10, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("11.Test for VerifyNCName( \ud801\udc01)") { Params = new object[] { 11, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("12.Test for VerifyNCName(\ud801\udc01 )") { Params = new object[] { 12, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("13.Test for VerifyNCName(\ud801 \udc01)") { Params = new object[] { 13, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("14.Test for VerifyNCName(\ud801 \udc01)") { Params = new object[] { 14, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("1.Test for VerifyNCName(abcd)") { Params = new object[] { 1, "valid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("16.Test for VerifyNCName(\ud801\n\udc01)") { Params = new object[] { 16, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("17.Test for VerifyNCName(\ud801\t\udc001)") { Params = new object[] { 17, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("18.Test for VerifyNCName(a\ud801\udc01b)") { Params = new object[] { 18, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("19.Test for VerifyNCName(a\udc01\ud801b)") { Params = new object[] { 19, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("20.Test for VerifyNCName(a\ud801b)") { Params = new object[] { 20, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("21.Test for VerifyNCName(a\udc01b)") { Params = new object[] { 21, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("22.Test for VerifyNCName(\ud801\udc01:)") { Params = new object[] { 22, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("23.Test for VerifyNCName(:a\ud801\udc01b)") { Params = new object[] { 23, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("24.Test for VerifyNCName(a\ud801\udc01:b)") { Params = new object[] { 24, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("25.Test for VerifyNCName(a\udbff\udc01\b)") { Params = new object[] { 25, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("7.Test for VerifyNCName(abcd def)") { Params = new object[] { 7, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("2.Test for VerifyNCName(abcd efgh)") { Params = new object[] { 2, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("3.Test for VerifyNCName( abcd)") { Params = new object[] { 3, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("4.Test for VerifyNCName(abcd\nalfafkjha)") { Params = new object[] { 4, "invalid" } } });
AddChild(new CVariation(v16) { Attribute = new Variation("5.Test for VerifyNCName(abcd\nalfafkjha)") { Params = new object[] { 5, "invalid" } } });
AddChild(new CVariation(v17) { Attribute = new Variation("Test for VerifyNCName(null)") { Param = 3 } });
AddChild(new CVariation(v17) { Attribute = new Variation("Test for VerifyXmlChars(null)") { Param = 5 } });
AddChild(new CVariation(v17) { Attribute = new Variation("Test for VerifyPublicId(null)") { Param = 6 } });
AddChild(new CVariation(v17) { Attribute = new Variation("Test for VerifyWhitespace(null)") { Param = 7 } });
AddChild(new CVariation(v17) { Attribute = new Variation("Test for VerifyName(null)") { Param = 2 } });
AddChild(new CVariation(v17) { Attribute = new Variation("Test for VerifyNMTOKEN(null)") { Param = 1 } });
AddChild(new CVariation(v18) { Attribute = new Variation("Test for VerifyPublicId(String.Empty)") { Params = new object[] { 6, null } } });
AddChild(new CVariation(v18) { Attribute = new Variation("Test for VerifyWhitespace(String.Empty)") { Params = new object[] { 7, null } } });
AddChild(new CVariation(v18) { Attribute = new Variation("Test for VerifyName(String.Empty)") { Params = new object[] { 2, typeof(ArgumentNullException) } } });
AddChild(new CVariation(v18) { Attribute = new Variation("Test for VerifyNCName(String.Empty)") { Params = new object[] { 3, typeof(ArgumentNullException) } } });
AddChild(new CVariation(v18) { Attribute = new Variation("Test for VerifyXmlChars(String.Empty)") { Params = new object[] { 5, null } } });
AddChild(new CVariation(v18) { Attribute = new Variation("Test for VerifyNMTOKEN(String.Empty)") { Params = new object[] { 1, typeof(XmlException) } } });
}
private int v16()
{
var param = (int)CurVariation.Params[0];
string input = String.Empty;
switch (param)
{
case 1:
input = "abcd";
break;
case 2:
input = "abcd efgh";
break;
case 3:
input = " abcd";
break;
case 4:
input = "abcd ";
break;
case 5:
input = "abcd\nalfafkjha";
break;
case 6:
input = "abcd\ralfafkjha";
break;
case 7:
input = "abcd def";
break;
case 8:
input = "abcd\tdef";
break;
case 9:
input = " \b";
break;
case 10:
input = "\ud801\udc01";
break;
case 11:
input = " \ud801\udc01";
break;
case 12:
input = "\ud801\udc01 ";
break;
case 13:
input = "\ud801 \udc01";
break;
case 14:
input = "\ud801 \udc01";
break;
case 15:
input = "\ud801\r\udc01";
break;
case 16:
input = "\ud801\n\udc01";
break;
case 17:
input = "\ud801\t\udc01";
break;
case 18:
input = "a\ud801\udc01b";
break;
case 19:
input = "a\udc01\ud801b";
break;
case 20:
input = "a\ud801b";
break;
case 21:
input = "a\udc01b";
break;
case 22:
input = "\ud801\udc01:";
break;
case 23:
input = ":a\ud801\udc01b";
break;
case 24:
input = "a\ud801\udc01b:";
break;
case 25:
input = "a\udbff\udc01\b";
break;
}
String expected = CurVariation.Params[1].ToString();
try
{
XmlConvert.VerifyNCName(input);
}
catch (XmlException e)
{
CError.WriteLine(e.LineNumber);
CError.WriteLine(e.LinePosition);
return (expected.Equals("invalid")) ? TEST_PASS : TEST_FAIL;
}
return (expected.Equals("valid")) ? TEST_PASS : TEST_FAIL;
}
private int v17()
{
var param = (int)CurVariation.Param;
try
{
switch (param)
{
case 1:
XmlConvert.VerifyNMTOKEN(null);
break;
case 2:
XmlConvert.VerifyName(null);
break;
case 3:
XmlConvert.VerifyNCName(null);
break;
case 5:
XmlConvert.VerifyXmlChars(null);
break;
case 6:
XmlConvert.VerifyPublicId(null);
break;
case 7:
XmlConvert.VerifyWhitespace(null);
break;
}
}
catch (ArgumentNullException)
{
return param != 4 ? TEST_PASS : TEST_FAIL; //param4 -> VerifyToken should not throw here
}
return TEST_FAIL;
}
/// <summary>
/// Params[] = { VariationNumber, Exception type (null if exception not expected) }
/// </summary>
/// <returns></returns>
private int v18()
{
var param = (int)CurVariation.Params[0];
var exceptionType = (Type)CurVariation.Params[1];
try
{
switch (param)
{
case 1:
XmlConvert.VerifyNMTOKEN(String.Empty);
break;
case 2:
XmlConvert.VerifyName(String.Empty);
break;
case 3:
XmlConvert.VerifyNCName(String.Empty);
break;
case 5:
XmlConvert.VerifyXmlChars(String.Empty);
break;
case 6:
XmlConvert.VerifyPublicId(String.Empty);
break;
case 7:
XmlConvert.VerifyWhitespace(String.Empty);
break;
}
}
catch (ArgumentException e)
{
return (exceptionType != null && e.GetType().Name == exceptionType.Name) ? TEST_PASS : TEST_FAIL;
}
catch (XmlException e)
{
CError.WriteLine(e.LineNumber);
CError.WriteLine(e.LinePosition);
return (exceptionType != null && e.GetType().Name == exceptionType.Name) ? TEST_PASS : TEST_FAIL;
}
return exceptionType == null ? TEST_PASS : TEST_FAIL;
}
}
}
| |
#region Copyright (c) 2003, newtelligence AG. All rights reserved.
/*
// Copyright (c) 2003, newtelligence AG. (http://www.newtelligence.com)
// Original BlogX Source Code: Copyright (c) 2003, Chris Anderson (http://simplegeek.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// (1) Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// (2) Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// (3) Neither the name of the newtelligence AG 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.
// -------------------------------------------------------------------------
//
// Original BlogX source code (c) 2003 by Chris Anderson (http://simplegeek.com)
//
// newtelligence is a registered trademark of newtelligence Aktiengesellschaft.
//
// For portions of this software, the some additional copyright notices may apply
// which can either be found in the license.txt file included in the source distribution
// or following this notice.
//
*/
#endregion
using System;
using System.Collections;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Web.UI;
using newtelligence.DasBlog.Runtime;
using System.Collections.Generic;
namespace newtelligence.DasBlog.Web.Core
{
/// <summary>
/// Summary description for BaseTemplateProcessor.
/// </summary>
public class TemplateProcessor
{
public TemplateProcessor()
{
}
public void ProcessTemplate(SharedBasePage page, string templateString, Control contentPlaceHolder, Macros macros)
{
ProcessTemplate(page, null, templateString, contentPlaceHolder, macros);
}
private static readonly Regex templateFinder = new Regex("<(?<esc>\\$|%)\\s*(?<macro>(?!\\k<esc>).+?)\\s*\\k<esc>>",RegexOptions.Compiled);
public void ProcessTemplate(SharedBasePage page, Entry entry, string templateString, Control contentPlaceHolder, Macros macros)
{
int lastIndex = 0;
MatchCollection matches = templateFinder.Matches(templateString);
foreach( Match match in matches )
{
if ( match.Index > lastIndex )
{
contentPlaceHolder.Controls.Add(new LiteralControl(templateString.Substring(lastIndex,match.Index-lastIndex)));
}
Group g = match.Groups["macro"];
Capture c = g.Captures[0];
Control ctrl = null;
object targetMacroObj = macros;
string captureValue = c.Value;
//Check for a string like: <%foo("bar", "bar")|assemblyConfigName%>
int assemblyNameIndex = captureValue.IndexOf(")|");
if (assemblyNameIndex != -1) //use the default Macros
{
//The QN minus the )|
string macroAssemblyName = captureValue.Substring(assemblyNameIndex+2);
//The method, including the )
captureValue = captureValue.Substring(0,assemblyNameIndex+1);
try
{
targetMacroObj = MacrosFactory.CreateCustomMacrosInstance(page, entry, macroAssemblyName);
}
catch (Exception ex)
{
string ExToString = ex.ToString();
if (ex.InnerException != null)
{
ExToString += ex.InnerException.ToString();
}
page.LoggingService.AddEvent(new EventDataItem(EventCodes.Error,String.Format("Error executing Macro: {0}",ExToString),string.Empty));
}
}
try
{
ctrl = InvokeMacro(targetMacroObj,captureValue) as Control;
if (ctrl != null)
{
contentPlaceHolder.Controls.Add(ctrl);
}
else
{
page.LoggingService.AddEvent(new EventDataItem(EventCodes.Error,String.Format("Error executing Macro: {0} returned null.",captureValue),string.Empty));
}
}
catch (Exception ex)
{
string error = String.Format("Error executing macro: {0}. Make sure it you're calling it in your BlogTemplate with parentheses like 'myMacro()'. Macros with parameter lists and overloads must be called in this way. Exception: {1}",c.Value, ex.ToString());
page.LoggingService.AddEvent(new EventDataItem(EventCodes.Error,error,string.Empty));
}
lastIndex = match.Index+match.Length;
}
if ( lastIndex < templateString.Length)
{
contentPlaceHolder.Controls.Add(new LiteralControl(templateString.Substring(lastIndex,templateString.Length-lastIndex)));
}
}
private bool IsMemberEligibleForMacroCall(MemberInfo m, object filterCriteria )
{
//This has to be case-insensitive and culture-invariant or
// "Item" and "item" won't match if the current culture is Turk
return String.Compare(m.Name,(string)filterCriteria,true,System.Globalization.CultureInfo.InvariantCulture)==0;
}
/// <summary>
/// Gotta replace that with regex one day....
/// </summary>
/// <param name="args"></param>
/// <param name="fromOffset"></param>
/// <param name="endOffset"></param>
/// <returns></returns>
private string[] SplitArgs( string args, int fromOffset, ref int endOffset )
{
List<string> arrList = new List<string>();
int argmark=fromOffset+1;
bool indquote=false,insquote=false,inesc=false;
char termChar = args[fromOffset]=='['?']':')';
int argwalk;
for( argwalk=fromOffset+1;argwalk<args.Length;argwalk++)
{
char chargwalk = args[argwalk];
if ( char.IsWhiteSpace(chargwalk) && !indquote && !insquote )
{
continue;
}
if ( chargwalk == '\"' && !inesc )
{
indquote = !indquote;
continue;
}
if ( chargwalk == '\'' && !inesc )
{
insquote = !insquote;
continue;
}
if ( chargwalk == '\\' && (indquote || insquote) )
{
inesc=!inesc;
continue;
}
if ( !indquote && !insquote && (chargwalk == ',' || chargwalk == termChar))
{
if ( argwalk > argmark )
{
string foundArg = args.Substring(argmark,argwalk-argmark).Trim();
if ( foundArg[0] == foundArg[foundArg.Length-1] )
{
foundArg = foundArg.Trim('\"','\'');
}
arrList.Add(foundArg);
argmark = argwalk+1;
}
if ( chargwalk == termChar)
{
break;
}
}
inesc=false;
}
endOffset = argwalk+1;
return arrList.ToArray();
}
private static Dictionary<string, CachedMacro> macros = new Dictionary<string, CachedMacro>();
private static object macrosLock = new object();
private class CachedMacro
{
public CachedMacro(MemberInfo macro) : this(macro, null){}
public CachedMacro(MemberInfo macro, object[] argumentList)
{
this.Macro = macro;
this.ArgumentList = argumentList;
}
public MemberInfo Macro = null;
public object[] ArgumentList = null;
public object Invoke(object obj)
{
PropertyInfo p = Macro as PropertyInfo;
if (p != null)
{
return p.GetValue(obj,ArgumentList);
}
MethodInfo m = Macro as MethodInfo;
if(m != null)
{
return m.Invoke(obj,ArgumentList);
}
FieldInfo f = Macro as FieldInfo;
if (f != null)
{
return f.GetValue(obj);
}
throw new NotSupportedException("Invalid cached macro!");
}
}
/// <summary>
/// This method invokes the macros. It's very tolerant about calls
/// it can't make, meaning that it absorbs the exceptions
/// </summary>
/// <param name="obj"></param>
/// <param name="expression"></param>
/// <returns></returns>
private object InvokeMacro( object obj, string expression )
{
int subexStartIndex = 0;
int subexEndIndex = 0;
object subexObject = obj;
try
{
do
{
subexEndIndex = expression.IndexOfAny(new char[]{'.','(','['}, subexStartIndex);
if ( subexEndIndex == -1 ) subexEndIndex=expression.Length;
string subex = expression.Substring(subexStartIndex,subexEndIndex-subexStartIndex);
int subexWithArgsEndIndex = expression.IndexOfAny(new char[]{'(','['}, subexStartIndex);
string subexWithArgs;
if ( subexWithArgsEndIndex != -1 )
subexWithArgs = expression.Substring(subexStartIndex);
else
subexWithArgs = subex;
// build the cacheKey used for caching the macros: typename.macroname
// obj can be null, so we should check for that
// we use obj instead of subexObject to short-cut the loop
string cacheKey = ( obj != null ? obj.GetType().FullName + "." : "" ) + subexWithArgs;
CachedMacro subCached;
if (!macros.TryGetValue(cacheKey, out subCached) || subCached == null)
{
lock(macrosLock)
{
subexStartIndex = subexEndIndex+1;
MemberInfo memberToInvoke;
MemberInfo[] members = subexObject.GetType().FindMembers(
MemberTypes.Field|MemberTypes.Method|MemberTypes.Property,
BindingFlags.IgnoreCase|BindingFlags.Instance|BindingFlags.Public,
new MemberFilter(this.IsMemberEligibleForMacroCall), subex.Trim() );
string[] arglist=null;
if ( members.Length == 0 )
{
throw new MissingMemberException(subexObject.GetType().FullName,subex.Trim());
}
if ( subexEndIndex<expression.Length && (expression[subexEndIndex] == '[' || expression[subexEndIndex] == '(') )
{
arglist = SplitArgs(expression,subexEndIndex, ref subexStartIndex);
}
//SDH: We REALLY need to refactor this whole Clemens thing - it's getting hairy.
memberToInvoke = null;
if ( members.Length > 1 )
{
foreach(MemberInfo potentialMember in members)
{
MethodInfo potentialMethod = potentialMember as MethodInfo;
if(potentialMethod != null)
{
ParameterInfo[] parameters = potentialMethod.GetParameters();
if(parameters != null && parameters.Length > 0)
{
if(parameters.Length == arglist.Length)
{
memberToInvoke = potentialMember;
break;
}
}
}
}
}
if(memberToInvoke == null)//Previous behavior, use the first one.
{
memberToInvoke = members[0];
}
if ( memberToInvoke.MemberType == MemberTypes.Property &&
(subexEndIndex==expression.Length ||
expression[subexEndIndex] == '.' ||
expression[subexEndIndex] == '[' ))
{
PropertyInfo propInfo = memberToInvoke as PropertyInfo;
if ( subexEndIndex<expression.Length && expression[subexEndIndex] == '[' )
{
System.Reflection.ParameterInfo[] paramInfo = propInfo.GetIndexParameters();
if ( arglist.Length > paramInfo.Length )
{
throw new InvalidOperationException(String.Format("Parameter list length mismatch {0}",memberToInvoke.Name));
}
object[] oarglist = new object[paramInfo.Length];
for( int n=0;n<arglist.Length;n++)
{
oarglist[n] = Convert.ChangeType(arglist[n],paramInfo[n].ParameterType);
}
CachedMacro macro = new CachedMacro(propInfo,oarglist);
macros[cacheKey] = macro;
subexObject = macro.Invoke(subexObject);
//subexObject = propInfo.GetValue(subexObject,oarglist);
}
else
{
CachedMacro macro = new CachedMacro(propInfo,null);
macros[cacheKey] = macro;
subexObject = macro.Invoke(subexObject);
//subexObject = propInfo.GetValue(subexObject,null);
}
}
else if ( memberToInvoke.MemberType == MemberTypes.Field &&
(subexEndIndex==expression.Length ||
expression[subexEndIndex] == '.'))
{
FieldInfo fieldInfo = memberToInvoke as FieldInfo;
CachedMacro macro = new CachedMacro(fieldInfo);
macros[cacheKey] = macro;
subexObject = macro.Invoke(subexObject);
//subexObject = fieldInfo.GetValue(subexObject);
}
else if ( memberToInvoke.MemberType == MemberTypes.Method &&
subexEndIndex<expression.Length && expression[subexEndIndex] == '(' )
{
MethodInfo methInfo = memberToInvoke as MethodInfo;
System.Reflection.ParameterInfo[] paramInfo = methInfo.GetParameters();
if ( arglist.Length > paramInfo.Length &&
!(paramInfo.Length>0 && paramInfo[paramInfo.Length-1].ParameterType == typeof(string[])))
{
throw new InvalidOperationException(String.Format("Parameter list length mismatch {0}",memberToInvoke.Name));
}
object[] oarglist = new object[paramInfo.Length];
for( int n=0;n<arglist.Length;n++)
{
if ( n == paramInfo.Length-1 &&
arglist.Length>paramInfo.Length)
{
string[] paramsArg = new string[arglist.Length-paramInfo.Length+1];
for( int m=n;m<arglist.Length;m++)
{
paramsArg[m-n] = Convert.ChangeType(arglist[n],typeof(string)) as string;
}
oarglist[n] = paramsArg;
break;
}
else
{
oarglist[n] = Convert.ChangeType(arglist[n],paramInfo[n].ParameterType);
}
}
CachedMacro macro = new CachedMacro(methInfo,oarglist);
macros[cacheKey] = macro;
subexObject = macro.Invoke(subexObject);
//subexObject = methInfo.Invoke(subexObject,oarglist);
}
}
}
else
{
subexStartIndex = subexEndIndex+1;
subexObject = subCached.Invoke(subexObject);
if (subexObject is Control)
{
return subexObject;
}
}
}
while(subexEndIndex<expression.Length && subexStartIndex < expression.Length);
return subexObject==null?new LiteralControl(""):subexObject;
}
catch( Exception exc )
{
ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error,exc);
throw;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Glimpse.Core.Tab.Assist;
using Xunit;
namespace Glimpse.Test.Core.Plugin.Assist
{
public class TabLayoutCellShould
{
[Fact]
public void SetDataId()
{
var cell = new TabLayoutCell(1);
Assert.Equal(1, cell.Data);
}
[Fact]
public void ThrowForNegativeValue()
{
Assert.Throws<ArgumentException>(() => new TabLayoutCell(-1));
}
[Fact]
public void SetDataFormatOnConstruction()
{
var cell = new TabLayoutCell("{0} - {1}");
Assert.Equal("{0} - {1}", cell.Data);
}
[Fact]
public void ThrowForNullOrEmptyConstruction()
{
Assert.Throws<ArgumentException>(() => new TabLayoutCell(null));
Assert.Throws<ArgumentException>(() => new TabLayoutCell(""));
}
[Fact]
public void ThrowWhenNullOrEmpty()
{
Assert.Throws<ArgumentException>(() => Cell.Format(""));
Assert.Throws<ArgumentException>(() => Cell.Format(null));
}
[Fact]
public void SetDataFormat()
{
Cell.Format("{0} -> {1} <- {2}");
Assert.Equal("{0} -> {1} <- {2}", Cell.Data);
}
[Fact]
public void SetStructureToRows()
{
var layout = TabLayout.Create();
layout.Row(r => { }).Row(r => {});
Cell.SetLayout(layout);
Assert.NotEqual(layout.Rows, Cell.Layout);
}
[Fact]
public void AddRowsToStructure()
{
IEnumerable<TabLayoutRow> rows = null;
Cell.SetLayout(layout =>
{
layout.Row(r => { }).Row(r => { });
rows = layout.Rows;
});
Assert.Equal(rows, Cell.Layout);
}
[Fact]
public void SetIsKey()
{
Cell.AsKey();
Assert.Equal(true, Cell.Key);
}
[Fact]
public void SetIsCodeAndCodeType()
{
Cell.AsCode(CodeType.Sql);
Assert.Equal(true, Cell.IsCode);
Assert.Equal(CodeType.Sql.ToString().ToLower(), Cell.CodeType);
}
[Fact]
public void SetAlign()
{
Cell.AlignRight();
Assert.Equal("Right", Cell.Align);
}
[Fact]
public void ThrowForNegativeValuePixelValue()
{
Assert.Throws<ArgumentException>(() => Cell.WidthInPixels(-1));
}
[Fact]
public void SetWidthInPixels()
{
Cell.WidthInPixels(123);
Assert.Equal("123px", Cell.Width);
}
[Fact]
public void ThrowForNegativePercentValue()
{
Assert.Throws<ArgumentException>(() => Cell.WidthInPercent(-1));
}
[Fact]
public void SetWidthInPecent()
{
Cell.WidthInPercent(123);
Assert.Equal("123%", Cell.Width);
}
[Fact]
public void ThrowForValueLessThenOne()
{
Assert.Throws<ArgumentException>(() => Cell.SpanColumns(-1));
Assert.Throws<ArgumentException>(() => Cell.SpanColumns(0));
}
[Fact]
public void SetRowSpan()
{
Cell.SpanColumns(3);
Assert.Equal(3, Cell.Span);
}
[Fact]
public void ThrowForNullOrEmptyClass()
{
Assert.Throws<ArgumentException>(() => Cell.Class(null));
Assert.Throws<ArgumentException>(() => Cell.Class(""));
}
[Fact]
public void SetClassName()
{
Cell.Class("mono");
Assert.Equal("mono", Cell.ClassName);
}
[Fact]
public void SetSuppressAutoPreview()
{
Cell.DisablePreview();
Assert.Equal(true, Cell.ForceFull);
}
[Fact]
public void ThrowForValueLessThenOneLimitTo()
{
Assert.Throws<ArgumentException>(() => Cell.LimitTo(-1));
Assert.Throws<ArgumentException>(() => Cell.LimitTo(0));
}
[Fact]
public void SetLimit()
{
Cell.LimitTo(10);
Assert.Equal(10, Cell.Limit);
}
[Fact]
public void ThrowForNullOrEmptyPrefix()
{
Assert.Throws<ArgumentException>(() => Cell.Prefix(null));
Assert.Throws<ArgumentException>(() => Cell.Prefix(""));
}
[Fact]
public void SetPre()
{
Cell.Prefix("T+ ");
Assert.Equal("T+ ", Cell.Pre);
}
[Fact]
public void ThrowForNullOrEmptySuffix()
{
Assert.Throws<ArgumentException>(() => Cell.Suffix(null));
Assert.Throws<ArgumentException>(() => Cell.Suffix(""));
}
[Fact]
public void SetPost()
{
Cell.Suffix(" ms");
Assert.Equal(" ms", Cell.Post);
}
private TabLayoutCell Cell { get; set; }
public TabLayoutCellShould()
{
Cell = new TabLayoutCell(1);
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web;
using Adxstudio.Xrm.Resources;
using Microsoft.Xrm.Client.Messages;
using Microsoft.Xrm.Portal.Configuration;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
namespace Adxstudio.Xrm.Web.UI.WebForms
{
/// <summary>
/// Session History Provider stores data to CRM
/// </summary>
public class CrmSessionHistoryProvider : ISessionHistoryProvider
{
/// <summary>
/// Initialize the Session History
/// </summary>
/// <param name="webFormId">ID of the web form</param>
/// <param name="currentStepId">ID of the current step</param>
/// <param name="currentStepIndex">Index of the current step</param>
/// <param name="recordId">ID of the target record</param>
/// <param name="recordEntityLogicalName">Logical name of the target record entity</param>
/// <param name="recordEntityPrimaryKeyLogicalName">Logical name of the primary key of the target record entity</param>
/// <param name="contactId">ID of the authenticated user's contact record</param>
/// <param name="systemUserId">ID of the authenticated user's system user record</param>
/// <param name="anonymousIdentification">Identifier of the anonymous user. Requires a web.config section anonymousIdentification <see href="http://msdn.microsoft.com/en-us/library/91ka2e6a.aspx"/></param>
/// <param name="userIdentityName">User's Identity Name</param>
/// <param name="userHostAddress">IP Address of the user's computer</param>
/// <returns>Session History</returns>
public SessionHistory InitializeSessionHistory(Guid webFormId, Guid currentStepId, int currentStepIndex, Guid recordId, string recordEntityLogicalName, string recordEntityPrimaryKeyLogicalName, Guid? contactId, Guid? systemUserId, string anonymousIdentification, string userIdentityName, string userHostAddress)
{
var stepHistory = new List<SessionHistory.Step>();
var referenceEntity = new SessionHistory.ReferenceEntity
{
ID = recordId,
LogicalName = recordEntityLogicalName,
PrimaryKeyLogicalName = recordEntityPrimaryKeyLogicalName
};
var step = new SessionHistory.Step { ID = currentStepId, Index = currentStepIndex, ReferenceEntity = referenceEntity };
stepHistory.Add(step);
return (new SessionHistory
{
Id = Guid.Empty,
WebFormId = webFormId,
CurrentStepId = currentStepId,
CurrentStepIndex = currentStepIndex,
PrimaryRecord = referenceEntity,
ContactId = contactId ?? Guid.Empty,
SystemUserId = systemUserId ?? Guid.Empty,
AnonymousIdentification = anonymousIdentification,
UserIdentityName = userIdentityName,
UserHostAddress = userHostAddress,
StepHistory = stepHistory
});
}
/// <summary>
/// Initialize the Session History
/// </summary>
/// <param name="context">Context used to retrieve session history</param>
/// <param name="webFormId">ID of the web form</param>
/// <param name="stepId">ID of the current step</param>
/// <param name="stepIndex">Index of the current step</param>
/// <param name="recordId">ID of the target record</param>
/// <param name="recordEntityLogicalName">Logical name of the target record entity</param>
/// <param name="recordEntityPrimaryKeyLogicalName">Logical name of the primary key of the target record entity</param>
/// <returns>Session History</returns>
public SessionHistory InitializeSessionHistory(OrganizationServiceContext context, Guid webFormId, Guid stepId, int stepIndex, Guid recordId, string recordEntityLogicalName, string recordEntityPrimaryKeyLogicalName)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (webFormId == Guid.Empty)
{
throw new ArgumentNullException("webFormId");
}
if (stepId == Guid.Empty)
{
throw new ArgumentNullException("stepId");
}
if (string.IsNullOrWhiteSpace(recordEntityLogicalName))
{
throw new ArgumentNullException("recordEntityLogicalName");
}
if (string.IsNullOrWhiteSpace(recordEntityPrimaryKeyLogicalName))
{
throw new ArgumentNullException("recordEntityPrimaryKeyLogicalName");
}
var contactId = Guid.Empty;
var systemUserId = Guid.Empty;
var anonymousIdentification = string.Empty;
var userIdentityName = string.Empty;
var userHostName = string.Empty;
if (HttpContext.Current.Request.IsAuthenticated)
{
var portalContext = PortalCrmConfigurationManager.CreatePortalContext();
if (portalContext.User == null)
{
throw new ApplicationException("Couldn't load user record. Portal context User is null.");
}
switch (portalContext.User.LogicalName)
{
case "contact":
contactId = portalContext.User.Id;
break;
case "systemuser":
systemUserId = portalContext.User.Id;
break;
default:
if (HttpContext.Current.User == null || string.IsNullOrWhiteSpace(HttpContext.Current.User.Identity.Name))
{
throw new ApplicationException(string.Format("The user entity type {0} isn't supported.", portalContext.User.LogicalName));
}
break;
}
}
else
{
if (HttpContext.Current.Profile != null && !string.IsNullOrWhiteSpace(HttpContext.Current.Profile.UserName))
{
anonymousIdentification = HttpContext.Current.Profile.UserName;
}
}
if (HttpContext.Current.User != null && !string.IsNullOrWhiteSpace(HttpContext.Current.User.Identity.Name))
{
userIdentityName = HttpContext.Current.User.Identity.Name;
}
if (!string.IsNullOrWhiteSpace(HttpContext.Current.Request.UserHostName))
{
userHostName = HttpContext.Current.Request.UserHostName;
}
return InitializeSessionHistory(webFormId, stepId, stepIndex, recordId, recordEntityLogicalName, recordEntityPrimaryKeyLogicalName, contactId, systemUserId, anonymousIdentification, userIdentityName, userHostName);
}
/// <summary>
/// Get Session History for the specified web form and contact
/// </summary>
/// <param name="context">Context used to retrieve session history</param>
/// <param name="webFormId">Unique Identifier of the Web Form</param>
/// <param name="contactId">Unique Identifier of the contact</param>
/// <returns>Session History</returns>
/// <exception cref="ArgumentNullException"></exception>
public SessionHistory GetSessionHistoryByContact(OrganizationServiceContext context, Guid webFormId, Guid contactId)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
var webFormSession = context.CreateQuery("adx_webformsession").Where(s => s.GetAttributeValue<OptionSetValue>("statecode") != null && s.GetAttributeValue<OptionSetValue>("statecode").Value == 0).OrderByDescending(s => s.GetAttributeValue<DateTime>("modifiedon")).FirstOrDefault(s => s.GetAttributeValue<EntityReference>("adx_webform") == new EntityReference("adx_webform", webFormId) && s.GetAttributeValue<EntityReference>("adx_contact") == new EntityReference("contact", contactId));
return GetSessionHistory(webFormSession);
}
/// <summary>
/// Get Session History for the specified web form and system user
/// </summary>
/// <param name="context">Context used to retrieve session history</param>
/// <param name="webFormId">Unique Identifier of the Web Form</param>
/// <param name="systemUserId">Unique Identifier of the system user</param>
/// <returns>Session History</returns>
/// <exception cref="ArgumentNullException"></exception>
public SessionHistory GetSessionHistoryBySystemUser(OrganizationServiceContext context, Guid webFormId, Guid systemUserId)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
var webFormSession = context.CreateQuery("adx_webformsession").Where(s => s.GetAttributeValue<OptionSetValue>("statecode") != null && s.GetAttributeValue<OptionSetValue>("statecode").Value == 0).OrderByDescending(s => s.GetAttributeValue<DateTime>("modifiedon")).FirstOrDefault(s => s.GetAttributeValue<EntityReference>("adx_webform") == new EntityReference("adx_webform", webFormId) && s.GetAttributeValue<EntityReference>("adx_systemuser") == new EntityReference("systemuser", systemUserId));
return GetSessionHistory(webFormSession);
}
/// <summary>
/// Get Session History for the specified web form and user identity name
/// </summary>
/// <param name="context">Context used to retrieve session history</param>
/// <param name="webFormId">Unique Identifier of the Web Form</param>
/// <param name="userIdentityName">User Identity Name</param>
/// <returns>Session History</returns>
/// <exception cref="ArgumentNullException"></exception>
public SessionHistory GetSessionHistoryByUserIdentityName(OrganizationServiceContext context, Guid webFormId, string userIdentityName)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
var webFormSession = context.CreateQuery("adx_webformsession").Where(s => s.GetAttributeValue<OptionSetValue>("statecode") != null && s.GetAttributeValue<OptionSetValue>("statecode").Value == 0).OrderByDescending(s => s.GetAttributeValue<DateTime>("modifiedon")).FirstOrDefault(s => s.GetAttributeValue<EntityReference>("adx_webform") == new EntityReference("adx_webform", webFormId) && s.GetAttributeValue<string>("adx_useridentityname") == userIdentityName);
return GetSessionHistory(webFormSession);
}
/// <summary>
/// Get Session History for the specified web form and anonymous user.
/// </summary>
/// <param name="context">Context used to retrieve session history</param>
/// <param name="webFormId">Unique Identifier of the Web Form</param>
/// <param name="anonymousIdentification">Identification of the anonymous user</param>
/// <returns>Session History</returns>
/// <exception cref="ArgumentNullException"></exception>
public SessionHistory GetSessionHistoryByAnonymousIdentification(OrganizationServiceContext context, Guid webFormId, string anonymousIdentification)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
var webFormSession = context.CreateQuery("adx_webformsession").Where(s => s.GetAttributeValue<OptionSetValue>("statecode") != null && s.GetAttributeValue<OptionSetValue>("statecode").Value == 0).OrderByDescending(s => s.GetAttributeValue<DateTime>("modifiedon")).FirstOrDefault(s => s.GetAttributeValue<EntityReference>("adx_webform") == new EntityReference("adx_webform", webFormId) && s.GetAttributeValue<string>("adx_anonymousidentification") == anonymousIdentification);
return GetSessionHistory(webFormSession);
}
/// <summary>
/// Get Session History for the specified record ID
/// </summary>
/// <param name="context">Context used to retrieve session history</param>
/// <param name="webFormId">Unique Identifier of the Web Form</param>
/// <param name="recordId">ID of the target record</param>
/// <returns></returns>
public SessionHistory GetSessionHistoryByPrimaryRecord(OrganizationServiceContext context, Guid webFormId, Guid recordId)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
var webFormSession = context.CreateQuery("adx_webformsession").FirstOrDefault(s => s.GetAttributeValue<OptionSetValue>("statecode") != null && s.GetAttributeValue<OptionSetValue>("statecode").Value == 0 && s.GetAttributeValue<EntityReference>("adx_webform") == new EntityReference("adx_webform", webFormId) && s.GetAttributeValue<string>("adx_primaryrecordid") == recordId.ToString());
return GetSessionHistory(webFormSession);
}
/// <summary>
/// Get Session History for the specified session history ID
/// </summary>
/// <param name="context">Context used to retrieve session history</param>
/// <param name="sessionID">ID of the session history record</param>
/// <returns></returns>
public SessionHistory GetSessionHistory(OrganizationServiceContext context, Guid sessionID)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
var webFormSession = context.CreateQuery("adx_webformsession").FirstOrDefault(s => s.GetAttributeValue<OptionSetValue>("statecode") != null && s.GetAttributeValue<OptionSetValue>("statecode").Value == 0 && s.GetAttributeValue<Guid>("adx_webformsessionid") == sessionID);
return GetSessionHistory(webFormSession);
}
private static SessionHistory GetSessionHistory(Entity webFormSession)
{
if (webFormSession == null)
{
return null;
}
var sessionHistory = new SessionHistory
{
Id = webFormSession.Id,
WebFormId = webFormSession.GetAttributeValue<EntityReference>("adx_webform") == null ? Guid.Empty : webFormSession.GetAttributeValue<EntityReference>("adx_webform").Id
};
var currentStep = webFormSession.GetAttributeValue<EntityReference>("adx_currentwebformstep");
if (currentStep == null)
{
throw new ApplicationException("adx_webformsession.adx_currentwebformstep is null.");
}
sessionHistory.CurrentStepId = currentStep.Id;
var currentStepIndex = webFormSession.GetAttributeValue<int?>("adx_currentstepindex");
var stepIndex = currentStepIndex ?? 0;
if (currentStepIndex == null)
{
throw new ApplicationException("adx_webformsession.adx_currentwebformstep is null.");
}
sessionHistory.CurrentStepIndex = stepIndex;
Guid recordGuid;
var recordid = webFormSession.GetAttributeValue<string>("adx_primaryrecordid");
sessionHistory.PrimaryRecord = new SessionHistory.ReferenceEntity();
if (!string.IsNullOrWhiteSpace(recordid) && Guid.TryParse(recordid, out recordGuid))
{
sessionHistory.PrimaryRecord.ID = recordGuid;
}
sessionHistory.PrimaryRecord.LogicalName = webFormSession.GetAttributeValue<string>("adx_primaryrecordentitylogicalname") ?? string.Empty;
sessionHistory.PrimaryRecord.PrimaryKeyLogicalName = webFormSession.GetAttributeValue<string>("adx_primaryrecordentitykeyname") ?? string.Empty;
var contact = webFormSession.GetAttributeValue<EntityReference>("adx_contact");
sessionHistory.ContactId = contact != null ? contact.Id : Guid.Empty;
var quote = webFormSession.GetAttributeValue<EntityReference>("adx_quoteid");
sessionHistory.QuoteId = quote != null ? quote.Id : Guid.Empty;
var systemUser = webFormSession.GetAttributeValue<EntityReference>("adx_systemuser");
sessionHistory.SystemUserId = systemUser != null ? systemUser.Id : Guid.Empty;
sessionHistory.AnonymousIdentification = webFormSession.GetAttributeValue<string>("adx_anonymousidentification") ?? string.Empty;
sessionHistory.StepHistory = ConvertJsonStringToList(webFormSession.GetAttributeValue<string>("adx_stephistory"));
sessionHistory.UserHostAddress = webFormSession.GetAttributeValue<string>("adx_userhostaddress") ?? string.Empty;
sessionHistory.UserIdentityName = webFormSession.GetAttributeValue<string>("adx_useridentityname") ?? string.Empty;
return sessionHistory;
}
/// <summary>
/// Persists the Session History
/// </summary>
/// <param name="context">Context used to save the session history</param>
/// <param name="sessionHistory">Session History object</param>
public Guid PersistSessionHistory(OrganizationServiceContext context, SessionHistory sessionHistory)
{
if (sessionHistory == null)
{
return Guid.Empty;
}
var webFormSession = sessionHistory.Id != Guid.Empty ? context.CreateQuery("adx_webformsession").FirstOrDefault(s => s.GetAttributeValue<OptionSetValue>("statecode") != null && s.GetAttributeValue<OptionSetValue>("statecode").Value == 0 && s.GetAttributeValue<Guid>("adx_webformsessionid") == sessionHistory.Id) : null;
var addNew = webFormSession == null;
if (addNew)
{
webFormSession = new Entity("adx_webformsession");
if (sessionHistory.WebFormId != Guid.Empty)
{
webFormSession.Attributes["adx_webform"] = new EntityReference("adx_webform", sessionHistory.WebFormId);
}
}
if (sessionHistory.PrimaryRecord != null && sessionHistory.PrimaryRecord.ID != Guid.Empty)
{
webFormSession.Attributes["adx_primaryrecordid"] = sessionHistory.PrimaryRecord.ID.ToString();
}
if (sessionHistory.CurrentStepId != Guid.Empty)
{
webFormSession.Attributes["adx_currentwebformstep"] = new EntityReference("adx_webformstep", sessionHistory.CurrentStepId);
}
if (sessionHistory.PrimaryRecord != null && !string.IsNullOrWhiteSpace(sessionHistory.PrimaryRecord.LogicalName))
{
webFormSession.Attributes["adx_primaryrecordentitylogicalname"] = sessionHistory.PrimaryRecord.LogicalName;
}
if (sessionHistory.PrimaryRecord != null && !string.IsNullOrWhiteSpace(sessionHistory.PrimaryRecord.PrimaryKeyLogicalName))
{
webFormSession.Attributes["adx_primaryrecordentitykeyname"] = sessionHistory.PrimaryRecord.PrimaryKeyLogicalName;
}
webFormSession.Attributes["adx_currentstepindex"] = sessionHistory.CurrentStepIndex;
if (sessionHistory.ContactId != Guid.Empty)
{
webFormSession.Attributes["adx_contact"] = new EntityReference("contact", sessionHistory.ContactId);
}
if (sessionHistory.QuoteId != Guid.Empty)
{
webFormSession.Attributes["adx_quoteid"] = new EntityReference("quote", sessionHistory.QuoteId);
}
if (sessionHistory.SystemUserId != Guid.Empty)
{
webFormSession.Attributes["adx_systemuser"] = new EntityReference("systemuser", sessionHistory.SystemUserId);
}
if (!string.IsNullOrWhiteSpace(sessionHistory.AnonymousIdentification))
{
webFormSession.Attributes["adx_anonymousidentification"] = sessionHistory.AnonymousIdentification;
}
webFormSession.Attributes["adx_stephistory"] = ConvertListToJsonString(sessionHistory.StepHistory);
if (!string.IsNullOrWhiteSpace(sessionHistory.UserHostAddress))
{
webFormSession.Attributes["adx_userhostaddress"] = sessionHistory.UserHostAddress;
}
if (!string.IsNullOrWhiteSpace(sessionHistory.UserIdentityName))
{
webFormSession.Attributes["adx_useridentityname"] = sessionHistory.UserIdentityName;
}
if (addNew)
{
context.AddObject(webFormSession);
}
else
{
context.UpdateObject(webFormSession);
}
context.SaveChanges();
return webFormSession.Id;
}
/// <summary>
/// Deactivates the Session History.
/// </summary>
/// <param name="context">Context used to deactivate the session history.</param>
/// <param name="id">ID of the Session History object.</param>
public void DeactivateSessionHistory(OrganizationServiceContext context, Guid id)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (id == Guid.Empty)
{
throw new ArgumentNullException("id");
}
var webFormSession = context.CreateQuery("adx_webformsession").FirstOrDefault(s => s.GetAttributeValue<Guid>("adx_webformsessionid") == id);
if (webFormSession == null)
{
return;
}
context.SetState(1, 2, webFormSession.ToEntityReference());
}
private static string ConvertListToJsonString(List<SessionHistory.Step> history)
{
var stream = new MemoryStream();
var serialiser = new DataContractJsonSerializer(typeof(List<SessionHistory.Step>));
serialiser.WriteObject(stream, history);
var json = Encoding.Default.GetString(stream.ToArray());
stream.Close();
return json;
}
private static List<SessionHistory.Step> ConvertJsonStringToList(string json)
{
List<SessionHistory.Step> result = null;
if (!string.IsNullOrWhiteSpace(json))
{
var byteArray = Encoding.Unicode.GetBytes(json);
var stream = new MemoryStream(byteArray);
var serialiser = new DataContractJsonSerializer(typeof(List<SessionHistory.Step>));
result = serialiser.ReadObject(stream) as List<SessionHistory.Step>;
stream.Close();
}
return result;
}
}
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.