context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Text;
using System.Diagnostics;
using Internal.Cryptography;
namespace System.Security.Cryptography
{
public class Rfc2898DeriveBytes : DeriveBytes
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5350", Justification = "HMACSHA1 is needed for compat. (https://github.com/dotnet/corefx/issues/9438)")]
public Rfc2898DeriveBytes(byte[] password, byte[] salt, int iterations)
{
if (salt == null)
throw new ArgumentNullException(nameof(salt));
if (salt.Length < MinimumSaltSize)
throw new ArgumentException(SR.Cryptography_PasswordDerivedBytes_FewBytesSalt, nameof(salt));
if (iterations <= 0)
throw new ArgumentOutOfRangeException(nameof(iterations), SR.ArgumentOutOfRange_NeedPosNum);
if (password == null)
throw new NullReferenceException(); // This "should" be ArgumentNullException but for compat, we throw NullReferenceException.
_salt = salt.CloneByteArray();
_iterations = (uint)iterations;
_password = password.CloneByteArray();
_hmacSha1 = new HMACSHA1(_password);
Initialize();
}
public Rfc2898DeriveBytes(string password, byte[] salt)
: this(password, salt, 1000)
{
}
public Rfc2898DeriveBytes(string password, byte[] salt, int iterations)
: this(Encoding.UTF8.GetBytes(password), salt, iterations)
{
}
public Rfc2898DeriveBytes(string password, int saltSize)
: this(password, saltSize, 1000)
{
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5350", Justification = "HMACSHA1 is needed for compat. (https://github.com/dotnet/corefx/issues/9438)")]
public Rfc2898DeriveBytes(string password, int saltSize, int iterations)
{
if (saltSize < 0)
throw new ArgumentOutOfRangeException(nameof(saltSize), SR.ArgumentOutOfRange_NeedNonNegNum);
if (saltSize < MinimumSaltSize)
throw new ArgumentException(SR.Cryptography_PasswordDerivedBytes_FewBytesSalt, nameof(saltSize));
if (iterations <= 0)
throw new ArgumentOutOfRangeException(nameof(iterations), SR.ArgumentOutOfRange_NeedPosNum);
_salt = Helpers.GenerateRandom(saltSize);
_iterations = (uint)iterations;
_password = Encoding.UTF8.GetBytes(password);
_hmacSha1 = new HMACSHA1(_password);
Initialize();
}
public int IterationCount
{
get
{
return (int)_iterations;
}
set
{
if (value <= 0)
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedPosNum);
_iterations = (uint)value;
Initialize();
}
}
public byte[] Salt
{
get
{
return _salt.CloneByteArray();
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.Length < MinimumSaltSize)
throw new ArgumentException(SR.Cryptography_PasswordDerivedBytes_FewBytesSalt);
_salt = value.CloneByteArray();
Initialize();
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (_hmacSha1 != null)
_hmacSha1.Dispose();
_hmacSha1 = null;
if (_buffer != null)
Array.Clear(_buffer, 0, _buffer.Length);
if (_password != null)
Array.Clear(_password, 0, _password.Length);
if (_salt != null)
Array.Clear(_salt, 0, _salt.Length);
}
base.Dispose(disposing);
}
public override byte[] GetBytes(int cb)
{
if (cb <= 0)
throw new ArgumentOutOfRangeException(nameof(cb), SR.ArgumentOutOfRange_NeedPosNum);
byte[] password = new byte[cb];
int offset = 0;
int size = _endIndex - _startIndex;
if (size > 0)
{
if (cb >= size)
{
Buffer.BlockCopy(_buffer, _startIndex, password, 0, size);
_startIndex = _endIndex = 0;
offset += size;
}
else
{
Buffer.BlockCopy(_buffer, _startIndex, password, 0, cb);
_startIndex += cb;
return password;
}
}
Debug.Assert(_startIndex == 0 && _endIndex == 0, "Invalid start or end index in the internal buffer.");
while (offset < cb)
{
byte[] T_block = Func();
int remainder = cb - offset;
if (remainder > BlockSize)
{
Buffer.BlockCopy(T_block, 0, password, offset, BlockSize);
offset += BlockSize;
}
else
{
Buffer.BlockCopy(T_block, 0, password, offset, remainder);
offset += remainder;
Buffer.BlockCopy(T_block, remainder, _buffer, _startIndex, BlockSize - remainder);
_endIndex += (BlockSize - remainder);
return password;
}
}
return password;
}
public byte[] CryptDeriveKey(string algname, string alghashname, int keySize, byte[] rgbIV)
{
// If this were to be implemented here, CAPI would need to be used (not CNG) because of
// unfortunate differences between the two. Using CNG would break compatibility. Since this
// assembly currently doesn't use CAPI it would require non-trivial additions.
// In addition, if implemented here, only Windows would be supported as it is intended as
// a thin wrapper over the corresponding native API.
// Note that this method is implemented in PasswordDeriveBytes (in the Csp assembly) using CAPI.
throw new PlatformNotSupportedException();
}
public override void Reset()
{
Initialize();
}
private void Initialize()
{
if (_buffer != null)
Array.Clear(_buffer, 0, _buffer.Length);
_buffer = new byte[BlockSize];
_block = 1;
_startIndex = _endIndex = 0;
}
// This function is defined as follows:
// Func (S, i) = HMAC(S || i) | HMAC2(S || i) | ... | HMAC(iterations) (S || i)
// where i is the block number.
private byte[] Func()
{
byte[] temp = new byte[_salt.Length + sizeof(uint)];
Buffer.BlockCopy(_salt, 0, temp, 0, _salt.Length);
Helpers.WriteInt(_block, temp, _salt.Length);
temp = _hmacSha1.ComputeHash(temp);
byte[] ret = temp;
for (int i = 2; i <= _iterations; i++)
{
temp = _hmacSha1.ComputeHash(temp);
for (int j = 0; j < BlockSize; j++)
{
ret[j] ^= temp[j];
}
}
// increment the block count.
_block++;
return ret;
}
private readonly byte[] _password;
private byte[] _salt;
private uint _iterations;
private HMACSHA1 _hmacSha1;
private byte[] _buffer;
private uint _block;
private int _startIndex;
private int _endIndex;
private const int BlockSize = 20;
private const int MinimumSaltSize = 8;
}
}
| |
/*
* 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 Nini.Config;
using log4net;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Data;
using OpenSim.Services.Interfaces;
using OpenMetaverse;
namespace OpenSim.Services.AssetService
{
public class AssetService : AssetServiceBase, IAssetService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
public AssetService(IConfigSource config) : base(config)
{
MainConsole.Instance.Commands.AddCommand("kfs", false,
"show digest",
"show digest <ID>",
"Show asset digest", HandleShowDigest);
MainConsole.Instance.Commands.AddCommand("kfs", false,
"delete asset",
"delete asset <ID>",
"Delete asset from database", HandleDeleteAsset);
if (m_AssetLoader != null)
{
IConfig assetConfig = config.Configs["AssetService"];
if (assetConfig == null)
throw new Exception("No AssetService configuration");
string loaderArgs = assetConfig.GetString("AssetLoaderArgs",
String.Empty);
bool assetLoaderEnabled = assetConfig.GetBoolean("AssetLoaderEnabled", true);
if (assetLoaderEnabled)
{
m_log.InfoFormat("[ASSET]: Loading default asset set from {0}", loaderArgs);
m_AssetLoader.ForEachDefaultXmlAsset(loaderArgs,
delegate(AssetBase a)
{
Store(a);
});
}
m_log.Info("[ASSET SERVICE]: Local asset service enabled");
}
}
public AssetBase Get(string id)
{
UUID assetID;
if (!UUID.TryParse(id, out assetID))
{
m_log.WarnFormat("[ASSET SERVICE]: Could not parse requested sset id {0}", id);
return null;
}
return m_Database.GetAsset(assetID);
}
public AssetBase GetCached(string id)
{
return Get(id);
}
public AssetMetadata GetMetadata(string id)
{
UUID assetID;
if (!UUID.TryParse(id, out assetID))
return null;
AssetBase asset = m_Database.GetAsset(assetID);
return asset.Metadata;
}
public byte[] GetData(string id)
{
UUID assetID;
if (!UUID.TryParse(id, out assetID))
return null;
AssetBase asset = m_Database.GetAsset(assetID);
return asset.Data;
}
public bool Get(string id, Object sender, AssetRetrieved handler)
{
//m_log.DebugFormat("[AssetService]: Get asset async {0}", id);
UUID assetID;
if (!UUID.TryParse(id, out assetID))
return false;
AssetBase asset = m_Database.GetAsset(assetID);
//m_log.DebugFormat("[AssetService]: Got asset {0}", asset);
handler(id, sender, asset);
return true;
}
public string Store(AssetBase asset)
{
//m_log.DebugFormat("[ASSET SERVICE]: Store asset {0} {1}", asset.Name, asset.ID);
m_Database.StoreAsset(asset);
return asset.ID;
}
public bool UpdateContent(string id, byte[] data)
{
return false;
}
public bool Delete(string id)
{
return false;
}
void HandleShowDigest(string module, string[] args)
{
if (args.Length < 3)
{
MainConsole.Instance.Output("Syntax: show digest <ID>");
return;
}
AssetBase asset = Get(args[2]);
if (asset == null || asset.Data.Length == 0)
{
MainConsole.Instance.Output("Asset not found");
return;
}
int i;
MainConsole.Instance.Output(String.Format("Name: {0}", asset.Name));
MainConsole.Instance.Output(String.Format("Description: {0}", asset.Description));
MainConsole.Instance.Output(String.Format("Type: {0}", asset.Type));
MainConsole.Instance.Output(String.Format("Content-type: {0}", asset.Metadata.ContentType));
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));
}
}
void HandleDeleteAsset(string module, string[] args)
{
if (args.Length < 3)
{
MainConsole.Instance.Output("Syntax: delete asset <ID>");
return;
}
AssetBase asset = Get(args[2]);
if (asset == null || asset.Data.Length == 0)
{
MainConsole.Instance.Output("Asset not found");
return;
}
Delete(args[2]);
//MainConsole.Instance.Output("Asset deleted");
// TODO: Implement this
MainConsole.Instance.Output("Asset deletion not supported by database");
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using Qooba.Framework.Abstractions;
namespace Qooba.Framework
{
public class JSON : ISerializer
{
public static IDictionary<Type, Tuple<object, bool>> objectParsers = new ConcurrentDictionary<Type, Tuple<object, bool>>();
public static IDictionary<Type, Func<object, string>> objectSerializers = new ConcurrentDictionary<Type, Func<object, string>>();
private static ExpressionHelper eh = new ExpressionHelper();
public static string SerializeObject(object o, bool camelCaseProprtiesNames = true)
{
var objectType = o.GetType();
Func<object, string> objectSerializer = null;
if (!objectSerializers.TryGetValue(objectType, out objectSerializer))
{
objectSerializer = objectSerializers[objectType] = PrepareObjectSerializer(objectType, camelCaseProprtiesNames);
}
return objectSerializer(o);
}
public static object DeserializeObject(Stream stream, Type objectType, bool caseInsensitive = true)
{
var o = eh.CreateInstance(objectType);
Tuple<object, bool> objectParser = null;
if (!objectParsers.TryGetValue(objectType, out objectParser))
{
if (o is IEnumerable)
{
var listProperty = PreparePropertyParser(objectType, caseInsensitive);
Func<Stream, object> a = st =>
{
return listProperty(st);
};
objectParser = objectParsers[objectType] = new Tuple<object, bool>(a, true);
}
else
{
objectParser = objectParsers[objectType] = new Tuple<object, bool>(PrepareObjectParser(objectType, caseInsensitive), false);
}
}
if (objectParser.Item2)
{
return ((Func<Stream, object>)objectParser.Item1)(stream);
}
else
{
(objectParser.Item1 as Action<object, Stream>)(o, stream);
return o;
}
}
private static Func<object, string> PrepareObjectSerializer(Type objectType, bool camelCaseProprtiesNames = true)
{
var ls = new List<Func<object, string>>();
var outputProperties = objectType.GetTypeInfo().GetProperties();
foreach (var p in outputProperties)
{
var name = p.Name;
ls.Add(PreparePropertySerializer(name, p.PropertyType, objectType, camelCaseProprtiesNames));
}
var propNum = ls.Count;
var diNum = ls.Count;
Func<object, string> action = (ob) =>
{
var sb = new StringBuilder();
sb.Append("{");
for (int i = 0; i < diNum; i++)
{
var sv = ls[i](ob);
if (sv != null)
{
sb.Append(sv);
if (i + 1 < diNum)
{
sb.Append(",");
}
}
}
sb.Append("}");
return sb.ToString();
};
return action;
}
private static Action<object, Stream> PrepareObjectParser(Type objectType, bool caseInsensitive = true)
{
IDictionary<string, Action<object, Stream>> dict = null;
if (caseInsensitive)
{
dict = new Dictionary<string, Action<object, Stream>>(StringComparer.OrdinalIgnoreCase);
}
else
{
dict = new Dictionary<string, Action<object, Stream>>();
}
var outputProperties = objectType.GetTypeInfo().GetProperties();
foreach (var p in outputProperties)
{
var name = p.Name;
dict[name] = PreparePropertyParser(name, p.PropertyType, objectType);
}
var propNum = dict.Count;
Action<object, Stream> action = (ob, st) =>
{
int i = 0;
while (i < propNum)
{
var propName = ParsePropertyName(st);
if (propName == null)
{
break;
}
if (dict.TryGetValue(propName, out Action<object, Stream> parser))
{
parser(ob, st);
i++;
}
else
{
var propVal = ParseSkipValue(st);
}
}
};
return action;
}
private static Func<object, string> PreparePropetyToStringGetter(Type objectType, Type propertyType, string propertyName)
{
var instance = Expression.Parameter(typeof(object), "instance");
var meth = propertyType.GetTypeInfo().GetMethod("ToString", new Type[] { });
var property = Expression.Call(Expression.Property(Expression.Convert(instance, objectType), propertyName), meth);
return Expression.Lambda<Func<object, string>>(property, instance).Compile();
}
private static Func<object, string> PreparePropertySerializer(string propertyName, Type propertyType, Type objectType, bool camelCaseProprtiesNames = true)
{
var propertyNameValue = camelCaseProprtiesNames ? string.Concat(propertyName[0].ToString().ToLower(), propertyName.Substring(1)) : propertyName;
Type nullableType = null;
Func<object, string> func = null;
if (propertyType == typeof(string) || propertyType.IsEnum)
{
var pGet = PreparePropetyToStringGetter(objectType, propertyType, propertyName);
func = o =>
{
var v = pGet(o);
if (v != null)
{
return string.Concat("\"", propertyNameValue, "\":\"", v, "\"");
}
return null;
};
}
else if (IsNumericType(propertyType))
{
var pGet = PreparePropetyToStringGetter(objectType, propertyType, propertyName);
func = o =>
{
var v = pGet(o);
if (v != null)
{
return string.Concat("\"", propertyNameValue, "\":", v);
}
return null;
};
}
else if (propertyType.GetTypeInfo().GetInterfaces().Contains(typeof(IEnumerable)))
{
var instance = Expression.Parameter(typeof(object), "instance");
var property = Expression.Convert(Expression.Property(Expression.Convert(instance, objectType), propertyName), typeof(object));
var pGet = Expression.Lambda<Func<object, object>>(property, instance).Compile();
Func<object, string> serializer;
//TODO:
var elementType = propertyType.GetElementType() ?? propertyType.GenericTypeArguments.FirstOrDefault();
if (elementType == typeof(string) || elementType.IsEnum)
{
serializer = o => string.Concat("\"", o.ToString(), "\"");
}
else if (IsNumericType(elementType))
{
serializer = o => o.ToString();
}
else if (elementType.IsClass)
{
serializer = PrepareObjectSerializer(elementType, camelCaseProprtiesNames);
}
else
{
serializer = o => string.Concat("\"", o.ToString(), "\"");
}
func = o =>
{
var v = pGet(o);
if (v != null)
{
var sb = new StringBuilder();
sb.Append(string.Concat("\"", propertyNameValue, "\":["));
var vl = v as IList;
var vlen = vl.Count;
var vlenm = vlen - 1;
for (var i = 0; i < vlen; i++)
{
sb.Append(serializer(vl[i]));
if (i < vlenm)
{
sb.Append(",");
}
}
sb.Append("]");
return sb.ToString();
}
return null;
};
}
else if ((nullableType = Nullable.GetUnderlyingType(propertyType)) != null)
{
var pGet = PreparePropetyToStringGetter(objectType, propertyType, propertyName);
func = o =>
{
var v = pGet(o);
if (v != null)
{
return string.Concat("\"", propertyNameValue, "\":", v);
}
return null;
};
}
else if (propertyType == typeof(object))
{
var instance = Expression.Parameter(typeof(object), "instance");
var property = Expression.Convert(Expression.Property(Expression.Convert(instance, objectType), propertyName), typeof(object));
var pGet = Expression.Lambda<Func<object, object>>(property, instance).Compile();
func = o =>
{
var v = pGet(o);
Func<object, string> serializer = null;
var pType = v.GetType();
if (!objectSerializers.TryGetValue(pType, out serializer))
{
serializer = objectSerializers[pType] = PrepareObjectSerializer(pType);
}
if (v != null)
{
return string.Concat("\"", propertyNameValue, "\":", serializer(v));
}
return null;
};
}
else if (propertyType.IsClass)
{
var serializer = PrepareObjectSerializer(propertyType);
var instance = Expression.Parameter(typeof(object), "instance");
var property = Expression.Convert(Expression.Property(Expression.Convert(instance, objectType), propertyName), typeof(object));
var pGet = Expression.Lambda<Func<object, object>>(property, instance).Compile();
func = o =>
{
var v = pGet(o);
if (v != null)
{
return string.Concat("\"", propertyNameValue, "\":", serializer(v));
}
return null;
};
}
else
{
var pGet = PreparePropetyToStringGetter(objectType, propertyType, propertyName);
func = o =>
{
var v = pGet(o);
if (v != null)
{
return string.Concat("\"", propertyNameValue, "\":\"", v, "\"");
}
return null;
};
}
return func;
}
public static Action<object, Stream> PreparePropertyParser(string propertyName, Type propertyType, Type objectType, bool caseInsensitive = true)
{
Type nullableType = null;
Action<object, Stream> act = null;
if (propertyType == typeof(object))
{
var setter = GetValueSetter(propertyName, objectType, propertyType);
act = (ob, st) =>
{
var val = ParseObjectValue(st);
if (val != "null") //Please don't user null string value :P
{
setter(ob, val.Trim());
}
};
}
else if (propertyType == typeof(string))
{
var setter = GetValueSetter(propertyName, objectType, propertyType);
act = (ob, st) =>
{
var val = ParsePropertyValue(st);
if (val != "null") //Please don't user null string value :P
{
setter(ob, val);
}
};
}
else if (propertyType.GetTypeInfo().GetInterfaces().Contains(typeof(IEnumerable)))
{
var elementType = propertyType.GetElementType() ?? propertyType.GenericTypeArguments.FirstOrDefault();
var parser = JSON.PreparePropertyParser(elementType, caseInsensitive);
Type pType = FindBestListType(propertyType, elementType);
var instance = Expression.Parameter(typeof(object), "instance");
var argument = Expression.Parameter(typeof(object), "argument");
var property = Expression.Property(Expression.Convert(instance, objectType), propertyName);
var assign = Expression.Assign(property, Expression.Convert(argument, propertyType));
var lam = Expression.Lambda<Action<object, object>>(assign, instance, argument).Compile();
act = (ob, st) =>
{
var list = (eh.CreateInstance(pType) as IList);
int chv;
char ch;
while (true)
{
chv = st.ReadByte();
ch = (char)chv;
if (ch == '[' || chv == -1)
{
break;
}
}
while (true)
{
var value = parser(st);
list.Add(value);
st.Position--; //remove this parser should retrun tuple with the last char value
chv = st.ReadByte();
ch = (char)chv;
if (ch == ']' || (char)st.ReadByte() == ']')
{
break;
}
if (ch == ',')
{
st.Position--;
}
}
lam(ob, list);
};
}
else if ((nullableType = Nullable.GetUnderlyingType(propertyType)) != null)
{
var setter = GetTryParseValueSetter(propertyName, objectType, nullableType);
act = (ob, st) =>
{
var val = ParsePropertyValue(st);
if (val != "null") //Please don't user null string value :P
{
setter(ob, val);
}
};
}
else if (propertyType.IsClass)
{
var setter = PrepareObjectParser(propertyType, caseInsensitive);
var instance = Expression.Parameter(typeof(object), "instance");
var argument = Expression.Parameter(typeof(object), "argument");
var property = Expression.Property(Expression.Convert(instance, objectType), propertyName);
var assign = Expression.Assign(property, Expression.Convert(argument, propertyType));
var lam = Expression.Lambda<Action<object, object>>(assign, instance, argument).Compile();
act = (ob, st) =>
{
var subOb = eh.CreateInstance(propertyType);
setter(subOb, st);
lam(ob, subOb);
};
}
else
{
var setter = GetTryParseValueSetter(propertyName, objectType, propertyType);
act = (ob, st) =>
{
var val = ParsePropertyValue(st);
if (val != "null") //Please don't user null string value :P
{
setter(ob, val);
}
};
}
return act;
}
public static Func<Stream, object> PreparePropertyParser(Type propertyType, bool caseInsensitive = true)
{
Type nullableType = null;
Func<Stream, object> func = null;
if (propertyType == typeof(object))
{
func = st =>
{
var val = ParseObjectValue(st);
if (val != "null") //Please don't user null string value :P
{
return val.Trim();
}
return null;
};
}
else if (propertyType == typeof(string))
{
func = st =>
{
var val = ParsePropertyValue(st);
if (val != "null") //Please don't user null string value :P
{
return val;
}
return null;
};
}
else if (propertyType.GetTypeInfo().GetInterfaces().Contains(typeof(IEnumerable)))
{
var elementType = propertyType.GetElementType() ?? propertyType.GenericTypeArguments.FirstOrDefault();
var setter = JSON.PreparePropertyParser(elementType, caseInsensitive);
Type pType = FindBestListType(propertyType, elementType);
func = st =>
{
var list = (eh.CreateInstance(pType) as IList);
int chv;
char ch;
while (true)
{
chv = st.ReadByte();
ch = (char)chv;
if (ch == '[' || chv == -1)
{
break;
}
}
while (true)
{
var value = setter(st);
list.Add(value);
st.Position--;
chv = st.ReadByte();
ch = (char)chv;
if (ch == ']' || (char)st.ReadByte() == ']')
{
break;
}
if (ch == ',')
{
st.Position--;
}
}
return list;
};
}
else if ((nullableType = Nullable.GetUnderlyingType(propertyType)) != null)
{
func = st =>
{
var val = ParsePropertyValue(st);
if (val != "null") //Please don't user null string value :P
{
return val;
}
return null;
};
}
else if (propertyType.IsClass)
{
var setter = PrepareObjectParser(propertyType, caseInsensitive);
func = st =>
{
var subOb = eh.CreateInstance(propertyType);
setter(subOb, st);
return subOb;
};
}
else
{
var setter = GetTryParseValueSetter(propertyType);
func = st =>
{
var val = ParsePropertyValue(st);
if (val != "null") //Please don't user null string value :P
{
return setter(val);
}
return null;
};
}
return func;
}
private static bool IsNumericType(Type type)
{
var code = Type.GetTypeCode(type);
return code == TypeCode.Int32 ||
code == TypeCode.Double ||
code == TypeCode.Byte ||
code == TypeCode.Int64 ||
code == TypeCode.Decimal ||
code == TypeCode.SByte ||
code == TypeCode.UInt16 ||
code == TypeCode.UInt32 ||
code == TypeCode.UInt64 ||
code == TypeCode.Int16 ||
code == TypeCode.Single;
}
private static Type FindBestListType(Type propertyType, Type elementType)
{
return typeof(List<>).MakeGenericType(elementType);
}
public static Action<object, object> GetValueSetter(string propertyName, Type objectType, Type propertyType)
{
var instance = Expression.Parameter(typeof(object), "instance");
var argument = Expression.Parameter(typeof(object), "argument");
var property = Expression.Property(Expression.Convert(instance, objectType), propertyName);
var assign = Expression.Assign(property, Expression.Convert(argument, propertyType));
return Expression.Lambda<Action<object, object>>(assign, instance, argument).Compile();
}
public static Action<object, object> GetTryParseValueSetter(string propertyName, Type objectType, Type propertyType)
{
var stringType = typeof(string);
var instance = Expression.Parameter(typeof(object), "instance");
var argument = Expression.Parameter(typeof(object), "argument");
var property = Expression.Property(Expression.Convert(instance, objectType), propertyName);
var localVariables = new List<ParameterExpression>();
var assignExpressions = new List<Expression>();
var parsed = Expression.Parameter(propertyType, string.Concat(propertyName, "Parsed"));
localVariables.Add(parsed);
MethodInfo meth;
if (propertyType.IsEnum)
{
meth = propertyType.GetTypeInfo().GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy).FirstOrDefault(x => x.Name == "TryParse" && x.GetParameters().Length == 2).MakeGenericMethod(propertyType);
}
else
{
meth = propertyType.GetTypeInfo().GetMethod("TryParse", new[] { stringType, propertyType.MakeByRefType() });
}
if (meth != null)
{
var parsingExpression = Expression.Call(null, meth, Expression.Convert(argument, stringType), parsed);
assignExpressions.Add(parsingExpression);
if (property.Type == propertyType)
{
assignExpressions.Add(Expression.Assign(property, parsed));
}
else
{
assignExpressions.Add(Expression.Assign(property, Expression.Convert(parsed, property.Type)));
}
}
assignExpressions.Add(Expression.Empty());
var block = Expression.Block(localVariables, assignExpressions);
return Expression.Lambda<Action<object, object>>(block, instance, argument).Compile();
}
public static Func<object, object> GetTryParseValueSetter(Type propertyType)
{
var stringType = typeof(string);
var argument = Expression.Parameter(typeof(object), "argument");
var localVariables = new List<ParameterExpression>();
var assignExpressions = new List<Expression>();
var parsed = Expression.Parameter(propertyType, "Parsed");
localVariables.Add(parsed);
MethodInfo meth;
if (propertyType.IsEnum)
{
meth = propertyType.GetTypeInfo().GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy).FirstOrDefault(x => x.Name == "TryParse" && x.GetParameters().Length == 2).MakeGenericMethod(propertyType);
}
else
{
meth = propertyType.GetTypeInfo().GetMethod("TryParse", new[] { stringType, propertyType.MakeByRefType() });
}
if (meth != null)
{
var parsingExpression = Expression.Call(null, meth, Expression.Convert(argument, stringType), parsed);
assignExpressions.Add(parsingExpression);
assignExpressions.Add(Expression.Convert(parsed, typeof(object)));
}
var block = Expression.Block(localVariables, assignExpressions);
return Expression.Lambda<Func<object, object>>(block, argument).Compile();
}
public static Expression CheckIsNull(Expression input, Type inputType, Expression expression)
{
if (Nullable.GetUnderlyingType(inputType) != null || inputType == typeof(string))
{
return Expression.IfThen(Expression.NotEqual(input, Expression.Constant(null, inputType)), expression);
}
return expression;
}
public static string ParsePropertyName(Stream stream)
{
var sb = new StringBuilder();
char ch;
int chv;
do
{
chv = stream.ReadByte();
ch = (char)chv;
if (chv == -1)
{
return null;
}
}
while (ch != '"');
while (true)
{
chv = stream.ReadByte();
ch = (char)chv;
if (chv == -1)
{
return null;
}
if (ch == '"')
{
break;
}
sb.Append(ch);
}
do
{
chv = stream.ReadByte();
ch = (char)chv;
if (chv == -1)
{
return null;
}
}
while (ch != ':');
return sb.ToString();
}
public static string ParseObjectValue(Stream stream)
{
var sb = new StringBuilder();
char ch;
int chv;
int nq = 0;
int ncb = 0;
int nsb = 0;
while (true)
{
chv = stream.ReadByte();
ch = (char)chv;
if (ch == '"')
{
nq = nq == 0 ? 1 : 0;
}
if (ch == '{')
{
ncb++;
}
if (ch == '}')
{
ncb--;
}
if (ch == '[')
{
nsb++;
}
if (ch == ']')
{
nsb--;
}
if ((ch == ',' && nq == 0 && ncb == 0 && nsb == 0) || ncb == -1)
{
return sb.ToString();
}
sb.Append(ch);
}
}
public static string ParseSkipValue(Stream stream)
{
char ch;
int chv;
int nq = 0;
int ncb = 0;
int nsb = 0;
while (true)
{
chv = stream.ReadByte();
ch = (char)chv;
if (ch == '"')
{
nq = nq == 0 ? 1 : 0;
}
if (ch == '{')
{
ncb++;
}
if (ch == '}')
{
ncb--;
}
if (ch == '[')
{
nsb++;
}
if (ch == ']')
{
nsb--;
}
if ((ch == ',' && nq == 0 && ncb == 0 && nsb == 0) || ncb == -1)
{
return null;
}
}
}
public static string ParsePropertyValue(Stream stream)
{
var sb = new StringBuilder();
char ch;
int chv;
while (true)
{
chv = stream.ReadByte();
ch = (char)chv;
if (chv == -1)
{
return null;
}
if (ch == '"' || ch != ' ')
{
break;
}
}
if (ch != '"')
{
sb.Append(ch);
}
while (true)
{
chv = stream.ReadByte();
ch = (char)chv;
if (chv == -1)
{
return null;
}
if (ch == '"')
{
break;
}
if (ch == ',' || ch == '}' || ch == ']')
{
return sb.ToString();
}
sb.Append(ch);
}
while (true)
{
if (ch == ',' || ch == '}' || ch == ']')
{
return sb.ToString();
}
chv = stream.ReadByte();
ch = (char)chv;
if (chv == -1)
{
return null;
}
}
}
public string Serialize<T>(T input) => JSON.SerializeObject(input);
public string Serialize(object input) => JSON.SerializeObject(input);
public T Deserialize<T>(string input) => (T)this.Deserialize(input, typeof(T));
public object Deserialize(string input, Type type)
{
using (Stream s = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(input)))
{
return JSON.DeserializeObject(s, type);
}
}
}
}
| |
/* ====================================================================
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 System;
using NUnit.Framework;
using NPOI.OpenXml4Net.OPC.Internal;
using NPOI.OpenXml4Net.Exceptions;
using System.IO;
using NPOI.OpenXml4Net.OPC;
using TestCases.OpenXml4Net;
using NPOI.XWPF.UserModel;
namespace TestCase.OPC
{
/**
* Tests for content type (ContentType class).
*
* @author Julien Chable
*/
[TestFixture]
public class TestContentType
{
/**
* Check rule M1.13: Package implementers shall only create and only
* recognize parts with a content type; format designers shall specify a
* content type for each part included in the format. Content types for
* namespace parts shall fit the defInition and syntax for media types as
* specified in RFC 2616, \u00A73.7.
*/
[Test]
public void TestContentTypeValidation()
{
String[] contentTypesToTest = new String[] { "text/xml",
"application/pgp-key", "application/vnd.hp-PCLXL",
"application/vnd.lotus-1-2-3" };
for (int i = 0; i < contentTypesToTest.Length; ++i)
{
new ContentType(contentTypesToTest[i]);
}
}
/**
* Check rule M1.13 : Package implementers shall only create and only
* recognize parts with a content type; format designers shall specify a
* content type for each part included in the format. Content types for
* namespace parts shall fit the defInition and syntax for media types as
* specified in RFC 2616, \u00A3.7.
*
* Check rule M1.14: Content types shall not use linear white space either
* between the type and subtype or between an attribute and its value.
* Content types also shall not have leading or trailing white spaces.
* Package implementers shall create only such content types and shall
* require such content types when retrieving a part from a namespace; format
* designers shall specify only such content types for inclusion in the
* format.
*/
[Test]
public void TestContentTypeValidationFailure()
{
String[] contentTypesToTest = new String[] { "text/xml/app", "",
"test", "text(xml/xml", "text)xml/xml", "text<xml/xml",
"text>/xml", "text@/xml", "text,/xml", "text;/xml",
"text:/xml", "text\\/xml", "t/ext/xml", "t\"ext/xml",
"text[/xml", "text]/xml", "text?/xml", "tex=t/xml",
"te{xt/xml", "tex}t/xml", "te xt/xml",
"text" + (char) 9 + "/xml", "text xml", " text/xml " };
for (int i = 0; i < contentTypesToTest.Length; ++i)
{
try
{
new ContentType(contentTypesToTest[i]);
}
catch (InvalidFormatException e)
{
continue;
}
Assert.Fail("Must have fail for content type: '" + contentTypesToTest[i]
+ "' !");
}
}
/**
* Parameters are allowed, provides that they meet the
* criteria of rule [01.2]
* Invalid parameters are verified as incorrect in
* {@link #testContentTypeParameterFailure()}
*/
[Test]
public void TestContentTypeParam()
{
String[] contentTypesToTest = new String[] { "mail/toto;titi=tata",
"text/xml;a=b;c=d", "text/xml;key1=param1;key2=param2",
"application/pgp-key;version=\"2\"",
"application/x-resqml+xml;version=2.0;type=obj_global2dCrs"
};
foreach (String contentType in contentTypesToTest)
{
new ContentType(contentType);
}
}
/**
* Check rule [O1.2]: Format designers might restrict the usage of
* parameters for content types.
*/
[Test]
public void TestContentTypeParameterFailure()
{
String[] contentTypesToTest = new String[] {
"mail/toto;\"titi=tata\"", // quotes not allowed like that
"mail/toto;titi = tata", // spaces not allowed
"text/\u0080" // characters above ASCII are not allowed
};
for (int i = 0; i < contentTypesToTest.Length; ++i)
{
try
{
new ContentType(contentTypesToTest[i]);
}
catch (InvalidFormatException e)
{
continue;
}
Assert.Fail("Must have fail for content type: '" + contentTypesToTest[i]
+ "' !");
}
}
/**
* Check rule M1.15: The namespace implementer shall require a content type
* that does not include comments and the format designer shall specify such
* a content type.
*/
[Test]
public void TestContentTypeCommentFailure()
{
String[] contentTypesToTest = new String[] { "text/xml(comment)" };
for (int i = 0; i < contentTypesToTest.Length; ++i)
{
try
{
new ContentType(contentTypesToTest[i]);
}
catch (InvalidFormatException e)
{
continue;
}
Assert.Fail("Must have fail for content type: '" + contentTypesToTest[i]
+ "' !");
}
}
/**
* OOXML content types don't need entities, but we shouldn't
* barf if we Get one from a third party system that Added them
*/
[Ignore("")]
public void TestFileWithContentTypeEntities()
{
Stream is1 = OpenXml4NetTestDataSamples.OpenSampleStream("ContentTypeHasEntities.ooxml");
OPCPackage p = OPCPackage.Open(is1);
// Check we found the contents of it
bool foundCoreProps = false, foundDocument = false, foundTheme1 = false;
foreach (PackagePart part in p.GetParts())
{
if (part.PartName.ToString().Equals("/docProps/core.xml"))
{
Assert.AreEqual(ContentTypes.CORE_PROPERTIES_PART, part.ContentType);
foundCoreProps = true;
}
if (part.PartName.ToString().Equals("/word/document.xml"))
{
Assert.AreEqual(XWPFRelation.DOCUMENT.ContentType, part.ContentType);
foundDocument = true;
}
if (part.PartName.ToString().Equals("/word/theme/theme1.xml"))
{
Assert.AreEqual(XWPFRelation.THEME.ContentType, part.ContentType);
foundTheme1 = true;
}
}
Assert.IsTrue(foundCoreProps, "Core not found in " + p.GetParts());
Assert.IsTrue(foundDocument, "Document not found in " + p.GetParts());
Assert.IsTrue(foundTheme1, "Theme1 not found in " + p.GetParts());
}
/**
* Check that we can open a file where there are valid
* parameters on a content type
*/
[Test]
public void TestFileWithContentTypeParams()
{
Stream is1 = OpenXml4NetTestDataSamples.OpenSampleStream("ContentTypeHasParameters.ooxml");
OPCPackage p = OPCPackage.Open(is1);
String typeResqml = "application/x-resqml+xml";
// Check the types on everything
foreach (PackagePart part in p.GetParts())
{
// _rels type doesn't have any params
if (part.IsRelationshipPart)
{
Assert.AreEqual(ContentTypes.RELATIONSHIPS_PART, part.ContentType);
Assert.AreEqual(ContentTypes.RELATIONSHIPS_PART, part.ContentTypeDetails.ToString());
Assert.AreEqual(false, part.ContentTypeDetails.HasParameters());
Assert.AreEqual(0, part.ContentTypeDetails.GetParameterKeys().Length);
}
// Core type doesn't have any params
else if (part.PartName.ToString().Equals("/docProps/core.xml"))
{
Assert.AreEqual(ContentTypes.CORE_PROPERTIES_PART, part.ContentType);
Assert.AreEqual(ContentTypes.CORE_PROPERTIES_PART, part.ContentTypeDetails.ToString());
Assert.AreEqual(false, part.ContentTypeDetails.HasParameters());
Assert.AreEqual(0, part.ContentTypeDetails.GetParameterKeys().Length);
}
// Global Crs types do have params
else if (part.PartName.ToString().Equals("/global1dCrs.xml"))
{
Assert.AreEqual(typeResqml, part.ContentType.Substring(0, typeResqml.Length));
Assert.AreEqual(typeResqml, part.ContentTypeDetails.ToString(false));
Assert.AreEqual(true, part.ContentTypeDetails.HasParameters());
Assert.AreEqual(typeResqml + ";version=2.0;type=obj_global1dCrs", part.ContentTypeDetails.ToString());
Assert.AreEqual(2, part.ContentTypeDetails.GetParameterKeys().Length);
Assert.AreEqual("2.0", part.ContentTypeDetails.GetParameter("version"));
Assert.AreEqual("obj_global1dCrs", part.ContentTypeDetails.GetParameter("type"));
}
else if (part.PartName.ToString().Equals("/global2dCrs.xml"))
{
Assert.AreEqual(typeResqml, part.ContentType.Substring(0, typeResqml.Length));
Assert.AreEqual(typeResqml, part.ContentTypeDetails.ToString(false));
Assert.AreEqual(true, part.ContentTypeDetails.HasParameters());
Assert.AreEqual(typeResqml + ";version=2.0;type=obj_global2dCrs", part.ContentTypeDetails.ToString());
Assert.AreEqual(2, part.ContentTypeDetails.GetParameterKeys().Length);
Assert.AreEqual("2.0", part.ContentTypeDetails.GetParameter("version"));
Assert.AreEqual("obj_global2dCrs", part.ContentTypeDetails.GetParameter("type"));
}
// Other thingy
else if (part.PartName.ToString().Equals("/myTestingGuid.xml"))
{
Assert.AreEqual(typeResqml, part.ContentType.Substring(0, typeResqml.Length));
Assert.AreEqual(typeResqml, part.ContentTypeDetails.ToString(false));
Assert.AreEqual(true, part.ContentTypeDetails.HasParameters());
Assert.AreEqual(typeResqml + ";version=2.0;type=obj_tectonicBoundaryFeature", part.ContentTypeDetails.ToString());
Assert.AreEqual(2, part.ContentTypeDetails.GetParameterKeys().Length);
Assert.AreEqual("2.0", part.ContentTypeDetails.GetParameter("version"));
Assert.AreEqual("obj_tectonicBoundaryFeature", part.ContentTypeDetails.GetParameter("type"));
}
// That should be it!
else
{
Assert.Fail("Unexpected part " + part);
}
}
}
}
}
| |
using Rhino;
using Rhino.Geometry;
using Rhino.DocObjects;
using Rhino.Collections;
using GH_IO;
using GH_IO.Serialization;
using Grasshopper;
using Grasshopper.Kernel;
using Grasshopper.Kernel.Data;
using Grasshopper.Kernel.Types;
using System;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Linq;
using System.Data;
using System.Drawing;
using System.Reflection;
using System.Collections;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Runtime.InteropServices;
/// <summary>
/// This class will be instantiated on demand by the Script component.
/// </summary>
public class Script_Instance : GH_ScriptInstance
{
#region Utility functions
/// <summary>Print a String to the [Out] Parameter of the Script component.</summary>
/// <param name="text">String to print.</param>
private void Print(string text) { __out.Add(text); }
/// <summary>Print a formatted String to the [Out] Parameter of the Script component.</summary>
/// <param name="format">String format.</param>
/// <param name="args">Formatting parameters.</param>
private void Print(string format, params object[] args) { __out.Add(string.Format(format, args)); }
/// <summary>Print useful information about an object instance to the [Out] Parameter of the Script component. </summary>
/// <param name="obj">Object instance to parse.</param>
private void Reflect(object obj) { __out.Add(GH_ScriptComponentUtilities.ReflectType_CS(obj)); }
/// <summary>Print the signatures of all the overloads of a specific method to the [Out] Parameter of the Script component. </summary>
/// <param name="obj">Object instance to parse.</param>
private void Reflect(object obj, string method_name) { __out.Add(GH_ScriptComponentUtilities.ReflectType_CS(obj, method_name)); }
#endregion
#region Members
/// <summary>Gets the current Rhino document.</summary>
private RhinoDoc RhinoDocument;
/// <summary>Gets the Grasshopper document that owns this script.</summary>
private GH_Document GrasshopperDocument;
/// <summary>Gets the Grasshopper script component that owns this script.</summary>
private IGH_Component Component;
/// <summary>
/// Gets the current iteration count. The first call to RunScript() is associated with Iteration==0.
/// Any subsequent call within the same solution will increment the Iteration count.
/// </summary>
private int Iteration;
#endregion
/// <summary>
/// This procedure contains the user code. Input parameters are provided as regular arguments,
/// Output parameters as ref arguments. You don't have to assign output parameters,
/// they will have a default value.
/// </summary>
private void RunScript(System.Object range, int n, double power, int seed, ref object result)
{
Interval _range = new Interval(0.01, 1);
//bool hasRange = false;
if (range != null) {
try {
_range = (Interval) range;
}
catch {
try {
_range = new Interval(0.01 * (double) range, (double) range);
Print("range: {0} to {1}", 0.01 * (double) range, range);
}
catch {
throw new Exception ("Wrong Input range format: range must be an Interval or a Number");
}
}
//hasRange = true;
}
if (_range.Min <= 0 || _range.Max <= 0) {
throw new Exception ("Wrong Input range: range must be larger than zero");
}
init_genrand((uint) seed);
var _result = new List<double>();
for (int i = 0; i < n; i++) {
_result.Add(uniformToPower(genrand_res53(), _range.Min, _range.Max, power));
}
result = _result;
}
// <Custom additional code>
double uniformToPower(double y, double min, double max, double power) {
power += 1;
if (power == 0) {
return Math.Exp((Math.Log(max) - Math.Log(min))* y + Math.Log(min));
}
else {
return (Math.Pow(((Math.Pow(max, power) - Math.Pow(min, power)) * y + Math.Pow(min, power)), 1 / power));
}
}
/* ---- MODIFIED ORIGINAL CODE ---- */
/*
A C-program for MT19937, with initialization improved 2002/1/26.
Coded by Takuji Nishimura and Makoto Matsumoto.
Before using, initialize the state by using init_genrand(seed)
or init_by_array(init_key, key_length).
Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
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 names of its contributors may not 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.
Any feedback is very welcome.
http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
*/
/* Period parameters */
const uint N = 624;
const uint M = 397;
const ulong MATRIX_A = 0x9908b0dfUL; /* constant vector a */
const ulong UPPER_MASK = 0x80000000UL; /* most significant w-r bits */
const ulong LOWER_MASK = 0x7fffffffUL; /* least significant r bits */
ulong[] mt = new ulong[N]; /* the array for the state vector */
uint mti = N + 1; /* mti==N+1 means mt[N] is not initialized */
/* initializes mt[N] with a seed */
void init_genrand(ulong s)
{
mt[0] = s & 0xffffffffUL;
for (mti = 1; mti < N; mti++) {
mt[mti] =
(1812433253UL * (mt[mti - 1] ^ (mt[mti - 1] >> 30)) + mti);
/* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
/* In the previous versions, MSBs of the seed affect */
/* only MSBs of the array mt[]. */
/* 2002/01/09 modified by Makoto Matsumoto */
mt[mti] &= 0xffffffffUL;
/* for >32 bit machines */
}
}
/* initialize by an array with array-length */
/* init_key is the array for initializing keys */
/* key_length is its length */
/* slight change for C++, 2004/2/26 */
void init_by_array(ulong[] init_key, uint key_length)
{
uint i, j, k;
init_genrand(19650218UL);
i = 1; j = 0;
k = (N > key_length ? N : key_length);
for (; k > 0; k--) {
mt[i] = (mt[i] ^ ((mt[i - 1] ^ (mt[i - 1] >> 30)) * 1664525UL))
+ init_key[j] + j; /* non linear */
mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
i++; j++;
if (i >= N) { mt[0] = mt[N - 1]; i = 1; }
if (j >= key_length) j = 0;
}
for (k = N - 1; k > 0; k--) {
mt[i] = (mt[i] ^ ((mt[i - 1] ^ (mt[i - 1] >> 30)) * 1566083941UL))
- i; /* non linear */
mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
i++;
if (i >= N) { mt[0] = mt[N - 1]; i = 1; }
}
mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */
}
/* generates a random number on [0,0xffffffff]-interval */
ulong genrand_int32()
{
ulong y;
ulong[] mag01 = {0x0UL, MATRIX_A};
/* mag01[x] = x * MATRIX_A for x=0,1 */
if (mti >= N) { /* generate N words at one time */
int kk;
if (mti == N+1) /* if init_genrand() has not been called, */
init_genrand(5489UL); /* a default initial seed is used */
for (kk=0;kk<N-M;kk++) {
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL];
}
for (;kk<N-1;kk++) {
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[unchecked((int)(kk+(M-N)))] ^ (y >> 1) ^ mag01[y & 0x1UL];
}
y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL];
mti = 0;
}
y = mt[mti++];
/* Tempering */
y ^= (y >> 11);
y ^= (y << 7) & 0x9d2c5680UL;
y ^= (y << 15) & 0xefc60000UL;
y ^= (y >> 18);
return y;
}
/* generates a random number on [0,0x7fffffff]-interval */
long genrand_int31()
{
return (long) (genrand_int32() >> 1);
}
/* generates a random number on [0,1]-real-interval */
double genrand_real1()
{
return genrand_int32() * (1.0 / 4294967295.0);
/* divided by 2^32-1 */
}
/* generates a random number on [0,1)-real-interval */
double genrand_real2()
{
return genrand_int32() * (1.0 / 4294967296.0);
/* divided by 2^32 */
}
/* generates a random number on (0,1)-real-interval */
double genrand_real3()
{
return (((double) genrand_int32()) + 0.5) * (1.0 / 4294967296.0);
/* divided by 2^32 */
}
/* generates a random number on [0,1) with 53-bit resolution*/
double genrand_res53()
{
ulong a=genrand_int32() >> 5, b = genrand_int32() >> 6;
return(a * 67108864.0 + b) * (1.0 / 9007199254740992.0);
}
/* These real versions are due to Isaku Wada, 2002/01/09 added */
// </Custom additional code>
private List<string> __err = new List<string>(); //Do not modify this list directly.
private List<string> __out = new List<string>(); //Do not modify this list directly.
private RhinoDoc doc = RhinoDoc.ActiveDoc; //Legacy field.
private IGH_ActiveObject owner; //Legacy field.
private int runCount; //Legacy field.
public override void InvokeRunScript(IGH_Component owner, object rhinoDocument, int iteration, List<object> inputs, IGH_DataAccess DA)
{
//Prepare for a new run...
//1. Reset lists
this.__out.Clear();
this.__err.Clear();
this.Component = owner;
this.Iteration = iteration;
this.GrasshopperDocument = owner.OnPingDocument();
this.RhinoDocument = rhinoDocument as Rhino.RhinoDoc;
this.owner = this.Component;
this.runCount = this.Iteration;
this. doc = this.RhinoDocument;
//2. Assign input parameters
System.Object range = default(System.Object);
if (inputs[0] != null)
{
range = (System.Object)(inputs[0]);
}
int n = default(int);
if (inputs[1] != null)
{
n = (int)(inputs[1]);
}
double power = default(double);
if (inputs[2] != null)
{
power = (double)(inputs[2]);
}
int seed = default(int);
if (inputs[3] != null)
{
seed = (int)(inputs[3]);
}
//3. Declare output parameters
object result = null;
//4. Invoke RunScript
RunScript(range, n, power, seed, ref result);
try
{
//5. Assign output parameters to component...
if (result != null)
{
if (GH_Format.TreatAsCollection(result))
{
IEnumerable __enum_result = (IEnumerable)(result);
DA.SetDataList(1, __enum_result);
}
else
{
if (result is Grasshopper.Kernel.Data.IGH_DataTree)
{
//merge tree
DA.SetDataTree(1, (Grasshopper.Kernel.Data.IGH_DataTree)(result));
}
else
{
//assign direct
DA.SetData(1, result);
}
}
}
else
{
DA.SetData(1, null);
}
}
catch (Exception ex)
{
this.__err.Add(string.Format("Script exception: {0}", ex.Message));
}
finally
{
//Add errors and messages...
if (owner.Params.Output.Count > 0)
{
if (owner.Params.Output[0] is Grasshopper.Kernel.Parameters.Param_String)
{
List<string> __errors_plus_messages = new List<string>();
if (this.__err != null) { __errors_plus_messages.AddRange(this.__err); }
if (this.__out != null) { __errors_plus_messages.AddRange(this.__out); }
if (__errors_plus_messages.Count > 0)
DA.SetDataList(0, __errors_plus_messages);
}
}
}
}
}
| |
using Nop.Core;
using Nop.Core.Domain.Directory;
using Nop.Core.Domain.Orders;
using Nop.Core.Domain.Payments;
using Nop.Core.Plugins;
using Nop.Plugin.Payments.GTPay.Controllers;
using Nop.Services.Common;
using Nop.Services.Configuration;
using Nop.Services.Customers;
using Nop.Services.Directory;
using Nop.Services.Localization;
using Nop.Services.Orders;
using Nop.Services.Payments;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;
namespace Nop.Plugin.Payments.GTPay
{
/// <summary>
/// GTPay payment processor
/// </summary>
public class GTPayPaymentProcessor : BasePlugin, IPaymentMethod
{
#region Fields
private readonly GTPayPaymentSettings _gtPayPaymentSettings;
private readonly ISettingService _settingService;
private readonly IGenericAttributeService _genericAttributeService;
private readonly ICurrencyService _currencyService;
private readonly ICustomerService _customerService;
private readonly CurrencySettings _currencySettings;
private readonly IWebHelper _webHelper;
private readonly IOrderTotalCalculationService _orderTotalCalculationService;
private readonly IStoreContext _storeContext;
private readonly ILocalizationService _localizationService;
#endregion
#region Ctor
public GTPayPaymentProcessor(GTPayPaymentSettings gtPayPaymentSettings,
ISettingService settingService,
IGenericAttributeService genericAttributeService,
ICurrencyService currencyService, ICustomerService customerService,
CurrencySettings currencySettings, IWebHelper webHelper,
IOrderTotalCalculationService orderTotalCalculationService,
IStoreContext storeContext,
ILocalizationService localizationService)
{
this._gtPayPaymentSettings = gtPayPaymentSettings;
this._settingService = settingService;
this._genericAttributeService = genericAttributeService;
this._currencyService = currencyService;
this._customerService = customerService;
this._currencySettings = currencySettings;
this._webHelper = webHelper;
this._orderTotalCalculationService = orderTotalCalculationService;
this._storeContext = storeContext;
this._localizationService = localizationService;
}
#endregion
#region Utilities
#endregion
#region Methods
/// <summary>
/// Process a payment
/// </summary>
/// <param name="processPaymentRequest">Payment info required for an order processing</param>
/// <returns>Process payment result</returns>
public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
{
var result = new ProcessPaymentResult();
result.NewPaymentStatus = PaymentStatus.Pending;
return result;
}
/// <summary>
/// Post process payment (used by payment gateways that require redirecting to a third-party URL)
/// </summary>
/// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
{
int orderId = postProcessPaymentRequest.Order.Id;
string url = $"~/Plugins/PaymentGTPay/SubmitPaymentInfo?orderId={orderId}";
HttpContext.Current.Response.Redirect(url);
}
/// <summary>
/// Returns a value indicating whether payment method should be hidden during checkout
/// </summary>
/// <param name="cart">Shoping cart</param>
/// <returns>true - hide; false - display.</returns>
public bool HidePaymentMethod(IList<ShoppingCartItem> cart)
{
//load settings for a chosen store scope
var storeScope = _storeContext.CurrentStore.Id;
var currencySettings = _settingService.LoadSetting<CurrencySettings>(storeScope);
var supportedCurrencyCodes = GTPayHelper.GetSupportedCurrencyCodes();
var primaryStoreCurrency = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId);
if (primaryStoreCurrency == null || !supportedCurrencyCodes.Contains(primaryStoreCurrency.CurrencyCode))
return true;
return false;
}
/// <summary>
/// Gets additional handling fee
/// </summary>
/// <param name="cart">Shoping cart</param>
/// <returns>Additional handling fee</returns>
public decimal GetAdditionalHandlingFee(IList<ShoppingCartItem> cart)
{
return 0;
}
/// <summary>
/// Captures payment
/// </summary>
/// <param name="capturePaymentRequest">Capture payment request</param>
/// <returns>Capture payment result</returns>
public CapturePaymentResult Capture(CapturePaymentRequest capturePaymentRequest)
{
var result = new CapturePaymentResult();
result.AddError("Capture method not supported.");
return result;
}
/// <summary>
/// Refunds a payment
/// </summary>
/// <param name="refundPaymentRequest">Request</param>
/// <returns>Result</returns>
public RefundPaymentResult Refund(RefundPaymentRequest refundPaymentRequest)
{
var result = new RefundPaymentResult();
result.AddError("Refund method not supported.");
return result;
}
/// <summary>
/// Voids a payment
/// </summary>
/// <param name="voidPaymentRequest">Request</param>
/// <returns>Result</returns>
public VoidPaymentResult Void(VoidPaymentRequest voidPaymentRequest)
{
var result = new VoidPaymentResult();
result.AddError("Void method not supported.");
return result;
}
/// <summary>
/// Process recurring payment
/// </summary>
/// <param name="processPaymentRequest">Payment info required for an order processing</param>
/// <returns>Process payment result</returns>
public ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest)
{
var result = new ProcessPaymentResult();
result.AddError("Recurring payment not supported.");
return result;
}
/// <summary>
/// Cancels a recurring payment
/// </summary>
/// <param name="cancelPaymentRequest">Request</param>
/// <returns>Result</returns>
public CancelRecurringPaymentResult CancelRecurringPayment(CancelRecurringPaymentRequest cancelPaymentRequest)
{
var result = new CancelRecurringPaymentResult();
result.AddError("Recurring payment not supported.");
return result;
}
/// <summary>
/// Gets a value indicating whether customers can complete a payment after order is placed but not completed (for redirection payment methods)
/// </summary>
/// <param name="order">Order</param>
/// <returns>Result</returns>
public bool CanRePostProcessPayment(Order order)
{
if (order == null)
throw new ArgumentNullException("order");
//it's a redirection payment method. So we always return true
return true;
}
/// <summary>
/// Gets a route for provider configuration
/// </summary>
/// <param name="actionName">Action name</param>
/// <param name="controllerName">Controller name</param>
/// <param name="routeValues">Route values</param>
public void GetConfigurationRoute(out string actionName, out string controllerName, out RouteValueDictionary routeValues)
{
actionName = "Configure";
controllerName = "PaymentGTPay";
routeValues = new RouteValueDictionary { { "Namespaces", "Nop.Plugin.Payments.GTPay.Controllers" }, { "area", null } };
}
/// <summary>
/// Gets a route for payment info
/// </summary>
/// <param name="actionName">Action name</param>
/// <param name="controllerName">Controller name</param>
/// <param name="routeValues">Route values</param>
public void GetPaymentInfoRoute(out string actionName, out string controllerName, out RouteValueDictionary routeValues)
{
actionName = "PaymentInfo";
controllerName = "PaymentGTPay";
routeValues = new RouteValueDictionary { { "Namespaces", "Nop.Plugin.Payments.GTPay.Controllers" }, { "area", null } };
}
public Type GetControllerType()
{
return typeof(PaymentGTPayController);
}
public override void Install()
{
//settings
var settings = new GTPayPaymentSettings
{
UseSandbox = true,
DescriptionText = "<p><b>GTPAY accepts both locally and internationally issued cards including Interswitch, MasterCard and VISA.</b><br /></p>",
ShowCustomerName = true
};
_settingService.SaveSetting(settings);
//locales
this.AddOrUpdatePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_DescriptionText, "Description");
this.AddOrUpdatePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_DescriptionText_Hint, "Enter info that will be shown to customers during checkout");
this.AddOrUpdatePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_DescriptionText_Required, "Description is required.");
this.AddOrUpdatePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_SkipPaymentInfo, "Skip payment info");
this.AddOrUpdatePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_SkipPaymentInfo_Hint, "Gets a value indicating whether we should display a payment information page for this plugin.");
this.AddOrUpdatePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_UseSandbox, "Use sandbox");
this.AddOrUpdatePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_UseSandbox_Hint, "Check to enable Sandbox (testing environment).");
this.AddOrUpdatePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_MerchantId, "Merchant identifier");
this.AddOrUpdatePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_MerchantId_Hint, "Specify merchant identifier.");
this.AddOrUpdatePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_MerchantId_Required, "Merchant identifier is required.");
this.AddOrUpdatePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_MerchantHashKey, "Merchant hash key");
this.AddOrUpdatePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_MerchantHashKey_Hint, "Specify merchant hash key provided by GTPay on merchant setup.");
this.AddOrUpdatePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_MerchantHashKey_Required, "Merchant hash key is required.");
this.AddOrUpdatePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_ShowGTPayPage, "Show GTPay page");
this.AddOrUpdatePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_ShowGTPayPage_Hint, "Check to show GTPay's own first page, from where the customer will click Continue to go to the gateway.");
this.AddOrUpdatePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_PreferredGateway, "Preferred gateway");
this.AddOrUpdatePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_PreferredGateway_Hint, "If specified, then customer cannot choose what gateway to use for the transaction.");
this.AddOrUpdatePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_ShowCustomerName, "Show customer name");
this.AddOrUpdatePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_ShowCustomerName_Hint, "Check to display customer name on the payment page for the customer.");
base.Install();
}
public override void Uninstall()
{
//settings
_settingService.DeleteSetting<GTPayPaymentSettings>();
//locales
this.DeletePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_DescriptionText);
this.DeletePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_DescriptionText_Hint);
this.DeletePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_DescriptionText_Required);
this.DeletePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_SkipPaymentInfo);
this.DeletePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_SkipPaymentInfo_Hint);
this.DeletePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_UseSandbox);
this.DeletePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_UseSandbox_Hint);
this.DeletePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_MerchantId);
this.DeletePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_MerchantId_Hint);
this.DeletePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_MerchantId_Required);
this.DeletePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_MerchantHashKey);
this.DeletePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_MerchantHashKey_Hint);
this.DeletePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_MerchantHashKey_Required);
this.DeletePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_ShowGTPayPage);
this.DeletePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_ShowGTPayPage_Hint);
this.DeletePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_PreferredGateway);
this.DeletePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_PreferredGateway_Hint);
this.DeletePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_ShowCustomerName);
this.DeletePluginLocaleResource(Constants.LocaleResources.GTPay_Fields_ShowCustomerName_Hint);
base.Uninstall();
}
#endregion
#region Properties
/// <summary>
/// Gets a value indicating whether capture is supported
/// </summary>
public bool SupportCapture
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether partial refund is supported
/// </summary>
public bool SupportPartiallyRefund
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether refund is supported
/// </summary>
public bool SupportRefund
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether void is supported
/// </summary>
public bool SupportVoid
{
get
{
return false;
}
}
/// <summary>
/// Gets a recurring payment type of payment method
/// </summary>
public RecurringPaymentType RecurringPaymentType
{
get
{
return RecurringPaymentType.NotSupported;
}
}
/// <summary>
/// Gets a payment method type
/// </summary>
public PaymentMethodType PaymentMethodType
{
get
{
return PaymentMethodType.Redirection;
}
}
/// <summary>
/// Gets a value indicating whether we should display a payment information page for this plugin
/// </summary>
public bool SkipPaymentInfo
{
get
{
return _gtPayPaymentSettings.SkipPaymentInfo;
}
}
/// <summary>
/// Gets a payment method description that will be displayed on checkout pages in the public store
/// </summary>
public string PaymentMethodDescription
{
//return description of this payment method to be display on "payment method" checkout step. good practice is to make it localizable
//for example, for a redirection payment method, description may be like this: "You will be redirected to GTPay site to complete the payment"
get { return _localizationService.GetResource("Plugins.Payments.GTPay.PaymentMethod.Description"); }
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Catnap.Database;
using Catnap.Extensions;
namespace Catnap.Citeria.Conditions
{
public class Criteria<T> : ICriteria<T>, IConditionMarker where T : class, new()
{
private readonly string conjunction;
private readonly List<IConditionMarker> conditions = new List<IConditionMarker>();
private readonly List<Expression<Func<T, bool>>> predicates = new List<Expression<Func<T, bool>>>();
private readonly List<Parameter> parameters = new List<Parameter>();
private int parameterCount;
private string commandText;
public Criteria() : this("and") { }
internal Criteria(string conjunction)
{
this.conjunction = conjunction;
}
internal Criteria(Action<ICriteria<T>> criteria, string conjunction)
{
this.conjunction = conjunction;
criteria(this);
}
internal Criteria(IEnumerable<IConditionMarker> conditions) : this("and")
{
this.conditions.AddRange(conditions);
}
public ICriteria<T> And(Action<ICriteria<T>> criteria)
{
if (criteria != null)
{
var condition = new Criteria<T>(criteria, "and");
conditions.Add(condition);
}
return this;
}
public ICriteria<T> Or(Action<ICriteria<T>> criteria)
{
if (criteria != null)
{
var condition = new Criteria<T>(criteria, "or");
conditions.Add(condition);
}
return this;
}
public ICriteria<T> Where(Expression<Func<T, bool>> predicate)
{
if (predicate != null)
{
predicates.Add(predicate);
}
return this;
}
public ICriteria<T> Where(Expression<Func<T, object>> property, string @operator, object value)
{
property.GuardArgumentNull("property");
var condition = new LeftRightCondition<T>(property, @operator, value);
conditions.Add(condition);
return this;
}
public ICriteria<T> Where(string columnName, string @operator, object value)
{
columnName.GuardArgumentNull("columnName");
var condition = new LeftRightCondition(columnName, @operator, value);
conditions.Add(condition);
return this;
}
public ICriteria<T> Equal(string columnName, object value)
{
columnName.GuardArgumentNull("columnName");
var condition = new Equal(columnName, value);
conditions.Add(condition);
return this;
}
public ICriteria<T> Equal(Expression<Func<T, object>> property, object value)
{
property.GuardArgumentNull("property");
var condition = new Equal<T>(property, value);
conditions.Add(condition);
return this;
}
public ICriteria<T> NotEqual(string columnName, object value)
{
columnName.GuardArgumentNull("columnName");
var condition = new NotEqual(columnName, value);
conditions.Add(condition);
return this;
}
public ICriteria<T> NotEqual(Expression<Func<T, object>> property, object value)
{
property.GuardArgumentNull("property");
var condition = new NotEqual<T>(property, value);
conditions.Add(condition);
return this;
}
public ICriteria<T> Greater(string columnName, object value)
{
columnName.GuardArgumentNull("columnName");
var condition = new GreaterThan(columnName, value);
conditions.Add(condition);
return this;
}
public ICriteria<T> Greater(Expression<Func<T, object>> property, object value)
{
property.GuardArgumentNull("property");
var condition = new GreaterThan<T>(property, value);
conditions.Add(condition);
return this;
}
public ICriteria<T> Less(string columnName, object value)
{
columnName.GuardArgumentNull("columnName");
var condition = new LessThan(columnName, value);
conditions.Add(condition);
return this;
}
public ICriteria<T> Less(Expression<Func<T, object>> property, object value)
{
property.GuardArgumentNull("property");
var condition = new LessThan<T>(property, value);
conditions.Add(condition);
return this;
}
public ICriteria<T> GreaterOrEqual(string columnName, object value)
{
columnName.GuardArgumentNull("columnName");
var condition = new GreaterThanOrEqual(columnName, value);
conditions.Add(condition);
return this;
}
public ICriteria<T> GreaterOrEqual(Expression<Func<T, object>> property, object value)
{
property.GuardArgumentNull("property");
var condition = new GreaterThanOrEqual<T>(property, value);
conditions.Add(condition);
return this;
}
public ICriteria<T> LessOrEqual(string columnName, object value)
{
columnName.GuardArgumentNull("columnName");
var condition = new LessThanOrEqual(columnName, value);
conditions.Add(condition);
return this;
}
public ICriteria<T> LessOrEqual(Expression<Func<T, object>> property, object value)
{
property.GuardArgumentNull("property");
var condition = new LessThanOrEqual<T>(property, value);
conditions.Add(condition);
return this;
}
public ICriteria<T> Null(string columnName)
{
columnName.GuardArgumentNull("columnName");
var condition = new IsNull(columnName);
conditions.Add(condition);
return this;
}
public ICriteria<T> Null(Expression<Func<T, object>> property)
{
property.GuardArgumentNull("property");
var condition = new IsNull<T>(property);
conditions.Add(condition);
return this;
}
public ICriteria<T> NotNull(string columnName)
{
columnName.GuardArgumentNull("columnName");
var condition = new IsNotNull(columnName);
conditions.Add(condition);
return this;
}
public ICriteria<T> NotNull(Expression<Func<T, object>> property)
{
property.GuardArgumentNull("property");
var condition = new IsNotNull<T>(property);
conditions.Add(condition);
return this;
}
public ICriteria<T> In(string columnName, params object[] values)
{
columnName.GuardArgumentNull("columnName");
var condition = new IsIn(columnName, values);
conditions.Add(condition);
return this;
}
public ICriteria<T> In(Expression<Func<T, object>> property, params object[] values)
{
property.GuardArgumentNull("property");
var condition = new IsIn<T>(property, values);
conditions.Add(condition);
return this;
}
public ICriteria<T> NotIn(string columnName, params object[] values)
{
columnName.GuardArgumentNull("columnName");
var condition = new IsNotIn(columnName, values);
conditions.Add(condition);
return this;
}
public ICriteria<T> NotIn(Expression<Func<T, object>> property, params object[] values)
{
property.GuardArgumentNull("property");
var condition = new IsNotIn<T>(property, values);
conditions.Add(condition);
return this;
}
public IDbCommandSpec Build(ISession session)
{
Build(session, parameterCount);
return new DbCommandSpec()
.SetCommandText(commandText)
.AddParameters(parameters.ToArray());
}
private void Build(ISession session, int currentParameterCount)
{
parameterCount = currentParameterCount;
var conditionSqls = conditions.Select(x => Visit(x, session)).ToList();
foreach (var predicate in predicates)
{
var commandSpec = new CriteriaPredicateBuilder<T>(session, predicate, parameterCount)
.Build(out parameterCount);
conditionSqls.Add(commandSpec.CommandText);
parameters.AddRange(commandSpec.Parameters);
}
commandText = string.Format("({0})",
string.Join(string.Format(" {0} ", conjunction.Trim()), conditionSqls.ToArray()));
}
private string Visit(IConditionMarker condition, ISession session)
{
var columnValueCondition = condition as ColumnValueCondition;
if (columnValueCondition != null)
{
return Visit(columnValueCondition, session);
}
var propertyValueCondition = condition as PropertyValueCondition<T>;
if (propertyValueCondition != null)
{
return Visit(propertyValueCondition, session);
}
var columnValuesCondition = condition as ColumnValuesCondition;
if (columnValuesCondition != null)
{
return Visit(columnValuesCondition, session);
}
var propertyValuesCondition = condition as PropertyValuesCondition<T>;
if (propertyValuesCondition != null)
{
return Visit(propertyValuesCondition, session);
}
var columnCondition = condition as ColumnCondition;
if (columnCondition != null)
{
return Visit(columnCondition);
}
var propertyCondition = condition as PropertyCondition<T>;
if (propertyCondition != null)
{
return Visit(propertyCondition, session);
}
var criteriaCondition = condition as Criteria<T>;
if (criteriaCondition != null)
{
return Visit(criteriaCondition, session);
}
return null;
}
private string Visit(Criteria<T> condition, ISession session)
{
condition.Build(session, parameterCount);
parameterCount = condition.parameterCount;
parameters.AddRange(condition.parameters);
return condition.commandText;
}
private string Visit(ColumnValueCondition condition, ISession session)
{
var parameterName = session.DbAdapter.FormatParameterName(parameterCount.ToString());
parameterCount++;
var commandSpec = condition.ToCommandSpec(parameterName);
parameters.AddRange(commandSpec.Parameters);
return commandSpec.CommandText;
}
private string Visit(PropertyValueCondition<T> condition, ISession session)
{
var parameterName = session.DbAdapter.FormatParameterName(parameterCount.ToString());
parameterCount++;
var commandSpec = condition.ToCommandSpec(session.GetEntityMapFor<T>(), parameterName);
parameters.AddRange(commandSpec.Parameters);
return commandSpec.CommandText;
}
private string Visit(ColumnValuesCondition condition, ISession session)
{
var parameterNames = condition.ValuesCount.Times(i =>
{
var result = session.DbAdapter.FormatParameterName(parameterCount.ToString());
parameterCount++;
return result;
});
var commandSpec = condition.ToCommandSpec(parameterNames.ToArray());
parameters.AddRange(commandSpec.Parameters);
return commandSpec.CommandText;
}
private string Visit(PropertyValuesCondition<T> condition, ISession session)
{
var parameterNames = condition.ValuesCount.Times(i =>
{
var result = session.DbAdapter.FormatParameterName(parameterCount.ToString());
parameterCount++;
return result;
});
var commandSpec = condition.ToCommandSpec(session.GetEntityMapFor<T>(), parameterNames.ToArray());
parameters.AddRange(commandSpec.Parameters);
return commandSpec.CommandText;
}
private string Visit(ColumnCondition condition)
{
return condition.ToSql();
}
private string Visit(PropertyCondition<T> condition, ISession session)
{
return condition.ToSql(session.GetEntityMapFor<T>());
}
}
}
| |
// 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
//
// 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 gaxres = Google.Api.Gax.ResourceNames;
using gcbcv = Google.Cloud.Bigtable.Common.V2;
using sys = System;
using linq = System.Linq;
namespace Google.Cloud.Bigtable.Admin.V2
{
/// <summary>
/// Resource name for the 'instance' resource.
/// </summary>
public sealed partial class InstanceName : gax::IResourceName, sys::IEquatable<InstanceName>
{
private static readonly gax::PathTemplate s_template = new gax::PathTemplate("projects/{project}/instances/{instance}");
/// <summary>
/// Parses the given instance resource name in string form into a new
/// <see cref="InstanceName"/> instance.
/// </summary>
/// <param name="instanceName">The instance resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="InstanceName"/> if successful.</returns>
public static InstanceName Parse(string instanceName)
{
gax::GaxPreconditions.CheckNotNull(instanceName, nameof(instanceName));
gax::TemplatedResourceName resourceName = s_template.ParseName(instanceName);
return new InstanceName(resourceName[0], resourceName[1]);
}
/// <summary>
/// Tries to parse the given instance resource name in string form into a new
/// <see cref="InstanceName"/> instance.
/// </summary>
/// <remarks>
/// This method still throws <see cref="sys::ArgumentNullException"/> if <paramref name="instanceName"/> is null,
/// as this would usually indicate a programming error rather than a data error.
/// </remarks>
/// <param name="instanceName">The instance resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">When this method returns, the parsed <see cref="InstanceName"/>,
/// or <c>null</c> if parsing fails.</param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string instanceName, out InstanceName result)
{
gax::GaxPreconditions.CheckNotNull(instanceName, nameof(instanceName));
gax::TemplatedResourceName resourceName;
if (s_template.TryParseName(instanceName, out resourceName))
{
result = new InstanceName(resourceName[0], resourceName[1]);
return true;
}
else
{
result = null;
return false;
}
}
/// <summary>
/// Constructs a new instance of the <see cref="InstanceName"/> resource name class
/// from its component parts.
/// </summary>
/// <param name="projectId">The project ID. Must not be <c>null</c>.</param>
/// <param name="instanceId">The instance ID. Must not be <c>null</c>.</param>
public InstanceName(string projectId, string instanceId)
{
ProjectId = gax::GaxPreconditions.CheckNotNull(projectId, nameof(projectId));
InstanceId = gax::GaxPreconditions.CheckNotNull(instanceId, nameof(instanceId));
}
/// <summary>
/// The project ID. Never <c>null</c>.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The instance ID. Never <c>null</c>.
/// </summary>
public string InstanceId { get; }
/// <inheritdoc />
public gax::ResourceNameKind Kind => gax::ResourceNameKind.Simple;
/// <inheritdoc />
public override string ToString() => s_template.Expand(ProjectId, InstanceId);
/// <inheritdoc />
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc />
public override bool Equals(object obj) => Equals(obj as InstanceName);
/// <inheritdoc />
public bool Equals(InstanceName other) => ToString() == other?.ToString();
/// <inheritdoc />
public static bool operator ==(InstanceName a, InstanceName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc />
public static bool operator !=(InstanceName a, InstanceName b) => !(a == b);
}
/// <summary>
/// Resource name for the 'app_profile' resource.
/// </summary>
public sealed partial class AppProfileName : gax::IResourceName, sys::IEquatable<AppProfileName>
{
private static readonly gax::PathTemplate s_template = new gax::PathTemplate("projects/{project}/instances/{instance}/appProfiles/{app_profile}");
/// <summary>
/// Parses the given app_profile resource name in string form into a new
/// <see cref="AppProfileName"/> instance.
/// </summary>
/// <param name="appProfileName">The app_profile resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="AppProfileName"/> if successful.</returns>
public static AppProfileName Parse(string appProfileName)
{
gax::GaxPreconditions.CheckNotNull(appProfileName, nameof(appProfileName));
gax::TemplatedResourceName resourceName = s_template.ParseName(appProfileName);
return new AppProfileName(resourceName[0], resourceName[1], resourceName[2]);
}
/// <summary>
/// Tries to parse the given app_profile resource name in string form into a new
/// <see cref="AppProfileName"/> instance.
/// </summary>
/// <remarks>
/// This method still throws <see cref="sys::ArgumentNullException"/> if <paramref name="appProfileName"/> is null,
/// as this would usually indicate a programming error rather than a data error.
/// </remarks>
/// <param name="appProfileName">The app_profile resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">When this method returns, the parsed <see cref="AppProfileName"/>,
/// or <c>null</c> if parsing fails.</param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string appProfileName, out AppProfileName result)
{
gax::GaxPreconditions.CheckNotNull(appProfileName, nameof(appProfileName));
gax::TemplatedResourceName resourceName;
if (s_template.TryParseName(appProfileName, out resourceName))
{
result = new AppProfileName(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
else
{
result = null;
return false;
}
}
/// <summary>
/// Constructs a new instance of the <see cref="AppProfileName"/> resource name class
/// from its component parts.
/// </summary>
/// <param name="projectId">The project ID. Must not be <c>null</c>.</param>
/// <param name="instanceId">The instance ID. Must not be <c>null</c>.</param>
/// <param name="appProfileId">The appProfile ID. Must not be <c>null</c>.</param>
public AppProfileName(string projectId, string instanceId, string appProfileId)
{
ProjectId = gax::GaxPreconditions.CheckNotNull(projectId, nameof(projectId));
InstanceId = gax::GaxPreconditions.CheckNotNull(instanceId, nameof(instanceId));
AppProfileId = gax::GaxPreconditions.CheckNotNull(appProfileId, nameof(appProfileId));
}
/// <summary>
/// The project ID. Never <c>null</c>.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The instance ID. Never <c>null</c>.
/// </summary>
public string InstanceId { get; }
/// <summary>
/// The appProfile ID. Never <c>null</c>.
/// </summary>
public string AppProfileId { get; }
/// <inheritdoc />
public gax::ResourceNameKind Kind => gax::ResourceNameKind.Simple;
/// <inheritdoc />
public override string ToString() => s_template.Expand(ProjectId, InstanceId, AppProfileId);
/// <inheritdoc />
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc />
public override bool Equals(object obj) => Equals(obj as AppProfileName);
/// <inheritdoc />
public bool Equals(AppProfileName other) => ToString() == other?.ToString();
/// <inheritdoc />
public static bool operator ==(AppProfileName a, AppProfileName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc />
public static bool operator !=(AppProfileName a, AppProfileName b) => !(a == b);
}
/// <summary>
/// Resource name for the 'cluster' resource.
/// </summary>
public sealed partial class ClusterName : gax::IResourceName, sys::IEquatable<ClusterName>
{
private static readonly gax::PathTemplate s_template = new gax::PathTemplate("projects/{project}/instances/{instance}/clusters/{cluster}");
/// <summary>
/// Parses the given cluster resource name in string form into a new
/// <see cref="ClusterName"/> instance.
/// </summary>
/// <param name="clusterName">The cluster resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ClusterName"/> if successful.</returns>
public static ClusterName Parse(string clusterName)
{
gax::GaxPreconditions.CheckNotNull(clusterName, nameof(clusterName));
gax::TemplatedResourceName resourceName = s_template.ParseName(clusterName);
return new ClusterName(resourceName[0], resourceName[1], resourceName[2]);
}
/// <summary>
/// Tries to parse the given cluster resource name in string form into a new
/// <see cref="ClusterName"/> instance.
/// </summary>
/// <remarks>
/// This method still throws <see cref="sys::ArgumentNullException"/> if <paramref name="clusterName"/> is null,
/// as this would usually indicate a programming error rather than a data error.
/// </remarks>
/// <param name="clusterName">The cluster resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">When this method returns, the parsed <see cref="ClusterName"/>,
/// or <c>null</c> if parsing fails.</param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string clusterName, out ClusterName result)
{
gax::GaxPreconditions.CheckNotNull(clusterName, nameof(clusterName));
gax::TemplatedResourceName resourceName;
if (s_template.TryParseName(clusterName, out resourceName))
{
result = new ClusterName(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
else
{
result = null;
return false;
}
}
/// <summary>
/// Constructs a new instance of the <see cref="ClusterName"/> resource name class
/// from its component parts.
/// </summary>
/// <param name="projectId">The project ID. Must not be <c>null</c>.</param>
/// <param name="instanceId">The instance ID. Must not be <c>null</c>.</param>
/// <param name="clusterId">The cluster ID. Must not be <c>null</c>.</param>
public ClusterName(string projectId, string instanceId, string clusterId)
{
ProjectId = gax::GaxPreconditions.CheckNotNull(projectId, nameof(projectId));
InstanceId = gax::GaxPreconditions.CheckNotNull(instanceId, nameof(instanceId));
ClusterId = gax::GaxPreconditions.CheckNotNull(clusterId, nameof(clusterId));
}
/// <summary>
/// The project ID. Never <c>null</c>.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The instance ID. Never <c>null</c>.
/// </summary>
public string InstanceId { get; }
/// <summary>
/// The cluster ID. Never <c>null</c>.
/// </summary>
public string ClusterId { get; }
/// <inheritdoc />
public gax::ResourceNameKind Kind => gax::ResourceNameKind.Simple;
/// <inheritdoc />
public override string ToString() => s_template.Expand(ProjectId, InstanceId, ClusterId);
/// <inheritdoc />
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc />
public override bool Equals(object obj) => Equals(obj as ClusterName);
/// <inheritdoc />
public bool Equals(ClusterName other) => ToString() == other?.ToString();
/// <inheritdoc />
public static bool operator ==(ClusterName a, ClusterName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc />
public static bool operator !=(ClusterName a, ClusterName b) => !(a == b);
}
/// <summary>
/// Resource name for the 'location' resource.
/// </summary>
public sealed partial class LocationName : gax::IResourceName, sys::IEquatable<LocationName>
{
private static readonly gax::PathTemplate s_template = new gax::PathTemplate("projects/{project}/locations/{location}");
/// <summary>
/// Parses the given location resource name in string form into a new
/// <see cref="LocationName"/> instance.
/// </summary>
/// <param name="locationName">The location resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="LocationName"/> if successful.</returns>
public static LocationName Parse(string locationName)
{
gax::GaxPreconditions.CheckNotNull(locationName, nameof(locationName));
gax::TemplatedResourceName resourceName = s_template.ParseName(locationName);
return new LocationName(resourceName[0], resourceName[1]);
}
/// <summary>
/// Tries to parse the given location resource name in string form into a new
/// <see cref="LocationName"/> instance.
/// </summary>
/// <remarks>
/// This method still throws <see cref="sys::ArgumentNullException"/> if <paramref name="locationName"/> is null,
/// as this would usually indicate a programming error rather than a data error.
/// </remarks>
/// <param name="locationName">The location resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">When this method returns, the parsed <see cref="LocationName"/>,
/// or <c>null</c> if parsing fails.</param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string locationName, out LocationName result)
{
gax::GaxPreconditions.CheckNotNull(locationName, nameof(locationName));
gax::TemplatedResourceName resourceName;
if (s_template.TryParseName(locationName, out resourceName))
{
result = new LocationName(resourceName[0], resourceName[1]);
return true;
}
else
{
result = null;
return false;
}
}
/// <summary>
/// Constructs a new instance of the <see cref="LocationName"/> resource name class
/// from its component parts.
/// </summary>
/// <param name="projectId">The project ID. Must not be <c>null</c>.</param>
/// <param name="locationId">The location ID. Must not be <c>null</c>.</param>
public LocationName(string projectId, string locationId)
{
ProjectId = gax::GaxPreconditions.CheckNotNull(projectId, nameof(projectId));
LocationId = gax::GaxPreconditions.CheckNotNull(locationId, nameof(locationId));
}
/// <summary>
/// The project ID. Never <c>null</c>.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The location ID. Never <c>null</c>.
/// </summary>
public string LocationId { get; }
/// <inheritdoc />
public gax::ResourceNameKind Kind => gax::ResourceNameKind.Simple;
/// <inheritdoc />
public override string ToString() => s_template.Expand(ProjectId, LocationId);
/// <inheritdoc />
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc />
public override bool Equals(object obj) => Equals(obj as LocationName);
/// <inheritdoc />
public bool Equals(LocationName other) => ToString() == other?.ToString();
/// <inheritdoc />
public static bool operator ==(LocationName a, LocationName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc />
public static bool operator !=(LocationName a, LocationName b) => !(a == b);
}
/// <summary>
/// Resource name for the 'snapshot' resource.
/// </summary>
public sealed partial class SnapshotName : gax::IResourceName, sys::IEquatable<SnapshotName>
{
private static readonly gax::PathTemplate s_template = new gax::PathTemplate("projects/{project}/instances/{instance}/clusters/{cluster}/snapshots/{snapshot}");
/// <summary>
/// Parses the given snapshot resource name in string form into a new
/// <see cref="SnapshotName"/> instance.
/// </summary>
/// <param name="snapshotName">The snapshot resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="SnapshotName"/> if successful.</returns>
public static SnapshotName Parse(string snapshotName)
{
gax::GaxPreconditions.CheckNotNull(snapshotName, nameof(snapshotName));
gax::TemplatedResourceName resourceName = s_template.ParseName(snapshotName);
return new SnapshotName(resourceName[0], resourceName[1], resourceName[2], resourceName[3]);
}
/// <summary>
/// Tries to parse the given snapshot resource name in string form into a new
/// <see cref="SnapshotName"/> instance.
/// </summary>
/// <remarks>
/// This method still throws <see cref="sys::ArgumentNullException"/> if <paramref name="snapshotName"/> is null,
/// as this would usually indicate a programming error rather than a data error.
/// </remarks>
/// <param name="snapshotName">The snapshot resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">When this method returns, the parsed <see cref="SnapshotName"/>,
/// or <c>null</c> if parsing fails.</param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string snapshotName, out SnapshotName result)
{
gax::GaxPreconditions.CheckNotNull(snapshotName, nameof(snapshotName));
gax::TemplatedResourceName resourceName;
if (s_template.TryParseName(snapshotName, out resourceName))
{
result = new SnapshotName(resourceName[0], resourceName[1], resourceName[2], resourceName[3]);
return true;
}
else
{
result = null;
return false;
}
}
/// <summary>
/// Constructs a new instance of the <see cref="SnapshotName"/> resource name class
/// from its component parts.
/// </summary>
/// <param name="projectId">The project ID. Must not be <c>null</c>.</param>
/// <param name="instanceId">The instance ID. Must not be <c>null</c>.</param>
/// <param name="clusterId">The cluster ID. Must not be <c>null</c>.</param>
/// <param name="snapshotId">The snapshot ID. Must not be <c>null</c>.</param>
public SnapshotName(string projectId, string instanceId, string clusterId, string snapshotId)
{
ProjectId = gax::GaxPreconditions.CheckNotNull(projectId, nameof(projectId));
InstanceId = gax::GaxPreconditions.CheckNotNull(instanceId, nameof(instanceId));
ClusterId = gax::GaxPreconditions.CheckNotNull(clusterId, nameof(clusterId));
SnapshotId = gax::GaxPreconditions.CheckNotNull(snapshotId, nameof(snapshotId));
}
/// <summary>
/// The project ID. Never <c>null</c>.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The instance ID. Never <c>null</c>.
/// </summary>
public string InstanceId { get; }
/// <summary>
/// The cluster ID. Never <c>null</c>.
/// </summary>
public string ClusterId { get; }
/// <summary>
/// The snapshot ID. Never <c>null</c>.
/// </summary>
public string SnapshotId { get; }
/// <inheritdoc />
public gax::ResourceNameKind Kind => gax::ResourceNameKind.Simple;
/// <inheritdoc />
public override string ToString() => s_template.Expand(ProjectId, InstanceId, ClusterId, SnapshotId);
/// <inheritdoc />
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc />
public override bool Equals(object obj) => Equals(obj as SnapshotName);
/// <inheritdoc />
public bool Equals(SnapshotName other) => ToString() == other?.ToString();
/// <inheritdoc />
public static bool operator ==(SnapshotName a, SnapshotName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc />
public static bool operator !=(SnapshotName a, SnapshotName b) => !(a == b);
}
public partial class CheckConsistencyRequest
{
/// <summary>
/// <see cref="gcbcv::TableName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcbcv::TableName TableName
{
get { return string.IsNullOrEmpty(Name) ? null : gcbcv::TableName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class Cluster
{
/// <summary>
/// <see cref="Google.Cloud.Bigtable.Admin.V2.ClusterName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public Google.Cloud.Bigtable.Admin.V2.ClusterName ClusterName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Bigtable.Admin.V2.ClusterName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
/// <summary>
/// <see cref="Google.Cloud.Bigtable.Admin.V2.LocationName"/>-typed view over the <see cref="Location"/> resource name property.
/// </summary>
public Google.Cloud.Bigtable.Admin.V2.LocationName LocationAsLocationName
{
get { return string.IsNullOrEmpty(Location) ? null : Google.Cloud.Bigtable.Admin.V2.LocationName.Parse(Location); }
set { Location = value != null ? value.ToString() : ""; }
}
}
public partial class CreateAppProfileRequest
{
/// <summary>
/// <see cref="Google.Cloud.Bigtable.Admin.V2.InstanceName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public Google.Cloud.Bigtable.Admin.V2.InstanceName ParentAsInstanceName
{
get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Bigtable.Admin.V2.InstanceName.Parse(Parent); }
set { Parent = value != null ? value.ToString() : ""; }
}
}
public partial class CreateClusterRequest
{
/// <summary>
/// <see cref="Google.Cloud.Bigtable.Admin.V2.InstanceName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public Google.Cloud.Bigtable.Admin.V2.InstanceName ParentAsInstanceName
{
get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Bigtable.Admin.V2.InstanceName.Parse(Parent); }
set { Parent = value != null ? value.ToString() : ""; }
}
}
public partial class CreateInstanceRequest
{
/// <summary>
/// <see cref="gaxres::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gaxres::ProjectName ParentAsProjectName
{
get { return string.IsNullOrEmpty(Parent) ? null : gaxres::ProjectName.Parse(Parent); }
set { Parent = value != null ? value.ToString() : ""; }
}
}
public partial class CreateTableFromSnapshotRequest
{
/// <summary>
/// <see cref="Google.Cloud.Bigtable.Admin.V2.InstanceName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public Google.Cloud.Bigtable.Admin.V2.InstanceName ParentAsInstanceName
{
get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Bigtable.Admin.V2.InstanceName.Parse(Parent); }
set { Parent = value != null ? value.ToString() : ""; }
}
/// <summary>
/// <see cref="Google.Cloud.Bigtable.Admin.V2.SnapshotName"/>-typed view over the <see cref="SourceSnapshot"/> resource name property.
/// </summary>
public Google.Cloud.Bigtable.Admin.V2.SnapshotName SourceSnapshotAsSnapshotName
{
get { return string.IsNullOrEmpty(SourceSnapshot) ? null : Google.Cloud.Bigtable.Admin.V2.SnapshotName.Parse(SourceSnapshot); }
set { SourceSnapshot = value != null ? value.ToString() : ""; }
}
}
public partial class CreateTableRequest
{
/// <summary>
/// <see cref="Google.Cloud.Bigtable.Admin.V2.InstanceName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public Google.Cloud.Bigtable.Admin.V2.InstanceName ParentAsInstanceName
{
get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Bigtable.Admin.V2.InstanceName.Parse(Parent); }
set { Parent = value != null ? value.ToString() : ""; }
}
}
public partial class DeleteAppProfileRequest
{
/// <summary>
/// <see cref="Google.Cloud.Bigtable.Admin.V2.AppProfileName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public Google.Cloud.Bigtable.Admin.V2.AppProfileName AppProfileName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Bigtable.Admin.V2.AppProfileName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class DeleteClusterRequest
{
/// <summary>
/// <see cref="Google.Cloud.Bigtable.Admin.V2.ClusterName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public Google.Cloud.Bigtable.Admin.V2.ClusterName ClusterName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Bigtable.Admin.V2.ClusterName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class DeleteInstanceRequest
{
/// <summary>
/// <see cref="Google.Cloud.Bigtable.Admin.V2.InstanceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public Google.Cloud.Bigtable.Admin.V2.InstanceName InstanceName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Bigtable.Admin.V2.InstanceName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class DeleteSnapshotRequest
{
/// <summary>
/// <see cref="Google.Cloud.Bigtable.Admin.V2.SnapshotName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public Google.Cloud.Bigtable.Admin.V2.SnapshotName SnapshotName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Bigtable.Admin.V2.SnapshotName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class DeleteTableRequest
{
/// <summary>
/// <see cref="gcbcv::TableName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcbcv::TableName TableName
{
get { return string.IsNullOrEmpty(Name) ? null : gcbcv::TableName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class DropRowRangeRequest
{
/// <summary>
/// <see cref="gcbcv::TableName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcbcv::TableName TableName
{
get { return string.IsNullOrEmpty(Name) ? null : gcbcv::TableName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class GenerateConsistencyTokenRequest
{
/// <summary>
/// <see cref="gcbcv::TableName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcbcv::TableName TableName
{
get { return string.IsNullOrEmpty(Name) ? null : gcbcv::TableName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class GetAppProfileRequest
{
/// <summary>
/// <see cref="Google.Cloud.Bigtable.Admin.V2.AppProfileName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public Google.Cloud.Bigtable.Admin.V2.AppProfileName AppProfileName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Bigtable.Admin.V2.AppProfileName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class GetClusterRequest
{
/// <summary>
/// <see cref="Google.Cloud.Bigtable.Admin.V2.ClusterName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public Google.Cloud.Bigtable.Admin.V2.ClusterName ClusterName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Bigtable.Admin.V2.ClusterName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class GetInstanceRequest
{
/// <summary>
/// <see cref="Google.Cloud.Bigtable.Admin.V2.InstanceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public Google.Cloud.Bigtable.Admin.V2.InstanceName InstanceName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Bigtable.Admin.V2.InstanceName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class GetSnapshotRequest
{
/// <summary>
/// <see cref="Google.Cloud.Bigtable.Admin.V2.SnapshotName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public Google.Cloud.Bigtable.Admin.V2.SnapshotName SnapshotName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Bigtable.Admin.V2.SnapshotName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class GetTableRequest
{
/// <summary>
/// <see cref="gcbcv::TableName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcbcv::TableName TableName
{
get { return string.IsNullOrEmpty(Name) ? null : gcbcv::TableName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class Instance
{
/// <summary>
/// <see cref="Google.Cloud.Bigtable.Admin.V2.InstanceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public Google.Cloud.Bigtable.Admin.V2.InstanceName InstanceName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Bigtable.Admin.V2.InstanceName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class ListAppProfilesRequest
{
/// <summary>
/// <see cref="Google.Cloud.Bigtable.Admin.V2.InstanceName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public Google.Cloud.Bigtable.Admin.V2.InstanceName ParentAsInstanceName
{
get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Bigtable.Admin.V2.InstanceName.Parse(Parent); }
set { Parent = value != null ? value.ToString() : ""; }
}
}
public partial class ListClustersRequest
{
/// <summary>
/// <see cref="Google.Cloud.Bigtable.Admin.V2.InstanceName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public Google.Cloud.Bigtable.Admin.V2.InstanceName ParentAsInstanceName
{
get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Bigtable.Admin.V2.InstanceName.Parse(Parent); }
set { Parent = value != null ? value.ToString() : ""; }
}
}
public partial class ListInstancesRequest
{
/// <summary>
/// <see cref="gaxres::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gaxres::ProjectName ParentAsProjectName
{
get { return string.IsNullOrEmpty(Parent) ? null : gaxres::ProjectName.Parse(Parent); }
set { Parent = value != null ? value.ToString() : ""; }
}
}
public partial class ListSnapshotsRequest
{
/// <summary>
/// <see cref="Google.Cloud.Bigtable.Admin.V2.ClusterName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public Google.Cloud.Bigtable.Admin.V2.ClusterName ParentAsClusterName
{
get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Bigtable.Admin.V2.ClusterName.Parse(Parent); }
set { Parent = value != null ? value.ToString() : ""; }
}
}
public partial class ListTablesRequest
{
/// <summary>
/// <see cref="Google.Cloud.Bigtable.Admin.V2.InstanceName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public Google.Cloud.Bigtable.Admin.V2.InstanceName ParentAsInstanceName
{
get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Bigtable.Admin.V2.InstanceName.Parse(Parent); }
set { Parent = value != null ? value.ToString() : ""; }
}
}
public partial class ModifyColumnFamiliesRequest
{
/// <summary>
/// <see cref="gcbcv::TableName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcbcv::TableName TableName
{
get { return string.IsNullOrEmpty(Name) ? null : gcbcv::TableName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class Snapshot
{
/// <summary>
/// <see cref="Google.Cloud.Bigtable.Admin.V2.SnapshotName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public Google.Cloud.Bigtable.Admin.V2.SnapshotName SnapshotName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Bigtable.Admin.V2.SnapshotName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class SnapshotTableRequest
{
/// <summary>
/// <see cref="gcbcv::TableName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcbcv::TableName TableName
{
get { return string.IsNullOrEmpty(Name) ? null : gcbcv::TableName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
/// <summary>
/// <see cref="Google.Cloud.Bigtable.Admin.V2.ClusterName"/>-typed view over the <see cref="Cluster"/> resource name property.
/// </summary>
public Google.Cloud.Bigtable.Admin.V2.ClusterName ClusterAsClusterName
{
get { return string.IsNullOrEmpty(Cluster) ? null : Google.Cloud.Bigtable.Admin.V2.ClusterName.Parse(Cluster); }
set { Cluster = value != null ? value.ToString() : ""; }
}
/// <summary>
/// <see cref="Google.Cloud.Bigtable.Admin.V2.SnapshotName"/>-typed view over the <see cref="SnapshotId"/> resource name property.
/// </summary>
public Google.Cloud.Bigtable.Admin.V2.SnapshotName SnapshotIdAsSnapshotName
{
get { return string.IsNullOrEmpty(SnapshotId) ? null : Google.Cloud.Bigtable.Admin.V2.SnapshotName.Parse(SnapshotId); }
set { SnapshotId = value != null ? value.ToString() : ""; }
}
}
public partial class Table
{
/// <summary>
/// <see cref="gcbcv::TableName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcbcv::TableName TableName
{
get { return string.IsNullOrEmpty(Name) ? null : gcbcv::TableName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
}
| |
// Copyright 2006 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Text;
using System.Collections.Generic;
//TODO: Reflection should be done at a higher level than this class
using System.Reflection;
namespace DBus.Protocol
{
//maybe this should be nullable?
public struct Signature
{
static readonly byte[] EmptyArray = new byte[0];
public static readonly Signature Empty = new Signature(String.Empty);
public static readonly Signature ArraySig = Allocate(DType.Array);
public static readonly Signature ByteSig = Allocate(DType.Byte);
public static readonly Signature DictEntryBegin = Allocate(DType.DictEntryBegin);
public static readonly Signature DictEntryEnd = Allocate(DType.DictEntryEnd);
public static readonly Signature Int32Sig = Allocate(DType.Int32);
public static readonly Signature UInt16Sig = Allocate(DType.UInt16);
public static readonly Signature UInt32Sig = Allocate(DType.UInt32);
public static readonly Signature StringSig = Allocate(DType.String);
public static readonly Signature StructBegin = Allocate(DType.StructBegin);
public static readonly Signature StructEnd = Allocate(DType.StructEnd);
public static readonly Signature ObjectPathSig = Allocate(DType.ObjectPath);
public static readonly Signature SignatureSig = Allocate(DType.Signature);
public static readonly Signature VariantSig = Allocate(DType.Variant);
public static bool operator ==(Signature a, Signature b)
{
if (a.data == b.data)
return true;
if (a.data == null)
return false;
if (b.data == null)
return false;
if (a.data.Length != b.data.Length)
return false;
for (int i = 0; i != a.data.Length; i++)
if (a.data[i] != b.data[i])
return false;
return true;
}
public static bool operator !=(Signature a, Signature b)
{
return !(a == b);
}
public override bool Equals(object o)
{
if (o == null)
return false;
if (!(o is Signature))
return false;
return this == (Signature)o;
}
public override int GetHashCode()
{
// TODO: Avoid string conversion
return Value.GetHashCode();
}
public static Signature operator +(Signature s1, Signature s2)
{
return Concat(s1, s2);
}
public static Signature Concat(Signature s1, Signature s2)
{
if (s1.data == null && s2.data == null)
return Signature.Empty;
if (s1.data == null)
return s2;
if (s2.data == null)
return s1;
if (s1.Length + s2.Length == 0)
return Signature.Empty;
byte[] data = new byte[s1.data.Length + s2.data.Length];
s1.data.CopyTo(data, 0);
s2.data.CopyTo(data, s1.data.Length);
return Signature.Take(data);
}
public Signature(string value)
{
if (value == null)
throw new ArgumentNullException("value");
if (!IsValid(value))
throw new ArgumentException(string.Format("'{0}' is not a valid signature", value), "value");
foreach (var c in value)
if (!Enum.IsDefined(typeof(DType), (byte)c))
throw new ArgumentException(string.Format("{0} is not a valid dbus type", c));
if (value.Length == 0)
{
data = EmptyArray;
}
else if (value.Length == 1)
{
data = DataForDType((DType)value[0]);
}
else
{
data = Encoding.ASCII.GetBytes(value);
}
}
// Basic validity is to check that every "opening" DType has a corresponding closing DType
static bool IsValid(string strSig)
{
int structCount = 0;
int dictCount = 0;
foreach (char c in strSig)
{
switch ((DType)c)
{
case DType.StructBegin:
structCount++;
break;
case DType.StructEnd:
structCount--;
break;
case DType.DictEntryBegin:
dictCount++;
break;
case DType.DictEntryEnd:
dictCount--;
break;
}
}
return structCount == 0 && dictCount == 0;
}
internal static Signature Take(byte[] value)
{
Signature sig;
if (value.Length == 0)
{
sig.data = Empty.data;
return sig;
}
if (value.Length == 1)
{
sig.data = DataForDType((DType)value[0]);
return sig;
}
sig.data = value;
return sig;
}
static byte[] DataForDType(DType value)
{
// Reduce heap allocations.
// For now, we only cache the most common protocol signatures.
switch (value)
{
case DType.Byte:
return ByteSig.data;
case DType.UInt16:
return UInt16Sig.data;
case DType.UInt32:
return UInt32Sig.data;
case DType.String:
return StringSig.data;
case DType.ObjectPath:
return ObjectPathSig.data;
case DType.Signature:
return SignatureSig.data;
case DType.Variant:
return VariantSig.data;
default:
return new byte[] { (byte)value };
}
}
private static Signature Allocate(DType value)
{
Signature sig;
sig.data = new byte[] { (byte)value };
return sig;
}
internal Signature(DType value)
{
this.data = DataForDType(value);
}
internal Signature(DType[] value)
{
if (value == null)
throw new ArgumentNullException("value");
if (value.Length == 0)
{
this.data = Empty.data;
return;
}
if (value.Length == 1)
{
this.data = DataForDType(value[0]);
return;
}
this.data = new byte[value.Length];
for (int i = 0; i != value.Length; i++)
this.data[i] = (byte)value[i];
}
byte[] data;
//TODO: this should be private, but MessageWriter and Monitor still use it
//[Obsolete]
public byte[] GetBuffer()
{
return data;
}
internal DType this[int index]
{
get
{
return (DType)data[index];
}
}
public int Length
{
get
{
return data.Length;
}
}
public string Value
{
get
{
//FIXME: hack to handle bad case when Data is null
if (data == null)
return String.Empty;
return Encoding.ASCII.GetString(data);
}
}
public override string ToString()
{
return Value;
}
public static Signature MakeArray(Signature signature)
{
if (!signature.IsSingleCompleteType)
throw new ArgumentException("The type of an array must be a single complete type", "signature");
return Signature.ArraySig + signature;
}
public static Signature MakeStruct(Signature signature)
{
if (signature == Signature.Empty)
throw new ArgumentException("Cannot create a struct with no fields", "signature");
return Signature.StructBegin + signature + Signature.StructEnd;
}
public static Signature MakeDictEntry(Signature keyType, Signature valueType)
{
if (!keyType.IsSingleCompleteType)
throw new ArgumentException("Signature must be a single complete type", "keyType");
if (!valueType.IsSingleCompleteType)
throw new ArgumentException("Signature must be a single complete type", "valueType");
return Signature.DictEntryBegin +
keyType +
valueType +
Signature.DictEntryEnd;
}
public static Signature MakeDict(Signature keyType, Signature valueType)
{
return MakeArray(MakeDictEntry(keyType, valueType));
}
public int Alignment
{
get
{
if (data.Length == 0)
return 0;
return ProtocolInformation.GetAlignment(this[0]);
}
}
static int GetSize(DType dtype)
{
switch (dtype)
{
case DType.Byte:
return 1;
case DType.Boolean:
return 4;
case DType.Int16:
case DType.UInt16:
return 2;
case DType.Int32:
case DType.UInt32:
return 4;
case DType.Int64:
case DType.UInt64:
return 8;
#if !DISABLE_SINGLE
case DType.Single: //Not yet supported!
return 4;
#endif
case DType.Double:
return 8;
case DType.String:
case DType.ObjectPath:
case DType.Signature:
case DType.Array:
case DType.StructBegin:
case DType.Variant:
case DType.DictEntryBegin:
return -1;
case DType.Invalid:
default:
throw new Exception("Cannot determine size of " + dtype);
}
}
public bool GetFixedSize(ref int size)
{
if (size < 0)
return false;
if (data.Length == 0)
return true;
// Sensible?
size = ProtocolInformation.Padded(size, Alignment);
if (data.Length == 1)
{
int valueSize = GetSize(this[0]);
if (valueSize == -1)
return false;
size += valueSize;
return true;
}
if (IsStructlike)
{
foreach (Signature sig in GetParts())
if (!sig.GetFixedSize(ref size))
return false;
return true;
}
if (IsArray || IsDict)
return false;
if (IsStruct)
{
foreach (Signature sig in GetFieldSignatures())
if (!sig.GetFixedSize(ref size))
return false;
return true;
}
// Any other cases?
throw new Exception();
}
public bool IsFixedSize
{
get
{
if (data.Length == 0)
return true;
if (data.Length == 1)
{
int size = GetSize(this[0]);
return size != -1;
}
if (IsStructlike)
{
foreach (Signature sig in GetParts())
if (!sig.IsFixedSize)
return false;
return true;
}
if (IsArray || IsDict)
return false;
if (IsStruct)
{
foreach (Signature sig in GetFieldSignatures())
if (!sig.IsFixedSize)
return false;
return true;
}
// Any other cases?
throw new Exception();
}
}
//TODO: complete this
public bool IsPrimitive
{
get
{
if (data.Length != 1)
return false;
if (this[0] == DType.Variant)
return false;
if (this[0] == DType.Invalid)
return false;
return true;
}
}
public bool IsVariant
{
get
{
return data.Length >= 1 && this[0] == DType.Variant;
}
}
public bool IsSingleCompleteType
{
get
{
if (data.Length == 0)
return true;
var checker = new SignatureChecker(data);
return checker.CheckSignature();
}
}
public bool IsStruct
{
get
{
if (Length < 2)
return false;
if (this[0] != DType.StructBegin)
return false;
// FIXME: Incorrect! What if this is in fact a Structlike starting and finishing with structs?
if (this[Length - 1] != DType.StructEnd)
return false;
return true;
}
}
public bool IsDictEntry
{
get
{
if (Length < 2)
return false;
if (this[0] != DType.DictEntryBegin)
return false;
// FIXME: Incorrect! What if this is in fact a Structlike starting and finishing with structs?
if (this[Length - 1] != DType.DictEntryEnd)
return false;
return true;
}
}
public bool IsStructlike
{
get
{
if (Length < 2)
return false;
if (IsArray)
return false;
if (IsDict)
return false;
if (IsStruct)
return false;
return true;
}
}
public bool IsDict
{
get
{
if (Length < 3)
return false;
if (!IsArray)
return false;
// 0 is 'a'
if (this[1] != DType.DictEntryBegin)
return false;
return true;
}
}
public bool IsArray
{
get
{
if (Length < 2)
return false;
if (this[0] != DType.Array)
return false;
return true;
}
}
public Signature GetElementSignature()
{
if (!IsArray)
throw new Exception("Cannot get the element signature of a non-array (signature was '" + this + "')");
//TODO: improve this
//if (IsDict)
// throw new NotSupportedException ("Parsing dict signature is not supported (signature was '" + this + "')");
// Skip over 'a'
int pos = 1;
return GetNextSignature(ref pos);
}
public Type[] ToTypes()
{
// TODO: Find a way to avoid these null checks everywhere.
if (data == null)
return Type.EmptyTypes;
List<Type> types = new List<Type>();
for (int i = 0; i != data.Length; types.Add(ToType(ref i))) ;
return types.ToArray();
}
public Type ToType()
{
int pos = 0;
Type ret = ToType(ref pos);
if (pos != data.Length)
throw new Exception("Signature '" + Value + "' is not a single complete type");
return ret;
}
internal static DType TypeCodeToDType(TypeCode typeCode)
{
switch (typeCode)
{
case TypeCode.Empty:
return DType.Invalid;
case TypeCode.Object:
return DType.Invalid;
case TypeCode.DBNull:
return DType.Invalid;
case TypeCode.Boolean:
return DType.Boolean;
case TypeCode.Char:
return DType.UInt16;
case TypeCode.SByte:
return DType.Byte;
case TypeCode.Byte:
return DType.Byte;
case TypeCode.Int16:
return DType.Int16;
case TypeCode.UInt16:
return DType.UInt16;
case TypeCode.Int32:
return DType.Int32;
case TypeCode.UInt32:
return DType.UInt32;
case TypeCode.Int64:
return DType.Int64;
case TypeCode.UInt64:
return DType.UInt64;
case TypeCode.Single:
return DType.Single;
case TypeCode.Double:
return DType.Double;
case TypeCode.Decimal:
return DType.Invalid;
case TypeCode.DateTime:
return DType.Invalid;
case TypeCode.String:
return DType.String;
default:
return DType.Invalid;
}
}
//FIXME: this method is bad, get rid of it
internal static DType TypeToDType(Type type)
{
if (type == typeof(void))
return DType.Invalid;
if (type == typeof(string))
return DType.String;
if (type == typeof(ObjectPath))
return DType.ObjectPath;
if (type == typeof(Signature))
return DType.Signature;
if (type == typeof(object))
return DType.Variant;
if (type.IsPrimitive)
return TypeCodeToDType(Type.GetTypeCode(type));
if (type.IsEnum)
return TypeToDType(Enum.GetUnderlyingType(type));
//needs work
if (type.IsArray)
return DType.Array;
//if (type.UnderlyingSystemType != null)
// return TypeToDType (type.UnderlyingSystemType);
if (Mapper.IsPublic(type))
return DType.ObjectPath;
if (!type.IsPrimitive && !type.IsEnum)
return DType.StructBegin;
//TODO: maybe throw an exception here
return DType.Invalid;
}
/*
public static DType TypeToDType (Type type)
{
if (type == null)
return DType.Invalid;
else if (type == typeof (byte))
return DType.Byte;
else if (type == typeof (bool))
return DType.Boolean;
else if (type == typeof (short))
return DType.Int16;
else if (type == typeof (ushort))
return DType.UInt16;
else if (type == typeof (int))
return DType.Int32;
else if (type == typeof (uint))
return DType.UInt32;
else if (type == typeof (long))
return DType.Int64;
else if (type == typeof (ulong))
return DType.UInt64;
else if (type == typeof (float)) //not supported by libdbus at time of writing
return DType.Single;
else if (type == typeof (double))
return DType.Double;
else if (type == typeof (string))
return DType.String;
else if (type == typeof (ObjectPath))
return DType.ObjectPath;
else if (type == typeof (Signature))
return DType.Signature;
else
return DType.Invalid;
}
*/
public IEnumerable<Signature> GetFieldSignatures()
{
if (this == Signature.Empty || this[0] != DType.StructBegin)
throw new Exception("Not a struct");
for (int pos = 1; pos < data.Length - 1;)
yield return GetNextSignature(ref pos);
}
public void GetDictEntrySignatures(out Signature sigKey, out Signature sigValue)
{
if (this == Signature.Empty || this[0] != DType.DictEntryBegin)
throw new Exception("Not a DictEntry");
int pos = 1;
sigKey = GetNextSignature(ref pos);
sigValue = GetNextSignature(ref pos);
}
public IEnumerable<Signature> GetParts()
{
if (data == null)
yield break;
for (int pos = 0; pos < data.Length;)
{
yield return GetNextSignature(ref pos);
}
}
public Signature GetNextSignature(ref int pos)
{
if (data == null)
return Signature.Empty;
DType dtype = (DType)data[pos++];
switch (dtype)
{
//case DType.Invalid:
// return typeof (void);
case DType.Array:
//peek to see if this is in fact a dictionary
if ((DType)data[pos] == DType.DictEntryBegin)
{
//skip over the {
pos++;
Signature keyType = GetNextSignature(ref pos);
Signature valueType = GetNextSignature(ref pos);
//skip over the }
pos++;
return Signature.MakeDict(keyType, valueType);
}
else
{
Signature elementType = GetNextSignature(ref pos);
return MakeArray(elementType);
}
//case DType.DictEntryBegin: // FIXME: DictEntries should be handled separately.
case DType.StructBegin:
//List<Signature> fieldTypes = new List<Signature> ();
Signature fieldsSig = Signature.Empty;
while ((DType)data[pos] != DType.StructEnd)
fieldsSig += GetNextSignature(ref pos);
//skip over the )
pos++;
return Signature.MakeStruct(fieldsSig);
//return fieldsSig;
case DType.DictEntryBegin:
Signature sigKey = GetNextSignature(ref pos);
Signature sigValue = GetNextSignature(ref pos);
//skip over the }
pos++;
return Signature.MakeDictEntry(sigKey, sigValue);
default:
return new Signature(dtype);
}
}
public Type ToType(ref int pos)
{
// TODO: Find a way to avoid these null checks everywhere.
if (data == null)
return typeof(void);
DType dtype = (DType)data[pos++];
switch (dtype)
{
case DType.Invalid:
return typeof(void);
case DType.Byte:
return typeof(byte);
case DType.Boolean:
return typeof(bool);
case DType.Int16:
return typeof(short);
case DType.UInt16:
return typeof(ushort);
case DType.Int32:
return typeof(int);
case DType.UInt32:
return typeof(uint);
case DType.Int64:
return typeof(long);
case DType.UInt64:
return typeof(ulong);
case DType.Single: ////not supported by libdbus at time of writing
return typeof(float);
case DType.Double:
return typeof(double);
case DType.String:
return typeof(string);
case DType.ObjectPath:
return typeof(ObjectPath);
case DType.Signature:
return typeof(Signature);
case DType.Array:
//peek to see if this is in fact a dictionary
if ((DType)data[pos] == DType.DictEntryBegin)
{
//skip over the {
pos++;
Type keyType = ToType(ref pos);
Type valueType = ToType(ref pos);
//skip over the }
pos++;
return typeof(Dictionary<,>).MakeGenericType(new[] { keyType, valueType });
}
else
{
return ToType(ref pos).MakeArrayType();
}
case DType.StructBegin:
List<Type> innerTypes = new List<Type>();
while (((DType)data[pos]) != DType.StructEnd)
innerTypes.Add(ToType(ref pos));
// go over the struct end
pos++;
return DBusStruct.FromInnerTypes(innerTypes.ToArray());
case DType.DictEntryBegin:
return typeof(System.Collections.Generic.KeyValuePair<,>);
case DType.Variant:
return typeof(object);
default:
throw new NotSupportedException("Parsing or converting this signature is not yet supported (signature was '" + this + "'), at DType." + dtype);
}
}
public static Signature GetSig(object[] objs)
{
return GetSig(Type.GetTypeArray(objs));
}
public static Signature GetSig(Type[] types)
{
if (types == null)
throw new ArgumentNullException("types");
Signature sig = Signature.Empty;
foreach (Type type in types)
sig += GetSig(type);
return sig;
}
public static Signature GetSig(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
//this is inelegant, but works for now
if (type == typeof(Signature))
return Signature.SignatureSig;
if (type == typeof(ObjectPath))
return Signature.ObjectPathSig;
if (type == typeof(void))
return Signature.Empty;
if (type == typeof(string))
return Signature.StringSig;
if (type == typeof(object))
return Signature.VariantSig;
if (type.IsArray)
return MakeArray(GetSig(type.GetElementType()));
if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(IDictionary<,>) || type.GetGenericTypeDefinition() == typeof(Dictionary<,>)))
{
Type[] genArgs = type.GetGenericArguments();
return Signature.MakeDict(GetSig(genArgs[0]), GetSig(genArgs[1]));
}
if (Mapper.IsPublic(type))
{
return Signature.ObjectPathSig;
}
if (!type.IsPrimitive && !type.IsEnum)
{
Signature sig = Signature.Empty;
foreach (FieldInfo fi in type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
sig += GetSig(fi.FieldType);
return Signature.MakeStruct(sig);
}
DType dtype = Signature.TypeToDType(type);
return new Signature(dtype);
}
class SignatureChecker
{
byte[] data;
int pos;
internal SignatureChecker(byte[] data)
{
this.data = data;
}
internal bool CheckSignature()
{
return SingleType() ? pos == data.Length : false;
}
bool SingleType()
{
if (pos >= data.Length)
return false;
//Console.WriteLine ((DType)data[pos]);
switch ((DType)data[pos])
{
// Simple Type
case DType.Byte:
case DType.Boolean:
case DType.Int16:
case DType.UInt16:
case DType.Int32:
case DType.UInt32:
case DType.Int64:
case DType.UInt64:
case DType.Single:
case DType.Double:
case DType.String:
case DType.ObjectPath:
case DType.Signature:
case DType.Variant:
pos += 1;
return true;
case DType.Array:
pos += 1;
return ArrayType();
case DType.StructBegin:
pos += 1;
return StructType();
case DType.DictEntryBegin:
pos += 1;
return DictType();
}
return false;
}
bool ArrayType()
{
return SingleType();
}
bool DictType()
{
bool result = SingleType() && SingleType() && ((DType)data[pos]) == DType.DictEntryEnd;
if (result)
pos += 1;
return result;
}
bool StructType()
{
if (pos >= data.Length)
return false;
while (((DType)data[pos]) != DType.StructEnd)
{
if (!SingleType())
return false;
if (pos >= data.Length)
return false;
}
pos += 1;
return true;
}
}
}
}
| |
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Reflection;
[CustomEditor(typeof(OVRManager))]
public class OVRManagerEditor : Editor
{
override public void OnInspectorGUI()
{
DrawDefaultInspector();
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
OVRManager manager = (OVRManager)target;
EditorGUILayout.Space();
EditorGUILayout.LabelField("Mixed Reality Capture", EditorStyles.boldLabel);
SetupBoolField("Show Properties", ref manager.expandMixedRealityCapturePropertySheet);
if (manager.expandMixedRealityCapturePropertySheet)
{
string[] layerMaskOptions = new string[32];
for (int i=0; i<32; ++i)
{
layerMaskOptions[i] = LayerMask.LayerToName(i);
if (layerMaskOptions[i].Length == 0)
{
layerMaskOptions[i] = "<Layer " + i.ToString() + ">";
}
}
EditorGUI.indentLevel++;
EditorGUILayout.Space();
SetupBoolField("enableMixedReality", ref manager.enableMixedReality);
SetupCompositoinMethodField("compositionMethod", ref manager.compositionMethod);
SetupLayerMaskField("extraHiddenLayers", ref manager.extraHiddenLayers, layerMaskOptions);
if (manager.compositionMethod == OVRManager.CompositionMethod.Direct || manager.compositionMethod == OVRManager.CompositionMethod.Sandwich)
{
EditorGUILayout.Space();
if (manager.compositionMethod == OVRManager.CompositionMethod.Direct)
{
EditorGUILayout.LabelField("Direct Composition", EditorStyles.boldLabel);
}
else
{
EditorGUILayout.LabelField("Sandwich Composition", EditorStyles.boldLabel);
}
EditorGUI.indentLevel++;
EditorGUILayout.Space();
EditorGUILayout.LabelField("Camera", EditorStyles.boldLabel);
SetupCameraDeviceField("capturingCameraDevice", ref manager.capturingCameraDevice);
SetupBoolField("flipCameraFrameHorizontally", ref manager.flipCameraFrameHorizontally);
SetupBoolField("flipCameraFrameVertically", ref manager.flipCameraFrameVertically);
EditorGUILayout.Space();
EditorGUILayout.LabelField("Chroma Key", EditorStyles.boldLabel);
SetupColorField("chromaKeyColor", ref manager.chromaKeyColor);
SetupFloatField("chromaKeySimilarity", ref manager.chromaKeySimilarity);
SetupFloatField("chromaKeySmoothRange", ref manager.chromaKeySmoothRange);
SetupFloatField("chromaKeySpillRange", ref manager.chromaKeySpillRange);
EditorGUILayout.Space();
EditorGUILayout.LabelField("Dynamic Lighting", EditorStyles.boldLabel);
SetupBoolField("useDynamicLighting", ref manager.useDynamicLighting);
SetupDepthQualityField("depthQuality", ref manager.depthQuality);
SetupFloatField("dynamicLightingSmoothFactor", ref manager.dynamicLightingSmoothFactor);
SetupFloatField("dynamicLightingDepthVariationClampingValue", ref manager.dynamicLightingDepthVariationClampingValue);
EditorGUILayout.Space();
EditorGUILayout.LabelField("Virtual Green Screen", EditorStyles.boldLabel);
SetupVirtualGreenTypeField("virtualGreenScreenType", ref manager.virtualGreenScreenType);
SetupFloatField("virtualGreenScreenTopY", ref manager.virtualGreenScreenTopY);
SetupFloatField("virtualGreenScreenBottomY", ref manager.virtualGreenScreenBottomY);
SetupBoolField("virtualGreenScreenApplyDepthCulling", ref manager.virtualGreenScreenApplyDepthCulling);
SetupFloatField("virtualGreenScreenDepthTolerance", ref manager.virtualGreenScreenDepthTolerance);
EditorGUILayout.Space();
EditorGUILayout.LabelField("Latency Control", EditorStyles.boldLabel);
SetupFloatField("handPoseStateLatency", ref manager.handPoseStateLatency);
if (manager.compositionMethod == OVRManager.CompositionMethod.Sandwich)
{
SetupFloatField("sandwichCompositionRenderLatency", ref manager.sandwichCompositionRenderLatency);
SetupIntField("sandwichCompositionBufferedFrames", ref manager.sandwichCompositionBufferedFrames);
}
EditorGUI.indentLevel--;
}
EditorGUI.indentLevel--;
}
#endif
}
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
void SetupBoolField(string name, ref bool member)
{
EditorGUI.BeginChangeCheck();
bool value = EditorGUILayout.Toggle(name, member);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, "Changed " + name);
member = value;
}
}
void SetupIntField(string name, ref int member)
{
EditorGUI.BeginChangeCheck();
int value = EditorGUILayout.IntField(name, member);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, "Changed " + name);
member = value;
}
}
void SetupFloatField(string name, ref float member)
{
EditorGUI.BeginChangeCheck();
float value = EditorGUILayout.FloatField(name, member);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, "Changed " + name);
member = value;
}
}
void SetupDoubleField(string name, ref double member)
{
EditorGUI.BeginChangeCheck();
double value = EditorGUILayout.DoubleField(name, member);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, "Changed " + name);
member = value;
}
}
void SetupColorField(string name, ref Color member)
{
EditorGUI.BeginChangeCheck();
Color value = EditorGUILayout.ColorField(name, member);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, "Changed " + name);
member = value;
}
}
void SetupLayerMaskField(string name, ref LayerMask layerMask, string[] layerMaskOptions)
{
EditorGUI.BeginChangeCheck();
int value = EditorGUILayout.MaskField(name, layerMask, layerMaskOptions);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, "Changed " + name);
layerMask = value;
}
}
void SetupCompositoinMethodField(string name, ref OVRManager.CompositionMethod method)
{
EditorGUI.BeginChangeCheck();
OVRManager.CompositionMethod value = (OVRManager.CompositionMethod)EditorGUILayout.EnumPopup(name, method);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, "Changed " + name);
method = value;
}
}
void SetupCameraDeviceField(string name, ref OVRManager.CameraDevice device)
{
EditorGUI.BeginChangeCheck();
OVRManager.CameraDevice value = (OVRManager.CameraDevice)EditorGUILayout.EnumPopup(name, device);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, "Changed " + name);
device = value;
}
}
void SetupDepthQualityField(string name, ref OVRManager.DepthQuality depthQuality)
{
EditorGUI.BeginChangeCheck();
OVRManager.DepthQuality value = (OVRManager.DepthQuality)EditorGUILayout.EnumPopup(name, depthQuality);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, "Changed " + name);
depthQuality = value;
}
}
void SetupVirtualGreenTypeField(string name, ref OVRManager.VirtualGreenScreenType virtualGreenScreenType)
{
EditorGUI.BeginChangeCheck();
OVRManager.VirtualGreenScreenType value = (OVRManager.VirtualGreenScreenType)EditorGUILayout.EnumPopup(name, virtualGreenScreenType);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, "Changed " + name);
virtualGreenScreenType = value;
}
}
#endif
}
#endif
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;
using pbd = global::Google.ProtocolBuffers.Descriptors;
using scg = global::System.Collections.Generic;
namespace Google.ProtocolBuffers.Examples.AddressBook {
public static partial class AddressBookProtos {
#region Extension registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
}
#endregion
#region Static variables
internal static pbd::MessageDescriptor internal__static_tutorial_Person__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.Examples.AddressBook.Person, global::Google.ProtocolBuffers.Examples.AddressBook.Person.Builder> internal__static_tutorial_Person__FieldAccessorTable;
internal static pbd::MessageDescriptor internal__static_tutorial_Person_PhoneNumber__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber, global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.Builder> internal__static_tutorial_Person_PhoneNumber__FieldAccessorTable;
internal static pbd::MessageDescriptor internal__static_tutorial_AddressBook__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.Examples.AddressBook.AddressBook, global::Google.ProtocolBuffers.Examples.AddressBook.AddressBook.Builder> internal__static_tutorial_AddressBook__FieldAccessorTable;
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static AddressBookProtos() {
byte[] descriptorData = global::System.Convert.FromBase64String(
"Chp0dXRvcmlhbC9hZGRyZXNzYm9vay5wcm90bxIIdHV0b3JpYWwaJGdvb2ds" +
"ZS9wcm90b2J1Zi9jc2hhcnBfb3B0aW9ucy5wcm90byLaAQoGUGVyc29uEgwK" +
"BG5hbWUYASACKAkSCgoCaWQYAiACKAUSDQoFZW1haWwYAyABKAkSKwoFcGhv" +
"bmUYBCADKAsyHC50dXRvcmlhbC5QZXJzb24uUGhvbmVOdW1iZXIaTQoLUGhv" +
"bmVOdW1iZXISDgoGbnVtYmVyGAEgAigJEi4KBHR5cGUYAiABKA4yGi50dXRv" +
"cmlhbC5QZXJzb24uUGhvbmVUeXBlOgRIT01FIisKCVBob25lVHlwZRIKCgZN" +
"T0JJTEUQABIICgRIT01FEAESCAoEV09SSxACIi8KC0FkZHJlc3NCb29rEiAK" +
"BnBlcnNvbhgBIAMoCzIQLnR1dG9yaWFsLlBlcnNvbkJFSAHCPkAKK0dvb2ds" +
"ZS5Qcm90b2NvbEJ1ZmZlcnMuRXhhbXBsZXMuQWRkcmVzc0Jvb2sSEUFkZHJl" +
"c3NCb29rUHJvdG9z");
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_tutorial_Person__Descriptor = Descriptor.MessageTypes[0];
internal__static_tutorial_Person__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.Examples.AddressBook.Person, global::Google.ProtocolBuffers.Examples.AddressBook.Person.Builder>(internal__static_tutorial_Person__Descriptor,
new string[] { "Name", "Id", "Email", "Phone", });
internal__static_tutorial_Person_PhoneNumber__Descriptor = internal__static_tutorial_Person__Descriptor.NestedTypes[0];
internal__static_tutorial_Person_PhoneNumber__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber, global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.Builder>(internal__static_tutorial_Person_PhoneNumber__Descriptor,
new string[] { "Number", "Type", });
internal__static_tutorial_AddressBook__Descriptor = Descriptor.MessageTypes[1];
internal__static_tutorial_AddressBook__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.Examples.AddressBook.AddressBook, global::Google.ProtocolBuffers.Examples.AddressBook.AddressBook.Builder>(internal__static_tutorial_AddressBook__Descriptor,
new string[] { "Person", });
pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance();
RegisterAllExtensions(registry);
global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.RegisterAllExtensions(registry);
return registry;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.Descriptor,
}, assigner);
}
#endregion
}
#region Messages
public sealed partial class Person : pb::GeneratedMessage<Person, Person.Builder> {
private static readonly Person defaultInstance = new Builder().BuildPartial();
public static Person DefaultInstance {
get { return defaultInstance; }
}
public override Person DefaultInstanceForType {
get { return defaultInstance; }
}
protected override Person ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::Google.ProtocolBuffers.Examples.AddressBook.AddressBookProtos.internal__static_tutorial_Person__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<Person, Person.Builder> InternalFieldAccessors {
get { return global::Google.ProtocolBuffers.Examples.AddressBook.AddressBookProtos.internal__static_tutorial_Person__FieldAccessorTable; }
}
#region Nested types
public static class Types {
public enum PhoneType {
MOBILE = 0,
HOME = 1,
WORK = 2,
}
public sealed partial class PhoneNumber : pb::GeneratedMessage<PhoneNumber, PhoneNumber.Builder> {
private static readonly PhoneNumber defaultInstance = new Builder().BuildPartial();
public static PhoneNumber DefaultInstance {
get { return defaultInstance; }
}
public override PhoneNumber DefaultInstanceForType {
get { return defaultInstance; }
}
protected override PhoneNumber ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::Google.ProtocolBuffers.Examples.AddressBook.AddressBookProtos.internal__static_tutorial_Person_PhoneNumber__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<PhoneNumber, PhoneNumber.Builder> InternalFieldAccessors {
get { return global::Google.ProtocolBuffers.Examples.AddressBook.AddressBookProtos.internal__static_tutorial_Person_PhoneNumber__FieldAccessorTable; }
}
public const int NumberFieldNumber = 1;
private bool hasNumber;
private string number_ = "";
public bool HasNumber {
get { return hasNumber; }
}
public string Number {
get { return number_; }
}
public const int TypeFieldNumber = 2;
private bool hasType;
private global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType type_ = global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType.HOME;
public bool HasType {
get { return hasType; }
}
public global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType Type {
get { return type_; }
}
public override bool IsInitialized {
get {
if (!hasNumber) return false;
return true;
}
}
public override void WriteTo(pb::CodedOutputStream output) {
int size = SerializedSize;
if (HasNumber) {
output.WriteString(1, Number);
}
if (HasType) {
output.WriteEnum(2, (int) Type);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (HasNumber) {
size += pb::CodedOutputStream.ComputeStringSize(1, Number);
}
if (HasType) {
size += pb::CodedOutputStream.ComputeEnumSize(2, (int) Type);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
}
public static PhoneNumber ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static PhoneNumber ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static PhoneNumber ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static PhoneNumber ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static PhoneNumber ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static PhoneNumber ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static PhoneNumber ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static PhoneNumber ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static PhoneNumber ParseFrom(pb::CodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static PhoneNumber ParseFrom(pb::CodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(PhoneNumber prototype) {
return (Builder) new Builder().MergeFrom(prototype);
}
public sealed partial class Builder : pb::GeneratedBuilder<PhoneNumber, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {}
PhoneNumber result = new PhoneNumber();
protected override PhoneNumber MessageBeingBuilt {
get { return result; }
}
public override Builder Clear() {
result = new PhoneNumber();
return this;
}
public override Builder Clone() {
return new Builder().MergeFrom(result);
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.Descriptor; }
}
public override PhoneNumber DefaultInstanceForType {
get { return global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.DefaultInstance; }
}
public override PhoneNumber BuildPartial() {
if (result == null) {
throw new global::System.InvalidOperationException("build() has already been called on this Builder");
}
PhoneNumber returnMe = result;
result = null;
return returnMe;
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is PhoneNumber) {
return MergeFrom((PhoneNumber) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(PhoneNumber other) {
if (other == global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.DefaultInstance) return this;
if (other.HasNumber) {
Number = other.Number;
}
if (other.HasType) {
Type = other.Type;
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::CodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::CodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
pb::UnknownFieldSet.Builder unknownFields = null;
while (true) {
uint tag = input.ReadTag();
switch (tag) {
case 0: {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag);
break;
}
case 10: {
Number = input.ReadString();
break;
}
case 16: {
int rawValue = input.ReadEnum();
if (!global::System.Enum.IsDefined(typeof(global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType), rawValue)) {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
unknownFields.MergeVarintField(2, (ulong) rawValue);
} else {
Type = (global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType) rawValue;
}
break;
}
}
}
}
public bool HasNumber {
get { return result.HasNumber; }
}
public string Number {
get { return result.Number; }
set { SetNumber(value); }
}
public Builder SetNumber(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
result.hasNumber = true;
result.number_ = value;
return this;
}
public Builder ClearNumber() {
result.hasNumber = false;
result.number_ = "";
return this;
}
public bool HasType {
get { return result.HasType; }
}
public global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType Type {
get { return result.Type; }
set { SetType(value); }
}
public Builder SetType(global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType value) {
result.hasType = true;
result.type_ = value;
return this;
}
public Builder ClearType() {
result.hasType = false;
result.type_ = global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType.HOME;
return this;
}
}
static PhoneNumber() {
object.ReferenceEquals(global::Google.ProtocolBuffers.Examples.AddressBook.AddressBookProtos.Descriptor, null);
}
}
}
#endregion
public const int NameFieldNumber = 1;
private bool hasName;
private string name_ = "";
public bool HasName {
get { return hasName; }
}
public string Name {
get { return name_; }
}
public const int IdFieldNumber = 2;
private bool hasId;
private int id_ = 0;
public bool HasId {
get { return hasId; }
}
public int Id {
get { return id_; }
}
public const int EmailFieldNumber = 3;
private bool hasEmail;
private string email_ = "";
public bool HasEmail {
get { return hasEmail; }
}
public string Email {
get { return email_; }
}
public const int PhoneFieldNumber = 4;
private pbc::PopsicleList<global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber> phone_ = new pbc::PopsicleList<global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber>();
public scg::IList<global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber> PhoneList {
get { return phone_; }
}
public int PhoneCount {
get { return phone_.Count; }
}
public global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber GetPhone(int index) {
return phone_[index];
}
public override bool IsInitialized {
get {
if (!hasName) return false;
if (!hasId) return false;
foreach (global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber element in PhoneList) {
if (!element.IsInitialized) return false;
}
return true;
}
}
public override void WriteTo(pb::CodedOutputStream output) {
int size = SerializedSize;
if (HasName) {
output.WriteString(1, Name);
}
if (HasId) {
output.WriteInt32(2, Id);
}
if (HasEmail) {
output.WriteString(3, Email);
}
foreach (global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber element in PhoneList) {
output.WriteMessage(4, element);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (HasName) {
size += pb::CodedOutputStream.ComputeStringSize(1, Name);
}
if (HasId) {
size += pb::CodedOutputStream.ComputeInt32Size(2, Id);
}
if (HasEmail) {
size += pb::CodedOutputStream.ComputeStringSize(3, Email);
}
foreach (global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber element in PhoneList) {
size += pb::CodedOutputStream.ComputeMessageSize(4, element);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
}
public static Person ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static Person ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static Person ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static Person ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static Person ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static Person ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static Person ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static Person ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static Person ParseFrom(pb::CodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static Person ParseFrom(pb::CodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(Person prototype) {
return (Builder) new Builder().MergeFrom(prototype);
}
public sealed partial class Builder : pb::GeneratedBuilder<Person, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {}
Person result = new Person();
protected override Person MessageBeingBuilt {
get { return result; }
}
public override Builder Clear() {
result = new Person();
return this;
}
public override Builder Clone() {
return new Builder().MergeFrom(result);
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::Google.ProtocolBuffers.Examples.AddressBook.Person.Descriptor; }
}
public override Person DefaultInstanceForType {
get { return global::Google.ProtocolBuffers.Examples.AddressBook.Person.DefaultInstance; }
}
public override Person BuildPartial() {
if (result == null) {
throw new global::System.InvalidOperationException("build() has already been called on this Builder");
}
result.phone_.MakeReadOnly();
Person returnMe = result;
result = null;
return returnMe;
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is Person) {
return MergeFrom((Person) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(Person other) {
if (other == global::Google.ProtocolBuffers.Examples.AddressBook.Person.DefaultInstance) return this;
if (other.HasName) {
Name = other.Name;
}
if (other.HasId) {
Id = other.Id;
}
if (other.HasEmail) {
Email = other.Email;
}
if (other.phone_.Count != 0) {
base.AddRange(other.phone_, result.phone_);
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::CodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::CodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
pb::UnknownFieldSet.Builder unknownFields = null;
while (true) {
uint tag = input.ReadTag();
switch (tag) {
case 0: {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag);
break;
}
case 10: {
Name = input.ReadString();
break;
}
case 16: {
Id = input.ReadInt32();
break;
}
case 26: {
Email = input.ReadString();
break;
}
case 34: {
global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.Builder subBuilder = global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.CreateBuilder();
input.ReadMessage(subBuilder, extensionRegistry);
AddPhone(subBuilder.BuildPartial());
break;
}
}
}
}
public bool HasName {
get { return result.HasName; }
}
public string Name {
get { return result.Name; }
set { SetName(value); }
}
public Builder SetName(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
result.hasName = true;
result.name_ = value;
return this;
}
public Builder ClearName() {
result.hasName = false;
result.name_ = "";
return this;
}
public bool HasId {
get { return result.HasId; }
}
public int Id {
get { return result.Id; }
set { SetId(value); }
}
public Builder SetId(int value) {
result.hasId = true;
result.id_ = value;
return this;
}
public Builder ClearId() {
result.hasId = false;
result.id_ = 0;
return this;
}
public bool HasEmail {
get { return result.HasEmail; }
}
public string Email {
get { return result.Email; }
set { SetEmail(value); }
}
public Builder SetEmail(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
result.hasEmail = true;
result.email_ = value;
return this;
}
public Builder ClearEmail() {
result.hasEmail = false;
result.email_ = "";
return this;
}
public pbc::IPopsicleList<global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber> PhoneList {
get { return result.phone_; }
}
public int PhoneCount {
get { return result.PhoneCount; }
}
public global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber GetPhone(int index) {
return result.GetPhone(index);
}
public Builder SetPhone(int index, global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
result.phone_[index] = value;
return this;
}
public Builder SetPhone(int index, global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.Builder builderForValue) {
pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue");
result.phone_[index] = builderForValue.Build();
return this;
}
public Builder AddPhone(global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
result.phone_.Add(value);
return this;
}
public Builder AddPhone(global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.Builder builderForValue) {
pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue");
result.phone_.Add(builderForValue.Build());
return this;
}
public Builder AddRangePhone(scg::IEnumerable<global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber> values) {
base.AddRange(values, result.phone_);
return this;
}
public Builder ClearPhone() {
result.phone_.Clear();
return this;
}
}
static Person() {
object.ReferenceEquals(global::Google.ProtocolBuffers.Examples.AddressBook.AddressBookProtos.Descriptor, null);
}
}
public sealed partial class AddressBook : pb::GeneratedMessage<AddressBook, AddressBook.Builder> {
private static readonly AddressBook defaultInstance = new Builder().BuildPartial();
public static AddressBook DefaultInstance {
get { return defaultInstance; }
}
public override AddressBook DefaultInstanceForType {
get { return defaultInstance; }
}
protected override AddressBook ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::Google.ProtocolBuffers.Examples.AddressBook.AddressBookProtos.internal__static_tutorial_AddressBook__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<AddressBook, AddressBook.Builder> InternalFieldAccessors {
get { return global::Google.ProtocolBuffers.Examples.AddressBook.AddressBookProtos.internal__static_tutorial_AddressBook__FieldAccessorTable; }
}
public const int PersonFieldNumber = 1;
private pbc::PopsicleList<global::Google.ProtocolBuffers.Examples.AddressBook.Person> person_ = new pbc::PopsicleList<global::Google.ProtocolBuffers.Examples.AddressBook.Person>();
public scg::IList<global::Google.ProtocolBuffers.Examples.AddressBook.Person> PersonList {
get { return person_; }
}
public int PersonCount {
get { return person_.Count; }
}
public global::Google.ProtocolBuffers.Examples.AddressBook.Person GetPerson(int index) {
return person_[index];
}
public override bool IsInitialized {
get {
foreach (global::Google.ProtocolBuffers.Examples.AddressBook.Person element in PersonList) {
if (!element.IsInitialized) return false;
}
return true;
}
}
public override void WriteTo(pb::CodedOutputStream output) {
int size = SerializedSize;
foreach (global::Google.ProtocolBuffers.Examples.AddressBook.Person element in PersonList) {
output.WriteMessage(1, element);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
foreach (global::Google.ProtocolBuffers.Examples.AddressBook.Person element in PersonList) {
size += pb::CodedOutputStream.ComputeMessageSize(1, element);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
}
public static AddressBook ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static AddressBook ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static AddressBook ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static AddressBook ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static AddressBook ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static AddressBook ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static AddressBook ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static AddressBook ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static AddressBook ParseFrom(pb::CodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static AddressBook ParseFrom(pb::CodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(AddressBook prototype) {
return (Builder) new Builder().MergeFrom(prototype);
}
public sealed partial class Builder : pb::GeneratedBuilder<AddressBook, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {}
AddressBook result = new AddressBook();
protected override AddressBook MessageBeingBuilt {
get { return result; }
}
public override Builder Clear() {
result = new AddressBook();
return this;
}
public override Builder Clone() {
return new Builder().MergeFrom(result);
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::Google.ProtocolBuffers.Examples.AddressBook.AddressBook.Descriptor; }
}
public override AddressBook DefaultInstanceForType {
get { return global::Google.ProtocolBuffers.Examples.AddressBook.AddressBook.DefaultInstance; }
}
public override AddressBook BuildPartial() {
if (result == null) {
throw new global::System.InvalidOperationException("build() has already been called on this Builder");
}
result.person_.MakeReadOnly();
AddressBook returnMe = result;
result = null;
return returnMe;
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is AddressBook) {
return MergeFrom((AddressBook) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(AddressBook other) {
if (other == global::Google.ProtocolBuffers.Examples.AddressBook.AddressBook.DefaultInstance) return this;
if (other.person_.Count != 0) {
base.AddRange(other.person_, result.person_);
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::CodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::CodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
pb::UnknownFieldSet.Builder unknownFields = null;
while (true) {
uint tag = input.ReadTag();
switch (tag) {
case 0: {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag);
break;
}
case 10: {
global::Google.ProtocolBuffers.Examples.AddressBook.Person.Builder subBuilder = global::Google.ProtocolBuffers.Examples.AddressBook.Person.CreateBuilder();
input.ReadMessage(subBuilder, extensionRegistry);
AddPerson(subBuilder.BuildPartial());
break;
}
}
}
}
public pbc::IPopsicleList<global::Google.ProtocolBuffers.Examples.AddressBook.Person> PersonList {
get { return result.person_; }
}
public int PersonCount {
get { return result.PersonCount; }
}
public global::Google.ProtocolBuffers.Examples.AddressBook.Person GetPerson(int index) {
return result.GetPerson(index);
}
public Builder SetPerson(int index, global::Google.ProtocolBuffers.Examples.AddressBook.Person value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
result.person_[index] = value;
return this;
}
public Builder SetPerson(int index, global::Google.ProtocolBuffers.Examples.AddressBook.Person.Builder builderForValue) {
pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue");
result.person_[index] = builderForValue.Build();
return this;
}
public Builder AddPerson(global::Google.ProtocolBuffers.Examples.AddressBook.Person value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
result.person_.Add(value);
return this;
}
public Builder AddPerson(global::Google.ProtocolBuffers.Examples.AddressBook.Person.Builder builderForValue) {
pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue");
result.person_.Add(builderForValue.Build());
return this;
}
public Builder AddRangePerson(scg::IEnumerable<global::Google.ProtocolBuffers.Examples.AddressBook.Person> values) {
base.AddRange(values, result.person_);
return this;
}
public Builder ClearPerson() {
result.person_.Clear();
return this;
}
}
static AddressBook() {
object.ReferenceEquals(global::Google.ProtocolBuffers.Examples.AddressBook.AddressBookProtos.Descriptor, null);
}
}
#endregion
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// 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 NUnit.Framework;
using System.Security.Principal;
namespace NUnit.TestData.TestFixtureTests
{
/// <summary>
/// Classes used for testing NUnit
/// </summary>
[TestFixture]
public class RegularFixtureWithOneTest
{
[Test]
public void OneTest()
{
}
}
[TestFixture]
public class NoDefaultCtorFixture
{
public NoDefaultCtorFixture(int index)
{
}
[Test]
public void OneTest()
{
}
}
[TestFixture(7,3)]
public class FixtureWithArgsSupplied
{
public FixtureWithArgsSupplied(int x, int y)
{
}
[Test]
public void OneTest()
{
}
}
[TestFixture(7, 3)]
[TestFixture(8, 4)]
public class FixtureWithMultipleArgsSupplied
{
public FixtureWithMultipleArgsSupplied(int x, int y)
{
}
[Test]
public void OneTest()
{
}
}
[TestFixture]
public class BadCtorFixture
{
public BadCtorFixture()
{
throw new Exception();
}
[Test] public void OneTest()
{
}
}
[TestFixture]
public class FixtureWithTestFixtureAttribute
{
[Test]
public void SomeTest()
{
}
}
public class FixtureWithoutTestFixtureAttributeContainingTest
{
[Test]
public void SomeTest()
{
}
}
public class FixtureWithoutTestFixtureAttributeContainingTestCase
{
[TestCase(42)]
public void SomeTest(int x)
{
}
}
[TestFixture]
public class FixtureWithParameterizedTestAndArgsSupplied
{
[TestCase(42, "abc")]
public void SomeTest(int x, string y)
{
}
}
[TestFixture]
public class FixtureWithParameterizedTestAndMultipleArgsSupplied
{
[TestCase(42, "abc")]
[TestCase(24, "cba")]
public void SomeTest(int x, string y)
{
}
}
public class FixtureWithoutTestFixtureAttributeContainingTestCaseSource
{
[TestCaseSource("data")]
public void SomeTest(int x)
{
}
}
public class FixtureWithoutTestFixtureAttributeContainingTheory
{
[Theory]
public void SomeTest(int x)
{
}
}
public static class StaticFixtureWithoutTestFixtureAttribute
{
[Test]
public static void StaticTest()
{
}
}
[TestFixture]
public class MultipleSetUpAttributes
{
[SetUp]
public void Init1()
{
}
[SetUp]
public void Init2()
{
}
[Test] public void OneTest()
{
}
}
[TestFixture]
public class MultipleTearDownAttributes
{
[TearDown]
public void Destroy1()
{
}
[TearDown]
public void Destroy2()
{
}
[Test] public void OneTest()
{
}
}
[TestFixture]
[Ignore("testing ignore a fixture")]
public class FixtureUsingIgnoreAttribute
{
[Test]
public void Success()
{
}
}
[TestFixture(Ignore = "testing ignore a fixture")]
public class FixtureUsingIgnoreProperty
{
[Test]
public void Success()
{
}
}
[TestFixture(IgnoreReason = "testing ignore a fixture")]
public class FixtureUsingIgnoreReasonProperty
{
[Test]
public void Success()
{
}
}
[TestFixture]
public class OuterClass
{
[TestFixture]
public class NestedTestFixture
{
[TestFixture]
public class DoublyNestedTestFixture
{
[Test]
public void Test()
{
}
}
}
}
[TestFixture]
public abstract class AbstractTestFixture
{
[TearDown]
public void Destroy1()
{
}
[Test]
public void SomeTest()
{
}
}
public class DerivedFromAbstractTestFixture : AbstractTestFixture
{
}
[TestFixture]
public class BaseClassTestFixture
{
[Test]
public void Success()
{
}
}
public abstract class AbstractDerivedTestFixture : BaseClassTestFixture
{
[Test]
public void Test()
{
}
}
public class DerivedFromAbstractDerivedTestFixture : AbstractDerivedTestFixture
{
}
[TestFixture]
public abstract class AbstractBaseFixtureWithAttribute
{
}
[TestFixture]
public abstract class AbstractDerivedFixtureWithSecondAttribute : AbstractBaseFixtureWithAttribute
{
}
public class DoubleDerivedClassWithTwoInheritedAttributes : AbstractDerivedFixtureWithSecondAttribute
{
}
[TestFixture]
public class MultipleFixtureSetUpAttributes
{
[OneTimeSetUp]
public void Init1()
{
}
[OneTimeSetUp]
public void Init2()
{
}
[Test] public void OneTest()
{
}
}
[TestFixture]
public class MultipleFixtureTearDownAttributes
{
[OneTimeTearDown]
public void Destroy1()
{
}
[OneTimeTearDown]
public void Destroy2()
{
}
[Test] public void OneTest()
{
}
}
// Base class used to ensure following classes
// all have at least one test
public class OneTestBase
{
[Test] public void OneTest()
{
}
}
[TestFixture]
public class PrivateSetUp : OneTestBase
{
[SetUp]
private void Setup()
{
}
}
[TestFixture]
public class ProtectedSetUp : OneTestBase
{
[SetUp]
protected void Setup()
{
}
}
[TestFixture]
public class StaticSetUp : OneTestBase
{
[SetUp]
public static void Setup()
{
}
}
[TestFixture]
public class SetUpWithReturnValue : OneTestBase
{
[SetUp]
public int Setup()
{
return 0;
}
}
[TestFixture]
public class SetUpWithParameters : OneTestBase
{
[SetUp]
public void Setup(int j)
{
}
}
[TestFixture]
public class PrivateTearDown : OneTestBase
{
[TearDown]
private void Teardown()
{
}
}
[TestFixture]
public class ProtectedTearDown : OneTestBase
{
[TearDown]
protected void Teardown()
{
}
}
[TestFixture]
public class StaticTearDown : OneTestBase
{
[SetUp]
public static void TearDown()
{
}
}
[TestFixture]
public class TearDownWithReturnValue : OneTestBase
{
[TearDown]
public int Teardown()
{
return 0;
}
}
[TestFixture]
public class TearDownWithParameters : OneTestBase
{
[TearDown]
public void Teardown(int j)
{
}
}
[TestFixture]
public class PrivateFixtureSetUp : OneTestBase
{
[OneTimeSetUp]
private void Setup()
{
}
}
[TestFixture]
public class ProtectedFixtureSetUp : OneTestBase
{
[OneTimeSetUp]
protected void Setup()
{
}
}
[TestFixture]
public class StaticFixtureSetUp : OneTestBase
{
[OneTimeSetUp]
public static void Setup()
{
}
}
[TestFixture]
public class FixtureSetUpWithReturnValue : OneTestBase
{
[OneTimeSetUp]
public int Setup()
{
return 0;
}
}
[TestFixture]
public class FixtureSetUpWithParameters : OneTestBase
{
[OneTimeSetUp]
public void Setup(int j)
{
}
}
[TestFixture]
public class PrivateFixtureTearDown : OneTestBase
{
[OneTimeTearDown]
private void Teardown()
{
}
}
[TestFixture]
public class ProtectedFixtureTearDown : OneTestBase
{
[OneTimeTearDown]
protected void Teardown()
{
}
}
[TestFixture]
public class StaticFixtureTearDown : OneTestBase
{
[OneTimeTearDown]
public static void Teardown()
{
}
}
[TestFixture]
public class FixtureTearDownWithReturnValue : OneTestBase
{
[OneTimeTearDown]
public int Teardown()
{
return 0;
}
}
[TestFixture]
public class FixtureTearDownWithParameters : OneTestBase
{
[OneTimeTearDown]
public void Teardown(int j)
{
}
}
#if !PORTABLE && !NETSTANDARD1_6
[TestFixture]
public class FixtureThatChangesTheCurrentPrincipal
{
[Test]
public void ChangeCurrentPrincipal()
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
GenericPrincipal principal = new GenericPrincipal( identity, new string[] { } );
System.Threading.Thread.CurrentPrincipal = principal;
}
}
#endif
[TestFixture(typeof(int))]
[TestFixture(typeof(string))]
public class GenericFixtureWithProperArgsProvided<T>
{
[Test]
public void SomeTest()
{
}
}
public class GenericFixtureWithNoTestFixtureAttribute<T>
{
[Test]
public void SomeTest()
{
}
}
[TestFixture]
public class GenericFixtureWithNoArgsProvided<T>
{
[Test]
public void SomeTest()
{
}
}
[TestFixture]
public abstract class AbstractFixtureBase
{
[Test]
public void SomeTest()
{
}
}
public class GenericFixtureDerivedFromAbstractFixtureWithNoArgsProvided<T> : AbstractFixtureBase
{
}
[TestFixture(typeof(int))]
[TestFixture(typeof(string))]
public class GenericFixtureDerivedFromAbstractFixtureWithArgsProvided<T> : AbstractFixtureBase
{
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace MRTutorial.Identity.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Linq.Expressions;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Query.Expressions;
using Microsoft.EntityFrameworkCore.Query.ExpressionVisitors;
using Microsoft.EntityFrameworkCore.Query.Sql;
using Pomelo.EntityFrameworkCore.MySql.Query.Expressions.Internal;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Utilities;
using Remotion.Linq.Clauses;
namespace Pomelo.EntityFrameworkCore.MySql.Query.Sql.Internal
{
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public class MySqlQuerySqlGenerator : DefaultQuerySqlGenerator, IMySqlExpressionVisitor
{
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public MySqlQuerySqlGenerator(
[NotNull] QuerySqlGeneratorDependencies dependencies,
[NotNull] SelectExpression selectExpression,
bool rowNumberPagingEnabled)
: base(dependencies, selectExpression)
{
if (rowNumberPagingEnabled)
{
var rowNumberPagingExpressionVisitor = new RowNumberPagingExpressionVisitor();
rowNumberPagingExpressionVisitor.Visit(selectExpression);
}
}
/// <summary>
/// Visit a BinaryExpression.
/// </summary>
/// <param name="binaryExpression"> The binary expression to visit. </param>
/// <returns>
/// An Expression.
/// </returns>
protected override Expression VisitBinary(BinaryExpression binaryExpression)
{
if (binaryExpression.Left is SqlFunctionExpression sqlFunctionExpression
&& (sqlFunctionExpression.FunctionName == "FREETEXT" || sqlFunctionExpression.FunctionName == "CONTAINS"))
{
Visit(binaryExpression.Left);
return binaryExpression;
}
return base.VisitBinary(binaryExpression);
}
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public override Expression VisitCrossJoinLateral(CrossJoinLateralExpression crossJoinLateralExpression)
{
Check.NotNull(crossJoinLateralExpression, nameof(crossJoinLateralExpression));
Sql.Append("CROSS APPLY ");
Visit(crossJoinLateralExpression.TableExpression);
return crossJoinLateralExpression;
}
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
protected override void GenerateLimitOffset(SelectExpression selectExpression)
{
if (selectExpression.Offset != null
&& selectExpression.OrderBy.Count == 0)
{
Sql.AppendLine().Append("ORDER BY (SELECT 1)");
}
base.GenerateLimitOffset(selectExpression);
}
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public virtual Expression VisitRowNumber(RowNumberExpression rowNumberExpression)
{
Check.NotNull(rowNumberExpression, nameof(rowNumberExpression));
Sql.Append("ROW_NUMBER() OVER(");
GenerateOrderBy(rowNumberExpression.Orderings);
Sql.Append(")");
return rowNumberExpression;
}
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public override Expression VisitSqlFunction(SqlFunctionExpression sqlFunctionExpression)
{
if (sqlFunctionExpression.FunctionName.StartsWith("@@", StringComparison.Ordinal))
{
Sql.Append(sqlFunctionExpression.FunctionName);
return sqlFunctionExpression;
}
if (sqlFunctionExpression.FunctionName == "COUNT"
&& sqlFunctionExpression.Type == typeof(long))
{
Visit(new SqlFunctionExpression("COUNT_BIG", typeof(long), sqlFunctionExpression.Arguments));
return sqlFunctionExpression;
}
return base.VisitSqlFunction(sqlFunctionExpression);
}
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
protected override Expression ApplyExplicitCastToBoolInProjectionOptimization(Expression expression)
{
var aliasedProjection = expression as AliasExpression;
var expressionToProcess = aliasedProjection?.Expression ?? expression;
var updatedExpression = ExplicitCastToBool(expressionToProcess);
return aliasedProjection != null
? new AliasExpression(aliasedProjection.Alias, updatedExpression)
: updatedExpression;
}
private static Expression ExplicitCastToBool(Expression expression)
=> ((expression as BinaryExpression)?.NodeType == ExpressionType.Coalesce || expression.NodeType == ExpressionType.Constant)
&& expression.Type.UnwrapNullableType() == typeof(bool)
? new ExplicitCastExpression(expression, expression.Type)
: expression;
private class RowNumberPagingExpressionVisitor : ExpressionVisitorBase
{
private const string RowNumberColumnName = "__RowNumber__";
private int _counter;
public override Expression Visit(Expression expression)
{
return expression is ExistsExpression existsExpression
? VisitExistExpression(existsExpression)
: expression is SelectExpression selectExpression
? VisitSelectExpression(selectExpression)
: base.Visit(expression);
}
private static bool RequiresRowNumberPaging(SelectExpression selectExpression)
=> selectExpression.Offset != null
&& !selectExpression.Projection.Any(p => p is RowNumberExpression);
private Expression VisitSelectExpression(SelectExpression selectExpression)
{
base.Visit(selectExpression);
if (!RequiresRowNumberPaging(selectExpression))
{
return selectExpression;
}
var subQuery = selectExpression.PushDownSubquery();
if (subQuery.Projection.Count > 0)
{
selectExpression.ExplodeStarProjection();
}
if (subQuery.OrderBy.Count == 0)
{
subQuery.AddToOrderBy(
new Ordering(new SqlFunctionExpression("@@RowCount", typeof(int)), OrderingDirection.Asc));
}
var innerRowNumberExpression = new AliasExpression(
RowNumberColumnName + (_counter != 0 ? $"{_counter}" : ""),
new RowNumberExpression(
subQuery.OrderBy
.Select(
o => new Ordering(
o.Expression is AliasExpression ae ? ae.Expression : o.Expression,
o.OrderingDirection))
.ToList()));
_counter++;
subQuery.ClearOrderBy();
subQuery.AddToProjection(innerRowNumberExpression, resetProjectStar: false);
var rowNumberReferenceExpression = new ColumnReferenceExpression(innerRowNumberExpression, subQuery);
var offset = subQuery.Offset ?? Expression.Constant(0);
if (subQuery.Offset != null)
{
selectExpression.AddToPredicate(
Expression.GreaterThan(
rowNumberReferenceExpression,
ApplyConversion(offset, rowNumberReferenceExpression.Type)));
subQuery.Offset = null;
}
if (subQuery.Limit != null)
{
var constantValue = (subQuery.Limit as ConstantExpression)?.Value;
var offsetValue = (offset as ConstantExpression)?.Value;
var limitExpression
= constantValue != null
&& offsetValue != null
? (Expression)Expression.Constant((int)offsetValue + (int)constantValue)
: Expression.Add(offset, subQuery.Limit);
selectExpression.AddToPredicate(
Expression.LessThanOrEqual(
rowNumberReferenceExpression,
ApplyConversion(limitExpression, rowNumberReferenceExpression.Type)));
subQuery.Limit = null;
}
return selectExpression;
}
private static Expression ApplyConversion(Expression expression, Type type)
{
return expression.Type != type ? Expression.Convert(expression, type) : expression;
}
private Expression VisitExistExpression(ExistsExpression existsExpression)
{
var newSubquery = (SelectExpression)Visit(existsExpression.Subquery);
if (newSubquery.Limit == null
&& newSubquery.Offset == null)
{
newSubquery.ClearOrderBy();
}
return new ExistsExpression(newSubquery);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System.Linq.Expressions;
using System;
using System.Diagnostics;
using System.Dynamic;
using System.Reflection;
using System.Runtime.CompilerServices;
using Microsoft.Scripting;
using Microsoft.Scripting.Actions;
using Microsoft.Scripting.Generation;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
using System.Threading;
using System.Collections.Generic;
namespace IronPython.Runtime.Binding {
using Ast = Expression;
using AstUtils = Microsoft.Scripting.Ast.Utils;
internal partial class MetaUserObject : MetaPythonObject, IPythonGetable {
#region IPythonGetable Members
public DynamicMetaObject GetMember(PythonGetMemberBinder/*!*/ member, DynamicMetaObject/*!*/ codeContext) {
return GetMemberWorker(member, codeContext);
}
#endregion
#region MetaObject Overrides
public override DynamicMetaObject/*!*/ BindGetMember(GetMemberBinder/*!*/ action) {
return GetMemberWorker(action, PythonContext.GetCodeContextMO(action));
}
public override DynamicMetaObject/*!*/ BindSetMember(SetMemberBinder/*!*/ action, DynamicMetaObject/*!*/ value) {
return new MetaSetBinderHelper(this, value, action).Bind(action.Name);
}
public override DynamicMetaObject/*!*/ BindDeleteMember(DeleteMemberBinder/*!*/ action) {
PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "DeleteMember");
PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, "DeleteMember");
return MakeDeleteMemberRule(
new DeleteBindingInfo(
action,
new DynamicMetaObject[] { this },
new ConditionalBuilder(action),
BindingHelpers.GetValidationInfo(this, PythonType)
)
);
}
#endregion
#region Get Member Helpers
/// <summary>
/// Provides the lookup logic for resolving a Python object. Subclasses
/// provide the actual logic for producing the binding result. Currently
/// there are two forms of the binding result: one is the DynamicMetaObject
/// form used for non-optimized bindings. The other is the Func of CallSite,
/// object, CodeContext, object form which is used for fast binding and
/// pre-compiled rules.
/// </summary>
internal abstract class GetOrInvokeBinderHelper<TResult> {
protected readonly IPythonObject _value;
protected bool _extensionMethodRestriction;
public GetOrInvokeBinderHelper(IPythonObject value) {
_value = value;
}
public TResult Bind(CodeContext context, string name) {
IPythonObject sdo = Value;
PythonTypeSlot foundSlot;
if (TryGetGetAttribute(context, sdo.PythonType, out foundSlot)) {
return BindGetAttribute(foundSlot);
}
// otherwise look the object according to Python rules:
// 1. 1st search the MRO of the type, and if it's there, and it's a get/set descriptor,
// return that value.
// 2. Look in the instance dictionary. If it's there return that value, otherwise return
// a value found during the MRO search. If no value was found during the MRO search then
// raise an exception.
// 3. fall back to __getattr__ if defined.
//
// Ultimately we cache the result of the MRO search based upon the type version. If we have
// a get/set descriptor we'll only ever use that directly. Otherwise if we have a get descriptor
// we'll first check the dictionary and then invoke the get descriptor. If we have no descriptor
// at all we'll just check the dictionary. If both lookups fail we'll raise an exception.
bool systemTypeResolution, extensionMethodResolution;
foundSlot = FindSlot(context, name, sdo, out systemTypeResolution, out extensionMethodResolution);
_extensionMethodRestriction = extensionMethodResolution;
if (sdo.PythonType.HasDictionary && (foundSlot == null || !foundSlot.IsSetDescriptor(context, sdo.PythonType))) {
MakeDictionaryAccess();
}
if (foundSlot != null) {
MakeSlotAccess(foundSlot, systemTypeResolution);
}
if (!IsFinal) {
// fall back to __getattr__ if it's defined.
// TODO: For InvokeMember we should probably do a fallback w/ an error suggestion
if (Value.PythonType.TryResolveSlot(context, "__getattr__", out PythonTypeSlot getattr)) {
MakeGetAttrAccess(getattr);
}
MakeTypeError();
}
return FinishRule();
}
protected abstract void MakeTypeError();
protected abstract void MakeGetAttrAccess(PythonTypeSlot getattr);
protected abstract bool IsFinal { get; }
protected abstract void MakeSlotAccess(PythonTypeSlot foundSlot, bool systemTypeResolution);
protected abstract TResult BindGetAttribute(PythonTypeSlot foundSlot);
protected abstract TResult FinishRule();
protected abstract void MakeDictionaryAccess();
public IPythonObject Value {
get {
return _value;
}
}
}
/// <summary>
/// GetBinder which produces a DynamicMetaObject. This binder always
/// successfully produces a DynamicMetaObject which can perform the requested get.
/// </summary>
private abstract class MetaGetBinderHelper : GetOrInvokeBinderHelper<DynamicMetaObject> {
private readonly DynamicMetaObject _self;
private readonly GetBindingInfo _bindingInfo;
protected readonly MetaUserObject _target;
private readonly DynamicMetaObjectBinder _binder;
protected readonly DynamicMetaObject _codeContext;
private string _resolution = "GetMember ";
public MetaGetBinderHelper(MetaUserObject target, DynamicMetaObjectBinder binder, DynamicMetaObject codeContext)
: base(target.Value) {
_target = target;
_self = _target.Restrict(Value.GetType());
_binder = binder;
_codeContext = codeContext;
_bindingInfo = new GetBindingInfo(
_binder,
new DynamicMetaObject[] { _target },
Ast.Variable(Expression.Type, "self"),
Ast.Variable(typeof(object), "lookupRes"),
new ConditionalBuilder(_binder),
BindingHelpers.GetValidationInfo(_self, Value.PythonType)
);
}
/// <summary>
/// Makes a rule which calls a user-defined __getattribute__ function and falls back to __getattr__ if that
/// raises an AttributeError.
///
/// slot is the __getattribute__ method to be called.
/// </summary>
private DynamicMetaObject/*!*/ MakeGetAttributeRule(GetBindingInfo/*!*/ info, IPythonObject/*!*/ obj, PythonTypeSlot/*!*/ slot, DynamicMetaObject codeContext) {
// if the type implements IDynamicMetaObjectProvider and we picked up it's __getattribute__ then we want to just
// dispatch to the base meta object (or to the default binder). an example of this is:
//
// class mc(type):
// def __getattr__(self, name):
// return 42
//
// class nc_ga(object):
// __metaclass__ = mc
//
// a = nc_ga.x # here we want to dispatch to the type's rule, not call __getattribute__ directly.
CodeContext context = PythonContext.GetPythonContext(info.Action).SharedContext;
Type finalType = obj.PythonType.FinalSystemType;
if (typeof(IDynamicMetaObjectProvider).IsAssignableFrom(finalType)) {
PythonTypeSlot baseSlot;
if (TryGetGetAttribute(context, DynamicHelpers.GetPythonTypeFromType(finalType), out baseSlot) && baseSlot == slot) {
return FallbackError();
}
}
// otherwise generate code into a helper function. This will do the slot lookup and exception
// handling for both __getattribute__ as well as __getattr__ if it exists.
PythonTypeSlot getattr;
obj.PythonType.TryResolveSlot(context, "__getattr__", out getattr);
DynamicMetaObject self = _target.Restrict(Value.GetType());
string methodName = BindingHelpers.IsNoThrow(info.Action) ? "GetAttributeNoThrow" : "GetAttribute";
return BindingHelpers.AddDynamicTestAndDefer(
info.Action,
new DynamicMetaObject(
Ast.Call(
typeof(UserTypeOps).GetMethod(methodName),
Ast.Constant(PythonContext.GetPythonContext(info.Action).SharedContext),
info.Args[0].Expression,
Ast.Constant(GetGetMemberName(info.Action)),
Ast.Constant(slot, typeof(PythonTypeSlot)),
Ast.Constant(getattr, typeof(PythonTypeSlot)),
Ast.Constant(new SiteLocalStorage<CallSite<Func<CallSite, CodeContext, object, string, object>>>())
),
self.Restrictions
),
info.Args,
info.Validation
);
}
protected abstract DynamicMetaObject FallbackError();
protected abstract DynamicMetaObject Fallback();
protected virtual Expression Invoke(Expression res) {
return Invoke(new DynamicMetaObject(res, BindingRestrictions.Empty)).Expression;
}
protected virtual DynamicMetaObject Invoke(DynamicMetaObject res) {
return res;
}
protected override DynamicMetaObject BindGetAttribute(PythonTypeSlot foundSlot) {
PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "User GetAttribute");
PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, "User GetAttribute");
return Invoke(MakeGetAttributeRule(_bindingInfo, Value, foundSlot, _codeContext));
}
protected override void MakeGetAttrAccess(PythonTypeSlot getattr) {
_resolution += "GetAttr ";
MakeGetAttrRule(_bindingInfo, GetWeakSlot(getattr), _codeContext);
}
protected override void MakeTypeError() {
_bindingInfo.Body.FinishCondition(FallbackError().Expression);
}
protected override bool IsFinal {
get { return _bindingInfo.Body.IsFinal; }
}
protected override DynamicMetaObject FinishRule() {
PerfTrack.NoteEvent(PerfTrack.Categories.Binding, _resolution);
PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, "UserGet");
DynamicMetaObject res = _bindingInfo.Body.GetMetaObject(_target);
res = new DynamicMetaObject(
Ast.Block(
new ParameterExpression[] { _bindingInfo.Self, _bindingInfo.Result },
Ast.Assign(_bindingInfo.Self, _self.Expression),
res.Expression
),
_self.Restrictions.Merge(res.Restrictions)
);
if (_extensionMethodRestriction) {
res = new DynamicMetaObject(
res.Expression,
res.Restrictions.Merge(((CodeContext)_codeContext.Value).ModuleContext.ExtensionMethods.GetRestriction(_codeContext.Expression))
);
}
return BindingHelpers.AddDynamicTestAndDefer(
_binder,
res,
new DynamicMetaObject[] { _target },
_bindingInfo.Validation
);
}
private void MakeGetAttrRule(GetBindingInfo/*!*/ info, Expression/*!*/ getattr, DynamicMetaObject codeContext) {
info.Body.AddCondition(
MakeGetAttrTestAndGet(info, getattr),
Invoke(MakeGetAttrCall(info, codeContext))
);
}
private Expression/*!*/ MakeGetAttrCall(GetBindingInfo/*!*/ info, DynamicMetaObject codeContext) {
Expression call = Ast.Dynamic(
PythonContext.GetPythonContext(info.Action).InvokeOne,
typeof(object),
PythonContext.GetCodeContext(info.Action),
info.Result,
Ast.Constant(GetGetMemberName(info.Action))
);
call = MaybeMakeNoThrow(info, call);
return call;
}
private Expression/*!*/ MaybeMakeNoThrow(GetBindingInfo/*!*/ info, Expression/*!*/ expr) {
if (BindingHelpers.IsNoThrow(info.Action)) {
DynamicMetaObject fallback = FallbackError();
ParameterExpression tmp = Ast.Variable(typeof(object), "getAttrRes");
expr = Ast.Block(
new ParameterExpression[] { tmp },
Ast.Block(
AstUtils.Try(
Ast.Assign(tmp, AstUtils.Convert(expr, typeof(object)))
).Catch(
typeof(MissingMemberException),
Ast.Assign(tmp, AstUtils.Convert(fallback.Expression, typeof(object)))
),
tmp
)
);
}
return expr;
}
protected override void MakeSlotAccess(PythonTypeSlot foundSlot, bool systemTypeResolution) {
_resolution += CompilerHelpers.GetType(foundSlot) + " ";
if (systemTypeResolution) {
_bindingInfo.Body.FinishCondition(Fallback().Expression);
} else {
MakeSlotAccess(foundSlot);
}
}
private void MakeSlotAccess(PythonTypeSlot dts) {
if (dts is ReflectedSlotProperty rsp) {
// we need to fall back to __getattr__ if the value is not defined, so call it and check the result.
_bindingInfo.Body.AddCondition(
Ast.NotEqual(
Ast.Assign(
_bindingInfo.Result,
Ast.ArrayAccess(
GetSlots(_target),
Ast.Constant(rsp.Index)
)
),
Ast.Field(null, typeof(Uninitialized).GetField(nameof(Uninitialized.Instance)))
),
Invoke(_bindingInfo.Result)
);
return;
}
if (dts is PythonTypeUserDescriptorSlot slot) {
_bindingInfo.Body.FinishCondition(
Ast.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.GetUserSlotValue)),
Ast.Constant(PythonContext.GetPythonContext(_bindingInfo.Action).SharedContext),
Ast.Convert(AstUtils.WeakConstant(slot), typeof(PythonTypeUserDescriptorSlot)),
_target.Expression,
Ast.Property(
Ast.Convert(
_bindingInfo.Self,
typeof(IPythonObject)),
PythonTypeInfo._IPythonObject.PythonType
)
)
);
}
// users can subclass PythonProperty so check the type explicitly
// and only in-line the ones we fully understand.
if (dts.GetType() == typeof(PythonProperty)) {
// properties are mutable so we generate code to get the value rather
// than burning it into the rule.
Expression getter = Ast.Property(
Ast.Convert(AstUtils.WeakConstant(dts), typeof(PythonProperty)),
"fget"
);
ParameterExpression tmpGetter = Ast.Variable(typeof(object), "tmpGet");
_bindingInfo.Body.AddVariable(tmpGetter);
_bindingInfo.Body.FinishCondition(
Ast.Block(
Ast.Assign(tmpGetter, getter),
Ast.Condition(
Ast.NotEqual(
tmpGetter,
Ast.Constant(null)
),
Invoke(
Ast.Dynamic(
PythonContext.GetPythonContext(_bindingInfo.Action).InvokeOne,
typeof(object),
Ast.Constant(PythonContext.GetPythonContext(_bindingInfo.Action).SharedContext),
tmpGetter,
_bindingInfo.Self
)
),
_binder.Throw(Ast.Call(typeof(PythonOps).GetMethod(nameof(PythonOps.UnreadableProperty))), typeof(object))
)
)
);
return;
}
Expression tryGet = Ast.Call(
PythonTypeInfo._PythonOps.SlotTryGetBoundValue,
Ast.Constant(PythonContext.GetPythonContext(_bindingInfo.Action).SharedContext),
Ast.Convert(AstUtils.WeakConstant(dts), typeof(PythonTypeSlot)),
AstUtils.Convert(_bindingInfo.Self, typeof(object)),
Ast.Property(
Ast.Convert(
_bindingInfo.Self,
typeof(IPythonObject)),
PythonTypeInfo._IPythonObject.PythonType
),
_bindingInfo.Result
);
Expression value = Invoke(_bindingInfo.Result);
if (dts.GetAlwaysSucceeds) {
_bindingInfo.Body.FinishCondition(
Ast.Block(tryGet, value)
);
} else {
_bindingInfo.Body.AddCondition(
tryGet,
value
);
}
}
protected override void MakeDictionaryAccess() {
_resolution += "Dictionary ";
FieldInfo fi = _target.LimitType.GetField(NewTypeMaker.DictFieldName);
Expression dict;
if (fi != null) {
dict = Ast.Field(
Ast.Convert(_bindingInfo.Self, _target.LimitType),
fi
);
} else {
dict = Ast.Property(
Ast.Convert(_bindingInfo.Self, typeof(IPythonObject)),
PythonTypeInfo._IPythonObject.Dict
);
}
var instanceNames = Value.PythonType.GetOptimizedInstanceNames();
int instanceIndex;
if (instanceNames != null && (instanceIndex = instanceNames.IndexOf(GetGetMemberName(_bindingInfo.Action))) != -1) {
// optimized instance value access
_bindingInfo.Body.AddCondition(
Ast.Call(
typeof(UserTypeOps).GetMethod(nameof(UserTypeOps.TryGetDictionaryValue)),
dict,
AstUtils.Constant(GetGetMemberName(_bindingInfo.Action)),
Ast.Constant(Value.PythonType.GetOptimizedInstanceVersion()),
Ast.Constant(instanceIndex),
_bindingInfo.Result
),
Invoke(new DynamicMetaObject(_bindingInfo.Result, BindingRestrictions.Empty)).Expression
);
} else {
_bindingInfo.Body.AddCondition(
Ast.AndAlso(
Ast.NotEqual(
dict,
Ast.Constant(null)
),
Ast.Call(
dict,
PythonTypeInfo._PythonDictionary.TryGetvalue,
AstUtils.Constant(GetGetMemberName(_bindingInfo.Action)),
_bindingInfo.Result
)
),
Invoke(new DynamicMetaObject(_bindingInfo.Result, BindingRestrictions.Empty)).Expression
);
}
}
public Expression Expression {
get {
return _target.Expression;
}
}
}
internal class FastGetBinderHelper : GetOrInvokeBinderHelper<FastGetBase> {
private readonly int _version;
private readonly PythonGetMemberBinder/*!*/ _binder;
private readonly CallSite<Func<CallSite, object, CodeContext, object>> _site;
private readonly CodeContext _context;
private bool _dictAccess;
private PythonTypeSlot _slot;
private PythonTypeSlot _getattrSlot;
public FastGetBinderHelper(CodeContext/*!*/ context, CallSite<Func<CallSite, object, CodeContext, object>>/*!*/ site, IPythonObject/*!*/ value, PythonGetMemberBinder/*!*/ binder)
: base(value) {
Assert.NotNull(value, binder, context, site);
_version = value.PythonType.Version;
_binder = binder;
_site = site;
_context = context;
}
protected override void MakeTypeError() {
}
protected override bool IsFinal {
get { return _slot != null && _slot.GetAlwaysSucceeds; }
}
protected override void MakeSlotAccess(PythonTypeSlot foundSlot, bool systemTypeResolution) {
if (systemTypeResolution) {
if (!_binder.Context.Binder.TryResolveSlot(_context, Value.PythonType, Value.PythonType, _binder.Name, out foundSlot)) {
Debug.Assert(false);
}
}
_slot = foundSlot;
}
public FastBindResult<Func<CallSite, object, CodeContext, object>> GetBinding(CodeContext context, string name) {
var cachedGets = GetCachedGets();
var key = CachedGetKey.Make(name, context.ModuleContext.ExtensionMethods);
FastGetBase dlg;
lock (cachedGets) {
if (!cachedGets.TryGetValue(key, out dlg) || !dlg.IsValid(Value.PythonType)) {
var binding = Bind(context, name);
if (binding != null) {
dlg = binding;
if (dlg.ShouldCache) {
cachedGets[key] = dlg;
}
}
}
}
if (dlg != null && dlg.ShouldUseNonOptimizedSite) {
return new FastBindResult<Func<CallSite, object, CodeContext, object>>(dlg._func, dlg.ShouldCache);
}
return new FastBindResult<Func<CallSite, object, CodeContext, object>>();
}
private Dictionary<CachedGetKey, FastGetBase> GetCachedGets() {
if (_binder.IsNoThrow) {
var cachedGets = Value.PythonType._cachedTryGets;
if (cachedGets == null) {
Interlocked.CompareExchange(
ref Value.PythonType._cachedTryGets,
new Dictionary<CachedGetKey, FastGetBase>(),
null);
cachedGets = Value.PythonType._cachedTryGets;
}
return cachedGets;
} else {
var cachedGets = Value.PythonType._cachedGets;
if (cachedGets == null) {
Interlocked.CompareExchange(
ref Value.PythonType._cachedGets,
new Dictionary<CachedGetKey, FastGetBase>(),
null);
cachedGets = Value.PythonType._cachedGets;
}
return cachedGets;
}
}
protected override FastGetBase FinishRule() {
GetMemberDelegates func;
if (_slot is ReflectedSlotProperty rsp) {
Debug.Assert(!_dictAccess); // properties for __slots__ are get/set descriptors so we should never access the dictionary.
func = new GetMemberDelegates(OptimizedGetKind.PropertySlot, Value.PythonType, _binder, _binder.Name, _version, _slot, _getattrSlot, rsp.Getter, FallbackError(), _context.ModuleContext.ExtensionMethods);
} else if (_dictAccess) {
if (_slot is PythonTypeUserDescriptorSlot) {
func = new GetMemberDelegates(OptimizedGetKind.UserSlotDict, Value.PythonType, _binder, _binder.Name, _version, _slot, _getattrSlot, null, FallbackError(), _context.ModuleContext.ExtensionMethods);
} else {
func = new GetMemberDelegates(OptimizedGetKind.SlotDict, Value.PythonType, _binder, _binder.Name, _version, _slot, _getattrSlot, null, FallbackError(), _context.ModuleContext.ExtensionMethods);
}
} else {
if (_slot is PythonTypeUserDescriptorSlot) {
func = new GetMemberDelegates(OptimizedGetKind.UserSlotOnly, Value.PythonType, _binder, _binder.Name, _version, _slot, _getattrSlot, null, FallbackError(), _context.ModuleContext.ExtensionMethods);
} else {
func = new GetMemberDelegates(OptimizedGetKind.SlotOnly, Value.PythonType, _binder, _binder.Name, _version, _slot, _getattrSlot, null, FallbackError(), _context.ModuleContext.ExtensionMethods);
}
}
return func;
}
private Func<CallSite, object, CodeContext, object> FallbackError() {
Type finalType = Value.PythonType.FinalSystemType;
if (typeof(IDynamicMetaObjectProvider).IsAssignableFrom(finalType)) {
return ((IFastGettable)Value).MakeGetBinding(_site, _binder, _context, _binder.Name);
}
if (_binder.IsNoThrow) {
return (site, self, context) => OperationFailed.Value;
}
string name = _binder.Name;
return (site, self, context) => { throw PythonOps.AttributeErrorForMissingAttribute(((IPythonObject)self).PythonType.Name, name); };
}
protected override void MakeDictionaryAccess() {
_dictAccess = true;
}
protected override FastGetBase BindGetAttribute(PythonTypeSlot foundSlot) {
Type finalType = Value.PythonType.FinalSystemType;
if (typeof(IDynamicMetaObjectProvider).IsAssignableFrom(finalType)) {
Debug.Assert(Value is IFastGettable);
PythonTypeSlot baseSlot;
if (TryGetGetAttribute(_context, DynamicHelpers.GetPythonTypeFromType(finalType), out baseSlot) &&
baseSlot == foundSlot) {
return new ChainedUserGet(_binder, _version, FallbackError());
}
}
PythonTypeSlot getattr;
Value.PythonType.TryResolveSlot(_context, "__getattr__", out getattr);
return new GetAttributeDelegates(_binder, _binder.Name, _version, foundSlot, getattr);
}
protected override void MakeGetAttrAccess(PythonTypeSlot getattr) {
_getattrSlot = getattr;
}
}
private class GetBinderHelper : MetaGetBinderHelper {
private readonly DynamicMetaObjectBinder _binder;
public GetBinderHelper(MetaUserObject target, DynamicMetaObjectBinder binder, DynamicMetaObject codeContext)
: base(target, binder, codeContext) {
_binder = binder;
}
protected override DynamicMetaObject Fallback() {
return GetMemberFallback(_target, _binder, _codeContext);
}
protected override DynamicMetaObject FallbackError() {
return _target.FallbackGetError(_binder, _codeContext);
}
}
private class InvokeBinderHelper : MetaGetBinderHelper {
private readonly InvokeMemberBinder _binder;
private readonly DynamicMetaObject[] _args;
public InvokeBinderHelper(MetaUserObject target, InvokeMemberBinder binder, DynamicMetaObject[] args, DynamicMetaObject codeContext)
: base(target, binder, codeContext) {
_binder = binder;
_args = args;
}
protected override DynamicMetaObject Fallback() {
return _binder.FallbackInvokeMember(_target, _args);
}
protected override DynamicMetaObject FallbackError() {
if (_target._baseMetaObject != null) {
return _target._baseMetaObject.BindInvokeMember(_binder, _args);
}
return Fallback();
}
protected override DynamicMetaObject Invoke(DynamicMetaObject res) {
return _binder.FallbackInvoke(res, _args, null);
}
}
private DynamicMetaObject GetMemberWorker(DynamicMetaObjectBinder/*!*/ member, DynamicMetaObject codeContext) {
return new GetBinderHelper(this, member, codeContext).Bind((CodeContext)codeContext.Value, GetGetMemberName(member));
}
/// <summary>
/// Checks to see if this type has __getattribute__ that overrides all other attribute lookup.
///
/// This is more complex then it needs to be. The problem is that when we have a
/// mixed new-style/old-style class we have a weird __getattribute__ defined. When
/// we always dispatch through rules instead of PythonTypes it should be easy to remove
/// this.
/// </summary>
private static bool TryGetGetAttribute(CodeContext/*!*/ context, PythonType/*!*/ type, out PythonTypeSlot dts) {
if (type.TryResolveSlot(context, "__getattribute__", out dts)) {
if (!(dts is BuiltinMethodDescriptor bmd) || bmd.DeclaringType != typeof(object) ||
bmd.Template.Targets.Count != 1 ||
bmd.Template.Targets[0].DeclaringType != typeof(ObjectOps) ||
bmd.Template.Targets[0].Name != "__getattribute__") {
return dts != null;
}
}
return false;
}
private static MethodCallExpression/*!*/ MakeGetAttrTestAndGet(GetBindingInfo/*!*/ info, Expression/*!*/ getattr) {
return Ast.Call(
PythonTypeInfo._PythonOps.SlotTryGetBoundValue,
AstUtils.Constant(PythonContext.GetPythonContext(info.Action).SharedContext),
AstUtils.Convert(getattr, typeof(PythonTypeSlot)),
AstUtils.Convert(info.Self, typeof(object)),
Ast.Convert(
Ast.Property(
Ast.Convert(
info.Self,
typeof(IPythonObject)),
PythonTypeInfo._IPythonObject.PythonType
),
typeof(PythonType)
),
info.Result
);
}
private static Expression/*!*/ GetWeakSlot(PythonTypeSlot slot) {
return AstUtils.Convert(AstUtils.WeakConstant(slot), typeof(PythonTypeSlot));
}
private static Expression/*!*/ MakeTypeError(DynamicMetaObjectBinder binder, string/*!*/ name, string/*!*/ typeName) {
return binder.Throw(
Ast.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.AttributeErrorForMissingAttribute), new Type[] { typeof(string), typeof(string) }),
AstUtils.Constant(typeName),
AstUtils.Constant(name)
),
typeof(object)
);
}
#endregion
#region Set Member Helpers
internal abstract class SetBinderHelper<TResult> {
private readonly IPythonObject/*!*/ _instance;
private readonly object _value;
protected readonly CodeContext/*!*/ _context;
public SetBinderHelper(CodeContext/*!*/ context, IPythonObject/*!*/ instance, object value) {
Assert.NotNull(context, instance);
_instance = instance;
_value = value;
_context = context;
}
public TResult Bind(string name) {
bool bound = false;
// call __setattr__ if it exists
PythonTypeSlot dts;
if (_instance.PythonType.TryResolveSlot(_context, "__setattr__", out dts) && !IsStandardObjectMethod(dts)) {
// skip the fake __setattr__ on mixed new-style/old-style types
if (dts != null) {
MakeSetAttrTarget(dts);
bound = true;
}
}
if (!bound) {
// then see if we have a set descriptor
bool systemTypeResolution, extensionMethodResolution;
dts = FindSlot(_context, name, _instance, out systemTypeResolution, out extensionMethodResolution);
if (dts is ReflectedSlotProperty rsp) {
MakeSlotsSetTarget(rsp);
bound = true;
} else if (dts != null && dts.IsSetDescriptor(_context, _instance.PythonType)) {
MakeSlotSetOrFallback(dts, systemTypeResolution);
bound = systemTypeResolution || dts.GetType() == typeof(PythonProperty); // the only slot we currently optimize in MakeSlotSet
}
}
if (!bound) {
// finally if we have a dictionary set the value there.
if (_instance.PythonType.HasDictionary) {
MakeDictionarySetTarget();
} else {
MakeFallback();
}
}
return Finish();
}
public IPythonObject Instance {
get {
return _instance;
}
}
public object Value {
get {
return _value;
}
}
protected abstract TResult Finish();
protected abstract void MakeSetAttrTarget(PythonTypeSlot dts);
protected abstract void MakeSlotsSetTarget(ReflectedSlotProperty prop);
protected abstract void MakeSlotSetOrFallback(PythonTypeSlot dts, bool systemTypeResolution);
protected abstract void MakeDictionarySetTarget();
protected abstract void MakeFallback();
}
internal class FastSetBinderHelper<TValue> : SetBinderHelper<SetMemberDelegates<TValue>> {
private readonly PythonSetMemberBinder _binder;
private readonly int _version;
private PythonTypeSlot _setattrSlot;
private ReflectedSlotProperty _slotProp;
private bool _unsupported, _dictSet;
public FastSetBinderHelper(CodeContext context, IPythonObject self, object value, PythonSetMemberBinder binder)
: base(context, self, value) {
_binder = binder;
_version = self.PythonType.Version;
}
protected override SetMemberDelegates<TValue> Finish() {
if (_unsupported) {
return new SetMemberDelegates<TValue>(_context, Instance.PythonType, OptimizedSetKind.None, _binder.Name, _version, _setattrSlot, null);
} else if (_setattrSlot != null) {
return new SetMemberDelegates<TValue>(_context, Instance.PythonType, OptimizedSetKind.SetAttr, _binder.Name, _version, _setattrSlot, null);
} else if (_slotProp != null) {
return new SetMemberDelegates<TValue>(_context, Instance.PythonType, OptimizedSetKind.UserSlot, _binder.Name, _version, null, _slotProp.Setter);
} else if(_dictSet) {
return new SetMemberDelegates<TValue>(_context, Instance.PythonType, OptimizedSetKind.SetDict, _binder.Name, _version, null, null);
} else {
return new SetMemberDelegates<TValue>(_context, Instance.PythonType, OptimizedSetKind.Error, _binder.Name, _version, null, null);
}
}
public FastBindResult<Func<CallSite, object, TValue, object>> MakeSet() {
var cachedSets = GetCachedSets();
FastSetBase dlg;
lock (cachedSets) {
var kvp = new SetMemberKey(typeof(TValue), _binder.Name);
if (!cachedSets.TryGetValue(kvp, out dlg) || dlg._version != Instance.PythonType.Version) {
dlg = Bind(_binder.Name);
if (dlg != null) {
cachedSets[kvp] = dlg;
}
}
}
if (dlg.ShouldUseNonOptimizedSite) {
return new FastBindResult<Func<CallSite, object, TValue, object>>((Func<CallSite, object, TValue, object>)(object)dlg._func, false);
}
return new FastBindResult<Func<CallSite, object, TValue, object>>();
}
private Dictionary<SetMemberKey, FastSetBase> GetCachedSets() {
var cachedSets = Instance.PythonType._cachedSets;
if (cachedSets == null) {
Interlocked.CompareExchange(
ref Instance.PythonType._cachedSets,
new Dictionary<SetMemberKey, FastSetBase>(),
null);
cachedSets = Instance.PythonType._cachedSets;
}
return cachedSets;
}
protected override void MakeSlotSetOrFallback(PythonTypeSlot dts, bool systemTypeResolution) {
_unsupported = true;
}
protected override void MakeSlotsSetTarget(ReflectedSlotProperty prop) {
_slotProp = prop;
}
protected override void MakeFallback() {
}
protected override void MakeSetAttrTarget(PythonTypeSlot dts) {
_setattrSlot = dts;
}
protected override void MakeDictionarySetTarget() {
_dictSet = true;
}
}
internal class MetaSetBinderHelper : SetBinderHelper<DynamicMetaObject> {
private readonly MetaUserObject/*!*/ _target;
private readonly DynamicMetaObject/*!*/ _value;
private readonly SetBindingInfo _info;
private DynamicMetaObject _result;
private string _resolution = "SetMember ";
public MetaSetBinderHelper(MetaUserObject/*!*/ target, DynamicMetaObject/*!*/ value, SetMemberBinder/*!*/ binder)
: base(PythonContext.GetPythonContext(binder).SharedContext, target.Value, value.Value) {
Assert.NotNull(target, value, binder);
_target = target;
_value = value;
_info = new SetBindingInfo(
binder,
new DynamicMetaObject[] { target, value },
new ConditionalBuilder(binder),
BindingHelpers.GetValidationInfo(target, Instance.PythonType)
);
}
protected override void MakeSetAttrTarget(PythonTypeSlot dts) {
ParameterExpression tmp = Ast.Variable(typeof(object), "boundVal");
_info.Body.AddVariable(tmp);
_info.Body.AddCondition(
Ast.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.SlotTryGetValue)),
AstUtils.Constant(PythonContext.GetPythonContext(_info.Action).SharedContext),
AstUtils.Convert(AstUtils.WeakConstant(dts), typeof(PythonTypeSlot)),
AstUtils.Convert(_info.Args[0].Expression, typeof(object)),
AstUtils.Convert(AstUtils.WeakConstant(Instance.PythonType), typeof(PythonType)),
tmp
),
Ast.Dynamic(
PythonContext.GetPythonContext(_info.Action).Invoke(
new CallSignature(2)
),
typeof(object),
PythonContext.GetCodeContext(_info.Action),
tmp,
AstUtils.Constant(_info.Action.Name),
_info.Args[1].Expression
)
);
_info.Body.FinishCondition(
FallbackSetError(_info.Action, _info.Args[1]).Expression
);
_result = _info.Body.GetMetaObject(_target, _value);
_resolution += "SetAttr ";
}
protected override DynamicMetaObject Finish() {
PerfTrack.NoteEvent(PerfTrack.Categories.Binding, _resolution);
PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, "UserSet");
Debug.Assert(_result != null);
_result = new DynamicMetaObject(
_result.Expression,
_target.Restrict(Instance.GetType()).Restrictions.Merge(_result.Restrictions)
);
Debug.Assert(!_result.Expression.Type.IsValueType);
return BindingHelpers.AddDynamicTestAndDefer(
_info.Action,
_result,
new DynamicMetaObject[] { _target, _value },
_info.Validation
);
}
protected override void MakeFallback() {
_info.Body.FinishCondition(
FallbackSetError(_info.Action, _value).Expression
);
_result = _info.Body.GetMetaObject(_target, _value);
}
protected override void MakeDictionarySetTarget() {
_resolution += "Dictionary ";
FieldInfo fi = _info.Args[0].LimitType.GetField(NewTypeMaker.DictFieldName);
if (fi != null) {
FieldInfo classField = _info.Args[0].LimitType.GetField(NewTypeMaker.ClassFieldName);
var optInstanceNames = Instance.PythonType.GetOptimizedInstanceNames();
int keysIndex;
if (classField != null && optInstanceNames != null && (keysIndex = optInstanceNames.IndexOf(_info.Action.Name)) != -1) {
// optimized access which can read directly into an object array avoiding a dictionary lookup.
// return UserTypeOps.FastSetDictionaryValue(this._class, ref this._dict, name, value, keysVersion, keysIndex);
_info.Body.FinishCondition(
Ast.Call(
typeof(UserTypeOps).GetMethod(nameof(UserTypeOps.FastSetDictionaryValueOptimized)),
Ast.Field(
Ast.Convert(_info.Args[0].Expression, _info.Args[0].LimitType),
classField
),
Ast.Field(
Ast.Convert(_info.Args[0].Expression, _info.Args[0].LimitType),
fi
),
AstUtils.Constant(_info.Action.Name),
AstUtils.Convert(_info.Args[1].Expression, typeof(object)),
Ast.Constant(Instance.PythonType.GetOptimizedInstanceVersion()),
Ast.Constant(keysIndex)
)
);
} else {
// return UserTypeOps.FastSetDictionaryValue(ref this._dict, name, value);
_info.Body.FinishCondition(
Ast.Call(
typeof(UserTypeOps).GetMethod(nameof(UserTypeOps.FastSetDictionaryValue)),
Ast.Field(
Ast.Convert(_info.Args[0].Expression, _info.Args[0].LimitType),
fi
),
AstUtils.Constant(_info.Action.Name),
AstUtils.Convert(_info.Args[1].Expression, typeof(object))
)
);
}
} else {
// return UserTypeOps.SetDictionaryValue(rule.Parameters[0], name, value);
_info.Body.FinishCondition(
Ast.Call(
typeof(UserTypeOps).GetMethod(nameof(UserTypeOps.SetDictionaryValue)),
Ast.Convert(_info.Args[0].Expression, typeof(IPythonObject)),
AstUtils.Constant(_info.Action.Name),
AstUtils.Convert(_info.Args[1].Expression, typeof(object))
)
);
}
_result = _info.Body.GetMetaObject(_target, _value);
}
protected override void MakeSlotSetOrFallback(PythonTypeSlot dts, bool systemTypeResolution) {
if (systemTypeResolution) {
_result = _target.Fallback(_info.Action, _value);
} else {
_result = MakeSlotSet(_info, dts);
}
}
protected override void MakeSlotsSetTarget(ReflectedSlotProperty prop) {
_resolution += "Slot ";
MakeSlotsSetTargetHelper(_info, prop, _value.Expression);
_result = _info.Body.GetMetaObject(_target, _value);
}
/// <summary>
/// Helper for falling back - if we have a base object fallback to it first (which can
/// then fallback to the calling site), otherwise fallback to the calling site.
/// </summary>
private DynamicMetaObject/*!*/ FallbackSetError(SetMemberBinder/*!*/ action, DynamicMetaObject/*!*/ value) {
if (_target._baseMetaObject != null) {
return _target._baseMetaObject.BindSetMember(action, value);
} else if (action is PythonSetMemberBinder) {
return new DynamicMetaObject(
MakeTypeError(action, action.Name, Instance.PythonType.Name),
BindingRestrictions.Empty
);
}
return _info.Action.FallbackSetMember(_target.Restrict(_target.GetLimitType()), value);
}
}
private static bool IsStandardObjectMethod(PythonTypeSlot dts) {
if (!(dts is BuiltinMethodDescriptor bmd)) return false;
return bmd.Template.Targets[0].DeclaringType == typeof(ObjectOps);
}
private static void MakeSlotsDeleteTarget(MemberBindingInfo/*!*/ info, ReflectedSlotProperty/*!*/ rsp) {
MakeSlotsSetTargetHelper(info, rsp, Ast.Field(null, typeof(Uninitialized).GetField(nameof(Uninitialized.Instance))));
}
private static void MakeSlotsSetTargetHelper(MemberBindingInfo/*!*/ info, ReflectedSlotProperty/*!*/ rsp, Expression/*!*/ value) {
// type has __slots__ defined for this member, call the setter directly
ParameterExpression tmp = Ast.Variable(typeof(object), "res");
info.Body.AddVariable(tmp);
info.Body.FinishCondition(
Ast.Block(
Ast.Assign(
tmp,
Ast.Convert(
Ast.Assign(
Ast.ArrayAccess(
GetSlots(info.Args[0]),
AstUtils.Constant(rsp.Index)
),
AstUtils.Convert(value, typeof(object))
),
tmp.Type
)
),
tmp
)
);
}
private static DynamicMetaObject MakeSlotSet(SetBindingInfo/*!*/ info, PythonTypeSlot/*!*/ dts) {
ParameterExpression tmp = Ast.Variable(info.Args[1].Expression.Type, "res");
info.Body.AddVariable(tmp);
// users can subclass PythonProperty so check the type explicitly
// and only in-line the ones we fully understand.
if (dts.GetType() == typeof(PythonProperty)) {
// properties are mutable so we generate code to get the value rather
// than burning it into the rule.
Expression setter = Ast.Property(
Ast.Convert(AstUtils.WeakConstant(dts), typeof(PythonProperty)),
"fset"
);
ParameterExpression tmpSetter = Ast.Variable(typeof(object), "tmpSet");
info.Body.AddVariable(tmpSetter);
info.Body.FinishCondition(
Ast.Block(
Ast.Assign(tmpSetter, setter),
Ast.Condition(
Ast.NotEqual(
tmpSetter,
AstUtils.Constant(null)
),
Ast.Block(
Ast.Assign(tmp, info.Args[1].Expression),
Ast.Dynamic(
PythonContext.GetPythonContext(info.Action).InvokeOne,
typeof(object),
AstUtils.Constant(PythonContext.GetPythonContext(info.Action).SharedContext),
tmpSetter,
info.Args[0].Expression,
AstUtils.Convert(tmp, typeof(object))
),
Ast.Convert(
tmp,
typeof(object)
)
),
info.Action.Throw(Ast.Call(typeof(PythonOps).GetMethod(nameof(PythonOps.UnsetableProperty))), typeof(object))
)
)
);
return info.Body.GetMetaObject();
}
CodeContext context = PythonContext.GetPythonContext(info.Action).SharedContext;
Debug.Assert(context != null);
info.Body.AddCondition(
Ast.Block(
Ast.Assign(tmp, info.Args[1].Expression),
Ast.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.SlotTrySetValue)),
AstUtils.Constant(context),
AstUtils.Convert(AstUtils.WeakConstant(dts), typeof(PythonTypeSlot)),
AstUtils.Convert(info.Args[0].Expression, typeof(object)),
Ast.Convert(
Ast.Property(
Ast.Convert(
info.Args[0].Expression,
typeof(IPythonObject)),
PythonTypeInfo._IPythonObject.PythonType
),
typeof(PythonType)
),
AstUtils.Convert(tmp, typeof(object))
)
),
AstUtils.Convert(tmp, typeof(object))
);
return null;
}
#endregion
#region Delete Member Helpers
private DynamicMetaObject/*!*/ MakeDeleteMemberRule(DeleteBindingInfo/*!*/ info) {
CodeContext context = PythonContext.GetPythonContext(info.Action).SharedContext;
DynamicMetaObject self = info.Args[0].Restrict(info.Args[0].GetRuntimeType());
IPythonObject sdo = info.Args[0].Value as IPythonObject;
if (info.Action.Name == "__class__") {
return new DynamicMetaObject(
info.Action.Throw(
Ast.New(
typeof(TypeErrorException).GetConstructor(new Type[] { typeof(string) }),
AstUtils.Constant("can't delete __class__ attribute")
),
typeof(object)
),
self.Restrictions
);
}
// call __delattr__ if it exists
PythonTypeSlot dts;
if (sdo.PythonType.TryResolveSlot(context, "__delattr__", out dts) && !IsStandardObjectMethod(dts)) {
MakeDeleteAttrTarget(info, sdo, dts);
}
// then see if we have a delete descriptor
sdo.PythonType.TryResolveSlot(context, info.Action.Name, out dts);
if (dts is ReflectedSlotProperty rsp) {
MakeSlotsDeleteTarget(info, rsp);
}
if (!info.Body.IsFinal && dts != null) {
MakeSlotDelete(info, dts);
}
if (!info.Body.IsFinal && sdo.PythonType.HasDictionary) {
// finally if we have a dictionary set the value there.
MakeDictionaryDeleteTarget(info);
}
if (!info.Body.IsFinal) {
// otherwise fallback
info.Body.FinishCondition(
FallbackDeleteError(info.Action, info.Args).Expression
);
}
DynamicMetaObject res = info.Body.GetMetaObject(info.Args);
res = new DynamicMetaObject(
res.Expression,
self.Restrictions.Merge(res.Restrictions)
);
return BindingHelpers.AddDynamicTestAndDefer(
info.Action,
res,
info.Args,
info.Validation
);
}
private static DynamicMetaObject MakeSlotDelete(DeleteBindingInfo/*!*/ info, PythonTypeSlot/*!*/ dts) {
// users can subclass PythonProperty so check the type explicitly
// and only in-line the ones we fully understand.
if (dts.GetType() == typeof(PythonProperty)) {
// properties are mutable so we generate code to get the value rather
// than burning it into the rule.
Expression deleter = Ast.Property(
Ast.Convert(AstUtils.WeakConstant(dts), typeof(PythonProperty)),
"fdel"
);
ParameterExpression tmpDeleter = Ast.Variable(typeof(object), "tmpDel");
info.Body.AddVariable(tmpDeleter);
info.Body.FinishCondition(
Ast.Block(
Ast.Assign(tmpDeleter, deleter),
Ast.Condition(
Ast.NotEqual(
tmpDeleter,
AstUtils.Constant(null)
),
Ast.Dynamic(
PythonContext.GetPythonContext(info.Action).InvokeOne,
typeof(object),
AstUtils.Constant(PythonContext.GetPythonContext(info.Action).SharedContext),
tmpDeleter,
info.Args[0].Expression
),
info.Action.Throw(Ast.Call(typeof(PythonOps).GetMethod(nameof(PythonOps.UndeletableProperty))), typeof(object))
)
)
);
return info.Body.GetMetaObject();
}
info.Body.AddCondition(
Ast.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.SlotTryDeleteValue)),
AstUtils.Constant(PythonContext.GetPythonContext(info.Action).SharedContext),
AstUtils.Convert(AstUtils.WeakConstant(dts), typeof(PythonTypeSlot)),
AstUtils.Convert(info.Args[0].Expression, typeof(object)),
Ast.Convert(
Ast.Property(
Ast.Convert(
info.Args[0].Expression,
typeof(IPythonObject)),
PythonTypeInfo._IPythonObject.PythonType
),
typeof(PythonType)
)
),
AstUtils.Constant(null)
);
return null;
}
private static void MakeDeleteAttrTarget(DeleteBindingInfo/*!*/ info, IPythonObject self, PythonTypeSlot dts) {
ParameterExpression tmp = Ast.Variable(typeof(object), "boundVal");
info.Body.AddVariable(tmp);
// call __delattr__
info.Body.AddCondition(
Ast.Call(
PythonTypeInfo._PythonOps.SlotTryGetBoundValue,
AstUtils.Constant(PythonContext.GetPythonContext(info.Action).SharedContext),
AstUtils.Convert(AstUtils.WeakConstant(dts), typeof(PythonTypeSlot)),
AstUtils.Convert(info.Args[0].Expression, typeof(object)),
AstUtils.Convert(AstUtils.WeakConstant(self.PythonType), typeof(PythonType)),
tmp
),
DynamicExpression.Dynamic(
PythonContext.GetPythonContext(info.Action).InvokeOne,
typeof(object),
PythonContext.GetCodeContext(info.Action),
tmp,
AstUtils.Constant(info.Action.Name)
)
);
}
private static void MakeDictionaryDeleteTarget(DeleteBindingInfo/*!*/ info) {
info.Body.FinishCondition(
Ast.Call(
typeof(UserTypeOps).GetMethod(nameof(UserTypeOps.RemoveDictionaryValue)),
Ast.Convert(info.Args[0].Expression, typeof(IPythonObject)),
AstUtils.Constant(info.Action.Name)
)
);
}
#endregion
#region Common Helpers
/// <summary>
/// Looks up the associated PythonTypeSlot from the object. Indicates if the result
/// came from a standard .NET type in which case we will fallback to the sites binder.
/// </summary>
private static PythonTypeSlot FindSlot(CodeContext/*!*/ context, string/*!*/ name, IPythonObject/*!*/ sdo, out bool systemTypeResolution, out bool extensionMethodResolution) {
PythonTypeSlot foundSlot = null;
systemTypeResolution = false; // if we pick up the property from a System type we fallback
foreach (PythonType pt in sdo.PythonType.ResolutionOrder) {
if (pt.TryLookupSlot(context, name, out foundSlot)) {
// use our built-in binding for ClassMethodDescriptors rather than falling back
if (!(foundSlot is ClassMethodDescriptor)) {
systemTypeResolution = pt.IsSystemType;
}
break;
}
}
extensionMethodResolution = false;
if (foundSlot == null) {
extensionMethodResolution = true;
var extMethods = context.ModuleContext.ExtensionMethods.GetBinder(context.LanguageContext).GetMember(MemberRequestKind.Get, sdo.PythonType.UnderlyingSystemType, name);
if (extMethods.Count > 0) {
foundSlot = PythonTypeOps.GetSlot(extMethods, name, false);
}
}
return foundSlot;
}
#endregion
#region BindingInfo classes
private class MemberBindingInfo {
public readonly ConditionalBuilder/*!*/ Body;
public readonly DynamicMetaObject/*!*/[]/*!*/ Args;
public readonly ValidationInfo/*!*/ Validation;
public MemberBindingInfo(DynamicMetaObject/*!*/[]/*!*/ args, ConditionalBuilder/*!*/ body, ValidationInfo/*!*/ validation) {
Body = body;
Validation = validation;
Args = args;
}
}
private class DeleteBindingInfo : MemberBindingInfo {
public readonly DeleteMemberBinder/*!*/ Action;
public DeleteBindingInfo(DeleteMemberBinder/*!*/ action, DynamicMetaObject/*!*/[]/*!*/ args, ConditionalBuilder/*!*/ body, ValidationInfo/*!*/ validation)
: base(args, body, validation) {
Action = action;
}
}
private class SetBindingInfo : MemberBindingInfo {
public readonly SetMemberBinder/*!*/ Action;
public SetBindingInfo(SetMemberBinder/*!*/ action, DynamicMetaObject/*!*/[]/*!*/ args, ConditionalBuilder/*!*/ body, ValidationInfo/*!*/ validation)
: base(args, body, validation) {
Action = action;
}
}
private class GetBindingInfo : MemberBindingInfo {
public readonly DynamicMetaObjectBinder/*!*/ Action;
public readonly ParameterExpression/*!*/ Self, Result;
public GetBindingInfo(DynamicMetaObjectBinder/*!*/ action, DynamicMetaObject/*!*/[]/*!*/ args, ParameterExpression/*!*/ self, ParameterExpression/*!*/ result, ConditionalBuilder/*!*/ body, ValidationInfo/*!*/ validationInfo)
: base(args, body, validationInfo) {
Action = action;
Self = self;
Result = result;
}
}
#endregion
#region Fallback Helpers
/// <summary>
/// Helper for falling back - if we have a base object fallback to it first (which can
/// then fallback to the calling site), otherwise fallback to the calling site.
/// </summary>
private DynamicMetaObject/*!*/ FallbackGetError(DynamicMetaObjectBinder/*!*/ action, DynamicMetaObject codeContext) {
if (_baseMetaObject != null) {
return Fallback(action, codeContext);
} else if (BindingHelpers.IsNoThrow(action)) {
return new DynamicMetaObject(
Ast.Field(null, typeof(OperationFailed).GetField(nameof(OperationFailed.Value))),
BindingRestrictions.Empty
);
} else if (action is PythonGetMemberBinder) {
return new DynamicMetaObject(
MakeTypeError(action, GetGetMemberName(action), GetPythonTypeName(this)),
BindingRestrictions.Empty
);
}
return GetMemberFallback(this, action, codeContext);
}
/// <summary>
/// Helper for falling back - if we have a base object fallback to it first (which can
/// then fallback to the calling site), otherwise fallback to the calling site.
/// </summary>
private DynamicMetaObject/*!*/ FallbackDeleteError(DeleteMemberBinder/*!*/ action, DynamicMetaObject/*!*/[] args) {
if (_baseMetaObject != null) {
return _baseMetaObject.BindDeleteMember(action);
} else if (action is PythonDeleteMemberBinder) {
return new DynamicMetaObject(
MakeTypeError(action, action.Name, MetaPythonObject.GetPythonTypeName(args[0])),
BindingRestrictions.Empty
);
}
return action.FallbackDeleteMember(Restrict(this.GetLimitType()));
}
#endregion
private static Expression/*!*/ GetSlots(DynamicMetaObject/*!*/ self) {
FieldInfo fi = self.LimitType.GetField(NewTypeMaker.SlotsAndWeakRefFieldName);
if (fi != null) {
return Ast.Field(
Ast.Convert(self.Expression, self.LimitType),
fi
);
}
return Ast.Call(
Ast.Convert(self.Expression, typeof(IPythonObject)),
typeof(IPythonObject).GetMethod(nameof(IPythonObject.GetSlots))
);
}
}
}
| |
using ClosedXML_Examples;
using ClosedXML_Examples.Misc;
using NUnit.Framework;
namespace ClosedXML_Tests.Examples
{
[TestFixture]
public class MiscTests
{
[Test]
public void AddingDataSet()
{
TestHelper.RunTestExample<AddingDataSet>(@"Misc\AddingDataSet.xlsx");
}
[Test]
public void AddingDataTableAsWorksheet()
{
TestHelper.RunTestExample<AddingDataTableAsWorksheet>(@"Misc\AddingDataTableAsWorksheet.xlsx");
}
[Test]
public void AdjustToContents()
{
TestHelper.RunTestExample<AdjustToContents>(@"Misc\AdjustToContents.xlsx");
}
[Test]
public void AdjustToContentsWithAutoFilter()
{
TestHelper.RunTestExample<AdjustToContentsWithAutoFilter>(@"Misc\AdjustToContentsWithAutoFilter.xlsx");
}
[Test]
public void AutoFilter()
{
TestHelper.RunTestExample<AutoFilter>(@"Misc\AutoFilter.xlsx");
}
[Test]
public void BasicTable()
{
TestHelper.RunTestExample<BasicTable>(@"Misc\BasicTable.xlsx");
}
[Test]
public void BlankCells()
{
TestHelper.RunTestExample<BlankCells>(@"Misc\BlankCells.xlsx");
}
[Test]
public void CellValues()
{
TestHelper.RunTestExample<CellValues>(@"Misc\CellValues.xlsx");
}
[Test]
public void Collections()
{
TestHelper.RunTestExample<Collections>(@"Misc\Collections.xlsx");
}
[Test]
public void CopyingRowsAndColumns()
{
TestHelper.RunTestExample<CopyingRowsAndColumns>(@"Misc\CopyingRowsAndColumns.xlsx");
}
[Test]
public void CopyingWorksheets()
{
TestHelper.RunTestExample<CopyingWorksheets>(@"Misc\CopyingWorksheets.xlsx");
}
[Test]
public void DataTypes()
{
TestHelper.RunTestExample<DataTypes>(@"Misc\DataTypes.xlsx");
}
[Test]
public void DataTypesUnderDifferentCulture()
{
TestHelper.RunTestExample<DataTypesUnderDifferentCulture>(@"Misc\DataTypesUnderDifferentCulture.xlsx");
}
[Test]
public void DataValidation()
{
TestHelper.RunTestExample<DataValidation>(@"Misc\DataValidation.xlsx");
}
[Test]
public void Formulas()
{
TestHelper.RunTestExample<Formulas>(@"Misc\Formulas.xlsx");
}
[Test]
public void FormulasWithEvaluation()
{
TestHelper.RunTestExample<FormulasWithEvaluation>(@"Misc\FormulasWithEvaluation.xlsx", true);
}
[Test]
public void FreezePanes()
{
TestHelper.RunTestExample<FreezePanes>(@"Misc\FreezePanes.xlsx");
}
[Test]
public void HideSheets()
{
TestHelper.RunTestExample<HideSheets>(@"Misc\HideSheets.xlsx");
}
[Test]
public void HideUnhide()
{
TestHelper.RunTestExample<HideUnhide>(@"Misc\HideUnhide.xlsx");
}
[Test]
public void Hyperlinks()
{
TestHelper.RunTestExample<Hyperlinks>(@"Misc\Hyperlinks.xlsx");
}
[Test]
public void InsertingData()
{
TestHelper.RunTestExample<InsertingData>(@"Misc\InsertingData.xlsx");
}
[Test]
public void LambdaExpressions()
{
TestHelper.RunTestExample<LambdaExpressions>(@"Misc\LambdaExpressions.xlsx");
}
[Test]
public void MergeCells()
{
TestHelper.RunTestExample<MergeCells>(@"Misc\MergeCells.xlsx");
}
[Test]
public void MergeMoves()
{
TestHelper.RunTestExample<MergeMoves>(@"Misc\MergeMoves.xlsx");
}
[Test]
public void Outline()
{
TestHelper.RunTestExample<Outline>(@"Misc\Outline.xlsx");
}
[Test]
public void RightToLeft()
{
TestHelper.RunTestExample<RightToLeft>(@"Misc\RightToLeft.xlsx");
}
[Test]
public void SheetProtection()
{
TestHelper.RunTestExample<SheetProtection>(@"Misc\SheetProtection.xlsx");
}
[Test]
public void SheetViews()
{
TestHelper.RunTestExample<SheetViews>(@"Misc\SheetViews.xlsx");
}
[Test]
public void ShiftingFormulas()
{
TestHelper.RunTestExample<ShiftingFormulas>(@"Misc\ShiftingFormulas.xlsx");
}
[Test]
public void ShowCase()
{
TestHelper.RunTestExample<ShowCase>(@"Misc\ShowCase.xlsx");
}
[Test]
public void TabColors()
{
TestHelper.RunTestExample<TabColors>(@"Misc\TabColors.xlsx");
}
[Test]
public void WorkbookProperties()
{
TestHelper.RunTestExample<WorkbookProperties>(@"Misc\WorkbookProperties.xlsx");
}
[Test]
public void WorkbookProtection()
{
TestHelper.RunTestExample<WorkbookProtection>(@"Misc\WorkbookProtection.xlsx");
}
}
}
| |
using System;
using System.Net;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Shared.Protocol;
using Microsoft.WindowsAzure.Storage.Table.Protocol;
using Orleans.AzureUtils;
using Orleans.TestingHost.Utils;
using Tester;
using TestExtensions;
using Xunit;
namespace UnitTests.StorageTests
{
public class AzureTableDataManagerTests : IClassFixture<AzureStorageBasicTestFixture>
{
private string PartitionKey;
private UnitTestAzureTableDataManager manager;
private UnitTestAzureTableData GenerateNewData()
{
return new UnitTestAzureTableData("JustData", PartitionKey, "RK-" + Guid.NewGuid());
}
public AzureTableDataManagerTests()
{
TestingUtils.ConfigureThreadPoolSettingsForStorageTests();
// Pre-create table, if required
manager = new UnitTestAzureTableDataManager(TestDefaultConfiguration.DataConnectionString);
PartitionKey = "PK-AzureTableDataManagerTests-" + Guid.NewGuid();
}
[Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
public async Task AzureTableDataManager_CreateTableEntryAsync()
{
var data = GenerateNewData();
await manager.CreateTableEntryAsync(data);
try
{
var data2 = data.Clone();
data2.StringData = "NewData";
await manager.CreateTableEntryAsync(data2);
Assert.True(false, "Should have thrown StorageException.");
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.Conflict, exc.RequestInformation.HttpStatusCode); // "Creating an already existing entry."
HttpStatusCode httpStatusCode;
string restStatus;
AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.Conflict, httpStatusCode);
Assert.Equal("EntityAlreadyExists", restStatus);
}
var tuple = await manager.ReadSingleTableEntryAsync(data.PartitionKey, data.RowKey);
Assert.Equal(data.StringData, tuple.Item1.StringData);
}
[Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
public async Task AzureTableDataManager_UpsertTableEntryAsync()
{
var data = GenerateNewData();
await manager.UpsertTableEntryAsync(data);
var tuple = await manager.ReadSingleTableEntryAsync(data.PartitionKey, data.RowKey);
Assert.Equal(data.StringData, tuple.Item1.StringData);
var data2 = data.Clone();
data2.StringData = "NewData";
await manager.UpsertTableEntryAsync(data2);
tuple = await manager.ReadSingleTableEntryAsync(data2.PartitionKey, data2.RowKey);
Assert.Equal(data2.StringData, tuple.Item1.StringData);
}
[Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
public async Task AzureTableDataManager_UpdateTableEntryAsync()
{
var data = GenerateNewData();
try
{
await manager.UpdateTableEntryAsync(data, AzureStorageUtils.ANY_ETAG);
Assert.True(false, "Should have thrown StorageException.");
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.NotFound, exc.RequestInformation.HttpStatusCode); // "Update before insert."
HttpStatusCode httpStatusCode;
string restStatus;
AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.NotFound, httpStatusCode);
Assert.Equal(StorageErrorCodeStrings.ResourceNotFound, restStatus);
}
await manager.UpsertTableEntryAsync(data);
var tuple = await manager.ReadSingleTableEntryAsync(data.PartitionKey, data.RowKey);
Assert.Equal(data.StringData, tuple.Item1.StringData);
var data2 = data.Clone();
data2.StringData = "NewData";
string eTag1 = await manager.UpdateTableEntryAsync(data2, AzureStorageUtils.ANY_ETAG);
tuple = await manager.ReadSingleTableEntryAsync(data2.PartitionKey, data2.RowKey);
Assert.Equal(data2.StringData, tuple.Item1.StringData);
var data3 = data.Clone();
data3.StringData = "EvenNewerData";
string ignoredETag = await manager.UpdateTableEntryAsync(data3, eTag1);
tuple = await manager.ReadSingleTableEntryAsync(data3.PartitionKey, data3.RowKey);
Assert.Equal(data3.StringData, tuple.Item1.StringData);
try
{
string eTag3 = await manager.UpdateTableEntryAsync(data3.Clone(), eTag1);
Assert.True(false, "Should have thrown StorageException.");
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.PreconditionFailed, exc.RequestInformation.HttpStatusCode); // "Wrong eTag"
HttpStatusCode httpStatusCode;
string restStatus;
AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.PreconditionFailed, httpStatusCode);
Assert.True(restStatus == TableErrorCodeStrings.UpdateConditionNotSatisfied
|| restStatus == StorageErrorCodeStrings.ConditionNotMet, restStatus);
}
}
[Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
public async Task AzureTableDataManager_DeleteTableAsync()
{
var data = GenerateNewData();
try
{
await manager.DeleteTableEntryAsync(data, AzureStorageUtils.ANY_ETAG);
Assert.True(false, "Should have thrown StorageException.");
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.NotFound, exc.RequestInformation.HttpStatusCode); // "Delete before create."
HttpStatusCode httpStatusCode;
string restStatus;
AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.NotFound, httpStatusCode);
Assert.Equal(StorageErrorCodeStrings.ResourceNotFound, restStatus);
}
string eTag1 = await manager.UpsertTableEntryAsync(data);
await manager.DeleteTableEntryAsync(data, eTag1);
try
{
await manager.DeleteTableEntryAsync(data, eTag1);
Assert.True(false, "Should have thrown StorageException.");
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.NotFound, exc.RequestInformation.HttpStatusCode); // "Deleting an already deleted item."
HttpStatusCode httpStatusCode;
string restStatus;
AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.NotFound, httpStatusCode);
Assert.Equal(StorageErrorCodeStrings.ResourceNotFound, restStatus);
}
var tuple = await manager.ReadSingleTableEntryAsync(data.PartitionKey, data.RowKey);
Assert.Null(tuple);
}
[Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
public async Task AzureTableDataManager_MergeTableAsync()
{
var data = GenerateNewData();
try
{
await manager.MergeTableEntryAsync(data, AzureStorageUtils.ANY_ETAG);
Assert.True(false, "Should have thrown StorageException.");
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.NotFound, exc.RequestInformation.HttpStatusCode); // "Merge before create."
HttpStatusCode httpStatusCode;
string restStatus;
AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.NotFound, httpStatusCode);
Assert.Equal(StorageErrorCodeStrings.ResourceNotFound, restStatus);
}
string eTag1 = await manager.UpsertTableEntryAsync(data);
var data2 = data.Clone();
data2.StringData = "NewData";
await manager.MergeTableEntryAsync(data2, eTag1);
try
{
await manager.MergeTableEntryAsync(data, eTag1);
Assert.True(false, "Should have thrown StorageException.");
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.PreconditionFailed, exc.RequestInformation.HttpStatusCode); // "Wrong eTag."
HttpStatusCode httpStatusCode;
string restStatus;
AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.PreconditionFailed, httpStatusCode);
Assert.True(restStatus == TableErrorCodeStrings.UpdateConditionNotSatisfied
|| restStatus == StorageErrorCodeStrings.ConditionNotMet, restStatus);
}
var tuple = await manager.ReadSingleTableEntryAsync(data.PartitionKey, data.RowKey);
Assert.Equal("NewData", tuple.Item1.StringData);
}
[Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
public async Task AzureTableDataManager_ReadSingleTableEntryAsync()
{
var data = GenerateNewData();
var tuple = await manager.ReadSingleTableEntryAsync(data.PartitionKey, data.RowKey);
Assert.Null(tuple);
}
[Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
public async Task AzureTableDataManager_InsertTwoTableEntriesConditionallyAsync()
{
var data1 = GenerateNewData();
var data2 = GenerateNewData();
try
{
await manager.InsertTwoTableEntriesConditionallyAsync(data1, data2, AzureStorageUtils.ANY_ETAG);
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.NotFound, exc.RequestInformation.HttpStatusCode); // "Upadte item 2 before created it."
HttpStatusCode httpStatusCode;
string restStatus;
AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.NotFound, httpStatusCode);
Assert.Equal(StorageErrorCodeStrings.ResourceNotFound, restStatus);
}
string etag = await manager.CreateTableEntryAsync(data2.Clone());
var tuple = await manager.InsertTwoTableEntriesConditionallyAsync(data1, data2, etag);
try
{
await manager.InsertTwoTableEntriesConditionallyAsync(data1.Clone(), data2.Clone(), tuple.Item2);
Assert.True(false, "Should have thrown StorageException.");
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.Conflict, exc.RequestInformation.HttpStatusCode); // "Inserting an already existing item 1."
HttpStatusCode httpStatusCode;
string restStatus;
AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.Conflict, httpStatusCode);
Assert.Equal("EntityAlreadyExists", restStatus);
}
try
{
await manager.InsertTwoTableEntriesConditionallyAsync(data1.Clone(), data2.Clone(), AzureStorageUtils.ANY_ETAG);
Assert.True(false, "Should have thrown StorageException.");
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.Conflict, exc.RequestInformation.HttpStatusCode); // "Inserting an already existing item 1 AND wring eTag"
HttpStatusCode httpStatusCode;
string restStatus;
AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.Conflict, httpStatusCode);
Assert.Equal("EntityAlreadyExists", restStatus);
};
}
[Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
public async Task AzureTableDataManager_UpdateTwoTableEntriesConditionallyAsync()
{
var data1 = GenerateNewData();
var data2 = GenerateNewData();
try
{
await manager.UpdateTwoTableEntriesConditionallyAsync(data1, AzureStorageUtils.ANY_ETAG, data2, AzureStorageUtils.ANY_ETAG);
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.NotFound, exc.RequestInformation.HttpStatusCode); // "Update before insert."
HttpStatusCode httpStatusCode;
string restStatus;
AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.NotFound, httpStatusCode);
Assert.Equal(StorageErrorCodeStrings.ResourceNotFound, restStatus);
}
string etag = await manager.CreateTableEntryAsync(data2.Clone());
var tuple1 = await manager.InsertTwoTableEntriesConditionallyAsync(data1, data2, etag);
var tuple2 = await manager.UpdateTwoTableEntriesConditionallyAsync(data1, tuple1.Item1, data2, tuple1.Item2);
try
{
await manager.UpdateTwoTableEntriesConditionallyAsync(data1, tuple1.Item1, data2, tuple1.Item2);
Assert.True(false, "Should have thrown StorageException.");
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.PreconditionFailed, exc.RequestInformation.HttpStatusCode); // "Wrong eTag"
HttpStatusCode httpStatusCode;
string restStatus;
AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.PreconditionFailed, httpStatusCode);
Assert.True(restStatus == TableErrorCodeStrings.UpdateConditionNotSatisfied
|| restStatus == StorageErrorCodeStrings.ConditionNotMet, restStatus);
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: StreamWriter
**
** <OWNER>gpaperin</OWNER>
**
**
** Purpose: For writing text to streams in a particular
** encoding.
**
**
===========================================================*/
using System;
using System.Text;
using System.Threading;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Permissions;
using System.Runtime.Serialization;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
#if FEATURE_ASYNC_IO
using System.Threading.Tasks;
#endif
namespace System.IO
{
// This class implements a TextWriter for writing characters to a Stream.
// This is designed for character output in a particular Encoding,
// whereas the Stream class is designed for byte input and output.
//
[Serializable]
[ComVisible(true)]
public class StreamWriter : TextWriter
{
// For UTF-8, the values of 1K for the default buffer size and 4K for the
// file stream buffer size are reasonable & give very reasonable
// performance for in terms of construction time for the StreamWriter and
// write perf. Note that for UTF-8, we end up allocating a 4K byte buffer,
// which means we take advantage of adaptive buffering code.
// The performance using UnicodeEncoding is acceptable.
internal const int DefaultBufferSize = 1024; // char[]
private const int DefaultFileStreamBufferSize = 4096;
private const int MinBufferSize = 128;
#if FEATURE_ASYNC_IO
private const Int32 DontCopyOnWriteLineThreshold = 512;
#endif
// Bit bucket - Null has no backing store. Non closable.
public new static readonly StreamWriter Null = new StreamWriter(Stream.Null, new UTF8Encoding(false, true), MinBufferSize, true);
private Stream stream;
private Encoding encoding;
private Encoder encoder;
private byte[] byteBuffer;
private char[] charBuffer;
private int charPos;
private int charLen;
private bool autoFlush;
private bool haveWrittenPreamble;
private bool closable;
#if MDA_SUPPORTED
[NonSerialized]
// For StreamWriterBufferedDataLost MDA
private MdaHelper mdaHelper;
#endif
#if FEATURE_ASYNC_IO
// We don't guarantee thread safety on StreamWriter, but we should at
// least prevent users from trying to write anything while an Async
// write from the same thread is in progress.
[NonSerialized]
private volatile Task _asyncWriteTask;
private void CheckAsyncTaskInProgress()
{
// We are not locking the access to _asyncWriteTask because this is not meant to guarantee thread safety.
// We are simply trying to deter calling any Write APIs while an async Write from the same thread is in progress.
Task t = _asyncWriteTask;
if (t != null && !t.IsCompleted)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsyncIOInProgress"));
}
#endif
// The high level goal is to be tolerant of encoding errors when we read and very strict
// when we write. Hence, default StreamWriter encoding will throw on encoding error.
// Note: when StreamWriter throws on invalid encoding chars (for ex, high surrogate character
// D800-DBFF without a following low surrogate character DC00-DFFF), it will cause the
// internal StreamWriter's state to be irrecoverable as it would have buffered the
// illegal chars and any subsequent call to Flush() would hit the encoding error again.
// Even Close() will hit the exception as it would try to flush the unwritten data.
// Maybe we can add a DiscardBufferedData() method to get out of such situation (like
// StreamReader though for different reason). Either way, the buffered data will be lost!
private static volatile Encoding _UTF8NoBOM;
internal static Encoding UTF8NoBOM {
[FriendAccessAllowed]
get {
if (_UTF8NoBOM == null) {
// No need for double lock - we just want to avoid extra
// allocations in the common case.
UTF8Encoding noBOM = new UTF8Encoding(false, true);
Thread.MemoryBarrier();
_UTF8NoBOM = noBOM;
}
return _UTF8NoBOM;
}
}
internal StreamWriter(): base(null) { // Ask for CurrentCulture all the time
}
public StreamWriter(Stream stream)
: this(stream, UTF8NoBOM, DefaultBufferSize, false) {
}
public StreamWriter(Stream stream, Encoding encoding)
: this(stream, encoding, DefaultBufferSize, false) {
}
// Creates a new StreamWriter for the given stream. The
// character encoding is set by encoding and the buffer size,
// in number of 16-bit characters, is set by bufferSize.
//
public StreamWriter(Stream stream, Encoding encoding, int bufferSize)
: this(stream, encoding, bufferSize, false) {
}
public StreamWriter(Stream stream, Encoding encoding, int bufferSize, bool leaveOpen)
: base(null) // Ask for CurrentCulture all the time
{
if (stream == null || encoding == null)
throw new ArgumentNullException((stream == null ? "stream" : "encoding"));
if (!stream.CanWrite)
throw new ArgumentException(Environment.GetResourceString("Argument_StreamNotWritable"));
if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
Contract.EndContractBlock();
Init(stream, encoding, bufferSize, leaveOpen);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public StreamWriter(String path)
: this(path, false, UTF8NoBOM, DefaultBufferSize) {
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public StreamWriter(String path, bool append)
: this(path, append, UTF8NoBOM, DefaultBufferSize) {
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public StreamWriter(String path, bool append, Encoding encoding)
: this(path, append, encoding, DefaultBufferSize) {
}
[System.Security.SecuritySafeCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public StreamWriter(String path, bool append, Encoding encoding, int bufferSize): this(path, append, encoding, bufferSize, true) {
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal StreamWriter(String path, bool append, Encoding encoding, int bufferSize, bool checkHost)
: base(null)
{ // Ask for CurrentCulture all the time
if (path == null)
throw new ArgumentNullException("path");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
Contract.EndContractBlock();
Stream stream = CreateFile(path, append, checkHost);
Init(stream, encoding, bufferSize, false);
}
[System.Security.SecuritySafeCritical]
private void Init(Stream streamArg, Encoding encodingArg, int bufferSize, bool shouldLeaveOpen)
{
this.stream = streamArg;
this.encoding = encodingArg;
this.encoder = encoding.GetEncoder();
if (bufferSize < MinBufferSize) bufferSize = MinBufferSize;
charBuffer = new char[bufferSize];
byteBuffer = new byte[encoding.GetMaxByteCount(bufferSize)];
charLen = bufferSize;
// If we're appending to a Stream that already has data, don't write
// the preamble.
if (stream.CanSeek && stream.Position > 0)
haveWrittenPreamble = true;
closable = !shouldLeaveOpen;
#if MDA_SUPPORTED
if (Mda.StreamWriterBufferedDataLost.Enabled) {
String callstack = null;
if (Mda.StreamWriterBufferedDataLost.CaptureAllocatedCallStack)
callstack = Environment.GetStackTrace(null, false);
mdaHelper = new MdaHelper(this, callstack);
}
#endif
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static Stream CreateFile(String path, bool append, bool checkHost) {
FileMode mode = append? FileMode.Append: FileMode.Create;
FileStream f = new FileStream(path, mode, FileAccess.Write, FileShare.Read,
DefaultFileStreamBufferSize, FileOptions.SequentialScan, Path.GetFileName(path), false, false, checkHost);
return f;
}
public override void Close() {
Dispose(true);
GC.SuppressFinalize(this);
}
protected override void Dispose(bool disposing) {
try {
// We need to flush any buffered data if we are being closed/disposed.
// Also, we never close the handles for stdout & friends. So we can safely
// write any buffered data to those streams even during finalization, which
// is generally the right thing to do.
if (stream != null) {
// Note: flush on the underlying stream can throw (ex., low disk space)
if (disposing || (LeaveOpen && stream is __ConsoleStream))
{
#if FEATURE_ASYNC_IO
CheckAsyncTaskInProgress();
#endif
Flush(true, true);
#if MDA_SUPPORTED
// Disable buffered data loss mda
if (mdaHelper != null)
GC.SuppressFinalize(mdaHelper);
#endif
}
}
}
finally {
// Dispose of our resources if this StreamWriter is closable.
// Note: Console.Out and other such non closable streamwriters should be left alone
if (!LeaveOpen && stream != null) {
try {
// Attempt to close the stream even if there was an IO error from Flushing.
// Note that Stream.Close() can potentially throw here (may or may not be
// due to the same Flush error). In this case, we still need to ensure
// cleaning up internal resources, hence the finally block.
if (disposing)
stream.Close();
}
finally {
stream = null;
byteBuffer = null;
charBuffer = null;
encoding = null;
encoder = null;
charLen = 0;
base.Dispose(disposing);
}
}
}
}
public override void Flush()
{
#if FEATURE_ASYNC_IO
CheckAsyncTaskInProgress();
#endif
Flush(true, true);
}
private void Flush(bool flushStream, bool flushEncoder)
{
// flushEncoder should be true at the end of the file and if
// the user explicitly calls Flush (though not if AutoFlush is true).
// This is required to flush any dangling characters from our UTF-7
// and UTF-8 encoders.
if (stream == null)
__Error.WriterClosed();
// Perf boost for Flush on non-dirty writers.
if (charPos==0 && ((!flushStream && !flushEncoder) || CompatibilitySwitches.IsAppEarlierThanWindowsPhone8))
return;
if (!haveWrittenPreamble) {
haveWrittenPreamble = true;
byte[] preamble = encoding.GetPreamble();
if (preamble.Length > 0)
stream.Write(preamble, 0, preamble.Length);
}
int count = encoder.GetBytes(charBuffer, 0, charPos, byteBuffer, 0, flushEncoder);
charPos = 0;
if (count > 0)
stream.Write(byteBuffer, 0, count);
// By definition, calling Flush should flush the stream, but this is
// only necessary if we passed in true for flushStream. The Web
// Services guys have some perf tests where flushing needlessly hurts.
if (flushStream)
stream.Flush();
}
public virtual bool AutoFlush {
get { return autoFlush; }
set
{
#if FEATURE_ASYNC_IO
CheckAsyncTaskInProgress();
#endif
autoFlush = value;
if (value) Flush(true, false);
}
}
public virtual Stream BaseStream {
get { return stream; }
}
internal bool LeaveOpen {
get { return !closable; }
}
internal bool HaveWrittenPreamble {
set { haveWrittenPreamble= value; }
}
public override Encoding Encoding {
get { return encoding; }
}
public override void Write(char value)
{
#if FEATURE_ASYNC_IO
CheckAsyncTaskInProgress();
#endif
if (charPos == charLen) Flush(false, false);
charBuffer[charPos] = value;
charPos++;
if (autoFlush) Flush(true, false);
}
public override void Write(char[] buffer)
{
// This may be faster than the one with the index & count since it
// has to do less argument checking.
if (buffer==null)
return;
#if FEATURE_ASYNC_IO
CheckAsyncTaskInProgress();
#endif
int index = 0;
int count = buffer.Length;
while (count > 0) {
if (charPos == charLen) Flush(false, false);
int n = charLen - charPos;
if (n > count) n = count;
Contract.Assert(n > 0, "StreamWriter::Write(char[]) isn't making progress! This is most likely a ---- in user code.");
Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char));
charPos += n;
index += n;
count -= n;
}
if (autoFlush) Flush(true, false);
}
public override void Write(char[] buffer, int index, int count) {
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
#if FEATURE_ASYNC_IO
CheckAsyncTaskInProgress();
#endif
while (count > 0) {
if (charPos == charLen) Flush(false, false);
int n = charLen - charPos;
if (n > count) n = count;
Contract.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code.");
Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char));
charPos += n;
index += n;
count -= n;
}
if (autoFlush) Flush(true, false);
}
public override void Write(String value)
{
if (value != null)
{
#if FEATURE_ASYNC_IO
CheckAsyncTaskInProgress();
#endif
int count = value.Length;
int index = 0;
while (count > 0) {
if (charPos == charLen) Flush(false, false);
int n = charLen - charPos;
if (n > count) n = count;
Contract.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code.");
value.CopyTo(index, charBuffer, charPos, n);
charPos += n;
index += n;
count -= n;
}
if (autoFlush) Flush(true, false);
}
}
#if FEATURE_ASYNC_IO
#region Task based Async APIs
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteAsync(char value)
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overriden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (this.GetType() != typeof(StreamWriter))
return base.WriteAsync(value);
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: false);
_asyncWriteTask = task;
return task;
}
// We pass in private instance fields of this MarshalByRefObject-derived type as local params
// to ensure performant access inside the state machine that corresponds this async method.
// Fields that are written to must be assigned at the end of the method *and* before instance invocations.
private static async Task WriteAsyncInternal(StreamWriter _this, Char value,
Char[] charBuffer, Int32 charPos, Int32 charLen, Char[] coreNewLine,
bool autoFlush, bool appendNewLine)
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
charBuffer[charPos] = value;
charPos++;
if (appendNewLine)
{
for (Int32 i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
charBuffer[charPos] = coreNewLine[i];
charPos++;
}
}
if (autoFlush) {
await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
_this.CharPos_Prop = charPos;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteAsync(String value)
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overriden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (this.GetType() != typeof(StreamWriter))
return base.WriteAsync(value);
if (value != null)
{
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: false);
_asyncWriteTask = task;
return task;
}
else
{
return Task.CompletedTask;
}
}
// We pass in private instance fields of this MarshalByRefObject-derived type as local params
// to ensure performant access inside the state machine that corresponds this async method.
// Fields that are written to must be assigned at the end of the method *and* before instance invocations.
private static async Task WriteAsyncInternal(StreamWriter _this, String value,
Char[] charBuffer, Int32 charPos, Int32 charLen, Char[] coreNewLine,
bool autoFlush, bool appendNewLine)
{
Contract.Requires(value != null);
int count = value.Length;
int index = 0;
while (count > 0)
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
int n = charLen - charPos;
if (n > count)
n = count;
Contract.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code.");
value.CopyTo(index, charBuffer, charPos, n);
charPos += n;
index += n;
count -= n;
}
if (appendNewLine)
{
for (Int32 i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
charBuffer[charPos] = coreNewLine[i];
charPos++;
}
}
if (autoFlush) {
await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
_this.CharPos_Prop = charPos;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteAsync(char[] buffer, int index, int count)
{
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overriden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (this.GetType() != typeof(StreamWriter))
return base.WriteAsync(buffer, index, count);
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, buffer, index, count, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: false);
_asyncWriteTask = task;
return task;
}
// We pass in private instance fields of this MarshalByRefObject-derived type as local params
// to ensure performant access inside the state machine that corresponds this async method.
// Fields that are written to must be assigned at the end of the method *and* before instance invocations.
private static async Task WriteAsyncInternal(StreamWriter _this, Char[] buffer, Int32 index, Int32 count,
Char[] charBuffer, Int32 charPos, Int32 charLen, Char[] coreNewLine,
bool autoFlush, bool appendNewLine)
{
Contract.Requires(count == 0 || (count > 0 && buffer != null));
Contract.Requires(index >= 0);
Contract.Requires(count >= 0);
Contract.Requires(buffer == null || (buffer != null && buffer.Length - index >= count));
while (count > 0)
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
int n = charLen - charPos;
if (n > count) n = count;
Contract.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code.");
Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char));
charPos += n;
index += n;
count -= n;
}
if (appendNewLine)
{
for (Int32 i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
charBuffer[charPos] = coreNewLine[i];
charPos++;
}
}
if (autoFlush) {
await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
_this.CharPos_Prop = charPos;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteLineAsync()
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overriden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (this.GetType() != typeof(StreamWriter))
return base.WriteLineAsync();
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, null, 0, 0, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true);
_asyncWriteTask = task;
return task;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteLineAsync(char value)
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overriden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (this.GetType() != typeof(StreamWriter))
return base.WriteLineAsync(value);
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true);
_asyncWriteTask = task;
return task;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteLineAsync(String value)
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overriden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (this.GetType() != typeof(StreamWriter))
return base.WriteLineAsync(value);
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, value ?? "", charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true);
_asyncWriteTask = task;
return task;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteLineAsync(char[] buffer, int index, int count)
{
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overriden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (this.GetType() != typeof(StreamWriter))
return base.WriteLineAsync(buffer, index, count);
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, buffer, index, count, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true);
_asyncWriteTask = task;
return task;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task FlushAsync()
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Flush() which a subclass might have overriden. To be safe
// we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Flush) when we are not sure.
if (this.GetType() != typeof(StreamWriter))
return base.FlushAsync();
// flushEncoder should be true at the end of the file and if
// the user explicitly calls Flush (though not if AutoFlush is true).
// This is required to flush any dangling characters from our UTF-7
// and UTF-8 encoders.
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = FlushAsyncInternal(true, true, charBuffer, charPos);
_asyncWriteTask = task;
return task;
}
private Int32 CharPos_Prop {
set { this.charPos = value; }
}
private bool HaveWrittenPreamble_Prop {
set { this.haveWrittenPreamble = value; }
}
private Task FlushAsyncInternal(bool flushStream, bool flushEncoder,
Char[] sCharBuffer, Int32 sCharPos) {
// Perf boost for Flush on non-dirty writers.
if (sCharPos == 0 && !flushStream && !flushEncoder)
return Task.CompletedTask;
Task flushTask = FlushAsyncInternal(this, flushStream, flushEncoder, sCharBuffer, sCharPos, this.haveWrittenPreamble,
this.encoding, this.encoder, this.byteBuffer, this.stream);
this.charPos = 0;
return flushTask;
}
// We pass in private instance fields of this MarshalByRefObject-derived type as local params
// to ensure performant access inside the state machine that corresponds this async method.
private static async Task FlushAsyncInternal(StreamWriter _this, bool flushStream, bool flushEncoder,
Char[] charBuffer, Int32 charPos, bool haveWrittenPreamble,
Encoding encoding, Encoder encoder, Byte[] byteBuffer, Stream stream)
{
if (!haveWrittenPreamble)
{
_this.HaveWrittenPreamble_Prop = true;
byte[] preamble = encoding.GetPreamble();
if (preamble.Length > 0)
await stream.WriteAsync(preamble, 0, preamble.Length).ConfigureAwait(false);
}
int count = encoder.GetBytes(charBuffer, 0, charPos, byteBuffer, 0, flushEncoder);
if (count > 0)
await stream.WriteAsync(byteBuffer, 0, count).ConfigureAwait(false);
// By definition, calling Flush should flush the stream, but this is
// only necessary if we passed in true for flushStream. The Web
// Services guys have some perf tests where flushing needlessly hurts.
if (flushStream)
await stream.FlushAsync().ConfigureAwait(false);
}
#endregion
#endif //FEATURE_ASYNC_IO
#if MDA_SUPPORTED
// StreamWriterBufferedDataLost MDA
// Instead of adding a finalizer to StreamWriter for detecting buffered data loss
// (ie, when the user forgets to call Close/Flush on the StreamWriter), we will
// have a separate object with normal finalization semantics that maintains a
// back pointer to this StreamWriter and alerts about any data loss
private sealed class MdaHelper
{
private StreamWriter streamWriter;
private String allocatedCallstack; // captures the callstack when this streamwriter was allocated
internal MdaHelper(StreamWriter sw, String cs)
{
streamWriter = sw;
allocatedCallstack = cs;
}
// Finalizer
~MdaHelper()
{
// Make sure people closed this StreamWriter, exclude StreamWriter::Null.
if (streamWriter.charPos != 0 && streamWriter.stream != null && streamWriter.stream != Stream.Null) {
String fileName = (streamWriter.stream is FileStream) ? ((FileStream)streamWriter.stream).NameInternal : "<unknown>";
String callStack = allocatedCallstack;
if (callStack == null)
callStack = Environment.GetResourceString("IO_StreamWriterBufferedDataLostCaptureAllocatedFromCallstackNotEnabled");
String message = Environment.GetResourceString("IO_StreamWriterBufferedDataLost", streamWriter.stream.GetType().FullName, fileName, callStack);
Mda.StreamWriterBufferedDataLost.ReportError(message);
}
}
} // class MdaHelper
#endif // MDA_SUPPORTED
} // class StreamWriter
} // namespace
| |
/*
* (c) 2008 MOSA - The Managed Operating System Alliance
*
* Licensed under the terms of the New BSD License.
*
* Authors:
* Simon Wollwage (rootnode) <[email protected]>
*/
using poly_subpixel_scale_e = Pictor.Basics.PolySubpixelScale;
namespace Pictor
{
//-----------------------------------------------------------------AntiAliasingCell
// A Pixel cell. There're no constructors defined and it was done
// intentionally in order to avoid extra overhead when allocating an
// array of cells.
public struct AntiAliasingCell// : IPixelCell
{
public int x;
public int y;
public int cover;
public int area;
public short left, right;
public void Initial()
{
x = 0x7FFFFFFF;
y = 0x7FFFFFFF;
cover = 0;
area = 0;
left = -1;
right = -1;
}
public void Set(AntiAliasingCell cellB)
{
x = cellB.x;
y = cellB.y;
cover = cellB.cover;
area = cellB.area;
left = cellB.left;
right = cellB.right;
}
public AntiAliasingCell Style
{
set
{
left = value.left;
right = value.right;
}
}
public bool NotEqual(int ex, int ey, AntiAliasingCell cell)
{
unchecked
{
return ((ex - x) | (ey - y) | (left - cell.left) | (right - cell.right)) != 0;
}
}
};
//-----------------------------------------------------AntiAliasedRasterizerCells
// An internal class that implements the main rasterization algorithm.
// Used in the rasterizer. Should not be used directly.
//template<class Cell>
public sealed class AntiAliasedRasterizerCells
{
private uint m_num_used_cells;
private VectorPOD<AntiAliasingCell> m_cells;
private VectorPOD<AntiAliasingCell> m_sorted_cells;
private VectorPOD<SortedY> m_sorted_y;
private QuickSortAntiAliasedCell m_QSorter;
private AntiAliasingCell m_curr_cell;
private AntiAliasingCell m_style_cell;
private int m_min_x;
private int m_min_y;
private int m_max_x;
private int m_max_y;
private bool m_sorted;
private enum ECellBlockScale
{
Shift = 12,
Size = 1 << Shift,
Mask = Size - 1,
Pool = 256,
Limit = 1024 * Size
};
private struct SortedY
{
internal uint start;
internal uint num;
};
public AntiAliasedRasterizerCells()
{
m_QSorter = new QuickSortAntiAliasedCell();
m_sorted_cells = new VectorPOD<AntiAliasingCell>();
m_sorted_y = new VectorPOD<SortedY>();
m_min_x = (0x7FFFFFFF);
m_min_y = (0x7FFFFFFF);
m_max_x = (-0x7FFFFFFF);
m_max_y = (-0x7FFFFFFF);
m_sorted = (false);
m_style_cell.Initial();
m_curr_cell.Initial();
}
public void Reset()
{
m_num_used_cells = 0;
m_curr_cell.Initial();
m_style_cell.Initial();
m_sorted = false;
m_min_x = 0x7FFFFFFF;
m_min_y = 0x7FFFFFFF;
m_max_x = -0x7FFFFFFF;
m_max_y = -0x7FFFFFFF;
}
public void Style(AntiAliasingCell style_cell)
{
m_style_cell.Style = style_cell;
}
private enum dx_limit_e { dx_limit = 16384 << Basics.PolySubpixelScale.Shift };
public void Line(int x1, int y1, int x2, int y2)
{
int poly_subpixel_shift = (int)Basics.PolySubpixelScale.Shift;
int poly_subpixel_mask = (int)Basics.PolySubpixelScale.Mask;
int poly_subpixel_scale = (int)Basics.PolySubpixelScale.Scale;
int dx = x2 - x1;
if (dx >= (int)dx_limit_e.dx_limit || dx <= -(int)dx_limit_e.dx_limit)
{
int cx = (x1 + x2) >> 1;
int cy = (y1 + y2) >> 1;
Line(x1, y1, cx, cy);
Line(cx, cy, x2, y2);
}
int dy = y2 - y1;
int ex1 = x1 >> poly_subpixel_shift;
int ex2 = x2 >> poly_subpixel_shift;
int ey1 = y1 >> poly_subpixel_shift;
int ey2 = y2 >> poly_subpixel_shift;
int fy1 = y1 & poly_subpixel_mask;
int fy2 = y2 & poly_subpixel_mask;
int x_from, x_to;
int p, rem, mod, lift, delta, first, incr;
if (ex1 < m_min_x) m_min_x = ex1;
if (ex1 > m_max_x) m_max_x = ex1;
if (ey1 < m_min_y) m_min_y = ey1;
if (ey1 > m_max_y) m_max_y = ey1;
if (ex2 < m_min_x) m_min_x = ex2;
if (ex2 > m_max_x) m_max_x = ex2;
if (ey2 < m_min_y) m_min_y = ey2;
if (ey2 > m_max_y) m_max_y = ey2;
SetCurrentCell(ex1, ey1);
//everything is on a single horizontal Line
if (ey1 == ey2)
{
RenderHorizontalLine(ey1, x1, fy1, x2, fy2);
return;
}
//Vertical Line - we have to Calculate Start and End cells,
//and then - the common values of the area and coverage for
//all cells of the Line. We know exactly there's only one
//cell, so, we don't have to call RenderHorizontalLine().
incr = 1;
if (dx == 0)
{
int ex = x1 >> poly_subpixel_shift;
int two_fx = (x1 - (ex << poly_subpixel_shift)) << 1;
int area;
first = poly_subpixel_scale;
if (dy < 0)
{
first = 0;
incr = -1;
}
x_from = x1;
delta = first - fy1;
m_curr_cell.cover += delta;
m_curr_cell.area += two_fx * delta;
ey1 += incr;
SetCurrentCell(ex, ey1);
delta = first + first - poly_subpixel_scale;
area = two_fx * delta;
while (ey1 != ey2)
{
m_curr_cell.cover = delta;
m_curr_cell.area = area;
ey1 += incr;
SetCurrentCell(ex, ey1);
}
delta = fy2 - poly_subpixel_scale + first;
m_curr_cell.cover += delta;
m_curr_cell.area += two_fx * delta;
return;
}
//ok, we have to render several hlines
p = (poly_subpixel_scale - fy1) * dx;
first = poly_subpixel_scale;
if (dy < 0)
{
p = fy1 * dx;
first = 0;
incr = -1;
dy = -dy;
}
delta = p / dy;
mod = p % dy;
if (mod < 0)
{
delta--;
mod += dy;
}
x_from = x1 + delta;
RenderHorizontalLine(ey1, x1, fy1, x_from, first);
ey1 += incr;
SetCurrentCell(x_from >> poly_subpixel_shift, ey1);
if (ey1 != ey2)
{
p = poly_subpixel_scale * dx;
lift = p / dy;
rem = p % dy;
if (rem < 0)
{
lift--;
rem += dy;
}
mod -= dy;
while (ey1 != ey2)
{
delta = lift;
mod += rem;
if (mod >= 0)
{
mod -= dy;
delta++;
}
x_to = x_from + delta;
RenderHorizontalLine(ey1, x_from, poly_subpixel_scale - first, x_to, first);
x_from = x_to;
ey1 += incr;
SetCurrentCell(x_from >> poly_subpixel_shift, ey1);
}
}
RenderHorizontalLine(ey1, x_from, poly_subpixel_scale - first, x2, fy2);
}
public int MinX()
{
return m_min_x;
}
public int MinY()
{
return m_min_y;
}
public int MaxX()
{
return m_max_x;
}
public int MaxY()
{
return m_max_y;
}
#if use_timers
static CNamedTimer SortCellsTimer = new CNamedTimer("SortCellsTimer");
static CNamedTimer QSortTimer = new CNamedTimer("QSortTimer");
#endif
public void SortCells()
{
if (m_sorted) return; //Perform Sort only the first time.
AddCurrentCell();
m_curr_cell.x = 0x7FFFFFFF;
m_curr_cell.y = 0x7FFFFFFF;
m_curr_cell.cover = 0;
m_curr_cell.area = 0;
if (m_num_used_cells == 0) return;
#if use_timers
SortCellsTimer.Start();
#endif
// Allocate the array of cell pointers
m_sorted_cells.Allocate(m_num_used_cells);
// Allocate and zero the Y array
m_sorted_y.Allocate((uint)(m_max_y - m_min_y + 1));
m_sorted_y.Zero();
AntiAliasingCell[] cells = m_cells.Array;
SortedY[] sortedYData = m_sorted_y.Array;
AntiAliasingCell[] sortedCellsData = m_sorted_cells.Array;
// Create the Y-histogram (count the numbers of cells for each Y)
for (uint i = 0; i < m_num_used_cells; i++)
{
int Index = cells[i].y - m_min_y;
sortedYData[Index].start++;
}
// Convert the Y-histogram into the array of starting indexes
uint start = 0;
uint SortedYSize = m_sorted_y.Size();
for (uint i = 0; i < SortedYSize; i++)
{
uint v = sortedYData[i].start;
sortedYData[i].start = start;
start += v;
}
// Fill the cell pointer array IsSorted by Y
for (uint i = 0; i < m_num_used_cells; i++)
{
int SortedIndex = cells[i].y - m_min_y;
uint curr_y_start = sortedYData[SortedIndex].start;
uint curr_y_num = sortedYData[SortedIndex].num;
sortedCellsData[curr_y_start + curr_y_num] = cells[i];
++sortedYData[SortedIndex].num;
}
#if use_timers
QSortTimer.Start();
#endif
// Finally arrange the X-arrays
for (uint i = 0; i < SortedYSize; i++)
{
if (sortedYData[i].num != 0)
{
m_QSorter.Sort(sortedCellsData, sortedYData[i].start, sortedYData[i].start + sortedYData[i].num - 1);
}
}
#if use_timers
QSortTimer.Stop();
#endif
m_sorted = true;
#if use_timers
SortCellsTimer.Stop();
#endif
}
public uint TotalCells
{
get
{
return m_num_used_cells;
}
}
public uint ScanlineNumCells(uint y)
{
if (y - m_min_y > m_sorted_y.Data().Length)
return 0;
return (uint)m_sorted_y.Data()[(int)y - m_min_y].num;
}
public void ScanlineCells(uint y, out AntiAliasingCell[] CellData, out uint Offset)
{
CellData = m_sorted_cells.Data();
Offset = m_sorted_y[(int)y - m_min_y].start;
}
public bool IsSorted
{
get { return m_sorted; }
}
private void SetCurrentCell(int x, int y)
{
if (m_curr_cell.NotEqual(x, y, m_style_cell))
{
AddCurrentCell();
m_curr_cell.Style = m_style_cell;
m_curr_cell.x = x;
m_curr_cell.y = y;
m_curr_cell.cover = 0;
m_curr_cell.area = 0;
}
}
private void AddCurrentCell()
{
if ((m_curr_cell.area | m_curr_cell.cover) != 0)
{
if (m_num_used_cells >= (int)ECellBlockScale.Limit)
{
return;
}
AllocateCellsIfRequired();
m_cells.Data()[m_num_used_cells].Set(m_curr_cell);
m_num_used_cells++;
#if false
if(m_num_used_cells == 281)
{
int a = 12;
}
DebugFile.Print(m_num_used_cells.ToString()
+ ". x=" + m_curr_cell.m_x.ToString()
+ " y=" + m_curr_cell.m_y.ToString()
+ " area=" + m_curr_cell.m_area.ToString()
+ " cover=" + m_curr_cell.m_cover.ToString()
+ "\n");
#endif
}
}
private void AllocateCellsIfRequired()
{
if (m_cells == null || (m_num_used_cells + 1) >= m_cells.Capacity())
{
if (m_num_used_cells >= (int)ECellBlockScale.Limit)
{
return;
}
uint new_num_allocated_cells = m_num_used_cells + (uint)ECellBlockScale.Size;
VectorPOD<AntiAliasingCell> new_cells = new VectorPOD<AntiAliasingCell>(new_num_allocated_cells);
if (m_cells != null)
{
new_cells.CopyFrom(m_cells);
}
m_cells = new_cells;
}
}
private void RenderHorizontalLine(int ey, int x1, int y1, int x2, int y2)
{
int ex1 = x1 >> (int)poly_subpixel_scale_e.Shift;
int ex2 = x2 >> (int)poly_subpixel_scale_e.Shift;
int fx1 = x1 & (int)poly_subpixel_scale_e.Mask;
int fx2 = x2 & (int)poly_subpixel_scale_e.Mask;
int delta, p, first, dx;
int incr, lift, mod, rem;
//trivial case. Happens often
if (y1 == y2)
{
SetCurrentCell(ex2, ey);
return;
}
//everything is located in a single cell. That is easy!
if (ex1 == ex2)
{
delta = y2 - y1;
m_curr_cell.cover += delta;
m_curr_cell.area += (fx1 + fx2) * delta;
return;
}
//ok, we'll have to render a run of adjacent cells on the same hline...
p = ((int)poly_subpixel_scale_e.Scale - fx1) * (y2 - y1);
first = (int)poly_subpixel_scale_e.Scale;
incr = 1;
dx = x2 - x1;
if (dx < 0)
{
p = fx1 * (y2 - y1);
first = 0;
incr = -1;
dx = -dx;
}
delta = p / dx;
mod = p % dx;
if (mod < 0)
{
delta--;
mod += dx;
}
m_curr_cell.cover += delta;
m_curr_cell.area += (fx1 + first) * delta;
ex1 += incr;
SetCurrentCell(ex1, ey);
y1 += delta;
if (ex1 != ex2)
{
p = (int)poly_subpixel_scale_e.Scale * (y2 - y1 + delta);
lift = p / dx;
rem = p % dx;
if (rem < 0)
{
lift--;
rem += dx;
}
mod -= dx;
while (ex1 != ex2)
{
delta = lift;
mod += rem;
if (mod >= 0)
{
mod -= dx;
delta++;
}
m_curr_cell.cover += delta;
m_curr_cell.area += (int)poly_subpixel_scale_e.Scale * delta;
y1 += delta;
ex1 += incr;
SetCurrentCell(ex1, ey);
}
}
delta = y2 - y1;
m_curr_cell.cover += delta;
m_curr_cell.area += (fx2 + (int)poly_subpixel_scale_e.Scale - first) * delta;
}
private static void SwapCells(AntiAliasingCell a, AntiAliasingCell b)
{
AntiAliasingCell temp = a;
a = b;
b = temp;
}
private enum qsort { qsort_threshold = 9 };
}
//------------------------------------------------------ScanlineHitTest
public class ScanlineHitTest : IScanline
{
private int m_x;
private bool m_hit;
public ScanlineHitTest(int x)
{
m_x = x;
m_hit = false;
}
public void ResetSpans()
{
}
public void Finalize(int nothing)
{
}
public void AddCell(int x, uint nothing)
{
if (m_x == x) m_hit = true;
}
public void AddSpan(int x, int len, uint nothing)
{
if (m_x >= x && m_x < x + len) m_hit = true;
}
public uint NumberOfSpans
{
get
{
return 1;
}
}
public bool hit()
{
return m_hit;
}
public void Reset(int min_x, int max_x)
{
throw new System.NotImplementedException();
}
public ScanlineSpan Begin
{
get
{
throw new System.NotImplementedException();
}
}
public ScanlineSpan GetNextScanlineSpan()
{
throw new System.NotImplementedException();
}
public int y()
{
throw new System.NotImplementedException();
}
public byte[] GetCovers()
{
throw new System.NotImplementedException();
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V9.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V9.Services
{
/// <summary>Settings for <see cref="BillingSetupServiceClient"/> instances.</summary>
public sealed partial class BillingSetupServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="BillingSetupServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="BillingSetupServiceSettings"/>.</returns>
public static BillingSetupServiceSettings GetDefault() => new BillingSetupServiceSettings();
/// <summary>Constructs a new <see cref="BillingSetupServiceSettings"/> object with default settings.</summary>
public BillingSetupServiceSettings()
{
}
private BillingSetupServiceSettings(BillingSetupServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetBillingSetupSettings = existing.GetBillingSetupSettings;
MutateBillingSetupSettings = existing.MutateBillingSetupSettings;
OnCopy(existing);
}
partial void OnCopy(BillingSetupServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>BillingSetupServiceClient.GetBillingSetup</c> and <c>BillingSetupServiceClient.GetBillingSetupAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetBillingSetupSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>BillingSetupServiceClient.MutateBillingSetup</c> and <c>BillingSetupServiceClient.MutateBillingSetupAsync</c>
/// .
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateBillingSetupSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="BillingSetupServiceSettings"/> object.</returns>
public BillingSetupServiceSettings Clone() => new BillingSetupServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="BillingSetupServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class BillingSetupServiceClientBuilder : gaxgrpc::ClientBuilderBase<BillingSetupServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public BillingSetupServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public BillingSetupServiceClientBuilder()
{
UseJwtAccessWithScopes = BillingSetupServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref BillingSetupServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<BillingSetupServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override BillingSetupServiceClient Build()
{
BillingSetupServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<BillingSetupServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<BillingSetupServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private BillingSetupServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return BillingSetupServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<BillingSetupServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return BillingSetupServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => BillingSetupServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => BillingSetupServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => BillingSetupServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>BillingSetupService client wrapper, for convenient use.</summary>
/// <remarks>
/// A service for designating the business entity responsible for accrued costs.
///
/// A billing setup is associated with a payments account. Billing-related
/// activity for all billing setups associated with a particular payments account
/// will appear on a single invoice generated monthly.
///
/// Mutates:
/// The REMOVE operation cancels a pending billing setup.
/// The CREATE operation creates a new billing setup.
/// </remarks>
public abstract partial class BillingSetupServiceClient
{
/// <summary>
/// The default endpoint for the BillingSetupService service, which is a host of "googleads.googleapis.com" and
/// a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default BillingSetupService scopes.</summary>
/// <remarks>
/// The default BillingSetupService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="BillingSetupServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use
/// <see cref="BillingSetupServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="BillingSetupServiceClient"/>.</returns>
public static stt::Task<BillingSetupServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new BillingSetupServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="BillingSetupServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use
/// <see cref="BillingSetupServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="BillingSetupServiceClient"/>.</returns>
public static BillingSetupServiceClient Create() => new BillingSetupServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="BillingSetupServiceClient"/> which uses the specified call invoker for remote
/// operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="BillingSetupServiceSettings"/>.</param>
/// <returns>The created <see cref="BillingSetupServiceClient"/>.</returns>
internal static BillingSetupServiceClient Create(grpccore::CallInvoker callInvoker, BillingSetupServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
BillingSetupService.BillingSetupServiceClient grpcClient = new BillingSetupService.BillingSetupServiceClient(callInvoker);
return new BillingSetupServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC BillingSetupService client</summary>
public virtual BillingSetupService.BillingSetupServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns a billing setup.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::BillingSetup GetBillingSetup(GetBillingSetupRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns a billing setup.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::BillingSetup> GetBillingSetupAsync(GetBillingSetupRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns a billing setup.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::BillingSetup> GetBillingSetupAsync(GetBillingSetupRequest request, st::CancellationToken cancellationToken) =>
GetBillingSetupAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns a billing setup.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the billing setup to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::BillingSetup GetBillingSetup(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetBillingSetup(new GetBillingSetupRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns a billing setup.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the billing setup to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::BillingSetup> GetBillingSetupAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetBillingSetupAsync(new GetBillingSetupRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns a billing setup.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the billing setup to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::BillingSetup> GetBillingSetupAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetBillingSetupAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns a billing setup.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the billing setup to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::BillingSetup GetBillingSetup(gagvr::BillingSetupName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetBillingSetup(new GetBillingSetupRequest
{
ResourceNameAsBillingSetupName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns a billing setup.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the billing setup to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::BillingSetup> GetBillingSetupAsync(gagvr::BillingSetupName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetBillingSetupAsync(new GetBillingSetupRequest
{
ResourceNameAsBillingSetupName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns a billing setup.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the billing setup to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::BillingSetup> GetBillingSetupAsync(gagvr::BillingSetupName resourceName, st::CancellationToken cancellationToken) =>
GetBillingSetupAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates a billing setup, or cancels an existing billing setup.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BillingSetupError]()
/// [DateError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateBillingSetupResponse MutateBillingSetup(MutateBillingSetupRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates a billing setup, or cancels an existing billing setup.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BillingSetupError]()
/// [DateError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateBillingSetupResponse> MutateBillingSetupAsync(MutateBillingSetupRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates a billing setup, or cancels an existing billing setup.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BillingSetupError]()
/// [DateError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateBillingSetupResponse> MutateBillingSetupAsync(MutateBillingSetupRequest request, st::CancellationToken cancellationToken) =>
MutateBillingSetupAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates a billing setup, or cancels an existing billing setup.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BillingSetupError]()
/// [DateError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. Id of the customer to apply the billing setup mutate operation to.
/// </param>
/// <param name="operation">
/// Required. The operation to perform.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateBillingSetupResponse MutateBillingSetup(string customerId, BillingSetupOperation operation, gaxgrpc::CallSettings callSettings = null) =>
MutateBillingSetup(new MutateBillingSetupRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operation = gax::GaxPreconditions.CheckNotNull(operation, nameof(operation)),
}, callSettings);
/// <summary>
/// Creates a billing setup, or cancels an existing billing setup.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BillingSetupError]()
/// [DateError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. Id of the customer to apply the billing setup mutate operation to.
/// </param>
/// <param name="operation">
/// Required. The operation to perform.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateBillingSetupResponse> MutateBillingSetupAsync(string customerId, BillingSetupOperation operation, gaxgrpc::CallSettings callSettings = null) =>
MutateBillingSetupAsync(new MutateBillingSetupRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operation = gax::GaxPreconditions.CheckNotNull(operation, nameof(operation)),
}, callSettings);
/// <summary>
/// Creates a billing setup, or cancels an existing billing setup.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BillingSetupError]()
/// [DateError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. Id of the customer to apply the billing setup mutate operation to.
/// </param>
/// <param name="operation">
/// Required. The operation to perform.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateBillingSetupResponse> MutateBillingSetupAsync(string customerId, BillingSetupOperation operation, st::CancellationToken cancellationToken) =>
MutateBillingSetupAsync(customerId, operation, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>BillingSetupService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// A service for designating the business entity responsible for accrued costs.
///
/// A billing setup is associated with a payments account. Billing-related
/// activity for all billing setups associated with a particular payments account
/// will appear on a single invoice generated monthly.
///
/// Mutates:
/// The REMOVE operation cancels a pending billing setup.
/// The CREATE operation creates a new billing setup.
/// </remarks>
public sealed partial class BillingSetupServiceClientImpl : BillingSetupServiceClient
{
private readonly gaxgrpc::ApiCall<GetBillingSetupRequest, gagvr::BillingSetup> _callGetBillingSetup;
private readonly gaxgrpc::ApiCall<MutateBillingSetupRequest, MutateBillingSetupResponse> _callMutateBillingSetup;
/// <summary>
/// Constructs a client wrapper for the BillingSetupService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="BillingSetupServiceSettings"/> used within this client.</param>
public BillingSetupServiceClientImpl(BillingSetupService.BillingSetupServiceClient grpcClient, BillingSetupServiceSettings settings)
{
GrpcClient = grpcClient;
BillingSetupServiceSettings effectiveSettings = settings ?? BillingSetupServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetBillingSetup = clientHelper.BuildApiCall<GetBillingSetupRequest, gagvr::BillingSetup>(grpcClient.GetBillingSetupAsync, grpcClient.GetBillingSetup, effectiveSettings.GetBillingSetupSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetBillingSetup);
Modify_GetBillingSetupApiCall(ref _callGetBillingSetup);
_callMutateBillingSetup = clientHelper.BuildApiCall<MutateBillingSetupRequest, MutateBillingSetupResponse>(grpcClient.MutateBillingSetupAsync, grpcClient.MutateBillingSetup, effectiveSettings.MutateBillingSetupSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateBillingSetup);
Modify_MutateBillingSetupApiCall(ref _callMutateBillingSetup);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetBillingSetupApiCall(ref gaxgrpc::ApiCall<GetBillingSetupRequest, gagvr::BillingSetup> call);
partial void Modify_MutateBillingSetupApiCall(ref gaxgrpc::ApiCall<MutateBillingSetupRequest, MutateBillingSetupResponse> call);
partial void OnConstruction(BillingSetupService.BillingSetupServiceClient grpcClient, BillingSetupServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC BillingSetupService client</summary>
public override BillingSetupService.BillingSetupServiceClient GrpcClient { get; }
partial void Modify_GetBillingSetupRequest(ref GetBillingSetupRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_MutateBillingSetupRequest(ref MutateBillingSetupRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns a billing setup.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::BillingSetup GetBillingSetup(GetBillingSetupRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetBillingSetupRequest(ref request, ref callSettings);
return _callGetBillingSetup.Sync(request, callSettings);
}
/// <summary>
/// Returns a billing setup.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::BillingSetup> GetBillingSetupAsync(GetBillingSetupRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetBillingSetupRequest(ref request, ref callSettings);
return _callGetBillingSetup.Async(request, callSettings);
}
/// <summary>
/// Creates a billing setup, or cancels an existing billing setup.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BillingSetupError]()
/// [DateError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override MutateBillingSetupResponse MutateBillingSetup(MutateBillingSetupRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateBillingSetupRequest(ref request, ref callSettings);
return _callMutateBillingSetup.Sync(request, callSettings);
}
/// <summary>
/// Creates a billing setup, or cancels an existing billing setup.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BillingSetupError]()
/// [DateError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<MutateBillingSetupResponse> MutateBillingSetupAsync(MutateBillingSetupRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateBillingSetupRequest(ref request, ref callSettings);
return _callMutateBillingSetup.Async(request, callSettings);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using HtmlAgilityPack;
namespace TungHoanhReader.Wrapper
{
public static class Extensions
{
public static string ToLsbString(this TagTruyen enumerationValue)
{
Type type = enumerationValue.GetType();
//Tries to find a DescriptionAttribute for a potential friendly name
//for the enum
var memberInfo = type.GetRuntimeFields();
if (memberInfo != null && memberInfo.First(o => o.Name == enumerationValue.ToString()) != null)
{
var attr = memberInfo.First(o => o.Name == enumerationValue.ToString()).GetCustomAttribute(typeof(LSBStringValue), false) as LSBStringValue;
if (attr != null) return attr.Value;
}
//If we have no description attribute, just return the ToString of the enum
return enumerationValue.ToString();
}
public static string ToTruyenConvertString(this TagTruyen enumerationValue)
{
Type type = enumerationValue.GetType();
//Tries to find a DescriptionAttribute for a potential friendly name
//for the enum
var memberInfo = type.GetRuntimeFields();
if (memberInfo != null && memberInfo.First(o => o.Name == enumerationValue.ToString()) != null)
{
var attr = memberInfo.First(o => o.Name == enumerationValue.ToString()).GetCustomAttribute(typeof(TruyenConvertStringValue), false) as TruyenConvertStringValue;
if (attr != null) return attr.Value;
}
//If we have no description attribute, just return the ToString of the enum
return enumerationValue.ToString();
}
public static string ToLsbHienThiString(this TagTruyen enumerationValue)
{
Type type = enumerationValue.GetType();
//Tries to find a DescriptionAttribute for a potential friendly name
//for the enum
var memberInfo = type.GetRuntimeFields();
if (memberInfo != null && memberInfo.First(o => o.Name == enumerationValue.ToString()) != null)
{
var attr = memberInfo.First(o => o.Name == enumerationValue.ToString()).GetCustomAttribute(typeof(HienThiStringValue), false) as HienThiStringValue;
if (attr != null) return attr.Value;
}
//If we have no description attribute, just return the ToString of the enum
return enumerationValue.ToString();
}
/// <summary>
/// Extension method for xpath support selectNodes with simple xpath query on ly support xpat with / and xpath [number]
/// example xpath /html/body/div[2]/div[2]/di
/// </summary>
/// <param name="dom"></param>
/// <param name="xpathquery"></param>
/// <returns></returns>
public static List<HtmlNode> SelectNodes(this HtmlNode dom, string xpathquery)
{
if (xpathquery.Contains(":"))
{
throw new InvalidDataException("This method don't support this query");
}
HtmlNode currentNode = dom;
if (xpathquery.StartsWith("/"))
{
xpathquery = xpathquery.Substring(1, xpathquery.Length - 1);
currentNode = currentNode.OwnerDocument.DocumentNode;
}
else if (xpathquery.StartsWith("./"))
{
xpathquery = xpathquery.Substring(2, xpathquery.Length - 2);
}
var listQuery = xpathquery.Split('/');
List<HtmlNode> listResultNode = null;
for (int i = 0; i < listQuery.Length; i++)
{
listResultNode = null;
var currentQuery = listQuery[i];
if (string.IsNullOrEmpty(currentQuery))
{
// process // query for one node only
// find first child node for next node
//lay node ke tiep ra tim kiem
var nextquery = listQuery[++i];
foreach (var iNode in currentNode.Descendants())
{
var tNode = iNode.SelectNodes(nextquery);
listResultNode = tNode;
if (tNode != null && tNode.Count >= 1)
{
currentNode = tNode[0];
break;
}
}
if (currentNode == null) return null;
}
else if (currentQuery.Contains("[@"))
{
currentQuery = currentQuery.Replace("\"", "'");
var nodeNameFound = currentQuery.Substring(0, currentQuery.IndexOf("["));
var atributeName = currentQuery.Substring(currentQuery.IndexOf("@") + 1, currentQuery.IndexOf("=") - currentQuery.IndexOf("@") - 1);
var atributeValue = currentQuery.Substring(currentQuery.IndexOf("'") + 1, currentQuery.LastIndexOf("'") - currentQuery.IndexOf("'") - 1);
foreach (var iNode in currentNode.Descendants(nodeNameFound))
{
if (iNode.GetAttributeValue(atributeName, "") != null &&
iNode.GetAttributeValue(atributeName, "") == atributeValue)
{
currentNode = iNode;
break;
}
}
if (currentNode == null || currentNode.Name != nodeNameFound) return null;
if (i >= listQuery.Length - 1)
{
var result = new List<HtmlNode>();
result.Add(currentNode);
return result;
}
}
else if (currentQuery.Contains("["))
{
//neu' k0 co' node tra? ve null;
// lay' thu' tu. cua? node
var numberStr = currentQuery.Substring(currentQuery.IndexOf("[") + 1, currentQuery.IndexOf("]") - currentQuery.IndexOf("[") - 1);
var number = 0;
int.TryParse(numberStr, out number);
currentQuery = currentQuery.Substring(0, currentQuery.IndexOf("["));
//if (dom.ChildNodes.Where(o => o.Name == currentQuery) == null) return null;
var listNode = currentNode.ChildNodes.Where(o => o.Name == currentQuery);
var htmlNodes = listNode.ToList();
if (htmlNodes.Count() > number - 1)
{
currentNode = htmlNodes[number - 1];
}
else
{
return null;
}
if (i >= listQuery.Length - 1)
{
var result = new List<HtmlNode>();
result.Add(currentNode);
return result;
}
}
else
{
//neu' nhu tim` kiem toi' hang cuoi cung roi`
if (i >= listQuery.Length - 1)
{
return currentNode.ChildNodes.Where(o => o.Name == currentQuery).ToList();
}
//neu nhu chi thay' 1 nut' tuong ung' thi` gan' nu't hien tai. la` nut' do'
if (dom.ChildNodes.FirstOrDefault(o => o.Name == currentQuery) != null)
{
currentNode = dom.ChildNodes.First(o => o.Name == currentQuery);
}
else
{
//ko co' thi` tra? ve null
return null;
}
}
}
return listResultNode;
}
/// <summary>
/// Extension method for xpath support selectNodes with simple xpath query on ly support xpat with / and xpath [number]
/// example xpath /html/body/div[2]/div[2]/di
/// </summary>
/// <param name="dom"></param>
/// <param name="xpathquery"></param>
/// <returns></returns>
public static HtmlNode SelectSingleNode(this HtmlNode dom, string xpathquery)
{
if (xpathquery.Contains(":"))
{
throw new InvalidDataException("This method don't support this query");
}
var result = dom.SelectNodes(xpathquery);
if (result == null || result.Count != 1) return null;
if (result.Count == 1)
{
return result[0];
}
return null;
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
#if UNITY_EDITOR
using UnityEditor;
using System.Linq;
#endif
// Uni2D sprite animation
[System.Serializable]
public class Uni2DSpriteAnimation
{
// Animation end handler
public delegate void AnimationEndEventHandler(Uni2DAnimationEvent a_rAnimationEvent);
// Animation frame event handler
public delegate void AnimationFrameEventHandler(Uni2DAnimationFrameEvent a_rAnimationFrameEvent);
// Handler called on animation end (i.e. NormalizedTime == 1.0f in forward play(positive speed) or NormalizedTime == 0.0f in backward play (negative speed))
// Called at each loop end for Loop and PingPong wrap mode
public AnimationEndEventHandler onAnimationEndEvent;
// Handler called at the begining of each frame where the "trigger event" checkbox is checked
public AnimationFrameEventHandler onAnimationFrameEvent;
// Animation player
private Uni2DAnimationPlayer m_rAnimationPlayer = new Uni2DAnimationPlayer( );
// Animation clips
[SerializeField]
private Uni2DAnimationClip[ ] m_rAnimationClips;
// Clip index
[SerializeField]
private int m_iStartClipIndex;
// Play automatically
public bool playAutomatically = true;
// Current clip index
private int m_iCurrentClipIndex = -1;
// The sprite
private Uni2DSprite m_rSprite;
// Clip index by name
private Dictionary<string, int> m_oClipIndexByName;
// Sprite
public Uni2DSprite Sprite
{
get
{
return m_rSprite;
}
}
// WrapMode
public Uni2DAnimationClip.WrapMode WrapMode
{
get
{
return m_rAnimationPlayer.WrapMode;
}
set
{
m_rAnimationPlayer.WrapMode = value;
}
}
// Framerate
public float FrameRate
{
get
{
return m_rAnimationPlayer.FrameRate;
}
set
{
m_rAnimationPlayer.FrameRate = value;
}
}
// Frame Count
public int FrameCount
{
get
{
return m_rAnimationPlayer.FrameCount;
}
}
// Frame Index
public int FrameIndex
{
get
{
return m_rAnimationPlayer.FrameIndex;
}
set
{
m_rAnimationPlayer.FrameIndex = value;
}
}
// Frame Name
public string FrameName
{
get
{
return m_rAnimationPlayer.FrameName;
}
set
{
m_rAnimationPlayer.FrameName = value;
}
}
// Frame
public Uni2DAnimationFrame Frame
{
get
{
return m_rAnimationPlayer.Frame;
}
}
// Time
public float Time
{
get
{
return m_rAnimationPlayer.Time;
}
set
{
// Set animation time
m_rAnimationPlayer.Time = value;
}
}
// NormalizedTime
public float NormalizedTime
{
get
{
return m_rAnimationPlayer.NormalizedTime;
}
set
{
m_rAnimationPlayer.NormalizedTime = value;
}
}
// Speed
public float Speed
{
get
{
return m_rAnimationPlayer.Speed;
}
set
{
m_rAnimationPlayer.Speed = value;
}
}
// Length
public float Length
{
get
{
return m_rAnimationPlayer.Length;
}
}
// Current clip name
public string Name
{
get
{
return m_rAnimationPlayer.Name;
}
}
// Current clip index
// return -1 if no clip is playing
public int CurrentClipIndex
{
get
{
return m_iCurrentClipIndex;
}
}
// Clip played
public Uni2DAnimationClip Clip
{
get
{
return m_rAnimationPlayer.Clip;
}
}
// Number of clip
public int ClipCount
{
get
{
return m_rAnimationClips != null ? m_rAnimationClips.Length : 0;
}
}
// Paused
public bool Paused
{
get
{
return m_rAnimationPlayer.Paused;
}
set
{
m_rAnimationPlayer.Paused = value;
}
}
// Is Playing
public bool IsPlaying
{
get
{
return m_rAnimationPlayer.Active;
}
}
// Play the current clip from the beginning
public void Play()
{
Play(m_iCurrentClipIndex);
}
// Stop playing the current clip
public void Stop(bool a_bResetToMainFrame = true)
{
m_rAnimationPlayer.Stop( a_bResetToMainFrame );
}
// Pause
public void Pause()
{
Paused = true;
}
// Resume
public void Resume()
{
Paused = false;
}
// Play the clip from the beginning by name
// Return false if the clip doesn't exist
public bool Play(string a_oClipName)
{
int iClipIndex = GetClipIndexByName(a_oClipName);
return Play(iClipIndex);
}
// Play the clip from the beginning
// Return false if the clip doesn't exist
public bool Play(int a_iClipIndex)
{
if(IsValidClipIndex(a_iClipIndex))
{
// Get the clip
m_iCurrentClipIndex = a_iClipIndex;
// Play
m_rAnimationPlayer.Play(m_rAnimationClips[a_iClipIndex]);
return true;
}
else
{
return false;
}
}
// Get clip by index
public Uni2DAnimationClip GetClipByIndex(int a_iClipIndex)
{
if(IsValidClipIndex(a_iClipIndex))
{
return m_rAnimationClips[a_iClipIndex];
}
else
{
return null;
}
}
// Get clip by index
public Uni2DAnimationClip GetClipByName(string a_oClipName)
{
return GetClipByIndex(GetClipIndexByName(a_oClipName));
}
// Get clip index by name
public int GetClipIndexByName(string a_oClipName)
{
Dictionary<string, int> oClipIndexByName = GetClipIndexByName();
int iClipIndex;
if(oClipIndexByName.TryGetValue(a_oClipName, out iClipIndex))
{
return iClipIndex;
}
else
{
return -1;
}
}
// Start
public void Start(Uni2DSprite a_rSprite)
{
m_rSprite = a_rSprite;
m_iCurrentClipIndex = m_iStartClipIndex;
// Setup animation player
m_rAnimationPlayer.onAnimationFrameEvent += RaiseAnimationFrameEvent;
m_rAnimationPlayer.onAnimationNewFrameEvent += RaiseAnimationNewFrameEvent; // New frame event
m_rAnimationPlayer.onAnimationEndEvent += RaiseAnimationEndEvent;
m_rAnimationPlayer.onAnimationInactiveEvent += RaiseAnimationInactiveEvent;
if( playAutomatically )
{
this.Play( );
}
}
// Update
public void Update(float a_fDeltaTime)
{
m_rAnimationPlayer.Update( a_fDeltaTime );
}
// Is valid clip index
private bool IsValidClipIndex(int a_iClipIndex)
{
return m_rAnimationClips != null && a_iClipIndex >= 0 && a_iClipIndex < m_rAnimationClips.Length;
}
// On new frame
private void RaiseAnimationNewFrameEvent( Uni2DAnimationPlayer a_rAnimationPlayer ) // On New Frame
{
m_rSprite.SetFrame( m_rAnimationPlayer.Frame );
}
// Raise animation end event
private void RaiseAnimationEndEvent( Uni2DAnimationPlayer a_rAnimationPlayer, Uni2DAnimationClip a_rAnimationClip )
{
if( onAnimationEndEvent != null )
{
onAnimationEndEvent( new Uni2DAnimationEvent( this, this.GetClipIndexByName( a_rAnimationClip.name ), a_rAnimationClip ) );
}
}
// Raise animation frame event
private void RaiseAnimationFrameEvent( Uni2DAnimationPlayer a_rAnimationPlayer )
{
if( onAnimationFrameEvent != null )
{
onAnimationFrameEvent(new Uni2DAnimationFrameEvent(this, m_iCurrentClipIndex, m_rAnimationClips[ m_iCurrentClipIndex ] , a_rAnimationPlayer.FrameIndex, a_rAnimationPlayer.Frame ) );
}
}
// Releases the sprite when animation is inactive (the sprite is no longer animated)
private void RaiseAnimationInactiveEvent( Uni2DAnimationPlayer a_rAnimationPlayer )
{
m_rSprite.ResetToMainFrame( );
}
// Get Clip Index By Name
private Dictionary<string, int> GetClipIndexByName()
{
if(m_oClipIndexByName == null)
{
BuildClipIndexByName();
}
return m_oClipIndexByName;
}
// Build Clip Index By Name
private void BuildClipIndexByName()
{
m_oClipIndexByName = new Dictionary<string, int>();
int iClipIndex = 0;
foreach(Uni2DAnimationClip rClip in m_rAnimationClips)
{
if(rClip != null)
{
if(m_oClipIndexByName.ContainsKey(rClip.name) == false)
{
m_oClipIndexByName.Add(rClip.name, iClipIndex);
}
}
iClipIndex++;
}
}
#if UNITY_EDITOR
public Uni2DAnimationClip[] Clips
{
get
{
return m_rAnimationClips;
}
}
public int StartClipIndex
{
get
{
return m_iStartClipIndex;
}
set
{
if( IsValidClipIndex( value ) )
{
m_iStartClipIndex = value;
}
}
}
// Swaps 2 clips specified by their index
public void SwapClips( int a_iClipIndexA, int a_iClipIndexB )
{
if( a_iClipIndexA != a_iClipIndexB && this.IsValidClipIndex( a_iClipIndexA ) && this.IsValidClipIndex( a_iClipIndexB ) )
{
// Update start clip index
if( a_iClipIndexA == m_iStartClipIndex )
{
m_iStartClipIndex = a_iClipIndexB;
}
else if( a_iClipIndexB == m_iStartClipIndex )
{
m_iStartClipIndex = a_iClipIndexA;
}
// Swap clips
Uni2DAnimationClip rTmp = m_rAnimationClips[ a_iClipIndexA ];
m_rAnimationClips[ a_iClipIndexA ] = m_rAnimationClips[ a_iClipIndexB ];
m_rAnimationClips[ a_iClipIndexB ] = rTmp;
}
}
// Add a clip to the list
public void AddClip( Uni2DAnimationClip a_rAnimationClip )
{
if( a_rAnimationClip != null )
{
int iClipCount = this.ClipCount;
// Prevent to add a clip twice
for( int iClipIndex = 0; iClipIndex < iClipCount; ++iClipIndex )
{
if( a_rAnimationClip == m_rAnimationClips[ iClipIndex ] )
{
return;
}
}
Uni2DAnimationClip[ ] oAnimationClips = new Uni2DAnimationClip[ iClipCount + 1 ];
if( m_rAnimationClips != null )
{
m_rAnimationClips.CopyTo( oAnimationClips, 0 );
}
oAnimationClips[ iClipCount ] = a_rAnimationClip;
m_rAnimationClips = oAnimationClips;
}
}
// Remove a clip specified by the given index
public void RemoveClip( int a_iClipToRemoveIndex )
{
if( this.IsValidClipIndex( a_iClipToRemoveIndex ) )
{
if( m_iStartClipIndex == a_iClipToRemoveIndex )
{
//playAutomatically = false;
m_iStartClipIndex = 0;
}
int iClipCount = this.ClipCount;
Uni2DAnimationClip[ ] oAnimationClips = new Uni2DAnimationClip[ iClipCount - 1 ];
for( int iClipIndex = 0; iClipIndex < a_iClipToRemoveIndex; ++iClipIndex )
{
oAnimationClips[ iClipIndex ] = m_rAnimationClips[ iClipIndex ];
}
for( int iClipIndex = a_iClipToRemoveIndex + 1; iClipIndex < iClipCount; ++iClipIndex )
{
oAnimationClips[ iClipIndex - 1 ] = m_rAnimationClips[ iClipIndex ];
}
m_rAnimationClips = oAnimationClips;
}
}
// Deletes null animation clip references (which appear after deleting a clip resource)
public void CleanDeletedAnimationClips( )
{
Uni2DAnimationClip rStartAnimationClip = playAutomatically
? m_rAnimationClips[ m_iStartClipIndex ]
: null;
// LINQ: Select only non null clips
m_rAnimationClips = m_rAnimationClips.Where( x => x != null ).ToArray( );
if( rStartAnimationClip != null )
{
m_iStartClipIndex = ArrayUtility.IndexOf<Uni2DAnimationClip>( m_rAnimationClips, rStartAnimationClip );
}
else
{
// Turn off auto play if clip array is empty
playAutomatically = ( m_rAnimationClips.Length > 0 ? playAutomatically : false );
m_iStartClipIndex = 0;
}
}
#endif
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Logic
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Rest.Azure.OData;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// MapsOperations operations.
/// </summary>
internal partial class MapsOperations : IServiceOperations<LogicManagementClient>, IMapsOperations
{
/// <summary>
/// Initializes a new instance of the MapsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal MapsOperations(LogicManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the LogicManagementClient
/// </summary>
public LogicManagementClient Client { get; private set; }
/// <summary>
/// Gets a list of integration account maps.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<IntegrationAccountMap>>> ListByIntegrationAccountsWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, ODataQuery<IntegrationAccountMapFilter> odataQuery = default(ODataQuery<IntegrationAccountMapFilter>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (integrationAccountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "integrationAccountName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("odataQuery", odataQuery);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("integrationAccountName", integrationAccountName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByIntegrationAccounts", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/maps").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{integrationAccountName}", System.Uri.EscapeDataString(integrationAccountName));
List<string> _queryParameters = new List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<IntegrationAccountMap>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<IntegrationAccountMap>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets an integration account map.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='mapName'>
/// The integration account map name.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IntegrationAccountMap>> GetWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, string mapName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (integrationAccountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "integrationAccountName");
}
if (mapName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "mapName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("integrationAccountName", integrationAccountName);
tracingParameters.Add("mapName", mapName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/maps/{mapName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{integrationAccountName}", System.Uri.EscapeDataString(integrationAccountName));
_url = _url.Replace("{mapName}", System.Uri.EscapeDataString(mapName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IntegrationAccountMap>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<IntegrationAccountMap>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates an integration account map.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='mapName'>
/// The integration account map name.
/// </param>
/// <param name='map'>
/// The integration account map.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IntegrationAccountMap>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, string mapName, IntegrationAccountMap map, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (integrationAccountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "integrationAccountName");
}
if (mapName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "mapName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (map == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "map");
}
if (map != null)
{
map.Validate();
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("integrationAccountName", integrationAccountName);
tracingParameters.Add("mapName", mapName);
tracingParameters.Add("map", map);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/maps/{mapName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{integrationAccountName}", System.Uri.EscapeDataString(integrationAccountName));
_url = _url.Replace("{mapName}", System.Uri.EscapeDataString(mapName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(map != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(map, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IntegrationAccountMap>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<IntegrationAccountMap>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<IntegrationAccountMap>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes an integration account map.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='mapName'>
/// The integration account map name.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, string mapName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (integrationAccountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "integrationAccountName");
}
if (mapName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "mapName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("integrationAccountName", integrationAccountName);
tracingParameters.Add("mapName", mapName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/maps/{mapName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{integrationAccountName}", System.Uri.EscapeDataString(integrationAccountName));
_url = _url.Replace("{mapName}", System.Uri.EscapeDataString(mapName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a list of integration account maps.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<IntegrationAccountMap>>> ListByIntegrationAccountsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByIntegrationAccountsNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<IntegrationAccountMap>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<IntegrationAccountMap>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// 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.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DevTestLabs
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// VirtualMachineOperations operations.
/// </summary>
public partial interface IVirtualMachineOperations
{
/// <summary>
/// List virtual machines in a given lab.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<LabVirtualMachine>>> ListWithHttpMessagesAsync(string resourceGroupName, string labName, ODataQuery<LabVirtualMachine> odataQuery = default(ODataQuery<LabVirtualMachine>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get virtual machine.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual Machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<LabVirtualMachine>> GetResourceWithHttpMessagesAsync(string resourceGroupName, string labName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create or replace an existing Virtual Machine. This operation can
/// take a while to complete.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual Machine.
/// </param>
/// <param name='labVirtualMachine'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<LabVirtualMachine>> CreateOrUpdateResourceWithHttpMessagesAsync(string resourceGroupName, string labName, string name, LabVirtualMachine labVirtualMachine, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create or replace an existing Virtual Machine. This operation can
/// take a while to complete.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual Machine.
/// </param>
/// <param name='labVirtualMachine'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<LabVirtualMachine>> BeginCreateOrUpdateResourceWithHttpMessagesAsync(string resourceGroupName, string labName, string name, LabVirtualMachine labVirtualMachine, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete virtual machine. This operation can take a while to
/// complete.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual Machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> DeleteResourceWithHttpMessagesAsync(string resourceGroupName, string labName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete virtual machine. This operation can take a while to
/// complete.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual Machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> BeginDeleteResourceWithHttpMessagesAsync(string resourceGroupName, string labName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Modify properties of virtual machines.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual Machine.
/// </param>
/// <param name='labVirtualMachine'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<LabVirtualMachine>> PatchResourceWithHttpMessagesAsync(string resourceGroupName, string labName, string name, LabVirtualMachine labVirtualMachine, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Apply artifacts to Lab VM. This operation can take a while to
/// complete.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual Machine.
/// </param>
/// <param name='applyArtifactsRequest'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> ApplyArtifactsWithHttpMessagesAsync(string resourceGroupName, string labName, string name, ApplyArtifactsRequest applyArtifactsRequest, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Apply artifacts to Lab VM. This operation can take a while to
/// complete.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual Machine.
/// </param>
/// <param name='applyArtifactsRequest'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> BeginApplyArtifactsWithHttpMessagesAsync(string resourceGroupName, string labName, string name, ApplyArtifactsRequest applyArtifactsRequest, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Start a Lab VM. This operation can take a while to complete.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual Machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> StartWithHttpMessagesAsync(string resourceGroupName, string labName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Start a Lab VM. This operation can take a while to complete.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual Machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> BeginStartWithHttpMessagesAsync(string resourceGroupName, string labName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Stop a Lab VM. This operation can take a while to complete.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual Machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> StopWithHttpMessagesAsync(string resourceGroupName, string labName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Stop a Lab VM. This operation can take a while to complete.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual Machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> BeginStopWithHttpMessagesAsync(string resourceGroupName, string labName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List virtual machines in a given lab.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<LabVirtualMachine>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// 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.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
namespace Microsoft.Cci.Extensions
{
public enum ErrorTreatment
{
Default,
TreatAsWarning,
Ignore
}
public class HostEnvironment : MetadataReaderHost
{
private PeReader _reader;
private HashSet<UnresolvedReference<IUnit, AssemblyIdentity>> _unresolvedIdentities;
private AssemblyIdentity _coreAssemblyIdentity;
public HostEnvironment()
: this(new NameTable(), new InternFactory())
{
}
public HostEnvironment(INameTable nameTable)
: this(nameTable, new InternFactory())
{
}
public HostEnvironment(IInternFactory internFactory)
: this(new NameTable(), internFactory)
{
}
public HostEnvironment(INameTable nameTable, IInternFactory internFactory)
: base(nameTable, internFactory, 0, null, false)
{
_reader = new PeReader(this);
_unresolvedIdentities = new HashSet<UnresolvedReference<IUnit, AssemblyIdentity>>();
}
public bool UnifyToLibPath { get; set; }
public ICollection<UnresolvedReference<IUnit, AssemblyIdentity>> UnresolvedIdentities { get { return _unresolvedIdentities; } }
public bool ResolveInReferringUnitLocation { get; set; }
public bool ResolveAgainstRunningFramework { get; set; }
public event EventHandler<UnresolvedReference<IUnit, AssemblyIdentity>> UnableToResolve;
public void AddLibPaths(IEnumerable<string> paths)
{
if (paths == null)
return;
foreach (var path in paths)
AddLibPath(path);
}
public void Cleanup()
{
_reader = null;
}
public override IUnit LoadUnitFrom(string location)
{
IUnit unit = _reader.OpenModule(
BinaryDocument.GetBinaryDocumentForFile(location, this));
this.RegisterAsLatest(unit);
return unit;
}
public IAssembly LoadAssemblyFrom(string location)
{
return LoadUnitFrom(location) as IAssembly;
}
/// <summary>
/// Loads the unit from the given stream. The caller should dispose the
/// stream after the API is called (the stream contents will have been copied
/// to unmanaged memory already).
/// </summary>
/// <param name="location">The location to be exposed from IUnit</param>
/// <param name="stream">The data to be used as the unit</param>
public IUnit LoadUnitFrom(string location, Stream stream)
{
string fileName = Path.GetFileName(location);
IName name = this.NameTable.GetNameFor(fileName);
StreamDocument document = new StreamDocument(location, name, stream);
IModule unit = _reader.OpenModule(document);
this.RegisterAsLatest(unit);
return unit;
}
public IAssembly LoadAssemblyFrom(string location, Stream stream)
{
return LoadUnitFrom(location, stream) as IAssembly;
}
public IAssembly LoadAssembly(string assemblyNameOrPath)
{
string path = assemblyNameOrPath;
if (File.Exists(path))
return this.LoadAssemblyFrom(path);
foreach (var extension in s_probingExtensions)
{
path = ProbeLibPaths(assemblyNameOrPath + extension);
if (path != null)
{
var assembly = this.LoadAssembly(path);
if (assembly == null) continue;
return assembly;
}
}
return null;
}
private AssemblyIdentity ProbeLibPaths(AssemblyIdentity identity)
{
foreach (var libPath in LibPaths)
{
AssemblyIdentity probedIdentity = this.Probe(libPath, identity);
if (probedIdentity != null)
return probedIdentity;
}
return new AssemblyIdentity(identity, "");
}
private string ProbeLibPaths(string assemblyPath)
{
if (File.Exists(assemblyPath))
return assemblyPath;
foreach (var libPath in LibPaths)
{
string combinedPath = Path.Combine(libPath, assemblyPath);
if (File.Exists(combinedPath))
return combinedPath;
}
return null;
}
// Potential way to unify assemblies based on the current runtime
//public override void ResolvingAssemblyReference(IUnit referringUnit, AssemblyIdentity referencedAssembly)
//{
// IAssemblyReference asmRef = referringUnit.UnitReferences.OfType<IAssemblyReference>()
// .FirstOrDefault(a => referencedAssembly.Equals(a.UnifiedAssemblyIdentity));
// if (asmRef != null && asmRef.IsRetargetable)
// {
// string strongName = UnitHelper.StrongName(asmRef);
// string retargetedName = AppDomain.CurrentDomain.ApplyPolicy(strongName);
// if (strongName != retargetedName)
// {
// System.Reflection.AssemblyName name = new System.Reflection.AssemblyName(retargetedName);
// referencedAssembly = new AssemblyIdentity(this.NameTable.GetNameFor(name.Name),
// name.CultureInfo != null ? name.CultureInfo.Name : "", name.Version, name.GetPublicKeyToken(), "");
// }
// }
// base.ResolvingAssemblyReference(referringUnit, referencedAssembly);
//}
private static string[] s_probingExtensions = new string[]
{
".dll",
".ildll",
".ni.dll",
".winmd",
".exe",
".ilexe",
//".ni.exe" Do these actually exist?
};
protected override AssemblyIdentity Probe(string probeDir, AssemblyIdentity referencedAssembly)
{
Contract.Requires(probeDir != null);
Contract.Requires(referencedAssembly != null);
string path = null;
foreach (var extension in s_probingExtensions)
{
path = Path.Combine(probeDir, referencedAssembly.Name.Value + extension);
if (File.Exists(path))
{
// Possible that we might find an assembly with a matching extension but without a match identity
// or possibly be a native version of the assembly so if that fails we should try other extensions.
var assembly = this.LoadUnitFrom(path) as IAssembly;
if (assembly == null) continue;
if (this.UnifyToLibPath)
{
// If Unifying to LibPath then we only verify the assembly name matches.
if (assembly.AssemblyIdentity.Name.UniqueKeyIgnoringCase != referencedAssembly.Name.UniqueKeyIgnoringCase) continue;
}
else
{
if (!assembly.AssemblyIdentity.Equals(referencedAssembly)) continue;
}
return assembly.AssemblyIdentity;
}
}
return null;
}
protected override AssemblyIdentity GetCoreAssemblySymbolicIdentity()
{
// If explicitly set return that identity
if (_coreAssemblyIdentity != null)
return _coreAssemblyIdentity;
// Try to find the assembly which believes itself is the core assembly
foreach (var assembly in this.LoadedUnits.OfType<IAssembly>())
{
if (assembly.AssemblyIdentity.Equals(assembly.CoreAssemblySymbolicIdentity))
return assembly.AssemblyIdentity;
}
// Otherwise fallback to CCI's default core assembly loading logic.
return base.GetCoreAssemblySymbolicIdentity();
}
public void SetCoreAssembly(AssemblyIdentity coreAssembly)
{
if (_coreAssemblyIdentity != null)
{
throw new InvalidOperationException("The Core Assembly can only be set once.");
}
// Lets ignore this if someone passes dummy as nothing good can come from it. We considered making it an error
// but in some logical cases (i.e. facades) the CoreAssembly might be dummy and we don't want to start throwing
// in a bunch of cases where if we let it go the right thing will happen.
if (coreAssembly == Dummy.AssemblyIdentity)
return;
_coreAssemblyIdentity = coreAssembly;
}
private AssemblyIdentity FindUnifiedAssemblyIdentity(AssemblyIdentity identity)
{
Contract.Assert(this.UnifyToLibPath);
// Find exact assembly match
IAssembly asm = this.FindAssembly(identity);
if (asm != null && !(asm is Dummy))
return asm.AssemblyIdentity;
// Find assembly match based on simple name only. (It might be worth caching these results if we find them to be too expensive)
foreach (var loadedAssembly in this.LoadedUnits.OfType<IAssembly>())
{
if (loadedAssembly.AssemblyIdentity.Name.UniqueKeyIgnoringCase == identity.Name.UniqueKeyIgnoringCase)
return loadedAssembly.AssemblyIdentity;
}
AssemblyIdentity probedIdentity = this.ProbeLibPaths(identity);
if (probedIdentity != null)
return probedIdentity;
return new AssemblyIdentity(identity, "");
}
/// <summary>
/// Default implementation of UnifyAssembly. Override this method to change the behavior.
/// </summary>
public override AssemblyIdentity UnifyAssembly(AssemblyIdentity assemblyIdentity)
{
if (ShouldUnifyToCoreAssembly(assemblyIdentity))
return this.CoreAssemblySymbolicIdentity;
if (this.UnifyToLibPath)
assemblyIdentity = this.FindUnifiedAssemblyIdentity(assemblyIdentity);
return assemblyIdentity;
}
// Managed WinMDs: Their 'BCL' reference looks like this:
// .assembly extern mscorlib
// {
// .publickeytoken = (B7 7A 5C 56 19 34 E0 89 )
// .ver 255:255:255:255
// }
private static readonly byte[] s_ecmaKey = { 0xb7, 0x7a, 0x5c, 0x56, 0x19, 0x34, 0xe0, 0x89 };
private static readonly Version s_winmdBclVersion = new Version(255, 255, 255, 255);
public bool ShouldUnifyToCoreAssembly(AssemblyIdentity assemblyIdentity)
{
// Unify any other potential versions of this core assembly to itself.
if (assemblyIdentity.Name.UniqueKeyIgnoringCase == this.CoreAssemblySymbolicIdentity.Name.UniqueKeyIgnoringCase)
{
if (assemblyIdentity.PublicKeyToken == null ||
!assemblyIdentity.PublicKeyToken.SequenceEqual(this.CoreAssemblySymbolicIdentity.PublicKeyToken))
return false;
return true;
}
// Unify the mscorlib 255.255.255.255 used by winmds back to corefx to avoid the need for yet
// another facade.
if (assemblyIdentity.Name.Value == "mscorlib")
{
if (assemblyIdentity.PublicKeyToken == null || !assemblyIdentity.PublicKeyToken.SequenceEqual(s_ecmaKey))
return false;
if (!(assemblyIdentity.Version.Equals(s_winmdBclVersion)))
return false;
return true;
}
return false;
}
/// <summary>
/// Override ProbeAssemblyReference to ensure we only look in the LibPaths for resolving assemblies and
/// we don't accidently find some in the GAC or in the framework directory.
/// </summary>
public override AssemblyIdentity ProbeAssemblyReference(IUnit referringUnit, AssemblyIdentity referencedAssembly)
{
// We need to ensure the core assembly is being unified and in some code paths, such as from GetCoreAssemblySymbolicIdentity
// it doesn't get properly unified before calling ProbeAssemblyReference
if (this.CoreAssemblySymbolicIdentity.Equals(referencedAssembly))
referencedAssembly = UnifyAssembly(referencedAssembly);
AssemblyIdentity result = null;
if (this.ResolveInReferringUnitLocation)
{
// NOTE: When probing for the core assembly, the referring unit is a dummy unit and thus does not have
// a location.
string referringDir = string.IsNullOrEmpty(referringUnit.Location) ? null
: Path.GetDirectoryName(Path.GetFullPath(referringUnit.Location));
result = string.IsNullOrEmpty(referringDir) ? null
: this.Probe(referringDir, referencedAssembly);
if (result != null) return result;
}
// Probe in the libPaths directories
foreach (string libPath in this.LibPaths)
{
result = this.Probe(libPath, referencedAssembly);
if (result != null) return result;
}
if (this.ResolveAgainstRunningFramework)
{
// Call base probe which has logic to check the frameworks installed on the machine
result = base.ProbeAssemblyReference(referringUnit, referencedAssembly);
if (result != null && result.Location != null && !result.Location.StartsWith("unknown"))
return result;
}
var unresolved = new UnresolvedReference<IUnit, AssemblyIdentity>(referringUnit, referencedAssembly);
OnUnableToResolve(unresolved);
// Give up
return new AssemblyIdentity(referencedAssembly, "unknown://location");
}
protected virtual void OnUnableToResolve(UnresolvedReference<IUnit, AssemblyIdentity> unresolved)
{
var unableToResolve = this.UnableToResolve;
if (unableToResolve != null)
unableToResolve(this, unresolved);
this.UnresolvedIdentities.Add(unresolved);
}
// Overriding this method allows us to read the binaries without blocking the files. The default
// implementation will use a memory mapped file (MMF) which causes the files to be locked. That
// means you can delete them, but you can't overwrite them in-palce, which is especially painful
// when reading binaries directly from a build ouput folder.
//
// Measuring indicated that performance implications are negligible. That's why we decided to
// make this the default and not exposing any (more) options to our ctor.
public override IBinaryDocumentMemoryBlock OpenBinaryDocument(IBinaryDocument sourceDocument)
{
// First let's see whether the document is a stream-based document. In that case, we'll
// call the overload that processes the stream.
var streamDocument = sourceDocument as StreamDocument;
if (streamDocument != null)
return UnmanagedBinaryMemoryBlock.CreateUnmanagedBinaryMemoryBlock(streamDocument.Stream, sourceDocument);
// Otherwise we assume that we can load the data from the location of sourceDocument.
try
{
var memoryBlock = UnmanagedBinaryMemoryBlock.CreateUnmanagedBinaryMemoryBlock(sourceDocument.Location, sourceDocument);
disposableObjectAllocatedByThisHost.Add(memoryBlock);
return memoryBlock;
}
catch (IOException)
{
return null;
}
}
#region Assembly Set and Path Helpers
public static string[] SplitPaths(string pathSet)
{
if (pathSet == null)
return new string[0];
return pathSet.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
}
public static IEnumerable<IAssembly> LoadAssemblySet(params string[] paths)
{
HostEnvironment host = new HostEnvironment();
return host.LoadAssemblies(paths);
}
private string GetCoreAssemblyFile(string coreAssemblySimpleName, IEnumerable<string> contractSet)
{
var coreAssemblyFile = contractSet.FirstOrDefault(c => Path.GetFileNameWithoutExtension(c).EndsWith(coreAssemblySimpleName, StringComparison.OrdinalIgnoreCase) == true);
if (string.IsNullOrEmpty(coreAssemblyFile))
{
throw new InvalidOperationException(string.Format("Could not find core assembly '{0}' in the list of contracts.", coreAssemblySimpleName));
}
return coreAssemblyFile;
}
public ReadOnlyCollection<IAssembly> LoadAssemblies(string unsplitContractSet)
{
return LoadAssemblies(unsplitContractSet, string.Empty);
}
public ReadOnlyCollection<IAssembly> LoadAssemblies(string unsplitContractSet, string coreAssemblySimpleName)
{
List<string> contractSet = new List<string>(GetFilePathsAndAddResolvedDirectoriesToLibPaths(SplitPaths(unsplitContractSet)));
string coreAssemblyFile = null;
if (!string.IsNullOrEmpty(coreAssemblySimpleName))
{
// Otherwise, rearange the list such that the specified coreAssembly is the first one in the list.
coreAssemblyFile = GetCoreAssemblyFile(coreAssemblySimpleName, contractSet);
contractSet.Remove(coreAssemblyFile);
contractSet.Insert(0, coreAssemblyFile);
}
ReadOnlyCollection<IAssembly> assemblies = LoadAssemblies(contractSet);
// Explicitly set the core assembly
if (coreAssemblyFile != null && assemblies.Count > 0)
SetCoreAssembly(assemblies[0].AssemblyIdentity);
return assemblies;
}
public ErrorTreatment LoadErrorTreatment
{
get;
set;
}
// False by deafult for backwards compatibility with tools that wire in their own custom handlers.
private bool _traceResolutionErrorsAsLoadErrors;
public bool TraceResolutionErrorsAsLoadErrors
{
get
{
return _traceResolutionErrorsAsLoadErrors;
}
set
{
if (value != _traceResolutionErrorsAsLoadErrors)
{
if (value)
{
this.UnableToResolve += TraceResolveErrorAsLoadError;
}
else
{
this.UnableToResolve -= TraceResolveErrorAsLoadError;
}
_traceResolutionErrorsAsLoadErrors = value;
}
}
}
private void TraceResolveErrorAsLoadError(object sender, UnresolvedReference<IUnit, AssemblyIdentity> e)
{
TraceLoadError("Unable to resolve reference to {0}.", e.Unresolved);
}
public void TraceLoadError(string format, params object[] arguments)
{
switch (LoadErrorTreatment)
{
case ErrorTreatment.Default:
default:
Trace.TraceError(format, arguments);
break;
case ErrorTreatment.TreatAsWarning:
Trace.TraceWarning(format, arguments);
break;
case ErrorTreatment.Ignore:
break;
}
}
public ReadOnlyCollection<IAssembly> LoadAssemblies(IEnumerable<string> paths)
{
List<IAssembly> assemblySet = new List<IAssembly>();
IAssembly assembly = null;
foreach (string file in GetFilePathsAndAddResolvedDirectoriesToLibPaths(paths))
{
string filePath = ProbeLibPaths(file);
if (filePath == null)
{
TraceLoadError("File does not exist {0}", file);
continue;
}
assembly = this.LoadAssembly(filePath);
if (assembly == null)
{
TraceLoadError("Failed to load assembly {0}", filePath);
continue;
}
assemblySet.Add(assembly);
}
if (assemblySet.Count == 0)
{
TraceLoadError("No assemblies loaded for {0}", string.Join(", ", paths));
}
return new ReadOnlyCollection<IAssembly>(assemblySet);
}
public ReadOnlyCollection<IAssembly> LoadAssemblies(IEnumerable<string> paths, string coreAssemblySimpleName)
{
// Re-arrange the list of paths so that the coreAssembly is the first one in the list.
if (!string.IsNullOrEmpty(coreAssemblySimpleName))
{
var coreAssemblyFile = GetCoreAssemblyFile(coreAssemblySimpleName, paths);
paths = Enumerable.Concat(new List<string>() { coreAssemblyFile }, paths.Where(ai => !StringComparer.OrdinalIgnoreCase.Equals(ai, coreAssemblyFile)));
}
return LoadAssemblies(paths);
}
public IEnumerable<IAssembly> LoadAssemblies(IEnumerable<AssemblyIdentity> identities)
{
return LoadAssemblies(identities, false);
}
public IEnumerable<IAssembly> LoadAssemblies(IEnumerable<AssemblyIdentity> identities, bool warnOnVersionMismatch)
{
List<IAssembly> matchingAssemblies = new List<IAssembly>();
foreach (var unmappedIdentity in identities)
{
// Remap the name and clear the location.
AssemblyIdentity identity = new AssemblyIdentity(this.NameTable.GetNameFor(unmappedIdentity.Name.Value),
unmappedIdentity.Culture, unmappedIdentity.Version, unmappedIdentity.PublicKeyToken, "");
AssemblyIdentity matchingIdentity = this.ProbeLibPaths(identity);
var matchingAssembly = this.LoadAssembly(matchingIdentity);
if (matchingAssembly == null || matchingAssembly == Dummy.Assembly)
{
TraceLoadError("Failed to find or load matching assembly '{0}'.", identity.Name.Value);
continue;
}
if (warnOnVersionMismatch && !identity.Version.Equals(matchingAssembly.Version))
{
Trace.TraceWarning("Found '{0}' with version '{1}' instead of '{2}'.",
identity.Name.Value, matchingAssembly.Version, identity.Version);
}
string idPKT = identity.GetPublicKeyToken();
string matchingPKT = matchingAssembly.GetPublicKeyToken();
if (!idPKT.Equals(matchingPKT))
{
Trace.TraceWarning("Found '{0}' with PublicKeyToken '{1}' instead of '{2}'.",
identity.Name.Value, matchingPKT, idPKT);
}
matchingAssemblies.Add(matchingAssembly);
}
return matchingAssemblies;
}
public IEnumerable<IAssembly> LoadAssemblies(IEnumerable<AssemblyIdentity> identities, bool warnOnVersionMismatch, string coreAssemblySimpleName)
{
// Re-arrange the list of identities so that the coreIdentity is the first one in the list.
if (!string.IsNullOrEmpty(coreAssemblySimpleName))
{
var coreIdentity = identities.FirstOrDefault(ai => StringComparer.OrdinalIgnoreCase.Equals(ai.Name.Value, coreAssemblySimpleName));
if (coreIdentity == null)
{
throw new InvalidOperationException(String.Format("Could not find core assembly '{0}' in the list of identities.", coreAssemblySimpleName));
}
identities = Enumerable.Concat(new List<AssemblyIdentity>() { coreIdentity }, identities.Where(ai => ai != coreIdentity));
}
return LoadAssemblies(identities, warnOnVersionMismatch);
}
public static IEnumerable<string> GetFilePaths(IEnumerable<string> paths, SearchOption searchOption)
{
if (searchOption == SearchOption.TopDirectoryOnly)
return GetFilePaths(paths);
// expand the path into a list of paths that contains all the subdirectories
Stack<string> unexpandedPaths = new Stack<string>(paths);
HashSet<string> allPaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var path in paths)
{
allPaths.Add(path);
// if the path did not point to a directory, continue
if (!Directory.Exists(path))
continue;
foreach (var dir in Directory.EnumerateDirectories(path, "*.*", SearchOption.AllDirectories))
{
allPaths.Add(dir);
}
}
// make sure we remove any duplicated folders (ie. if the user specified both a root folder and a leaf one)
return GetFilePaths(allPaths);
}
public static IEnumerable<string> GetFilePaths(IEnumerable<string> paths)
{
return GetFilePaths(paths, (resolvedPath) => { });
}
private IEnumerable<string> GetFilePathsAndAddResolvedDirectoriesToLibPaths(IEnumerable<string> paths)
{
return GetFilePaths(paths, (resolvedPath) => this.LibPaths.Add(resolvedPath));
}
private static IEnumerable<string> GetFilePaths(IEnumerable<string> paths, Action<string> perResolvedPathAction, bool recursive = false)
{
foreach (var path in paths)
{
if (path == null)
continue;
string resolvedPath = Environment.ExpandEnvironmentVariables(path);
if (Directory.Exists(resolvedPath))
{
perResolvedPathAction(resolvedPath);
for (int extIndex = 0; extIndex < s_probingExtensions.Length; extIndex++)
{
var searchPattern = "*" + s_probingExtensions[extIndex];
foreach (var file in Directory.EnumerateFiles(resolvedPath, searchPattern))
{
yield return file;
}
}
if (recursive)
{
//recursively do the same for sub-folders
foreach (var file in GetFilePaths(Directory.EnumerateDirectories(resolvedPath), perResolvedPathAction, recursive))
{
yield return file;
}
}
}
else if (Path.GetFileName(resolvedPath).Contains('*'))
{
IEnumerable<string> files;
// Cannot yield a value in the body of a try-catch with catch clause.
try
{
files = Directory.EnumerateFiles(Path.GetDirectoryName(resolvedPath), Path.GetFileName(resolvedPath));
}
catch (ArgumentException)
{
files = new[] { resolvedPath };
}
foreach (var file in files)
yield return file;
}
else
{
yield return resolvedPath;
}
}
}
#endregion
private sealed class StreamDocument : IBinaryDocument
{
private readonly string _location;
private readonly IName _name;
private readonly Stream _stream;
public StreamDocument(string location, IName name, Stream stream)
{
_stream = stream;
_location = location;
_name = name;
}
public string Location
{
get { return _location; }
}
public IName Name
{
get { return _name; }
}
public Stream Stream
{
get { return _stream; }
}
public uint Length
{
get { return (uint)_stream.Length; }
}
}
}
public class UnresolvedReference<TReferrer, TUnresolved> : EventArgs
{
public UnresolvedReference(TReferrer referrer, TUnresolved unresolvedReference)
{
this.Referrer = referrer;
this.Unresolved = unresolvedReference;
}
public TReferrer Referrer { get; private set; }
public TUnresolved Unresolved { get; private set; }
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Linq;
using Xunit;
namespace System.Collections.Immutable.Tests
{
public class ImmutableSortedSetTest : ImmutableSetTest
{
private enum Operation
{
Add,
Union,
Remove,
Except,
Last,
}
protected override bool IncludesGetHashCodeDerivative
{
get { return false; }
}
[Fact]
public void RandomOperationsTest()
{
int operationCount = this.RandomOperationsCount;
var expected = new SortedSet<int>();
var actual = ImmutableSortedSet<int>.Empty;
int seed = (int)DateTime.Now.Ticks;
Debug.WriteLine("Using random seed {0}", seed);
var random = new Random(seed);
for (int iOp = 0; iOp < operationCount; iOp++)
{
switch ((Operation)random.Next((int)Operation.Last))
{
case Operation.Add:
int value = random.Next();
Debug.WriteLine("Adding \"{0}\" to the set.", value);
expected.Add(value);
actual = actual.Add(value);
break;
case Operation.Union:
int inputLength = random.Next(100);
int[] values = Enumerable.Range(0, inputLength).Select(i => random.Next()).ToArray();
Debug.WriteLine("Adding {0} elements to the set.", inputLength);
expected.UnionWith(values);
actual = actual.Union(values);
break;
case Operation.Remove:
if (expected.Count > 0)
{
int position = random.Next(expected.Count);
int element = expected.Skip(position).First();
Debug.WriteLine("Removing element \"{0}\" from the set.", element);
Assert.True(expected.Remove(element));
actual = actual.Remove(element);
}
break;
case Operation.Except:
var elements = expected.Where(el => random.Next(2) == 0).ToArray();
Debug.WriteLine("Removing {0} elements from the set.", elements.Length);
expected.ExceptWith(elements);
actual = actual.Except(elements);
break;
}
Assert.Equal<int>(expected.ToList(), actual.ToList());
}
}
[Fact]
[ActiveIssue(780)]
public void EmptyTest()
{
this.EmptyTestHelper(Empty<int>(), 5, null);
this.EmptyTestHelper(Empty<string>().ToImmutableSortedSet(StringComparer.OrdinalIgnoreCase), "a", StringComparer.OrdinalIgnoreCase);
}
[Fact]
public void CustomSort()
{
this.CustomSortTestHelper(
ImmutableSortedSet<string>.Empty.WithComparer(StringComparer.Ordinal),
true,
new[] { "apple", "APPLE" },
new[] { "APPLE", "apple" });
this.CustomSortTestHelper(
ImmutableSortedSet<string>.Empty.WithComparer(StringComparer.OrdinalIgnoreCase),
true,
new[] { "apple", "APPLE" },
new[] { "apple" });
}
[Fact]
public void ChangeSortComparer()
{
var ordinalSet = ImmutableSortedSet<string>.Empty
.WithComparer(StringComparer.Ordinal)
.Add("apple")
.Add("APPLE");
Assert.Equal(2, ordinalSet.Count); // claimed count
Assert.False(ordinalSet.Contains("aPpLe"));
var ignoreCaseSet = ordinalSet.WithComparer(StringComparer.OrdinalIgnoreCase);
Assert.Equal(1, ignoreCaseSet.Count);
Assert.True(ignoreCaseSet.Contains("aPpLe"));
}
[Fact]
public void ToUnorderedTest()
{
var result = ImmutableSortedSet<int>.Empty.Add(3).ToImmutableHashSet();
Assert.True(result.Contains(3));
}
[Fact]
public void ToImmutableSortedSetFromArrayTest()
{
var set = new[] { 1, 2, 2 }.ToImmutableSortedSet();
Assert.Same(Comparer<int>.Default, set.KeyComparer);
Assert.Equal(2, set.Count);
}
[Theory]
[InlineData(new int[] { }, new int[] { })]
[InlineData(new int[] { 1 }, new int[] { 1 })]
[InlineData(new int[] { 1, 1 }, new int[] { 1 })]
[InlineData(new int[] { 1, 1, 1 }, new int[] { 1 })]
[InlineData(new int[] { 1, 2, 3 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 3, 2, 1 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 1, 1, 3 }, new int[] { 1, 3 })]
[InlineData(new int[] { 1, 2, 2 }, new int[] { 1, 2 })]
[InlineData(new int[] { 1, 2, 2, 3, 3, 3 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 1, 2, 3, 1, 2, 3 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 1, 1, 2, 2, 2, 3, 3, 3, 3 }, new int[] { 1, 2, 3 })]
public void ToImmutableSortedSetFromEnumerableTest(int[] input, int[] expectedOutput)
{
IEnumerable<int> enumerableInput = input.Select(i => i); // prevent querying for indexable interfaces
var set = enumerableInput.ToImmutableSortedSet();
Assert.Equal((IEnumerable<int>)expectedOutput, set.ToArray());
}
[Theory]
[InlineData(new int[] { }, new int[] { 1 })]
[InlineData(new int[] { 1 }, new int[] { 1 })]
[InlineData(new int[] { 1, 1 }, new int[] { 1 })]
[InlineData(new int[] { 1, 1, 1 }, new int[] { 1 })]
[InlineData(new int[] { 1, 2, 3 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 3, 2, 1 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 1, 1, 3 }, new int[] { 1, 3 })]
[InlineData(new int[] { 1, 2, 2 }, new int[] { 1, 2 })]
[InlineData(new int[] { 1, 2, 2, 3, 3, 3 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 1, 2, 3, 1, 2, 3 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 1, 1, 2, 2, 2, 3, 3, 3, 3 }, new int[] { 1, 2, 3 })]
public void UnionWithEnumerableTest(int[] input, int[] expectedOutput)
{
IEnumerable<int> enumerableInput = input.Select(i => i); // prevent querying for indexable interfaces
var set = ImmutableSortedSet.Create(1).Union(enumerableInput);
Assert.Equal((IEnumerable<int>)expectedOutput, set.ToArray());
}
[Fact]
public void IndexOfTest()
{
var set = ImmutableSortedSet<int>.Empty;
Assert.Equal(~0, set.IndexOf(5));
set = ImmutableSortedSet<int>.Empty.Union(Enumerable.Range(1, 10).Select(n => n * 10)); // 10, 20, 30, ... 100
Assert.Equal(0, set.IndexOf(10));
Assert.Equal(1, set.IndexOf(20));
Assert.Equal(4, set.IndexOf(50));
Assert.Equal(8, set.IndexOf(90));
Assert.Equal(9, set.IndexOf(100));
Assert.Equal(~0, set.IndexOf(5));
Assert.Equal(~1, set.IndexOf(15));
Assert.Equal(~2, set.IndexOf(25));
Assert.Equal(~5, set.IndexOf(55));
Assert.Equal(~9, set.IndexOf(95));
Assert.Equal(~10, set.IndexOf(105));
}
[Fact]
public void IndexGetTest()
{
var set = ImmutableSortedSet<int>.Empty
.Union(Enumerable.Range(1, 10).Select(n => n * 10)); // 10, 20, 30, ... 100
int i = 0;
foreach (var item in set)
{
AssertAreSame(item, set[i++]);
}
Assert.Throws<ArgumentOutOfRangeException>(() => set[-1]);
Assert.Throws<ArgumentOutOfRangeException>(() => set[set.Count]);
}
[Fact]
public void ReverseTest()
{
var range = Enumerable.Range(1, 10);
var set = ImmutableSortedSet<int>.Empty.Union(range);
var expected = range.Reverse().ToList();
var actual = set.Reverse().ToList();
Assert.Equal<int>(expected, actual);
}
[Fact]
public void MaxTest()
{
Assert.Equal(5, ImmutableSortedSet<int>.Empty.Union(Enumerable.Range(1, 5)).Max);
Assert.Equal(0, ImmutableSortedSet<int>.Empty.Max);
}
[Fact]
public void MinTest()
{
Assert.Equal(1, ImmutableSortedSet<int>.Empty.Union(Enumerable.Range(1, 5)).Min);
Assert.Equal(0, ImmutableSortedSet<int>.Empty.Min);
}
[Fact]
public void InitialBulkAdd()
{
Assert.Equal(1, Empty<int>().Union(new[] { 1, 1 }).Count);
Assert.Equal(2, Empty<int>().Union(new[] { 1, 2 }).Count);
}
[Fact]
public void ICollectionOfTMethods()
{
ICollection<string> set = ImmutableSortedSet.Create<string>();
Assert.Throws<NotSupportedException>(() => set.Add("a"));
Assert.Throws<NotSupportedException>(() => set.Clear());
Assert.Throws<NotSupportedException>(() => set.Remove("a"));
Assert.True(set.IsReadOnly);
}
[Fact]
public void IListOfTMethods()
{
IList<string> set = ImmutableSortedSet.Create<string>("b");
Assert.Throws<NotSupportedException>(() => set.Insert(0, "a"));
Assert.Throws<NotSupportedException>(() => set.RemoveAt(0));
Assert.Throws<NotSupportedException>(() => set[0] = "a");
Assert.Equal("b", set[0]);
Assert.True(set.IsReadOnly);
}
[Fact]
public void UnionOptimizationsTest()
{
var set = ImmutableSortedSet.Create(1, 2, 3);
var builder = set.ToBuilder();
Assert.Same(set, ImmutableSortedSet.Create<int>().Union(builder));
Assert.Same(set, set.Union(ImmutableSortedSet.Create<int>()));
var smallSet = ImmutableSortedSet.Create(1);
var unionSet = smallSet.Union(set);
Assert.Same(set, unionSet); // adding a larger set to a smaller set is reversed, and then the smaller in this case has nothing unique
}
[Fact]
public void Create()
{
var comparer = StringComparer.OrdinalIgnoreCase;
var set = ImmutableSortedSet.Create<string>();
Assert.Equal(0, set.Count);
Assert.Same(Comparer<string>.Default, set.KeyComparer);
set = ImmutableSortedSet.Create<string>(comparer);
Assert.Equal(0, set.Count);
Assert.Same(comparer, set.KeyComparer);
set = ImmutableSortedSet.Create("a");
Assert.Equal(1, set.Count);
Assert.Same(Comparer<string>.Default, set.KeyComparer);
set = ImmutableSortedSet.Create(comparer, "a");
Assert.Equal(1, set.Count);
Assert.Same(comparer, set.KeyComparer);
set = ImmutableSortedSet.Create("a", "b");
Assert.Equal(2, set.Count);
Assert.Same(Comparer<string>.Default, set.KeyComparer);
set = ImmutableSortedSet.Create(comparer, "a", "b");
Assert.Equal(2, set.Count);
Assert.Same(comparer, set.KeyComparer);
set = ImmutableSortedSet.CreateRange((IEnumerable<string>)new[] { "a", "b" });
Assert.Equal(2, set.Count);
Assert.Same(Comparer<string>.Default, set.KeyComparer);
set = ImmutableSortedSet.CreateRange(comparer, (IEnumerable<string>)new[] { "a", "b" });
Assert.Equal(2, set.Count);
Assert.Same(comparer, set.KeyComparer);
}
[Fact]
public void IListMethods()
{
IList list = ImmutableSortedSet.Create("a", "b");
Assert.True(list.Contains("a"));
Assert.Equal("a", list[0]);
Assert.Equal("b", list[1]);
Assert.Equal(0, list.IndexOf("a"));
Assert.Equal(1, list.IndexOf("b"));
Assert.Throws<NotSupportedException>(() => list.Add("b"));
Assert.Throws<NotSupportedException>(() => list[3] = "c");
Assert.Throws<NotSupportedException>(() => list.Clear());
Assert.Throws<NotSupportedException>(() => list.Insert(0, "b"));
Assert.Throws<NotSupportedException>(() => list.Remove("a"));
Assert.Throws<NotSupportedException>(() => list.RemoveAt(0));
Assert.True(list.IsFixedSize);
Assert.True(list.IsReadOnly);
}
[Fact]
public void TryGetValueTest()
{
this.TryGetValueTestHelper(ImmutableSortedSet<string>.Empty.WithComparer(StringComparer.OrdinalIgnoreCase));
}
[Fact]
public void EnumeratorRecyclingMisuse()
{
var collection = ImmutableSortedSet.Create<int>();
var enumerator = collection.GetEnumerator();
var enumeratorCopy = enumerator;
Assert.False(enumerator.MoveNext());
enumerator.Dispose();
Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumerator.Reset());
Assert.Throws<ObjectDisposedException>(() => enumerator.Current);
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Reset());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Current);
enumerator.Dispose(); // double-disposal should not throw
enumeratorCopy.Dispose();
// We expect that acquiring a new enumerator will use the same underlying Stack<T> object,
// but that it will not throw exceptions for the new enumerator.
enumerator = collection.GetEnumerator();
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
enumerator.Dispose();
}
[Fact]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableSortedSet.Create<int>());
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(ImmutableSortedSet.Create<string>("1", "2", "3"));
object rootNode = DebuggerAttributes.GetFieldValue(ImmutableSortedSet.Create<object>(), "_root");
DebuggerAttributes.ValidateDebuggerDisplayReferences(rootNode);
}
[Fact]
public void SymmetricExceptWithComparerTests()
{
var set = ImmutableSortedSet.Create<string>("a").WithComparer(StringComparer.OrdinalIgnoreCase);
var otherCollection = new[] {"A"};
var expectedSet = new SortedSet<string>(set, set.KeyComparer);
expectedSet.SymmetricExceptWith(otherCollection);
var actualSet = set.SymmetricExcept(otherCollection);
CollectionAssertAreEquivalent(expectedSet.ToList(), actualSet.ToList());
}
protected override IImmutableSet<T> Empty<T>()
{
return ImmutableSortedSet<T>.Empty;
}
protected ImmutableSortedSet<T> EmptyTyped<T>()
{
return ImmutableSortedSet<T>.Empty;
}
protected override ISet<T> EmptyMutable<T>()
{
return new SortedSet<T>();
}
internal override IBinaryTree GetRootNode<T>(IImmutableSet<T> set)
{
return ((ImmutableSortedSet<T>)set).Root;
}
/// <summary>
/// Tests various aspects of a sorted set.
/// </summary>
/// <typeparam name="T">The type of element stored in the set.</typeparam>
/// <param name="emptySet">The empty set.</param>
/// <param name="value">A value that could be placed in the set.</param>
/// <param name="comparer">The comparer used to obtain the empty set, if any.</param>
private void EmptyTestHelper<T>(IImmutableSet<T> emptySet, T value, IComparer<T> comparer)
{
Contract.Requires(emptySet != null);
this.EmptyTestHelper(emptySet);
Assert.Same(emptySet, emptySet.ToImmutableSortedSet(comparer));
Assert.Same(comparer ?? Comparer<T>.Default, ((ISortKeyCollection<T>)emptySet).KeyComparer);
var reemptied = emptySet.Add(value).Clear();
Assert.Same(reemptied, reemptied.ToImmutableSortedSet(comparer)); //, "Getting the empty set from a non-empty instance did not preserve the comparer.");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
namespace System.Buffers.Text
{
public static partial class Utf8Parser
{
private enum ComponentParseResult : byte
{
// Do not change or add values in this enum unless you review every use of the TimeSpanSplitter.Separators field. That field is an "array of four
// ComponentParseResults" encoded as a 32-bit integer with each of its four bytes containing one of 0 (NoMoreData), 1 (Colon) or 2 (Period).
// (So a value of 0x01010200 means the string parsed as "nn:nn:nn.nnnnnnn")
NoMoreData = 0,
Colon = 1,
Period = 2,
ParseFailure = 3,
}
private struct TimeSpanSplitter
{
public uint V1;
public uint V2;
public uint V3;
public uint V4;
public uint V5;
public bool IsNegative;
// Encodes an "array of four ComponentParseResults" as a 32-bit integer with each of its four bytes containing one of 0 (NoMoreData), 1 (Colon) or 2 (Period).
// (So a value of 0x01010200 means the string parsed as "nn:nn:nn.nnnnnnn")
public uint Separators;
public bool TrySplitTimeSpan(ReadOnlySpan<byte> source, bool periodUsedToSeparateDay, out int bytesConsumed)
{
int srcIndex = 0;
byte c = default;
// Unlike many other data types, TimeSpan allow leading whitespace.
while (srcIndex != source.Length)
{
c = source[srcIndex];
if (!(c == ' ' || c == '\t'))
break;
srcIndex++;
}
if (srcIndex == source.Length)
{
bytesConsumed = 0;
return false;
}
// Check for an option negative sign. ('+' is not allowed.)
if (c == Utf8Constants.Minus)
{
IsNegative = true;
srcIndex++;
if (srcIndex == source.Length)
{
bytesConsumed = 0;
return false;
}
}
// From here, we terminate on anything that's not a digit, ':' or '.' The '.' is only allowed after at least three components have
// been specified. If we see it earlier, we'll assume that's an error and fail out rather than treating it as the end of data.
//
// Timespan has to start with a number - parse the first one.
//
if (!TryParseUInt32D(source.Slice(srcIndex), out V1, out int justConsumed))
{
bytesConsumed = 0;
return false;
}
srcIndex += justConsumed;
ComponentParseResult result;
//
// Split out the second number (if any) For the 'c' format, a period might validly appear here as it;s used both to separate the day and the fraction - however,
// the fraction is always the fourth component at earliest, so if we do see a period at this stage, always parse the integer as a regular integer, not as
// a fraction.
//
result = ParseComponent(source, neverParseAsFraction: periodUsedToSeparateDay, ref srcIndex, out V2);
if (result == ComponentParseResult.ParseFailure)
{
bytesConsumed = 0;
return false;
}
else if (result == ComponentParseResult.NoMoreData)
{
bytesConsumed = srcIndex;
return true;
}
else
{
Debug.Assert(result == ComponentParseResult.Colon || result == ComponentParseResult.Period);
Separators |= ((uint)result) << 24;
}
//
// Split out the third number (if any)
//
result = ParseComponent(source, false, ref srcIndex, out V3);
if (result == ComponentParseResult.ParseFailure)
{
bytesConsumed = 0;
return false;
}
else if (result == ComponentParseResult.NoMoreData)
{
bytesConsumed = srcIndex;
return true;
}
else
{
Debug.Assert(result == ComponentParseResult.Colon || result == ComponentParseResult.Period);
Separators |= ((uint)result) << 16;
}
//
// Split out the fourth number (if any)
//
result = ParseComponent(source, false, ref srcIndex, out V4);
if (result == ComponentParseResult.ParseFailure)
{
bytesConsumed = 0;
return false;
}
else if (result == ComponentParseResult.NoMoreData)
{
bytesConsumed = srcIndex;
return true;
}
else
{
Debug.Assert(result == ComponentParseResult.Colon || result == ComponentParseResult.Period);
Separators |= ((uint)result) << 8;
}
//
// Split out the fifth number (if any)
//
result = ParseComponent(source, false, ref srcIndex, out V5);
if (result == ComponentParseResult.ParseFailure)
{
bytesConsumed = 0;
return false;
}
else if (result == ComponentParseResult.NoMoreData)
{
bytesConsumed = srcIndex;
return true;
}
else
{
Debug.Assert(result == ComponentParseResult.Colon || result == ComponentParseResult.Period);
Separators |= (uint)result;
}
//
// There cannot legally be a sixth number. If the next character is a period or colon, treat this as a error as it's likely
// to indicate the start of a sixth number. Otherwise, treat as end of parse with data left over.
//
if (srcIndex != source.Length && (source[srcIndex] == Utf8Constants.Period || source[srcIndex] == Utf8Constants.Colon))
{
bytesConsumed = 0;
return false;
}
bytesConsumed = srcIndex;
return true;
}
//
// Look for a separator followed by an unsigned integer.
//
private static ComponentParseResult ParseComponent(ReadOnlySpan<byte> source, bool neverParseAsFraction, ref int srcIndex, out uint value)
{
if (srcIndex == source.Length)
{
value = default;
return ComponentParseResult.NoMoreData;
}
byte c = source[srcIndex];
if (c == Utf8Constants.Colon || (c == Utf8Constants.Period && neverParseAsFraction))
{
srcIndex++;
if (!TryParseUInt32D(source.Slice(srcIndex), out value, out int bytesConsumed))
{
value = default;
return ComponentParseResult.ParseFailure;
}
srcIndex += bytesConsumed;
return c == Utf8Constants.Colon ? ComponentParseResult.Colon : ComponentParseResult.Period;
}
else if (c == Utf8Constants.Period)
{
srcIndex++;
if (!TryParseTimeSpanFraction(source.Slice(srcIndex), out value, out int bytesConsumed))
{
value = default;
return ComponentParseResult.ParseFailure;
}
srcIndex += bytesConsumed;
return ComponentParseResult.Period;
}
else
{
value = default;
return ComponentParseResult.NoMoreData;
}
}
}
}
}
| |
// 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 MaxDouble()
{
var test = new SimpleBinaryOpTest__MaxDouble();
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__MaxDouble
{
private const int VectorSize = 16;
private const int ElementCount = VectorSize / sizeof(Double);
private static Double[] _data1 = new Double[ElementCount];
private static Double[] _data2 = new Double[ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private SimpleBinaryOpTest__DataTable<Double> _dataTable;
static SimpleBinaryOpTest__MaxDouble()
{
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<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__MaxDouble()
{
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<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<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 => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.Max(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.Max(
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.Max(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Max), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Max), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Max), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.Max(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var result = Sse2.Max(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.Max(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.Max(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__MaxDouble();
var result = Sse2.Max(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.Max(_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(Vector128<Double> left, Vector128<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(Math.Max(left[0], right[0])) != BitConverter.DoubleToInt64Bits(result[0]))
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if (BitConverter.DoubleToInt64Bits(Math.Max(left[i], right[i])) != BitConverter.DoubleToInt64Bits(result[i]))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Max)}<Double>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
namespace Humidifier.EC2
{
using System.Collections.Generic;
using EC2FleetTypes;
public class EC2Fleet : Humidifier.Resource
{
public override string AWSTypeName
{
get
{
return @"AWS::EC2::EC2Fleet";
}
}
/// <summary>
/// TargetCapacitySpecification
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html#cfn-ec2-ec2fleet-targetcapacityspecification
/// Required: True
/// UpdateType: Mutable
/// Type: TargetCapacitySpecificationRequest
/// </summary>
public TargetCapacitySpecificationRequest TargetCapacitySpecification
{
get;
set;
}
/// <summary>
/// OnDemandOptions
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html#cfn-ec2-ec2fleet-ondemandoptions
/// Required: False
/// UpdateType: Immutable
/// Type: OnDemandOptionsRequest
/// </summary>
public OnDemandOptionsRequest OnDemandOptions
{
get;
set;
}
/// <summary>
/// Type
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html#cfn-ec2-ec2fleet-type
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic Type
{
get;
set;
}
/// <summary>
/// ExcessCapacityTerminationPolicy
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html#cfn-ec2-ec2fleet-excesscapacityterminationpolicy
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic ExcessCapacityTerminationPolicy
{
get;
set;
}
/// <summary>
/// TagSpecifications
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html#cfn-ec2-ec2fleet-tagspecifications
/// Required: False
/// UpdateType: Immutable
/// Type: List
/// ItemType: TagSpecification
/// </summary>
public List<TagSpecification> TagSpecifications
{
get;
set;
}
/// <summary>
/// SpotOptions
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html#cfn-ec2-ec2fleet-spotoptions
/// Required: False
/// UpdateType: Immutable
/// Type: SpotOptionsRequest
/// </summary>
public SpotOptionsRequest SpotOptions
{
get;
set;
}
/// <summary>
/// ValidFrom
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html#cfn-ec2-ec2fleet-validfrom
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic ValidFrom
{
get;
set;
}
/// <summary>
/// ReplaceUnhealthyInstances
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html#cfn-ec2-ec2fleet-replaceunhealthyinstances
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic ReplaceUnhealthyInstances
{
get;
set;
}
/// <summary>
/// LaunchTemplateConfigs
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html#cfn-ec2-ec2fleet-launchtemplateconfigs
/// Required: True
/// UpdateType: Immutable
/// Type: List
/// ItemType: FleetLaunchTemplateConfigRequest
/// </summary>
public List<FleetLaunchTemplateConfigRequest> LaunchTemplateConfigs
{
get;
set;
}
/// <summary>
/// TerminateInstancesWithExpiration
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html#cfn-ec2-ec2fleet-terminateinstanceswithexpiration
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic TerminateInstancesWithExpiration
{
get;
set;
}
/// <summary>
/// ValidUntil
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-ec2fleet.html#cfn-ec2-ec2fleet-validuntil
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic ValidUntil
{
get;
set;
}
}
namespace EC2FleetTypes
{
public class FleetLaunchTemplateSpecificationRequest
{
/// <summary>
/// LaunchTemplateName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-fleetlaunchtemplatespecificationrequest.html#cfn-ec2-ec2fleet-fleetlaunchtemplatespecificationrequest-launchtemplatename
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic LaunchTemplateName
{
get;
set;
}
/// <summary>
/// Version
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-fleetlaunchtemplatespecificationrequest.html#cfn-ec2-ec2fleet-fleetlaunchtemplatespecificationrequest-version
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Version
{
get;
set;
}
/// <summary>
/// LaunchTemplateId
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-fleetlaunchtemplatespecificationrequest.html#cfn-ec2-ec2fleet-fleetlaunchtemplatespecificationrequest-launchtemplateid
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic LaunchTemplateId
{
get;
set;
}
}
public class OnDemandOptionsRequest
{
/// <summary>
/// AllocationStrategy
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-ondemandoptionsrequest.html#cfn-ec2-ec2fleet-ondemandoptionsrequest-allocationstrategy
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic AllocationStrategy
{
get;
set;
}
}
public class TagRequest
{
/// <summary>
/// Value
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-tagrequest.html#cfn-ec2-ec2fleet-tagrequest-value
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Value
{
get;
set;
}
/// <summary>
/// Key
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-tagrequest.html#cfn-ec2-ec2fleet-tagrequest-key
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Key
{
get;
set;
}
}
public class TargetCapacitySpecificationRequest
{
/// <summary>
/// DefaultTargetCapacityType
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-targetcapacityspecificationrequest.html#cfn-ec2-ec2fleet-targetcapacityspecificationrequest-defaulttargetcapacitytype
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic DefaultTargetCapacityType
{
get;
set;
}
/// <summary>
/// TotalTargetCapacity
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-targetcapacityspecificationrequest.html#cfn-ec2-ec2fleet-targetcapacityspecificationrequest-totaltargetcapacity
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic TotalTargetCapacity
{
get;
set;
}
/// <summary>
/// OnDemandTargetCapacity
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-targetcapacityspecificationrequest.html#cfn-ec2-ec2fleet-targetcapacityspecificationrequest-ondemandtargetcapacity
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic OnDemandTargetCapacity
{
get;
set;
}
/// <summary>
/// SpotTargetCapacity
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-targetcapacityspecificationrequest.html#cfn-ec2-ec2fleet-targetcapacityspecificationrequest-spottargetcapacity
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic SpotTargetCapacity
{
get;
set;
}
}
public class FleetLaunchTemplateOverridesRequest
{
/// <summary>
/// WeightedCapacity
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-fleetlaunchtemplateoverridesrequest.html#cfn-ec2-ec2fleet-fleetlaunchtemplateoverridesrequest-weightedcapacity
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Double
/// </summary>
public dynamic WeightedCapacity
{
get;
set;
}
/// <summary>
/// Priority
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-fleetlaunchtemplateoverridesrequest.html#cfn-ec2-ec2fleet-fleetlaunchtemplateoverridesrequest-priority
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Double
/// </summary>
public dynamic Priority
{
get;
set;
}
/// <summary>
/// AvailabilityZone
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-fleetlaunchtemplateoverridesrequest.html#cfn-ec2-ec2fleet-fleetlaunchtemplateoverridesrequest-availabilityzone
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic AvailabilityZone
{
get;
set;
}
/// <summary>
/// SubnetId
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-fleetlaunchtemplateoverridesrequest.html#cfn-ec2-ec2fleet-fleetlaunchtemplateoverridesrequest-subnetid
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic SubnetId
{
get;
set;
}
/// <summary>
/// InstanceType
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-fleetlaunchtemplateoverridesrequest.html#cfn-ec2-ec2fleet-fleetlaunchtemplateoverridesrequest-instancetype
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic InstanceType
{
get;
set;
}
/// <summary>
/// MaxPrice
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-fleetlaunchtemplateoverridesrequest.html#cfn-ec2-ec2fleet-fleetlaunchtemplateoverridesrequest-maxprice
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic MaxPrice
{
get;
set;
}
}
public class FleetLaunchTemplateConfigRequest
{
/// <summary>
/// LaunchTemplateSpecification
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-fleetlaunchtemplateconfigrequest.html#cfn-ec2-ec2fleet-fleetlaunchtemplateconfigrequest-launchtemplatespecification
/// Required: False
/// UpdateType: Mutable
/// Type: FleetLaunchTemplateSpecificationRequest
/// </summary>
public FleetLaunchTemplateSpecificationRequest LaunchTemplateSpecification
{
get;
set;
}
/// <summary>
/// Overrides
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-fleetlaunchtemplateconfigrequest.html#cfn-ec2-ec2fleet-fleetlaunchtemplateconfigrequest-overrides
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// ItemType: FleetLaunchTemplateOverridesRequest
/// </summary>
public List<FleetLaunchTemplateOverridesRequest> Overrides
{
get;
set;
}
}
public class TagSpecification
{
/// <summary>
/// ResourceType
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-tagspecification.html#cfn-ec2-ec2fleet-tagspecification-resourcetype
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic ResourceType
{
get;
set;
}
/// <summary>
/// Tags
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-tagspecification.html#cfn-ec2-ec2fleet-tagspecification-tags
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// ItemType: TagRequest
/// </summary>
public List<TagRequest> Tags
{
get;
set;
}
}
public class SpotOptionsRequest
{
/// <summary>
/// AllocationStrategy
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-spotoptionsrequest.html#cfn-ec2-ec2fleet-spotoptionsrequest-allocationstrategy
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic AllocationStrategy
{
get;
set;
}
/// <summary>
/// InstanceInterruptionBehavior
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-spotoptionsrequest.html#cfn-ec2-ec2fleet-spotoptionsrequest-instanceinterruptionbehavior
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic InstanceInterruptionBehavior
{
get;
set;
}
/// <summary>
/// InstancePoolsToUseCount
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-spotoptionsrequest.html#cfn-ec2-ec2fleet-spotoptionsrequest-instancepoolstousecount
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic InstancePoolsToUseCount
{
get;
set;
}
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type WorkbookChartDataLabelsRequest.
/// </summary>
public partial class WorkbookChartDataLabelsRequest : BaseRequest, IWorkbookChartDataLabelsRequest
{
/// <summary>
/// Constructs a new WorkbookChartDataLabelsRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public WorkbookChartDataLabelsRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified WorkbookChartDataLabels using POST.
/// </summary>
/// <param name="workbookChartDataLabelsToCreate">The WorkbookChartDataLabels to create.</param>
/// <returns>The created WorkbookChartDataLabels.</returns>
public System.Threading.Tasks.Task<WorkbookChartDataLabels> CreateAsync(WorkbookChartDataLabels workbookChartDataLabelsToCreate)
{
return this.CreateAsync(workbookChartDataLabelsToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified WorkbookChartDataLabels using POST.
/// </summary>
/// <param name="workbookChartDataLabelsToCreate">The WorkbookChartDataLabels to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created WorkbookChartDataLabels.</returns>
public async System.Threading.Tasks.Task<WorkbookChartDataLabels> CreateAsync(WorkbookChartDataLabels workbookChartDataLabelsToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<WorkbookChartDataLabels>(workbookChartDataLabelsToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified WorkbookChartDataLabels.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified WorkbookChartDataLabels.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
{
this.Method = "DELETE";
await this.SendAsync<WorkbookChartDataLabels>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified WorkbookChartDataLabels.
/// </summary>
/// <returns>The WorkbookChartDataLabels.</returns>
public System.Threading.Tasks.Task<WorkbookChartDataLabels> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified WorkbookChartDataLabels.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The WorkbookChartDataLabels.</returns>
public async System.Threading.Tasks.Task<WorkbookChartDataLabels> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<WorkbookChartDataLabels>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified WorkbookChartDataLabels using PATCH.
/// </summary>
/// <param name="workbookChartDataLabelsToUpdate">The WorkbookChartDataLabels to update.</param>
/// <returns>The updated WorkbookChartDataLabels.</returns>
public System.Threading.Tasks.Task<WorkbookChartDataLabels> UpdateAsync(WorkbookChartDataLabels workbookChartDataLabelsToUpdate)
{
return this.UpdateAsync(workbookChartDataLabelsToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified WorkbookChartDataLabels using PATCH.
/// </summary>
/// <param name="workbookChartDataLabelsToUpdate">The WorkbookChartDataLabels to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated WorkbookChartDataLabels.</returns>
public async System.Threading.Tasks.Task<WorkbookChartDataLabels> UpdateAsync(WorkbookChartDataLabels workbookChartDataLabelsToUpdate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<WorkbookChartDataLabels>(workbookChartDataLabelsToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartDataLabelsRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartDataLabelsRequest Expand(Expression<Func<WorkbookChartDataLabels, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartDataLabelsRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartDataLabelsRequest Select(Expression<Func<WorkbookChartDataLabels, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="workbookChartDataLabelsToInitialize">The <see cref="WorkbookChartDataLabels"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(WorkbookChartDataLabels workbookChartDataLabelsToInitialize)
{
}
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Commons.Music.Midi;
using osu.Framework.Input.StateChanges;
using osu.Framework.Logging;
using osu.Framework.Platform;
using osu.Framework.Statistics;
using osu.Framework.Threading;
namespace osu.Framework.Input.Handlers.Midi
{
public class MidiInputHandler : InputHandler
{
public override bool IsActive => true;
public override int Priority => 0;
private ScheduledDelegate scheduledRefreshDevices;
private readonly Dictionary<string, IMidiInput> openedDevices = new Dictionary<string, IMidiInput>();
/// <summary>
/// The last event for each midi device. This is required for Running Status (repeat messages sent without
/// event type).
/// </summary>
private readonly Dictionary<string, byte> runningStatus = new Dictionary<string, byte>();
public override bool Initialize(GameHost host)
{
Enabled.BindValueChanged(e =>
{
if (e.NewValue)
{
host.InputThread.Scheduler.Add(scheduledRefreshDevices = new ScheduledDelegate(() => refreshDevices(), 0, 500));
}
else
{
scheduledRefreshDevices?.Cancel();
foreach (var value in openedDevices.Values)
{
value.MessageReceived -= onMidiMessageReceived;
}
openedDevices.Clear();
}
}, true);
return refreshDevices();
}
private bool refreshDevices()
{
try
{
var inputs = MidiAccessManager.Default.Inputs.ToList();
// check removed devices
foreach (string key in openedDevices.Keys.ToArray())
{
var value = openedDevices[key];
if (inputs.All(i => i.Id != key))
{
value.MessageReceived -= onMidiMessageReceived;
openedDevices.Remove(key);
Logger.Log($"Disconnected MIDI device: {value.Details.Name}");
}
}
// check added devices
foreach (IMidiPortDetails input in inputs)
{
if (openedDevices.All(x => x.Key != input.Id))
{
var newInput = MidiAccessManager.Default.OpenInputAsync(input.Id).Result;
newInput.MessageReceived += onMidiMessageReceived;
openedDevices[input.Id] = newInput;
Logger.Log($"Connected MIDI device: {newInput.Details.Name}");
}
}
return true;
}
catch (Exception e)
{
Logger.Error(e, RuntimeInfo.OS == RuntimeInfo.Platform.Linux
? "Couldn't list input devices. Is libasound2-dev installed?"
: "Couldn't list input devices. There may be another application already using MIDI.");
Enabled.Value = false;
return false;
}
}
private void onMidiMessageReceived(object sender, MidiReceivedEventArgs e)
{
Debug.Assert(sender is IMidiInput);
var senderId = ((IMidiInput)sender).Details.Id;
try
{
for (int i = e.Start; i < e.Length;)
{
readEvent(e.Data, senderId, ref i, out byte eventType, out byte key, out byte velocity);
dispatchEvent(eventType, key, velocity);
}
}
catch (Exception exception)
{
var dataString = string.Join("-", e.Data.Select(b => b.ToString("X2")));
Logger.Error(exception, $"An exception occurred while reading MIDI data from sender {senderId}: {dataString}");
}
}
/// <remarks>
/// This function is not intended to provide complete correctness of MIDI parsing.
/// For now the goal is to correctly parse "note start" and "note end" events and correctly delimit all events.
/// </remarks>
private void readEvent(byte[] data, string senderId, ref int i, out byte eventType, out byte key, out byte velocity)
{
byte statusType = data[i++];
// continuation messages:
// need running status to be interpreted correctly
if (statusType <= 0x7F)
{
if (!runningStatus.ContainsKey(senderId))
throw new InvalidDataException($"Received running status of sender {senderId}, but no event type was stored");
eventType = runningStatus[senderId];
key = statusType;
velocity = data[i++];
return;
}
// real-time messages:
// 0 additional data bytes always, do not reset running status
if (statusType >= 0xF8)
{
eventType = statusType;
key = velocity = 0;
return;
}
// system common messages:
// variable number of additional data bytes, reset running status
if (statusType >= 0xF0)
{
eventType = statusType;
// system exclusive message
// vendor-specific, terminated by 0xF7
// ignoring their whole contents for now since we can't do anything with them anyway
if (statusType == 0xF0)
{
while (data[i - 1] != 0xF7)
i++;
key = velocity = 0;
}
// other common system messages
// fixed size given by MidiEvent.FixedDataSize
else
{
key = MidiEvent.FixedDataSize(statusType) >= 1 ? data[i++] : (byte)0;
velocity = MidiEvent.FixedDataSize(statusType) == 2 ? data[i++] : (byte)0;
}
runningStatus.Remove(senderId);
return;
}
// channel messages
// fixed size (varying per event type), set running status
eventType = statusType;
key = MidiEvent.FixedDataSize(statusType) >= 1 ? data[i++] : (byte)0;
velocity = MidiEvent.FixedDataSize(statusType) == 2 ? data[i++] : (byte)0;
runningStatus[senderId] = eventType;
}
private void dispatchEvent(byte eventType, byte key, byte velocity)
{
Logger.Log($"Handling MIDI event {eventType:X2}:{key:X2}:{velocity:X2}");
switch (eventType)
{
case MidiEvent.NoteOn when velocity != 0:
Logger.Log($"NoteOn: {(MidiKey)key}/{velocity / 128f:P}");
PendingInputs.Enqueue(new MidiKeyInput((MidiKey)key, velocity, true));
FrameStatistics.Increment(StatisticsCounterType.MidiEvents);
break;
case MidiEvent.NoteOff:
case MidiEvent.NoteOn when velocity == 0:
Logger.Log($"NoteOff: {(MidiKey)key}/{velocity / 128f:P}");
PendingInputs.Enqueue(new MidiKeyInput((MidiKey)key, 0, false));
FrameStatistics.Increment(StatisticsCounterType.MidiEvents);
break;
}
}
}
}
| |
// 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.
//
// C# implementation of the proposed SHA-256 hash algorithm
//
namespace System.Security.Cryptography {
using System;
using System.Security;
using System.Diagnostics.Contracts;
[System.Runtime.InteropServices.ComVisible(true)]
public class SHA256Managed : SHA256
{
private byte[] _buffer;
private long _count; // Number of bytes in the hashed message
private UInt32[] _stateSHA256;
private UInt32[] _W;
//
// public constructors
//
public SHA256Managed()
{
#if FEATURE_CRYPTO
if (CryptoConfig.AllowOnlyFipsAlgorithms)
throw new InvalidOperationException(Environment.GetResourceString("Cryptography_NonCompliantFIPSAlgorithm"));
Contract.EndContractBlock();
#endif // FEATURE_CRYPTO
_stateSHA256 = new UInt32[8];
_buffer = new byte[64];
_W = new UInt32[64];
InitializeState();
}
//
// public methods
//
public override void Initialize() {
InitializeState();
// Zeroize potentially sensitive information.
Array.Clear(_buffer, 0, _buffer.Length);
Array.Clear(_W, 0, _W.Length);
}
protected override void HashCore(byte[] rgb, int ibStart, int cbSize) {
_HashData(rgb, ibStart, cbSize);
}
protected override byte[] HashFinal() {
return _EndHash();
}
//
// private methods
//
private void InitializeState() {
_count = 0;
_stateSHA256[0] = 0x6a09e667;
_stateSHA256[1] = 0xbb67ae85;
_stateSHA256[2] = 0x3c6ef372;
_stateSHA256[3] = 0xa54ff53a;
_stateSHA256[4] = 0x510e527f;
_stateSHA256[5] = 0x9b05688c;
_stateSHA256[6] = 0x1f83d9ab;
_stateSHA256[7] = 0x5be0cd19;
}
/* SHA256 block update operation. Continues an SHA message-digest
operation, processing another message block, and updating the
context.
*/
[System.Security.SecuritySafeCritical] // auto-generated
private unsafe void _HashData(byte[] partIn, int ibStart, int cbSize)
{
int bufferLen;
int partInLen = cbSize;
int partInBase = ibStart;
/* Compute length of buffer */
bufferLen = (int) (_count & 0x3f);
/* Update number of bytes */
_count += partInLen;
fixed (uint* stateSHA256 = _stateSHA256) {
fixed (byte* buffer = _buffer) {
fixed (uint* expandedBuffer = _W) {
if ((bufferLen > 0) && (bufferLen + partInLen >= 64)) {
Buffer.InternalBlockCopy(partIn, partInBase, _buffer, bufferLen, 64 - bufferLen);
partInBase += (64 - bufferLen);
partInLen -= (64 - bufferLen);
SHATransform(expandedBuffer, stateSHA256, buffer);
bufferLen = 0;
}
/* Copy input to temporary buffer and hash */
while (partInLen >= 64) {
Buffer.InternalBlockCopy(partIn, partInBase, _buffer, 0, 64);
partInBase += 64;
partInLen -= 64;
SHATransform(expandedBuffer, stateSHA256, buffer);
}
if (partInLen > 0) {
Buffer.InternalBlockCopy(partIn, partInBase, _buffer, bufferLen, partInLen);
}
}
}
}
}
/* SHA256 finalization. Ends an SHA256 message-digest operation, writing
the message digest.
*/
private byte[] _EndHash()
{
byte[] pad;
int padLen;
long bitCount;
byte[] hash = new byte[32]; // HashSizeValue = 256
/* Compute padding: 80 00 00 ... 00 00 <bit count>
*/
padLen = 64 - (int)(_count & 0x3f);
if (padLen <= 8)
padLen += 64;
pad = new byte[padLen];
pad[0] = 0x80;
// Convert count to bit count
bitCount = _count * 8;
pad[padLen-8] = (byte) ((bitCount >> 56) & 0xff);
pad[padLen-7] = (byte) ((bitCount >> 48) & 0xff);
pad[padLen-6] = (byte) ((bitCount >> 40) & 0xff);
pad[padLen-5] = (byte) ((bitCount >> 32) & 0xff);
pad[padLen-4] = (byte) ((bitCount >> 24) & 0xff);
pad[padLen-3] = (byte) ((bitCount >> 16) & 0xff);
pad[padLen-2] = (byte) ((bitCount >> 8) & 0xff);
pad[padLen-1] = (byte) ((bitCount >> 0) & 0xff);
/* Digest padding */
_HashData(pad, 0, pad.Length);
/* Store digest */
Utils.DWORDToBigEndian (hash, _stateSHA256, 8);
HashValue = hash;
return hash;
}
private readonly static UInt32[] _K = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
};
[System.Security.SecurityCritical] // auto-generated
private static unsafe void SHATransform (uint* expandedBuffer, uint* state, byte* block)
{
UInt32 a, b, c, d, e, f, h, g;
UInt32 aa, bb, cc, dd, ee, ff, hh, gg;
UInt32 T1;
a = state[0];
b = state[1];
c = state[2];
d = state[3];
e = state[4];
f = state[5];
g = state[6];
h = state[7];
// fill in the first 16 bytes of W.
Utils.DWORDFromBigEndian(expandedBuffer, 16, block);
SHA256Expand(expandedBuffer);
/* Apply the SHA256 compression function */
// We are trying to be smart here and avoid as many copies as we can
// The perf gain with this method over the straightforward modify and shift
// forward is >= 20%, so it's worth the pain
for (int j=0; j<64; ) {
T1 = h + Sigma_1(e) + Ch(e,f,g) + _K[j] + expandedBuffer[j];
ee = d + T1;
aa = T1 + Sigma_0(a) + Maj(a,b,c);
j++;
T1 = g + Sigma_1(ee) + Ch(ee,e,f) + _K[j] + expandedBuffer[j];
ff = c + T1;
bb = T1 + Sigma_0(aa) + Maj(aa,a,b);
j++;
T1 = f + Sigma_1(ff) + Ch(ff,ee,e) + _K[j] + expandedBuffer[j];
gg = b + T1;
cc = T1 + Sigma_0(bb) + Maj(bb,aa,a);
j++;
T1 = e + Sigma_1(gg) + Ch(gg,ff,ee) + _K[j] + expandedBuffer[j];
hh = a + T1;
dd = T1 + Sigma_0(cc) + Maj(cc,bb,aa);
j++;
T1 = ee + Sigma_1(hh) + Ch(hh,gg,ff) + _K[j] + expandedBuffer[j];
h = aa + T1;
d = T1 + Sigma_0(dd) + Maj(dd,cc,bb);
j++;
T1 = ff + Sigma_1(h) + Ch(h,hh,gg) + _K[j] + expandedBuffer[j];
g = bb + T1;
c = T1 + Sigma_0(d) + Maj(d,dd,cc);
j++;
T1 = gg + Sigma_1(g) + Ch(g,h,hh) + _K[j] + expandedBuffer[j];
f = cc + T1;
b = T1 + Sigma_0(c) + Maj(c,d,dd);
j++;
T1 = hh + Sigma_1(f) + Ch(f,g,h) + _K[j] + expandedBuffer[j];
e = dd + T1;
a = T1 + Sigma_0(b) + Maj(b,c,d);
j++;
}
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
state[4] += e;
state[5] += f;
state[6] += g;
state[7] += h;
}
private static UInt32 RotateRight(UInt32 x, int n) {
return (((x) >> (n)) | ((x) << (32-(n))));
}
private static UInt32 Ch(UInt32 x, UInt32 y, UInt32 z) {
return ((x & y) ^ ((x ^ 0xffffffff) & z));
}
private static UInt32 Maj(UInt32 x, UInt32 y, UInt32 z) {
return ((x & y) ^ (x & z) ^ (y & z));
}
private static UInt32 sigma_0(UInt32 x) {
return (RotateRight(x,7) ^ RotateRight(x,18) ^ (x >> 3));
}
private static UInt32 sigma_1(UInt32 x) {
return (RotateRight(x,17) ^ RotateRight(x,19) ^ (x >> 10));
}
private static UInt32 Sigma_0(UInt32 x) {
return (RotateRight(x,2) ^ RotateRight(x,13) ^ RotateRight(x,22));
}
private static UInt32 Sigma_1(UInt32 x) {
return (RotateRight(x,6) ^ RotateRight(x,11) ^ RotateRight(x,25));
}
/* This function creates W_16,...,W_63 according to the formula
W_j <- sigma_1(W_{j-2}) + W_{j-7} + sigma_0(W_{j-15}) + W_{j-16};
*/
[System.Security.SecurityCritical] // auto-generated
private static unsafe void SHA256Expand (uint* x)
{
for (int i = 16; i < 64; i++) {
x[i] = sigma_1(x[i-2]) + x[i-7] + sigma_0(x[i-15]) + x[i-16];
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using org.apache.zookeeper;
using org.apache.zookeeper.data;
using Orleans.Messaging;
using Orleans.Runtime.Configuration;
namespace Orleans.Runtime.Host
{
/// <summary>
/// A Membership Table implementation using Apache Zookeeper 3.4.6 https://zookeeper.apache.org/doc/r3.4.6/
/// </summary>
/// <remarks>
/// A brief overview of ZK features used: The data is represented by a tree of nodes (similar to a file system).
/// Every node is addressed by a path and can hold data as a byte array and has a version. When a node is created,
/// its version is 0. Upon updates, the version is atomically incremented. An update can also be conditional on an
/// expected current version. A transaction can hold several operations, which succeed or fail atomically.
/// when creating a zookeeper client, one can set a base path where all operations are relative to.
///
/// In this implementation:
/// Every Orleans deployment has a node /UniqueDeploymentId
/// Every Silo's state is saved in /UniqueDeploymentId/IP:Port@Gen
/// Every Silo's IAmAlive is saved in /UniqueDeploymentId/IP:Port@Gen/IAmAlive
/// IAmAlive is saved in a separate node because its updates are unconditional.
///
/// a node's ZK version is its ETag:
/// the table version is the version of /UniqueDeploymentId
/// the silo entry version is the version of /UniqueDeploymentId/IP:Port@Gen
/// </remarks>
public class ZooKeeperBasedMembershipTable : IMembershipTable, IGatewayListProvider
{
private Logger Logger;
private const int ZOOKEEPER_CONNECTION_TIMEOUT = 2000;
private ZooKeeperWatcher watcher;
/// <summary>
/// The deployment connection string. for eg. "192.168.1.1,192.168.1.2/DeploymentId"
/// </summary>
private string deploymentConnectionString;
/// <summary>
/// the node name for this deployment. for eg. /DeploymentId
/// </summary>
private string deploymentPath;
/// <summary>
/// The root connection string. for eg. "192.168.1.1,192.168.1.2"
/// </summary>
private string rootConnectionString;
private TimeSpan maxStaleness;
/// <summary>
/// Initializes the ZooKeeper based gateway provider
/// </summary>
/// <param name="config">The given client configuration.</param>
/// <param name="logger">The logger to be used by this instance</param>
public Task InitializeGatewayListProvider(ClientConfiguration config, Logger logger)
{
InitConfig(logger,config.DataConnectionString, config.DeploymentId);
maxStaleness = config.GatewayListRefreshPeriod;
return Task.CompletedTask;
}
/// <summary>
/// Initializes the ZooKeeper based membership table.
/// </summary>
/// <param name="config">The configuration for this instance.</param>
/// <param name="tryInitPath">if set to true, we'll try to create a node named "/DeploymentId"</param>
/// <param name="logger">The logger to be used by this instance</param>
/// <returns></returns>
public async Task InitializeMembershipTable(GlobalConfiguration config, bool tryInitPath, Logger logger)
{
InitConfig(logger, config.DataConnectionString, config.DeploymentId);
// even if I am not the one who created the path,
// try to insert an initial path if it is not already there,
// so we always have the path, before this silo starts working.
// note that when a zookeeper connection adds /DeploymentId to the connection string, the nodes are relative
await UsingZookeeper(rootConnectionString, async zk =>
{
try
{
await zk.createAsync(deploymentPath, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
await zk.sync(deploymentPath);
//if we got here we know that we've just created the deployment path with version=0
logger.Info("Created new deployment path: " + deploymentPath);
}
catch (KeeperException.NodeExistsException)
{
logger.Verbose("Deployment path already exists: " + deploymentPath);
}
});
}
private void InitConfig(Logger logger, string dataConnectionString, string deploymentId)
{
watcher = new ZooKeeperWatcher(logger);
Logger = logger;
deploymentPath = "/" + deploymentId;
deploymentConnectionString = dataConnectionString + deploymentPath;
rootConnectionString = dataConnectionString;
}
/// <summary>
/// Atomically reads the Membership Table information about a given silo.
/// The returned MembershipTableData includes one MembershipEntry entry for a given silo and the
/// TableVersion for this table. The MembershipEntry and the TableVersion have to be read atomically.
/// </summary>
/// <param name="siloAddress">The address of the silo whose membership information needs to be read.</param>
/// <returns>The membership information for a given silo: MembershipTableData consisting one MembershipEntry entry and
/// TableVersion, read atomically.</returns>
public Task<MembershipTableData> ReadRow(SiloAddress siloAddress)
{
return UsingZookeeper(async zk =>
{
var getRowTask = GetRow(zk, siloAddress);
var getTableNodeTask = zk.getDataAsync("/");//get the current table version
List<Tuple<MembershipEntry, string>> rows = new List<Tuple<MembershipEntry, string>>(1);
try
{
await Task.WhenAll(getRowTask, getTableNodeTask);
rows.Add(await getRowTask);
}
catch (KeeperException.NoNodeException)
{
//that's ok because orleans expects an empty list in case of a missing row
}
var tableVersion = ConvertToTableVersion((await getTableNodeTask).Stat);
return new MembershipTableData(rows, tableVersion);
}, true);
}
/// <summary>
/// Atomically reads the full content of the Membership Table.
/// The returned MembershipTableData includes all MembershipEntry entry for all silos in the table and the
/// TableVersion for this table. The MembershipEntries and the TableVersion have to be read atomically.
/// </summary>
/// <returns>The membership information for a given table: MembershipTableData consisting multiple MembershipEntry entries and
/// TableVersion, all read atomically.</returns>
public Task<MembershipTableData> ReadAll()
{
return UsingZookeeper(async zk =>
{
var childrenResult = await zk.getChildrenAsync("/");//get all the child nodes (without the data)
var childrenTasks = //get the data from each child node
childrenResult.Children.Select(child => GetRow(zk, SiloAddress.FromParsableString(child))).ToList();
var childrenTaskResults = await Task.WhenAll(childrenTasks);
var tableVersion = ConvertToTableVersion(childrenResult.Stat);//this is the current table version
return new MembershipTableData(childrenTaskResults.ToList(), tableVersion);
}, true);
}
/// <summary>
/// Atomically tries to insert (add) a new MembershipEntry for one silo and also update the TableVersion.
/// If operation succeeds, the following changes would be made to the table:
/// 1) New MembershipEntry will be added to the table.
/// 2) The newly added MembershipEntry will also be added with the new unique automatically generated eTag.
/// 3) TableVersion.Version in the table will be updated to the new TableVersion.Version.
/// 4) TableVersion etag in the table will be updated to the new unique automatically generated eTag.
/// All those changes to the table, insert of a new row and update of the table version and the associated etags, should happen atomically, or fail atomically with no side effects.
/// The operation should fail in each of the following conditions:
/// 1) A MembershipEntry for a given silo already exist in the table
/// 2) Update of the TableVersion failed since the given TableVersion etag (as specified by the TableVersion.VersionEtag property) did not match the TableVersion etag in the table.
/// </summary>
/// <param name="entry">MembershipEntry to be inserted.</param>
/// <param name="tableVersion">The new TableVersion for this table, along with its etag.</param>
/// <returns>True if the insert operation succeeded and false otherwise.</returns>
public Task<bool> InsertRow(MembershipEntry entry, TableVersion tableVersion)
{
string rowPath = ConvertToRowPath(entry.SiloAddress);
string rowIAmAlivePath = ConvertToRowIAmAlivePath(entry.SiloAddress);
byte[] newRowData = Serialize(entry);
byte[] newRowIAmAliveData = Serialize(entry.IAmAliveTime);
int expectedTableVersion = int.Parse(tableVersion.VersionEtag, CultureInfo.InvariantCulture);
return TryTransaction(t => t
.setData("/", null, expectedTableVersion)//increments the version of node "/"
.create(rowPath, newRowData, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT)
.create(rowIAmAlivePath, newRowIAmAliveData, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT));
}
/// <summary>
/// Atomically tries to update the MembershipEntry for one silo and also update the TableVersion.
/// If operation succeeds, the following changes would be made to the table:
/// 1) The MembershipEntry for this silo will be updated to the new MembershipEntry (the old entry will be fully substitued by the new entry)
/// 2) The eTag for the updated MembershipEntry will also be eTag with the new unique automatically generated eTag.
/// 3) TableVersion.Version in the table will be updated to the new TableVersion.Version.
/// 4) TableVersion etag in the table will be updated to the new unique automatically generated eTag.
/// All those changes to the table, update of a new row and update of the table version and the associated etags, should happen atomically, or fail atomically with no side effects.
/// The operation should fail in each of the following conditions:
/// 1) A MembershipEntry for a given silo does not exist in the table
/// 2) A MembershipEntry for a given silo exist in the table but its etag in the table does not match the provided etag.
/// 3) Update of the TableVersion failed since the given TableVersion etag (as specified by the TableVersion.VersionEtag property) did not match the TableVersion etag in the table.
/// </summary>
/// <param name="entry">MembershipEntry to be updated.</param>
/// <param name="etag">The etag for the given MembershipEntry.</param>
/// <param name="tableVersion">The new TableVersion for this table, along with its etag.</param>
/// <returns>True if the update operation succeeded and false otherwise.</returns>
public Task<bool> UpdateRow(MembershipEntry entry, string etag, TableVersion tableVersion)
{
string rowPath = ConvertToRowPath(entry.SiloAddress);
string rowIAmAlivePath = ConvertToRowIAmAlivePath(entry.SiloAddress);
var newRowData = Serialize(entry);
var newRowIAmAliveData = Serialize(entry.IAmAliveTime);
int expectedTableVersion = int.Parse(tableVersion.VersionEtag, CultureInfo.InvariantCulture);
int expectedRowVersion = int.Parse(etag, CultureInfo.InvariantCulture);
return TryTransaction(t => t
.setData("/", null, expectedTableVersion)//increments the version of node "/"
.setData(rowPath, newRowData, expectedRowVersion)//increments the version of node "/IP:Port@Gen"
.setData(rowIAmAlivePath, newRowIAmAliveData));
}
/// <summary>
/// Updates the IAmAlive part (column) of the MembershipEntry for this silo.
/// This operation should only update the IAmAlive collumn and not change other columns.
/// This operation is a "dirty write" or "in place update" and is performed without etag validation.
/// With regards to eTags update:
/// This operation may automatically update the eTag associated with the given silo row, but it does not have to. It can also leave the etag not changed ("dirty write").
/// With regards to TableVersion:
/// this operation should not change the TableVersion of the table. It should leave it untouched.
/// There is no scenario where this operation could fail due to table semantical reasons. It can only fail due to network problems or table unavailability.
/// </summary>
/// <param name="entry">The target MembershipEntry tp update</param>
/// <returns>Task representing the successful execution of this operation. </returns>
public Task UpdateIAmAlive(MembershipEntry entry)
{
string rowIAmAlivePath = ConvertToRowIAmAlivePath(entry.SiloAddress);
byte[] newRowIAmAliveData = Serialize(entry.IAmAliveTime);
//update the data for IAmAlive unconditionally
return UsingZookeeper(zk => zk.setDataAsync(rowIAmAlivePath, newRowIAmAliveData));
}
/// <summary>
/// Returns the list of gateways (silos) that can be used by a client to connect to Orleans cluster.
/// The Uri is in the form of: "gwy.tcp://IP:port/Generation". See Utils.ToGatewayUri and Utils.ToSiloAddress for more details about Uri format.
/// </summary>
public async Task<IList<Uri>> GetGateways()
{
var membershipTableData = await ReadAll();
return membershipTableData.Members.Select(e => e.Item1).
Where(m => m.Status == SiloStatus.Active && m.ProxyPort != 0).
Select(m =>
{
m.SiloAddress.Endpoint.Port = m.ProxyPort;
return m.SiloAddress.ToGatewayUri();
}).ToList();
}
/// <summary>
/// Specifies how often this IGatewayListProvider is refreshed, to have a bound on max staleness of its returned infomation.
/// </summary>
public TimeSpan MaxStaleness
{
get { return maxStaleness; }
}
/// <summary>
/// Specifies whether this IGatewayListProvider ever refreshes its returned infomation, or always returns the same gw list.
/// (currently only the static config based StaticGatewayListProvider is not updatable. All others are.)
/// </summary>
public bool IsUpdatable
{
get { return true; }
}
/// <summary>
/// Deletes all table entries of the given deploymentId
/// </summary>
public Task DeleteMembershipTableEntries(string deploymentId)
{
string pathToDelete = "/" + deploymentId;
return UsingZookeeper(rootConnectionString, async zk =>
{
await ZKUtil.deleteRecursiveAsync(zk, pathToDelete);
await zk.sync(pathToDelete);
});
}
private async Task<bool> TryTransaction(Func<Transaction, Transaction> transactionFunc)
{
try
{
await UsingZookeeper(zk => transactionFunc(zk.transaction()).commitAsync());
return true;
}
catch (KeeperException e)
{
//these exceptions are thrown when the transaction fails to commit due to semantical reasons
if (e is KeeperException.NodeExistsException || e is KeeperException.NoNodeException ||
e is KeeperException.BadVersionException)
{
return false;
}
throw;
}
}
/// <summary>
/// Reads the nodes /IP:Port@Gen and /IP:Port@Gen/IAmAlive (which together is one row)
/// </summary>
/// <param name="zk">The zookeeper instance used for the read</param>
/// <param name="siloAddress">The silo address.</param>
private static async Task<Tuple<MembershipEntry, string>> GetRow(ZooKeeper zk, SiloAddress siloAddress)
{
string rowPath = ConvertToRowPath(siloAddress);
string rowIAmAlivePath = ConvertToRowIAmAlivePath(siloAddress);
var rowDataTask = zk.getDataAsync(rowPath);
var rowIAmAliveDataTask = zk.getDataAsync(rowIAmAlivePath);
await Task.WhenAll(rowDataTask, rowIAmAliveDataTask);
MembershipEntry me = Deserialize<MembershipEntry>((await rowDataTask).Data);
me.IAmAliveTime = Deserialize<DateTime>((await rowIAmAliveDataTask).Data);
int rowVersion = (await rowDataTask).Stat.getVersion();
return new Tuple<MembershipEntry, string>(me, rowVersion.ToString(CultureInfo.InvariantCulture));
}
private Task<T> UsingZookeeper<T>(Func<ZooKeeper, Task<T>> zkMethod, bool canBeReadOnly = false)
{
return ZooKeeper.Using(deploymentConnectionString, ZOOKEEPER_CONNECTION_TIMEOUT, watcher, zkMethod, canBeReadOnly);
}
private Task UsingZookeeper(string connectString, Func<ZooKeeper, Task> zkMethod)
{
return ZooKeeper.Using(connectString, ZOOKEEPER_CONNECTION_TIMEOUT, watcher, zkMethod);
}
private static string ConvertToRowPath(SiloAddress siloAddress)
{
return "/" + siloAddress.ToParsableString();
}
private static string ConvertToRowIAmAlivePath(SiloAddress siloAddress)
{
return ConvertToRowPath(siloAddress) + "/IAmAlive";
}
private static TableVersion ConvertToTableVersion(Stat stat)
{
int version = stat.getVersion();
return new TableVersion(version, version.ToString(CultureInfo.InvariantCulture));
}
private static byte[] Serialize(object obj)
{
return
Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(obj, Formatting.None,
MembershipSerializerSettings.Instance));
}
private static T Deserialize<T>(byte[] data)
{
return JsonConvert.DeserializeObject<T>(Encoding.UTF8.GetString(data), MembershipSerializerSettings.Instance);
}
/// <summary>
/// the state of every ZooKeeper client and its push notifications are published using watchers.
/// in orleans the watcher is only for debugging purposes
/// </summary>
private class ZooKeeperWatcher : Watcher
{
private readonly Logger logger;
public ZooKeeperWatcher(Logger logger)
{
this.logger = logger;
}
public override Task process(WatchedEvent @event)
{
if (logger.IsVerbose)
{
logger.Verbose(@event.ToString());
}
return Task.CompletedTask;
}
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// InputState.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
using System.Collections.Generic;
#endregion
namespace HoneycombRush
{
/// <summary>
/// Helper for reading input from keyboard, gamepad, and touch input. This class
/// tracks both the current and previous state of the input devices, and implements
/// query methods for high level input actions such as "move up through the menu"
/// or "pause the game".
/// </summary>
public class InputState
{
#region Fields
public const int MaxInputs = 4;
public readonly KeyboardState[] CurrentKeyboardStates;
public readonly GamePadState[] CurrentGamePadStates;
public readonly KeyboardState[] LastKeyboardStates;
public readonly GamePadState[] LastGamePadStates;
public readonly bool[] GamePadWasConnected;
public TouchCollection TouchState;
public readonly List<GestureSample> Gestures = new List<GestureSample>();
#endregion
#region Initialization
/// <summary>
/// Constructs a new input state.
/// </summary>
public InputState()
{
CurrentKeyboardStates = new KeyboardState[MaxInputs];
CurrentGamePadStates = new GamePadState[MaxInputs];
LastKeyboardStates = new KeyboardState[MaxInputs];
LastGamePadStates = new GamePadState[MaxInputs];
GamePadWasConnected = new bool[MaxInputs];
}
#endregion
#region Public Methods
/// <summary>
/// Reads the latest state of the keyboard and gamepad.
/// </summary>
public void Update()
{
for (int i = 0; i < MaxInputs; i++)
{
LastKeyboardStates[i] = CurrentKeyboardStates[i];
LastGamePadStates[i] = CurrentGamePadStates[i];
CurrentKeyboardStates[i] = Keyboard.GetState((PlayerIndex)i);
CurrentGamePadStates[i] = GamePad.GetState((PlayerIndex)i);
// Keep track of whether a gamepad has ever been
// connected, so we can detect if it is unplugged.
if (CurrentGamePadStates[i].IsConnected)
{
GamePadWasConnected[i] = true;
}
}
TouchState = TouchPanel.GetState();
Gestures.Clear();
while (TouchPanel.IsGestureAvailable)
{
Gestures.Add(TouchPanel.ReadGesture());
}
}
/// <summary>
/// Helper for checking if a key was newly pressed during this update. The
/// controllingPlayer parameter specifies which player to read input for.
/// If this is null, it will accept input from any player. When a keypress
/// is detected, the output playerIndex reports which player pressed it.
/// </summary>
public bool IsNewKeyPress(Keys key, PlayerIndex? controllingPlayer,
out PlayerIndex playerIndex)
{
if (controllingPlayer.HasValue)
{
// Read input from the specified player.
playerIndex = controllingPlayer.Value;
int i = (int)playerIndex;
return (CurrentKeyboardStates[i].IsKeyDown(key) &&
LastKeyboardStates[i].IsKeyUp(key));
}
else
{
// Accept input from any player.
return (IsNewKeyPress(key, PlayerIndex.One, out playerIndex) ||
IsNewKeyPress(key, PlayerIndex.Two, out playerIndex) ||
IsNewKeyPress(key, PlayerIndex.Three, out playerIndex) ||
IsNewKeyPress(key, PlayerIndex.Four, out playerIndex));
}
}
/// <summary>
/// Helper for checking if a key is currently pressed during the update. The
/// controllingPlayer parameter specifies which player to read input for.
/// If this is null, it will accept input from any player. When a pressed key
/// is detected, the output playerIndex reports which player pressed it.
/// </summary>
public bool IsKeyDown(Keys key, PlayerIndex? controllingPlayer,
out PlayerIndex playerIndex)
{
if (controllingPlayer.HasValue)
{
// Read input from the specified player.
playerIndex = controllingPlayer.Value;
int i = (int)playerIndex;
return (CurrentKeyboardStates[i].IsKeyDown(key));
}
else
{
// Accept input from any player.
return (IsKeyDown(key, PlayerIndex.One, out playerIndex) ||
IsKeyDown(key, PlayerIndex.Two, out playerIndex) ||
IsKeyDown(key, PlayerIndex.Three, out playerIndex) ||
IsKeyDown(key, PlayerIndex.Four, out playerIndex));
}
}
/// <summary>
/// Helper for checking if a button was newly pressed during this update.
/// The controllingPlayer parameter specifies which player to read input for.
/// If this is null, it will accept input from any player. When a button press
/// is detected, the output playerIndex reports which player pressed it.
/// </summary>
public bool IsNewButtonPress(Buttons button, PlayerIndex? controllingPlayer,
out PlayerIndex playerIndex)
{
if (controllingPlayer.HasValue)
{
// Read input from the specified player.
playerIndex = controllingPlayer.Value;
int i = (int)playerIndex;
return (CurrentGamePadStates[i].IsButtonDown(button) &&
LastGamePadStates[i].IsButtonUp(button));
}
else
{
// Accept input from any player.
return (IsNewButtonPress(button, PlayerIndex.One, out playerIndex) ||
IsNewButtonPress(button, PlayerIndex.Two, out playerIndex) ||
IsNewButtonPress(button, PlayerIndex.Three, out playerIndex) ||
IsNewButtonPress(button, PlayerIndex.Four, out playerIndex));
}
}
/// <summary>
/// Checks for a "menu select" input action.
/// The controllingPlayer parameter specifies which player to read input for.
/// If this is null, it will accept input from any player. When the action
/// is detected, the output playerIndex reports which player pressed it.
/// </summary>
public bool IsMenuSelect(PlayerIndex? controllingPlayer,
out PlayerIndex playerIndex)
{
return IsNewKeyPress(Keys.Space, controllingPlayer, out playerIndex) ||
IsNewKeyPress(Keys.Enter, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.A, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.Start, controllingPlayer, out playerIndex);
}
/// <summary>
/// Checks for a "menu cancel" input action.
/// The controllingPlayer parameter specifies which player to read input for.
/// If this is null, it will accept input from any player. When the action
/// is detected, the output playerIndex reports which player pressed it.
/// </summary>
public bool IsMenuCancel(PlayerIndex? controllingPlayer,
out PlayerIndex playerIndex)
{
return IsNewKeyPress(Keys.Escape, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.B, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.Back, controllingPlayer, out playerIndex);
}
/// <summary>
/// Checks for a "menu up" input action.
/// The controllingPlayer parameter specifies which player to read
/// input for. If this is null, it will accept input from any player.
/// </summary>
public bool IsMenuUp(PlayerIndex? controllingPlayer)
{
PlayerIndex playerIndex;
return IsNewKeyPress(Keys.Up, controllingPlayer, out playerIndex) ||
IsNewKeyPress(Keys.Left, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.DPadLeft, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.LeftThumbstickLeft, controllingPlayer, out playerIndex);
}
/// <summary>
/// Checks for a "menu down" input action.
/// The controllingPlayer parameter specifies which player to read
/// input for. If this is null, it will accept input from any player.
/// </summary>
public bool IsMenuDown(PlayerIndex? controllingPlayer)
{
PlayerIndex playerIndex;
return IsNewKeyPress(Keys.Down, controllingPlayer, out playerIndex) ||
IsNewKeyPress(Keys.Right, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.DPadRight, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.LeftThumbstickRight, controllingPlayer, out playerIndex);
}
/// <summary>
/// Checks for a "pause the game" input action.
/// The controllingPlayer parameter specifies which player to read
/// input for. If this is null, it will accept input from any player.
/// </summary>
public bool IsPauseGame(PlayerIndex? controllingPlayer)
{
PlayerIndex playerIndex;
return IsNewKeyPress(Keys.Escape, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.Back, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.Start, controllingPlayer, out playerIndex);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void OrUInt16()
{
var test = new SimpleBinaryOpTest__OrUInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__OrUInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(UInt16[] inArray1, UInt16[] inArray2, UInt16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<UInt16> _fld1;
public Vector256<UInt16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__OrUInt16 testClass)
{
var result = Avx2.Or(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__OrUInt16 testClass)
{
fixed (Vector256<UInt16>* pFld1 = &_fld1)
fixed (Vector256<UInt16>* pFld2 = &_fld2)
{
var result = Avx2.Or(
Avx.LoadVector256((UInt16*)(pFld1)),
Avx.LoadVector256((UInt16*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static UInt16[] _data1 = new UInt16[Op1ElementCount];
private static UInt16[] _data2 = new UInt16[Op2ElementCount];
private static Vector256<UInt16> _clsVar1;
private static Vector256<UInt16> _clsVar2;
private Vector256<UInt16> _fld1;
private Vector256<UInt16> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__OrUInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
}
public SimpleBinaryOpTest__OrUInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
_dataTable = new DataTable(_data1, _data2, new UInt16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.Or(
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.Or(
Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.Or(
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Or), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Or), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Or), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.Or(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<UInt16>* pClsVar1 = &_clsVar1)
fixed (Vector256<UInt16>* pClsVar2 = &_clsVar2)
{
var result = Avx2.Or(
Avx.LoadVector256((UInt16*)(pClsVar1)),
Avx.LoadVector256((UInt16*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr);
var result = Avx2.Or(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr));
var result = Avx2.Or(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr));
var result = Avx2.Or(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__OrUInt16();
var result = Avx2.Or(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__OrUInt16();
fixed (Vector256<UInt16>* pFld1 = &test._fld1)
fixed (Vector256<UInt16>* pFld2 = &test._fld2)
{
var result = Avx2.Or(
Avx.LoadVector256((UInt16*)(pFld1)),
Avx.LoadVector256((UInt16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.Or(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<UInt16>* pFld1 = &_fld1)
fixed (Vector256<UInt16>* pFld2 = &_fld2)
{
var result = Avx2.Or(
Avx.LoadVector256((UInt16*)(pFld1)),
Avx.LoadVector256((UInt16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.Or(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx2.Or(
Avx.LoadVector256((UInt16*)(&test._fld1)),
Avx.LoadVector256((UInt16*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<UInt16> op1, Vector256<UInt16> op2, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((ushort)(left[0] | right[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((ushort)(left[i] | right[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Or)}<UInt16>(Vector256<UInt16>, Vector256<UInt16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Text;
using Debug = System.Diagnostics.Debug;
namespace Internal.TypeSystem
{
/// <summary>
/// Base type for all type system exceptions.
/// </summary>
public abstract class TypeSystemException : Exception
{
private string[] _arguments;
/// <summary>
/// Gets the resource string identifier.
/// </summary>
public ExceptionStringID StringID { get; }
/// <summary>
/// Gets the formatting arguments for the exception string.
/// </summary>
public IReadOnlyList<string> Arguments
{
get
{
return _arguments;
}
}
public override string Message
{
get
{
return GetExceptionString(StringID, _arguments);
}
}
public TypeSystemException(ExceptionStringID id, params string[] args)
{
StringID = id;
_arguments = args;
}
private static string GetExceptionString(ExceptionStringID id, string[] args)
{
// TODO: Share the strings and lookup logic with System.Private.CoreLib.
return "[TEMPORARY EXCEPTION MESSAGE] " + id.ToString() + ": " + String.Join(", ", args);
}
/// <summary>
/// The exception that is thrown when type-loading failures occur.
/// </summary>
public class TypeLoadException : TypeSystemException
{
public string TypeName { get; }
public string AssemblyName { get; }
private TypeLoadException(ExceptionStringID id, string typeName, string assemblyName, string messageArg)
: base(id, new string[] { typeName, assemblyName, messageArg })
{
TypeName = typeName;
AssemblyName = assemblyName;
}
private TypeLoadException(ExceptionStringID id, string typeName, string assemblyName)
: base(id, new string[] { typeName, assemblyName })
{
TypeName = typeName;
AssemblyName = assemblyName;
}
public TypeLoadException(string nestedTypeName, ModuleDesc module)
: this(ExceptionStringID.ClassLoadGeneral, nestedTypeName, Format.Module(module))
{
}
public TypeLoadException(string @namespace, string name, ModuleDesc module)
: this(ExceptionStringID.ClassLoadGeneral, Format.Type(@namespace, name), Format.Module(module))
{
}
public TypeLoadException(ExceptionStringID id, MethodDesc method)
: this(id, Format.Type(method.OwningType), Format.OwningModule(method), Format.Method(method))
{
}
public TypeLoadException(ExceptionStringID id, TypeDesc type, string messageArg)
: this(id, Format.Type(type), Format.OwningModule(type), messageArg)
{
}
public TypeLoadException(ExceptionStringID id, TypeDesc type)
: this(id, Format.Type(type), Format.OwningModule(type))
{
}
}
/// <summary>
/// The exception that is thrown when there is an attempt to access a class member that does not exist
/// or that is not declared as public.
/// </summary>
public abstract class MissingMemberException : TypeSystemException
{
protected internal MissingMemberException(ExceptionStringID id, params string[] args)
: base(id, args)
{
}
}
/// <summary>
/// The exception that is thrown when there is an attempt to access a method that does not exist.
/// </summary>
public class MissingMethodException : MissingMemberException
{
public MissingMethodException(ExceptionStringID id, params string[] args)
: base(id, args)
{
}
public MissingMethodException(TypeDesc owningType, string methodName, MethodSignature signature)
: this(ExceptionStringID.MissingMethod, Format.Method(owningType, methodName, signature))
{
}
}
/// <summary>
/// The exception that is thrown when there is an attempt to access a field that does not exist.
/// </summary>
public class MissingFieldException : MissingMemberException
{
public MissingFieldException(ExceptionStringID id, params string[] args)
: base(id, args)
{
}
public MissingFieldException(TypeDesc owningType, string fieldName)
: this(ExceptionStringID.MissingField, Format.Field(owningType, fieldName))
{
}
}
/// <summary>
/// The exception that is thrown when an attempt to access a file that does not exist on disk fails.
/// </summary>
public class FileNotFoundException : TypeSystemException
{
public FileNotFoundException(ExceptionStringID id, string fileName)
: base(id, fileName)
{
}
}
/// <summary>
/// The exception that is thrown when a program contains invalid Microsoft intermediate language (MSIL) or metadata.
/// Generally this indicates a bug in the compiler that generated the program.
/// </summary>
public class InvalidProgramException : TypeSystemException
{
public InvalidProgramException(ExceptionStringID id, MethodDesc method)
: base(id, Format.Method(method))
{
}
}
public class BadImageFormatException : TypeSystemException
{
public BadImageFormatException()
: base(ExceptionStringID.BadImageFormatGeneric)
{
}
}
#region Formatting helpers
private static class Format
{
public static string OwningModule(MethodDesc method)
{
return OwningModule(method.OwningType);
}
public static string OwningModule(TypeDesc type)
{
return Module((type as MetadataType)?.Module);
}
public static string Module(ModuleDesc module)
{
if (module == null)
return "?";
IAssemblyDesc assembly = module as IAssemblyDesc;
if (assembly != null)
{
return assembly.GetName().FullName;
}
else
{
Debug.Assert(false, "Multi-module assemblies");
return module.ToString();
}
}
public static string Type(TypeDesc type)
{
return ExceptionTypeNameFormatter.Instance.FormatName(type);
}
public static string Type(string @namespace, string name)
{
return String.IsNullOrEmpty(@namespace) ? name : @namespace + "." + name;
}
public static string Field(TypeDesc owningType, string fieldName)
{
return Type(owningType) + "." + fieldName;
}
public static string Method(MethodDesc method)
{
return Method(method.OwningType, method.Name, method.Signature);
}
public static string Method(TypeDesc owningType, string methodName, MethodSignature signature)
{
StringBuilder sb = new StringBuilder();
if (signature != null)
{
sb.Append(ExceptionTypeNameFormatter.Instance.FormatName(signature.ReturnType));
sb.Append(' ');
}
sb.Append(ExceptionTypeNameFormatter.Instance.FormatName(owningType));
sb.Append('.');
sb.Append(methodName);
if (signature != null)
{
sb.Append('(');
for (int i = 0; i < signature.Length; i++)
{
if (i > 0)
{
sb.Append(", ");
}
sb.Append(ExceptionTypeNameFormatter.Instance.FormatName(signature[i]));
}
sb.Append(')');
}
return sb.ToString();
}
/// <summary>
/// Provides a name formatter that is compatible with SigFormat.cpp in the CLR.
/// </summary>
private class ExceptionTypeNameFormatter : TypeNameFormatter
{
public static ExceptionTypeNameFormatter Instance { get; } = new ExceptionTypeNameFormatter();
public override void AppendName(StringBuilder sb, PointerType type)
{
AppendName(sb, type.ParameterType);
sb.Append('*');
}
public override void AppendName(StringBuilder sb, GenericParameterDesc type)
{
string prefix = type.Kind == GenericParameterKind.Type ? "!" : "!!";
sb.Append(prefix);
sb.Append(type.Name);
}
public override void AppendName(StringBuilder sb, SignatureTypeVariable type)
{
sb.Append("!");
sb.Append(type.Index.ToStringInvariant());
}
public override void AppendName(StringBuilder sb, SignatureMethodVariable type)
{
sb.Append("!!");
sb.Append(type.Index.ToStringInvariant());
}
public override void AppendName(StringBuilder sb, FunctionPointerType type)
{
MethodSignature signature = type.Signature;
AppendName(sb, signature.ReturnType);
sb.Append(" (");
for (int i = 0; i < signature.Length; i++)
{
if (i > 0)
sb.Append(", ");
AppendName(sb, signature[i]);
}
// TODO: Append '...' for vararg methods
sb.Append(')');
}
public override void AppendName(StringBuilder sb, ByRefType type)
{
AppendName(sb, type.ParameterType);
sb.Append(" ByRef");
}
public override void AppendName(StringBuilder sb, ArrayType type)
{
AppendName(sb, type.ElementType);
sb.Append('[');
// NOTE: We're ignoring difference between SzArray and MdArray rank 1 for SigFormat.cpp compat.
sb.Append(',', type.Rank - 1);
sb.Append(']');
}
protected override void AppendNameForInstantiatedType(StringBuilder sb, DefType type)
{
AppendName(sb, type.GetTypeDefinition());
sb.Append('<');
for (int i = 0; i < type.Instantiation.Length; i++)
{
if (i > 0)
sb.Append(", ");
AppendName(sb, type.Instantiation[i]);
}
sb.Append('>');
}
protected override void AppendNameForNamespaceType(StringBuilder sb, DefType type)
{
if (type.IsPrimitive)
{
sb.Append(type.Name);
}
else
{
string ns = type.Namespace;
if (ns.Length > 0)
{
sb.Append(ns);
sb.Append('.');
}
sb.Append(type.Name);
}
}
protected override void AppendNameForNestedType(StringBuilder sb, DefType nestedType, DefType containingType)
{
// NOTE: We're ignoring the containing type for compatiblity with SigFormat.cpp
sb.Append(nestedType.Name);
}
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Concurrent;
using System.Globalization;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Management.Automation.Remoting;
using System.Management.Automation.Remoting.Internal;
using System.Threading;
using Microsoft.Management.Infrastructure;
using Microsoft.Management.Infrastructure.Options;
using Microsoft.PowerShell.Cim;
using Dbg = System.Management.Automation.Diagnostics;
namespace Microsoft.PowerShell.Cmdletization.Cim
{
/// <summary>
/// Base class for all child jobs that wrap CIM operations.
/// </summary>
internal abstract class CimChildJobBase<T> :
StartableJob,
IObserver<T>
{
private static long s_globalJobNumberCounter;
private readonly long _myJobNumber = Interlocked.Increment(ref s_globalJobNumberCounter);
private const string CIMJobType = "CimJob";
internal CimJobContext JobContext
{
get
{
return _jobContext;
}
}
private readonly CimJobContext _jobContext;
internal CimChildJobBase(CimJobContext jobContext)
: base(Job.GetCommandTextFromInvocationInfo(jobContext.CmdletInvocationInfo), " " /* temporary name - reset below */)
{
_jobContext = jobContext;
this.PSJobTypeName = CIMJobType;
this.Name = this.GetType().Name + _myJobNumber.ToString(CultureInfo.InvariantCulture);
UsesResultsCollection = true;
lock (s_globalRandom)
{
_random = new Random(s_globalRandom.Next());
}
_jobSpecificCustomOptions = new Lazy<CimCustomOptionsDictionary>(this.CalculateJobSpecificCustomOptions);
}
private readonly CimSensitiveValueConverter _cimSensitiveValueConverter = new();
internal CimSensitiveValueConverter CimSensitiveValueConverter { get { return _cimSensitiveValueConverter; } }
internal abstract IObservable<T> GetCimOperation();
public abstract void OnNext(T item);
// copied from sdpublic\sdk\inc\wsmerror.h
private enum WsManErrorCode : uint
{
ERROR_WSMAN_QUOTA_MAX_SHELLS = 0x803381A5,
ERROR_WSMAN_QUOTA_MAX_OPERATIONS = 0x803381A6,
ERROR_WSMAN_QUOTA_USER = 0x803381A7,
ERROR_WSMAN_QUOTA_SYSTEM = 0x803381A8,
ERROR_WSMAN_QUOTA_MAX_SHELLUSERS = 0x803381AB,
ERROR_WSMAN_QUOTA_MAX_SHELLS_PPQ = 0x803381E4,
ERROR_WSMAN_QUOTA_MAX_USERS_PPQ = 0x803381E5,
ERROR_WSMAN_QUOTA_MAX_PLUGINSHELLS_PPQ = 0x803381E6,
ERROR_WSMAN_QUOTA_MAX_PLUGINOPERATIONS_PPQ = 0x803381E7,
ERROR_WSMAN_QUOTA_MAX_OPERATIONS_USER_PPQ = 0x803381E8,
ERROR_WSMAN_QUOTA_MAX_COMMANDS_PER_SHELL_PPQ = 0x803381E9,
ERROR_WSMAN_QUOTA_MIN_REQUIREMENT_NOT_AVAILABLE_PPQ = 0x803381EA,
}
private static bool IsWsManQuotaReached(Exception exception)
{
if (!(exception is CimException cimException))
{
return false;
}
if (cimException.NativeErrorCode != NativeErrorCode.ServerLimitsExceeded)
{
return false;
}
CimInstance cimError = cimException.ErrorData;
if (cimError == null)
{
return false;
}
CimProperty errorCodeProperty = cimError.CimInstanceProperties["error_Code"];
if (errorCodeProperty == null)
{
return false;
}
if (errorCodeProperty.CimType != CimType.UInt32)
{
return false;
}
WsManErrorCode wsManErrorCode = (WsManErrorCode)(uint)(errorCodeProperty.Value);
switch (wsManErrorCode) // error codes that should result in sleep-and-retry are based on an email from Ryan
{
case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_SHELLS:
case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_OPERATIONS:
case WsManErrorCode.ERROR_WSMAN_QUOTA_USER:
case WsManErrorCode.ERROR_WSMAN_QUOTA_SYSTEM:
case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_SHELLUSERS:
case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_SHELLS_PPQ:
case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_USERS_PPQ:
case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_PLUGINSHELLS_PPQ:
case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_PLUGINOPERATIONS_PPQ:
case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_OPERATIONS_USER_PPQ:
case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_COMMANDS_PER_SHELL_PPQ:
case WsManErrorCode.ERROR_WSMAN_QUOTA_MIN_REQUIREMENT_NOT_AVAILABLE_PPQ:
return true;
default:
return false;
}
}
public virtual void OnError(Exception exception)
{
this.ExceptionSafeWrapper(
delegate
{
if (IsWsManQuotaReached(exception))
{
this.SleepAndRetry();
return;
}
var cje = CimJobException.CreateFromAnyException(this.GetDescription(), this.JobContext, exception);
this.ReportJobFailure(cje);
});
}
public virtual void OnCompleted()
{
this.ExceptionSafeWrapper(
delegate
{
this.SetCompletedJobState(JobState.Completed, null);
});
}
private static readonly Random s_globalRandom = new();
private readonly Random _random;
private int _sleepAndRetryDelayRangeMs = 1000;
private int _sleepAndRetryExtraDelayMs = 0;
private const int MaxRetryDelayMs = 15 * 1000;
private const int MinRetryDelayMs = 100;
private Timer _sleepAndRetryTimer;
private void SleepAndRetry_OnWakeup(object state)
{
this.ExceptionSafeWrapper(
delegate
{
lock (_jobStateLock)
{
if (_sleepAndRetryTimer != null)
{
_sleepAndRetryTimer.Dispose();
_sleepAndRetryTimer = null;
}
if (_jobWasStopped)
{
this.SetCompletedJobState(JobState.Stopped, null);
return;
}
}
this.StartJob();
});
}
private void SleepAndRetry()
{
int tmpRandomDelay = _random.Next(0, _sleepAndRetryDelayRangeMs);
int delay = MinRetryDelayMs + _sleepAndRetryExtraDelayMs + tmpRandomDelay;
_sleepAndRetryExtraDelayMs = _sleepAndRetryDelayRangeMs - tmpRandomDelay;
if (_sleepAndRetryDelayRangeMs < MaxRetryDelayMs)
{
_sleepAndRetryDelayRangeMs *= 2;
}
string verboseMessage = string.Format(
CultureInfo.InvariantCulture,
CmdletizationResources.CimJob_SleepAndRetryVerboseMessage,
this.JobContext.CmdletInvocationInfo.InvocationName,
this.JobContext.Session.ComputerName ?? "localhost",
delay / 1000.0);
this.WriteVerbose(verboseMessage);
lock (_jobStateLock)
{
if (_jobWasStopped)
{
this.SetCompletedJobState(JobState.Stopped, null);
}
else
{
Dbg.Assert(_sleepAndRetryTimer == null, "There should be only 1 active _sleepAndRetryTimer");
_sleepAndRetryTimer = new Timer(
state: null,
dueTime: delay,
period: Timeout.Infinite,
callback: SleepAndRetry_OnWakeup);
}
}
}
/// <summary>
/// Indicates a location where this job is running.
/// </summary>
public override string Location
{
get
{
// this.JobContext is set in the constructor of CimChildJobBase,
// but the constructor of Job wants to access Location property
// before CimChildJobBase is fully initialized
if (this.JobContext == null)
{
return null;
}
string location = this.JobContext.Session.ComputerName ?? Environment.MachineName;
return location;
}
}
/// <summary>
/// Status message associated with the Job.
/// </summary>
public override string StatusMessage
{
get
{
return this.JobStateInfo.State.ToString();
}
}
/// <summary>
/// Indicates if job has more data available.
/// </summary>
public override bool HasMoreData
{
get
{
return (Results.IsOpen || Results.Count > 0);
}
}
internal void WriteVerboseStartOfCimOperation()
{
if (this.JobContext.CmdletInvocationContext.CmdletDefinitionContext.ClientSideWriteVerbose)
{
string verboseMessage = string.Format(
CultureInfo.CurrentCulture,
CmdletizationResources.CimJob_VerboseExecutionMessage,
this.GetDescription());
this.WriteVerbose(verboseMessage);
}
}
internal override void StartJob()
{
lock (_jobStateLock)
{
if (_jobWasStopped)
{
this.SetCompletedJobState(JobState.Stopped, null);
return;
}
Dbg.Assert(!_alreadyReachedCompletedState, "Job shouldn't reach completed state, before ThrottlingJob has a chance to register for job-completed/failed events");
TerminatingErrorTracker tracker = TerminatingErrorTracker.GetTracker(this.JobContext.CmdletInvocationInfo);
if (tracker.IsSessionTerminated(this.JobContext.Session))
{
this.SetCompletedJobState(JobState.Failed, new OperationCanceledException());
return;
}
if (!_jobWasStarted)
{
_jobWasStarted = true;
this.SetJobState(JobState.Running);
}
}
// This invocation can block (i.e. by calling Job.ShouldProcess) and wait for pipeline thread to unblock it
// Therefore we have to do the invocation outside of the pipeline thread.
ThreadPool.QueueUserWorkItem(delegate
{
this.ExceptionSafeWrapper(delegate
{
IObservable<T> observable = this.GetCimOperation();
if (observable != null)
{
observable.Subscribe(this);
}
});
});
}
internal string GetDescription()
{
try
{
return this.Description;
}
catch (Exception)
{
return this.FailSafeDescription;
}
}
internal abstract string Description { get; }
internal abstract string FailSafeDescription { get; }
internal void ExceptionSafeWrapper(Action action)
{
try
{
try
{
Dbg.Assert(action != null, "Caller should verify action != null");
action();
}
catch (CimJobException e)
{
this.ReportJobFailure(e);
}
catch (PSInvalidCastException e)
{
this.ReportJobFailure(e);
}
catch (CimException e)
{
var cje = CimJobException.CreateFromCimException(this.GetDescription(), this.JobContext, e);
this.ReportJobFailure(cje);
}
catch (PSInvalidOperationException)
{
lock (_jobStateLock)
{
bool everythingIsOk = false;
if (_jobWasStopped)
{
everythingIsOk = true;
}
if (_alreadyReachedCompletedState && _jobHadErrors)
{
everythingIsOk = true;
}
if (!everythingIsOk)
{
Dbg.Assert(false, "PSInvalidOperationException should only happen in certain job states");
throw;
}
}
}
}
catch (Exception e)
{
var cje = CimJobException.CreateFromAnyException(this.GetDescription(), this.JobContext, e);
this.ReportJobFailure(cje);
}
}
#region Operation options
internal virtual string GetProviderVersionExpectedByJob()
{
return this.JobContext.CmdletInvocationContext.CmdletDefinitionContext.CmdletizationClassVersion;
}
internal CimOperationOptions CreateOperationOptions()
{
var operationOptions = new CimOperationOptions(mustUnderstand: false)
{
CancellationToken = _cancellationTokenSource.Token,
WriteProgress = this.WriteProgressCallback,
WriteMessage = this.WriteMessageCallback,
WriteError = this.WriteErrorCallback,
PromptUser = this.PromptUserCallback,
};
operationOptions.SetOption("__MI_OPERATIONOPTIONS_IMPROVEDPERF_STREAMING", 1);
operationOptions.Flags |= this.JobContext.CmdletInvocationContext.CmdletDefinitionContext.SchemaConformanceLevel;
if (this.JobContext.CmdletInvocationContext.CmdletDefinitionContext.ResourceUri != null)
{
operationOptions.ResourceUri = this.JobContext.CmdletInvocationContext.CmdletDefinitionContext.ResourceUri;
}
if ((
(_jobContext.WarningActionPreference == ActionPreference.SilentlyContinue) ||
(_jobContext.WarningActionPreference == ActionPreference.Ignore)
) && (!_jobContext.IsRunningInBackground))
{
operationOptions.DisableChannel((uint)MessageChannel.Warning);
}
else
{
operationOptions.EnableChannel((uint)MessageChannel.Warning);
}
if ((
(_jobContext.VerboseActionPreference == ActionPreference.SilentlyContinue) ||
(_jobContext.VerboseActionPreference == ActionPreference.Ignore)
) && (!_jobContext.IsRunningInBackground))
{
operationOptions.DisableChannel((uint)MessageChannel.Verbose);
}
else
{
operationOptions.EnableChannel((uint)MessageChannel.Verbose);
}
if ((
(_jobContext.DebugActionPreference == ActionPreference.SilentlyContinue) ||
(_jobContext.DebugActionPreference == ActionPreference.Ignore)
) && (!_jobContext.IsRunningInBackground))
{
operationOptions.DisableChannel((uint)MessageChannel.Debug);
}
else
{
operationOptions.EnableChannel((uint)MessageChannel.Debug);
}
switch (this.JobContext.ShouldProcessOptimization)
{
case MshCommandRuntime.ShouldProcessPossibleOptimization.AutoNo_CanCallShouldProcessAsynchronously:
operationOptions.SetPromptUserRegularMode(CimCallbackMode.Report, automaticConfirmation: false);
break;
case MshCommandRuntime.ShouldProcessPossibleOptimization.AutoYes_CanCallShouldProcessAsynchronously:
operationOptions.SetPromptUserRegularMode(CimCallbackMode.Report, automaticConfirmation: true);
break;
case MshCommandRuntime.ShouldProcessPossibleOptimization.AutoYes_CanSkipShouldProcessCall:
operationOptions.SetPromptUserRegularMode(CimCallbackMode.Ignore, automaticConfirmation: true);
break;
case MshCommandRuntime.ShouldProcessPossibleOptimization.NoOptimizationPossible:
default:
operationOptions.PromptUserMode = CimCallbackMode.Inquire;
break;
}
switch (this.JobContext.ErrorActionPreference)
{
case ActionPreference.Continue:
case ActionPreference.SilentlyContinue:
case ActionPreference.Ignore:
operationOptions.WriteErrorMode = CimCallbackMode.Report;
break;
case ActionPreference.Stop:
case ActionPreference.Inquire:
default:
operationOptions.WriteErrorMode = CimCallbackMode.Inquire;
break;
}
if (!string.IsNullOrWhiteSpace(this.GetProviderVersionExpectedByJob()))
{
CimOperationOptionsHelper.SetCustomOption(
operationOptions,
"MI_OPERATIONOPTIONS_PROVIDERVERSION",
this.GetProviderVersionExpectedByJob(),
CimSensitiveValueConverter);
}
if (this.JobContext.CmdletizationModuleVersion != null)
{
CimOperationOptionsHelper.SetCustomOption(
operationOptions,
"MI_OPERATIONOPTIONS_POWERSHELL_MODULEVERSION",
this.JobContext.CmdletizationModuleVersion,
CimSensitiveValueConverter);
}
CimOperationOptionsHelper.SetCustomOption(
operationOptions,
"MI_OPERATIONOPTIONS_POWERSHELL_CMDLETNAME",
this.JobContext.CmdletInvocationInfo.MyCommand.Name,
CimSensitiveValueConverter);
if (!string.IsNullOrWhiteSpace(this.JobContext.Session.ComputerName))
{
CimOperationOptionsHelper.SetCustomOption(
operationOptions,
"MI_OPERATIONOPTIONS_POWERSHELL_COMPUTERNAME",
this.JobContext.Session.ComputerName,
CimSensitiveValueConverter);
}
CimCustomOptionsDictionary jobSpecificCustomOptions = this.GetJobSpecificCustomOptions();
if (jobSpecificCustomOptions != null)
{
jobSpecificCustomOptions.Apply(operationOptions, CimSensitiveValueConverter);
}
return operationOptions;
}
private readonly Lazy<CimCustomOptionsDictionary> _jobSpecificCustomOptions;
internal abstract CimCustomOptionsDictionary CalculateJobSpecificCustomOptions();
private CimCustomOptionsDictionary GetJobSpecificCustomOptions()
{
return _jobSpecificCustomOptions.Value;
}
#endregion
#region Controlling job state
private readonly CancellationTokenSource _cancellationTokenSource = new();
/// <summary>
/// Stops this job.
/// </summary>
public override void StopJob()
{
lock (_jobStateLock)
{
if (_jobWasStopped || _alreadyReachedCompletedState)
{
return;
}
_jobWasStopped = true;
if (!_jobWasStarted)
{
this.SetCompletedJobState(JobState.Stopped, null);
}
else if (_sleepAndRetryTimer != null)
{
_sleepAndRetryTimer.Dispose();
_sleepAndRetryTimer = null;
this.SetCompletedJobState(JobState.Stopped, null);
}
else
{
this.SetJobState(JobState.Stopping);
}
}
_cancellationTokenSource.Cancel();
}
private readonly object _jobStateLock = new();
private bool _jobHadErrors;
private bool _jobWasStarted;
private bool _jobWasStopped;
private bool _alreadyReachedCompletedState;
internal bool JobHadErrors
{
get
{
lock (_jobStateLock)
{
return _jobHadErrors;
}
}
}
internal void ReportJobFailure(IContainsErrorRecord exception)
{
TerminatingErrorTracker terminatingErrorTracker = TerminatingErrorTracker.GetTracker(this.JobContext.CmdletInvocationInfo);
bool sessionWasAlreadyTerminated = false;
bool isThisTerminatingError = false;
Exception brokenSessionException = null;
lock (_jobStateLock)
{
if (!_jobWasStopped)
{
brokenSessionException = terminatingErrorTracker.GetExceptionIfBrokenSession(
this.JobContext.Session,
this.JobContext.CmdletInvocationContext.CmdletDefinitionContext.SkipTestConnection,
out sessionWasAlreadyTerminated);
}
}
if (brokenSessionException != null)
{
string brokenSessionMessage = string.Format(
CultureInfo.InvariantCulture,
CmdletizationResources.CimJob_BrokenSession,
brokenSessionException.Message);
exception = CimJobException.CreateWithFullControl(
this.JobContext,
brokenSessionMessage,
"CimJob_BrokenCimSession",
ErrorCategory.ResourceUnavailable,
brokenSessionException);
isThisTerminatingError = true;
}
else
{
CimJobException cje = exception as CimJobException;
if ((cje != null) && (cje.IsTerminatingError))
{
terminatingErrorTracker.MarkSessionAsTerminated(this.JobContext.Session, out sessionWasAlreadyTerminated);
isThisTerminatingError = true;
}
}
bool writeError = !sessionWasAlreadyTerminated;
if (writeError)
{
lock (_jobStateLock)
{
if (_jobWasStopped)
{
writeError = false;
}
}
}
ErrorRecord errorRecord = exception.ErrorRecord;
errorRecord.SetInvocationInfo(this.JobContext.CmdletInvocationInfo);
errorRecord.PreserveInvocationInfoOnce = true;
if (writeError)
{
lock (_jobStateLock)
{
if (!_alreadyReachedCompletedState)
{
if (isThisTerminatingError)
{
this.Error.Add(errorRecord);
CmdletMethodInvoker<bool> methodInvoker = terminatingErrorTracker.GetErrorReportingDelegate(errorRecord);
this.Results.Add(new PSStreamObject(PSStreamObjectType.ShouldMethod, methodInvoker));
}
else
{
this.WriteError(errorRecord);
}
}
}
}
this.SetCompletedJobState(JobState.Failed, errorRecord.Exception);
}
internal override void WriteWarning(string message)
{
message = this.JobContext.PrependComputerNameToMessage(message);
base.WriteWarning(message);
}
internal override void WriteVerbose(string message)
{
message = this.JobContext.PrependComputerNameToMessage(message);
base.WriteVerbose(message);
}
internal override void WriteDebug(string message)
{
message = this.JobContext.PrependComputerNameToMessage(message);
base.WriteDebug(message);
}
internal void SetCompletedJobState(JobState state, Exception reason)
{
lock (_jobStateLock)
{
if (_alreadyReachedCompletedState)
{
return;
}
_alreadyReachedCompletedState = true;
if ((state == JobState.Failed) || (reason != null))
{
_jobHadErrors = true;
}
if (_jobWasStopped)
{
state = JobState.Stopped;
}
else if (_jobHadErrors)
{
state = JobState.Failed;
}
}
this.FinishProgressReporting();
this.SetJobState(state, reason);
this.CloseAllStreams();
_cancellationTokenSource.Cancel();
}
#endregion
#region Support for progress reporting
private readonly ConcurrentDictionary<int, ProgressRecord> _activityIdToLastProgressRecord = new();
internal override void WriteProgress(ProgressRecord progressRecord)
{
progressRecord.Activity = this.JobContext.PrependComputerNameToMessage(progressRecord.Activity);
_activityIdToLastProgressRecord.AddOrUpdate(
progressRecord.ActivityId,
progressRecord,
(activityId, oldProgressRecord) => progressRecord);
base.WriteProgress(progressRecord);
}
internal void FinishProgressReporting()
{
foreach (ProgressRecord lastProgressRecord in _activityIdToLastProgressRecord.Values)
{
if (lastProgressRecord.RecordType != ProgressRecordType.Completed)
{
var newProgressRecord = new ProgressRecord(lastProgressRecord.ActivityId, lastProgressRecord.Activity, lastProgressRecord.StatusDescription);
newProgressRecord.RecordType = ProgressRecordType.Completed;
newProgressRecord.PercentComplete = 100;
newProgressRecord.SecondsRemaining = 0;
this.WriteProgress(newProgressRecord);
}
}
}
#endregion
#region Handling extended semantics callbacks
private void WriteProgressCallback(string activity, string currentOperation, string statusDescription, uint percentageCompleted, uint secondsRemaining)
{
if (string.IsNullOrEmpty(activity))
{
activity = this.GetDescription();
}
if (string.IsNullOrEmpty(statusDescription))
{
statusDescription = this.StatusMessage;
}
int signedSecondsRemaining;
if (secondsRemaining == uint.MaxValue)
{
signedSecondsRemaining = -1;
}
else if (secondsRemaining <= int.MaxValue)
{
signedSecondsRemaining = (int)secondsRemaining;
}
else
{
signedSecondsRemaining = int.MaxValue;
}
int signedPercentageComplete;
if (percentageCompleted == uint.MaxValue)
{
signedPercentageComplete = -1;
}
else if (percentageCompleted <= 100)
{
signedPercentageComplete = (int)percentageCompleted;
}
else
{
signedPercentageComplete = 100;
}
var progressRecord = new ProgressRecord(unchecked((int)(_myJobNumber % int.MaxValue)), activity, statusDescription)
{
CurrentOperation = currentOperation,
PercentComplete = signedPercentageComplete,
SecondsRemaining = signedSecondsRemaining,
RecordType = ProgressRecordType.Processing,
};
this.ExceptionSafeWrapper(
delegate
{
this.WriteProgress(progressRecord);
});
}
private enum MessageChannel
{
Warning = 0,
Verbose = 1,
Debug = 2,
}
private void WriteMessageCallback(uint channel, string message)
{
this.ExceptionSafeWrapper(
delegate
{
switch ((MessageChannel)channel)
{
case MessageChannel.Warning:
this.WriteWarning(message);
break;
case MessageChannel.Verbose:
this.WriteVerbose(message);
break;
case MessageChannel.Debug:
this.WriteDebug(message);
break;
default:
Dbg.Assert(false, "We shouldn't get messages in channels that we didn't register for");
break;
}
});
}
private CimResponseType BlockingWriteError(ErrorRecord errorRecord)
{
Exception exceptionThrownOnCmdletThread = null;
this.ExceptionSafeWrapper(
delegate
{
this.WriteError(errorRecord, out exceptionThrownOnCmdletThread);
});
return (exceptionThrownOnCmdletThread != null)
? CimResponseType.NoToAll
: CimResponseType.Yes;
}
private CimResponseType WriteErrorCallback(CimInstance cimError)
{
lock (_jobStateLock)
{
_jobHadErrors = true;
}
var cimException = new CimException(cimError);
var jobException = CimJobException.CreateFromCimException(this.GetDescription(), this.JobContext, cimException);
var errorRecord = jobException.ErrorRecord;
switch (this.JobContext.ErrorActionPreference)
{
case ActionPreference.Stop:
case ActionPreference.Inquire:
return this.BlockingWriteError(errorRecord);
default:
this.WriteError(errorRecord);
return CimResponseType.Yes;
}
}
private bool _userWasPromptedForContinuationOfProcessing;
private bool _userRespondedYesToAtLeastOneShouldProcess;
internal bool DidUserSuppressTheOperation
{
get
{
bool didUserSuppressTheOperation = _userWasPromptedForContinuationOfProcessing && (!_userRespondedYesToAtLeastOneShouldProcess);
return didUserSuppressTheOperation;
}
}
internal CimResponseType ShouldProcess(string target, string action)
{
string verboseDescription = StringUtil.Format(CommandBaseStrings.ShouldProcessMessage,
action,
target,
null);
return ShouldProcess(verboseDescription, null, null);
}
internal CimResponseType ShouldProcess(
string verboseDescription,
string verboseWarning,
string caption)
{
if (this.JobContext.IsRunningInBackground)
{
return CimResponseType.YesToAll;
}
if (this.JobContext.ShouldProcessOptimization == MshCommandRuntime.ShouldProcessPossibleOptimization.AutoNo_CanCallShouldProcessAsynchronously)
{
this.NonblockingShouldProcess(verboseDescription, verboseWarning, caption);
return CimResponseType.No;
}
if (this.JobContext.ShouldProcessOptimization == MshCommandRuntime.ShouldProcessPossibleOptimization.AutoYes_CanCallShouldProcessAsynchronously)
{
this.NonblockingShouldProcess(verboseDescription, verboseWarning, caption);
return CimResponseType.Yes;
}
Dbg.Assert(
(this.JobContext.ShouldProcessOptimization != MshCommandRuntime.ShouldProcessPossibleOptimization.AutoYes_CanSkipShouldProcessCall) ||
(this.JobContext.CmdletInvocationContext.CmdletDefinitionContext.ClientSideShouldProcess),
"MI layer should not call us when AutoYes_CanSkipShouldProcessCall optimization is in effect");
Exception exceptionThrownOnCmdletThread;
ShouldProcessReason shouldProcessReason;
bool shouldProcessResponse = this.ShouldProcess(verboseDescription, verboseWarning, caption, out shouldProcessReason, out exceptionThrownOnCmdletThread);
if (exceptionThrownOnCmdletThread != null)
{
return CimResponseType.NoToAll;
}
else if (shouldProcessResponse)
{
return CimResponseType.Yes;
}
else
{
return CimResponseType.No;
}
}
private CimResponseType PromptUserCallback(string message, CimPromptType promptType)
{
message = this.JobContext.PrependComputerNameToMessage(message);
Exception exceptionThrownOnCmdletThread = null;
CimResponseType result = CimResponseType.No;
_userWasPromptedForContinuationOfProcessing = true;
switch (promptType)
{
case CimPromptType.Critical:
this.ExceptionSafeWrapper(
delegate
{
if (this.ShouldContinue(message, null, out exceptionThrownOnCmdletThread))
{
result = CimResponseType.Yes;
}
else
{
result = CimResponseType.No;
}
});
break;
case CimPromptType.Normal:
this.ExceptionSafeWrapper(
delegate
{
result = this.ShouldProcess(message, null, null);
});
break;
default:
Dbg.Assert(false, "Unrecognized CimPromptType");
break;
}
if (exceptionThrownOnCmdletThread != null)
{
result = CimResponseType.NoToAll;
}
if ((result == CimResponseType.Yes) || (result == CimResponseType.YesToAll))
{
_userRespondedYesToAtLeastOneShouldProcess = true;
}
return result;
}
#endregion
internal static bool IsShowComputerNameMarkerPresent(CimInstance cimInstance)
{
PSObject pso = PSObject.AsPSObject(cimInstance);
if (!(pso.InstanceMembers[RemotingConstants.ShowComputerNameNoteProperty] is PSPropertyInfo psShowComputerNameProperty))
{
return false;
}
return true.Equals(psShowComputerNameProperty.Value);
}
internal static void AddShowComputerNameMarker(PSObject pso)
{
PSPropertyInfo psShowComputerNameProperty = pso.InstanceMembers[RemotingConstants.ShowComputerNameNoteProperty] as PSPropertyInfo;
if (psShowComputerNameProperty != null)
{
psShowComputerNameProperty.Value = true;
}
else
{
psShowComputerNameProperty = new PSNoteProperty(RemotingConstants.ShowComputerNameNoteProperty, true);
pso.InstanceMembers.Add(psShowComputerNameProperty);
}
}
internal override void WriteObject(object outputObject)
{
CimInstance cimInstance = null;
PSObject pso = null;
if (outputObject is PSObject)
{
pso = PSObject.AsPSObject(outputObject);
cimInstance = pso.BaseObject as CimInstance;
}
else
{
cimInstance = outputObject as CimInstance;
}
if (cimInstance != null)
{
CimCmdletAdapter.AssociateSessionOfOriginWithInstance(cimInstance, this.JobContext.Session);
CimCustomOptionsDictionary.AssociateCimInstanceWithCustomOptions(cimInstance, this.GetJobSpecificCustomOptions());
}
if (this.JobContext.ShowComputerName)
{
if (pso == null)
{
pso = PSObject.AsPSObject(outputObject);
}
AddShowComputerNameMarker(pso);
if (cimInstance == null)
{
pso.Properties.Add(new PSNoteProperty(RemotingConstants.ComputerNameNoteProperty, this.JobContext.Session.ComputerName));
}
}
base.WriteObject(outputObject);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
bool isCompleted;
lock (_jobStateLock)
{
isCompleted = _alreadyReachedCompletedState;
}
if (!isCompleted)
{
this.StopJob();
this.Finished.WaitOne();
}
_cimSensitiveValueConverter.Dispose();
_cancellationTokenSource.Dispose();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Linq;
using System.Text;
using Xunit;
namespace System.Memory.Tests
{
public abstract class ReadOnlySequenceTests
{
public class Array : ReadOnlySequenceTests
{
public Array() : base(ReadOnlySequenceFactory.ArrayFactory) { }
}
public class OwnedMemory : ReadOnlySequenceTests
{
public OwnedMemory() : base(ReadOnlySequenceFactory.OwnedMemoryFactory) { }
}
public class Memory : ReadOnlySequenceTests
{
public Memory() : base(ReadOnlySequenceFactory.MemoryFactory) { }
}
public class SingleSegment : ReadOnlySequenceTests
{
public SingleSegment() : base(ReadOnlySequenceFactory.SingleSegmentFactory) { }
}
public class SegmentPerByte : ReadOnlySequenceTests
{
public SegmentPerByte() : base(ReadOnlySequenceFactory.SegmentPerByteFactory) { }
}
internal ReadOnlySequenceFactory Factory { get; }
internal ReadOnlySequenceTests(ReadOnlySequenceFactory factory)
{
Factory = factory;
}
[Fact]
public void EmptyIsCorrect()
{
ReadOnlySequence<byte> buffer = Factory.CreateOfSize(0);
Assert.Equal(0, buffer.Length);
Assert.True(buffer.IsEmpty);
}
[Theory]
[InlineData(1)]
[InlineData(8)]
public void LengthIsCorrect(int length)
{
ReadOnlySequence<byte> buffer = Factory.CreateOfSize(length);
Assert.Equal(length, buffer.Length);
}
[Theory]
[InlineData(1)]
[InlineData(8)]
public void ToArrayIsCorrect(int length)
{
byte[] data = Enumerable.Range(0, length).Select(i => (byte)i).ToArray();
ReadOnlySequence<byte> buffer = Factory.CreateWithContent(data);
Assert.Equal(length, buffer.Length);
Assert.Equal(data, buffer.ToArray());
}
[Fact]
public void ToStringIsCorrect()
{
ReadOnlySequence<byte> buffer = Factory.CreateWithContent(Enumerable.Range(0, 255).Select(i => (byte)i).ToArray());
Assert.Equal("System.Buffers.ReadOnlySequence<Byte>[255]", buffer.ToString());
}
[Theory]
[MemberData(nameof(ValidSliceCases))]
public void Slice_Works(Func<ReadOnlySequence<byte>, ReadOnlySequence<byte>> func)
{
ReadOnlySequence<byte> buffer = Factory.CreateWithContent(new byte[] { 0, 1, 2 ,3 ,4, 5, 6, 7, 8, 9 });
ReadOnlySequence<byte> slice = func(buffer);
Assert.Equal(new byte[] { 5, 6, 7, 8, 9 }, slice.ToArray());
}
[Theory]
[MemberData(nameof(OutOfRangeSliceCases))]
public void ReadOnlyBufferDoesNotAllowSlicingOutOfRange(Action<ReadOnlySequence<byte>> fail)
{
ReadOnlySequence<byte> buffer = Factory.CreateOfSize(100);
Assert.Throws<ArgumentOutOfRangeException>(() => fail(buffer));
}
[Fact]
public void ReadOnlyBufferGetPosition_MovesPosition()
{
ReadOnlySequence<byte> buffer = Factory.CreateOfSize(100);
SequencePosition position = buffer.GetPosition(buffer.Start, 65);
Assert.Equal(buffer.Slice(position).Length, 35);
}
[Fact]
public void ReadOnlyBufferGetPosition_ChecksBounds()
{
ReadOnlySequence<byte> buffer = Factory.CreateOfSize(100);
Assert.Throws<ArgumentOutOfRangeException>(() => buffer.GetPosition(buffer.Start, 101));
}
[Fact]
public void ReadOnlyBufferGetPosition_DoesNotAlowNegative()
{
ReadOnlySequence<byte> buffer = Factory.CreateOfSize(20);
Assert.Throws<ArgumentOutOfRangeException>(() => buffer.GetPosition(buffer.Start, -1));
}
public void ReadOnlyBufferSlice_ChecksEnd()
{
ReadOnlySequence<byte> buffer = Factory.CreateOfSize(100);
Assert.Throws<ArgumentOutOfRangeException>(() => buffer.Slice(70, buffer.Start));
}
[Fact]
public void SegmentStartIsConsideredInBoundsCheck()
{
// 0 50 100 0 50 100
// [ ##############] -> [############## ]
// ^c1 ^c2
var bufferSegment1 = new BufferSegment(new byte[49]);
BufferSegment bufferSegment2 = bufferSegment1.Append(new byte[50]);
var buffer = new ReadOnlySequence<byte>(bufferSegment1, 0, bufferSegment2, 50);
SequencePosition c1 = buffer.GetPosition(buffer.Start, 25); // segment 1 index 75
SequencePosition c2 = buffer.GetPosition(buffer.Start, 55); // segment 2 index 5
ReadOnlySequence<byte> sliced = buffer.Slice(c1, c2);
Assert.Equal(30, sliced.Length);
}
[Fact]
public void GetPositionPrefersNextSegment()
{
BufferSegment bufferSegment1 = new BufferSegment(new byte[50]);
BufferSegment bufferSegment2 = bufferSegment1.Append(new byte[0]);
ReadOnlySequence<byte> buffer = new ReadOnlySequence<byte>(bufferSegment1, 0, bufferSegment2, 0);
SequencePosition c1 = buffer.GetPosition(buffer.Start, 50);
Assert.Equal(0, c1.GetInteger());
Assert.Equal(bufferSegment2, c1.GetObject());
}
[Fact]
public void GetPositionDoesNotCrossOutsideBuffer()
{
var bufferSegment1 = new BufferSegment(new byte[100]);
BufferSegment bufferSegment2 = bufferSegment1.Append(new byte[100]);
BufferSegment bufferSegment3 = bufferSegment2.Append(new byte[0]);
var buffer = new ReadOnlySequence<byte>(bufferSegment1, 0, bufferSegment2, 100);
SequencePosition c1 = buffer.GetPosition(buffer.Start, 200);
Assert.Equal(100, c1.GetInteger());
Assert.Equal(bufferSegment2, c1.GetObject());
}
[Fact]
public void Create_WorksWithArray()
{
var buffer = new ReadOnlySequence<byte>(new byte[] { 1, 2, 3, 4, 5 });
Assert.Equal(buffer.ToArray(), new byte[] { 1, 2, 3, 4, 5 });
}
[Fact]
public void Empty_ReturnsLengthZeroBuffer()
{
var buffer = ReadOnlySequence<byte>.Empty;
Assert.Equal(0, buffer.Length);
Assert.Equal(true, buffer.IsSingleSegment);
Assert.Equal(0, buffer.First.Length);
}
[Fact]
public void Create_WorksWithArrayWithOffset()
{
var buffer = new ReadOnlySequence<byte>(new byte[] { 1, 2, 3, 4, 5 }, 2, 3);
Assert.Equal(buffer.ToArray(), new byte[] { 3, 4, 5 });
}
[Fact]
public void C_WorksWithArrayWithOffset()
{
var buffer = new ReadOnlySequence<byte>(new byte[] { 1, 2, 3, 4, 5 }, 2, 3);
Assert.Equal(buffer.ToArray(), new byte[] { 3, 4, 5 });
}
[Fact]
public void Create_WorksWithMemory()
{
var memory = new ReadOnlyMemory<byte>(new byte[] { 1, 2, 3, 4, 5 });
var buffer = new ReadOnlySequence<byte>(memory.Slice(2, 3));
Assert.Equal(new byte[] { 3, 4, 5 }, buffer.ToArray());
}
[Fact]
public void SliceToTheEndWorks()
{
ReadOnlySequence<byte> buffer = Factory.CreateOfSize(10);
Assert.True(buffer.Slice(buffer.End).IsEmpty);
}
[Theory]
[InlineData("a", 'a', 0)]
[InlineData("ab", 'a', 0)]
[InlineData("aab", 'a', 0)]
[InlineData("acab", 'a', 0)]
[InlineData("acab", 'c', 1)]
[InlineData("abcdefghijklmnopqrstuvwxyz", 'l', 11)]
[InlineData("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", 'l', 11)]
[InlineData("aaaaaaaaaaacmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", 'm', 12)]
[InlineData("aaaaaaaaaaarmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", 'r', 11)]
[InlineData("/localhost:5000/PATH/%2FPATH2/ HTTP/1.1", '%', 21)]
[InlineData("/localhost:5000/PATH/%2FPATH2/?key=value HTTP/1.1", '%', 21)]
[InlineData("/localhost:5000/PATH/PATH2/?key=value HTTP/1.1", '?', 27)]
[InlineData("/localhost:5000/PATH/PATH2/ HTTP/1.1", ' ', 27)]
public void PositionOf_ReturnsPosition(string raw, char searchFor, int expectIndex)
{
ReadOnlySequence<byte> buffer = Factory.CreateWithContent(raw);
SequencePosition? result = buffer.PositionOf((byte)searchFor);
Assert.NotNull(result);
Assert.Equal(buffer.Slice(result.Value).ToArray(), Encoding.ASCII.GetBytes(raw.Substring(expectIndex)));
}
[Fact]
public void PositionOf_ReturnsNullIfNotFound()
{
ReadOnlySequence<byte> buffer = Factory.CreateWithContent(new byte[] { 1, 2, 3 });
SequencePosition? result = buffer.PositionOf((byte)4);
Assert.Null(result);
}
[Fact]
public void CopyTo_ThrowsWhenSourceLargerThenDestination()
{
ReadOnlySequence<byte> buffer = Factory.CreateOfSize(10);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
Span<byte> span = new byte[5];
buffer.CopyTo(span);
});
}
public static TheoryData<Func<ReadOnlySequence<byte>, ReadOnlySequence<byte>>> ValidSliceCases => new TheoryData<Func<ReadOnlySequence<byte>, ReadOnlySequence<byte>>>
{
b => b.Slice(5),
b => b.Slice(0).Slice(5),
b => b.Slice(5, 5),
b => b.Slice(b.GetPosition(b.Start, 5), 5),
b => b.Slice(5, b.GetPosition(b.Start, 10)),
b => b.Slice(b.GetPosition(b.Start, 5), b.GetPosition(b.Start, 10)),
b => b.Slice((long)5),
b => b.Slice((long)5, 5),
b => b.Slice(b.GetPosition(b.Start, 5), (long)5),
b => b.Slice((long)5, b.GetPosition(b.Start, 10)),
};
public static TheoryData<Action<ReadOnlySequence<byte>>> OutOfRangeSliceCases => new TheoryData<Action<ReadOnlySequence<byte>>>
{
b => b.Slice(101),
b => b.Slice(0, 101),
b => b.Slice(b.Start, 101),
b => b.Slice(0, 70).Slice(b.End, b.End),
b => b.Slice(0, 70).Slice(b.Start, b.End),
b => b.Slice(0, 70).Slice(0, b.End)
};
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace NuGet
{
public static class PathResolver
{
/// <summary>
/// Returns a collection of files from the source that matches the wildcard.
/// </summary>
/// <param name="source">The collection of files to match.</param>
/// <param name="getPath">Function that returns the path to filter a package file </param>
/// <param name="wildcards">The wildcards to apply to match the path with.</param>
/// <returns></returns>
public static IEnumerable<T> GetMatches<T>(IEnumerable<T> source, Func<T, string> getPath, IEnumerable<string> wildcards)
{
var filters = wildcards.Select(WildcardToRegex);
return source.Where(item =>
{
string path = getPath(item);
return filters.Any(f => f.IsMatch(path));
});
}
/// <summary>
/// Removes files from the source that match any wildcard.
/// </summary>
public static void FilterPackageFiles<T>(ICollection<T> source, Func<T, string> getPath, IEnumerable<string> wildcards)
{
var matchedFiles = new HashSet<T>(GetMatches(source, getPath, wildcards));
source.RemoveAll(matchedFiles.Contains);
}
public static string NormalizeWildcard(string basePath, string wildcard)
{
basePath = NormalizeBasePath(basePath, ref wildcard);
return Path.Combine(basePath, wildcard);
}
private static Regex WildcardToRegex(string wildcard)
{
var pattern = Regex.Escape(wildcard);
if (Path.DirectorySeparatorChar == '/')
{
// regex wildcard adjustments for *nix-style file systems
pattern = pattern
.Replace(@"\*\*/", ".*") //For recursive wildcards /**/, include the current directory.
.Replace(@"\*\*", ".*") // For recursive wildcards that don't end in a slash e.g. **.txt would be treated as a .txt file at any depth
.Replace(@"\*", @"[^/]*(/)?") // For non recursive searches, limit it any character that is not a directory separator
.Replace(@"\?", "."); // ? translates to a single any character
}
else
{
// regex wildcard adjustments for Windows-style file systems
pattern = pattern
.Replace(@"\*\*\\", ".*") //For recursive wildcards \**\, include the current directory.
.Replace(@"\*\*", ".*") // For recursive wildcards that don't end in a slash e.g. **.txt would be treated as a .txt file at any depth
.Replace(@"\*", @"[^\\]*(\\)?") // For non recursive searches, limit it any character that is not a directory separator
.Replace(@"\?", "."); // ? translates to a single any character
}
return new Regex('^' + pattern + '$', RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
}
internal static IEnumerable<PhysicalPackageFile> ResolveSearchPattern(string basePath, string searchPath, string targetPath, bool includeEmptyDirectories)
{
string normalizedBasePath;
IEnumerable<SearchPathResult> searchResults = PerformWildcardSearchInternal(basePath, searchPath, includeEmptyDirectories, out normalizedBasePath);
return searchResults.Select(result =>
result.IsFile
? new PhysicalPackageFile
{
SourcePath = result.Path,
TargetPath = ResolvePackagePath(normalizedBasePath, searchPath, result.Path, targetPath)
}
: new EmptyFrameworkFolderFile(ResolvePackagePath(normalizedBasePath, searchPath, result.Path, targetPath))
{
SourcePath = result.Path
}
);
}
public static IEnumerable<string> PerformWildcardSearch(string basePath, string searchPath)
{
string normalizedBasePath;
var searchResults = PerformWildcardSearchInternal(basePath, searchPath, includeEmptyDirectories: false, normalizedBasePath: out normalizedBasePath);
return searchResults.Select(s => s.Path);
}
private static IEnumerable<SearchPathResult> PerformWildcardSearchInternal(string basePath, string searchPath, bool includeEmptyDirectories, out string normalizedBasePath)
{
if (!searchPath.StartsWith(@"\\", StringComparison.OrdinalIgnoreCase))
{
// If we aren't dealing with network paths, trim the leading slash.
searchPath = searchPath.TrimStart(Path.DirectorySeparatorChar);
}
bool searchDirectory = false;
// If the searchPath ends with \ or /, we treat searchPath as a directory,
// and will include everything under it, recursively
if (IsDirectoryPath(searchPath))
{
searchPath = searchPath + "**" + Path.DirectorySeparatorChar + "*";
searchDirectory = true;
}
basePath = NormalizeBasePath(basePath, ref searchPath);
normalizedBasePath = GetPathToEnumerateFrom(basePath, searchPath);
// Append the basePath to searchPattern and get the search regex. We need to do this because the search regex is matched from line start.
Regex searchRegex = WildcardToRegex(Path.Combine(basePath, searchPath));
// This is a hack to prevent enumerating over the entire directory tree if the only wildcard characters are the ones in the file name.
// If the path portion of the search path does not contain any wildcard characters only iterate over the TopDirectory.
SearchOption searchOption = SearchOption.AllDirectories;
// (a) Path is not recursive search
bool isRecursiveSearch = searchPath.IndexOf("**", StringComparison.OrdinalIgnoreCase) != -1;
// (b) Path does not have any wildcards.
bool isWildcardPath = Path.GetDirectoryName(searchPath).Contains('*');
if (!isRecursiveSearch && !isWildcardPath)
{
searchOption = SearchOption.TopDirectoryOnly;
}
// Starting from the base path, enumerate over all files and match it using the wildcard expression provided by the user.
// Note: We use Directory.GetFiles() instead of Directory.EnumerateFiles() here to support Mono
var matchedFiles = from file in Directory.GetFiles(normalizedBasePath, "*.*", searchOption)
where searchRegex.IsMatch(file)
select new SearchPathResult(file, isFile: true);
if (!includeEmptyDirectories)
{
return matchedFiles;
}
// retrieve empty directories
// Note: We use Directory.GetDirectories() instead of Directory.EnumerateDirectories() here to support Mono
var matchedDirectories = from directory in Directory.GetDirectories(normalizedBasePath, "*.*", searchOption)
where searchRegex.IsMatch(directory) && IsEmptyDirectory(directory)
select new SearchPathResult(directory, isFile: false);
if (searchDirectory && IsEmptyDirectory(normalizedBasePath))
{
matchedDirectories = matchedDirectories.Concat(new [] { new SearchPathResult(normalizedBasePath, isFile: false) });
}
return matchedFiles.Concat(matchedDirectories);
}
internal static string GetPathToEnumerateFrom(string basePath, string searchPath)
{
string basePathToEnumerate;
int wildcardIndex = searchPath.IndexOf('*');
if (wildcardIndex == -1)
{
// For paths without wildcard, we could either have base relative paths (such as lib\foo.dll) or paths outside the base path
// (such as basePath: C:\packages and searchPath: D:\packages\foo.dll)
// In this case, Path.Combine would pick up the right root to enumerate from.
var searchRoot = Path.GetDirectoryName(searchPath);
basePathToEnumerate = Path.Combine(basePath, searchRoot);
}
else
{
// If not, find the first directory separator and use the path to the left of it as the base path to enumerate from.
int directorySeparatoryIndex = searchPath.LastIndexOf(Path.DirectorySeparatorChar, wildcardIndex);
if (directorySeparatoryIndex == -1)
{
// We're looking at a path like "NuGet*.dll", NuGet*\bin\release\*.dll
// In this case, the basePath would continue to be the path to begin enumeration from.
basePathToEnumerate = basePath;
}
else
{
string nonWildcardPortion = searchPath.Substring(0, directorySeparatoryIndex);
basePathToEnumerate = Path.Combine(basePath, nonWildcardPortion);
}
}
return basePathToEnumerate;
}
/// <summary>
/// Determins the path of the file inside a package.
/// For recursive wildcard paths, we preserve the path portion beginning with the wildcard.
/// For non-recursive wildcard paths, we use the file name from the actual file path on disk.
/// </summary>
internal static string ResolvePackagePath(string searchDirectory, string searchPattern, string fullPath, string targetPath)
{
string packagePath;
bool isDirectorySearch = IsDirectoryPath(searchPattern);
bool isWildcardSearch = IsWildcardSearch(searchPattern);
bool isRecursiveWildcardSearch = isWildcardSearch && searchPattern.IndexOf("**", StringComparison.OrdinalIgnoreCase) != -1;
if ((isRecursiveWildcardSearch || isDirectorySearch) && fullPath.StartsWith(searchDirectory, StringComparison.OrdinalIgnoreCase))
{
// The search pattern is recursive. Preserve the non-wildcard portion of the path.
// e.g. Search: X:\foo\**\*.cs results in SearchDirectory: X:\foo and a file path of X:\foo\bar\biz\boz.cs
// Truncating X:\foo\ would result in the package path.
packagePath = fullPath.Substring(searchDirectory.Length).TrimStart(Path.DirectorySeparatorChar);
}
else if (!isWildcardSearch && Path.GetExtension(searchPattern).Equals(Path.GetExtension(targetPath), StringComparison.OrdinalIgnoreCase))
{
// If the search does not contain wild cards, and the target path shares the same extension, copy it
// e.g. <file src="ie\css\style.css" target="Content\css\ie.css" /> --> Content\css\ie.css
return targetPath;
}
else
{
packagePath = Path.GetFileName(fullPath);
}
return Path.Combine(targetPath ?? String.Empty, packagePath);
}
internal static string NormalizeBasePath(string basePath, ref string searchPath)
{
const string relativePath = @"..\";
// If no base path is provided, use the current directory.
basePath = String.IsNullOrEmpty(basePath) ? @".\" : basePath;
// If the search path is relative, transfer the ..\ portion to the base path.
// This needs to be done because the base path determines the root for our enumeration.
while (searchPath.StartsWith(relativePath, StringComparison.OrdinalIgnoreCase))
{
basePath = Path.Combine(basePath, relativePath);
searchPath = searchPath.Substring(relativePath.Length);
}
return Path.GetFullPath(basePath);
}
/// <summary>
/// Returns true if the path contains any wildcard characters.
/// </summary>
internal static bool IsWildcardSearch(string filter)
{
return filter.IndexOf('*') != -1;
}
internal static bool IsDirectoryPath(string path)
{
return path != null && path.Length > 1 && path[path.Length - 1] == Path.DirectorySeparatorChar;
}
private static bool IsEmptyDirectory(string directory)
{
return !Directory.EnumerateFileSystemEntries(directory).Any();
}
private struct SearchPathResult
{
private readonly string _path;
private readonly bool _isFile;
public string Path
{
get
{
return _path;
}
}
public bool IsFile
{
get
{
return _isFile;
}
}
public SearchPathResult(string path, bool isFile)
{
_path = path;
_isFile = isFile;
}
}
}
}
| |
//-----------------------------------------------------------------------------
// 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.
//-----------------------------------------------------------------------------
/*
================================================================================
The DOFPostEffect API
================================================================================
DOFPostEffect::setFocalDist( %dist )
@summary
This method is for manually controlling the focus distance. It will have no
effect if auto focus is currently enabled. Makes use of the parameters set by
setFocusParams.
@param dist
float distance in meters
--------------------------------------------------------------------------------
DOFPostEffect::setAutoFocus( %enabled )
@summary
This method sets auto focus enabled or disabled. Makes use of the parameters set
by setFocusParams. When auto focus is enabled it determines the focal depth
by performing a raycast at the screen-center.
@param enabled
bool
--------------------------------------------------------------------------------
DOFPostEffect::setFocusParams( %nearBlurMax, %farBlurMax, %minRange, %maxRange, %nearSlope, %farSlope )
Set the parameters that control how the near and far equations are calculated
from the focal distance. If you are not using auto focus you will need to call
setFocusParams PRIOR to calling setFocalDist.
@param nearBlurMax
float between 0.0 and 1.0
The max allowed value of near blur.
@param farBlurMax
float between 0.0 and 1.0
The max allowed value of far blur.
@param minRange/maxRange
float in meters
The distance range around the focal distance that remains in focus is a lerp
between the min/maxRange using the normalized focal distance as the parameter.
The point is to allow the focal range to expand as you focus farther away since this is
visually appealing.
Note: since min/maxRange are lerped by the "normalized" focal distance it is
dependant on the visible distance set in your level.
@param nearSlope
float less than zero
The slope of the near equation. A small number causes bluriness to increase gradually
at distances closer than the focal distance. A large number causes bluriness to
increase quickly.
@param farSlope
float greater than zero
The slope of the far equation. A small number causes bluriness to increase gradually
at distances farther than the focal distance. A large number causes bluriness to
increase quickly.
Note: To rephrase, the min/maxRange parameters control how much area around the
focal distance is completely in focus where the near/farSlope parameters control
how quickly or slowly bluriness increases at distances outside of that range.
================================================================================
Examples
================================================================================
Example1: Turn on DOF while zoomed in with a weapon.
NOTE: These are not real callbacks! Hook these up to your code where appropriate!
function onSniperZoom()
{
// Parameterize how you want DOF to look.
DOFPostEffect.setFocusParams( 0.3, 0.3, 50, 500, -5, 5 );
// Turn on auto focus
DOFPostEffect.setAutoFocus( true );
// Turn on the PostEffect
DOFPostEffect.enable();
}
function onSniperUnzoom()
{
// Turn off the PostEffect
DOFPostEffect.disable();
}
Example2: Manually control DOF with the mouse wheel.
// Somewhere on startup...
// Parameterize how you want DOF to look.
DOFPostEffect.setFocusParams( 0.3, 0.3, 50, 500, -5, 5 );
// Turn off auto focus
DOFPostEffect.setAutoFocus( false );
// Turn on the PostEffect
DOFPostEffect.enable();
NOTE: These are not real callbacks! Hook these up to your code where appropriate!
function onMouseWheelUp()
{
// Since setFocalDist is really just a wrapper to assign to the focalDist
// dynamic field we can shortcut and increment it directly.
DOFPostEffect.focalDist += 8;
}
function onMouseWheelDown()
{
DOFPostEffect.focalDist -= 8;
}
*/
/// This method is for manually controlling the focal distance. It will have no
/// effect if auto focus is currently enabled. Makes use of the parameters set by
/// setFocusParams.
function DOFPostEffect::setFocalDist( %this, %dist )
{
%this.focalDist = %dist;
}
/// This method sets auto focus enabled or disabled. Makes use of the parameters set
/// by setFocusParams. When auto focus is enabled it determine the focal depth
/// by performing a raycast at the screen-center.
function DOFPostEffect::setAutoFocus( %this, %enabled )
{
%this.autoFocusEnabled = %enabled;
}
/// Set the parameters that control how the near and far equations are calculated
/// from the focal distance. If you are not using auto focus you will need to call
/// setFocusParams PRIOR to calling setFocalDist.
function DOFPostEffect::setFocusParams( %this, %nearBlurMax, %farBlurMax, %minRange, %maxRange, %nearSlope, %farSlope )
{
%this.nearBlurMax = %nearBlurMax;
%this.farBlurMax = %farBlurMax;
%this.minRange = %minRange;
%this.maxRange = %maxRange;
%this.nearSlope = %nearSlope;
%this.farSlope = %farSlope;
}
/*
More information...
This DOF technique is based on this paper:
http://http.developer.nvidia.com/GPUGems3/gpugems3_ch28.html
================================================================================
1. Overview of how we represent "Depth of Field"
================================================================================
DOF is expressed as an amount of bluriness per pixel according to its depth.
We represented this by a piecewise linear curve depicted below.
Note: we also refer to "bluriness" as CoC ( circle of confusion ) which is the term
used in the basis paper and in photography.
X-axis (depth)
x = 0.0----------------------------------------------x = 1.0
Y-axis (bluriness)
y = 1.0
|
| ____(x1,y1) (x4,y4)____
| (ns,nb)\ <--Line1 line2---> /(fe,fb)
| \ /
| \(x2,y2) (x3,y3)/
| (ne,0)------(fs,0)
y = 0.0
I have labeled the "corners" of this graph with (Xn,Yn) to illustrate that
this is in fact a collection of line segments where the x/y of each point
corresponds to the key below.
key:
ns - (n)ear blur (s)tart distance
nb - (n)ear (b)lur amount (max value)
ne - (n)ear blur (e)nd distance
fs - (f)ar blur (s)tart distance
fe - (f)ar blur (e)nd distance
fb - (f)ar (b)lur amount (max value)
Of greatest importance in this graph is Line1 and Line2. Where...
L1 { (x1,y1), (x2,y2) }
L2 { (x3,y3), (x4,y4) }
Line one represents the amount of "near" blur given a pixels depth and line two
represents the amount of "far" blur at that depth.
Both these equations are evaluated for each pixel and then the larger of the two
is kept. Also the output blur (for each equation) is clamped between 0 and its
maximum allowable value.
Therefore, to specify a DOF "qualify" you need to specify the near-blur-line,
far-blur-line, and maximum near and far blur value.
================================================================================
2. Abstracting a "focal depth"
================================================================================
Although the shader(s) work in terms of a near and far equation it is more
useful to express DOF as an adjustable focal depth and derive the other parameters
"under the hood".
Given a maximum near/far blur amount and a near/far slope we can calculate the
near/far equations for any focal depth. We extend this to also support a range
of depth around the focal depth that is also in focus and for that range to
shrink or grow as the focal depth moves closer or farther.
Keep in mind this is only one implementation and depending on the effect you
desire you may which to express the relationship between focal depth and
the shader paramaters different.
*/
//-----------------------------------------------------------------------------
// GFXStateBlockData / ShaderData
//-----------------------------------------------------------------------------
singleton GFXStateBlockData( PFX_DefaultDOFStateBlock )
{
zDefined = true;
zEnable = false;
zWriteEnable = false;
samplersDefined = true;
samplerStates[0] = SamplerClampPoint;
samplerStates[1] = SamplerClampPoint;
};
singleton GFXStateBlockData( PFX_DOFCalcCoCStateBlock )
{
zDefined = true;
zEnable = false;
zWriteEnable = false;
samplersDefined = true;
samplerStates[0] = SamplerClampLinear;
samplerStates[1] = SamplerClampLinear;
};
singleton GFXStateBlockData( PFX_DOFDownSampleStateBlock )
{
zDefined = true;
zEnable = false;
zWriteEnable = false;
samplersDefined = true;
samplerStates[0] = SamplerClampLinear;
samplerStates[1] = SamplerClampPoint;
};
singleton GFXStateBlockData( PFX_DOFBlurStateBlock )
{
zDefined = true;
zEnable = false;
zWriteEnable = false;
samplersDefined = true;
samplerStates[0] = SamplerClampLinear;
};
singleton GFXStateBlockData( PFX_DOFFinalStateBlock )
{
zDefined = true;
zEnable = false;
zWriteEnable = false;
samplersDefined = true;
samplerStates[0] = SamplerClampLinear;
samplerStates[1] = SamplerClampLinear;
samplerStates[2] = SamplerClampLinear;
samplerStates[3] = SamplerClampPoint;
blendDefined = true;
blendEnable = true;
blendDest = GFXBlendInvSrcAlpha;
blendSrc = GFXBlendOne;
};
singleton ShaderData( PFX_DOFDownSampleShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/postFX/dof/DOF_DownSample_V.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/postFX/dof/DOF_DownSample_P.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/postFX/dof/gl/DOF_DownSample_V.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/postFX/dof/gl/DOF_DownSample_P.glsl";
samplerNames[0] = "$colorSampler";
samplerNames[1] = "$depthSampler";
pixVersion = 3.0;
};
singleton ShaderData( PFX_DOFBlurYShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/postFX/dof/DOF_Gausian_V.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/postFX/dof/DOF_Gausian_P.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/postFX/dof/gl/DOF_Gausian_V.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/postFX/dof/gl/DOF_Gausian_P.glsl";
samplerNames[0] = "$diffuseMap";
pixVersion = 2.0;
defines = "BLUR_DIR=float2(0.0,1.0)";
};
singleton ShaderData( PFX_DOFBlurXShader : PFX_DOFBlurYShader )
{
defines = "BLUR_DIR=float2(1.0,0.0)";
};
singleton ShaderData( PFX_DOFCalcCoCShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/postFX/dof/DOF_CalcCoC_V.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/postFX/dof/DOF_CalcCoC_P.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/postFX/dof/gl/DOF_CalcCoC_V.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/postFX/dof/gl/DOF_CalcCoC_P.glsl";
samplerNames[0] = "$shrunkSampler";
samplerNames[1] = "$blurredSampler";
pixVersion = 3.0;
};
singleton ShaderData( PFX_DOFSmallBlurShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/postFX/dof/DOF_SmallBlur_V.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/postFX/dof/DOF_SmallBlur_P.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/postFX/dof/gl/DOF_SmallBlur_V.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/postFX/dof/gl/DOF_SmallBlur_P.glsl";
samplerNames[0] = "$colorSampler";
pixVersion = 3.0;
};
singleton ShaderData( PFX_DOFFinalShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/postFX/dof/DOF_Final_V.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/postFX/dof/DOF_Final_P.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/postFX/dof/gl/DOF_Final_V.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/postFX/dof/gl/DOF_Final_P.glsl";
samplerNames[0] = "$colorSampler";
samplerNames[1] = "$smallBlurSampler";
samplerNames[2] = "$largeBlurSampler";
samplerNames[3] = "$depthSampler";
pixVersion = 3.0;
};
//-----------------------------------------------------------------------------
// PostEffects
//-----------------------------------------------------------------------------
function DOFPostEffect::onAdd( %this )
{
// The weighted distribution of CoC value to the three blur textures
// in the order small, medium, large. Most likely you will not need to
// change this value.
%this.setLerpDist( 0.2, 0.3, 0.5 );
// Fill out some default values but DOF really should not be turned on
// without actually specifying your own parameters!
%this.autoFocusEnabled = false;
%this.focalDist = 0.0;
%this.nearBlurMax = 0.5;
%this.farBlurMax = 0.5;
%this.minRange = 50;
%this.maxRange = 500;
%this.nearSlope = -5.0;
%this.farSlope = 5.0;
}
function DOFPostEffect::setLerpDist( %this, %d0, %d1, %d2 )
{
%this.lerpScale = -1.0 / %d0 SPC -1.0 / %d1 SPC -1.0 / %d2 SPC 1.0 / %d2;
%this.lerpBias = 1.0 SPC ( 1.0 - %d2 ) / %d1 SPC 1.0 / %d2 SPC ( %d2 - 1.0 ) / %d2;
}
singleton PostEffect( DOFPostEffect )
{
renderTime = "PFXAfterBin";
renderBin = "GlowBin";
renderPriority = 0.1;
shader = PFX_DOFDownSampleShader;
stateBlock = PFX_DOFDownSampleStateBlock;
texture[0] = "$backBuffer";
texture[1] = "#prepass";
target = "#shrunk";
targetScale = "0.25 0.25";
isEnabled = false;
};
singleton PostEffect( DOFBlurY )
{
shader = PFX_DOFBlurYShader;
stateBlock = PFX_DOFBlurStateBlock;
texture[0] = "#shrunk";
target = "$outTex";
};
DOFPostEffect.add( DOFBlurY );
singleton PostEffect( DOFBlurX )
{
shader = PFX_DOFBlurXShader;
stateBlock = PFX_DOFBlurStateBlock;
texture[0] = "$inTex";
target = "#largeBlur";
};
DOFPostEffect.add( DOFBlurX );
singleton PostEffect( DOFCalcCoC )
{
shader = PFX_DOFCalcCoCShader;
stateBlock = PFX_DOFCalcCoCStateBlock;
texture[0] = "#shrunk";
texture[1] = "#largeBlur";
target = "$outTex";
};
DOFPostEffect.add( DOFCalcCoc );
singleton PostEffect( DOFSmallBlur )
{
shader = PFX_DOFSmallBlurShader;
stateBlock = PFX_DefaultDOFStateBlock;
texture[0] = "$inTex";
target = "$outTex";
};
DOFPostEffect.add( DOFSmallBlur );
singleton PostEffect( DOFFinalPFX )
{
shader = PFX_DOFFinalShader;
stateBlock = PFX_DOFFinalStateBlock;
texture[0] = "$backBuffer";
texture[1] = "$inTex";
texture[2] = "#largeBlur";
texture[3] = "#prepass";
target = "$backBuffer";
};
DOFPostEffect.add( DOFFinalPFX );
//-----------------------------------------------------------------------------
// Scripts
//-----------------------------------------------------------------------------
function DOFPostEffect::setShaderConsts( %this )
{
if ( %this.autoFocusEnabled )
%this.autoFocus();
%fd = %this.focalDist / $Param::FarDist;
%range = mLerp( %this.minRange, %this.maxRange, %fd ) / $Param::FarDist * 0.5;
// We work in "depth" space rather than real-world units for the
// rest of this method...
// Given the focal distance and the range around it we want in focus
// we can determine the near-end-distance and far-start-distance
%ned = getMax( %fd - %range, 0.0 );
%fsd = getMin( %fd + %range, 1.0 );
// near slope
%nsl = %this.nearSlope;
// Given slope of near blur equation and the near end dist and amount (x2,y2)
// solve for the y-intercept
// y = mx + b
// so...
// y - mx = b
%b = 0.0 - %nsl * %ned;
%eqNear = %nsl SPC %b SPC 0.0;
// Do the same for the far blur equation...
%fsl = %this.farSlope;
%b = 0.0 - %fsl * %fsd;
%eqFar = %fsl SPC %b SPC 1.0;
%this.setShaderConst( "$dofEqWorld", %eqNear );
DOFFinalPFX.setShaderConst( "$dofEqFar", %eqFar );
%this.setShaderConst( "$maxWorldCoC", %this.nearBlurMax );
DOFFinalPFX.setShaderConst( "$maxFarCoC", %this.farBlurMax );
DOFFinalPFX.setShaderConst( "$dofLerpScale", %this.lerpScale );
DOFFinalPFX.setShaderConst( "$dofLerpBias", %this.lerpBias );
}
function DOFPostEffect::autoFocus( %this )
{
if ( !isObject( ServerConnection ) ||
!isObject( ServerConnection.getCameraObject() ) )
{
return;
}
%mask = $TypeMasks::StaticObjectType | $TypeMasks::TerrainObjectType;
%control = ServerConnection.getCameraObject();
%fvec = %control.getEyeVector();
%start = %control.getEyePoint();
%end = VectorAdd( %start, VectorScale( %fvec, $Param::FarDist ) );
// Use the client container for this ray cast.
%result = containerRayCast( %start, %end, %mask, %control, true );
%hitPos = getWords( %result, 1, 3 );
if ( %hitPos $= "" )
%focDist = $Param::FarDist;
else
%focDist = VectorDist( %hitPos, %start );
// For debuging
//$DOF::debug_dist = %focDist;
//$DOF::debug_depth = %focDist / $Param::FarDist;
//echo( "F: " @ %focDist SPC "D: " @ %delta );
%this.focalDist = %focDist;
}
// For debugging
/*
function reloadDOF()
{
exec( "./dof.cs" );
DOFPostEffect.reload();
DOFPostEffect.disable();
DOFPostEffect.enable();
}
function dofMetricsCallback()
{
return " | DOF |" @
" Dist: " @ $DOF::debug_dist @
" Depth: " @ $DOF::debug_depth;
}
*/
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Windows;
using Lighthouse.Common.Interoperability;
using Lighthouse.Silverlight.Core.Controls;
using Microsoft.Silverlight.Testing;
using Microsoft.Silverlight.Testing.Client;
using Microsoft.Silverlight.Testing.Harness;
using Microsoft.Silverlight.Testing.Service;
using Microsoft.Silverlight.Testing.UnitTesting.Metadata;
namespace Lighthouse.Silverlight.Core.SilverlightUnitTestingCustomizations
{
public class MyUnitTestSystem
{
/// <summary>
/// Friendly unit test system name.
/// </summary>
private const string UnitTestSystemName = "Silverlight Unit Test Framework";
/// <summary>
/// Gets the test system name built into the assembly.
/// </summary>
public static string SystemName { get { return UnitTestSystemName; } }
/// <summary>
/// Gets a string representing the file version attribute of the main
/// unit test framework assembly, if present.
/// </summary>
public static string FrameworkFileVersion
{
get
{
Assembly utf = typeof(UnitTestSystem).Assembly;
return utf.ImageRuntimeVersion;
}
}
/// <summary>
/// Register another available unit test provider for the unit test system.
/// </summary>
/// <param name="provider">A unit test provider.</param>
public static void RegisterUnitTestProvider(IUnitTestProvider provider)
{
if (!UnitTestProviders.Providers.Contains(provider))
{
UnitTestProviders.Providers.Add(provider);
}
}
/// <summary>
/// Test harness instance.
/// </summary>
private UnitTestHarness _harness;
/// <summary>
/// Start a new unit test run.
/// </summary>
/// <param name="settings">Unit test settings object.</param>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "This makes the purpose clear to test developers")]
public void Run(UnitTestSettings settings)
{
// Avoid having the Run method called twice
if (_harness != null)
{
return;
}
_harness = settings.TestHarness;
if (_harness == null)
{
throw new InvalidOperationException("NoTestHarnessInSettings");
}
// Conside re-setting the test service only in our default case
if (settings.TestService is SilverlightTestService)
{
SetTestService(settings);
}
_harness.Settings = settings;
_harness.TestHarnessCompleted += (sender, args) => OnTestHarnessCompleted(args);
if (settings.StartRunImmediately)
{
_harness.Run();
}
}
/// <summary>
/// Prepares the default log manager.
/// </summary>
/// <param name="settings">The test harness settings.</param>
public static void SetStandardLogProviders(UnitTestSettings settings)
{
// Debug provider
DebugOutputProvider debugger = new DebugOutputProvider();
debugger.ShowAllFailures = true;
settings.LogProviders.Add(debugger);
// Visual Studio log provider
try
{
TryAddVisualStudioLogProvider(settings);
}
catch
{
}
PrepareCustomLogProviders(settings);
}
/// <summary>
/// Tries to instantiate and initialize a VSTT provider. Requires that
/// XLinq is available and included in the application package.
/// </summary>
/// <param name="settings">The test harness settings object.</param>
private static void TryAddVisualStudioLogProvider(UnitTestSettings settings)
{
VisualStudioLogProvider trx = new VisualStudioLogProvider();
settings.LogProviders.Add(trx);
}
/// <summary>
/// Creates the default settings that would be used by the UnitTestHarness
/// if none were specified.
/// </summary>
/// <returns>A new RootVisual.</returns>
/// <remarks>Assumes the calling assembly is a test assembly.</remarks>
public static UnitTestSettings CreateDefaultSettings()
{
/* foreach (var assemblyPart in Deployment.Current.Parts)
{
var sri = Application.GetResourceStream(new Uri(assemblyPart.Source, UriKind.Relative));
try
{
var assembly = new AssemblyPart().Load(sri.Stream);
assemblies.Add(assembly);
}
catch (Exception e)
{
Debug.WriteLine(string.Format("Skipping Assembly: {0}. Error: {1}.", assemblyPart.Source, e.Message));
}
}*/
return CreateDefaultSettings(Assembly.GetCallingAssembly());
}
public static UnitTestSettings CreateDefaultSettings(SilverlightUnitTestRunSettings silverlightUnitTestRunSettings)
{
var settings = new UnitTestSettings();
settings.ShowTagExpressionEditor = false;
settings.SampleTags = new List<string>();
settings.TagExpression = null;
if (silverlightUnitTestRunSettings != null)
{
if (silverlightUnitTestRunSettings.AssembliesThatContainTests.Any())
{
foreach (var assemblyPartDllName in silverlightUnitTestRunSettings.AssembliesThatContainTests)
{
var partDllNameCopy = assemblyPartDllName;
var foundAssemblyPart = Deployment.Current.Parts.FirstOrDefault(p => p.Source == partDllNameCopy);
if (foundAssemblyPart != null)
{
var sri = Application.GetResourceStream(new Uri(foundAssemblyPart.Source, UriKind.Relative));
var assembly = new AssemblyPart().Load(sri.Stream);
settings.TestAssemblies.Add(assembly);
}
}
}
if (!string.IsNullOrWhiteSpace(silverlightUnitTestRunSettings.TagFilter))
{
settings.TagExpression = silverlightUnitTestRunSettings.TagFilter;
}
}
SetStandardLogProviders(settings);
settings.TestHarness = new LighthouseUnitTestHarness();
settings.TestHarness.Settings = settings;
// Sets initial but user can override
SetTestService(settings);
return settings;
}
/// <summary>
/// A completed test harness handler.
/// </summary>
public event EventHandler<TestHarnessCompletedEventArgs> TestHarnessCompleted;
/// <summary>
/// Call the TestHarnessCompleted event.
/// </summary>
/// <param name="args">The test harness completed event arguments.</param>
private void OnTestHarnessCompleted(TestHarnessCompletedEventArgs args)
{
var handler = TestHarnessCompleted;
if (handler != null)
{
handler(this, args);
}
}
/// <summary>
/// Create a default settings object for unit testing.
/// </summary>
/// <param name="callingAssembly">The assembly reflection object.</param>
/// <returns>A unit test settings instance.</returns>
private static UnitTestSettings CreateDefaultSettings(Assembly callingAssembly)
{
return CreateDefaultSettings(new List<Assembly> { callingAssembly });
}
private static UnitTestSettings CreateDefaultSettings(IEnumerable<Assembly> callingAssemblies)
{
var settings = new UnitTestSettings();
settings.ShowTagExpressionEditor = false;
settings.SampleTags = new List<string>();
settings.TagExpression = null;
if (callingAssemblies != null)
{
foreach (var callingAssembly in callingAssemblies)
{
if (!settings.TestAssemblies.Contains(callingAssembly))
{
settings.TestAssemblies.Add(callingAssembly);
}
}
}
SetStandardLogProviders(settings);
settings.TestHarness = new LighthouseUnitTestHarness();
settings.TestHarness.Settings = settings;
// Sets initial but user can override
SetTestService(settings);
return settings;
}
public static void PrepareCustomLogProviders(UnitTestSettings settings)
{
// TODO: Consider what to do on this one...
// Should probably update to use the newer log system with events,
// and then after that figure out when it applies... perhaps only
// when someone first requests to use it.
////if (HtmlPage.IsEnabled)
////{
////settings.LogProviders.Add(new TextFailuresLogProvider());
////}
}
public static void SetTestService(UnitTestSettings settings)
{
settings.TestService = new SilverlightTestService(settings);
}
/// <summary>
/// Creates a new TestPage visual that in turn will setup and begin a
/// unit test run.
/// </summary>
/// <returns>A new RootVisual.</returns>
/// <remarks>Assumes the calling assembly is a test assembly.</remarks>
public static UIElement CreateTestPage()
{
UnitTestSettings settings = CreateDefaultSettings(Assembly.GetCallingAssembly());
return CreateTestPage(settings);
}
/// <summary>
/// Creates a new TestPage visual that in turn will setup and begin a
/// unit test run.
/// </summary>
/// <param name="settings">Test harness settings to be applied.</param>
/// <returns>A new RootVisual.</returns>
/// <remarks>Assumes the calling assembly is a test assembly.</remarks>
public static UIElement CreateTestPage(UnitTestSettings settings)
{
var system = new MyUnitTestSystem();
Type testPageType = Environment.OSVersion.Platform == PlatformID.WinCE ? typeof(MobileTestPage) : typeof(LighthouseUnitTestRunnerPage);
Type testPageInterface = typeof(ITestPage);
if (settings.TestPanelType != null && testPageInterface.IsAssignableFrom(settings.TestPanelType))
{
testPageType = settings.TestPanelType;
}
object testPage;
try
{
// Try creating with an instance of the test harness
testPage = Activator.CreateInstance(testPageType, settings.TestHarness);
}
catch (Exception e)
{
// Fall back to a standard instance only
testPage = Activator.CreateInstance(testPageType);
}
PrepareTestService(settings, () => system.Run(settings));
// NOTE: A silent failure would be if the testPanel is not a
// UIElement, and it returns anyway.
return testPage as UIElement;
}
private static void MergeSettingsAndParameters(TestServiceProvider testService, UnitTestSettings inputSettings)
{
if (testService != null && testService.HasService(TestServiceFeature.RunSettings))
{
SettingsProvider settings = testService.GetService<SettingsProvider>(TestServiceFeature.RunSettings);
foreach (string key in settings.Settings.Keys)
{
if (inputSettings.Parameters.ContainsKey(key))
{
Debug.WriteLine("MergeSettingsAndParameters: Overwriting " + key + " key during merge.");
}
inputSettings.Parameters[key] = settings.Settings[key];
}
}
}
private static void PrepareTestService(UnitTestSettings inputSettings, Action complete)
{
TestServiceProvider testService = inputSettings.TestService;
if (testService != null && testService.Initialized == false)
{
Action after = delegate
{
MergeSettingsAndParameters(testService, inputSettings);
complete();
};
testService.InitializeCompleted += delegate(object sender, EventArgs e) { after(); };
testService.Initialize();
}
else
{
complete();
}
}
}
}
| |
// Copyright 2015, 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.
// Author: Chris Seeley
using Google.Api.Ads.Common.Lib;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Google.Api.Ads.Dfp.Lib {
/// <summary>
/// Lists all the services available through this library.
/// </summary>
public partial class DfpService : AdsService {
/// <summary>
/// All the services available in v201405.
/// </summary>
public class v201405 {
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/ActivityGroupService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ActivityGroupService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/ActivityService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ActivityService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/AdRuleService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature AdRuleService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/BaseRateService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature BaseRateService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/ContactService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ContactService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/AudienceSegmentService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature AudienceSegmentService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/CompanyService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature CompanyService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/ContentService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ContentService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/ContentMetadataKeyHierarchyService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ContentMetadataKeyHierarchyService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/CreativeService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature CreativeService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/CreativeSetService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature CreativeSetService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/CreativeTemplateService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature CreativeTemplateService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/CreativeWrapperService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature CreativeWrapperService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/CustomFieldService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature CustomFieldService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/CustomTargetingService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature CustomTargetingService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/ExchangeRateService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ExchangeRateService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/ForecastService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ForecastService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/InventoryService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature InventoryService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/LabelService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature LabelService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/LineItemTemplateService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature LineItemTemplateService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/LineItemService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature LineItemService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/LineItemCreativeAssociationService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature LineItemCreativeAssociationService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/LiveStreamEventService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature LiveStreamEventService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/NetworkService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature NetworkService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/OrderService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature OrderService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/PlacementService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature PlacementService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/ProductService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature ProductService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/ProductTemplateService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature ProductTemplateService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/ProposalService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature ProposalService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/ProposalLineItemService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature ProposalLineItemService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/PublisherQueryLanguageService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature PublisherQueryLanguageService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/RateCardService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature RateCardService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/RateCardCustomizationService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature RateCardCustomizationService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/RateCardCustomizationGroupService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature RateCardCustomizationGroupService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/ReconciliationOrderReportService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ReconciliationOrderReportService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/ReconciliationReportService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ReconciliationReportService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/ReconciliationReportRowService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ReconciliationReportRowService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/ReportService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ReportService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/SuggestedAdUnitService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature SuggestedAdUnitService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/TeamService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature TeamService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/UserService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature UserService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/UserTeamAssociationService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature UserTeamAssociationService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201405/WorkflowRequestService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature WorkflowRequestService;
/// <summary>
/// Factory type for v201405 services.
/// </summary>
public static readonly Type factoryType = typeof(DfpServiceFactory);
/// <summary>
/// Static constructor to initialize the service constants.
/// </summary>
static v201405() {
ActivityGroupService = DfpService.MakeServiceSignature("v201405", "ActivityGroupService");
ActivityService = DfpService.MakeServiceSignature("v201405", "ActivityService");
AdRuleService = DfpService.MakeServiceSignature("v201405", "AdRuleService");
BaseRateService = DfpService.MakeServiceSignature("v201405", "BaseRateService");
ContactService = DfpService.MakeServiceSignature("v201405", "ContactService");
AudienceSegmentService = DfpService.MakeServiceSignature("v201405",
"AudienceSegmentService");
CompanyService = DfpService.MakeServiceSignature("v201405", "CompanyService");
ContentService = DfpService.MakeServiceSignature("v201405", "ContentService");
ContentMetadataKeyHierarchyService = DfpService.MakeServiceSignature("v201405",
"ContentMetadataKeyHierarchyService");
CreativeService = DfpService.MakeServiceSignature("v201405", "CreativeService");
CreativeSetService = DfpService.MakeServiceSignature("v201405", "CreativeSetService");
CreativeTemplateService = DfpService.MakeServiceSignature("v201405",
"CreativeTemplateService");
CreativeWrapperService = DfpService.MakeServiceSignature("v201405",
"CreativeWrapperService");
CustomTargetingService = DfpService.MakeServiceSignature("v201405",
"CustomTargetingService");
CustomFieldService = DfpService.MakeServiceSignature("v201405",
"CustomFieldService");
ExchangeRateService = DfpService.MakeServiceSignature("v201405", "ExchangeRateService");
ForecastService = DfpService.MakeServiceSignature("v201405", "ForecastService");
InventoryService = DfpService.MakeServiceSignature("v201405", "InventoryService");
LabelService = DfpService.MakeServiceSignature("v201405", "LabelService");
LineItemTemplateService = DfpService.MakeServiceSignature("v201405",
"LineItemTemplateService");
LineItemService = DfpService.MakeServiceSignature("v201405", "LineItemService");
LineItemCreativeAssociationService =
DfpService.MakeServiceSignature("v201405", "LineItemCreativeAssociationService");
LiveStreamEventService = DfpService.MakeServiceSignature("v201405",
"LiveStreamEventService");
NetworkService = DfpService.MakeServiceSignature("v201405", "NetworkService");
OrderService = DfpService.MakeServiceSignature("v201405", "OrderService");
PlacementService = DfpService.MakeServiceSignature("v201405", "PlacementService");
ProductService = DfpService.MakeServiceSignature("v201405", "ProductService");
ProductTemplateService = DfpService.MakeServiceSignature("v201405",
"ProductTemplateService");
ProposalService = DfpService.MakeServiceSignature("v201405", "ProposalService");
ProposalLineItemService = DfpService.MakeServiceSignature("v201405",
"ProposalLineItemService");
PublisherQueryLanguageService = DfpService.MakeServiceSignature("v201405",
"PublisherQueryLanguageService");
RateCardService = DfpService.MakeServiceSignature("v201405", "RateCardService");
RateCardCustomizationService = DfpService.MakeServiceSignature("v201405",
"RateCardCustomizationService");
RateCardCustomizationGroupService = DfpService.MakeServiceSignature("v201405",
"RateCardCustomizationGroupService");
ReconciliationOrderReportService = DfpService.MakeServiceSignature("v201405",
"ReconciliationOrderReportService");
ReconciliationReportService = DfpService.MakeServiceSignature("v201405",
"ReconciliationReportService");
ReconciliationReportRowService = DfpService.MakeServiceSignature("v201405",
"ReconciliationReportRowService");
ReportService = DfpService.MakeServiceSignature("v201405", "ReportService");
SuggestedAdUnitService = DfpService.MakeServiceSignature("v201405",
"SuggestedAdUnitService");
TeamService = DfpService.MakeServiceSignature("v201405", "TeamService");
UserService = DfpService.MakeServiceSignature("v201405", "UserService");
UserTeamAssociationService = DfpService.MakeServiceSignature("v201405",
"UserTeamAssociationService");
WorkflowRequestService = DfpService.MakeServiceSignature("v201405",
"WorkflowRequestService");
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: addressbook.proto
#pragma warning disable 1591, 0612, 3021
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace ProtoBuf.Serialization.Tests {
/// <summary>Holder for reflection information generated from addressbook.proto</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class AddressbookReflection {
/// <summary>File descriptor for addressbook.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static AddressbookReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChFhZGRyZXNzYm9vay5wcm90bxIIdHV0b3JpYWwi1QEKBlBlcnNvbhIMCgRu",
"YW1lGAEgASgJEgoKAmlkGAIgASgFEg0KBWVtYWlsGAMgASgJEiwKBnBob25l",
"cxgEIAMoCzIcLnR1dG9yaWFsLlBlcnNvbi5QaG9uZU51bWJlchpHCgtQaG9u",
"ZU51bWJlchIOCgZudW1iZXIYASABKAkSKAoEdHlwZRgCIAEoDjIaLnR1dG9y",
"aWFsLlBlcnNvbi5QaG9uZVR5cGUiKwoJUGhvbmVUeXBlEgoKBk1PQklMRRAA",
"EggKBEhPTUUQARIICgRXT1JLEAIiSAoLQWRkcmVzc0Jvb2sSIAoGcGVvcGxl",
"GAEgAygLMhAudHV0b3JpYWwuUGVyc29uEhcKD2FkZHJlc3NCb29rTmFtZRgC",
"IAEoCUIaqgIXVW5pdFRlc3RzLlNlcmlhbGl6YXRpb25iBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::ProtoBuf.Serialization.Tests.Person), global::ProtoBuf.Serialization.Tests.Person.Parser, new[]{ "Name", "Id", "Email", "Phones" }, null, new[]{ typeof(global::ProtoBuf.Serialization.Tests.Person.Types.PhoneType) }, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::ProtoBuf.Serialization.Tests.Person.Types.PhoneNumber), global::ProtoBuf.Serialization.Tests.Person.Types.PhoneNumber.Parser, new[]{ "Number", "Type" }, null, null, null)}),
new pbr::GeneratedClrTypeInfo(typeof(global::ProtoBuf.Serialization.Tests.AddressBook), global::ProtoBuf.Serialization.Tests.AddressBook.Parser, new[]{ "People", "AddressBookName" }, null, null, null)
}));
}
}
/// <summary>
/// [START messages]
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Person : pb::IMessage<Person> {
private static readonly pb::MessageParser<Person> _parser = new pb::MessageParser<Person>(() => new Person());
public static pb::MessageParser<Person> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::ProtoBuf.Serialization.Tests.AddressbookReflection.Descriptor.MessageTypes[0]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public Person() {
OnConstruction();
}
partial void OnConstruction();
public Person(Person other) : this() {
name_ = other.name_;
id_ = other.id_;
email_ = other.email_;
phones_ = other.phones_.Clone();
}
public Person Clone() {
return new Person(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "id" field.</summary>
public const int IdFieldNumber = 2;
private int id_;
/// <summary>
/// Unique ID number for this person.
/// </summary>
public int Id {
get { return id_; }
set {
id_ = value;
}
}
/// <summary>Field number for the "email" field.</summary>
public const int EmailFieldNumber = 3;
private string email_ = "";
public string Email {
get { return email_; }
set {
email_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "phones" field.</summary>
public const int PhonesFieldNumber = 4;
private static readonly pb::FieldCodec<global::ProtoBuf.Serialization.Tests.Person.Types.PhoneNumber> _repeated_phones_codec
= pb::FieldCodec.ForMessage(34, global::ProtoBuf.Serialization.Tests.Person.Types.PhoneNumber.Parser);
private readonly pbc::RepeatedField<global::ProtoBuf.Serialization.Tests.Person.Types.PhoneNumber> phones_ = new pbc::RepeatedField<global::ProtoBuf.Serialization.Tests.Person.Types.PhoneNumber>();
public pbc::RepeatedField<global::ProtoBuf.Serialization.Tests.Person.Types.PhoneNumber> Phones {
get { return phones_; }
}
public override bool Equals(object other) {
return Equals(other as Person);
}
public bool Equals(Person other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
if (Id != other.Id) return false;
if (Email != other.Email) return false;
if(!phones_.Equals(other.phones_)) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
if (Id != 0) hash ^= Id.GetHashCode();
if (Email.Length != 0) hash ^= Email.GetHashCode();
hash ^= phones_.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
if (Id != 0) {
output.WriteRawTag(16);
output.WriteInt32(Id);
}
if (Email.Length != 0) {
output.WriteRawTag(26);
output.WriteString(Email);
}
phones_.WriteTo(output, _repeated_phones_codec);
}
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
if (Id != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Id);
}
if (Email.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Email);
}
size += phones_.CalculateSize(_repeated_phones_codec);
return size;
}
public void MergeFrom(Person other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
if (other.Id != 0) {
Id = other.Id;
}
if (other.Email.Length != 0) {
Email = other.Email;
}
phones_.Add(other.phones_);
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Name = input.ReadString();
break;
}
case 16: {
Id = input.ReadInt32();
break;
}
case 26: {
Email = input.ReadString();
break;
}
case 34: {
phones_.AddEntriesFrom(input, _repeated_phones_codec);
break;
}
}
}
}
/// <summary>Container for nested types declared in the Person message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Types {
public enum PhoneType {
[pbr::OriginalName("MOBILE")] Mobile = 0,
[pbr::OriginalName("HOME")] Home = 1,
[pbr::OriginalName("WORK")] Work = 2,
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class PhoneNumber : pb::IMessage<PhoneNumber> {
private static readonly pb::MessageParser<PhoneNumber> _parser = new pb::MessageParser<PhoneNumber>(() => new PhoneNumber());
public static pb::MessageParser<PhoneNumber> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::ProtoBuf.Serialization.Tests.Person.Descriptor.NestedTypes[0]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public PhoneNumber() {
OnConstruction();
}
partial void OnConstruction();
public PhoneNumber(PhoneNumber other) : this() {
number_ = other.number_;
type_ = other.type_;
}
public PhoneNumber Clone() {
return new PhoneNumber(this);
}
/// <summary>Field number for the "number" field.</summary>
public const int NumberFieldNumber = 1;
private string number_ = "";
public string Number {
get { return number_; }
set {
number_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "type" field.</summary>
public const int TypeFieldNumber = 2;
private global::ProtoBuf.Serialization.Tests.Person.Types.PhoneType type_ = 0;
public global::ProtoBuf.Serialization.Tests.Person.Types.PhoneType Type {
get { return type_; }
set {
type_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as PhoneNumber);
}
public bool Equals(PhoneNumber other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Number != other.Number) return false;
if (Type != other.Type) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Number.Length != 0) hash ^= Number.GetHashCode();
if (Type != 0) hash ^= Type.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Number.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Number);
}
if (Type != 0) {
output.WriteRawTag(16);
output.WriteEnum((int) Type);
}
}
public int CalculateSize() {
int size = 0;
if (Number.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Number);
}
if (Type != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type);
}
return size;
}
public void MergeFrom(PhoneNumber other) {
if (other == null) {
return;
}
if (other.Number.Length != 0) {
Number = other.Number;
}
if (other.Type != 0) {
Type = other.Type;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Number = input.ReadString();
break;
}
case 16: {
type_ = (global::ProtoBuf.Serialization.Tests.Person.Types.PhoneType) input.ReadEnum();
break;
}
}
}
}
}
}
}
/// <summary>
/// Our address book file is just one of these.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class AddressBook : pb::IMessage<AddressBook> {
private static readonly pb::MessageParser<AddressBook> _parser = new pb::MessageParser<AddressBook>(() => new AddressBook());
public static pb::MessageParser<AddressBook> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::ProtoBuf.Serialization.Tests.AddressbookReflection.Descriptor.MessageTypes[1]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public AddressBook() {
OnConstruction();
}
partial void OnConstruction();
public AddressBook(AddressBook other) : this() {
people_ = other.people_.Clone();
addressBookName_ = other.addressBookName_;
}
public AddressBook Clone() {
return new AddressBook(this);
}
/// <summary>Field number for the "people" field.</summary>
public const int PeopleFieldNumber = 1;
private static readonly pb::FieldCodec<global::ProtoBuf.Serialization.Tests.Person> _repeated_people_codec
= pb::FieldCodec.ForMessage(10, global::ProtoBuf.Serialization.Tests.Person.Parser);
private readonly pbc::RepeatedField<global::ProtoBuf.Serialization.Tests.Person> people_ = new pbc::RepeatedField<global::ProtoBuf.Serialization.Tests.Person>();
public pbc::RepeatedField<global::ProtoBuf.Serialization.Tests.Person> People {
get { return people_; }
}
/// <summary>Field number for the "addressBookName" field.</summary>
public const int AddressBookNameFieldNumber = 2;
private string addressBookName_ = "";
/// <summary>
/// the name of this address book
/// </summary>
public string AddressBookName {
get { return addressBookName_; }
set {
addressBookName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
public override bool Equals(object other) {
return Equals(other as AddressBook);
}
public bool Equals(AddressBook other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!people_.Equals(other.people_)) return false;
if (AddressBookName != other.AddressBookName) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
hash ^= people_.GetHashCode();
if (AddressBookName.Length != 0) hash ^= AddressBookName.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
people_.WriteTo(output, _repeated_people_codec);
if (AddressBookName.Length != 0) {
output.WriteRawTag(18);
output.WriteString(AddressBookName);
}
}
public int CalculateSize() {
int size = 0;
size += people_.CalculateSize(_repeated_people_codec);
if (AddressBookName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(AddressBookName);
}
return size;
}
public void MergeFrom(AddressBook other) {
if (other == null) {
return;
}
people_.Add(other.people_);
if (other.AddressBookName.Length != 0) {
AddressBookName = other.AddressBookName;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
people_.AddEntriesFrom(input, _repeated_people_codec);
break;
}
case 18: {
AddressBookName = input.ReadString();
break;
}
}
}
}
}
}
| |
// Copyright 2016 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.
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
/// This is the main GVR audio class that communicates with the native code implementation of
/// the audio system. Native functions of the system can only be called through this class to
/// preserve the internal system functionality. Public function calls are *not* thread-safe.
public static class GvrAudio {
/// Audio system rendering quality.
public enum Quality {
Stereo = 0, ///< Stereo-only rendering
Low = 1, ///< Low quality binaural rendering (first-order HRTF)
High = 2 ///< High quality binaural rendering (third-order HRTF)
}
/// Native audio spatializer effect data.
public enum SpatializerData {
Id = 0, /// ID.
Type = 1, /// Spatializer type.
NumChannels = 2, /// Number of input channels.
ChannelSet = 3, /// Soundfield channel set.
Gain = 4, /// Gain.
DistanceAttenuation = 5, /// Computed distance attenuation.
MinDistance = 6, /// Minimum distance for distance-based attenuation.
ZeroOutput = 7, /// Should zero out the output buffer?
}
/// Native audio spatializer type.
public enum SpatializerType {
Source = 0, /// 3D sound object.
Soundfield = 1 /// First-order ambisonic soundfield.
}
/// System sampling rate.
public static int SampleRate {
get { return sampleRate; }
}
private static int sampleRate = -1;
/// System number of output channels.
public static int NumChannels {
get { return numChannels; }
}
private static int numChannels = -1;
/// System number of frames per buffer.
public static int FramesPerBuffer {
get { return framesPerBuffer; }
}
private static int framesPerBuffer = -1;
/// Initializes the audio system with the current audio configuration.
/// @note This should only be called from the main Unity thread.
public static void Initialize (GvrAudioListener listener, Quality quality) {
if (!initialized) {
// Initialize the audio system.
AudioConfiguration config = AudioSettings.GetConfiguration();
sampleRate = config.sampleRate;
numChannels = (int)config.speakerMode;
framesPerBuffer = config.dspBufferSize;
if (numChannels != (int)AudioSpeakerMode.Stereo) {
Debug.LogError("Only 'Stereo' speaker mode is supported by GVR Audio.");
return;
}
if (Application.platform != RuntimePlatform.Android) {
// TODO: GvrAudio bug on Android with Unity 2017
Initialize((int) quality, sampleRate, numChannels, framesPerBuffer);
}
listenerTransform = listener.transform;
if (Application.platform == RuntimePlatform.Android) {
// TODO: GvrAudio bug on Android with Unity 2017
return;
}
initialized = true;
} else if (listener.transform != listenerTransform) {
Debug.LogError("Only one GvrAudioListener component is allowed in the scene.");
GvrAudioListener.Destroy(listener);
}
}
/// Shuts down the audio system.
/// @note This should only be called from the main Unity thread.
public static void Shutdown (GvrAudioListener listener) {
if (initialized && listener.transform == listenerTransform) {
initialized = false;
if (Application.platform == RuntimePlatform.Android) {
// TODO: GvrAudio bug on Android with Unity 2017
return;
}
Shutdown();
sampleRate = -1;
numChannels = -1;
framesPerBuffer = -1;
listenerTransform = null;
}
}
/// Updates the audio listener.
/// @note This should only be called from the main Unity thread.
public static void UpdateAudioListener (float globalGainDb, LayerMask occlusionMask) {
if (initialized) {
occlusionMaskValue = occlusionMask.value;
SetListenerGain(ConvertAmplitudeFromDb(globalGainDb));
}
}
/// Creates a new first-order ambisonic soundfield with a unique id.
/// @note This should only be called from the main Unity thread.
public static int CreateAudioSoundfield () {
int soundfieldId = -1;
if (initialized) {
soundfieldId = CreateSoundfield(numFoaChannels);
}
return soundfieldId;
}
/// Updates the |soundfield| with given |id| and its properties.
/// @note This should only be called from the main Unity thread.
public static void UpdateAudioSoundfield (int id, GvrAudioSoundfield soundfield) {
if (initialized) {
SetSourceBypassRoomEffects(id, soundfield.bypassRoomEffects);
}
}
/// Creates a new audio source with a unique id.
/// @note This should only be called from the main Unity thread.
public static int CreateAudioSource (bool hrtfEnabled) {
int sourceId = -1;
if (initialized) {
sourceId = CreateSoundObject(hrtfEnabled);
}
return sourceId;
}
/// Destroys the audio source with given |id|.
/// @note This should only be called from the main Unity thread.
public static void DestroyAudioSource (int id) {
if (initialized) {
DestroySource(id);
}
}
/// Updates the audio |source| with given |id| and its properties.
/// @note This should only be called from the main Unity thread.
public static void UpdateAudioSource (int id, GvrAudioSource source, float currentOcclusion) {
if (initialized) {
SetSourceBypassRoomEffects(id, source.bypassRoomEffects);
SetSourceDirectivity(id, source.directivityAlpha, source.directivitySharpness);
SetSourceListenerDirectivity(id, source.listenerDirectivityAlpha,
source.listenerDirectivitySharpness);
SetSourceOcclusionIntensity(id, currentOcclusion);
}
}
/// Updates the room effects of the environment with given |room| properties.
/// @note This should only be called from the main Unity thread.
public static void UpdateAudioRoom(GvrAudioRoom room, bool roomEnabled) {
// Update the enabled rooms list.
if (roomEnabled) {
if (!enabledRooms.Contains(room)) {
enabledRooms.Add(room);
}
} else {
enabledRooms.Remove(room);
}
// Update the current room effects to be applied.
if(initialized) {
if (enabledRooms.Count > 0) {
GvrAudioRoom currentRoom = enabledRooms[enabledRooms.Count - 1];
RoomProperties roomProperties = GetRoomProperties(currentRoom);
// Pass the room properties into a pointer.
IntPtr roomPropertiesPtr = Marshal.AllocHGlobal(Marshal.SizeOf(roomProperties));
Marshal.StructureToPtr(roomProperties, roomPropertiesPtr, false);
SetRoomProperties(roomPropertiesPtr);
Marshal.FreeHGlobal(roomPropertiesPtr);
} else {
// Set the room properties to null, which will effectively disable the room effects.
SetRoomProperties(IntPtr.Zero);
}
}
}
/// Computes the occlusion intensity of a given |source| using point source detection.
/// @note This should only be called from the main Unity thread.
public static float ComputeOcclusion (Transform sourceTransform) {
float occlusion = 0.0f;
if (initialized) {
Vector3 listenerPosition = listenerTransform.position;
Vector3 sourceFromListener = sourceTransform.position - listenerPosition;
int numHits = Physics.RaycastNonAlloc(listenerPosition, sourceFromListener, occlusionHits,
sourceFromListener.magnitude, occlusionMaskValue);
for (int i = 0; i < numHits; ++i) {
if (occlusionHits[i].transform != listenerTransform &&
occlusionHits[i].transform != sourceTransform) {
occlusion += 1.0f;
}
}
}
return occlusion;
}
/// Converts given |db| value to its amplitude equivalent where 'dB = 20 * log10(amplitude)'.
public static float ConvertAmplitudeFromDb (float db) {
return Mathf.Pow(10.0f, 0.05f * db);
}
/// Generates a set of points to draw a 2D polar pattern.
public static Vector2[] Generate2dPolarPattern (float alpha, float order, int resolution) {
Vector2[] points = new Vector2[resolution];
float interval = 2.0f * Mathf.PI / resolution;
for (int i = 0; i < resolution; ++i) {
float theta = i * interval;
// Magnitude |r| for |theta| in radians.
float r = Mathf.Pow(Mathf.Abs((1 - alpha) + alpha * Mathf.Cos(theta)), order);
points[i] = new Vector2(r * Mathf.Sin(theta), r * Mathf.Cos(theta));
}
return points;
}
/// Returns whether the listener is currently inside the given |room| boundaries.
public static bool IsListenerInsideRoom(GvrAudioRoom room) {
bool isInside = false;
if(initialized) {
Vector3 relativePosition = listenerTransform.position - room.transform.position;
Quaternion rotationInverse = Quaternion.Inverse(room.transform.rotation);
bounds.size = Vector3.Scale(room.transform.lossyScale, room.size);
isInside = bounds.Contains(rotationInverse * relativePosition);
}
return isInside;
}
/// Listener directivity GUI color.
public static readonly Color listenerDirectivityColor = 0.65f * Color.magenta;
/// Source directivity GUI color.
public static readonly Color sourceDirectivityColor = 0.65f * Color.blue;
/// Minimum distance threshold between |minDistance| and |maxDistance|.
public const float distanceEpsilon = 0.01f;
/// Max distance limit that can be set for volume rolloff.
public const float maxDistanceLimit = 1000000.0f;
/// Min distance limit that can be set for volume rolloff.
public const float minDistanceLimit = 990099.0f;
/// Maximum allowed gain value in decibels.
public const float maxGainDb = 24.0f;
/// Minimum allowed gain value in decibels.
public const float minGainDb = -24.0f;
/// Maximum allowed reverb brightness modifier value.
public const float maxReverbBrightness = 1.0f;
/// Minimum allowed reverb brightness modifier value.
public const float minReverbBrightness = -1.0f;
/// Maximum allowed reverb time modifier value.
public const float maxReverbTime = 3.0f;
/// Maximum allowed reflectivity multiplier of a room surface material.
public const float maxReflectivity = 2.0f;
/// Maximum allowed number of raycast hits for occlusion computation per source.
public const int maxNumOcclusionHits = 12;
/// Source occlusion detection rate in seconds.
public const float occlusionDetectionInterval = 0.2f;
/// Number of first-order ambisonic input channels.
public const int numFoaChannels = 4;
[StructLayout(LayoutKind.Sequential)]
private struct RoomProperties {
// Center position of the room in world space.
public float positionX;
public float positionY;
public float positionZ;
// Rotation (quaternion) of the room in world space.
public float rotationX;
public float rotationY;
public float rotationZ;
public float rotationW;
// Size of the shoebox room in world space.
public float dimensionsX;
public float dimensionsY;
public float dimensionsZ;
// Material name of each surface of the shoebox room.
public GvrAudioRoom.SurfaceMaterial materialLeft;
public GvrAudioRoom.SurfaceMaterial materialRight;
public GvrAudioRoom.SurfaceMaterial materialBottom;
public GvrAudioRoom.SurfaceMaterial materialTop;
public GvrAudioRoom.SurfaceMaterial materialFront;
public GvrAudioRoom.SurfaceMaterial materialBack;
// User defined uniform scaling factor for reflectivity. This parameter has no effect when set
// to 1.0f.
public float reflectionScalar;
// User defined reverb tail gain multiplier. This parameter has no effect when set to 0.0f.
public float reverbGain;
// Parameter which allows the reverberation time across all frequency bands to be increased or
// decreased. This parameter has no effect when set to 1.0f.
public float reverbTime;
// Parameter which allows the ratio of high frequncy reverb components to low frequency reverb
// components to be adjusted. This parameter has no effect when set to 0.0f.
public float reverbBrightness;
};
// Converts given |position| and |rotation| from Unity space to audio space.
private static void ConvertAudioTransformFromUnity (ref Vector3 position,
ref Quaternion rotation) {
transformMatrix = flipZ * Matrix4x4.TRS(position, rotation, Vector3.one) * flipZ;
position = transformMatrix.GetColumn(3);
rotation = Quaternion.LookRotation(transformMatrix.GetColumn(2), transformMatrix.GetColumn(1));
}
// Returns room properties of the given |room|.
private static RoomProperties GetRoomProperties(GvrAudioRoom room) {
RoomProperties roomProperties;
Vector3 position = room.transform.position;
Quaternion rotation = room.transform.rotation;
Vector3 scale = Vector3.Scale(room.transform.lossyScale, room.size);
ConvertAudioTransformFromUnity(ref position, ref rotation);
roomProperties.positionX = position.x;
roomProperties.positionY = position.y;
roomProperties.positionZ = position.z;
roomProperties.rotationX = rotation.x;
roomProperties.rotationY = rotation.y;
roomProperties.rotationZ = rotation.z;
roomProperties.rotationW = rotation.w;
roomProperties.dimensionsX = scale.x;
roomProperties.dimensionsY = scale.y;
roomProperties.dimensionsZ = scale.z;
roomProperties.materialLeft = room.leftWall;
roomProperties.materialRight = room.rightWall;
roomProperties.materialBottom = room.floor;
roomProperties.materialTop = room.ceiling;
roomProperties.materialFront = room.frontWall;
roomProperties.materialBack = room.backWall;
roomProperties.reverbGain = ConvertAmplitudeFromDb(room.reverbGainDb);
roomProperties.reverbTime = room.reverbTime;
roomProperties.reverbBrightness = room.reverbBrightness;
roomProperties.reflectionScalar = room.reflectivity;
return roomProperties;
}
// Right-handed to left-handed matrix converter (and vice versa).
private static readonly Matrix4x4 flipZ = Matrix4x4.Scale(new Vector3(1.0f, 1.0f, -1.0f));
// Boundaries instance to be used in room detection logic.
private static Bounds bounds = new Bounds(Vector3.zero, Vector3.zero);
// Container to store the currently active rooms in the scene.
private static List<GvrAudioRoom> enabledRooms = new List<GvrAudioRoom>();
// Denotes whether the system is initialized properly.
private static bool initialized = false;
// Listener transform.
private static Transform listenerTransform = null;
// Pre-allocated raycast hit list for occlusion computation.
private static RaycastHit[] occlusionHits = new RaycastHit[maxNumOcclusionHits];
// Occlusion layer mask.
private static int occlusionMaskValue = -1;
// 4x4 transformation matrix to be used in transform space conversion.
private static Matrix4x4 transformMatrix = Matrix4x4.identity;
#if UNITY_IOS
private const string pluginName = "__Internal";
#else
private const string pluginName = "audioplugingvrunity";
#endif
// Listener handlers.
[DllImport(pluginName)]
private static extern void SetListenerGain (float gain);
// Soundfield handlers.
[DllImport(pluginName)]
private static extern int CreateSoundfield (int numChannels);
// Source handlers.
[DllImport(pluginName)]
private static extern int CreateSoundObject (bool enableHrtf);
[DllImport(pluginName)]
private static extern void DestroySource (int sourceId);
[DllImport(pluginName)]
private static extern void SetSourceBypassRoomEffects (int sourceId, bool bypassRoomEffects);
[DllImport(pluginName)]
private static extern void SetSourceDirectivity (int sourceId, float alpha, float order);
[DllImport(pluginName)]
private static extern void SetSourceListenerDirectivity (int sourceId, float alpha, float order);
[DllImport(pluginName)]
private static extern void SetSourceOcclusionIntensity (int sourceId, float intensity);
// Room handlers.
[DllImport(pluginName)]
private static extern void SetRoomProperties (IntPtr roomProperties);
// System handlers.
[DllImport(pluginName)]
private static extern void Initialize (int quality, int sampleRate, int numChannels,
int framesPerBuffer);
[DllImport(pluginName)]
private static extern void Shutdown ();
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type SiteSitesCollectionRequest.
/// </summary>
public partial class SiteSitesCollectionRequest : BaseRequest, ISiteSitesCollectionRequest
{
/// <summary>
/// Constructs a new SiteSitesCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public SiteSitesCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified Site to the collection via POST.
/// </summary>
/// <param name="site">The Site to add.</param>
/// <returns>The created Site.</returns>
public System.Threading.Tasks.Task<Site> AddAsync(Site site)
{
return this.AddAsync(site, CancellationToken.None);
}
/// <summary>
/// Adds the specified Site to the collection via POST.
/// </summary>
/// <param name="site">The Site to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created Site.</returns>
public System.Threading.Tasks.Task<Site> AddAsync(Site site, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
return this.SendAsync<Site>(site, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<ISiteSitesCollectionPage> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<ISiteSitesCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<SiteSitesCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response != null && response.Value != null && response.Value.CurrentPage != null)
{
if (response.AdditionalData != null)
{
object nextPageLink;
response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
response.Value.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
}
return response.Value;
}
return null;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public ISiteSitesCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public ISiteSitesCollectionRequest Expand(Expression<Func<Site, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public ISiteSitesCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public ISiteSitesCollectionRequest Select(Expression<Func<Site, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public ISiteSitesCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public ISiteSitesCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public ISiteSitesCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public ISiteSitesCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| |
/***************************************************************************
* Album.cs
*
* Copyright (C) 2008 Novell
* Authors:
* Gabriel Burt ([email protected])
****************************************************************************/
/* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
*
* 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.Runtime.InteropServices;
namespace Mtp
{
public class Album : AbstractTrackList
{
internal static List<Album> GetAlbums (MtpDevice device)
{
List<Album> albums = new List<Album> ();
IntPtr ptr = LIBMTP_Get_Album_List (device.Handle);
while (ptr != IntPtr.Zero) {
// Destroy the struct *after* we use it to ensure we don't access freed memory
// for the 'tracks' variable
AlbumStruct d = (AlbumStruct)Marshal.PtrToStructure(ptr, typeof(AlbumStruct));
albums.Add (new Album (device, d));
LIBMTP_destroy_album_t (ptr);
ptr = d.next;
}
return albums;
}
private AlbumStruct album;
public uint AlbumId {
get { return Saved ? album.album_id : 0; }
}
public override string Name {
get { return album.name; }
set { album.name = value; }
}
public string Artist {
get { return album.artist; }
set { album.artist = value; }
}
public string Genre {
get { return album.genre; }
set { album.genre = value; }
}
public string Composer {
get {
#if LIBMTP8
return album.composer;
#else
return null;
#endif
}
set {
#if LIBMTP8
album.composer = value;
#endif
}
}
public override uint Count {
get { return album.no_tracks; }
protected set { album.no_tracks = value; }
}
protected override IntPtr TracksPtr {
get { return album.tracks; }
set { album.tracks = value; }
}
public Album (MtpDevice device, string name, string artist, string genre, string composer) : base (device, name)
{
Name = name;
Artist = artist;
Genre = genre;
Composer = composer;
Count = 0;
}
internal Album (MtpDevice device, AlbumStruct album) : base (device, album.tracks, album.no_tracks)
{
// Once we've loaded the tracks, set the TracksPtr to NULL as it
// will be freed when the Album constructor is finished.
this.album = album;
TracksPtr = IntPtr.Zero;
}
public override void Save ()
{
Save (null, 0, 0);
}
public void Save (byte [] cover_art, uint width, uint height)
{
base.Save ();
if (Saved) {
if (cover_art == null) {
return;
}
FileSampleData cover = new FileSampleData ();
cover.data = Marshal.AllocHGlobal (Marshal.SizeOf (typeof (byte)) * cover_art.Length);
Marshal.Copy (cover_art, 0, cover.data, cover_art.Length);
cover.size = (ulong)cover_art.Length;
cover.width = width;
cover.height = height;
cover.filetype = FileType.JPEG;
if (FileSample.LIBMTP_Send_Representative_Sample (Device.Handle, AlbumId, ref cover) != 0) {
//Console.WriteLine ("Failed to send representative sample file for album {0} (id {1})", Name, AlbumId);
}
Marshal.FreeHGlobal (cover.data);
}
}
protected override int Create ()
{
#if LIBMTP8
return LIBMTP_Create_New_Album (Device.Handle, ref album);
#else
return LIBMTP_Create_New_Album (Device.Handle, ref album, 0);
#endif
}
protected override int Update ()
{
return LIBMTP_Update_Album (Device.Handle, ref album);
}
public void Remove ()
{
MtpDevice.LIBMTP_Delete_Object(Device.Handle, AlbumId);
}
public override string ToString ()
{
return String.Format ("Album < Id: {4}, '{0}' by '{1}', genre '{2}', tracks {3} >", Name, Artist, Genre, Count, AlbumId);
}
public static Album GetById (MtpDevice device, uint id)
{
IntPtr ptr = Album.LIBMTP_Get_Album (device.Handle, id);
if (ptr == IntPtr.Zero) {
return null;
} else {
// Destroy the struct after we use it to prevent accessing freed memory
// in the 'tracks' variable
AlbumStruct album = (AlbumStruct) Marshal.PtrToStructure(ptr, typeof (AlbumStruct));
var ret = new Album (device, album);
LIBMTP_destroy_album_t (ptr);
return ret;
}
}
//[DllImport("libmtp.dll")]
//internal static extern IntPtr LIBMTP_new_album_t (); // LIBMTP_album_t*
[DllImport("libmtp.dll")]
static extern void LIBMTP_destroy_album_t (IntPtr album);
[DllImport("libmtp.dll")]
static extern IntPtr LIBMTP_Get_Album_List (MtpDeviceHandle handle); // LIBMTP_album_t*
[DllImport("libmtp.dll")]
static extern IntPtr LIBMTP_Get_Album (MtpDeviceHandle handle, uint albumId); // LIBMTP_album_t*
#if LIBMTP8
[DllImport("libmtp.dll")]
internal static extern int LIBMTP_Create_New_Album (MtpDeviceHandle handle, ref AlbumStruct album);
#else
[DllImport("libmtp.dll")]
internal static extern int LIBMTP_Create_New_Album (MtpDeviceHandle handle, ref AlbumStruct album, uint parentId);
#endif
[DllImport("libmtp.dll")]
static extern int LIBMTP_Update_Album (MtpDeviceHandle handle, ref AlbumStruct album);
}
[StructLayout(LayoutKind.Sequential)]
internal struct AlbumStruct
{
public uint album_id;
#if LIBMTP8
public uint parent_id;
public uint storage_id;
#endif
[MarshalAs(UnmanagedType.LPStr)]
public string name;
[MarshalAs(UnmanagedType.LPStr)]
public string artist;
#if LIBMTP8
[MarshalAs(UnmanagedType.LPStr)]
public string composer;
#endif
[MarshalAs(UnmanagedType.LPStr)]
public string genre;
public IntPtr tracks;
public uint no_tracks;
public IntPtr next;
}
}
| |
// 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.Globalization;
using Xunit;
namespace System.Tests
{
public static partial class TimeSpanTests
{
[Fact]
public static void MaxValue()
{
VerifyTimeSpan(TimeSpan.MaxValue, 10675199, 2, 48, 5, 477);
}
[Fact]
public static void MinValue()
{
VerifyTimeSpan(TimeSpan.MinValue, -10675199, -2, -48, -5, -477);
}
[Fact]
public static void Zero()
{
VerifyTimeSpan(TimeSpan.Zero, 0, 0, 0, 0, 0);
}
[Fact]
public static void Ctor_Empty()
{
VerifyTimeSpan(new TimeSpan(), 0, 0, 0, 0, 0);
VerifyTimeSpan(default(TimeSpan), 0, 0, 0, 0, 0);
}
[Fact]
public static void Ctor_Long()
{
VerifyTimeSpan(new TimeSpan(999999999999999999), 1157407, 9, 46, 39, 999);
}
[Fact]
public static void Ctor_Int_Int_Int()
{
var timeSpan = new TimeSpan(10, 9, 8);
VerifyTimeSpan(timeSpan, 0, 10, 9, 8, 0);
}
[Fact]
public static void Ctor_Int_Int_Int_Invalid()
{
Assert.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan((int)TimeSpan.MinValue.TotalHours - 1, 0, 0)); // TimeSpan < TimeSpan.MinValue
Assert.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan((int)TimeSpan.MaxValue.TotalHours + 1, 0, 0)); // TimeSpan > TimeSpan.MaxValue
}
[Fact]
public static void Ctor_Int_Int_Int_Int_Int()
{
var timeSpan = new TimeSpan(10, 9, 8, 7, 6);
VerifyTimeSpan(timeSpan, 10, 9, 8, 7, 6);
}
[Fact]
public static void Ctor_Int_Int_Int_Int_Int_Invalid()
{
// TimeSpan > TimeSpan.MinValue
TimeSpan min = TimeSpan.MinValue;
Assert.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(min.Days - 1, min.Hours, min.Minutes, min.Seconds, min.Milliseconds));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(min.Days, min.Hours - 1, min.Minutes, min.Seconds, min.Milliseconds));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(min.Days, min.Hours, min.Minutes - 1, min.Seconds, min.Milliseconds));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(min.Days, min.Hours, min.Minutes, min.Seconds - 1, min.Milliseconds));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(min.Days, min.Hours, min.Minutes, min.Seconds, min.Milliseconds - 1));
// TimeSpan > TimeSpan.MaxValue
TimeSpan max = TimeSpan.MaxValue;
Assert.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(max.Days + 1, max.Hours, max.Minutes, max.Seconds, max.Milliseconds));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(max.Days, max.Hours + 1, max.Minutes, max.Seconds, max.Milliseconds));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(max.Days, max.Hours, max.Minutes + 1, max.Seconds, max.Milliseconds));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(max.Days, max.Hours, max.Minutes, max.Seconds + 1, max.Milliseconds));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(max.Days, max.Hours, max.Minutes, max.Seconds, max.Milliseconds + 1));
}
public static IEnumerable<object[]> Total_Days_Hours_Minutes_Seconds_Milliseconds_TestData()
{
yield return new object[] { new TimeSpan(0, 0, 0, 0, 0), 0.0, 0.0, 0.0, 0.0, 0.0 };
yield return new object[] { new TimeSpan(0, 0, 0, 0, 500), 0.5 / 60.0 / 60.0 / 24.0, 0.5 / 60.0 / 60.0, 0.5 / 60.0, 0.5, 500.0 };
yield return new object[] { new TimeSpan(0, 1, 0, 0, 0), 1 / 24.0, 1, 60, 3600, 3600000 };
yield return new object[] { new TimeSpan(1, 0, 0, 0, 0), 1, 24, 1440, 86400, 86400000 };
yield return new object[] { new TimeSpan(1, 1, 0, 0, 0), 25.0 / 24.0, 25, 1500, 90000, 90000000 };
}
[Theory]
[MemberData(nameof(Total_Days_Hours_Minutes_Seconds_Milliseconds_TestData))]
public static void Total_Days_Hours_Minutes_Seconds_Milliseconds(TimeSpan timeSpan, double expectedDays, double expectedHours, double expectedMinutes, double expectedSeconds, double expectedMilliseconds)
{
// Use ToString() to prevent any rounding errors when comparing
Assert.Equal(expectedDays.ToString(), timeSpan.TotalDays.ToString());
Assert.Equal(expectedHours, timeSpan.TotalHours);
Assert.Equal(expectedMinutes, timeSpan.TotalMinutes);
Assert.Equal(expectedSeconds, timeSpan.TotalSeconds);
Assert.Equal(expectedMilliseconds, timeSpan.TotalMilliseconds);
}
[Fact]
public static void TotalMilliseconds_Invalid()
{
long maxMilliseconds = long.MaxValue / 10000;
long minMilliseconds = long.MinValue / 10000;
Assert.Equal(maxMilliseconds, TimeSpan.MaxValue.TotalMilliseconds);
Assert.Equal(minMilliseconds, TimeSpan.MinValue.TotalMilliseconds);
}
public static IEnumerable<object[]> Add_TestData()
{
yield return new object[] { new TimeSpan(0, 0, 0), new TimeSpan(1, 2, 3), new TimeSpan(1, 2, 3) };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(4, 5, 6), new TimeSpan(5, 7, 9) };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(-4, -5, -6), new TimeSpan(-3, -3, -3) };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 3), new TimeSpan(1, 3, 5, 7, 5) };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(10, 12, 13, 14, 15), new TimeSpan(11, 14, 16, 18, 20) };
yield return new object[] { new TimeSpan(10000), new TimeSpan(200000), new TimeSpan(210000) };
}
[Theory]
[MemberData(nameof(Add_TestData))]
public static void Add(TimeSpan timeSpan1, TimeSpan timeSpan2, TimeSpan expected)
{
Assert.Equal(expected, timeSpan1.Add(timeSpan2));
Assert.Equal(expected, timeSpan1 + timeSpan2);
}
[Fact]
public static void Add_Invalid()
{
Assert.Throws<OverflowException>(() => TimeSpan.MaxValue.Add(new TimeSpan(1))); // Result > TimeSpan.MaxValue
Assert.Throws<OverflowException>(() => TimeSpan.MinValue.Add(new TimeSpan(-1))); // Result < TimeSpan.MinValue
Assert.Throws<OverflowException>(() => TimeSpan.MaxValue + new TimeSpan(1)); // Result > TimeSpan.MaxValue
Assert.Throws<OverflowException>(() => TimeSpan.MinValue + new TimeSpan(-1)); // Result < TimeSpan.MinValue
}
public static IEnumerable<object[]> CompareTo_TestData()
{
yield return new object[] { new TimeSpan(10000), new TimeSpan(10000), 0 };
yield return new object[] { new TimeSpan(20000), new TimeSpan(10000), 1 };
yield return new object[] { new TimeSpan(10000), new TimeSpan(20000), -1 };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(1, 2, 3), 0 };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(1, 2, 4), -1 };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(1, 2, 2), 1 };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(1, 3, 3), -1 };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(1, 1, 3), 1 };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(2, 2, 3), -1 };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(0, 2, 3), 1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(1, 2, 3, 4), 0 };
yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(1, 2, 3, 5), -1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(1, 2, 3, 3), 1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(1, 2, 4, 4), -1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(1, 2, 2, 4), 1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(1, 3, 3, 4), -1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(1, 1, 3, 4), 1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(2, 2, 3, 4), -1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(0, 2, 3, 4), 1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 3, 4, 5), 0 };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 3, 4, 6), -1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 3, 4, 4), 1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 3, 5, 5), -1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 3, 3, 5), 1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 4, 4, 5), -1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 2, 4, 5), 1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 3, 3, 4, 5), -1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 1, 3, 4, 5), 1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(2, 2, 3, 4, 5), -1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(0, 2, 3, 4, 5), 1 };
yield return new object[] { new TimeSpan(10000), null, 1 };
}
[Theory]
[MemberData(nameof(CompareTo_TestData))]
public static void CompareTo(TimeSpan timeSpan1, object obj, int expected)
{
if (obj is TimeSpan)
{
TimeSpan timeSpan2 = (TimeSpan)obj;
Assert.Equal(expected, Math.Sign(timeSpan1.CompareTo(timeSpan2)));
Assert.Equal(expected, Math.Sign(TimeSpan.Compare(timeSpan1, timeSpan2)));
if (expected >= 0)
{
Assert.True(timeSpan1 >= timeSpan2);
Assert.False(timeSpan1 < timeSpan2);
}
if (expected > 0)
{
Assert.True(timeSpan1 > timeSpan2);
Assert.False(timeSpan1 <= timeSpan2);
}
if (expected <= 0)
{
Assert.True(timeSpan1 <= timeSpan2);
Assert.False(timeSpan1 > timeSpan2);
}
if (expected < 0)
{
Assert.True(timeSpan1 < timeSpan2);
Assert.False(timeSpan1 >= timeSpan2);
}
}
IComparable comparable = timeSpan1;
Assert.Equal(expected, Math.Sign(comparable.CompareTo(obj)));
}
[Fact]
public static void CompareTo_ObjectNotTimeSpan_ThrowsArgumentException()
{
IComparable comparable = new TimeSpan(10000);
Assert.Throws<ArgumentException>(null, () => comparable.CompareTo("10000")); // Obj is not a time span
}
public static IEnumerable<object[]> Duration_TestData()
{
yield return new object[] { new TimeSpan(0, 0, 0), new TimeSpan(0, 0, 0) };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(1, 2, 3) };
yield return new object[] { new TimeSpan(-1, -2, -3), new TimeSpan(1, 2, 3) };
yield return new object[] { new TimeSpan(12345), new TimeSpan(12345) };
yield return new object[] { new TimeSpan(-12345), new TimeSpan(12345) };
}
[Theory]
[MemberData(nameof(Duration_TestData))]
public static void Duration(TimeSpan timeSpan, TimeSpan expected)
{
Assert.Equal(expected, timeSpan.Duration());
}
[Fact]
public static void Duration_Invalid()
{
Assert.Throws<OverflowException>(() => TimeSpan.MinValue.Duration()); // TimeSpan.Ticks == TimeSpan.MinValue.Ticks
Assert.Throws<OverflowException>(() => new TimeSpan(TimeSpan.MinValue.Ticks).Duration()); // TimeSpan.Ticks == TimeSpan.MinValue.Ticks
}
public static IEnumerable<object[]> Equals_TestData()
{
yield return new object[] { new TimeSpan(0, 0, 0), new TimeSpan(0, 0, 0), true };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(1, 2, 3), true };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(1, 2, 4), false };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(1, 3, 3), false };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(2, 2, 3), false };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(0, 1, 2, 3), true };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(0, 1, 2, 3, 0), true };
yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(1, 2, 3, 4), true };
yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(1, 2, 3, 5), false };
yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(1, 2, 4, 4), false };
yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(1, 3, 3, 4), false };
yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(2, 2, 3, 4), false };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(2, 3, 4), false };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 3, 4, 5), true };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 3, 4, 6), false };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 3, 5, 5), false };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 4, 4, 5), false };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 3, 3, 4, 5), false };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(2, 2, 3, 4, 5), false };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(2, 2, 3, 4, 5), false };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 3, 4), false };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(2, 2, 3), false };
yield return new object[] { new TimeSpan(10000), new TimeSpan(10000), true };
yield return new object[] { new TimeSpan(10000), new TimeSpan(20000), false };
yield return new object[] { new TimeSpan(10000), "20000", false };
yield return new object[] { new TimeSpan(10000), null, false };
}
[Theory]
[MemberData(nameof(Equals_TestData))]
public static void Equals(TimeSpan timeSpan1, object obj, bool expected)
{
if (obj is TimeSpan)
{
TimeSpan timeSpan2 = (TimeSpan)obj;
Assert.Equal(expected, TimeSpan.Equals(timeSpan1, timeSpan2));
Assert.Equal(expected, timeSpan1.Equals(timeSpan2));
Assert.Equal(expected, timeSpan1 == timeSpan2);
Assert.Equal(!expected, timeSpan1 != timeSpan2);
Assert.Equal(expected, timeSpan1.GetHashCode().Equals(timeSpan2.GetHashCode()));
}
Assert.Equal(expected, timeSpan1.Equals(obj));
}
public static IEnumerable<object[]> FromDays_TestData()
{
yield return new object[] { 100.5, new TimeSpan(100, 12, 0, 0) };
yield return new object[] { 2.5, new TimeSpan(2, 12, 0, 0) };
yield return new object[] { 1.0, new TimeSpan(1, 0, 0, 0) };
yield return new object[] { 0.0, new TimeSpan(0, 0, 0, 0) };
yield return new object[] { -1.0, new TimeSpan(-1, 0, 0, 0) };
yield return new object[] { -2.5, new TimeSpan(-2, -12, 0, 0) };
yield return new object[] { -100.5, new TimeSpan(-100, -12, 0, 0) };
}
[Theory]
[MemberData(nameof(FromDays_TestData))]
public static void FromDays(double value, TimeSpan expected)
{
Assert.Equal(expected, TimeSpan.FromDays(value));
}
[Fact]
public static void FromDays_Invalid()
{
double maxDays = long.MaxValue / (TimeSpan.TicksPerMillisecond / 1000.0 / 60.0 / 60.0 / 24.0);
Assert.Throws<OverflowException>(() => TimeSpan.FromDays(double.PositiveInfinity)); // Value is positive infinity
Assert.Throws<OverflowException>(() => TimeSpan.FromDays(double.NegativeInfinity)); // Value is positive infinity
Assert.Throws<OverflowException>(() => TimeSpan.FromDays(maxDays)); // Value > TimeSpan.MaxValue
Assert.Throws<OverflowException>(() => TimeSpan.FromDays(-maxDays)); // Value < TimeSpan.MinValue
Assert.Throws<ArgumentException>(null, () => TimeSpan.FromMinutes(double.NaN)); // Value is NaN
}
public static IEnumerable<object[]> FromHours_TestData()
{
yield return new object[] { 100.5, new TimeSpan(4, 4, 30, 0) };
yield return new object[] { 2.5, new TimeSpan(2, 30, 0) };
yield return new object[] { 1.0, new TimeSpan(1, 0, 0) };
yield return new object[] { 0.0, new TimeSpan(0, 0, 0) };
yield return new object[] { -1.0, new TimeSpan(-1, 0, 0) };
yield return new object[] { -2.5, new TimeSpan(-2, -30, 0) };
yield return new object[] { -100.5, new TimeSpan(-4, -4, -30, 0) };
}
[Theory]
[MemberData(nameof(FromHours_TestData))]
public static void FromHours(double value, TimeSpan expected)
{
Assert.Equal(expected, TimeSpan.FromHours(value));
}
[Fact]
public static void FromHours_Invalid()
{
double maxHours = long.MaxValue / (TimeSpan.TicksPerMillisecond / 1000.0 / 60.0 / 60.0);
Assert.Throws<OverflowException>(() => TimeSpan.FromHours(double.PositiveInfinity)); // Value is positive infinity
Assert.Throws<OverflowException>(() => TimeSpan.FromHours(double.NegativeInfinity)); // Value is positive infinity
Assert.Throws<OverflowException>(() => TimeSpan.FromHours(maxHours)); // Value > TimeSpan.MaxValue
Assert.Throws<OverflowException>(() => TimeSpan.FromHours(-maxHours)); // Value < TimeSpan.MinValue
Assert.Throws<ArgumentException>(null, () => TimeSpan.FromMinutes(double.NaN)); // Value is NaN
}
public static IEnumerable<object[]> FromMinutes_TestData()
{
yield return new object[] { 100.5, new TimeSpan(1, 40, 30) };
yield return new object[] { 2.5, new TimeSpan(0, 2, 30) };
yield return new object[] { 1.0, new TimeSpan(0, 1, 0) };
yield return new object[] { 0.0, new TimeSpan(0, 0, 0) };
yield return new object[] { -1.0, new TimeSpan(0, -1, 0) };
yield return new object[] { -2.5, new TimeSpan(0, -2, -30) };
yield return new object[] { -100.5, new TimeSpan(-1, -40, -30) };
}
[Theory]
[MemberData(nameof(FromMinutes_TestData))]
public static void FromMinutes(double value, TimeSpan expected)
{
Assert.Equal(expected, TimeSpan.FromMinutes(value));
}
[Fact]
public static void FromMinutes_Invalid()
{
double maxMinutes = long.MaxValue / (TimeSpan.TicksPerMillisecond / 1000.0 / 60.0);
Assert.Throws<OverflowException>(() => TimeSpan.FromMinutes(double.PositiveInfinity)); // Value is positive infinity
Assert.Throws<OverflowException>(() => TimeSpan.FromMinutes(double.NegativeInfinity)); // Value is positive infinity
Assert.Throws<OverflowException>(() => TimeSpan.FromMinutes(maxMinutes)); // Value > TimeSpan.MaxValue
Assert.Throws<OverflowException>(() => TimeSpan.FromMinutes(-maxMinutes)); // Value < TimeSpan.MinValue
Assert.Throws<ArgumentException>(null, () => TimeSpan.FromMinutes(double.NaN)); // Value is NaN
}
public static IEnumerable<object[]> FromSeconds_TestData()
{
yield return new object[] { 100.5, new TimeSpan(0, 0, 1, 40, 500) };
yield return new object[] { 2.5, new TimeSpan(0, 0, 0, 2, 500) };
yield return new object[] { 1.0, new TimeSpan(0, 0, 0, 1, 0) };
yield return new object[] { 0.0, new TimeSpan(0, 0, 0, 0, 0) };
yield return new object[] { -1.0, new TimeSpan(0, 0, 0, -1, 0) };
yield return new object[] { -2.5, new TimeSpan(0, 0, 0, -2, -500) };
yield return new object[] { -100.5, new TimeSpan(0, 0, -1, -40, -500) };
}
[Theory]
[MemberData(nameof(FromSeconds_TestData))]
public static void FromSeconds(double value, TimeSpan expected)
{
Assert.Equal(expected, TimeSpan.FromSeconds(value));
}
[Fact]
public static void FromSeconds_Invalid()
{
double maxSeconds = long.MaxValue / (TimeSpan.TicksPerMillisecond / 1000.0);
Assert.Throws<OverflowException>(() => TimeSpan.FromSeconds(double.PositiveInfinity)); // Value is positive infinity
Assert.Throws<OverflowException>(() => TimeSpan.FromSeconds(double.NegativeInfinity)); // Value is positive infinity
Assert.Throws<OverflowException>(() => TimeSpan.FromSeconds(maxSeconds)); // Value > TimeSpan.MaxValue
Assert.Throws<OverflowException>(() => TimeSpan.FromSeconds(-maxSeconds)); // Value < TimeSpan.MinValue
Assert.Throws<ArgumentException>(null, () => TimeSpan.FromSeconds(double.NaN)); // Value is NaN
}
public static IEnumerable<object[]> FromMilliseconds_TestData()
{
yield return new object[] { 1500.5, new TimeSpan(0, 0, 0, 1, 501) };
yield return new object[] { 2.5, new TimeSpan(0, 0, 0, 0, 3) };
yield return new object[] { 1.0, new TimeSpan(0, 0, 0, 0, 1) };
yield return new object[] { 0.0, new TimeSpan(0, 0, 0, 0, 0) };
yield return new object[] { -1.0, new TimeSpan(0, 0, 0, 0, -1) };
yield return new object[] { -2.5, new TimeSpan(0, 0, 0, 0, -3) };
yield return new object[] { -1500.5, new TimeSpan(0, 0, 0, -1, -501) };
}
[Theory]
[MemberData(nameof(FromMilliseconds_TestData))]
public static void FromMilliseconds(double value, TimeSpan expected)
{
Assert.Equal(expected, TimeSpan.FromMilliseconds(value));
}
[Fact]
public static void FromMilliseconds_Invalid()
{
double maxMilliseconds = long.MaxValue / TimeSpan.TicksPerMillisecond;
Assert.Throws<OverflowException>(() => TimeSpan.FromMilliseconds(double.PositiveInfinity)); // Value is positive infinity
Assert.Throws<OverflowException>(() => TimeSpan.FromMilliseconds(double.NegativeInfinity)); // Value is positive infinity
Assert.Throws<OverflowException>(() => TimeSpan.FromMilliseconds(maxMilliseconds)); // Value > TimeSpan.MaxValue
Assert.Throws<OverflowException>(() => TimeSpan.FromMilliseconds(-maxMilliseconds)); // Value < TimeSpan.MinValue
Assert.Throws<ArgumentException>(null, () => TimeSpan.FromMilliseconds(double.NaN)); // Value is NaN
}
public static IEnumerable<object[]> FromTicks_TestData()
{
yield return new object[] { TimeSpan.TicksPerMillisecond, new TimeSpan(0, 0, 0, 0, 1) };
yield return new object[] { TimeSpan.TicksPerSecond, new TimeSpan(0, 0, 0, 1, 0) };
yield return new object[] { TimeSpan.TicksPerMinute, new TimeSpan(0, 0, 1, 0, 0) };
yield return new object[] { TimeSpan.TicksPerHour, new TimeSpan(0, 1, 0, 0, 0) };
yield return new object[] { TimeSpan.TicksPerDay, new TimeSpan(1, 0, 0, 0, 0) };
yield return new object[] { 1.0, new TimeSpan(1) };
yield return new object[] { 0.0, new TimeSpan(0, 0, 0) };
yield return new object[] { -1.0, new TimeSpan(-1) };
yield return new object[] { -TimeSpan.TicksPerMillisecond, new TimeSpan(0, 0, 0, 0, -1) };
yield return new object[] { -TimeSpan.TicksPerSecond, new TimeSpan(0, 0, 0, -1, 0) };
yield return new object[] { -TimeSpan.TicksPerMinute, new TimeSpan(0, 0, -1, 0, 0) };
yield return new object[] { -TimeSpan.TicksPerHour, new TimeSpan(0, -1, 0, 0, 0) };
yield return new object[] { -TimeSpan.TicksPerDay, new TimeSpan(-1, 0, 0, 0, 0) };
}
[Theory]
[MemberData(nameof(FromTicks_TestData))]
public static void FromTicks(long value, TimeSpan expected)
{
Assert.Equal(expected, TimeSpan.FromTicks(value));
}
public static IEnumerable<object[]> Negate_TestData()
{
yield return new object[] { new TimeSpan(0, 0, 0), new TimeSpan(0, 0, 0) };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(-1, -2, -3) };
yield return new object[] { new TimeSpan(-1, -2, -3), new TimeSpan(1, 2, 3) };
yield return new object[] { new TimeSpan(12345), new TimeSpan(-12345) };
yield return new object[] { new TimeSpan(-12345), new TimeSpan(12345) };
}
[Theory]
[MemberData(nameof(Negate_TestData))]
public static void Negate(TimeSpan timeSpan, TimeSpan expected)
{
Assert.Equal(expected, timeSpan.Negate());
Assert.Equal(expected, -timeSpan);
}
[Fact]
public static void Negate_Invalid()
{
Assert.Throws<OverflowException>(() => TimeSpan.MinValue.Negate()); // TimeSpan.MinValue cannot be negated
Assert.Throws<OverflowException>(() => -TimeSpan.MinValue); // TimeSpan.MinValue cannot be negated
}
public static IEnumerable<object[]> Parse_Valid_TestData()
{
yield return new object[] { " 12:24:02", null, new TimeSpan(0, 12, 24, 2, 0) };
yield return new object[] { "12:24", null, new TimeSpan(0, 12, 24, 0, 0) };
yield return new object[] { "12:24:02", null, new TimeSpan(0, 12, 24, 2, 0) };
yield return new object[] { "1.12:24:02", null, new TimeSpan(1, 12, 24, 2, 0) };
yield return new object[] { "1:12:24:02", null, new TimeSpan(1, 12, 24, 2, 0) };
yield return new object[] { "1.12:24:02.999", null, new TimeSpan(1, 12, 24, 2, 999) };
yield return new object[] { "-12:24:02", null, new TimeSpan(0, -12, -24, -2, 0) };
yield return new object[] { "-1.12:24:02.999", null, new TimeSpan(-1, -12, -24, -2, -999) };
// Croatia uses ',' in place of '.'
CultureInfo croatianCulture = new CultureInfo("hr-HR");
yield return new object[] { "6:12:14:45,348", croatianCulture, new TimeSpan(6, 12, 14, 45, 348) };
}
[Theory]
[MemberData(nameof(Parse_Valid_TestData))]
public static void Parse(string input, IFormatProvider provider, TimeSpan expected)
{
TimeSpan result;
if (provider == null)
{
Assert.True(TimeSpan.TryParse(input, out result));
Assert.Equal(expected, result);
Assert.Equal(expected, TimeSpan.Parse(input));
}
Assert.True(TimeSpan.TryParse(input, provider, out result));
Assert.Equal(expected, result);
Assert.Equal(expected, TimeSpan.Parse(input, provider));
}
public static IEnumerable<object[]> Parse_Invalid_TestData()
{
yield return new object[] { null, null, typeof(ArgumentNullException) };
yield return new object[] { "", null, typeof(FormatException) };
yield return new object[] { "-", null, typeof(FormatException) };
yield return new object[] { "garbage", null, typeof(FormatException) };
yield return new object[] { "12/12/12", null, typeof(FormatException) };
yield return new object[] { "1:1:1.99999999", null, typeof(OverflowException) };
// Croatia uses ',' in place of '.'
CultureInfo croatianCulture = new CultureInfo("hr-HR");
yield return new object[] { "6:12:14:45.3448", croatianCulture, typeof(FormatException) };
}
[Theory]
[MemberData(nameof(Parse_Invalid_TestData))]
public static void Parse_Invalid(string input, IFormatProvider provider, Type exceptionType)
{
TimeSpan result;
if (provider == null)
{
Assert.False(TimeSpan.TryParse(input, out result));
Assert.Equal(TimeSpan.Zero, result);
Assert.Throws(exceptionType, () => TimeSpan.Parse(input));
}
Assert.False(TimeSpan.TryParse(input, provider, out result));
Assert.Equal(TimeSpan.Zero, result);
Assert.Throws(exceptionType, () => TimeSpan.Parse(input, provider));
}
public static IEnumerable<object[]> ParseExact_Valid_TestData()
{
// Standard timespan formats 'c', 'g', 'G'
yield return new object[] { "12:24:02", "c", new TimeSpan(0, 12, 24, 2) };
yield return new object[] { "1.12:24:02", "c", new TimeSpan(1, 12, 24, 2) };
yield return new object[] { "-01.07:45:16.999", "c", new TimeSpan(1, 7, 45, 16, 999).Negate() };
yield return new object[] { "12:24:02", "g", new TimeSpan(0, 12, 24, 2) };
yield return new object[] { "1:12:24:02", "g", new TimeSpan(1, 12, 24, 2) };
yield return new object[] { "-01:07:45:16.999", "g", new TimeSpan(1, 7, 45, 16, 999).Negate() };
yield return new object[] { "1:12:24:02.243", "G", new TimeSpan(1, 12, 24, 2, 243) };
yield return new object[] { "-01:07:45:16.999", "G", new TimeSpan(1, 7, 45, 16, 999).Negate() };
// Custom timespan formats
yield return new object[] { "12.23:32:43", @"dd\.h\:m\:s", new TimeSpan(12, 23, 32, 43) };
yield return new object[] { "012.23:32:43.893", @"ddd\.h\:m\:s\.fff", new TimeSpan(12, 23, 32, 43, 893) };
yield return new object[] { "12.05:02:03", @"d\.hh\:mm\:ss", new TimeSpan(12, 5, 2, 3) };
yield return new object[] { "12:34 minutes", @"mm\:ss\ \m\i\n\u\t\e\s", new TimeSpan(0, 12, 34) };
}
[Theory]
[MemberData(nameof(ParseExact_Valid_TestData))]
public static void ParseExact(string input, string format, TimeSpan expected)
{
TimeSpan result;
Assert.Equal(expected, TimeSpan.ParseExact(input, format, new CultureInfo("en-US")));
Assert.True(TimeSpan.TryParseExact(input, format, new CultureInfo("en-US"), out result));
Assert.Equal(expected, result);
// TimeSpanStyles is interpreted only for custom formats
if (format != "c" && format != "g" && format != "G")
{
Assert.Equal(expected.Negate(), TimeSpan.ParseExact(input, format, new CultureInfo("en-US"), TimeSpanStyles.AssumeNegative));
Assert.True(TimeSpan.TryParseExact(input, format, new CultureInfo("en-US"), TimeSpanStyles.AssumeNegative, out result));
Assert.Equal(expected.Negate(), result);
}
}
public static IEnumerable<object[]> ParseExact_Invalid_TestData()
{
yield return new object[] { null, "c", typeof(ArgumentNullException) };
yield return new object[] { "", "c", typeof(FormatException) };
yield return new object[] { "-", "c", typeof(FormatException) };
yield return new object[] { "garbage", "c", typeof(FormatException) };
// Standard timespan formats 'c', 'g', 'G'
yield return new object[] { "24:24:02", "c", typeof(OverflowException) };
yield return new object[] { "1:12:24:02", "c", typeof(FormatException) };
yield return new object[] { "12:61:02", "g", typeof(OverflowException) };
yield return new object[] { "1.12:24:02", "g", typeof(FormatException) };
yield return new object[] { "1:07:45:16.99999999", "G", typeof(OverflowException) };
yield return new object[] { "1:12:24:02", "G", typeof(FormatException) };
// Custom timespan formats
yield return new object[] { "12.35:32:43", @"dd\.h\:m\:s", typeof(OverflowException) };
yield return new object[] { "12.5:2:3", @"d\.hh\:mm\:ss", typeof(FormatException) };
yield return new object[] { "12.5:2", @"d\.hh\:mm\:ss", typeof(FormatException) };
}
[Theory]
[MemberData(nameof(ParseExact_Invalid_TestData))]
public static void ParseExactTest_Invalid(string input, string format, Type exceptionType)
{
Assert.Throws(exceptionType, () => TimeSpan.ParseExact(input, format, new CultureInfo("en-US")));
TimeSpan result;
Assert.False(TimeSpan.TryParseExact(input, format, new CultureInfo("en-US"), out result));
Assert.Equal(TimeSpan.Zero, result);
}
public static IEnumerable<object[]> Subtract_TestData()
{
yield return new object[] { new TimeSpan(0, 0, 0), new TimeSpan(1, 2, 3), new TimeSpan(-1, -2, -3) };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(4, 5, 6), new TimeSpan(-3, -3, -3) };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(-4, -5, -6), new TimeSpan(5, 7, 9) };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 3), new TimeSpan(1, 1, 1, 1, 5) };
yield return new object[] { new TimeSpan(10, 11, 12, 13, 14), new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(9, 9, 9, 9, 9) };
yield return new object[] { new TimeSpan(200000), new TimeSpan(10000), new TimeSpan(190000) };
}
[Theory]
[MemberData(nameof(Subtract_TestData))]
public static void Subtract(TimeSpan ts1, TimeSpan ts2, TimeSpan expected)
{
Assert.Equal(expected, ts1.Subtract(ts2));
Assert.Equal(expected, ts1 - ts2);
}
[Fact]
public static void Subtract_Invalid()
{
Assert.Throws<OverflowException>(() => TimeSpan.MaxValue.Subtract(new TimeSpan(-1))); // Result > TimeSpan.MaxValue
Assert.Throws<OverflowException>(() => TimeSpan.MinValue.Subtract(new TimeSpan(1))); // Result < TimeSpan.MinValue
Assert.Throws<OverflowException>(() => TimeSpan.MaxValue - new TimeSpan(-1)); // Result > TimeSpan.MaxValue
Assert.Throws<OverflowException>(() => TimeSpan.MinValue - new TimeSpan(1)); // Result < TimeSpan.MinValue
}
[Fact]
public static void ToStringTest()
{
var timeSpan1 = new TimeSpan(1, 2, 3);
var timeSpan2 = new TimeSpan(1, 2, 3);
var timeSpan3 = new TimeSpan(1, 2, 4);
var timeSpan4 = new TimeSpan(1, 2, 3, 4);
var timeSpan5 = new TimeSpan(1, 2, 3, 4);
var timeSpan6 = new TimeSpan(1, 2, 3, 5);
var timeSpan7 = new TimeSpan(1, 2, 3, 4, 5);
var timeSpan8 = new TimeSpan(1, 2, 3, 4, 5);
var timeSpan9 = new TimeSpan(1, 2, 3, 4, 6);
Assert.Equal(timeSpan1.ToString(), timeSpan2.ToString());
Assert.Equal(timeSpan1.ToString("c"), timeSpan2.ToString("c"));
Assert.Equal(timeSpan1.ToString("c", null), timeSpan2.ToString("c", null));
Assert.NotEqual(timeSpan1.ToString(), timeSpan3.ToString());
Assert.NotEqual(timeSpan1.ToString(), timeSpan4.ToString());
Assert.NotEqual(timeSpan1.ToString(), timeSpan7.ToString());
Assert.Equal(timeSpan4.ToString(), timeSpan5.ToString());
Assert.Equal(timeSpan4.ToString("c"), timeSpan5.ToString("c"));
Assert.Equal(timeSpan4.ToString("c", null), timeSpan5.ToString("c", null));
Assert.NotEqual(timeSpan4.ToString(), timeSpan6.ToString());
Assert.NotEqual(timeSpan4.ToString(), timeSpan7.ToString());
Assert.Equal(timeSpan7.ToString(), timeSpan8.ToString());
Assert.Equal(timeSpan7.ToString("c"), timeSpan8.ToString("c"));
Assert.Equal(timeSpan7.ToString("c", null), timeSpan8.ToString("c", null));
Assert.NotEqual(timeSpan7.ToString(), timeSpan9.ToString());
}
[Fact]
public static void ToString_InvalidFormat_ThrowsFormatException()
{
var timeSpan = new TimeSpan();
Assert.Throws<FormatException>(() => timeSpan.ToString("y")); // Invalid format
Assert.Throws<FormatException>(() => timeSpan.ToString("cc")); // Invalid format
}
private static void VerifyTimeSpan(TimeSpan timeSpan, int days, int hours, int minutes, int seconds, int milliseconds)
{
Assert.Equal(days, timeSpan.Days);
Assert.Equal(hours, timeSpan.Hours);
Assert.Equal(minutes, timeSpan.Minutes);
Assert.Equal(seconds, timeSpan.Seconds);
Assert.Equal(milliseconds, timeSpan.Milliseconds);
Assert.Equal(timeSpan, +timeSpan);
}
}
}
| |
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using DevExpress.CodeRush.Core;
using DevExpress.CodeRush.PlugInCore;
using DevExpress.CodeRush.StructuralParser;
namespace CR_StringFormatter
{
public partial class PlugIn1 : StandardPlugIn
{
// DXCore-generated code...
#region InitializePlugIn
public override void InitializePlugIn()
{
base.InitializePlugIn();
//
// TODO: Add your initialization code here.
//
}
#endregion
#region FinalizePlugIn
public override void FinalizePlugIn()
{
//
// TODO: Add your finalization code here.
//
base.FinalizePlugIn();
}
#endregion
#region IsStringFormatCall
public static bool IsStringFormatCall(IElement methodCallExpression)
{
IElement validMethodCallExpression = GetValidMethodCallExpression(methodCallExpression);
if (validMethodCallExpression == null)
return false;
IMethodReferenceExpression formatCall = (validMethodCallExpression as IWithSource).Source as IMethodReferenceExpression;
if (formatCall == null)
return false;
IExpression qualifier = formatCall.Source as IExpression;
if (qualifier == null)
return false;
if (!(qualifier is IReferenceExpression || qualifier is IThisReferenceExpression || qualifier is IBaseReferenceExpression))
return false;
string formatCallName = formatCall.Name;
List<string> expectedTypeNames = new List<string>();
if (formatCallName == "Format")
expectedTypeNames.Add("System.String");
else if (formatCallName == "AppendFormat")
expectedTypeNames.Add("System.Text.StringBuilder");
else if (formatCallName == "Write" || formatCall.Name == "WriteLine")
{
expectedTypeNames.Add("System.Console");
expectedTypeNames.Add("System.IO.TextWriter");
}
if (expectedTypeNames.Count > 0)
foreach (string expectedTypeName in expectedTypeNames)
{
ITypeElement qualifierDeclaration = qualifier.Resolve(ParserServices.SourceTreeResolver) as ITypeElement;
if (qualifierDeclaration != null && qualifierDeclaration.Is(expectedTypeName))
return true;
}
return false;
}
#endregion
private static IElement GetValidMethodCallExpression(IElement methodCallExpression)
{
if (methodCallExpression == null)
return null;
if (methodCallExpression is IAttributeVariableInitializer)
return methodCallExpression.Parent;
if (!(methodCallExpression is IWithArguments))
return null;
if (!(methodCallExpression is IWithSource))
return null;
return methodCallExpression;
}
#region InFirstStringArgument
private static bool InFirstStringArgument(LanguageElement element, int line, int offset)
{
PrimitiveExpression primitiveExpression = element as PrimitiveExpression;
if (primitiveExpression == null)
return false;
if (primitiveExpression.PrimitiveType != PrimitiveType.String)
return false;
LanguageElement methodCallExpression = primitiveExpression.Parent;
if (!IsStringFormatCall(methodCallExpression))
return false;
IExpression formatStringArgument = GetFormatStringArgument(methodCallExpression);
if (formatStringArgument == null)
return false;
return formatStringArgument.FirstNameRange.Contains(line, offset);
}
#endregion
private static IExpression GetFormatStringArgument(LanguageElement methodCallExpression)
{
if (methodCallExpression is IAttributeVariableInitializer)
methodCallExpression = methodCallExpression.Parent;
IHasArguments hasArguments = methodCallExpression as IHasArguments;
if (hasArguments == null)
return null;
if (hasArguments.ArgumentsCount <= 0)
return null;
IExpression firstArgument = hasArguments.Arguments[0];
if (IsPrimitiveExpressionArg(firstArgument))
return GetPrimitiveExpressionArg(firstArgument);
else if (hasArguments.ArgumentsCount > 1)
{
IExpression secondArgument = hasArguments.Arguments[1];
if (IsPrimitiveExpressionArg(secondArgument))
return GetPrimitiveExpressionArg(secondArgument);
}
return null;
}
public static bool IsPrimitiveExpressionArg(IExpression exp)
{
if (exp is IPrimitiveExpression)
return true;
IAttributeVariableInitializer attrInitializer = exp as IAttributeVariableInitializer;
if (attrInitializer != null)
return attrInitializer.RightSide is IPrimitiveExpression;
return false;
}
private static IPrimitiveExpression GetPrimitiveExpressionArg(IExpression exp)
{
if (exp is IPrimitiveExpression)
return exp as IPrimitiveExpression;
IAttributeVariableInitializer attrInitializer = exp as IAttributeVariableInitializer;
if (attrInitializer != null)
return attrInitializer.RightSide as IPrimitiveExpression;
return null;
}
private bool InFormatItem(LanguageElement element, int line, int offset)
{
if (!InFirstStringArgument(element, line, offset))
return false;
FormatItems formatItems = GetFormatItems(element as PrimitiveExpression);
return formatItems.GetFormatItemAtPos(line, offset) != null;
}
private void spFormatItems_CheckAvailability(object sender, CheckSearchAvailabilityEventArgs ea)
{
ea.Available = InFormatItem(ea.Element, ea.Caret.Line, ea.Caret.Offset);
}
private void spFormatItems_SearchReferences(object sender, SearchEventArgs ea)
{
int caretLine = ea.Caret.Line;
int caretOffset = ea.Caret.Offset;
if (!InFirstStringArgument(ea.Element, caretLine, caretOffset))
return;
FormatItems formatItems = GetFormatItems(ea.Element as PrimitiveExpression);
if (formatItems.Count == 0)
return;
ISourceFile sourceFile = formatItems.SourceFile;
FormatItemPos formatItemPos = formatItems.GetFormatItemPosAtPos(caretLine, caretOffset);
FormatItem formatItem = formatItemPos.Parent;
if (formatItem == null)
return;
// Add each occurrence of this format item to the navigation range...
foreach (FormatItemPos position in formatItem.Positions)
{
SourceRange sourceRange = position.GetSourceRange(caretLine);
ea.AddRange(new FileSourceRange(sourceFile, sourceRange));
}
if (formatItem.Argument != null)
ea.AddRange(new FileSourceRange(sourceFile, formatItem.Argument.FirstNameRange));
}
#region GetFormatItems
/// <summary>
/// Parses the text in the specified PrimitiveExpression, collecting and returning a dictionary of FormatItems, indexed by the format item number.
/// </summary>
public static FormatItems GetFormatItems(IPrimitiveExpression primitiveExpression)
{
FormatItems formatItems = new FormatItems();
formatItems.ParentMethodCall = GetValidMethodCallExpression(primitiveExpression.Parent) as IWithArguments;
int argumentCount = formatItems.ParentMethodCall.Args.Count;
formatItems.PrimitiveExpression = primitiveExpression;
if (primitiveExpression == null)
return formatItems;
string text = primitiveExpression.Value as string;
if (String.IsNullOrEmpty(text))
return formatItems;
bool lastCharWasOpenBrace = false;
bool insideFormatItem = false;
bool collectingFormatItemNumber = false;
string numberStr = String.Empty;
int lastOpenBraceOffset = 0;
int length = 0;
for (int i = 0; i < text.Length; i++)
{
char thisChar = text[i];
if (thisChar == '{')
{
lastCharWasOpenBrace = !lastCharWasOpenBrace;
lastOpenBraceOffset = i;
}
else if (thisChar == '}')
{
if (insideFormatItem)
{
insideFormatItem = false;
if (numberStr != String.Empty)
{
int number = int.Parse(numberStr);
const int INT_CountForBraceDelimeters = 2;
int argumentIndex = number + 1;
IExpression argument = null;
if (argumentIndex < argumentCount)
argument = formatItems.ParentMethodCall.Args[argumentIndex];
if (!formatItems.HasFormatItem(number))
formatItems.AddFormatItem(number, argument);
formatItems[number].AddPosition(lastOpenBraceOffset, length + INT_CountForBraceDelimeters);
}
}
}
else if (lastCharWasOpenBrace)
{
length = 0;
lastCharWasOpenBrace = false;
insideFormatItem = true;
collectingFormatItemNumber = true;
numberStr = String.Empty;
if (char.IsDigit(thisChar))
numberStr = thisChar.ToString(); // First digit...
}
else if (collectingFormatItemNumber)
{
if (char.IsDigit(thisChar))
numberStr += thisChar.ToString(); // Subsequent digit...
else
collectingFormatItemNumber = false;
}
length++;
}
return formatItems;
}
#endregion
#region ctxInFormatItem_ContextSatisfied
private void ctxInFormatItem_ContextSatisfied(ContextSatisfiedEventArgs ea)
{
ea.Satisfied = InFormatItem(CodeRush.Source.Active, CodeRush.Caret.Line, CodeRush.Caret.Offset);
}
#endregion
#region cpFormatItem_CheckAvailability
private void cpFormatItem_CheckAvailability(object sender, CheckContentAvailabilityEventArgs ea)
{
ea.Available = InFormatItem(ea.Element, ea.Caret.Line, ea.Caret.Offset);
}
#endregion
private FormatItemPos GetActivePosition(ApplyContentEventArgs ea)
{
int caretLine = ea.Caret.Line;
int caretOffset = ea.Caret.Offset;
if (!InFirstStringArgument(ea.Element, caretLine, caretOffset))
return null;
FormatItems formatItems = GetFormatItems(ea.Element as PrimitiveExpression);
return formatItems.GetFormatItemPosAtPos(caretLine, caretOffset);
}
#region GetFormatItemDetails
private static void GetFormatItemDetails(TextDocument textDocument, SourceRange formatItemRange, out string numberStr, out string alignment, out string format)
{
format = textDocument.GetText(formatItemRange);
alignment = String.Empty;
numberStr = String.Empty;
if (format.Length >= 3)
{
if (format[format.Length - 1] == '}')
format = format.Remove(format.Length - 1, 1);
if (format[0] == '{')
format = format.Remove(0, 1);
while (format.Length > 0 && char.IsDigit(format[0]))
{
numberStr += format[0];
format = format.Remove(0, 1);
}
if (format.StartsWith(","))
{
format = format.Remove(0, 1);
if (format.StartsWith("-"))
{
format = format.Remove(0, 1);
alignment = "-";
}
// Remove alignment text...
while (format.Length > 0 && char.IsDigit(format[0]))
{
alignment += format[0];
format = format.Remove(0, 1);
}
}
if (format.StartsWith(":"))
format = format.Remove(0, 1);
}
}
#endregion
private void cpFormatItem_Apply(object sender, ApplyContentEventArgs ea)
{
FormatItemPos activePosition;
activePosition = GetActivePosition(ea);
if (activePosition == null)
return;
FormatItems formatItems = activePosition.Parent.Parent;
int line = formatItems.PrimitiveExpression.FirstNameRange.Start.Line;
SourceRange formatItemRange = activePosition.GetSourceRange(line);
string number;
string alignment;
string format;
GetFormatItemDetails(ea.TextDocument, formatItemRange, out number, out alignment, out format);
using (FrmStringFormatter frmStringFormatter = new FrmStringFormatter())
{
if (number != String.Empty)
{
int argumentIndex = int.Parse(number) + 1;
IExpression argument = null;
IPrimitiveExpression primitiveExpression = null;
if (argumentIndex < formatItems.ParentMethodCall.Args.Count)
{
argument = formatItems.ParentMethodCall.Args[argumentIndex];
primitiveExpression = argument as IPrimitiveExpression;
}
if (primitiveExpression != null)
{
// Use primitiveExpression's PrimitiveType property
PrimitiveType primitiveType = primitiveExpression.PrimitiveType;
if (primitiveType == PrimitiveType.Single || primitiveType == PrimitiveType.Decimal || primitiveType == PrimitiveType.Double)
frmStringFormatter.FormatItemExpressionType = FormatItemExpressionType.DateTime;
else if (primitiveType == PrimitiveType.Char || primitiveType == PrimitiveType.String)
frmStringFormatter.FormatItemExpressionType = FormatItemExpressionType.String;
else if (primitiveType == PrimitiveType.SByte || primitiveType == PrimitiveType.Byte || primitiveType == PrimitiveType.Int16 || primitiveType == PrimitiveType.Int32 || primitiveType == PrimitiveType.Int64 || primitiveType == PrimitiveType.UInt16 || primitiveType == PrimitiveType.UInt32 || primitiveType == PrimitiveType.UInt64)
frmStringFormatter.FormatItemExpressionType = FormatItemExpressionType.Integer;
else
frmStringFormatter.FormatItemExpressionType = FormatItemExpressionType.Custom;
}
else
{
if (argument != null)
{
IElement resolve = argument.Resolve(ParserServices.SourceTreeResolver);
if (resolve.Name == "DateTime")
frmStringFormatter.FormatItemExpressionType = FormatItemExpressionType.DateTime;
else if (resolve.Name == "Double" || resolve.Name == "Single")
frmStringFormatter.FormatItemExpressionType = FormatItemExpressionType.Real;
else if (resolve.Name == "String")
frmStringFormatter.FormatItemExpressionType = FormatItemExpressionType.String;
else if (resolve.Name == "Int32" || resolve.Name == "Int64" || resolve.Name == "Int16")
frmStringFormatter.FormatItemExpressionType = FormatItemExpressionType.Integer;
else
{
// set default value...
}
}
else
{
frmStringFormatter.FormatItemExpressionType = FormatItemExpressionType.Integer;
}
}
}
frmStringFormatter.FormatString = format;
frmStringFormatter.AlignmentString = alignment;
if (frmStringFormatter.ShowDialog() == DialogResult.OK)
{
string newFormatItemCode = String.Format("{{{0}{1}:{2}}}", number, frmStringFormatter.AlignmentString, frmStringFormatter.FormatString);
ea.TextDocument.Replace(formatItemRange, newFormatItemCode, "Format Item");
}
}
}
private void ipFormatItemIndexTooLarge_CheckCodeIssues(object sender, CheckCodeIssuesEventArgs ea)
{
FormatItemTooLargeSearcher searcher = new FormatItemTooLargeSearcher(ipFormatItemIndexTooLarge.DisplayName);
searcher.CheckCodeIssues(ea);
}
public static Expression formatStringArgument { get; set; }
}
public class FormatItemTooLargeSearcher : BaseCodeIssueSearcher
{
private string _Message;
public FormatItemTooLargeSearcher(string message)
{
_Message = message;
}
public override void CheckCodeIssues(CheckCodeIssuesEventArgs ea)
{
IEnumerable<IElement> enumerable = ea.GetEnumerable(ea.Scope, new ElementTypeFilter(LanguageElementType.PrimitiveExpression));
foreach (IElement element in enumerable)
{
IPrimitiveExpression iPrimitiveExpression = element as IPrimitiveExpression;
if (iPrimitiveExpression != null)
{
if (iPrimitiveExpression.PrimitiveType == PrimitiveType.String)
{
IElement methodCallExpression = iPrimitiveExpression.Parent;
if (PlugIn1.IsStringFormatCall(methodCallExpression))
{
FormatItems formatItems = PlugIn1.GetFormatItems(iPrimitiveExpression);
if (formatItems.ParentMethodCall != null)
{
int argumentCount = GetValidArgumentsCount(formatItems);
foreach (FormatItem formatItem in formatItems.Values)
{
int argumentIndex = formatItem.Id + 1;
if (argumentIndex >= argumentCount)
{
int line = formatItems.PrimitiveExpression.FirstNameRange.Start.Line;
foreach (FormatItemPos position in formatItem.Positions)
ea.AddError(position.GetSourceRange(line), _Message);
}
}
}
}
}
}
}
}
private static int GetValidArgumentsCount(FormatItems formatItems)
{
if (formatItems == null)
return -1;
IWithArguments withArguments = formatItems.ParentMethodCall;
if (withArguments == null)
return -1;
int argsCount = withArguments.Args.Count;
if (argsCount > 0)
{
if (PlugIn1.IsPrimitiveExpressionArg(withArguments.Args[0]))
return argsCount;
else
return argsCount - 1; // skip IFormatter argument...
}
return -1;
}
}
}
| |
using NBitcoin;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using WalletWasabi.Blockchain.Analysis.Clustering;
using WalletWasabi.Blockchain.Transactions;
using WalletWasabi.Helpers;
using WalletWasabi.Models;
using WalletWasabi.Tests.Helpers;
using Xunit;
namespace WalletWasabi.Tests.UnitTests.Transactions
{
public class AllTransactionStoreTests
{
#region Helpers
private static SmartTransaction CreateTransaction(int height, uint256 blockHash)
{
var tx = Network.RegTest.CreateTransaction();
tx.Version = 1;
tx.LockTime = LockTime.Zero;
tx.Inputs.Add(new OutPoint(RandomUtils.GetUInt256(), 0), new Script(OpcodeType.OP_0, OpcodeType.OP_0), sequence: Sequence.Final);
tx.Outputs.Add(Money.Coins(1), Script.Empty);
return new SmartTransaction(tx, new Height(height), blockHash);
}
private void PrepareTestEnv(out string dir, out Network network, out string mempoolFile, out string txFile, out SmartTransaction uTx1, out SmartTransaction uTx2, out SmartTransaction uTx3, out SmartTransaction cTx1, out SmartTransaction cTx2, out SmartTransaction cTx3, [CallerFilePath] string callerFilePath = "", [CallerMemberName] string callerMemberName = "")
{
dir = PrepareWorkDir(EnvironmentHelpers.ExtractFileName(callerFilePath), callerMemberName);
network = Network.TestNet;
mempoolFile = Path.Combine(dir, "Mempool", "Transactions.dat");
txFile = Path.Combine(dir, "ConfirmedTransactions", Constants.ConfirmedTransactionsVersion, "Transactions.dat");
IoHelpers.EnsureContainingDirectoryExists(mempoolFile);
IoHelpers.EnsureContainingDirectoryExists(txFile);
uTx1 = SmartTransaction.FromLine("34fc45781f2ac8e541b6045c2858c755dd2ab85e0ea7b5778b4d0cc191468571:01000000000102d5ae6e2612cdf8932d0e4f684d8ad9afdbca0afffba5c3dc0bf85f2b661bfb670000000000ffffffffbfd117908d5ba536624630519aaea7419605efa33bf1cb50c5ff7441f7b27a5b0100000000ffffffff01c6473d0000000000160014f9d25fe27812c3d35ad3819fcab8b95098effe15024730440220165730f8275434a5484b6aba3c71338a109b7cfd7380fdc18c6791a6afba9dee0220633b3b65313e57bdbd491d17232e6702912869d81461b4c939600d1cc99c06ec012102667c9fb272660cd6c06f853314b53c41da851f86024f9475ff15ea0636f564130247304402205e81562139231274cd7f705772c2810e34b7a291bd9882e6c567553babca9c7402206554ebd60d62a605a27bd4bf6482a533dd8dd35b12dc9d6abfa21738fdf7b57a012102b25dec5439a1aad8d901953a90d16252514a55f547fe2b85bc12e3f72cff1c4b00000000:Mempool::0::1570464578:False", network);
uTx2 = SmartTransaction.FromLine("b5cd5b4431891d913a6fbc0e946798b6f730c8b97f95a5c730c24189bed24ce7:01000000010113145dd6264da43406a0819b6e2d791ec9281322f33944ef034c3307f38c330000000000ffffffff0220a10700000000001600149af662cf9564700b93bd46fac8b51f64f2adad2343a5070000000000160014f1938902267eac1ae527128fe7773657d2b757b900000000:Mempool::0::1555590391:False", network);
uTx3 = SmartTransaction.FromLine("89e6788e63c5966fae0ccf6e85665ec62754f982b9593d7e3c4b78ac0e93208d:01000000000101f3e7c1bce1e0566800d8e6cae8f0d771a2ace8939cc6be7c8c21b05e590969530000000000ffffffff01cc2b0f0000000000160014e0ff6f42032bbfda63fabe0832b4ccb7be7350ae024730440220791e34413957c0f8348718d5d767f660657faf241801e74b5b81ac69e8912f60022041f3e9aeca137044565e1a81b6bcca74a88166436e5fa5f0e390448ac18fa5900121034dc07f3c26734591eb97f7e112888c3198d62bc3718106cba5a5688c62485b4500000000:Mempool::0::1555590448:False", network);
cTx1 = SmartTransaction.FromLine("95374c1037eb5268c8ae6681eb26756459d19754d41b660c251e6f62df586d29:0100000001357852bdf4e75a4ee2afe213463ff8afbed977ea5459a310777322504254ffdf0100000000ffffffff0240420f0000000000160014dc992214c430bf306fe446e9bac1dfc4ad4d3ee368cc100300000000160014005340d370675c47f7a04eb186200dd98c3d463c00000000:1580176:0000000034522ee38f074e1f4330b9c2f20c6a2b9a96de6f474a5f5f8fa76e2b:307::1569940579:False", network);
cTx2 = SmartTransaction.FromLine("af73b4c173da1bd24063e35a755babfa40728a282d6f56eeef4ce5a81ab26ee7:01000000013c81d2dcb25ad36781d1a6f9faa68f4a8b927f40e0b4e4b6184bb4761ebfc0dd0000000000ffffffff016f052e0000000000160014ae6e31ee9dae103f50979f761c2f9b44661da24f00000000:1580176:0000000034522ee38f074e1f4330b9c2f20c6a2b9a96de6f474a5f5f8fa76e2b:346::1569940633:False", network);
cTx3 = SmartTransaction.FromLine("ebcef423f6b03ef89dce076b53e624c966381f76e5d8b2b5034d3615ae950b2f:01000000000101296d58df626f1e250c661bd45497d159647526eb8166aec86852eb37104c37950100000000ffffffff01facb100300000000160014d5461e0e7077d62c4cf9c18a4e9ba10efd4930340247304402206d2c5b2b182474531ed07587e44ea22b136a37d5ddbd35aa2d984da7be5f7e5202202abd8435d9856e3d0892dbd54e9c05f2a20d9d5f333247314b925947a480a2eb01210321dd0574c773a35d4a7ebf17bf8f974b5665c0183598f1db53153e74c876768500000000:1580673:0000000017b09a77b815f3df513ff698d1f3b0e8c5e16ac0d6558e2d831f3bf9:130::1570462988:False", network);
}
private string PrepareWorkDir([CallerFilePath] string callerFilePath = "", [CallerMemberName] string callerMemberName = "")
{
string dir = Path.Combine(Common.GetWorkDir(callerFilePath, callerMemberName));
if (Directory.Exists(dir))
{
Directory.Delete(dir, true);
}
return dir;
}
public static IEnumerable<object[]> GetDifferentNetworkValues()
{
var networks = new List<Network>
{
Network.Main,
Network.TestNet,
Network.RegTest
};
foreach (Network network in networks)
{
yield return new object[] { network };
}
}
#endregion Helpers
[Theory]
[MemberData(nameof(GetDifferentNetworkValues))]
public async Task CanInitializeEmptyAsync(Network network)
{
var dir = PrepareWorkDir();
await using var txStore = new AllTransactionStore(dir, network);
await txStore.InitializeAsync(ensureBackwardsCompatibility: false);
Assert.NotNull(txStore.ConfirmedStore);
Assert.NotNull(txStore.MempoolStore);
Assert.Empty(txStore.GetTransactions());
Assert.Empty(txStore.GetTransactionHashes());
Assert.Empty(txStore.MempoolStore.GetTransactions());
Assert.Empty(txStore.MempoolStore.GetTransactionHashes());
Assert.Empty(txStore.ConfirmedStore.GetTransactions());
Assert.Empty(txStore.ConfirmedStore.GetTransactionHashes());
uint256 txHash = BitcoinFactory.CreateSmartTransaction().GetHash();
Assert.False(txStore.Contains(txHash));
Assert.True(txStore.IsEmpty());
Assert.False(txStore.TryGetTransaction(txHash, out _));
var mempoolFile = Path.Combine(dir, "Mempool", "Transactions.dat");
var txFile = Path.Combine(dir, "ConfirmedTransactions", Constants.ConfirmedTransactionsVersion, "Transactions.dat");
var mempoolContent = await File.ReadAllBytesAsync(mempoolFile);
var txContent = await File.ReadAllBytesAsync(txFile);
Assert.True(File.Exists(mempoolFile));
Assert.True(File.Exists(txFile));
Assert.Empty(mempoolContent);
Assert.Empty(txContent);
}
[Fact]
public async Task CanInitializeAsync()
{
string dir = PrepareWorkDir();
var network = Network.TestNet;
var mempoolFile = Path.Combine(dir, "Mempool", "Transactions.dat");
var txFile = Path.Combine(dir, "ConfirmedTransactions", Constants.ConfirmedTransactionsVersion, "Transactions.dat");
IoHelpers.EnsureContainingDirectoryExists(mempoolFile);
IoHelpers.EnsureContainingDirectoryExists(txFile);
var uTx1 = SmartTransaction.FromLine("34fc45781f2ac8e541b6045c2858c755dd2ab85e0ea7b5778b4d0cc191468571:01000000000102d5ae6e2612cdf8932d0e4f684d8ad9afdbca0afffba5c3dc0bf85f2b661bfb670000000000ffffffffbfd117908d5ba536624630519aaea7419605efa33bf1cb50c5ff7441f7b27a5b0100000000ffffffff01c6473d0000000000160014f9d25fe27812c3d35ad3819fcab8b95098effe15024730440220165730f8275434a5484b6aba3c71338a109b7cfd7380fdc18c6791a6afba9dee0220633b3b65313e57bdbd491d17232e6702912869d81461b4c939600d1cc99c06ec012102667c9fb272660cd6c06f853314b53c41da851f86024f9475ff15ea0636f564130247304402205e81562139231274cd7f705772c2810e34b7a291bd9882e6c567553babca9c7402206554ebd60d62a605a27bd4bf6482a533dd8dd35b12dc9d6abfa21738fdf7b57a012102b25dec5439a1aad8d901953a90d16252514a55f547fe2b85bc12e3f72cff1c4b00000000:Mempool::0::1570464578:False", network);
var uTx2 = SmartTransaction.FromLine("b5cd5b4431891d913a6fbc0e946798b6f730c8b97f95a5c730c24189bed24ce7:01000000010113145dd6264da43406a0819b6e2d791ec9281322f33944ef034c3307f38c330000000000ffffffff0220a10700000000001600149af662cf9564700b93bd46fac8b51f64f2adad2343a5070000000000160014f1938902267eac1ae527128fe7773657d2b757b900000000:Mempool::0::1555590391:False", network);
var uTx3 = SmartTransaction.FromLine("89e6788e63c5966fae0ccf6e85665ec62754f982b9593d7e3c4b78ac0e93208d:01000000000101f3e7c1bce1e0566800d8e6cae8f0d771a2ace8939cc6be7c8c21b05e590969530000000000ffffffff01cc2b0f0000000000160014e0ff6f42032bbfda63fabe0832b4ccb7be7350ae024730440220791e34413957c0f8348718d5d767f660657faf241801e74b5b81ac69e8912f60022041f3e9aeca137044565e1a81b6bcca74a88166436e5fa5f0e390448ac18fa5900121034dc07f3c26734591eb97f7e112888c3198d62bc3718106cba5a5688c62485b4500000000:Mempool::0::1555590448:False", network);
var cTx1 = SmartTransaction.FromLine("95374c1037eb5268c8ae6681eb26756459d19754d41b660c251e6f62df586d29:0100000001357852bdf4e75a4ee2afe213463ff8afbed977ea5459a310777322504254ffdf0100000000ffffffff0240420f0000000000160014dc992214c430bf306fe446e9bac1dfc4ad4d3ee368cc100300000000160014005340d370675c47f7a04eb186200dd98c3d463c00000000:1580176:0000000034522ee38f074e1f4330b9c2f20c6a2b9a96de6f474a5f5f8fa76e2b:307::1569940579:False", network);
var cTx2 = SmartTransaction.FromLine("af73b4c173da1bd24063e35a755babfa40728a282d6f56eeef4ce5a81ab26ee7:01000000013c81d2dcb25ad36781d1a6f9faa68f4a8b927f40e0b4e4b6184bb4761ebfc0dd0000000000ffffffff016f052e0000000000160014ae6e31ee9dae103f50979f761c2f9b44661da24f00000000:1580176:0000000034522ee38f074e1f4330b9c2f20c6a2b9a96de6f474a5f5f8fa76e2b:346::1569940633:False", network);
var cTx3 = SmartTransaction.FromLine("ebcef423f6b03ef89dce076b53e624c966381f76e5d8b2b5034d3615ae950b2f:01000000000101296d58df626f1e250c661bd45497d159647526eb8166aec86852eb37104c37950100000000ffffffff01facb100300000000160014d5461e0e7077d62c4cf9c18a4e9ba10efd4930340247304402206d2c5b2b182474531ed07587e44ea22b136a37d5ddbd35aa2d984da7be5f7e5202202abd8435d9856e3d0892dbd54e9c05f2a20d9d5f333247314b925947a480a2eb01210321dd0574c773a35d4a7ebf17bf8f974b5665c0183598f1db53153e74c876768500000000:1580673:0000000017b09a77b815f3df513ff698d1f3b0e8c5e16ac0d6558e2d831f3bf9:130::1570462988:False", network);
var mempoolFileContent = new[]
{
uTx1.ToLine(),
uTx2.ToLine(),
uTx3.ToLine()
};
var txFileContent = new[]
{
cTx1.ToLine(),
cTx2.ToLine(),
cTx3.ToLine()
};
await File.WriteAllLinesAsync(mempoolFile, mempoolFileContent);
await File.WriteAllLinesAsync(txFile, txFileContent);
await using var txStore = new AllTransactionStore(dir, network);
await txStore.InitializeAsync(ensureBackwardsCompatibility: false);
Assert.Equal(6, txStore.GetTransactions().Count());
Assert.Equal(6, txStore.GetTransactionHashes().Count());
Assert.Equal(3, txStore.MempoolStore.GetTransactions().Count());
Assert.Equal(3, txStore.MempoolStore.GetTransactionHashes().Count());
Assert.Equal(3, txStore.ConfirmedStore.GetTransactions().Count());
Assert.Equal(3, txStore.ConfirmedStore.GetTransactionHashes().Count());
Assert.False(txStore.IsEmpty());
uint256 doesntContainTxHash = BitcoinFactory.CreateSmartTransaction().GetHash();
Assert.False(txStore.Contains(doesntContainTxHash));
Assert.False(txStore.TryGetTransaction(doesntContainTxHash, out _));
Assert.True(txStore.Contains(uTx1.GetHash()));
Assert.True(txStore.Contains(uTx2.GetHash()));
Assert.True(txStore.Contains(uTx3.GetHash()));
Assert.True(txStore.Contains(cTx2.GetHash()));
Assert.True(txStore.Contains(cTx2.GetHash()));
Assert.True(txStore.Contains(cTx3.GetHash()));
Assert.True(txStore.TryGetTransaction(uTx1.GetHash(), out SmartTransaction uTx1Same));
Assert.True(txStore.TryGetTransaction(uTx2.GetHash(), out SmartTransaction uTx2Same));
Assert.True(txStore.TryGetTransaction(uTx3.GetHash(), out SmartTransaction uTx3Same));
Assert.True(txStore.TryGetTransaction(cTx1.GetHash(), out SmartTransaction cTx1Same));
Assert.True(txStore.TryGetTransaction(cTx2.GetHash(), out SmartTransaction cTx2Same));
Assert.True(txStore.TryGetTransaction(cTx3.GetHash(), out SmartTransaction cTx3Same));
Assert.Equal(uTx1, uTx1Same);
Assert.Equal(uTx2, uTx2Same);
Assert.Equal(uTx3, uTx3Same);
Assert.Equal(cTx1, cTx1Same);
Assert.Equal(cTx2, cTx2Same);
Assert.Equal(cTx3, cTx3Same);
}
[Fact]
public async Task CorrectsMempoolConfSeparateDupAsync()
{
PrepareTestEnv(out string dir, out Network network, out string mempoolFile, out string txFile, out SmartTransaction uTx1, out SmartTransaction uTx2, out SmartTransaction uTx3, out SmartTransaction cTx1, out SmartTransaction cTx2, out SmartTransaction cTx3);
// Duplication in mempoool and confirmedtxs.
var mempoolFileContent = new[]
{
uTx1.ToLine(),
uTx2.ToLine(),
uTx3.ToLine(),
uTx2.ToLine()
};
var txFileContent = new[]
{
cTx1.ToLine(),
cTx2.ToLine(),
cTx3.ToLine(),
cTx3.ToLine()
};
await File.WriteAllLinesAsync(mempoolFile, mempoolFileContent);
await File.WriteAllLinesAsync(txFile, txFileContent);
await using var txStore = new AllTransactionStore(dir, network);
await txStore.InitializeAsync(ensureBackwardsCompatibility: false);
Assert.Equal(6, txStore.GetTransactions().Count());
Assert.Equal(6, txStore.GetTransactionHashes().Count());
Assert.Equal(3, txStore.MempoolStore.GetTransactions().Count());
Assert.Equal(3, txStore.MempoolStore.GetTransactionHashes().Count());
Assert.Equal(3, txStore.ConfirmedStore.GetTransactions().Count());
Assert.Equal(3, txStore.ConfirmedStore.GetTransactionHashes().Count());
}
[Fact]
public async Task CorrectsLabelDupAsync()
{
PrepareTestEnv(out string dir, out Network network, out string mempoolFile, out string txFile, out SmartTransaction uTx1, out SmartTransaction uTx2, out SmartTransaction uTx3, out SmartTransaction cTx1, out SmartTransaction cTx2, out SmartTransaction cTx3);
// Duplication is resolved with labels merged.
var mempoolFileContent = new[]
{
new SmartTransaction(uTx1.Transaction, uTx1.Height, label: "buz, qux").ToLine(),
new SmartTransaction(uTx2.Transaction, uTx2.Height, label: "buz, qux").ToLine(),
new SmartTransaction(uTx2.Transaction, uTx2.Height, label: "foo, bar").ToLine(),
uTx3.ToLine(),
new SmartTransaction(cTx1.Transaction, Height.Mempool, label: new SmartLabel("buz", "qux")).ToLine()
};
var txFileContent = new[]
{
new SmartTransaction(cTx1.Transaction, cTx1.Height, label: new SmartLabel("foo", "bar")).ToLine(),
cTx2.ToLine(),
cTx3.ToLine(),
new SmartTransaction(uTx1.Transaction, new Height(2), label: "foo, bar").ToLine()
};
await File.WriteAllLinesAsync(mempoolFile, mempoolFileContent);
await File.WriteAllLinesAsync(txFile, txFileContent);
await using var txStore = new AllTransactionStore(dir, network);
await txStore.InitializeAsync(ensureBackwardsCompatibility: false);
Assert.Equal(6, txStore.GetTransactions().Count());
Assert.Equal(2, txStore.MempoolStore.GetTransactions().Count());
Assert.Equal(4, txStore.ConfirmedStore.GetTransactions().Count());
Assert.True(txStore.MempoolStore.Contains(uTx2.GetHash()));
Assert.True(txStore.ConfirmedStore.Contains(uTx1.GetHash()));
Assert.True(txStore.ConfirmedStore.Contains(cTx1.GetHash()));
Assert.True(txStore.TryGetTransaction(uTx1.GetHash(), out _));
Assert.True(txStore.TryGetTransaction(uTx2.GetHash(), out _));
Assert.True(txStore.TryGetTransaction(cTx1.GetHash(), out _));
}
[Fact]
public async Task CorrectsMempoolConfBetweenDupAsync()
{
PrepareTestEnv(out string dir, out Network network, out string mempoolFile, out string txFile, out SmartTransaction uTx1, out SmartTransaction uTx2, out SmartTransaction uTx3, out SmartTransaction cTx1, out SmartTransaction cTx2, out SmartTransaction cTx3);
// Duplication between mempool and confirmed txs.
var mempoolFileContent = new[]
{
uTx1.ToLine(),
uTx2.ToLine(),
uTx3.ToLine(),
new SmartTransaction(cTx1.Transaction, Height.Mempool).ToLine()
};
var txFileContent = new[]
{
cTx1.ToLine(),
cTx2.ToLine(),
cTx3.ToLine(),
new SmartTransaction(uTx1.Transaction, new Height(2)).ToLine()
};
await File.WriteAllLinesAsync(mempoolFile, mempoolFileContent);
await File.WriteAllLinesAsync(txFile, txFileContent);
await using var txStore = new AllTransactionStore(dir, network);
await txStore.InitializeAsync(ensureBackwardsCompatibility: false);
Assert.Equal(6, txStore.GetTransactions().Count());
Assert.Equal(2, txStore.MempoolStore.GetTransactions().Count());
Assert.Equal(4, txStore.ConfirmedStore.GetTransactions().Count());
}
[Fact]
public async Task CorrectsOrderAsync()
{
string dir = PrepareWorkDir();
var network = Network.TestNet;
var mempoolFile = Path.Combine(dir, "Mempool", "Transactions.dat");
var txFile = Path.Combine(dir, "ConfirmedTransactions", Constants.ConfirmedTransactionsVersion, "Transactions.dat");
IoHelpers.EnsureContainingDirectoryExists(mempoolFile);
IoHelpers.EnsureContainingDirectoryExists(txFile);
var uTx1 = SmartTransaction.FromLine("34fc45781f2ac8e541b6045c2858c755dd2ab85e0ea7b5778b4d0cc191468571:01000000000102d5ae6e2612cdf8932d0e4f684d8ad9afdbca0afffba5c3dc0bf85f2b661bfb670000000000ffffffffbfd117908d5ba536624630519aaea7419605efa33bf1cb50c5ff7441f7b27a5b0100000000ffffffff01c6473d0000000000160014f9d25fe27812c3d35ad3819fcab8b95098effe15024730440220165730f8275434a5484b6aba3c71338a109b7cfd7380fdc18c6791a6afba9dee0220633b3b65313e57bdbd491d17232e6702912869d81461b4c939600d1cc99c06ec012102667c9fb272660cd6c06f853314b53c41da851f86024f9475ff15ea0636f564130247304402205e81562139231274cd7f705772c2810e34b7a291bd9882e6c567553babca9c7402206554ebd60d62a605a27bd4bf6482a533dd8dd35b12dc9d6abfa21738fdf7b57a012102b25dec5439a1aad8d901953a90d16252514a55f547fe2b85bc12e3f72cff1c4b00000000:Mempool::0::1570464578:False", network);
var uTx2 = SmartTransaction.FromLine("b5cd5b4431891d913a6fbc0e946798b6f730c8b97f95a5c730c24189bed24ce7:01000000010113145dd6264da43406a0819b6e2d791ec9281322f33944ef034c3307f38c330000000000ffffffff0220a10700000000001600149af662cf9564700b93bd46fac8b51f64f2adad2343a5070000000000160014f1938902267eac1ae527128fe7773657d2b757b900000000:Mempool::0::1555590391:False", network);
var uTx3 = SmartTransaction.FromLine("89e6788e63c5966fae0ccf6e85665ec62754f982b9593d7e3c4b78ac0e93208d:01000000000101f3e7c1bce1e0566800d8e6cae8f0d771a2ace8939cc6be7c8c21b05e590969530000000000ffffffff01cc2b0f0000000000160014e0ff6f42032bbfda63fabe0832b4ccb7be7350ae024730440220791e34413957c0f8348718d5d767f660657faf241801e74b5b81ac69e8912f60022041f3e9aeca137044565e1a81b6bcca74a88166436e5fa5f0e390448ac18fa5900121034dc07f3c26734591eb97f7e112888c3198d62bc3718106cba5a5688c62485b4500000000:Mempool::0::1555590448:False", network);
var cTx1 = SmartTransaction.FromLine("95374c1037eb5268c8ae6681eb26756459d19754d41b660c251e6f62df586d29:0100000001357852bdf4e75a4ee2afe213463ff8afbed977ea5459a310777322504254ffdf0100000000ffffffff0240420f0000000000160014dc992214c430bf306fe446e9bac1dfc4ad4d3ee368cc100300000000160014005340d370675c47f7a04eb186200dd98c3d463c00000000:1580176:0000000034522ee38f074e1f4330b9c2f20c6a2b9a96de6f474a5f5f8fa76e2b:307::1569940579:False", network);
var cTx2 = SmartTransaction.FromLine("af73b4c173da1bd24063e35a755babfa40728a282d6f56eeef4ce5a81ab26ee7:01000000013c81d2dcb25ad36781d1a6f9faa68f4a8b927f40e0b4e4b6184bb4761ebfc0dd0000000000ffffffff016f052e0000000000160014ae6e31ee9dae103f50979f761c2f9b44661da24f00000000:1580176:0000000034522ee38f074e1f4330b9c2f20c6a2b9a96de6f474a5f5f8fa76e2b:346::1569940633:False", network);
var cTx3 = SmartTransaction.FromLine("ebcef423f6b03ef89dce076b53e624c966381f76e5d8b2b5034d3615ae950b2f:01000000000101296d58df626f1e250c661bd45497d159647526eb8166aec86852eb37104c37950100000000ffffffff01facb100300000000160014d5461e0e7077d62c4cf9c18a4e9ba10efd4930340247304402206d2c5b2b182474531ed07587e44ea22b136a37d5ddbd35aa2d984da7be5f7e5202202abd8435d9856e3d0892dbd54e9c05f2a20d9d5f333247314b925947a480a2eb01210321dd0574c773a35d4a7ebf17bf8f974b5665c0183598f1db53153e74c876768500000000:1580673:0000000017b09a77b815f3df513ff698d1f3b0e8c5e16ac0d6558e2d831f3bf9:130::1570462988:False", network);
// Duplication in mempoool and confirmedtxs.
var mempoolFileContent = new[]
{
uTx2.ToLine(),
uTx1.ToLine(),
uTx3.ToLine()
};
var txFileContent = new[]
{
cTx3.ToLine(),
cTx1.ToLine(),
cTx2.ToLine()
};
await File.WriteAllLinesAsync(mempoolFile, mempoolFileContent);
await File.WriteAllLinesAsync(txFile, txFileContent);
var expectedArray = new[]
{
uTx1,
uTx2,
uTx3,
cTx1,
cTx2,
cTx3
}.OrderByBlockchain().ToList();
await using (var txStore = new AllTransactionStore(dir, network))
{
await txStore.InitializeAsync(ensureBackwardsCompatibility: false);
var txs = txStore.GetTransactions();
var txHashes = txStore.GetTransactionHashes();
Assert.Equal(txHashes, txs.Select(x => x.GetHash()));
Assert.Equal(expectedArray, txs);
}
await using (var txStore = new AllTransactionStore(PrepareWorkDir(), network))
{
await txStore.InitializeAsync(ensureBackwardsCompatibility: false);
txStore.AddOrUpdate(uTx3);
txStore.AddOrUpdate(uTx1);
txStore.AddOrUpdate(uTx2);
txStore.AddOrUpdate(cTx3);
txStore.AddOrUpdate(cTx1);
txStore.AddOrUpdate(cTx2);
var txs = txStore.GetTransactions();
var txHashes = txStore.GetTransactionHashes();
Assert.Equal(txHashes, txs.Select(x => x.GetHash()));
Assert.Equal(expectedArray, txs);
}
}
[Theory]
[MemberData(nameof(GetDifferentNetworkValues))]
public async Task DoesntUpdateAsync(Network network)
{
await using var txStore = new AllTransactionStore(PrepareWorkDir(), network);
await txStore.InitializeAsync(ensureBackwardsCompatibility: false);
var tx = BitcoinFactory.CreateSmartTransaction();
Assert.False(txStore.TryUpdate(tx));
// Assert TryUpdate didn't modify anything.
Assert.NotNull(txStore.ConfirmedStore);
Assert.NotNull(txStore.MempoolStore);
Assert.Empty(txStore.GetTransactions());
Assert.Empty(txStore.GetTransactionHashes());
Assert.Empty(txStore.MempoolStore.GetTransactions());
Assert.Empty(txStore.MempoolStore.GetTransactionHashes());
Assert.Empty(txStore.ConfirmedStore.GetTransactions());
Assert.Empty(txStore.ConfirmedStore.GetTransactionHashes());
uint256 txHash = BitcoinFactory.CreateSmartTransaction().GetHash();
Assert.False(txStore.Contains(txHash));
Assert.True(txStore.IsEmpty());
Assert.False(txStore.TryGetTransaction(txHash, out _));
}
[Fact]
public async Task ReorgAsync()
{
PrepareTestEnv(
out string dir,
out Network network,
out string mempoolFile,
out string txFile,
out SmartTransaction uTx1,
out SmartTransaction uTx2,
out SmartTransaction uTx3,
out SmartTransaction _,
out SmartTransaction cTx2,
out SmartTransaction cTx3);
// Duplication is resolved with labels merged.
var mempoolFileContent = new[]
{
uTx1.ToLine(),
uTx2.ToLine(),
uTx3.ToLine(),
};
var txFileContent = new[]
{
cTx2.ToLine(),
cTx3.ToLine()
};
await File.WriteAllLinesAsync(mempoolFile, mempoolFileContent);
await File.WriteAllLinesAsync(txFile, txFileContent);
await using var txStore = new AllTransactionStore(dir, network);
await txStore.InitializeAsync(ensureBackwardsCompatibility: false);
// Two transactions are in the mempool store and unconfirmed.
Assert.True(txStore.MempoolStore.TryGetTransaction(uTx1.GetHash(), out SmartTransaction myUnconfirmedTx1));
Assert.False(myUnconfirmedTx1.Confirmed);
Assert.True(txStore.MempoolStore.TryGetTransaction(uTx2.GetHash(), out SmartTransaction myUnconfirmedTx2));
Assert.False(myUnconfirmedTx2.Confirmed);
// Create the same transaction but now with a Height to make it confirmed.
const int ReorgedBlockHeight = 34532;
uint256 reorgedBlockHash = new uint256(5);
var tx1Confirmed = new SmartTransaction(uTx1.Transaction, new Height(ReorgedBlockHeight), blockHash: reorgedBlockHash, label: "buz, qux");
var tx2Confirmed = new SmartTransaction(uTx2.Transaction, new Height(ReorgedBlockHeight), blockHash: reorgedBlockHash, label: "buz, qux");
Assert.True(txStore.TryUpdate(tx1Confirmed));
Assert.True(txStore.TryUpdate(tx2Confirmed));
// Two transactions are in the ConfirmedStore store and confirmed.
Assert.True(txStore.ConfirmedStore.TryGetTransaction(uTx1.GetHash(), out SmartTransaction mytx1));
Assert.False(txStore.MempoolStore.TryGetTransaction(uTx1.GetHash(), out _));
Assert.True(mytx1.Confirmed);
Assert.True(txStore.ConfirmedStore.TryGetTransaction(uTx2.GetHash(), out SmartTransaction mytx2));
Assert.False(txStore.MempoolStore.TryGetTransaction(uTx2.GetHash(), out _));
Assert.True(mytx2.Confirmed);
// Now reorg.
txStore.ReleaseToMempoolFromBlock(reorgedBlockHash);
// Two transactions are in the mempool store and unconfirmed.
Assert.True(txStore.MempoolStore.TryGetTransaction(uTx1.GetHash(), out SmartTransaction myReorgedTx1));
Assert.False(txStore.ConfirmedStore.TryGetTransaction(uTx1.GetHash(), out _));
Assert.False(myReorgedTx1.Confirmed);
Assert.True(txStore.MempoolStore.TryGetTransaction(uTx2.GetHash(), out SmartTransaction myReorgedTx2));
Assert.False(txStore.ConfirmedStore.TryGetTransaction(uTx2.GetHash(), out _));
Assert.False(myReorgedTx2.Confirmed);
}
[Fact]
public async Task ReorgSameBlockAgainAsync()
{
int blocks = 300;
int transactionsPerBlock = 3;
string dir = PrepareWorkDir();
var network = Network.Main;
await using var txStore = new AllTransactionStore(dir, network);
await txStore.InitializeAsync(ensureBackwardsCompatibility: false);
foreach (var height in Enumerable.Range(1, blocks))
{
var blockHash = RandomUtils.GetUInt256();
foreach (var n in Enumerable.Range(0, transactionsPerBlock))
{
txStore.AddOrUpdate(CreateTransaction(height, blockHash));
}
}
var storedTxs = txStore.GetTransactions();
Assert.Equal(blocks * transactionsPerBlock, storedTxs.Count());
var newestConfirmedTx = storedTxs.Last();
var tipHeight = blocks;
var tipHash = newestConfirmedTx.BlockHash;
Assert.Equal(tipHeight, newestConfirmedTx.Height.Value);
// reorgs non-existing block
var reorgedTxs = txStore.ReleaseToMempoolFromBlock(RandomUtils.GetUInt256());
Assert.Empty(reorgedTxs);
// reorgs most recent block
reorgedTxs = txStore.ReleaseToMempoolFromBlock(newestConfirmedTx.BlockHash);
Assert.Equal(3, reorgedTxs.Count());
Assert.All(reorgedTxs, tx => Assert.False(tx.Confirmed));
Assert.All(reorgedTxs, tx => Assert.True(txStore.TryGetTransaction(tx.GetHash(), out _)));
Assert.False(txStore.TryGetTransaction(tipHash, out _));
Assert.DoesNotContain(tipHash, txStore.GetTransactionHashes());
// reorgs the same block again
reorgedTxs = txStore.ReleaseToMempoolFromBlock(newestConfirmedTx.BlockHash);
Assert.Empty(reorgedTxs);
Assert.False(txStore.TryGetTransaction(tipHash, out _));
Assert.DoesNotContain(tipHash, txStore.GetTransactionHashes());
// reorgs deep block
var oldestConfirmedTx = storedTxs.First();
var firstBlockHash = oldestConfirmedTx.BlockHash;
// What to do here
reorgedTxs = txStore.ReleaseToMempoolFromBlock(firstBlockHash);
Assert.NotEmpty(reorgedTxs);
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="IncrementalHitTester.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Ink;
using System.Windows.Media;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using MS.Internal.Ink;
using MS.Utility;
using MS.Internal;
using System.Diagnostics;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
namespace System.Windows.Ink
{
#region IncrementalHitTester Abstract Base Class
/// <summary>
/// This class serves as both the base class and public interface for
/// incremental hit-testing implementaions.
/// </summary>
public abstract class IncrementalHitTester
{
#region Public API
/// <summary>
/// Adds a point representing an incremental move of the hit-testing tool
/// </summary>
/// <param name="point">a point that represents an incremental move of the hitting tool</param>
public void AddPoint(Point point)
{
AddPoints(new Point[1] { point });
}
/// <summary>
/// Adds an array of points representing an incremental move of the hit-testing tool
/// </summary>
/// <param name="points">points representing an incremental move of the hitting tool</param>
public void AddPoints(IEnumerable<Point> points)
{
if (points == null)
{
throw new System.ArgumentNullException("points");
}
if (IEnumerablePointHelper.GetCount(points) == 0)
{
throw new System.ArgumentException(SR.Get(SRID.EmptyArrayNotAllowedAsArgument), "points");
}
if (false == _fValid)
{
throw new System.InvalidOperationException(SR.Get(SRID.EndHitTestingCalled));
}
System.Diagnostics.Debug.Assert(_strokes != null);
AddPointsCore(points);
}
/// <summary>
/// Adds a StylusPacket representing an incremental move of the hit-testing tool
/// </summary>
/// <param name="stylusPoints">stylusPoints</param>
public void AddPoints(StylusPointCollection stylusPoints)
{
if (stylusPoints == null)
{
throw new System.ArgumentNullException("stylusPoints");
}
if (stylusPoints.Count == 0)
{
throw new System.ArgumentException(SR.Get(SRID.EmptyArrayNotAllowedAsArgument), "stylusPoints");
}
if (false == _fValid)
{
throw new System.InvalidOperationException(SR.Get(SRID.EndHitTestingCalled));
}
System.Diagnostics.Debug.Assert(_strokes != null);
Point[] points = new Point[stylusPoints.Count];
for (int x = 0; x < stylusPoints.Count; x++)
{
points[x] = (Point)stylusPoints[x];
}
AddPointsCore(points);
}
/// <summary>
/// Release as many resources as possible for this enumerator
/// </summary>
public void EndHitTesting()
{
if (_strokes != null)
{
// Detach the event handler
_strokes.StrokesChangedInternal -= new StrokeCollectionChangedEventHandler(OnStrokesChanged);
_strokes = null;
int count = _strokeInfos.Count;
for ( int i = 0; i < count; i++)
{
_strokeInfos[i].Detach();
}
_strokeInfos = null;
}
_fValid = false;
}
/// <summary>
/// Accessor to see if the Hit Tester is still valid
/// </summary>
public bool IsValid { get { return _fValid; } }
#endregion
#region Internal
/// <summary>
/// C-tor.
/// </summary>
/// <param name="strokes">strokes to hit-test</param>
internal IncrementalHitTester(StrokeCollection strokes)
{
System.Diagnostics.Debug.Assert(strokes != null);
// Create a StrokeInfo object for each stroke.
_strokeInfos = new List<StrokeInfo>(strokes.Count);
for (int x = 0; x < strokes.Count; x++)
{
Stroke stroke = strokes[x];
_strokeInfos.Add(new StrokeInfo(stroke));
}
_strokes = strokes;
// Attach an event handler to the strokes' changed event
_strokes.StrokesChangedInternal += new StrokeCollectionChangedEventHandler(OnStrokesChanged);
}
/// <summary>
/// The implementation behind AddPoint/AddPoints.
/// Derived classes are supposed to override this method.
/// </summary>
protected abstract void AddPointsCore(IEnumerable<Point> points);
/// <summary>
/// Accessor to the internal collection of StrokeInfo objects
/// </summary>
internal List<StrokeInfo> StrokeInfos { get { return _strokeInfos; } }
#endregion
#region Private
/// <summary>
/// Event handler associated with the stroke collection.
/// </summary>
/// <param name="sender">Stroke collection that was modified</param>
/// <param name="args">Modification that occurred</param>
/// <remarks>
/// Update our _strokeInfos cache. We get notified on StrokeCollection.StrokesChangedInternal which
/// is raised first so we can assume we're the first delegate in the call chain
/// </remarks>
private void OnStrokesChanged(object sender, StrokeCollectionChangedEventArgs args)
{
System.Diagnostics.Debug.Assert((_strokes != null) && (_strokeInfos != null) && (_strokes == sender));
StrokeCollection added = args.Added;
StrokeCollection removed = args.Removed;
if (added.Count > 0)
{
int firstIndex = _strokes.IndexOf(added[0]);
for (int i = 0; i < added.Count; i++)
{
_strokeInfos.Insert(firstIndex, new StrokeInfo(added[i]));
firstIndex++;
}
}
if (removed.Count > 0)
{
StrokeCollection localRemoved = new StrokeCollection(removed);
//we have to assume that removed strokes can be in any order in _strokes
for (int i = 0; i < _strokeInfos.Count && localRemoved.Count > 0; )
{
bool found = false;
for (int j = 0; j < localRemoved.Count; j++)
{
if (localRemoved[j] == _strokeInfos[i].Stroke)
{
_strokeInfos.RemoveAt(i);
localRemoved.RemoveAt(j);
found = true;
}
}
//we didn't find a removed stroke at index i in _strokeInfos, so advance i
if (!found)
{
i++;
}
}
}
//validate our cache
if (_strokes.Count != _strokeInfos.Count)
{
Debug.Assert(false, "Benign assert. IncrementalHitTester's _strokeInfos cache is out of [....], rebuilding.");
RebuildStrokeInfoCache();
return;
}
for (int i = 0; i < _strokeInfos.Count; i++)
{
if (_strokeInfos[i].Stroke != _strokes[i])
{
Debug.Assert(false, "Benign assert. IncrementalHitTester's _strokeInfos cache is out of [....], rebuilding.");
RebuildStrokeInfoCache();
return;
}
}
}
/// <summary>
/// IHT's can get into a state where their StrokeInfo cache is too
/// out of [....] with the StrokeCollection to incrementally update it.
/// When we detect this has happened, we just rebuild the entire cache.
/// </summary>
private void RebuildStrokeInfoCache()
{
List<StrokeInfo> newStrokeInfos = new List<StrokeInfo>(_strokes.Count);
foreach (Stroke stroke in _strokes)
{
bool found = false;
for (int x = 0; x < _strokeInfos.Count; x++)
{
StrokeInfo strokeInfo = _strokeInfos[x];
if (strokeInfo != null && stroke == strokeInfo.Stroke)
{
newStrokeInfos.Add(strokeInfo);
//just set to null instead of removing and shifting
//we're about to GC _strokeInfos
_strokeInfos[x] = null;
found = true;
break;
}
}
if (!found)
{
//we didn't find an existing strokeInfo
newStrokeInfos.Add(new StrokeInfo(stroke));
}
}
//detach the remaining strokeInfo's from their strokes
for (int x = 0; x < _strokeInfos.Count; x++)
{
StrokeInfo strokeInfo = _strokeInfos[x];
if (strokeInfo != null)
{
strokeInfo.Detach();
}
}
_strokeInfos = newStrokeInfos;
#if DEBUG
Debug.Assert(_strokeInfos.Count == _strokes.Count);
for (int x = 0; x < _strokeInfos.Count; x++)
{
Debug.Assert(_strokeInfos[x].Stroke == _strokes[x]);
}
#endif
}
#endregion
#region Fields
/// <summary> Reference to the stroke collection under test </summary>
private StrokeCollection _strokes;
/// <summary> A collection of helper objects mapped to the stroke colection</summary>
private List<StrokeInfo> _strokeInfos;
private bool _fValid = true;
#endregion
}
#endregion
#region IncrementalLassoHitTester
/// <summary>
/// IncrementalHitTester implementation for hit-testing with lasso
/// </summary>
public class IncrementalLassoHitTester : IncrementalHitTester
{
#region public APIs
/// <summary>
/// Event
/// </summary>
public event LassoSelectionChangedEventHandler SelectionChanged;
#endregion
#region C-tor and the overrides
/// <summary>
/// C-tor.
/// </summary>
/// <param name="strokes">strokes to hit-test</param>
/// <param name="percentageWithinLasso">a hit-testing parameter that defines the minimal
/// percent of nodes of a stroke to be inside the lasso to consider the stroke hit</param>
internal IncrementalLassoHitTester(StrokeCollection strokes, int percentageWithinLasso)
: base(strokes)
{
System.Diagnostics.Debug.Assert((percentageWithinLasso >= 0) && (percentageWithinLasso <= 100));
_lasso = new SingleLoopLasso();
_percentIntersect = percentageWithinLasso;
}
/// <summary>
/// The implementation behind the public methods AddPoint/AddPoints
/// </summary>
/// <param name="points">new points to add to the lasso</param>
protected override void AddPointsCore(IEnumerable<Point> points)
{
System.Diagnostics.Debug.Assert((points != null) && (IEnumerablePointHelper.GetCount(points)!= 0));
// Add the new points to the lasso
int lastPointIndex = (0 != _lasso.PointCount) ? (_lasso.PointCount - 1) : 0;
_lasso.AddPoints(points);
// Do nothing if there's not enough points, or there's nobody listening
// The points may be filtered out, so if all the points are filtered out, (lastPointIndex == (_lasso.PointCount - 1).
// For this case, check if the incremental lasso is disabled (i.e., points modified).
if ((_lasso.IsEmpty) || (lastPointIndex == (_lasso.PointCount - 1) && false == _lasso.IsIncrementalLassoDirty)
|| (SelectionChanged == null))
{
return;
}
// Variables for possible HitChanged events to fire
StrokeCollection strokesHit = null;
StrokeCollection strokesUnhit = null;
// Create a lasso that represents the current increment
Lasso lassoUpdate = new Lasso();
if (false == _lasso.IsIncrementalLassoDirty)
{
if (0 < lastPointIndex)
{
lassoUpdate.AddPoint(_lasso[0]);
}
// Only the points the have been successfully added to _lasso will be added to
// lassoUpdate.
for (; lastPointIndex < _lasso.PointCount; lastPointIndex++)
{
lassoUpdate.AddPoint(_lasso[lastPointIndex]);
}
}
// Enumerate through the strokes and update their hit-test results
foreach (StrokeInfo strokeInfo in this.StrokeInfos)
{
Lasso lasso;
if (true == strokeInfo.IsDirty || true == _lasso.IsIncrementalLassoDirty)
{
// If this is the first time this stroke gets hit-tested with this lasso,
// or if the stroke (or its DAs) has changed since the last hit-testing,
// or if the lasso points have been modified,
// then (re)hit-test this stroke against the entire lasso.
lasso = _lasso;
strokeInfo.IsDirty = false;
}
else
{
// Otherwise, hit-test it against the lasso increment first and then only
// those ink points that are in that small lasso need to be hit-tested
// against the big (entire) lasso.
// This is supposed to be a significant piece of optimization, since
// lasso increments are usually very small, they are defined by just
// a few points and they don't capture and/or release too many ink nodes.
lasso = lassoUpdate;
}
// Skip those stroke which bounding box doesn't even intersects with the lasso bounds
double hitWeightChange = 0f;
if (lasso.Bounds.IntersectsWith(strokeInfo.StrokeBounds))
{
// Get the stroke node points for the hit-testing.
StylusPointCollection stylusPoints = strokeInfo.StylusPoints;
// Find out if the lasso update has changed the hit count of the stroke.
for (int i = 0; i < stylusPoints.Count; i++)
{
// Consider only the points that become captured/released with this particular update
if (true == lasso.Contains((Point)stylusPoints[i]))
{
double weight = strokeInfo.GetPointWeight(i);
if (lasso == _lasso || _lasso.Contains((Point)stylusPoints[i]))
{
hitWeightChange += weight;
}
else
{
hitWeightChange -= weight;
}
}
}
}
// Update the stroke hit weight and check whether it has crossed the margin
// in either direction since the last update.
if ((hitWeightChange != 0) || (lasso == _lasso))
{
strokeInfo.HitWeight = (lasso == _lasso) ? hitWeightChange : (strokeInfo.HitWeight + hitWeightChange);
bool isHit = DoubleUtil.GreaterThanOrClose(strokeInfo.HitWeight, strokeInfo.TotalWeight * _percentIntersect / 100f - Stroke.PercentageTolerance);
if (strokeInfo.IsHit != isHit)
{
strokeInfo.IsHit = isHit;
if (isHit)
{
// The hit count became greater than the margin percentage, the stroke
// needs to be reported for selection
if (null == strokesHit)
{
strokesHit = new StrokeCollection();
}
strokesHit.Add(strokeInfo.Stroke);
}
else
{
// The hit count just became less than the margin percentage,
// the stroke needs to be reported for de-selection
if (null == strokesUnhit)
{
strokesUnhit = new StrokeCollection();
}
strokesUnhit.Add(strokeInfo.Stroke);
}
}
}
}
_lasso.IsIncrementalLassoDirty = false;
// Raise StrokesHitChanged event if any strokes has changed thier
// hit status and there're the event subscribers.
if ((null != strokesHit) || (null != strokesUnhit))
{
OnSelectionChanged(new LassoSelectionChangedEventArgs (strokesHit, strokesUnhit));
}
}
/// <summary>
/// SelectionChanged event raiser
/// </summary>
/// <param name="eventArgs"></param>
protected void OnSelectionChanged(LassoSelectionChangedEventArgs eventArgs)
{
System.Diagnostics.Debug.Assert(eventArgs != null);
if (SelectionChanged != null)
{
SelectionChanged(this, eventArgs);
}
}
#endregion
#region Fields
private Lasso _lasso;
private int _percentIntersect;
#endregion
}
#endregion
#region IncrementalStrokeHitTester
/// <summary>
/// IncrementalHitTester implementation for hit-testing with a shape, PointErasing .
/// </summary>
public class IncrementalStrokeHitTester : IncrementalHitTester
{
/// <summary>
///
/// </summary>
public event StrokeHitEventHandler StrokeHit;
#region C-tor and the overrides
/// <summary>
/// C-tor
/// </summary>
/// <param name="strokes">strokes to hit-test for erasing</param>
/// <param name="eraserShape">erasing shape</param>
internal IncrementalStrokeHitTester(StrokeCollection strokes, StylusShape eraserShape)
: base(strokes)
{
System.Diagnostics.Debug.Assert(eraserShape != null);
// Create an ErasingStroke objects that implements the actual hit-testing
_erasingStroke = new ErasingStroke(eraserShape);
}
/// <summary>
/// The implementation behind the public methods AddPoint/AddPoints
/// </summary>
/// <param name="points">a set of points representing the last increment
/// in the moving of the erasing shape</param>
protected override void AddPointsCore(IEnumerable<Point> points)
{
System.Diagnostics.Debug.Assert((points != null) && (IEnumerablePointHelper.GetCount(points) != 0));
System.Diagnostics.Debug.Assert(_erasingStroke != null);
// Move the shape through the new points and build the contour of the move.
_erasingStroke.MoveTo(points);
Rect erasingBounds = _erasingStroke.Bounds;
if (erasingBounds.IsEmpty)
{
return;
}
List<StrokeHitEventArgs> strokeHitEventArgCollection = null;
// Do nothing if there's nobody listening to the events
if (StrokeHit != null)
{
List<StrokeIntersection> eraseAt = new List<StrokeIntersection>();
// Test stroke by stroke and collect the results.
for (int x = 0; x < this.StrokeInfos.Count; x++)
{
StrokeInfo strokeInfo = this.StrokeInfos[x];
// Skip the stroke if its bounding box doesn't intersect with the one of the hitting shape.
if ((erasingBounds.IntersectsWith(strokeInfo.StrokeBounds) == false) ||
(_erasingStroke.EraseTest(StrokeNodeIterator.GetIterator(strokeInfo.Stroke, strokeInfo.Stroke.DrawingAttributes), eraseAt) == false))
{
continue;
}
// Create an event args to raise after done with hit-testing
// We don't fire these events right away because user is expected to
// modify the stroke collection in her event handler, and that would
// invalidate this foreach loop.
if (strokeHitEventArgCollection == null)
{
strokeHitEventArgCollection = new List<StrokeHitEventArgs>();
}
strokeHitEventArgCollection.Add(new StrokeHitEventArgs(strokeInfo.Stroke, eraseAt.ToArray()));
// We must clear eraseAt or it will contain invalid results for the next strokes
eraseAt.Clear();
}
}
// Raise StrokeHit event if needed.
if (strokeHitEventArgCollection != null)
{
System.Diagnostics.Debug.Assert(strokeHitEventArgCollection.Count != 0);
for (int x = 0; x < strokeHitEventArgCollection.Count; x++)
{
StrokeHitEventArgs eventArgs = strokeHitEventArgCollection[x];
System.Diagnostics.Debug.Assert(eventArgs.HitStroke != null);
OnStrokeHit(eventArgs);
}
}
}
/// <summary>
/// Event raiser for StrokeHit
/// </summary>
protected void OnStrokeHit(StrokeHitEventArgs eventArgs)
{
System.Diagnostics.Debug.Assert(eventArgs != null);
if (StrokeHit != null)
{
StrokeHit(this, eventArgs);
}
}
#endregion
#region Fields
private ErasingStroke _erasingStroke;
#endregion
}
#endregion
#region EventArgs and delegates
/// <summary>
/// Declaration for LassoSelectionChanged event handler. Used in lasso-selection
/// </summary>
public delegate void LassoSelectionChangedEventHandler(object sender, LassoSelectionChangedEventArgs e);
/// <summary>
/// Declaration for StrokeHit event handler. Used in point-erasing
/// </summary>
public delegate void StrokeHitEventHandler(object sender, StrokeHitEventArgs e);
/// <summary>
/// Event arguments for LassoSelectionChanged event
/// </summary>
public class LassoSelectionChangedEventArgs : EventArgs
{
internal LassoSelectionChangedEventArgs(StrokeCollection selectedStrokes, StrokeCollection deselectedStrokes)
{
_selectedStrokes = selectedStrokes;
_deselectedStrokes = deselectedStrokes;
}
/// <summary>
/// Collection of strokes which were hit with the last increment
/// </summary>
public StrokeCollection SelectedStrokes
{
get
{
if (_selectedStrokes != null)
{
StrokeCollection sc = new StrokeCollection();
sc.Add(_selectedStrokes);
return sc;
}
else
{
return new StrokeCollection();
}
}
}
/// <summary>
/// Collection of strokes which were unhit with the last increment
/// </summary>
public StrokeCollection DeselectedStrokes
{
get
{
if (_deselectedStrokes != null)
{
StrokeCollection sc = new StrokeCollection();
sc.Add(_deselectedStrokes);
return sc;
}
else
{
return new StrokeCollection();
}
}
}
private StrokeCollection _selectedStrokes;
private StrokeCollection _deselectedStrokes;
}
/// <summary>
/// Event arguments for StrokeHit event
/// </summary>
public class StrokeHitEventArgs : EventArgs
{
/// <summary>
/// C-tor
/// </summary>
internal StrokeHitEventArgs(Stroke stroke, StrokeIntersection[] hitFragments)
{
System.Diagnostics.Debug.Assert(stroke != null && hitFragments != null && hitFragments.Length > 0);
_stroke = stroke;
_hitFragments = hitFragments;
}
/// <summary>Stroke that was hit</summary>
public Stroke HitStroke { get { return _stroke; } }
/// <summary>
///
/// </summary>
/// <returns></returns>
public StrokeCollection GetPointEraseResults()
{
return _stroke.Erase(_hitFragments);
}
private Stroke _stroke;
private StrokeIntersection[] _hitFragments;
}
#endregion
}
namespace MS.Internal.Ink
{
#region StrokeInfo
/// <summary>
/// A helper class associated with a stroke. Used for caching the stroke's
/// bounding box, hit-testing results, and for keeping an eye on the stroke changes
/// </summary>
internal class StrokeInfo
{
#region API (used by incremental hit-testers)
/// <summary>
/// StrokeInfo
/// </summary>
internal StrokeInfo(Stroke stroke)
{
System.Diagnostics.Debug.Assert(stroke != null);
_stroke = stroke;
_bounds = stroke.GetBounds();
// Start listening to the stroke events
_stroke.DrawingAttributesChanged += new PropertyDataChangedEventHandler(OnStrokeDrawingAttributesChanged);
_stroke.StylusPointsReplaced += new StylusPointsReplacedEventHandler(OnStylusPointsReplaced);
_stroke.StylusPoints.Changed += new EventHandler(OnStylusPointsChanged);
_stroke.DrawingAttributesReplaced += new DrawingAttributesReplacedEventHandler(OnDrawingAttributesReplaced);
}
/// <summary>The stroke object associated with this helper structure</summary>
internal Stroke Stroke { get { return _stroke; } }
/// <summary>Pre-calculated bounds of the stroke </summary>
internal Rect StrokeBounds { get { return _bounds; } }
/// <summary>Tells whether the stroke or its drawing attributes have been modified
/// since the last use (hit-testing)</summary>
internal bool IsDirty
{
get { return _isDirty; }
set { _isDirty = value; }
}
/// <summary>Tells whether the stroke was found (and reported) as hit </summary>
internal bool IsHit
{
get { return _isHit; }
set { _isHit = value; }
}
/// <summary>
/// Cache teh stroke points
/// </summary>
internal StylusPointCollection StylusPoints
{
get
{
if (_stylusPoints == null)
{
if (_stroke.DrawingAttributes.FitToCurve)
{
_stylusPoints = _stroke.GetBezierStylusPoints();
}
else
{
_stylusPoints = _stroke.StylusPoints;
}
}
return _stylusPoints;
}
}
/// <summary>
/// Holds the current hit-testing result for the stroke. Represents the length of
/// the stroke "inside" and "hit" by the lasso
/// </summary>
internal double HitWeight
{
get { return _hitWeight; }
set
{
// it is ok to clamp this off, rounding error sends it over or under by a minimal amount.
if (DoubleUtil.GreaterThan(value, TotalWeight))
{
_hitWeight = TotalWeight;
}
else if (DoubleUtil.LessThan(value, 0f))
{
_hitWeight = 0f;
}
else
{
_hitWeight = value;
}
}
}
/// <summary>
/// Get the total weight of the stroke. For this implementation, it is the total length of the stroke.
/// </summary>
/// <returns></returns>
internal double TotalWeight
{
get
{
if (!_totalWeightCached)
{
_totalWeight= 0;
for (int i = 0; i < StylusPoints.Count; i++)
{
_totalWeight += this.GetPointWeight(i);
}
_totalWeightCached = true;
}
return _totalWeight;
}
}
/// <summary>
/// Calculate the weight of a point.
/// </summary>
internal double GetPointWeight(int index)
{
StylusPointCollection stylusPoints = this.StylusPoints;
DrawingAttributes da = this.Stroke.DrawingAttributes;
System.Diagnostics.Debug.Assert(stylusPoints != null && index >= 0 && index < stylusPoints.Count);
double weight = 0f;
if (index == 0)
{
weight += Math.Sqrt(da.Width*da.Width + da.Height*da.Height) / 2.0f;
}
else
{
Vector spine = (Point)stylusPoints[index] - (Point)stylusPoints[index - 1];
weight += Math.Sqrt(spine.LengthSquared) / 2.0f;
}
if (index == stylusPoints.Count - 1)
{
weight += Math.Sqrt(da.Width*da.Width + da.Height*da.Height) / 2.0f;
}
else
{
Vector spine = (Point)stylusPoints[index + 1] - (Point)stylusPoints[index];
weight += Math.Sqrt(spine.LengthSquared) / 2.0f;
}
return weight;
}
/// <summary>
/// A kind of disposing method
/// </summary>
internal void Detach()
{
if (_stroke != null)
{
// Detach the event handlers
_stroke.DrawingAttributesChanged -= new PropertyDataChangedEventHandler(OnStrokeDrawingAttributesChanged);
_stroke.StylusPointsReplaced -= new StylusPointsReplacedEventHandler(OnStylusPointsReplaced);
_stroke.StylusPoints.Changed -= new EventHandler(OnStylusPointsChanged);
_stroke.DrawingAttributesReplaced -= new DrawingAttributesReplacedEventHandler(OnDrawingAttributesReplaced);
_stroke = null;
}
}
#endregion
#region Stroke event handlers (Private)
/// <summary>Event handler for stroke data changed events</summary>
private void OnStylusPointsChanged(object sender, EventArgs args)
{
Invalidate();
}
/// <summary>Event handler for stroke data changed events</summary>
private void OnStylusPointsReplaced(object sender, StylusPointsReplacedEventArgs args)
{
Invalidate();
}
/// <summary>
/// Event handler for stroke's drawing attributes changes.
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private void OnStrokeDrawingAttributesChanged(object sender, PropertyDataChangedEventArgs args)
{
// Only enforce rehittesting of the whole stroke when the DrawingAttribute change may affect hittesting
if(DrawingAttributes.IsGeometricalDaGuid(args.PropertyGuid))
{
Invalidate();
}
}
private void OnDrawingAttributesReplaced(Object sender, DrawingAttributesReplacedEventArgs args)
{
// If the drawing attributes change involves Width, Height, StylusTipTransform, IgnorePressure, or FitToCurve,
// we need to invalidate
if (false == DrawingAttributes.GeometricallyEqual(args.NewDrawingAttributes, args.PreviousDrawingAttributes))
{
Invalidate();
}
}
/// <summary>Implementation for the event handlers above</summary>
private void Invalidate()
{
_totalWeightCached = false;
_stylusPoints = null;
_hitWeight = 0;
// Let the hit-tester know that it should not use incremental hit-testing
_isDirty = true;
// The Stroke.GetBounds may be overriden in the 3rd party code.
// The out-side code could throw exception. If an exception is thrown, _bounds will keep the original value.
// Re-compute the stroke bounds
_bounds = _stroke.GetBounds();
}
#endregion
#region Fields
private Stroke _stroke;
private Rect _bounds;
private double _hitWeight = 0f;
private bool _isHit = false;
private bool _isDirty = true;
private StylusPointCollection _stylusPoints; // Cache the stroke rendering points
private double _totalWeight = 0f;
private bool _totalWeightCached = false;
#endregion
}
#endregion // StrokeInfo
}
// The following code is for Stroke-Erasing scenario. Currently the IncrementalStrokeHitTester
// can be used for Stroke-erasing but the following class is faster. If in the future there's a
// perf issue with Stroke-Erasing, consider adding the following code.
//#region Commented Code for IncrementalStrokeHitTester
//#region IncrementalStrokeHitTester
///// <summary>
///// IncrementalHitTester implementation for hit-testing with a shape, StrokeErasing .
///// </summary>
//public class IncrementalStrokeHitTester : IncrementalHitTester
//{
// /// <summary>
// /// event
// /// </summary>
// public event StrokesHitEventHandler StrokesHit;
// #region C-tor and the overrides
// /// <summary>
// /// C-tor
// /// </summary>
// /// <param name="strokes">strokes to hit-test for erasing</param>
// /// <param name="eraserShape">erasing shape</param>
// internal IncrementalStrokeHitTester(StrokeCollection strokes, StylusShape eraserShape)
// : base(strokes)
// {
// System.Diagnostics.Debug.Assert(eraserShape != null);
// // Create an ErasingStroke objects that implements the actual hit-testing
// _erasingStroke = new ErasingStroke(eraserShape);
// }
// /// <summary>
// ///
// /// </summary>
// /// <param name="eventArgs"></param>
// internal protected void OnStrokesHit(StrokesHitEventArgs eventArgs)
// {
// if (StrokesHit != null)
// {
// StrokesHit(this, eventArgs);
// }
// }
// /// <summary>
// /// The implementation behind the public methods AddPoint/AddPoints
// /// </summary>
// /// <param name="points">a set of points representing the last increment
// /// in the moving of the erasing shape</param>
// internal protected override void AddPointsCore(Point[] points)
// {
// System.Diagnostics.Debug.Assert((points != null) && (points.Length != 0));
// System.Diagnostics.Debug.Assert(_erasingStroke != null);
// // Move the shape through the new points and build the contour of the move.
// _erasingStroke.MoveTo(points);
// Rect erasingBounds = _erasingStroke.Bounds;
// if (erasingBounds.IsEmpty)
// {
// return;
// }
// StrokeCollection strokesHit = null;
// if (StrokesHit != null)
// {
// // Test stroke by stroke and collect hits.
// foreach (StrokeInfo strokeInfo in StrokeInfos)
// {
// // Skip strokes that have already been reported hit or which bounds
// // don't intersect with the bounds of the erasing stroke.
// if ((strokeInfo.IsHit == false) && erasingBounds.IntersectsWith(strokeInfo.StrokeBounds)
// && _erasingStroke.HitTest(StrokeNodeIterator.GetIterator(strokeInfo.Stroke, strokeInfo.Overrides)))
// {
// if (strokesHit == null)
// {
// strokesHit = new StrokeCollection();
// }
// strokesHit.Add(strokeInfo.Stroke);
// strokeInfo.IsHit = true;
// }
// }
// }
// // Raise StrokesHitChanged event if any strokes have been hit and there're listeners to the event.
// if (strokesHit != null)
// {
// System.Diagnostics.Debug.Assert(strokesHit.Count != 0);
// OnStrokesHit(new StrokesHitEventArgs(strokesHit));
// }
// }
// #endregion
// #region Fields
// private ErasingStroke _erasingStroke;
// #endregion
//}
//#endregion
///// <summary>
///// Declaration for StrokesHit event handler. Used in stroke-erasing
///// </summary>
//public delegate void StrokesHitEventHandler(object sender, StrokesHitEventArgs e);
///// <summary>
///// Event arguments for StrokesHit event
///// </summary>
//public class StrokesHitEventArgs : EventArgs
//{
// internal StrokesHitEventArgs(StrokeCollection hitStrokes)
// {
// System.Diagnostics.Debug.Assert(hitStrokes != null && hitStrokes.Count > 0);
// _hitStrokes = hitStrokes;
// }
// /// <summary>
// ///
// /// </summary>
// public StrokeCollection HitStrokes
// {
// get { return _hitStrokes; }
// }
// private StrokeCollection _hitStrokes;
//}
//#endregion
| |
using System;
using System.Collections.Generic;
using NUnit.Framework;
namespace Axon.Collections
{
[TestFixture]
public class ConcurrentPriorityQueueTest
{
#region Instance members
[Test]
public void PropertyCapacity()
{
// Create a new priority queue.
ConcurrentPriorityQueue<int> queue = new ConcurrentPriorityQueue<int>( 15 );
// Ensure that Capacity reports 15.
Assert.That( queue.Capacity, Is.EqualTo( 15 ) );
// Intentionally over-fill the queue to force it to resize.
for ( int i = 0; i < 16; i++ )
{
queue.Enqueue( 1f, 1 );
}
// Ensure that Capacity is now greater than 15.
Assert.That( queue.Capacity, Is.GreaterThan( 15 ) );
}
[Test]
public void PropertyCount()
{
// Create a new priority queue.
ConcurrentPriorityQueue<int> queue = new ConcurrentPriorityQueue<int>();
// Ensure that Count reports 0.
Assert.That( queue.Count, Is.EqualTo( 0 ) );
// Enqueue 3 elements in the queue.
queue.Enqueue( 1.0, 1 );
queue.Enqueue( 3.0, 3 );
queue.Enqueue( 2.0, 2 );
// Ensure that Count now reports 3.
Assert.That( queue.Count, Is.EqualTo( 3 ) );
}
[Test]
public void PropertyIsEmpty()
{
// Create a new priority queue.
ConcurrentPriorityQueue<int> queue = new ConcurrentPriorityQueue<int>();
// Ensure that IsEmpty reports TRUE.
Assert.That( queue.IsEmpty, Is.True );
// Enqueue an element in the queue.
queue.Enqueue( 1.0, 1 );
// Ensure that IsEmpty now reports FALSE.
Assert.That( queue.IsEmpty, Is.False );
}
[Test]
public void PropertyIsReadOnly()
{
// Create a new priority queue.
ConcurrentPriorityQueue<int> queue = new ConcurrentPriorityQueue<int>();
// Ensure that IsReadOnly always reports FALSE.
Assert.That( queue.IsReadOnly, Is.False );
}
[Test]
public void PropertyNumQueuedItems()
{
// Create a new priority queue.
ConcurrentPriorityQueue<int> queue = new ConcurrentPriorityQueue<int>();
// Ensure that NumQueuedItems reports 0.
Assert.That( queue.NumQueuedItems, Is.EqualTo( 0L ) );
// Enqueue an element in the queue.
queue.Enqueue( 1.0, 1 );
// Ensure that NumQueuedItems reports 1.
Assert.That( queue.NumQueuedItems, Is.EqualTo( 1L ) );
// Enqueue an element in the queue.
queue.Enqueue( 1.0, 1 );
// Ensure that NumQueuedItems reports 2.
Assert.That( queue.NumQueuedItems, Is.EqualTo( 2L ) );
// Clear the queue.
queue.Clear();
// Ensure that NumQueuedItems reports 0.
Assert.That( queue.NumQueuedItems, Is.EqualTo( 0L ) );
}
[Test]
public void PropertyPriorityAdjustment()
{
// Create a new priority queue.
ConcurrentPriorityQueue<int> queue = new ConcurrentPriorityQueue<int>();
// Ensure that PriorityAdjustment reports 0.
Assert.That( queue.PriorityAdjustment, Is.EqualTo( 0.0 ) );
// Enqueue an element in the queue.
queue.Enqueue( 1.0, 1 );
// Ensure that PriorityAdjustment reports 1.
Assert.That( queue.PriorityAdjustment, Is.EqualTo( 1L * ConcurrentPriorityQueue<int>.EPSILON ) );
// Enqueue an element in the queue.
queue.Enqueue( 1.0, 1 );
// Ensure that PriorityAdjustment reports 2.
Assert.That( queue.PriorityAdjustment, Is.EqualTo( 2L * ConcurrentPriorityQueue<int>.EPSILON ) );
// Clear the queue.
queue.Clear();
// Ensure that PriorityAdjustment reports 0.
Assert.That( queue.PriorityAdjustment, Is.EqualTo( 0.0 ) );
}
#endregion
#region Constructors
[Test]
public void ConstructorParameterless()
{
// Create a new priority queue.
ConcurrentPriorityQueue<int> queue = new ConcurrentPriorityQueue<int>();
// Nothing to test about the queue, but check that NumQueuedItems inits to 0.
Assert.That( queue.NumQueuedItems, Is.EqualTo( 0L ) );
}
[Test]
public void ConstructorInitialSize()
{
// Try to create a priority queue with a negative initial size and expect an
// ArgumentOutOfRangeException to be thrown.
Assert.Throws<ArgumentOutOfRangeException>( () => {
new ConcurrentPriorityQueue<int>( -10 );
} );
// Create a new priority queue.
ConcurrentPriorityQueue<int> queue = new ConcurrentPriorityQueue<int>( 15 );
// Ensure that Capacity reports 15.
Assert.That( queue.Capacity, Is.EqualTo( 15 ) );
// Check that NumQueuedItems inits to 0.
Assert.That( queue.NumQueuedItems, Is.EqualTo( 0L ) );
}
#endregion
#region Public API
[Test]
public void Add()
{
// Create a new priority queue.
ConcurrentPriorityQueue<int> queue = new ConcurrentPriorityQueue<int>();
// Ensure that the queue is empty.
Assert.That( queue.Count, Is.EqualTo( 0 ) );
// Call Add() to insert a new element to the queue as a KeyValuePair.
queue.Add( new PriorityValuePair<int>( 1.0, 2 ) );
// Expect a value of 2 on the first item to be removed after adding it.
Assert.That( queue.Dequeue().Value, Is.EqualTo( 2 ) );
}
[Test]
public void Clear()
{
// Create a new priority queue.
ConcurrentPriorityQueue<int> queue = new ConcurrentPriorityQueue<int>();
// Enqueue a few elements into the queue.
queue.Enqueue( 1.0, 2 );
queue.Enqueue( 3.0, 6 );
queue.Enqueue( 2.0, 4 );
// Ensure that 3 elements have been added to the queue.
Assert.That( queue.Count, Is.EqualTo( 3 ) );
// Clear the queue.
queue.Clear();
// Ensure that all of the elements have been removed.
Assert.That( queue.Count, Is.EqualTo( 0 ) );
}
[Test]
public void Contains()
{
// Create a new priority queue.
ConcurrentPriorityQueue<int> queue = new ConcurrentPriorityQueue<int>();
// Create and store a new element.
PriorityValuePair<int> elem = new PriorityValuePair<int>( 1.0, 2 );
// Ensure the queue contains the element.
Assert.That( queue.Contains( elem ), Is.False );
// Enqueue it in the queue.
queue.Enqueue( elem );
// Ensure the queue now contains the element.
Assert.That( queue.Contains( elem ), Is.True );
}
[Test]
public void CopyTo()
{
// Create a new priority queue.
ConcurrentPriorityQueue<int> queue = new ConcurrentPriorityQueue<int>();
// Create a new array of size 5.
PriorityValuePair<int>[] arrayCopy = new PriorityValuePair<int>[ 5 ];
// Enqueue 3 elements into the queue.
PriorityValuePair<int> elem = new PriorityValuePair<int>( 3.0, 6 );
queue.Enqueue( 1.0, 2 );
queue.Enqueue( elem );
queue.Enqueue( 2.0, 4 );
// Copy the queue data to the array, starting from index 1 (not 0).
queue.CopyTo( arrayCopy, 1 );
// Expect the first array index to be unset, but all the rest to be set.
// Note: The order of elements after the first can't be guaranteed, because the heap
// implementing the queue internally doesn't store things in an exact linear order,
// but we can be sure that the elements aren't going to be equal to null because we
// set them.
Assert.That( arrayCopy[ 0 ], Is.EqualTo( null ) );
Assert.That( arrayCopy[ 1 ], Is.EqualTo( elem ) );
Assert.That( arrayCopy[ 2 ], Is.Not.EqualTo( null ) );
Assert.That( arrayCopy[ 3 ], Is.Not.EqualTo( null ) );
Assert.That( arrayCopy[ 4 ], Is.EqualTo( null ) );
}
[Test]
public void Dequeue()
{
// Create a new priority queue.
ConcurrentPriorityQueue<int> queue = new ConcurrentPriorityQueue<int>();
// Ensure that the heap is empty.
Assert.That( queue.Count, Is.EqualTo( 0 ) );
// Expect Dequeue() to return null for an empty heap.
Assert.That( queue.Dequeue(), Is.EqualTo( null ) );
// Ensure that the heap is empty.
Assert.That( queue.Count, Is.EqualTo( 0 ) );
// Store an element and insert it into the heap.
PriorityValuePair<int> elem = new PriorityValuePair<int>( 1.0, 2 );
queue.Enqueue( elem );
// Ensure that the element was inserted into the heap.
Assert.That( queue.Count, Is.EqualTo( 1 ) );
Assert.That( queue.Peek(), Is.EqualTo( elem ) );
// Ensure that the PriorityAdjustment was incremented.
Assert.That( queue.PriorityAdjustment, Is.EqualTo( ConcurrentPriorityQueue<int>.EPSILON ) );
// Ensure that the returned element points to the same object we stored earlier.
Assert.That( queue.Dequeue(), Is.EqualTo( elem ) );
// Ensure that the element was removed from the heap.
Assert.That( queue.Count, Is.EqualTo( 0 ) );
// Ensure that the PriorityAdjustment was reset once the queue became empty.
Assert.That( queue.PriorityAdjustment, Is.EqualTo( 0.0 ) );
// Enqueue 5 items with the same priority.
PriorityValuePair<int> elem2 = new PriorityValuePair<int>( 2.0, 0 );
PriorityValuePair<int> elem3 = new PriorityValuePair<int>( 2.0, 2 );
PriorityValuePair<int> elem4 = new PriorityValuePair<int>( 2.0, 4 );
PriorityValuePair<int> elem5 = new PriorityValuePair<int>( 2.0, 6 );
PriorityValuePair<int> elem6 = new PriorityValuePair<int>( 2.0, 8 );
queue.Enqueue( elem2 );
queue.Enqueue( elem3 );
queue.Enqueue( elem4 );
queue.Enqueue( elem5 );
queue.Enqueue( elem6 );
//// Ensure that Dequeue() returns the items in the order they were enqueued.
Assert.That( queue.Dequeue(), Is.EqualTo( elem2 ) );
Assert.That( queue.Dequeue(), Is.EqualTo( elem3 ) );
Assert.That( queue.Dequeue(), Is.EqualTo( elem4 ) );
Assert.That( queue.Dequeue(), Is.EqualTo( elem5 ) );
Assert.That( queue.Dequeue(), Is.EqualTo( elem6 ) );
}
[Test]
public void EnqueueElement()
{
// Create a new priority queue.
ConcurrentPriorityQueue<int> queue = new ConcurrentPriorityQueue<int>();
// Ensure that the queue is empty.
Assert.That( queue.Count, Is.EqualTo( 0 ) );
// Store an element and insert it into the queue.
PriorityValuePair<int> elem = new PriorityValuePair<int>( 1.0, 2 );
queue.Enqueue( elem );
// Ensure that the element was inserted into the queue.
Assert.That( queue.Peek(), Is.EqualTo( elem ) );
// Store another element with higher priority and insert it as well.
elem = new PriorityValuePair<int>( 2.0, 4 );
queue.Enqueue( elem );
// Ensure that the element was inserted into the queue and is at the front.
Assert.That( queue.Peek(), Is.EqualTo( elem ) );
}
[Test]
public void EnqueuePriorityValue()
{
// Create a new priority queue.
ConcurrentPriorityQueue<int> queue = new ConcurrentPriorityQueue<int>();
// Ensure that queue is empty.
Assert.That( queue.Count, Is.EqualTo( 0 ) );
// Store an element and insert it into the queue.
queue.Enqueue( 1.0, 2 );
// Ensure that the element was inserted into the queue.
Assert.That( queue.Peek().Value, Is.EqualTo( 2 ) );
// Store another element with higher priority and insert it as well.
queue.Enqueue( 2.0, 4 );
// Ensure that the element was inserted into the queue.
Assert.That( queue.Peek().Value, Is.EqualTo( 4 ) );
}
[Test]
public void GetEnumerator()
{
// Create a new priority queue.
ConcurrentPriorityQueue<int> queue = new ConcurrentPriorityQueue<int>();
// Enqueue a few elements into the queue.
queue.Enqueue( 1.0, 2 );
queue.Enqueue( 3.0, 6 );
queue.Enqueue( 2.0, 4 );
// Use the enumerator of queue (using disposes it when we're finished).
using ( IEnumerator< PriorityValuePair<int> > enumerator = queue.GetEnumerator() )
{
// Expect the first element to have the highest priority, and expect MoveNext() to
// return true until the last element. After the end of the heap is reached, it
// then returns false.
// Note: Since the heap implementing the queue internally doesn't guarantee the
// order of elements after the first, we can only be certain of the root element
// and after that we really can't be sure of the order -- just the length.
Assert.That( enumerator.MoveNext(), Is.True );
Assert.That( enumerator.Current.Value, Is.EqualTo( 6 ) );
Assert.That( enumerator.MoveNext(), Is.True );
Assert.That( enumerator.MoveNext(), Is.True );
Assert.That( enumerator.MoveNext(), Is.False );
}
}
[Test]
public void Peek() {
// Create a new priority queue.
ConcurrentPriorityQueue<int> queue = new ConcurrentPriorityQueue<int>();
// Ensure that the heap is empty.
Assert.That( queue.Count, Is.EqualTo( 0 ) );
// Expect Peek() to return null for an empty heap.
Assert.That( queue.Peek(), Is.EqualTo( null ) );
// Ensure that the queue is empty.
Assert.That( queue.Count, Is.EqualTo( 0 ) );
// Store an element and insert it into the queue.
PriorityValuePair<int> elem1 = new PriorityValuePair<int>( 1.0, 2 );
queue.Enqueue( elem1 );
// Ensure that the element was inserted into the queue at the front.
Assert.That( queue.Count, Is.EqualTo( 1 ) );
Assert.That( queue.Peek(), Is.EqualTo( elem1 ) );
// Ensure that the element was not removed from the heap.
Assert.That( queue.Count, Is.EqualTo( 1 ) );
// Insert another element with higher priority than the last.
PriorityValuePair<int> elem2 = new PriorityValuePair<int>( 2.0, 4 );
queue.Enqueue( elem2 );
// Ensure that Peek() returns the new front element.
Assert.That( queue.Peek(), Is.EqualTo( elem2 ) );
// Insert another element with the same priority as the last.
PriorityValuePair<int> elem3 = new PriorityValuePair<int>( 2.0, 6 );
queue.Enqueue( elem3 );
// Ensure that Peek() returns still returns the first value with that priority.
Assert.That( queue.Peek(), Is.EqualTo( elem2 ) );
// Remove the element from the queue.
queue.Dequeue();
// Ensure that Peek() returns now returns the other value with the same priorty.
Assert.That( queue.Peek(), Is.EqualTo( elem3 ) );
}
[Test]
public void Remove() {
// Create a new priority queue.
ConcurrentPriorityQueue<int> queue = new ConcurrentPriorityQueue<int>();
// Create and store a few elements.
PriorityValuePair<int> elem1 = new PriorityValuePair<int>( 1.0, 2 );
PriorityValuePair<int> elem2 = new PriorityValuePair<int>( 2.0, 4 );
PriorityValuePair<int> elem3 = new PriorityValuePair<int>( 3.0, 6 );
// Expect Remove() to return false for an empty queue.
Assert.That( queue.Remove( elem1 ), Is.False );
// Enqueue 2 of the elements into the heap.
queue.Enqueue( elem2 );
queue.Enqueue( elem3 );
// Expect Remove() to return false for elem1, indicating the element was removed
// (since it doesn't belong to the heap and can't be found). This tests the if-else
// case for when the provided element isn't found in the heap.
Assert.That( queue.Remove( elem1 ), Is.False );
// Expect Remove() to return true for elem2, indicating the element was removed
// (since it belongs to the heap and can be found). This tests the if-else case for
// when Count is 2 or greater.
Assert.That( queue.Remove( elem2 ), Is.True );
// Expect Remove() to return true for elem3, indicating the element was removed
// (since it belongs to the heap and can be found). This tests the if-else case for
// when Count equals 1.
Assert.That( queue.Remove( elem3 ), Is.True );
}
#endregion
}
}
| |
#region License
/*
* HttpRequestEventArgs.cs
*
* The MIT License
*
* Copyright (c) 2012-2021 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
using System.IO;
using System.Security.Principal;
using System.Text;
using WebSocketSharp.Net;
namespace WebSocketSharp.Server
{
/// <summary>
/// Represents the event data for the HTTP request events of the
/// <see cref="HttpServer"/> class.
/// </summary>
/// <remarks>
/// <para>
/// An HTTP request event occurs when the <see cref="HttpServer"/>
/// instance receives an HTTP request.
/// </para>
/// <para>
/// You should access the <see cref="Request"/> property if you would
/// like to get the request data sent from a client.
/// </para>
/// <para>
/// And you should access the <see cref="Response"/> property if you
/// would like to get the response data to return to the client.
/// </para>
/// </remarks>
public class HttpRequestEventArgs : EventArgs
{
#region Private Fields
private HttpListenerContext _context;
private string _docRootPath;
#endregion
#region Internal Constructors
internal HttpRequestEventArgs (
HttpListenerContext context, string documentRootPath
)
{
_context = context;
_docRootPath = documentRootPath;
}
#endregion
#region Public Properties
/// <summary>
/// Gets the request data sent from a client.
/// </summary>
/// <value>
/// A <see cref="HttpListenerRequest"/> that provides the methods and
/// properties for the request data.
/// </value>
public HttpListenerRequest Request {
get {
return _context.Request;
}
}
/// <summary>
/// Gets the response data to return to the client.
/// </summary>
/// <value>
/// A <see cref="HttpListenerResponse"/> that provides the methods and
/// properties for the response data.
/// </value>
public HttpListenerResponse Response {
get {
return _context.Response;
}
}
/// <summary>
/// Gets the information for the client.
/// </summary>
/// <value>
/// <para>
/// A <see cref="IPrincipal"/> instance or <see langword="null"/>
/// if not authenticated.
/// </para>
/// <para>
/// That instance describes the identity, authentication scheme,
/// and security roles for the client.
/// </para>
/// </value>
public IPrincipal User {
get {
return _context.User;
}
}
#endregion
#region Private Methods
private string createFilePath (string childPath)
{
childPath = childPath.TrimStart ('/', '\\');
return new StringBuilder (_docRootPath, 32)
.AppendFormat ("/{0}", childPath)
.ToString ()
.Replace ('\\', '/');
}
private static bool tryReadFile (string path, out byte[] contents)
{
contents = null;
if (!File.Exists (path))
return false;
try {
contents = File.ReadAllBytes (path);
}
catch {
return false;
}
return true;
}
#endregion
#region Public Methods
/// <summary>
/// Reads the specified file from the document folder of the
/// <see cref="HttpServer"/> class.
/// </summary>
/// <returns>
/// <para>
/// An array of <see cref="byte"/> or <see langword="null"/>
/// if it fails.
/// </para>
/// <para>
/// That array receives the contents of the file.
/// </para>
/// </returns>
/// <param name="path">
/// A <see cref="string"/> that specifies a virtual path to
/// find the file from the document folder.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="path"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="path"/> is an empty string.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="path"/> contains "..".
/// </para>
/// </exception>
public byte[] ReadFile (string path)
{
if (path == null)
throw new ArgumentNullException ("path");
if (path.Length == 0)
throw new ArgumentException ("An empty string.", "path");
if (path.IndexOf ("..") > -1)
throw new ArgumentException ("It contains '..'.", "path");
path = createFilePath (path);
byte[] contents;
tryReadFile (path, out contents);
return contents;
}
/// <summary>
/// Tries to read the specified file from the document folder of
/// the <see cref="HttpServer"/> class.
/// </summary>
/// <returns>
/// <c>true</c> if it succeeds to read; otherwise, <c>false</c>.
/// </returns>
/// <param name="path">
/// A <see cref="string"/> that specifies a virtual path to find
/// the file from the document folder.
/// </param>
/// <param name="contents">
/// <para>
/// When this method returns, an array of <see cref="byte"/> or
/// <see langword="null"/> if it fails.
/// </para>
/// <para>
/// That array receives the contents of the file.
/// </para>
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="path"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="path"/> is an empty string.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="path"/> contains "..".
/// </para>
/// </exception>
public bool TryReadFile (string path, out byte[] contents)
{
if (path == null)
throw new ArgumentNullException ("path");
if (path.Length == 0)
throw new ArgumentException ("An empty string.", "path");
if (path.IndexOf ("..") > -1)
throw new ArgumentException ("It contains '..'.", "path");
path = createFilePath (path);
return tryReadFile (path, out contents);
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.ResourceManager.Models;
using Microsoft.Azure.Management.StreamAnalytics;
using Microsoft.Azure.Management.StreamAnalytics.Models;
using Microsoft.Rest.Azure;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Xunit;
namespace StreamAnalytics.Tests
{
public class StreamingJobTests : TestBase
{
[Fact]
public async Task StreamingJobOperationsTest_JobShell()
{
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
string resourceGroupName = TestUtilities.GenerateName("sjrg");
string jobName = TestUtilities.GenerateName("sj");
var resourceManagementClient = this.GetResourceManagementClient(context);
var streamAnalyticsManagementClient = this.GetStreamAnalyticsManagementClient(context);
string expectedJobResourceId = TestHelper.GetJobResourceId(streamAnalyticsManagementClient.SubscriptionId, resourceGroupName, jobName);
resourceManagementClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = TestHelper.DefaultLocation });
StreamingJob streamingJob = new StreamingJob()
{
Tags = new Dictionary<string, string>()
{
{ "key1", "value1" },
{ "randomKey", "randomValue" },
{ "key3", "value3" }
},
Location = TestHelper.DefaultLocation,
EventsOutOfOrderPolicy = EventsOutOfOrderPolicy.Drop,
EventsOutOfOrderMaxDelayInSeconds = 5,
EventsLateArrivalMaxDelayInSeconds = 16,
OutputErrorPolicy = OutputErrorPolicy.Drop,
DataLocale = "en-US",
CompatibilityLevel = CompatibilityLevel.OneFullStopZero,
Sku = new Microsoft.Azure.Management.StreamAnalytics.Models.Sku()
{
Name = SkuName.Standard
},
Inputs = new List<Input>(),
Outputs = new List<Output>(),
Functions = new List<Function>()
};
// PUT job
var putResponse = await streamAnalyticsManagementClient.StreamingJobs.CreateOrReplaceWithHttpMessagesAsync(streamingJob, resourceGroupName, jobName);
ValidationHelper.ValidateStreamingJob(streamingJob, putResponse.Body, false);
Assert.Equal(expectedJobResourceId, putResponse.Body.Id);
Assert.Equal(jobName, putResponse.Body.Name);
Assert.Equal(TestHelper.StreamingJobFullResourceType, putResponse.Body.Type);
Assert.Equal("Succeeded", putResponse.Body.ProvisioningState);
Assert.Equal("Created", putResponse.Body.JobState);
// Verify GET request returns expected job
var getResponse = await streamAnalyticsManagementClient.StreamingJobs.GetWithHttpMessagesAsync(resourceGroupName, jobName, "inputs,outputs,transformation,functions");
ValidationHelper.ValidateStreamingJob(putResponse.Body, getResponse.Body, true);
// ETag should be the same
Assert.Equal(putResponse.Headers.ETag, getResponse.Headers.ETag);
// PATCH job
var streamingJobPatch = new StreamingJob()
{
EventsOutOfOrderMaxDelayInSeconds = 21,
EventsLateArrivalMaxDelayInSeconds = 13
};
putResponse.Body.EventsOutOfOrderMaxDelayInSeconds = streamingJobPatch.EventsOutOfOrderMaxDelayInSeconds;
putResponse.Body.EventsLateArrivalMaxDelayInSeconds = streamingJobPatch.EventsLateArrivalMaxDelayInSeconds;
putResponse.Body.Inputs = null;
putResponse.Body.Outputs = null;
putResponse.Body.Functions = null;
var patchResponse = await streamAnalyticsManagementClient.StreamingJobs.UpdateWithHttpMessagesAsync(streamingJobPatch, resourceGroupName, jobName);
ValidationHelper.ValidateStreamingJob(putResponse.Body, patchResponse.Body, true);
// ETag should be different after a PATCH operation
Assert.NotEqual(putResponse.Headers.ETag, patchResponse.Headers.ETag);
putResponse.Body.Inputs = new List<Input>();
putResponse.Body.Outputs = new List<Output>();
putResponse.Body.Functions = new List<Function>();
// Run another GET job to verify that it returns the newly updated properties as well
getResponse = await streamAnalyticsManagementClient.StreamingJobs.GetWithHttpMessagesAsync(resourceGroupName, jobName, "inputs,outputs,transformation,functions");
ValidationHelper.ValidateStreamingJob(putResponse.Body, getResponse.Body, true);
Assert.NotEqual(putResponse.Headers.ETag, getResponse.Headers.ETag);
Assert.Equal(patchResponse.Headers.ETag, getResponse.Headers.ETag);
// List job and verify that the job shows up in the list
var listByRgResponse = streamAnalyticsManagementClient.StreamingJobs.ListByResourceGroup(resourceGroupName, "inputs,outputs,transformation,functions");
Assert.Equal(1, listByRgResponse.Count());
ValidationHelper.ValidateStreamingJob(putResponse.Body, listByRgResponse.Single(), true);
Assert.Equal(getResponse.Headers.ETag, listByRgResponse.Single().Etag);
var listReponse = streamAnalyticsManagementClient.StreamingJobs.List("inputs, outputs, transformation, functions");
Assert.Equal(1, listReponse.Count());
ValidationHelper.ValidateStreamingJob(putResponse.Body, listReponse.Single(), true);
Assert.Equal(getResponse.Headers.ETag, listReponse.Single().Etag);
// Delete job
streamAnalyticsManagementClient.StreamingJobs.Delete(resourceGroupName, jobName);
// Verify that list operation returns an empty list after deleting the job
listByRgResponse = streamAnalyticsManagementClient.StreamingJobs.ListByResourceGroup(resourceGroupName, "inputs,outputs,transformation,functions");
Assert.Equal(0, listByRgResponse.Count());
listReponse = streamAnalyticsManagementClient.StreamingJobs.List("inputs, outputs, transformation, functions");
Assert.Equal(0, listReponse.Count());
}
}
[Fact]
public async Task StreamingJobOperationsTest_FullJob()
{
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
string resourceGroupName = TestUtilities.GenerateName("sjrg");
string jobName = TestUtilities.GenerateName("sj");
string inputName = "inputtest";
string transformationName = "transformationtest";
string outputName = "outputtest";
var resourceManagementClient = this.GetResourceManagementClient(context);
var streamAnalyticsManagementClient = this.GetStreamAnalyticsManagementClient(context);
string expectedJobResourceId = TestHelper.GetJobResourceId(streamAnalyticsManagementClient.SubscriptionId, resourceGroupName, jobName);
string expectedInputResourceId = TestHelper.GetRestOnlyResourceId(streamAnalyticsManagementClient.SubscriptionId, resourceGroupName, jobName, TestHelper.InputsResourceType, inputName);
string expectedTransformationResourceId = TestHelper.GetRestOnlyResourceId(streamAnalyticsManagementClient.SubscriptionId, resourceGroupName, jobName, TestHelper.TransformationResourceType, transformationName);
string expectedOutputResourceId = TestHelper.GetRestOnlyResourceId(streamAnalyticsManagementClient.SubscriptionId, resourceGroupName, jobName, TestHelper.OutputsResourceType, outputName);
resourceManagementClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = TestHelper.DefaultLocation });
StorageAccount storageAccount = new StorageAccount()
{
AccountName = TestHelper.AccountName,
AccountKey = TestHelper.AccountKey
};
Input input = new Input(id: expectedInputResourceId)
{
Name = inputName,
Properties = new StreamInputProperties()
{
Serialization = new JsonSerialization()
{
Encoding = Encoding.UTF8
},
Datasource = new BlobStreamInputDataSource()
{
StorageAccounts = new[] { storageAccount },
Container = TestHelper.Container,
PathPattern = "",
}
}
};
AzureSqlDatabaseOutputDataSource azureSqlDatabase = new AzureSqlDatabaseOutputDataSource()
{
Server = TestHelper.Server,
Database = TestHelper.Database,
User = TestHelper.User,
Password = TestHelper.Password,
Table = TestHelper.SqlTableName
};
Output output = new Output(id: expectedOutputResourceId)
{
Name = outputName,
Datasource = azureSqlDatabase
};
StreamingJob streamingJob = new StreamingJob()
{
Tags = new Dictionary<string, string>()
{
{ "key1", "value1" },
{ "randomKey", "randomValue" },
{ "key3", "value3" }
},
Location = TestHelper.DefaultLocation,
EventsOutOfOrderPolicy = EventsOutOfOrderPolicy.Drop,
EventsOutOfOrderMaxDelayInSeconds = 0,
EventsLateArrivalMaxDelayInSeconds = 5,
OutputErrorPolicy = OutputErrorPolicy.Drop,
DataLocale = "en-US",
CompatibilityLevel = "1.0",
Sku = new Microsoft.Azure.Management.StreamAnalytics.Models.Sku()
{
Name = SkuName.Standard
},
Inputs = new List<Input>() { input },
Transformation = new Transformation(id: expectedTransformationResourceId)
{
Name = transformationName,
Query = "Select Id, Name from inputtest",
StreamingUnits = 1
},
Outputs = new List<Output>() { output },
Functions = new List<Function>()
};
// PUT job
var putResponse = await streamAnalyticsManagementClient.StreamingJobs.CreateOrReplaceWithHttpMessagesAsync(streamingJob, resourceGroupName, jobName);
// Null out because secrets are not returned in responses
storageAccount.AccountKey = null;
azureSqlDatabase.Password = null;
ValidationHelper.ValidateStreamingJob(streamingJob, putResponse.Body, false);
Assert.Equal(expectedJobResourceId, putResponse.Body.Id);
Assert.Equal(jobName, putResponse.Body.Name);
Assert.Equal(TestHelper.StreamingJobFullResourceType, putResponse.Body.Type);
//Assert.True(putResponse.Body.CreatedDate > DateTime.UtcNow.AddMinutes(-1));
Assert.Equal("Succeeded", putResponse.Body.ProvisioningState);
Assert.Equal("Created", putResponse.Body.JobState);
// Verify GET request returns expected job
var getResponse = await streamAnalyticsManagementClient.StreamingJobs.GetWithHttpMessagesAsync(resourceGroupName, jobName, "inputs,outputs,transformation,functions");
ValidationHelper.ValidateStreamingJob(putResponse.Body, getResponse.Body, true);
// ETag should be the same
Assert.Equal(putResponse.Headers.ETag, getResponse.Headers.ETag);
// PATCH job
var streamingJobPatch = new StreamingJob()
{
EventsOutOfOrderPolicy = EventsOutOfOrderPolicy.Adjust,
OutputErrorPolicy = OutputErrorPolicy.Stop
};
putResponse.Body.EventsOutOfOrderPolicy = streamingJobPatch.EventsOutOfOrderPolicy;
putResponse.Body.OutputErrorPolicy = streamingJobPatch.OutputErrorPolicy;
putResponse.Body.Functions = null;
streamingJob.EventsOutOfOrderPolicy = streamingJobPatch.EventsOutOfOrderPolicy;
streamingJob.OutputErrorPolicy = streamingJobPatch.OutputErrorPolicy;
streamingJob.Inputs = null;
streamingJob.Transformation = null;
streamingJob.Outputs = null;
streamingJob.Functions = null;
var patchResponse = await streamAnalyticsManagementClient.StreamingJobs.UpdateWithHttpMessagesAsync(streamingJobPatch, resourceGroupName, jobName);
ValidationHelper.ValidateStreamingJob(streamingJob, patchResponse.Body, false);
// ETag should be different after a PATCH operation
Assert.NotEqual(putResponse.Headers.ETag, patchResponse.Headers.ETag);
putResponse.Body.Functions = new List<Function>();
// Run another GET job to verify that it returns the newly updated properties as well
getResponse = await streamAnalyticsManagementClient.StreamingJobs.GetWithHttpMessagesAsync(resourceGroupName, jobName, "inputs,outputs,transformation,functions");
ValidationHelper.ValidateStreamingJob(putResponse.Body, getResponse.Body, true);
Assert.NotEqual(putResponse.Headers.ETag, getResponse.Headers.ETag);
Assert.Equal(patchResponse.Headers.ETag, getResponse.Headers.ETag);
// List job and verify that the job shows up in the list
var listByRgResponse = streamAnalyticsManagementClient.StreamingJobs.ListByResourceGroup(resourceGroupName, "inputs,outputs,transformation,functions");
Assert.Equal(1, listByRgResponse.Count());
ValidationHelper.ValidateStreamingJob(putResponse.Body, listByRgResponse.Single(), true);
Assert.Equal(getResponse.Headers.ETag, listByRgResponse.Single().Etag);
var listReponse = streamAnalyticsManagementClient.StreamingJobs.List("inputs, outputs, transformation, functions");
Assert.Equal(1, listReponse.Count());
ValidationHelper.ValidateStreamingJob(putResponse.Body, listReponse.Single(), true);
Assert.Equal(getResponse.Headers.ETag, listReponse.Single().Etag);
// Start job
StartStreamingJobParameters startStreamingJobParameters = new StartStreamingJobParameters()
{
OutputStartMode = OutputStartMode.LastOutputEventTime
};
CloudException cloudException = Assert.Throws<CloudException>(() => streamAnalyticsManagementClient.StreamingJobs.Start(resourceGroupName, jobName, startStreamingJobParameters));
Assert.Equal((HttpStatusCode)422, cloudException.Response.StatusCode);
Assert.True(cloudException.Response.Content.Contains("LastOutputEventTime must be available when OutputStartMode is set to LastOutputEventTime. Please make sure at least one output event has been processed."));
startStreamingJobParameters.OutputStartMode = OutputStartMode.CustomTime;
startStreamingJobParameters.OutputStartTime = new DateTime(2012, 12, 12, 12, 12, 12, DateTimeKind.Utc);
putResponse.Body.OutputStartMode = startStreamingJobParameters.OutputStartMode;
putResponse.Body.OutputStartTime = startStreamingJobParameters.OutputStartTime;
streamingJob.OutputStartMode = startStreamingJobParameters.OutputStartMode;
streamingJob.OutputStartTime = startStreamingJobParameters.OutputStartTime;
streamAnalyticsManagementClient.StreamingJobs.Start(resourceGroupName, jobName, startStreamingJobParameters);
// Check that job started
var getResponseAfterStart = await streamAnalyticsManagementClient.StreamingJobs.GetWithHttpMessagesAsync(resourceGroupName, jobName);
Assert.Equal("Succeeded", getResponseAfterStart.Body.ProvisioningState);
Assert.True(getResponseAfterStart.Body.JobState == "Running" || getResponseAfterStart.Body.JobState == "Degraded");
Assert.Null(getResponseAfterStart.Body.Inputs);
Assert.Null(getResponseAfterStart.Body.Transformation);
Assert.Null(getResponseAfterStart.Body.Outputs);
Assert.Null(getResponseAfterStart.Body.Functions);
ValidationHelper.ValidateStreamingJob(streamingJob, getResponseAfterStart.Body, false);
Assert.NotEqual(putResponse.Headers.ETag, getResponseAfterStart.Headers.ETag);
Assert.NotEqual(patchResponse.Headers.ETag, getResponseAfterStart.Headers.ETag);
// Check diagnostics
var inputListResponse = streamAnalyticsManagementClient.Inputs.ListByStreamingJob(resourceGroupName, jobName, "*");
Assert.NotNull(inputListResponse);
Assert.Equal(1, inputListResponse.Count());
var inputFromList = inputListResponse.Single();
Assert.NotNull(inputFromList.Properties.Diagnostics);
Assert.Equal(1, inputFromList.Properties.Diagnostics.Conditions.Count());
Assert.NotNull(inputFromList.Properties.Diagnostics.Conditions[0].Since);
DateTime.Parse(inputFromList.Properties.Diagnostics.Conditions[0].Since);
Assert.Equal(@"INP-3", inputFromList.Properties.Diagnostics.Conditions[0].Code);
Assert.Equal(@"Could not deserialize the input event as Json. Some possible reasons: 1) Malformed events 2) Input source configured with incorrect serialization format", inputFromList.Properties.Diagnostics.Conditions[0].Message);
// Stop job
streamAnalyticsManagementClient.StreamingJobs.Stop(resourceGroupName, jobName);
// Check that job stopped
var getResponseAfterStop = await streamAnalyticsManagementClient.StreamingJobs.GetWithHttpMessagesAsync(resourceGroupName, jobName, "inputs,outputs,transformation,functions");
Assert.Equal("Succeeded", getResponseAfterStop.Body.ProvisioningState);
Assert.Equal("Stopped", getResponseAfterStop.Body.JobState);
ValidationHelper.ValidateStreamingJob(putResponse.Body, getResponseAfterStop.Body, false);
Assert.NotEqual(putResponse.Headers.ETag, getResponseAfterStop.Headers.ETag);
Assert.NotEqual(patchResponse.Headers.ETag, getResponseAfterStop.Headers.ETag);
Assert.NotEqual(getResponseAfterStart.Headers.ETag, getResponseAfterStop.Headers.ETag);
// Delete job
streamAnalyticsManagementClient.StreamingJobs.Delete(resourceGroupName, jobName);
// Verify that list operation returns an empty list after deleting the job
listByRgResponse = streamAnalyticsManagementClient.StreamingJobs.ListByResourceGroup(resourceGroupName, "inputs,outputs,transformation,functions");
Assert.Equal(0, listByRgResponse.Count());
listReponse = streamAnalyticsManagementClient.StreamingJobs.List("inputs, outputs, transformation, functions");
Assert.Equal(0, listReponse.Count());
}
}
}
}
| |
using System;
using Palaso.WritingSystems;
using Palaso.WritingSystems.Migration.WritingSystemsLdmlV0To1Migration;
namespace Palaso.TestUtilities
{
public class LdmlContentForTests
{
public static string Version0English()
{
return Version0("en", String.Empty, String.Empty, String.Empty);
}
public static string Version1English()
{
return Version1("en", String.Empty, String.Empty, String.Empty);
}
static public string Version0(string language, string script, string region, string variant)
{
return String.Format(
@"<?xml version='1.0' encoding='utf-8'?>
<ldml>
<identity>
<version number='' />
<generation date='0001-01-01T00:00:00' />
<language type='{0}' />
<script type='{1}' />
<territory type='{2}' />
<variant type='{3}' />
</identity>
<collations />
<special xmlns:palaso='urn://palaso.org/ldmlExtensions/v1'>
<palaso:defaultFontFamily value='Arial' />
<palaso:defaultFontSize value='12' />
</special>
</ldml>".Replace('\'', '"'), language, script, region, variant);
}
static public string CurrentVersion(string language, string script, string region, string variant)
{
return String.Format(
@"<?xml version='1.0' encoding='utf-8'?>
<ldml>
<identity>
<version number='' />
<generation date='0001-01-01T00:00:00' />
<language type='{0}' />
<script type='{1}' />
<territory type='{2}' />
<variant type='{3}' />
</identity>
<collations />
<special xmlns:palaso='urn://palaso.org/ldmlExtensions/v1'>
<palaso:version value='{4}' />
<palaso:defaultFontFamily value='Arial' />
<palaso:defaultFontSize value='12' />
</special>
</ldml>".Replace('\'', '"'), language, script, region, variant, WritingSystemDefinition.LatestWritingSystemDefinitionVersion);
}
static public string Version0WithLanguageSubtagAndName(string languageSubtag, string languageName)
{
return String.Format(
@"<?xml version='1.0' encoding='utf-8'?>
<ldml>
<identity>
<version number='' />
<generation date='0001-01-01T00:00:00' />
<language type='{0}' />
</identity>
<collations />
<special xmlns:palaso='urn://palaso.org/ldmlExtensions/v1'>
<palaso:languageName value='{1}' />
<palaso:defaultFontFamily value='Arial' />
<palaso:defaultFontSize value='12' />
</special>
</ldml>".Replace('\'', '"'), languageSubtag, languageName);
}
static public string Version99Default()
{
return
@"<?xml version='1.0' encoding='utf-8'?>
<ldml>
<identity>
<version number='' />
<generation date='0001-01-01T00:00:00' />
<language type='en' />
</identity>
<collations />
<special xmlns:palaso='urn://palaso.org/ldmlExtensions/v1'>
<palaso:version value='99' />
<palaso:defaultFontFamily value='Arial' />
<palaso:defaultFontSize value='12' />
</special>
</ldml>".Replace('\'', '"');
}
static public string Version0WithAllSortsOfDatathatdoesNotNeedSpecialAttention(string language, string script, string region, string variant)
{
return String.Format(
@"<?xml version='1.0' encoding='utf-8'?>
<ldml>
<identity>
<version number='' />
<generation date='0001-01-01T00:00:00' />
<language type='{0}' />
<script type='{1}' />
<territory type='{2}' />
<variant type='{3}' />
</identity>
<layout>
<orientation characters='left-to-right'/>
</layout>
<collations>
<collation>
<base>
<alias source=''/>
</base>
<special xmlns:palaso='urn://palaso.org/ldmlExtensions/v1'>
<palaso:sortRulesType value='OtherLanguage' />
</special>
</collation>
</collations>
<special xmlns:palaso='urn://palaso.org/ldmlExtensions/v1'>
<palaso:abbreviation value='la' />
<palaso:defaultFontFamily value='Arial' />
<palaso:defaultFontSize value='12' />
<palaso:defaultKeyboard value='bogusKeyboard' />
<palaso:isLegacyEncoded value='true' />
<palaso:languageName value='language' />
<palaso:spellCheckingId value='ol' />
</special>
</ldml>".Replace('\'', '"'), language, script, region, variant);
}
static public string Version0WithCollationInfo(WritingSystemDefinitionV0.SortRulesType sortType)
{
string collationelement = GetCollationElementXml(sortType);
return String.Format(
@"<?xml version='1.0' encoding='utf-8'?>
<ldml>
<identity>
<version number='' />
<generation date='0001-01-01T00:00:00' />
<language type='en' />
</identity>
<layout>
<orientation characters='left-to-right'/>
</layout>
<collations>
{0}
</collations>
<special xmlns:palaso='urn://palaso.org/ldmlExtensions/v1'>
<palaso:abbreviation value='la' />
<palaso:defaultFontFamily value='Arial' />
<palaso:defaultFontSize value='12' />
<palaso:defaultKeyboard value='bogusKeyboard' />
<palaso:isLegacyEncoded value='true' />
<palaso:languageName value='language' />
<palaso:spellCheckingId value='ol' />
</special>
</ldml>".Replace('\'', '"'), collationelement);
}
static public string Version0WithLdmlInfoWeDontCareAbout(string language, string script, string region, string variant)
{
return String.Format(
@"<?xml version='1.0' encoding='utf-8'?>
<ldml>
<identity>
<version number='' />
<generation date='0001-01-01T00:00:00' />
<language type='{0}' />
<script type='{1}' />
<territory type='{2}' />
<variant type='{3}' />
</identity>
<fallback><testing>fallback</testing></fallback>
<localeDisplayNames><testing>localeDisplayNames</testing></localeDisplayNames>
<layout><testing>layout</testing></layout>
<characters><testing>characters</testing></characters>
<delimiters><testing>delimiters</testing></delimiters>
<measurement><testing>measurement</testing></measurement>
<dates><testing>dates</testing></dates>
<numbers><testing>numbers</testing></numbers>
<units><testing>units</testing></units>
<listPatterns><testing>listPatterns</testing></listPatterns>
<collations />
<posix><testing>posix</testing></posix>
<segmentations><testing>segmentations</testing></segmentations>
<rbnf><testing>rbnf</testing></rbnf>
<references><testing>references</testing></references>
<special xmlns:palaso='urn://palaso.org/ldmlExtensions/v1'>
<palaso:defaultFontFamily value='Arial' />
<palaso:defaultFontSize value='12' />
</special>
</ldml>".Replace('\'', '"'), language, script, region, variant);
}
private static string GetCollationElementXml(WritingSystemDefinitionV0.SortRulesType sortType)
{
string collationelement = String.Empty;
switch (sortType)
{
case WritingSystemDefinitionV0.SortRulesType.DefaultOrdering:
collationelement = String.Empty;
break;
case WritingSystemDefinitionV0.SortRulesType.CustomICU:
collationelement =
@"<collation>
<base>
<alias source='' />
</base>
<rules>
<reset>ab</reset><s>q</s><t>Q</t><reset>ad</reset><t>AD</t><p>x</p><t>X</t>
</rules>
<special xmlns:palaso='urn://palaso.org/ldmlExtensions/v1'>
<palaso:sortRulesType value='CustomICU' />
</special>
</collation>";
break;
case WritingSystemDefinitionV0.SortRulesType.CustomSimple:
collationelement =
@"<collation>
<base>
<alias source='' />
</base>
<rules>
<reset before='primary'><first_non_ignorable /></reset><p>a</p><s>A</s><p>b</p><s>B</s><p>o</p><s>O</s><p>m</p><s>M</s>
</rules>
<special xmlns:palaso='urn://palaso.org/ldmlExtensions/v1'>
<palaso:sortRulesType value='CustomSimple' />
</special>
</collation>";
break;
case WritingSystemDefinitionV0.SortRulesType.OtherLanguage:
collationelement =
@"<collation>
<base>
<alias source='en'/>
</base>
<rules>
<reset before='primary'><first_non_ignorable /></reset><p>a</p><s>A</s><p>b</p><s>B</s><p>o</p><s>O</s><p>m</p><s>M</s>
</rules>
<special xmlns:palaso='urn://palaso.org/ldmlExtensions/v1'>
<palaso:sortRulesType value='OtherLanguage' />
</special>
</collation>
";
break;
}
return collationelement;
}
static private string Version1(string language, string script, string region, string variant)
{
return
String.Format(@"<?xml version='1.0' encoding='utf-8'?>
<ldml>
<identity>
<version number='' />
<generation date='0001-01-01T00:00:00' />
<language type='{0}' />
<script type='{1}' />
<territory type='{2}' />
<variant type='{3}' />
</identity>
<collations />
<special xmlns:palaso='urn://palaso.org/ldmlExtensions/v1'>
<palaso:version value='1' />
<palaso:defaultFontFamily value='Arial' />
<palaso:defaultFontSize value='12' />
</special>
</ldml>".Replace('\'', '"'), language, script, region, variant);
}
static public string Version2(string language, string script, string region, string variant)
{
return
String.Format(@"<?xml version='1.0' encoding='utf-8'?>
<ldml>
<identity>
<version number='' />
<generation date='0001-01-01T00:00:00' />
<language type='{0}' />
<script type='{1}' />
<territory type='{2}' />
<variant type='{3}' />
</identity>
<collations />
<special xmlns:palaso='urn://palaso.org/ldmlExtensions/v1'>
<palaso:version value='2' />
<palaso:defaultFontFamily value='Arial' />
<palaso:defaultFontSize value='12' />
</special>
</ldml>".Replace('\'', '"'), language, script, region, variant);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyDateTime
{
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for Datetime.
/// </summary>
public static partial class DatetimeExtensions
{
/// <summary>
/// Get null datetime value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static System.DateTime? GetNull(this IDatetime operations)
{
return operations.GetNullAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Get null datetime value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<System.DateTime?> GetNullAsync(this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetNullWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get invalid datetime value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static System.DateTime? GetInvalid(this IDatetime operations)
{
return operations.GetInvalidAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Get invalid datetime value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<System.DateTime?> GetInvalidAsync(this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetInvalidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get overflow datetime value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static System.DateTime? GetOverflow(this IDatetime operations)
{
return operations.GetOverflowAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Get overflow datetime value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<System.DateTime?> GetOverflowAsync(this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetOverflowWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get underflow datetime value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static System.DateTime? GetUnderflow(this IDatetime operations)
{
return operations.GetUnderflowAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Get underflow datetime value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<System.DateTime?> GetUnderflowAsync(this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetUnderflowWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put max datetime value 9999-12-31T23:59:59.9999999Z
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='datetimeBody'>
/// </param>
public static void PutUtcMaxDateTime(this IDatetime operations, System.DateTime datetimeBody)
{
operations.PutUtcMaxDateTimeAsync(datetimeBody).GetAwaiter().GetResult();
}
/// <summary>
/// Put max datetime value 9999-12-31T23:59:59.9999999Z
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='datetimeBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutUtcMaxDateTimeAsync(this IDatetime operations, System.DateTime datetimeBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutUtcMaxDateTimeWithHttpMessagesAsync(datetimeBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get max datetime value 9999-12-31t23:59:59.9999999z
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static System.DateTime? GetUtcLowercaseMaxDateTime(this IDatetime operations)
{
return operations.GetUtcLowercaseMaxDateTimeAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Get max datetime value 9999-12-31t23:59:59.9999999z
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<System.DateTime?> GetUtcLowercaseMaxDateTimeAsync(this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetUtcLowercaseMaxDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get max datetime value 9999-12-31T23:59:59.9999999Z
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static System.DateTime? GetUtcUppercaseMaxDateTime(this IDatetime operations)
{
return operations.GetUtcUppercaseMaxDateTimeAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Get max datetime value 9999-12-31T23:59:59.9999999Z
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<System.DateTime?> GetUtcUppercaseMaxDateTimeAsync(this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetUtcUppercaseMaxDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put max datetime value with positive numoffset
/// 9999-12-31t23:59:59.9999999+14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='datetimeBody'>
/// </param>
public static void PutLocalPositiveOffsetMaxDateTime(this IDatetime operations, System.DateTime datetimeBody)
{
operations.PutLocalPositiveOffsetMaxDateTimeAsync(datetimeBody).GetAwaiter().GetResult();
}
/// <summary>
/// Put max datetime value with positive numoffset
/// 9999-12-31t23:59:59.9999999+14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='datetimeBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutLocalPositiveOffsetMaxDateTimeAsync(this IDatetime operations, System.DateTime datetimeBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutLocalPositiveOffsetMaxDateTimeWithHttpMessagesAsync(datetimeBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get max datetime value with positive num offset
/// 9999-12-31t23:59:59.9999999+14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static System.DateTime? GetLocalPositiveOffsetLowercaseMaxDateTime(this IDatetime operations)
{
return operations.GetLocalPositiveOffsetLowercaseMaxDateTimeAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Get max datetime value with positive num offset
/// 9999-12-31t23:59:59.9999999+14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<System.DateTime?> GetLocalPositiveOffsetLowercaseMaxDateTimeAsync(this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetLocalPositiveOffsetLowercaseMaxDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get max datetime value with positive num offset
/// 9999-12-31T23:59:59.9999999+14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static System.DateTime? GetLocalPositiveOffsetUppercaseMaxDateTime(this IDatetime operations)
{
return operations.GetLocalPositiveOffsetUppercaseMaxDateTimeAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Get max datetime value with positive num offset
/// 9999-12-31T23:59:59.9999999+14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<System.DateTime?> GetLocalPositiveOffsetUppercaseMaxDateTimeAsync(this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetLocalPositiveOffsetUppercaseMaxDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put max datetime value with positive numoffset
/// 9999-12-31t23:59:59.9999999-14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='datetimeBody'>
/// </param>
public static void PutLocalNegativeOffsetMaxDateTime(this IDatetime operations, System.DateTime datetimeBody)
{
operations.PutLocalNegativeOffsetMaxDateTimeAsync(datetimeBody).GetAwaiter().GetResult();
}
/// <summary>
/// Put max datetime value with positive numoffset
/// 9999-12-31t23:59:59.9999999-14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='datetimeBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutLocalNegativeOffsetMaxDateTimeAsync(this IDatetime operations, System.DateTime datetimeBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutLocalNegativeOffsetMaxDateTimeWithHttpMessagesAsync(datetimeBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get max datetime value with positive num offset
/// 9999-12-31T23:59:59.9999999-14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static System.DateTime? GetLocalNegativeOffsetUppercaseMaxDateTime(this IDatetime operations)
{
return operations.GetLocalNegativeOffsetUppercaseMaxDateTimeAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Get max datetime value with positive num offset
/// 9999-12-31T23:59:59.9999999-14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<System.DateTime?> GetLocalNegativeOffsetUppercaseMaxDateTimeAsync(this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetLocalNegativeOffsetUppercaseMaxDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get max datetime value with positive num offset
/// 9999-12-31t23:59:59.9999999-14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static System.DateTime? GetLocalNegativeOffsetLowercaseMaxDateTime(this IDatetime operations)
{
return operations.GetLocalNegativeOffsetLowercaseMaxDateTimeAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Get max datetime value with positive num offset
/// 9999-12-31t23:59:59.9999999-14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<System.DateTime?> GetLocalNegativeOffsetLowercaseMaxDateTimeAsync(this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetLocalNegativeOffsetLowercaseMaxDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put min datetime value 0001-01-01T00:00:00Z
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='datetimeBody'>
/// </param>
public static void PutUtcMinDateTime(this IDatetime operations, System.DateTime datetimeBody)
{
operations.PutUtcMinDateTimeAsync(datetimeBody).GetAwaiter().GetResult();
}
/// <summary>
/// Put min datetime value 0001-01-01T00:00:00Z
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='datetimeBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutUtcMinDateTimeAsync(this IDatetime operations, System.DateTime datetimeBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutUtcMinDateTimeWithHttpMessagesAsync(datetimeBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get min datetime value 0001-01-01T00:00:00Z
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static System.DateTime? GetUtcMinDateTime(this IDatetime operations)
{
return operations.GetUtcMinDateTimeAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Get min datetime value 0001-01-01T00:00:00Z
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<System.DateTime?> GetUtcMinDateTimeAsync(this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetUtcMinDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put min datetime value 0001-01-01T00:00:00+14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='datetimeBody'>
/// </param>
public static void PutLocalPositiveOffsetMinDateTime(this IDatetime operations, System.DateTime datetimeBody)
{
operations.PutLocalPositiveOffsetMinDateTimeAsync(datetimeBody).GetAwaiter().GetResult();
}
/// <summary>
/// Put min datetime value 0001-01-01T00:00:00+14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='datetimeBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutLocalPositiveOffsetMinDateTimeAsync(this IDatetime operations, System.DateTime datetimeBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutLocalPositiveOffsetMinDateTimeWithHttpMessagesAsync(datetimeBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get min datetime value 0001-01-01T00:00:00+14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static System.DateTime? GetLocalPositiveOffsetMinDateTime(this IDatetime operations)
{
return operations.GetLocalPositiveOffsetMinDateTimeAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Get min datetime value 0001-01-01T00:00:00+14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<System.DateTime?> GetLocalPositiveOffsetMinDateTimeAsync(this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetLocalPositiveOffsetMinDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put min datetime value 0001-01-01T00:00:00-14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='datetimeBody'>
/// </param>
public static void PutLocalNegativeOffsetMinDateTime(this IDatetime operations, System.DateTime datetimeBody)
{
operations.PutLocalNegativeOffsetMinDateTimeAsync(datetimeBody).GetAwaiter().GetResult();
}
/// <summary>
/// Put min datetime value 0001-01-01T00:00:00-14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='datetimeBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutLocalNegativeOffsetMinDateTimeAsync(this IDatetime operations, System.DateTime datetimeBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutLocalNegativeOffsetMinDateTimeWithHttpMessagesAsync(datetimeBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get min datetime value 0001-01-01T00:00:00-14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static System.DateTime? GetLocalNegativeOffsetMinDateTime(this IDatetime operations)
{
return operations.GetLocalNegativeOffsetMinDateTimeAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Get min datetime value 0001-01-01T00:00:00-14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<System.DateTime?> GetLocalNegativeOffsetMinDateTimeAsync(this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetLocalNegativeOffsetMinDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// 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 Searchservice
{
using Microsoft.Rest;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Indexes operations.
/// </summary>
public partial class Indexes : IServiceOperations<SearchandStorage>, IIndexes
{
/// <summary>
/// Initializes a new instance of the Indexes class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public Indexes(SearchandStorage client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the SearchandStorage
/// </summary>
public SearchandStorage Client { get; private set; }
/// <summary>
/// Creates a new Azure Search index.
/// <see href="https://msdn.microsoft.com/library/azure/dn798941.aspx" />
/// </summary>
/// <param name='index'>
/// The definition of the index to create.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Index>> CreateWithHttpMessagesAsync(Index index, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (index == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "index");
}
if (index != null)
{
index.Validate();
}
string apiVersion = "2015-02-28";
System.Guid? clientRequestId = default(System.Guid?);
if (searchRequestOptions != null)
{
clientRequestId = searchRequestOptions.ClientRequestId;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("index", index);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("clientRequestId", clientRequestId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "indexes").ToString();
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (clientRequestId != null)
{
if (_httpRequest.Headers.Contains("client-request-id"))
{
_httpRequest.Headers.Remove("client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(clientRequestId, Client.SerializationSettings).Trim('"'));
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(index != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(index, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 201)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Index>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Index>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists all indexes available for an Azure Search service.
/// <see href="https://msdn.microsoft.com/library/azure/dn798923.aspx" />
/// </summary>
/// <param name='select'>
/// Selects which properties of the index definitions to retrieve. Specified as
/// a comma-separated list of JSON property names, or '*' for all properties.
/// The default is all properties.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<IndexListResult>> ListWithHttpMessagesAsync(string select = default(string), SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
string apiVersion = "2015-02-28";
System.Guid? clientRequestId = default(System.Guid?);
if (searchRequestOptions != null)
{
clientRequestId = searchRequestOptions.ClientRequestId;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("select", select);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("clientRequestId", clientRequestId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "indexes").ToString();
List<string> _queryParameters = new List<string>();
if (select != null)
{
_queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(select)));
}
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (clientRequestId != null)
{
if (_httpRequest.Headers.Contains("client-request-id"))
{
_httpRequest.Headers.Remove("client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(clientRequestId, Client.SerializationSettings).Trim('"'));
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<IndexListResult>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<IndexListResult>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates a new Azure Search index or updates an index if it already exists.
/// <see href="https://msdn.microsoft.com/library/azure/dn800964.aspx" />
/// </summary>
/// <param name='indexName'>
/// The definition of the index to create or update.
/// </param>
/// <param name='index'>
/// The definition of the index to create or update.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Index>> CreateOrUpdateWithHttpMessagesAsync(string indexName, Index index, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (indexName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "indexName");
}
if (index == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "index");
}
if (index != null)
{
index.Validate();
}
string apiVersion = "2015-02-28";
System.Guid? clientRequestId = default(System.Guid?);
if (searchRequestOptions != null)
{
clientRequestId = searchRequestOptions.ClientRequestId;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("indexName", indexName);
tracingParameters.Add("index", index);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("clientRequestId", clientRequestId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "indexes('{indexName}')").ToString();
_url = _url.Replace("{indexName}", System.Uri.EscapeDataString(indexName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (clientRequestId != null)
{
if (_httpRequest.Headers.Contains("client-request-id"))
{
_httpRequest.Headers.Remove("client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(clientRequestId, Client.SerializationSettings).Trim('"'));
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(index != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(index, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Index>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Index>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Index>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes an Azure Search index and all the documents it contains.
/// <see href="https://msdn.microsoft.com/library/azure/dn798926.aspx" />
/// </summary>
/// <param name='indexName'>
/// The name of the index to delete.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> DeleteWithHttpMessagesAsync(string indexName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (indexName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "indexName");
}
string apiVersion = "2015-02-28";
System.Guid? clientRequestId = default(System.Guid?);
if (searchRequestOptions != null)
{
clientRequestId = searchRequestOptions.ClientRequestId;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("indexName", indexName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("clientRequestId", clientRequestId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "indexes('{indexName}')").ToString();
_url = _url.Replace("{indexName}", System.Uri.EscapeDataString(indexName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (clientRequestId != null)
{
if (_httpRequest.Headers.Contains("client-request-id"))
{
_httpRequest.Headers.Remove("client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(clientRequestId, Client.SerializationSettings).Trim('"'));
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204 && (int)_statusCode != 404)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Retrieves an index definition from Azure Search.
/// <see href="https://msdn.microsoft.com/library/azure/dn798939.aspx" />
/// </summary>
/// <param name='indexName'>
/// The name of the index to retrieve.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Index>> GetWithHttpMessagesAsync(string indexName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (indexName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "indexName");
}
string apiVersion = "2015-02-28";
System.Guid? clientRequestId = default(System.Guid?);
if (searchRequestOptions != null)
{
clientRequestId = searchRequestOptions.ClientRequestId;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("indexName", indexName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("clientRequestId", clientRequestId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "indexes('{indexName}')").ToString();
_url = _url.Replace("{indexName}", System.Uri.EscapeDataString(indexName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (clientRequestId != null)
{
if (_httpRequest.Headers.Contains("client-request-id"))
{
_httpRequest.Headers.Remove("client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(clientRequestId, Client.SerializationSettings).Trim('"'));
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Index>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Index>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Returns statistics for the given index, including a document count and
/// storage usage.
/// <see href="https://msdn.microsoft.com/library/azure/dn798942.aspx" />
/// </summary>
/// <param name='indexName'>
/// The name of the index for which to retrieve statistics.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<IndexGetStatisticsResult>> GetStatisticsWithHttpMessagesAsync(string indexName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (indexName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "indexName");
}
string apiVersion = "2015-02-28";
System.Guid? clientRequestId = default(System.Guid?);
if (searchRequestOptions != null)
{
clientRequestId = searchRequestOptions.ClientRequestId;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("indexName", indexName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("clientRequestId", clientRequestId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetStatistics", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "indexes('{indexName}')/search.stats").ToString();
_url = _url.Replace("{indexName}", System.Uri.EscapeDataString(indexName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (clientRequestId != null)
{
if (_httpRequest.Headers.Contains("client-request-id"))
{
_httpRequest.Headers.Remove("client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(clientRequestId, Client.SerializationSettings).Trim('"'));
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<IndexGetStatisticsResult>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<IndexGetStatisticsResult>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Xaml.Media;
using Windows.Media.DialProtocol;
using ScreenCasting.Data.Azure;
using System.Collections.Generic;
using ScreenCasting.Data.Common;
using Windows.Devices.Enumeration;
using System.Threading.Tasks;
using Windows.Media.Casting;
using ScreenCasting.Controls;
using ScreenCasting.Util;
using Windows.UI;
using Windows.UI.ViewManagement;
using Windows.ApplicationModel.Core;
using Windows.UI.Core;
using Windows.UI.Xaml.Media.Imaging;
namespace ScreenCasting
{
public sealed partial class Scenario06 : Page
{
private const int MAX_RESULTS = 10;
private MainPage rootPage;
private DevicePicker picker = null;
private DeviceInformation activeDevice = null;
private object activeCastConnectionHandler = null;
private VideoMetaData video = null;
int thisViewId;
public Scenario06()
{
this.InitializeComponent();
rootPage = MainPage.Current;
//Subscribe to player events
player.MediaOpened += Player_MediaOpened;
player.MediaFailed += Player_MediaFailed;
player.CurrentStateChanged += Player_CurrentStateChanged;
// Get an Azure hosted video
AzureDataProvider dataProvider = new AzureDataProvider();
video = dataProvider.GetRandomVideo();
//Set the source on the player
rootPage.NotifyUser(string.Format("Opening '{0}'", video.Title), NotifyType.StatusMessage);
this.player.Source = video.VideoLink;
//Configure the DIAL launch arguments for the current video
this.dial_launch_args_textbox.Text = string.Format("v={0}&t=0&pairingCode=E4A8136D-BCD3-45F4-8E49-AE01E9A46B5F", video.Id);
//Subscribe for the clicked event on the custom cast button
((MediaTransportControlsWithCustomCastButton)this.player.TransportControls).CastButtonClicked += TransportControls_CastButtonClicked;
// Instantiate the Device Picker
picker = new DevicePicker();
//Hook up device selected event
picker.DeviceSelected += Picker_DeviceSelected;
//Hook up device disconnected event
picker.DisconnectButtonClicked += Picker_DisconnectButtonClicked;
//Hook up device disconnected event
picker.DevicePickerDismissed += Picker_DevicePickerDismissed;
//Add the DIAL Filter, so that the application only shows DIAL devices that have the application installed or advertise that they can install them.
picker.Filter.SupportedDeviceSelectors.Add(DialDevice.GetDeviceSelector(this.dial_appname_textbox.Text));
//Add the CAST API Filter, so that the application only shows Miracast, Bluetooth, DLNA devices that can render the video
//picker.Filter.SupportedDeviceSelectors.Add(await CastingDevice.GetDeviceSelectorFromCastingSourceAsync(player.GetAsCastingSource()));
//picker.Filter.SupportedDeviceSelectors.Add(CastingDevice.GetDeviceSelector(CastingPlaybackTypes.Video));
picker.Filter.SupportedDeviceSelectors.Add("System.Devices.InterfaceClassGuid:=\"{D0875FB4-2196-4c7a-A63D-E416ADDD60A1}\"" + " AND System.Devices.InterfaceEnabled:=System.StructuredQueryType.Boolean#True");
//Add projection manager filter
picker.Filter.SupportedDeviceSelectors.Add(ProjectionManager.GetDeviceSelector());
pvb.ProjectionStopping += Pvb_ProjectionStopping;
}
ProjectionViewBroker pvb = new ProjectionViewBroker();
private void TransportControls_CastButtonClicked(object sender, EventArgs e)
{
//Pause Current Playback
player.Pause();
rootPage.NotifyUser("Show Device Picker Button Clicked", NotifyType.StatusMessage);
//Get the custom transport controls
MediaTransportControlsWithCustomCastButton mtc = (MediaTransportControlsWithCustomCastButton)this.player.TransportControls;
//Retrieve the location of the casting button
GeneralTransform transform = mtc.CastButton.TransformToVisual(Window.Current.Content as UIElement);
Point pt = transform.TransformPoint(new Point(0, 0));
//Show the picker above our Show Device Picker button
picker.Show(new Rect(pt.X, pt.Y, mtc.CastButton.ActualWidth, mtc.CastButton.ActualHeight), Windows.UI.Popups.Placement.Above);
}
#region Windows.Devices.Enumeration.DevicePicker Methods
private async void Picker_DeviceSelected(DevicePicker sender, DeviceSelectedEventArgs args)
{
string deviceId = args.SelectedDevice.Id;
//Casting must occur from the UI thread. This dispatches the casting calls to the UI thread.
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
//Update the display status for the selected device to connecting.
picker.SetDisplayStatus(args.SelectedDevice, "Connecting", DevicePickerDisplayStatusOptions.ShowProgress);
// BUG: In order to support debugging it is best to retreive the device from the local app instead
// of continuing to use the DeviceInformation instance that is proxied from the picker.
DeviceInformation device = await DeviceInformation.CreateFromIdAsync(deviceId);
bool castSucceeded = false;
// The dial AssociationEndpoint ID will have 'dial' in the string.
// If it doesn't try the ProjectionManager API.
if (deviceId.IndexOf("dial", StringComparison.OrdinalIgnoreCase) == -1)
castSucceeded = await TryProjectionManagerCastAsync(device);
// If the ProjectionManager API did not work and the device id will have 'dial' in it.
if (!castSucceeded && deviceId.IndexOf("dial", StringComparison.OrdinalIgnoreCase) > -1)
castSucceeded = await TryLaunchDialAppAsync(device);
//If DIAL and ProjectionManager did not work for the selected device, try the CAST API
if (!castSucceeded)
castSucceeded = await TryCastMediaElementAsync(device);
if (castSucceeded)
{
//Update the display status for the selected device. Try Catch in case the picker is not visible anymore.
try { picker.SetDisplayStatus(device, "Connected", DevicePickerDisplayStatusOptions.ShowDisconnectButton); } catch { }
// Hide the picker now that all the work is completed. Try Catch in case the picker is not visible anymore.
try { picker.Hide(); } catch { }
}
else
{
//Show a retry button when connecting to the selected device failed.
try { picker.SetDisplayStatus(device, "Connecting failed", DevicePickerDisplayStatusOptions.ShowRetryButton); } catch { }
}
});
}
private async void Picker_DevicePickerDismissed(DevicePicker sender, object args)
{
//Casting must occur from the UI thread. This dispatches the casting calls to the UI thread.
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
if (activeDevice == null)
{
player.Play();
}
});
}
private async void Picker_DisconnectButtonClicked(DevicePicker sender, DeviceDisconnectButtonClickedEventArgs args)
{
//Casting must occur from the UI thread. This dispatches the casting calls to the UI thread.
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
rootPage.NotifyUser("Disconnect Button clicked", NotifyType.StatusMessage);
//Update the display status for the selected device.
sender.SetDisplayStatus(args.Device, "Disconnecting", DevicePickerDisplayStatusOptions.ShowProgress);
bool disconnected = false;
if (this.activeCastConnectionHandler is ProjectionViewBroker)
disconnected = TryStopProjectionManagerAsync((ProjectionViewBroker)activeCastConnectionHandler);
if (this.activeCastConnectionHandler is DialApp)
disconnected = await TryStopDialAppAsync((DialApp)activeCastConnectionHandler);
if (this.activeCastConnectionHandler is CastingConnection)
disconnected = await TryDisconnectCastingSessionAsync((CastingConnection)activeCastConnectionHandler);
if (disconnected)
{
//Update the display status for the selected device.
try { sender.SetDisplayStatus(args.Device, "Disconnected", DevicePickerDisplayStatusOptions.None); } catch { }
// Set the active device variables to null
activeDevice = null;
activeCastConnectionHandler = null;
//Hide the picker
sender.Hide();
}
else
{
//Update the display status for the selected device.
sender.SetDisplayStatus(args.Device, "Disconnect failed", DevicePickerDisplayStatusOptions.ShowDisconnectButton);
}
});
}
#endregion
#region ProjectionManager APIs
private async Task<bool> TryProjectionManagerCastAsync(DeviceInformation device)
{
bool projectionManagerCastAsyncSucceeded = false;
if ((activeDevice ==null && ProjectionManager.ProjectionDisplayAvailable && device == null) || device != null)
{
thisViewId = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().Id;
// If projection is already in progress, then it could be shown on the monitor again
// Otherwise, we need to create a new view to show the presentation
if (rootPage.ProjectionViewPageControl == null)
{
// First, create a new, blank view
var thisDispatcher = Window.Current.Dispatcher;
await CoreApplication.CreateNewView().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
// ViewLifetimeControl is a wrapper to make sure the view is closed only
// when the app is done with it
rootPage.ProjectionViewPageControl = ViewLifetimeControl.CreateForCurrentView();
// Assemble some data necessary for the new page
pvb.MainPageDispatcher = thisDispatcher;
pvb.ProjectionViewPageControl = rootPage.ProjectionViewPageControl;
pvb.MainViewId = thisViewId;
// Display the page in the view. Note that the view will not become visible
// until "StartProjectingAsync" is called
var rootFrame = new Frame();
rootFrame.Navigate(typeof(ProjectionViewPage), pvb);
Window.Current.Content = rootFrame;
Window.Current.Activate();
});
}
try
{
// Start/StopViewInUse are used to signal that the app is interacting with the
// view, so it shouldn't be closed yet, even if the user loses access to it
rootPage.ProjectionViewPageControl.StartViewInUse();
try
{
await ProjectionManager.StartProjectingAsync(rootPage.ProjectionViewPageControl.Id, thisViewId, device);
}
catch (Exception ex)
{
if (!ProjectionManager.ProjectionDisplayAvailable)
throw ex;
}
if (pvb.ProjectedPage != null)
{
this.player.Pause();
await pvb.ProjectedPage.SetMediaSource(this.player.Source, this.player.Position);
}
if (device != null)
{
activeDevice = device;
activeCastConnectionHandler = pvb;
}
projectionManagerCastAsyncSucceeded = true;
}
catch (Exception)
{
rootPage.NotifyUser("The projection view is being disposed", NotifyType.ErrorMessage);
}
ApplicationView.GetForCurrentView().ExitFullScreenMode();
}
return projectionManagerCastAsyncSucceeded;
}
private bool TryStopProjectionManagerAsync(ProjectionViewBroker broker)
{
broker.ProjectedPage.StopProjecting();
return true;
}
private async void Pvb_ProjectionStopping(object sender, EventArgs e)
{
ProjectionViewBroker broker = sender as ProjectionViewBroker;
TimeSpan position = broker.ProjectedPage.Player.Position;
Uri source = broker.ProjectedPage.Player.Source;
await rootPage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
rootPage.NotifyUser("Resuming playback on the first screen", NotifyType.StatusMessage);
this.player.Source = source;
this.player.Position = position;
this.player.Play();
rootPage.ProjectionViewPageControl = null;
});
}
#endregion
#region Windows.Media.Casting APIs
private async Task<bool> TryCastMediaElementAsync(DeviceInformation device)
{
bool castMediaElementSucceeded = false;
//Verify whether the selected device supports DLNA, Bluetooth, or Miracast.
rootPage.NotifyUser(string.Format("Checking to see if device {0} supports Miracast, Bluetooth, or DLNA", device.Name), NotifyType.StatusMessage);
//BUG: Takes too long. Workaround, just try to create the CastingDevice
//if (await CastingDevice.DeviceInfoSupportsCastingAsync(device))
//{
CastingConnection connection = null;
//Check to see whether we are casting to the same device
if (activeDevice != null && device.Id == activeDevice.Id)
connection = activeCastConnectionHandler as CastingConnection;
else // if not casting to the same device reset the active device related variables.
{
activeDevice = null;
activeCastConnectionHandler = null;
}
// If we can re-use the existing connection
if (connection == null || connection.State == CastingConnectionState.Disconnected || connection.State == CastingConnectionState.Disconnecting)
{
CastingDevice castDevice = null;
activeDevice = null;
//Try to create a CastingDevice instannce. If it doesn't succeed, the selected device does not support playback of the video source.
rootPage.NotifyUser(string.Format("Attempting to resolve casting device for '{0}'", device.Name), NotifyType.StatusMessage);
try { castDevice = await CastingDevice.FromIdAsync(device.Id); } catch { }
if (castDevice == null)
{
//Try to create a DIAL device. If it doesn't succeed, the selected device does not support DIAL.
rootPage.NotifyUser(string.Format("'{0}' does not support playback of this media", device.Name), NotifyType.StatusMessage);
}
else
{
//Create a casting conneciton from our selected casting device
rootPage.NotifyUser(string.Format("Creating connection for '{0}'", device.Name), NotifyType.StatusMessage);
connection = castDevice.CreateCastingConnection();
//Hook up the casting events
connection.ErrorOccurred += Connection_ErrorOccurred;
connection.StateChanged += Connection_StateChanged;
}
//Cast the content loaded in the media element to the selected casting device
rootPage.NotifyUser(string.Format("Casting to '{0}'", device.Name), NotifyType.StatusMessage);
CastingSource source = null;
// Get the casting source
try { source = player.GetAsCastingSource(); } catch { }
if (source == null)
{
rootPage.NotifyUser(string.Format("Failed to get casting source for video '{0}'", video.Title), NotifyType.ErrorMessage);
}
else
{
CastingConnectionErrorStatus status = await connection.RequestStartCastingAsync(source);
if (status == CastingConnectionErrorStatus.Succeeded)
{
//Remember the device to which casting succeeded
activeDevice = device;
//Remember the current active connection.
activeCastConnectionHandler = connection;
castMediaElementSucceeded = true;
player.Play();
}
else
{
rootPage.NotifyUser(string.Format("Failed to cast to '{0}'", device.Name), NotifyType.ErrorMessage);
}
}
//}
}
return castMediaElementSucceeded;
}
private async void Connection_StateChanged(CastingConnection sender, object args)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
rootPage.NotifyUser("Casting Connection State Changed: " + sender.State, NotifyType.StatusMessage);
});
}
private async void Connection_ErrorOccurred(CastingConnection sender, CastingConnectionErrorOccurredEventArgs args)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
rootPage.NotifyUser("Casting Error Occured: " + args.Message, NotifyType.ErrorMessage);
activeDevice = null;
activeCastConnectionHandler = null;
});
}
private async Task<bool> TryDisconnectCastingSessionAsync(CastingConnection connection)
{
bool disconnected = false;
//Disconnect the casting session
CastingConnectionErrorStatus status = await connection.DisconnectAsync();
if (status == CastingConnectionErrorStatus.Succeeded)
{
rootPage.NotifyUser("Connection disconnected successfully.", NotifyType.StatusMessage);
disconnected = true;
}
else
{
rootPage.NotifyUser(string.Format("Failed to disconnect connection with reason {0}.", status.ToString()), NotifyType.ErrorMessage);
}
return disconnected;
}
#endregion
#region Windows.Media.DialProtocol APIs
private async Task<bool> TryLaunchDialAppAsync(DeviceInformation device)
{
bool dialAppLaunchSucceeded = false;
if (device.Id.IndexOf("dial", StringComparison.OrdinalIgnoreCase) > -1)
{
//Update the launch arguments to include the Position
this.dial_launch_args_textbox.Text = string.Format("v={0}&t={1}&pairingCode=E4A8136D-BCD3-45F4-8E49-AE01E9A46B5F", video.Id, player.Position.Ticks);
//Try to create a DIAL device. If it doesn't succeed, the selected device does not support DIAL.
rootPage.NotifyUser(string.Format("Checking to see if device {0} supports DIAL", device.Name), NotifyType.StatusMessage);
//BUG: Takes too long. Workaround, just try to create the DialDevice
//if (await DialDevice.DeviceInfoSupportsDialAsync(device))
//{
DialDevice dialDevice = null;
//Try to create a DIAL device. If it doesn't succeed, the selected device does not support DIAL.
rootPage.NotifyUser(string.Format("Attempting to resolve DIAL device for '{0}'", device.Name), NotifyType.StatusMessage);
try { dialDevice = await DialDevice.FromIdAsync(device.Id); } catch { }
if (dialDevice == null)
{
//Try to create a DIAL device. If it doesn't succeed, the selected device does not support DIAL.
rootPage.NotifyUser(string.Format("'{0}' does not support DIAL", device.Name), NotifyType.StatusMessage);
}
else
{
//Get the DialApp object for the specific application on the selected device
DialApp app = dialDevice.GetDialApp(this.dial_appname_textbox.Text);
if (app == null)
{
//Try to create a DIAL device. If it doesn't succeed, the selected device does not support DIAL.
rootPage.NotifyUser(string.Format("'{0}' cannot find app with ID '{1}'", device.Name, this.dial_appname_textbox.Text), NotifyType.StatusMessage);
}
else
{
//Get the current application state
DialAppStateDetails stateDetails = await app.GetAppStateAsync();
if (stateDetails.State == DialAppState.NetworkFailure)
{
// In case getting the application state failed because of a network failure
rootPage.NotifyUser("Network Failure while getting application state", NotifyType.ErrorMessage);
}
else
{
rootPage.NotifyUser(string.Format("Attempting to launch '{0}'", app.AppName), NotifyType.StatusMessage);
//Launch the application on the 1st screen device
DialAppLaunchResult result = await app.RequestLaunchAsync(this.dial_launch_args_textbox.Text);
//Verify to see whether the application was launched
if (result == DialAppLaunchResult.Launched)
{
//Remember the device to which casting succeeded
activeDevice = device;
//DIAL is sessionsless but the DIAL app allows us to get the state and "disconnect".
//Disconnect in the case of DIAL is equivalenet to stopping the app.
activeCastConnectionHandler = app;
rootPage.NotifyUser(string.Format("Launched '{0}'", app.AppName), NotifyType.StatusMessage);
//This is where you will need to add you application specific communication between your 1st and 2nd screen applications
//...
dialAppLaunchSucceeded = true;
}
}
}
}
//}
//else
//{
// rootPage.NotifyUser(string.Format("'{0}' does not support DIAL", device.Name), NotifyType.StatusMessage);
//}
}
else
{
rootPage.NotifyUser(string.Format("'{0}' does not support DIAL", device.Name), NotifyType.StatusMessage);
}
return dialAppLaunchSucceeded;
}
private async Task<bool> TryStopDialAppAsync(DialApp app)
{
bool stopped = false;
//Get the current application state
DialAppStateDetails stateDetails = await app.GetAppStateAsync();
switch (stateDetails.State)
{
case DialAppState.NetworkFailure:
{
// In case getting the application state failed because of a network failure, you could add retry logic
rootPage.NotifyUser("Network Failure while getting application state", NotifyType.ErrorMessage);
break;
}
case DialAppState.Stopped:
{
stopped = true;
// In case getting the application state failed because of a network failure, you could add retry logic
rootPage.NotifyUser("Application was already stopped.", NotifyType.StatusMessage);
break;
}
default:
{
DialAppStopResult result = await app.StopAsync();
if (result == DialAppStopResult.Stopped)
{
stopped = true;
// In case getting the application state failed because of a network failure, you could add retry logic
rootPage.NotifyUser("Application stopped successfully.", NotifyType.StatusMessage);
}
else
{
if (result == DialAppStopResult.StopFailed || result == DialAppStopResult.NetworkFailure)
{
// In case getting the application state failed because of a network failure, you could add retry logic
rootPage.NotifyUser(string.Format("Error occured trying to stop application. Status: '{0}'", result.ToString()), NotifyType.StatusMessage);
}
else //in case of DialAppStopResult.OperationNotSupported, there is not much more you can do. You could implement your own
// mechanism to stop the application on that device.
{
stopped = true;
// In case getting the application state failed because of a network failure, you could add retry logic
rootPage.NotifyUser(string.Format("Stop is not supported by device: '{0}'", activeDevice.Name), NotifyType.ErrorMessage);
}
}
break;
}
}
return stopped;
}
#endregion
#region Media Element Status Methods
private void Player_CurrentStateChanged(object sender, RoutedEventArgs e)
{
// Update status
rootPage.NotifyUser(string.Format("{0} '{1}'", this.player.CurrentState, video.Title), NotifyType.StatusMessage);
}
private void Player_MediaFailed(object sender, ExceptionRoutedEventArgs e)
{
rootPage.NotifyUser(string.Format("Failed to load '{0}'", video.Title), NotifyType.ErrorMessage);
}
private void Player_MediaOpened(object sender, RoutedEventArgs e)
{
rootPage.NotifyUser(string.Format("Openend '{0}'", video.Title), NotifyType.StatusMessage);
player.Play();
}
#endregion
protected override void OnNavigatedTo(NavigationEventArgs e)
{
rootPage = MainPage.Current;
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: SampleIB.SampleIBPublic
File: SecuritiesWindow.xaml.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace SampleIB
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using Ecng.Collections;
using Ecng.Common;
using Ecng.Xaml;
using MoreLinq;
using StockSharp.Algo.Candles;
using StockSharp.BusinessEntities;
using StockSharp.InteractiveBrokers;
using StockSharp.Xaml;
using StockSharp.Localization;
using StockSharp.Messages;
public partial class SecuritiesWindow
{
private readonly SynchronizedDictionary<Security, QuotesWindow> _quotesWindows = new SynchronizedDictionary<Security, QuotesWindow>();
private readonly SynchronizedDictionary<CandleSeries, CandlesWindow> _historyCandles = new SynchronizedDictionary<CandleSeries, CandlesWindow>();
private readonly SynchronizedDictionary<CandleSeries, CandlesWindow> _realTimeCandles = new SynchronizedDictionary<CandleSeries, CandlesWindow>();
private readonly Dictionary<Security, long[]> _reportSecurities = new Dictionary<Security, long[]>();
private readonly Dictionary<Security, long> _optionSecurities = new Dictionary<Security, long>();
private bool _initialized;
private long? _scannerId;
public SecuritiesWindow()
{
InitializeComponent();
CandlesPeriods.ItemsSource = InteractiveBrokersTimeFrames.AllTimeFrames;
CandlesPeriods.SelectedItem = InteractiveBrokersTimeFrames.Hour;
}
protected override void OnClosed(EventArgs e)
{
_quotesWindows.SyncDo(d => d.Values.ForEach(w =>
{
w.DeleteHideable();
w.Close();
}));
if (Trader != null)
{
if (_initialized)
Trader.MarketDepthChanged -= TraderOnMarketDepthChanged;
if (_scannerId != null)
{
Trader.UnSubscribeScanner(_scannerId.Value);
_scannerId = null;
}
_reportSecurities.SelectMany(p => p.Value).ForEach(Trader.UnSubscribeFundamentalReport);
_optionSecurities.ForEach(p => Trader.UnSubscribeOptionCalc(p.Value));
_reportSecurities.Clear();
_optionSecurities.Clear();
}
base.OnClosed(e);
}
private void NewOrderClick(object sender, RoutedEventArgs e)
{
var newOrder = new OrderWindow
{
Order = new Order { Security = SecurityPicker.SelectedSecurity },
SecurityProvider = Trader,
MarketDataProvider = Trader,
Portfolios = new PortfolioDataSource(Trader),
};
if (newOrder.ShowModal(this))
Trader.RegisterOrder(newOrder.Order);
}
private Security SelectedSecurity => SecurityPicker.SelectedSecurity;
private static InteractiveBrokersTrader Trader => MainWindow.Instance.Trader;
private void SecurityPicker_OnSecuritySelected(Security security)
{
Level1.IsEnabled = Reports.IsEnabled = NewOrder.IsEnabled = Depth.IsEnabled = HistoryCandles.IsEnabled = RealTimeCandles.IsEnabled = security != null;
if (security == null)
return;
Level1.IsChecked = Trader.RegisteredSecurities.Contains(SelectedSecurity);
Reports.IsChecked = _reportSecurities.ContainsKey(SelectedSecurity);
Options.IsChecked = _optionSecurities.ContainsKey(SelectedSecurity);
RealTimeCandles.IsChecked = _realTimeCandles.Keys.Any(s => s.Security == SelectedSecurity);
Depth.IsChecked = _quotesWindows.ContainsKey(SelectedSecurity);
}
private void Level1Click(object sender, RoutedEventArgs e)
{
var security = SecurityPicker.SelectedSecurity;
var trader = Trader;
if (trader.RegisteredSecurities.Contains(security))
{
trader.UnRegisterSecurity(security);
//trader.UnRegisterTrades(security);
}
else
{
trader.RegisterSecurity(security);
//trader.RegisterTrades(security);
}
}
private void DepthClick(object sender, RoutedEventArgs e)
{
if (Depth.IsChecked == false)
{
// create order book window
var wnd = new QuotesWindow { Title = SelectedSecurity.Id + " " + LocalizedStrings.MarketDepth };
_quotesWindows.Add(SelectedSecurity, wnd);
// subscribe on order book flow
Trader.RegisterMarketDepth(SelectedSecurity);
wnd.Show();
}
else
{
Trader.UnRegisterMarketDepth(SelectedSecurity);
var wnd = _quotesWindows[SelectedSecurity];
_quotesWindows.Remove(SelectedSecurity);
wnd.Close();
}
if (!_initialized)
{
TraderOnMarketDepthChanged(Trader.GetMarketDepth(SecurityPicker.SelectedSecurity));
Trader.MarketDepthChanged += TraderOnMarketDepthChanged;
_initialized = true;
}
}
private void TraderOnMarketDepthChanged(MarketDepth depth)
{
var wnd = _quotesWindows.TryGetValue(depth.Security);
if (wnd != null)
wnd.DepthCtrl.UpdateDepth(depth);
}
private void FindClick(object sender, RoutedEventArgs e)
{
var wnd = new SecurityLookupWindow { Criteria = new Security { Code = "AAPL", Type = SecurityTypes.Stock } };
if (!wnd.ShowModal(this))
return;
Trader.LookupSecurities(wnd.Criteria);
}
public void AddCandles(CandleSeries series, IEnumerable<Candle> candles)
{
var wnd = _realTimeCandles.TryGetValue(series) ?? _historyCandles.TryGetValue(series);
if (wnd != null)
candles.ForEach(wnd.ProcessCandles);
}
private void HistoryCandlesClick(object sender, RoutedEventArgs e)
{
var series = new CandleSeries
{
CandleType = typeof(TimeFrameCandle),
Security = SelectedSecurity,
Arg = CandlesPeriods.SelectedItem,
};
var wnd = new CandlesWindow { Title = series.ToString() };
_historyCandles.Add(series, wnd);
Trader.SubscribeCandles(series, DateTime.Today.Subtract(TimeSpan.FromTicks(((TimeSpan)series.Arg).Ticks * 30)), DateTime.Now);
wnd.Show();
}
private void RealTimeCandlesClick(object sender, RoutedEventArgs e)
{
var series = new CandleSeries(typeof(TimeFrameCandle), SelectedSecurity, InteractiveBrokersTimeFrames.Second5);
if (RealTimeCandles.IsChecked == true)
{
Trader.UnSubscribeCandles(series);
_realTimeCandles.GetAndRemove(series).Close();
RealTimeCandles.IsChecked = false;
}
else
{
var wnd = new CandlesWindow { Title = SelectedSecurity.Id + LocalizedStrings.Str2973 };
_realTimeCandles.Add(series, wnd);
Trader.SubscribeCandles(series, DateTimeOffset.MinValue, DateTimeOffset.MaxValue);
wnd.Show();
RealTimeCandles.IsChecked = true;
}
}
private void ReportsClick(object sender, RoutedEventArgs e)
{
var security = SelectedSecurity;
var ids = _reportSecurities.TryGetValue(security);
if (ids == null)
{
ids = Enumerator.GetValues<FundamentalReports>()
.Select(report => Trader.SubscribeFundamentalReport(security, report))
.ToArray();
_reportSecurities.Add(security, ids);
Reports.IsChecked = true;
}
else
{
_reportSecurities.Remove(security);
ids.ForEach(Trader.UnSubscribeFundamentalReport);
Reports.IsChecked = false;
}
}
private void OptionsClick(object sender, RoutedEventArgs e)
{
var security = SelectedSecurity;
var id = _optionSecurities.TryGetValue2(security);
if (id == null)
{
var wnd = new OptionWindow();
if (!wnd.ShowModal(this))
return;
Trader.SubscribeOptionCalc(security, wnd.Volatility, wnd.OptionPrice, wnd.AssetPrice);
Options.IsChecked = true;
}
else
{
Trader.UnSubscribeOptionCalc(id.Value);
_optionSecurities.Remove(security);
Options.IsChecked = false;
}
}
private void ScannerClick(object sender, RoutedEventArgs e)
{
if (_scannerId == null)
{
Trader.NewScannerResults += TraderOnNewScannerResults;
_scannerId = Trader.SubscribeScanner(new ScannerFilter
{
ScanCode = "LOW_WS_13W_HL",
BoardCode = "STK.US",
SecurityType = "ALL",
RowCount = 15,
});
Scanner.IsChecked = true;
}
else
{
Trader.NewScannerResults -= TraderOnNewScannerResults;
Trader.UnSubscribeScanner(_scannerId.Value);
Scanner.IsChecked = false;
_scannerId = null;
}
}
private void TraderOnNewScannerResults(ScannerFilter filter, IEnumerable<ScannerResult> results)
{
}
}
}
| |
/*
* 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 Mono.Addins;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Physics.Manager;
using System;
using System.Collections.Generic;
namespace OpenSim.Region.OptionalModules.PhysicsParameters
{
/// <summary>
/// </summary>
/// <remarks>
/// </remarks>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "PhysicsParameters")]
public class PhysicsParameters : ISharedRegionModule
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// private static string LogHeader = "[PHYSICS PARAMETERS]";
private List<Scene> m_scenes = new List<Scene>();
private static bool m_commandsLoaded = false;
#region ISharedRegionModule
public string Name { get { return "Runtime Physics Parameter Module"; } }
public Type ReplaceableInterface { get { return null; } }
public void Initialise(IConfigSource source)
{
// m_log.DebugFormat("{0}: INITIALIZED MODULE", LogHeader);
}
public void PostInitialise()
{
// m_log.DebugFormat("[{0}: POST INITIALIZED MODULE", LogHeader);
InstallInterfaces();
}
public void Close()
{
// m_log.DebugFormat("{0}: CLOSED MODULE", LogHeader);
}
public void AddRegion(Scene scene)
{
// m_log.DebugFormat("{0}: REGION {1} ADDED", LogHeader, scene.RegionInfo.RegionName);
m_scenes.Add(scene);
}
public void RemoveRegion(Scene scene)
{
// m_log.DebugFormat("{0}: REGION {1} REMOVED", LogHeader, scene.RegionInfo.RegionName);
if (m_scenes.Contains(scene))
m_scenes.Remove(scene);
}
public void RegionLoaded(Scene scene)
{
// m_log.DebugFormat("{0}: REGION {1} LOADED", LogHeader, scene.RegionInfo.RegionName);
}
#endregion INonSharedRegionModule
private const string getInvocation = "physics get [<param>|ALL]";
private const string setInvocation = "physics set <param> [<value>|TRUE|FALSE] [localID|ALL]";
private const string listInvocation = "physics list";
private void InstallInterfaces()
{
if (!m_commandsLoaded)
{
MainConsole.Instance.Commands.AddCommand(
"Regions", false, "physics set",
setInvocation,
"Set physics parameter from currently selected region",
ProcessPhysicsSet);
MainConsole.Instance.Commands.AddCommand(
"Regions", false, "physics get",
getInvocation,
"Get physics parameter from currently selected region",
ProcessPhysicsGet);
MainConsole.Instance.Commands.AddCommand(
"Regions", false, "physics list",
listInvocation,
"List settable physics parameters",
ProcessPhysicsList);
m_commandsLoaded = true;
}
}
// TODO: extend get so you can get a value from an individual localID
private void ProcessPhysicsGet(string module, string[] cmdparms)
{
if (cmdparms.Length != 3)
{
WriteError("Parameter count error. Invocation: " + getInvocation);
return;
}
string parm = cmdparms[2];
if (SceneManager.Instance == null || SceneManager.Instance.CurrentScene == null)
{
WriteError("Error: no region selected. Use 'change region' to select a region.");
return;
}
Scene scene = SceneManager.Instance.CurrentScene;
IPhysicsParameters physScene = scene.PhysicsScene as IPhysicsParameters;
if (physScene != null)
{
if (parm.ToLower() == "all")
{
foreach (PhysParameterEntry ppe in physScene.GetParameterList())
{
string val = string.Empty;
if (physScene.GetPhysicsParameter(ppe.name, out val))
{
WriteOut(" {0}/{1} = {2}", scene.RegionInfo.RegionName, ppe.name, val);
}
else
{
WriteOut(" {0}/{1} = {2}", scene.RegionInfo.RegionName, ppe.name, "unknown");
}
}
}
else
{
string val = string.Empty;
if (physScene.GetPhysicsParameter(parm, out val))
{
WriteOut(" {0}/{1} = {2}", scene.RegionInfo.RegionName, parm, val);
}
else
{
WriteError("Failed fetch of parameter '{0}' from region '{1}'", parm, scene.RegionInfo.RegionName);
}
}
}
else
{
WriteError("Region '{0}' physics engine has no gettable physics parameters", scene.RegionInfo.RegionName);
}
return;
}
private void ProcessPhysicsSet(string module, string[] cmdparms)
{
if (cmdparms.Length < 4 || cmdparms.Length > 5)
{
WriteError("Parameter count error. Invocation: " + getInvocation);
return;
}
string parm = "xxx";
string valparm = String.Empty;
uint localID = (uint)PhysParameterEntry.APPLY_TO_NONE; // set default value
try
{
parm = cmdparms[2];
valparm = cmdparms[3].ToLower();
if (cmdparms.Length > 4)
{
if (cmdparms[4].ToLower() == "all")
localID = (uint)PhysParameterEntry.APPLY_TO_ALL;
else
localID = uint.Parse(cmdparms[2], Culture.NumberFormatInfo);
}
}
catch
{
WriteError(" Error parsing parameters. Invocation: " + setInvocation);
return;
}
if (SceneManager.Instance == null || SceneManager.Instance.CurrentScene == null)
{
WriteError("Error: no region selected. Use 'change region' to select a region.");
return;
}
Scene scene = SceneManager.Instance.CurrentScene;
IPhysicsParameters physScene = scene.PhysicsScene as IPhysicsParameters;
if (physScene != null)
{
if (!physScene.SetPhysicsParameter(parm, valparm, localID))
{
WriteError("Failed set of parameter '{0}' for region '{1}'", parm, scene.RegionInfo.RegionName);
}
}
else
{
WriteOut("Region '{0}'s physics engine has no settable physics parameters", scene.RegionInfo.RegionName);
}
return;
}
private void ProcessPhysicsList(string module, string[] cmdparms)
{
if (SceneManager.Instance == null || SceneManager.Instance.CurrentScene == null)
{
WriteError("Error: no region selected. Use 'change region' to select a region.");
return;
}
Scene scene = SceneManager.Instance.CurrentScene;
IPhysicsParameters physScene = scene.PhysicsScene as IPhysicsParameters;
if (physScene != null)
{
WriteOut("Available physics parameters:");
PhysParameterEntry[] parms = physScene.GetParameterList();
foreach (PhysParameterEntry ent in parms)
{
WriteOut(" {0}: {1}", ent.name, ent.desc);
}
}
else
{
WriteError("Current regions's physics engine has no settable physics parameters");
}
return;
}
private void WriteOut(string msg, params object[] args)
{
// m_log.InfoFormat(msg, args);
MainConsole.Instance.OutputFormat(msg, args);
}
private void WriteError(string msg, params object[] args)
{
// m_log.ErrorFormat(msg, args);
MainConsole.Instance.OutputFormat(msg, args);
}
}
}
| |
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
using UnityStandardAssets.Utility;
using Random = UnityEngine.Random;
namespace UnityStandardAssets.Characters.FirstPerson
{
[RequireComponent(typeof (CharacterController))]
[RequireComponent(typeof (AudioSource))]
public class FirstPersonController : MonoBehaviour
{
[SerializeField] private bool m_IsWalking;
[SerializeField] private float m_WalkSpeed;
[SerializeField] private float m_RunSpeed;
[SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten;
[SerializeField] private float m_JumpSpeed;
[SerializeField] private float m_StickToGroundForce;
[SerializeField] private float m_GravityMultiplier;
[SerializeField] private MouseLook m_MouseLook;
[SerializeField] private bool m_UseFovKick;
[SerializeField] private FOVKick m_FovKick = new FOVKick();
[SerializeField] private bool m_UseHeadBob;
[SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob();
[SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob();
[SerializeField] private float m_StepInterval;
[SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from.
[SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground.
[SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground.
private Camera m_Camera;
private bool m_Jump;
private float m_YRotation;
private Vector2 m_Input;
private Vector3 m_MoveDir = Vector3.zero;
private CharacterController m_CharacterController;
private CollisionFlags m_CollisionFlags;
private bool m_PreviouslyGrounded;
private Vector3 m_OriginalCameraPosition;
private float m_StepCycle;
private float m_NextStep;
private bool m_Jumping;
private AudioSource m_AudioSource;
// Use this for initialization
private void Start()
{
m_CharacterController = GetComponent<CharacterController>();
m_Camera = Camera.main;
m_OriginalCameraPosition = m_Camera.transform.localPosition;
m_FovKick.Setup(m_Camera);
m_HeadBob.Setup(m_Camera, m_StepInterval);
m_StepCycle = 0f;
m_NextStep = m_StepCycle/2f;
m_Jumping = false;
m_AudioSource = GetComponent<AudioSource>();
m_MouseLook.Init(transform , m_Camera.transform);
}
// Update is called once per frame
private void Update()
{
RotateView();
// the jump state needs to read here to make sure it is not missed
if (!m_Jump)
{
//Jump disabled.
//m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
}
if (!m_PreviouslyGrounded && m_CharacterController.isGrounded)
{
StartCoroutine(m_JumpBob.DoBobCycle());
PlayLandingSound();
m_MoveDir.y = 0f;
m_Jumping = false;
}
if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded)
{
m_MoveDir.y = 0f;
}
m_PreviouslyGrounded = m_CharacterController.isGrounded;
}
private void PlayLandingSound()
{
m_AudioSource.clip = m_LandSound;
m_AudioSource.Play();
m_NextStep = m_StepCycle + .5f;
}
private void FixedUpdate()
{
float speed;
GetInput(out speed);
// always move along the camera forward as it is the direction that it being aimed at
Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x;
// get a normal for the surface that is being touched to move along it
RaycastHit hitInfo;
Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo,
m_CharacterController.height/2f);
desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized;
m_MoveDir.x = desiredMove.x*speed;
m_MoveDir.z = desiredMove.z*speed;
if (m_CharacterController.isGrounded)
{
m_MoveDir.y = -m_StickToGroundForce;
if (m_Jump)
{
m_MoveDir.y = m_JumpSpeed;
PlayJumpSound();
m_Jump = false;
m_Jumping = true;
}
}
else
{
m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime;
}
m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime);
ProgressStepCycle(speed);
UpdateCameraPosition(speed);
}
private void PlayJumpSound()
{
m_AudioSource.clip = m_JumpSound;
m_AudioSource.Play();
}
private void ProgressStepCycle(float speed)
{
if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0))
{
m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))*
Time.fixedDeltaTime;
}
if (!(m_StepCycle > m_NextStep))
{
return;
}
m_NextStep = m_StepCycle + m_StepInterval;
PlayFootStepAudio();
}
private void PlayFootStepAudio()
{
if (!m_CharacterController.isGrounded)
{
return;
}
// pick & play a random footstep sound from the array,
// excluding sound at index 0
int n = Random.Range(1, m_FootstepSounds.Length);
m_AudioSource.clip = m_FootstepSounds[n];
m_AudioSource.PlayOneShot(m_AudioSource.clip);
// move picked sound to index 0 so it's not picked next time
m_FootstepSounds[n] = m_FootstepSounds[0];
m_FootstepSounds[0] = m_AudioSource.clip;
}
private void UpdateCameraPosition(float speed)
{
Vector3 newCameraPosition;
if (!m_UseHeadBob)
{
return;
}
if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded)
{
m_Camera.transform.localPosition =
m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude +
(speed*(m_IsWalking ? 1f : m_RunstepLenghten)));
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset();
}
else
{
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset();
}
m_Camera.transform.localPosition = newCameraPosition;
}
private void GetInput(out float speed)
{
// Read input
float horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
float vertical = CrossPlatformInputManager.GetAxis("Vertical");
bool waswalking = m_IsWalking;
#if !MOBILE_INPUT
// On standalone builds, walk/run speed is modified by a key press.
// keep track of whether or not the character is walking or running
m_IsWalking = !Input.GetKey(KeyCode.LeftShift);
#endif
// set the desired speed to be walking or running
speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed;
m_Input = new Vector2(horizontal, vertical);
// normalize input if it exceeds 1 in combined length:
if (m_Input.sqrMagnitude > 1)
{
m_Input.Normalize();
}
// handle speed change to give an fov kick
// only if the player is going to a run, is running and the fovkick is to be used
if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0)
{
StopAllCoroutines();
StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown());
}
}
private void RotateView()
{
m_MouseLook.LookRotation (transform, m_Camera.transform);
}
private void OnControllerColliderHit(ControllerColliderHit hit)
{
Rigidbody body = hit.collider.attachedRigidbody;
//dont move the rigidbody if the character is on top of it
if (m_CollisionFlags == CollisionFlags.Below)
{
return;
}
if (body == null || body.isKinematic)
{
return;
}
body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Xml.XPath;
namespace System.Xml.Xsl.XsltOld
{
internal enum VariableType
{
GlobalVariable,
GlobalParameter,
LocalVariable,
LocalParameter,
WithParameter,
}
internal class VariableAction : ContainerAction, IXsltContextVariable
{
public static object BeingComputedMark = new object();
private const int ValueCalculated = 2;
protected XmlQualifiedName name;
protected string nameStr;
protected string baseUri;
protected int selectKey = Compiler.InvalidQueryKey;
protected int stylesheetid;
protected VariableType varType;
private int _varKey;
internal int Stylesheetid
{
get { return this.stylesheetid; }
}
internal XmlQualifiedName Name
{
get { return this.name; }
}
internal string NameStr
{
get { return this.nameStr; }
}
internal VariableType VarType
{
get { return this.varType; }
}
internal int VarKey
{
get { return _varKey; }
}
internal bool IsGlobal
{
get { return this.varType == VariableType.GlobalVariable || this.varType == VariableType.GlobalParameter; }
}
internal VariableAction(VariableType type)
{
this.varType = type;
}
internal override void Compile(Compiler compiler)
{
this.stylesheetid = compiler.Stylesheetid;
this.baseUri = compiler.Input.BaseURI;
CompileAttributes(compiler);
CheckRequiredAttribute(compiler, this.name, "name");
if (compiler.Recurse())
{
CompileTemplate(compiler);
compiler.ToParent();
if (this.selectKey != Compiler.InvalidQueryKey && this.containedActions != null)
{
throw XsltException.Create(SR.Xslt_VariableCntSel2, this.nameStr);
}
}
if (this.containedActions != null)
{
baseUri = baseUri + '#' + compiler.GetUnicRtfId();
}
else
{
baseUri = null;
}
_varKey = compiler.InsertVariable(this);
}
internal override bool CompileAttribute(Compiler compiler)
{
string name = compiler.Input.LocalName;
string value = compiler.Input.Value;
if (Ref.Equal(name, compiler.Atoms.Name))
{
Debug.Assert(this.name == null && this.nameStr == null);
this.nameStr = value;
this.name = compiler.CreateXPathQName(this.nameStr);
}
else if (Ref.Equal(name, compiler.Atoms.Select))
{
this.selectKey = compiler.AddQuery(value);
}
else
{
return false;
}
return true;
}
internal override void Execute(Processor processor, ActionFrame frame)
{
Debug.Assert(processor != null && frame != null && frame.State != ValueCalculated);
object value = null;
switch (frame.State)
{
case Initialized:
if (IsGlobal)
{
if (frame.GetVariable(_varKey) != null)
{ // This var was calculated already
frame.Finished();
break;
}
// Mark that the variable is being computed to check for circular references
frame.SetVariable(_varKey, BeingComputedMark);
}
// If this is a parameter, check whether the caller has passed the value
if (this.varType == VariableType.GlobalParameter)
{
value = processor.GetGlobalParameter(this.name);
}
else if (this.varType == VariableType.LocalParameter)
{
value = processor.GetParameter(this.name);
}
if (value != null)
{
goto case ValueCalculated;
}
// If value was not passed, check the 'select' attribute
if (this.selectKey != Compiler.InvalidQueryKey)
{
value = processor.RunQuery(frame, this.selectKey);
goto case ValueCalculated;
}
// If there is no 'select' attribute and the content is empty, use the empty string
if (this.containedActions == null)
{
value = string.Empty;
goto case ValueCalculated;
}
// RTF case
NavigatorOutput output = new NavigatorOutput(this.baseUri);
processor.PushOutput(output);
processor.PushActionFrame(frame);
frame.State = ProcessingChildren;
break;
case ProcessingChildren:
IRecordOutput recOutput = processor.PopOutput();
Debug.Assert(recOutput is NavigatorOutput);
value = ((NavigatorOutput)recOutput).Navigator;
goto case ValueCalculated;
case ValueCalculated:
Debug.Assert(value != null);
frame.SetVariable(_varKey, value);
frame.Finished();
break;
default:
Debug.Fail("Invalid execution state inside VariableAction.Execute");
break;
}
}
// ---------------------- IXsltContextVariable --------------------
XPathResultType IXsltContextVariable.VariableType
{
get { return XPathResultType.Any; }
}
object IXsltContextVariable.Evaluate(XsltContext xsltContext)
{
return ((XsltCompileContext)xsltContext).EvaluateVariable(this);
}
bool IXsltContextVariable.IsLocal
{
get { return this.varType == VariableType.LocalVariable || this.varType == VariableType.LocalParameter; }
}
bool IXsltContextVariable.IsParam
{
get { return this.varType == VariableType.LocalParameter || this.varType == VariableType.GlobalParameter; }
}
}
}
| |
using Microsoft.VisualStudio.Services.Agent.Util;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Net.Http;
using System.Diagnostics.Tracing;
using Microsoft.TeamFoundation.DistributedTask.Logging;
using System.Net.Http.Headers;
namespace Microsoft.VisualStudio.Services.Agent
{
public interface IHostContext : IDisposable
{
RunMode RunMode { get; set; }
StartupType StartupType { get; set; }
CancellationToken AgentShutdownToken { get; }
ShutdownReason AgentShutdownReason { get; }
ISecretMasker SecretMasker { get; }
ProductInfoHeaderValue UserAgent { get; }
string GetDirectory(WellKnownDirectory directory);
string GetConfigFile(WellKnownConfigFile configFile);
Tracing GetTrace(string name);
Task Delay(TimeSpan delay, CancellationToken cancellationToken);
T CreateService<T>() where T : class, IAgentService;
T GetService<T>() where T : class, IAgentService;
void SetDefaultCulture(string name);
event EventHandler Unloading;
void ShutdownAgent(ShutdownReason reason);
void WritePerfCounter(string counter);
}
public enum StartupType
{
Manual,
Service,
AutoStartup
}
public sealed class HostContext : EventListener, IObserver<DiagnosticListener>, IObserver<KeyValuePair<string, object>>, IHostContext, IDisposable
{
private const int _defaultLogPageSize = 8; //MB
private static int _defaultLogRetentionDays = 30;
private static int[] _vssHttpMethodEventIds = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 24 };
private static int[] _vssHttpCredentialEventIds = new int[] { 11, 13, 14, 15, 16, 17, 18, 20, 21, 22, 27, 29 };
private readonly ConcurrentDictionary<Type, object> _serviceInstances = new ConcurrentDictionary<Type, object>();
private readonly ConcurrentDictionary<Type, Type> _serviceTypes = new ConcurrentDictionary<Type, Type>();
private readonly ISecretMasker _secretMasker = new SecretMasker();
private readonly ProductInfoHeaderValue _userAgent = new ProductInfoHeaderValue($"VstsAgentCore-{BuildConstants.AgentPackage.PackageName}", Constants.Agent.Version);
private CancellationTokenSource _agentShutdownTokenSource = new CancellationTokenSource();
private object _perfLock = new object();
private RunMode _runMode = RunMode.Normal;
private Tracing _trace;
private Tracing _vssTrace;
private Tracing _httpTrace;
private ITraceManager _traceManager;
private AssemblyLoadContext _loadContext;
private IDisposable _httpTraceSubscription;
private IDisposable _diagListenerSubscription;
private StartupType _startupType;
private string _perfFile;
public event EventHandler Unloading;
public CancellationToken AgentShutdownToken => _agentShutdownTokenSource.Token;
public ShutdownReason AgentShutdownReason { get; private set; }
public ISecretMasker SecretMasker => _secretMasker;
public ProductInfoHeaderValue UserAgent => _userAgent;
public HostContext(string hostType, string logFile = null)
{
// Validate args.
ArgUtil.NotNullOrEmpty(hostType, nameof(hostType));
_loadContext = AssemblyLoadContext.GetLoadContext(typeof(HostContext).GetTypeInfo().Assembly);
_loadContext.Unloading += LoadContext_Unloading;
this.SecretMasker.AddValueEncoder(ValueEncoders.JsonStringEscape);
this.SecretMasker.AddValueEncoder(ValueEncoders.UriDataEscape);
// Create the trace manager.
if (string.IsNullOrEmpty(logFile))
{
int logPageSize;
string logSizeEnv = Environment.GetEnvironmentVariable($"{hostType.ToUpperInvariant()}_LOGSIZE");
if (!string.IsNullOrEmpty(logSizeEnv) || !int.TryParse(logSizeEnv, out logPageSize))
{
logPageSize = _defaultLogPageSize;
}
int logRetentionDays;
string logRetentionDaysEnv = Environment.GetEnvironmentVariable($"{hostType.ToUpperInvariant()}_LOGRETENTION");
if (!string.IsNullOrEmpty(logRetentionDaysEnv) || !int.TryParse(logRetentionDaysEnv, out logRetentionDays))
{
logRetentionDays = _defaultLogRetentionDays;
}
// this should give us _diag folder under agent root directory
string diagLogDirectory = Path.Combine(new DirectoryInfo(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)).Parent.FullName, Constants.Path.DiagDirectory);
_traceManager = new TraceManager(new HostTraceListener(diagLogDirectory, hostType, logPageSize, logRetentionDays), this.SecretMasker);
}
else
{
_traceManager = new TraceManager(new HostTraceListener(logFile), this.SecretMasker);
}
_trace = GetTrace(nameof(HostContext));
_vssTrace = GetTrace(nameof(VisualStudio) + nameof(VisualStudio.Services)); // VisualStudioService
// Enable Http trace
bool enableHttpTrace;
if (bool.TryParse(Environment.GetEnvironmentVariable("VSTS_AGENT_HTTPTRACE"), out enableHttpTrace) && enableHttpTrace)
{
_trace.Warning("*****************************************************************************************");
_trace.Warning("** **");
_trace.Warning("** Http trace is enabled, all your http traffic will be dumped into agent diag log. **");
_trace.Warning("** DO NOT share the log in public place! The trace may contains secrets in plain text. **");
_trace.Warning("** **");
_trace.Warning("*****************************************************************************************");
_httpTrace = GetTrace("HttpTrace");
_diagListenerSubscription = DiagnosticListener.AllListeners.Subscribe(this);
}
// Enable perf counter trace
string perfCounterLocation = Environment.GetEnvironmentVariable("VSTS_AGENT_PERFLOG");
if (!string.IsNullOrEmpty(perfCounterLocation))
{
try
{
Directory.CreateDirectory(perfCounterLocation);
_perfFile = Path.Combine(perfCounterLocation, $"{hostType}.perf");
}
catch (Exception ex)
{
_trace.Error(ex);
}
}
}
public RunMode RunMode
{
get
{
return _runMode;
}
set
{
_trace.Info($"Set run mode: {value}");
_runMode = value;
}
}
public string GetDirectory(WellKnownDirectory directory)
{
string path;
switch (directory)
{
case WellKnownDirectory.Bin:
path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
break;
case WellKnownDirectory.Diag:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Root),
Constants.Path.DiagDirectory);
break;
case WellKnownDirectory.Externals:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Root),
Constants.Path.ExternalsDirectory);
break;
case WellKnownDirectory.LegacyPSHost:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Externals),
Constants.Path.LegacyPSHostDirectory);
break;
case WellKnownDirectory.Root:
path = new DirectoryInfo(GetDirectory(WellKnownDirectory.Bin)).Parent.FullName;
break;
case WellKnownDirectory.ServerOM:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Externals),
Constants.Path.ServerOMDirectory);
break;
case WellKnownDirectory.Tee:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Externals),
Constants.Path.TeeDirectory);
break;
case WellKnownDirectory.Temp:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Work),
Constants.Path.TempDirectory);
break;
case WellKnownDirectory.Tasks:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Work),
Constants.Path.TasksDirectory);
break;
case WellKnownDirectory.Tools:
path = Environment.GetEnvironmentVariable("AGENT_TOOLSDIRECTORY") ?? Environment.GetEnvironmentVariable(Constants.Variables.Agent.ToolsDirectory);
if (string.IsNullOrEmpty(path))
{
path = Path.Combine(
GetDirectory(WellKnownDirectory.Work),
Constants.Path.ToolDirectory);
}
break;
case WellKnownDirectory.Update:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Work),
Constants.Path.UpdateDirectory);
break;
case WellKnownDirectory.Work:
var configurationStore = GetService<IConfigurationStore>();
AgentSettings settings = configurationStore.GetSettings();
ArgUtil.NotNull(settings, nameof(settings));
ArgUtil.NotNullOrEmpty(settings.WorkFolder, nameof(settings.WorkFolder));
path = Path.GetFullPath(Path.Combine(
GetDirectory(WellKnownDirectory.Root),
settings.WorkFolder));
break;
default:
throw new NotSupportedException($"Unexpected well known directory: '{directory}'");
}
_trace.Info($"Well known directory '{directory}': '{path}'");
return path;
}
public string GetConfigFile(WellKnownConfigFile configFile)
{
string path;
switch (configFile)
{
case WellKnownConfigFile.Agent:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Root),
".agent");
break;
case WellKnownConfigFile.Credentials:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Root),
".credentials");
break;
case WellKnownConfigFile.RSACredentials:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Root),
".credentials_rsaparams");
break;
case WellKnownConfigFile.Service:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Root),
".service");
break;
case WellKnownConfigFile.CredentialStore:
#if OS_OSX
path = Path.Combine(
GetDirectory(WellKnownDirectory.Root),
".credential_store.keychain");
#else
path = Path.Combine(
GetDirectory(WellKnownDirectory.Root),
".credential_store");
#endif
break;
case WellKnownConfigFile.Certificates:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Root),
".certificates");
break;
case WellKnownConfigFile.Proxy:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Root),
".proxy");
break;
case WellKnownConfigFile.ProxyCredentials:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Root),
".proxycredentials");
break;
case WellKnownConfigFile.ProxyBypass:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Root),
".proxybypass");
break;
case WellKnownConfigFile.Autologon:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Root),
".autologon");
break;
case WellKnownConfigFile.Options:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Root),
".options");
break;
default:
throw new NotSupportedException($"Unexpected well known config file: '{configFile}'");
}
_trace.Info($"Well known config file '{configFile}': '{path}'");
return path;
}
public Tracing GetTrace(string name)
{
return _traceManager[name];
}
public async Task Delay(TimeSpan delay, CancellationToken cancellationToken)
{
await Task.Delay(delay, cancellationToken);
}
/// <summary>
/// Creates a new instance of T.
/// </summary>
public T CreateService<T>() where T : class, IAgentService
{
Type target;
if (!_serviceTypes.TryGetValue(typeof(T), out target))
{
// Infer the concrete type from the ServiceLocatorAttribute.
CustomAttributeData attribute = typeof(T)
.GetTypeInfo()
.CustomAttributes
.FirstOrDefault(x => x.AttributeType == typeof(ServiceLocatorAttribute));
if (attribute != null)
{
foreach (CustomAttributeNamedArgument arg in attribute.NamedArguments)
{
if (string.Equals(arg.MemberName, ServiceLocatorAttribute.DefaultPropertyName, StringComparison.Ordinal))
{
target = arg.TypedValue.Value as Type;
}
}
}
if (target == null)
{
throw new KeyNotFoundException(string.Format(CultureInfo.InvariantCulture, "Service mapping not found for key '{0}'.", typeof(T).FullName));
}
_serviceTypes.TryAdd(typeof(T), target);
target = _serviceTypes[typeof(T)];
}
// Create a new instance.
T svc = Activator.CreateInstance(target) as T;
svc.Initialize(this);
return svc;
}
/// <summary>
/// Gets or creates an instance of T.
/// </summary>
public T GetService<T>() where T : class, IAgentService
{
// Return the cached instance if one already exists.
object instance;
if (_serviceInstances.TryGetValue(typeof(T), out instance))
{
return instance as T;
}
// Otherwise create a new instance and try to add it to the cache.
_serviceInstances.TryAdd(typeof(T), CreateService<T>());
// Return the instance from the cache.
return _serviceInstances[typeof(T)] as T;
}
public void SetDefaultCulture(string name)
{
ArgUtil.NotNull(name, nameof(name));
_trace.Verbose($"Setting default culture and UI culture to: '{name}'");
CultureInfo.DefaultThreadCurrentCulture = new CultureInfo(name);
CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo(name);
}
public void ShutdownAgent(ShutdownReason reason)
{
ArgUtil.NotNull(reason, nameof(reason));
_trace.Info($"Agent will be shutdown for {reason.ToString()}");
AgentShutdownReason = reason;
_agentShutdownTokenSource.Cancel();
}
public override void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public StartupType StartupType
{
get
{
return _startupType;
}
set
{
_startupType = value;
}
}
public void WritePerfCounter(string counter)
{
if (!string.IsNullOrEmpty(_perfFile))
{
string normalizedCounter = counter.Replace(':', '_');
lock (_perfLock)
{
try
{
File.AppendAllLines(_perfFile, new[] { $"{normalizedCounter}:{DateTime.UtcNow.ToString("O")}" });
}
catch (Exception ex)
{
_trace.Error(ex);
}
}
}
}
private void Dispose(bool disposing)
{
// TODO: Dispose the trace listener also.
if (disposing)
{
if (_loadContext != null)
{
_loadContext.Unloading -= LoadContext_Unloading;
_loadContext = null;
}
_httpTraceSubscription?.Dispose();
_diagListenerSubscription?.Dispose();
_traceManager?.Dispose();
_traceManager = null;
_agentShutdownTokenSource?.Dispose();
_agentShutdownTokenSource = null;
base.Dispose();
}
}
private void LoadContext_Unloading(AssemblyLoadContext obj)
{
if (Unloading != null)
{
Unloading(this, null);
}
}
void IObserver<DiagnosticListener>.OnCompleted()
{
_httpTrace.Info("DiagListeners finished transmitting data.");
}
void IObserver<DiagnosticListener>.OnError(Exception error)
{
_httpTrace.Error(error);
}
void IObserver<DiagnosticListener>.OnNext(DiagnosticListener listener)
{
if (listener.Name == "HttpHandlerDiagnosticListener" && _httpTraceSubscription == null)
{
_httpTraceSubscription = listener.Subscribe(this);
}
}
void IObserver<KeyValuePair<string, object>>.OnCompleted()
{
_httpTrace.Info("HttpHandlerDiagnosticListener finished transmitting data.");
}
void IObserver<KeyValuePair<string, object>>.OnError(Exception error)
{
_httpTrace.Error(error);
}
void IObserver<KeyValuePair<string, object>>.OnNext(KeyValuePair<string, object> value)
{
_httpTrace.Info($"Trace {value.Key} event:{Environment.NewLine}{value.Value.ToString()}");
}
protected override void OnEventSourceCreated(EventSource source)
{
if (source.Name.Equals("Microsoft-VSS-Http"))
{
EnableEvents(source, EventLevel.Verbose);
}
}
protected override void OnEventWritten(EventWrittenEventArgs eventData)
{
if (eventData == null)
{
return;
}
string message = eventData.Message;
object[] payload = new object[0];
if (eventData.Payload != null && eventData.Payload.Count > 0)
{
payload = eventData.Payload.ToArray();
}
try
{
if (_vssHttpMethodEventIds.Contains(eventData.EventId))
{
payload[0] = Enum.Parse(typeof(VssHttpMethod), ((int)payload[0]).ToString());
}
else if (_vssHttpCredentialEventIds.Contains(eventData.EventId))
{
payload[0] = Enum.Parse(typeof(VisualStudio.Services.Common.VssCredentialsType), ((int)payload[0]).ToString());
}
if (payload.Length > 0)
{
message = String.Format(eventData.Message.Replace("%n", Environment.NewLine), payload);
}
switch (eventData.Level)
{
case EventLevel.Critical:
case EventLevel.Error:
_vssTrace.Error(message);
break;
case EventLevel.Warning:
_vssTrace.Warning(message);
break;
case EventLevel.Informational:
_vssTrace.Info(message);
break;
default:
_vssTrace.Verbose(message);
break;
}
}
catch (Exception ex)
{
_vssTrace.Error(ex);
_vssTrace.Info(eventData.Message);
_vssTrace.Info(string.Join(", ", eventData.Payload?.ToArray() ?? new string[0]));
}
}
// Copied from VSTS code base, used for EventData translation.
internal enum VssHttpMethod
{
UNKNOWN,
DELETE,
HEAD,
GET,
OPTIONS,
PATCH,
POST,
PUT,
}
}
public static class HostContextExtension
{
public static HttpClientHandler CreateHttpClientHandler(this IHostContext context)
{
HttpClientHandler clientHandler = new HttpClientHandler();
var agentWebProxy = context.GetService<IVstsAgentWebProxy>();
clientHandler.Proxy = agentWebProxy.WebProxy;
return clientHandler;
}
}
public enum ShutdownReason
{
UserCancelled = 0,
OperatingSystemShutdown = 1,
}
}
| |
using Shouldly;
using StructureMap.Building;
using StructureMap.Diagnostics;
using StructureMap.Graph;
using StructureMap.Pipeline;
using System;
using System.Linq;
using System.Linq.Expressions;
using Xunit;
namespace StructureMap.Testing.Graph
{
public class PluginGraphTester
{
public static PluginGraph Empty()
{
return new PluginGraphBuilder().Build();
}
[Fact]
public void default_tracking_style()
{
Empty().TransientTracking.ShouldBe(TransientTracking.DefaultNotTrackedAtRoot);
}
[Fact]
public void add_type_adds_an_instance_for_type_once_and_only_once()
{
var graph = PluginGraph.CreateRoot();
graph.AddType(typeof(IThingy), typeof(BigThingy));
var family = graph.Families[typeof(IThingy)];
family.Instances
.Single()
.ShouldBeOfType<ConstructorInstance>()
.PluggedType.ShouldBe(typeof(BigThingy));
graph.AddType(typeof(IThingy), typeof(BigThingy));
family.Instances.Count().ShouldBe(1);
}
[Fact]
public void all_instances_when_family_has_not_been_created()
{
var graph = PluginGraph.CreateRoot();
graph.AllInstances(typeof(BigThingy)).Any().ShouldBeFalse();
graph.Families.Has(typeof(BigThingy)).ShouldBeFalse();
}
[Fact]
public void all_instances_when_the_family_already_exists()
{
var graph = PluginGraph.CreateRoot();
// just forcing the family to be created
graph.Families[typeof(BigThingy)].ShouldNotBeNull();
graph.AllInstances(typeof(BigThingy)).Any().ShouldBeFalse();
}
[Fact]
public void eject_family_removes_the_family_and_disposes_all_of_its_instances()
{
var instance1 = new FakeInstance();
var instance2 = new FakeInstance();
var instance3 = new FakeInstance();
var graph = PluginGraph.CreateRoot();
graph.Families[typeof(IThingy)].AddInstance(instance1);
graph.Families[typeof(IThingy)].AddInstance(instance2);
graph.Families[typeof(IThingy)].AddInstance(instance3);
graph.EjectFamily(typeof(IThingy));
instance1.WasDisposed.ShouldBeTrue();
instance2.WasDisposed.ShouldBeTrue();
instance3.WasDisposed.ShouldBeTrue();
graph.Families.Has(typeof(IThingy));
}
[Fact]
public void find_family_by_closing_an_open_interface_that_matches()
{
var graph = Empty();
graph.Families[typeof(IOpen<>)].SetDefault(new ConfiguredInstance(typeof(Open<>)));
graph.Families[typeof(IOpen<string>)].GetDefaultInstance().ShouldBeOfType<ConstructorInstance>()
.PluggedType.ShouldBe(typeof(Open<string>));
}
[Fact]
public void find_family_for_concrete_type_with_default()
{
var graph = Empty();
graph.Families[typeof(BigThingy)].GetDefaultInstance()
.ShouldBeOfType<ConstructorInstance>()
.PluggedType.ShouldBe(typeof(BigThingy));
}
[Fact]
public void find_instance_negative_when_family_does_exist_but_instance_does_not()
{
var graph = PluginGraph.CreateRoot();
graph.Families[typeof(BigThingy)].AddInstance(new SmartInstance<BigThingy>().Named("red"));
graph.FindInstance(typeof(BigThingy), "blue").ShouldBeNull();
}
[Fact]
public void find_instance_negative_when_family_does_not_exist_does_not_create_family()
{
var graph = PluginGraph.CreateRoot();
graph.FindInstance(typeof(BigThingy), "blue").ShouldBeNull();
graph.Families.Has(typeof(BigThingy)).ShouldBeFalse();
}
[Fact]
public void find_instance_positive()
{
var graph = PluginGraph.CreateRoot();
var instance = new SmartInstance<BigThingy>().Named("red");
graph.Families[typeof(BigThingy)].AddInstance(instance);
graph.FindInstance(typeof(BigThingy), "red").ShouldBeTheSameAs(instance);
}
[Fact]
public void find_instance_can_use_missing_instance()
{
var graph = PluginGraph.CreateRoot();
var instance = new SmartInstance<BigThingy>().Named("red");
graph.Families[typeof(BigThingy)].MissingInstance = instance;
var cloned_and_renamed = graph.FindInstance(typeof(BigThingy), "green").ShouldBeAssignableTo<ConfiguredInstance>();
cloned_and_renamed.Name.ShouldBe("green");
cloned_and_renamed.PluggedType.ShouldBe(typeof(BigThingy));
}
[Fact]
public void has_default_positive()
{
var graph = PluginGraph.CreateRoot();
graph.Families[typeof(IThingy)].SetDefault(new SmartInstance<BigThingy>());
graph.HasDefaultForPluginType(typeof(IThingy));
}
[Fact]
public void has_default_when_the_family_has_not_been_created()
{
var graph = PluginGraph.CreateRoot();
graph.HasDefaultForPluginType(typeof(IThingy)).ShouldBeFalse();
}
[Fact]
public void has_default_with_family_but_no_default()
{
var graph = PluginGraph.CreateRoot();
graph.Families[typeof(IThingy)].AddInstance(new SmartInstance<BigThingy>());
graph.Families[typeof(IThingy)].AddInstance(new SmartInstance<BigThingy>());
graph.HasDefaultForPluginType(typeof(IThingy))
.ShouldBeFalse();
}
[Fact]
public void has_instance_negative_when_the_family_has_not_been_created()
{
var graph = PluginGraph.CreateRoot();
graph.HasInstance(typeof(IThingy), "red")
.ShouldBeFalse();
}
[Fact]
public void has_instance_negative_with_the_family_already_existing()
{
var graph = PluginGraph.CreateRoot();
graph.Families[typeof(IThingy)]
.AddInstance(new SmartInstance<BigThingy>().Named("blue"));
graph.HasInstance(typeof(IThingy), "red")
.ShouldBeFalse();
}
[Fact]
public void has_instance_positive()
{
var graph = PluginGraph.CreateRoot();
graph.Families[typeof(IThingy)]
.AddInstance(new SmartInstance<BigThingy>().Named("blue"));
graph.HasInstance(typeof(IThingy), "blue")
.ShouldBeTrue();
}
[Fact]
public void has_family_false_with_simple()
{
var graph = Empty();
graph.HasFamily(typeof(IThingy)).ShouldBeFalse();
}
[Fact]
public void has_family_true_with_simple()
{
var graph = Empty();
graph.AddFamily(new PluginFamily(typeof(IThingy)));
graph.HasFamily(typeof(IThingy)).ShouldBeTrue();
}
[Fact]
public void add_family_sets_the_parent_relationship()
{
var graph = Empty();
graph.AddFamily(new PluginFamily(typeof(IThingy)));
graph.Families[typeof(IThingy)].Owner.ShouldBeTheSameAs(graph);
}
[Fact]
public void find_root()
{
var top = PluginGraph.CreateRoot();
var node = top.Profile("Foo");
var leaf = node.Profile("Bar");
top.Root.ShouldBeTheSameAs(top);
node.Root.ShouldBeTheSameAs(top);
leaf.Root.ShouldBeTheSameAs(top);
}
[Fact]
public void has_family_true_with_open_generics()
{
var graph = Empty();
graph.Families[typeof(IOpen<>)].SetDefault(new ConstructorInstance(typeof(Open<>)));
graph.HasFamily(typeof(IOpen<string>))
.ShouldBeTrue();
}
}
public class FakeDependencySource : IDependencySource
{
public FakeDependencySource()
{
ReturnedType = typeof(string);
}
public string Description { get; private set; }
public Expression ToExpression(ParameterExpression session, ParameterExpression context)
{
throw new NotImplementedException();
}
public Type ReturnedType { get; }
public void AcceptVisitor(IDependencyVisitor visitor)
{
visitor.Dependency(this);
}
}
public class FakeInstance : Instance, IDisposable
{
public bool WasDisposed;
public readonly FakeDependencySource DependencySource = new FakeDependencySource();
public override IDependencySource ToDependencySource(Type pluginType)
{
return DependencySource;
}
public override Type ReturnedType
{
get { return null; }
}
public override string Description
{
get { return "fake"; }
}
public void Dispose()
{
WasDisposed = true;
}
}
public interface IOpen<T>
{
}
public class Open<T> : IOpen<T>
{
}
//[PluginFamily]
public interface IThingy
{
void Go();
}
//[Pluggable("Big")]
public class BigThingy : IThingy
{
#region IThingy Members
public void Go()
{
}
#endregion IThingy Members
}
}
| |
namespace Shopify.Unity {
using System.Collections.Generic;
using System.Collections;
using System;
using Shopify.Unity.GraphQL;
using Shopify.Unity.SDK;
/// <summary>
/// Internal state class for a Cart.
/// </summary>
public partial class CartState {
public CartLineItems LineItems {
get {
return _LineItems;
}
}
public List<CheckoutUserError> UserErrors {
get {
return _UserErrors;
}
}
public bool IsSaved {
get {
return IsCreated && LineItems.IsSaved;
}
}
public bool IsCreated {
get {
return CurrentCheckout != null;
}
}
public Checkout CurrentCheckout { get; private set; }
private ShopifyClient Client;
private CartLineItems _LineItems;
private List<CheckoutUserError> _UserErrors = null;
private List<String> DeletedLineItems = new List<string>();
public CartState(ShopifyClient client) {
Client = client;
_LineItems = new CartLineItems();
_LineItems.OnChange += OnLineItemChange;
}
public void Reset() {
_LineItems.Reset();
_UserErrors = null;
DeletedLineItems.Clear();
CurrentCheckout = null;
}
public decimal Subtotal() {
return _LineItems.Subtotal;
}
public void SetShippingLine(string shippingRateHandle, CompletionCallback callback) {
MutationQuery query = new MutationQuery();
DefaultQueries.checkout.ShippingLineUpdate(query, CurrentCheckout.id(), shippingRateHandle);
Client.Mutation(query, (Mutation response, ShopifyError error) => {
if (error != null) {
callback(error);
return;
}
if (UpdateState(response.checkoutShippingLineUpdate().checkout(), response.checkoutShippingLineUpdate().checkoutUserErrors())) {
if (CurrentCheckout.ready()) {
callback(null);
} else {
PollCheckoutAndUpdate(PollCheckoutReady, callback);
}
} else {
HandleUserError(callback);
}
});
}
public void SetEmailAddress(string email, CompletionCallback callback) {
MutationQuery query = new MutationQuery();
DefaultQueries.checkout.EmailUpdate(query, CurrentCheckout.id(), email);
Client.Mutation(query, (Mutation response, ShopifyError error) => {
if (error != null) {
callback(error);
} else {
if (UpdateState(response.checkoutEmailUpdateV2().checkout(), response.checkoutEmailUpdateV2().checkoutUserErrors())) {
if (CurrentCheckout.ready()) {
callback(null);
} else {
PollCheckoutAndUpdate(PollCheckoutReady, callback);
}
} else {
HandleUserError(callback);
}
}
});
}
public void SetShippingAddress(MailingAddressInput mailingAddressInput, CompletionCallback callback) {
MutationQuery query = new MutationQuery();
DefaultQueries.checkout.ShippingAddressUpdate(query, CurrentCheckout.id(), mailingAddressInput);
Client.Mutation(query, (Mutation response, ShopifyError error) => {
if (error != null) {
callback(error);
} else {
if (UpdateState(response.checkoutShippingAddressUpdateV2().checkout(), response.checkoutShippingAddressUpdateV2().checkoutUserErrors())) {
PollCheckoutAndUpdate(PollCheckoutAvailableShippingRatesReady, callback);
} else {
HandleUserError(callback);
}
}
});
}
public void SetFinalCheckoutFields(string email, ShippingFields? shippingFields, CompletionCallback callback) {
MutationQuery query = new MutationQuery();
DefaultQueries.checkout.EmailUpdate(query, CurrentCheckout.id(), email);
if (shippingFields.HasValue) {
DefaultQueries.checkout.ShippingAddressUpdate(query, CurrentCheckout.id(), shippingFields.Value.ShippingAddress);
DefaultQueries.checkout.ShippingLineUpdate(query, CurrentCheckout.id(), shippingFields.Value.ShippingIdentifier);
}
Client.Mutation(query, (Mutation response, ShopifyError error) => {
if (error != null) {
callback(error);
} else {
var userErrors = response.checkoutShippingAddressUpdateV2().checkoutUserErrors();
if (shippingFields.HasValue) {
userErrors.AddRange(response.checkoutShippingLineUpdate().checkoutUserErrors());
userErrors.AddRange(response.checkoutEmailUpdateV2().checkoutUserErrors());
}
if (UpdateState(response.checkoutEmailUpdateV2().checkout(), userErrors)) {
PollCheckoutAndUpdate(PollCheckoutReady, callback);
} else {
HandleUserError(callback);
}
}
});
}
public void CheckoutSave(CompletionCallback callback) {
if (!IsCreated) {
CreateRemoteCheckoutFromLocalState(callback);
} else if (!IsSaved) {
UpdateRemoteCheckoutFromLocalState(callback);
} else {
callback(null);
}
}
private void CreateRemoteCheckoutFromLocalState(CompletionCallback callback) {
MutationQuery query = new MutationQuery();
List<CheckoutLineItemInput> newLineItemInput = CartLineItems.ConvertToCheckoutLineItemInput(LineItems.All());
DefaultQueries.checkout.Create(query, newLineItemInput);
Client.Mutation(query, (Mutation response, ShopifyError error) => {
if (error != null) {
callback(error);
return;
}
if (UpdateState(response.checkoutCreate().checkout(), response.checkoutCreate().checkoutUserErrors())) {
if (CurrentCheckout.ready()) {
callback(null);
} else {
PollCheckoutAndUpdate(PollCheckoutReady, callback);
}
} else {
HandleUserError(callback);
}
});
}
public void CheckoutWithTokenizedPaymentV2(TokenizedPaymentInputV2 tokenizedPaymentInputV2, CompletionCallback callback) {
Action<Payment> pollPayment = (payment) => {
PollPaymentReady(payment.id(), (Payment newPayment, ShopifyError error) => {
if (error != null) {
callback(error);
} else {
if (UpdateState(payment.checkout())) {
callback(null);
} else {
HandleUserError(callback);
}
}
});
};
Action checkoutWithTokenizedPaymentV2 = () => {
MutationQuery query = new MutationQuery();
DefaultQueries.checkout.CheckoutCompleteWithTokenizedPaymentV2(query, CurrentCheckout.id(), tokenizedPaymentInputV2);
Client.Mutation(query, (Mutation response, ShopifyError error) => {
if (error != null) {
callback(error);
return;
} else {
var responseNode = response.checkoutCompleteWithTokenizedPaymentV2();
var payment = responseNode.payment();
if (UpdateState(responseNode.checkout(), responseNode.checkoutUserErrors())) {
if (payment.ready()) {
callback(null);
} else {
pollPayment(payment);
}
} else {
HandleUserError(callback);
}
}
});
};
// Ensure we can checkout first
if (CurrentCheckout.ready()) {
checkoutWithTokenizedPaymentV2();
} else {
PollCheckoutReady((Checkout checkout, ShopifyError error) => {
if (error != null) {
callback(error);
} else {
checkoutWithTokenizedPaymentV2();
}
});
}
}
private void UpdateRemoteCheckoutFromLocalState(CompletionCallback callback) {
MutationQuery query = new MutationQuery();
// remove all line items them add them
List<string> lineItemsToRemove = CartLineItems.ConvertToLineItemIds(LineItems.All());
lineItemsToRemove.AddRange(DeletedLineItems);
List<CheckoutLineItemInput> lineItemsToAdd = CartLineItems.ConvertToCheckoutLineItemInput(LineItems.All());
DefaultQueries.checkout.LineItemsRemove(query, CurrentCheckout.id(), lineItemsToRemove);
DefaultQueries.checkout.LineItemsAdd(query, CurrentCheckout.id(), lineItemsToAdd);
Client.Mutation(query, (Mutation response, ShopifyError error) => {
if (error != null) {
callback(error);
return;
}
DeletedLineItems.Clear();
if (UpdateState(response.checkoutLineItemsAdd().checkout(), response.checkoutLineItemsAdd().checkoutUserErrors())) {
if (CurrentCheckout.ready()) {
callback(null);
} else {
PollCheckoutAndUpdate(PollCheckoutReady, callback);
}
} else {
HandleUserError(callback);
}
});
}
private bool UpdateState(Checkout checkout) {
return UpdateState(checkout, new List<CheckoutUserError>());
}
private bool UpdateState(Checkout checkout, List<CheckoutUserError> userErrors) {
if (CurrentCheckout == null) {
CurrentCheckout = checkout;
} else {
MergeCheckout merger = new MergeCheckout();
CurrentCheckout = merger.Merge(CurrentCheckout, checkout);
}
if (userErrors.Count > 0) {
_UserErrors = userErrors;
} else {
_UserErrors = null;
}
UpdateLineItemFromCheckout(CurrentCheckout);
return _UserErrors == null;
}
private void UpdateLineItemFromCheckout(Checkout checkout) {
if (checkout == null) {
return;
}
// sometimes we may not query line items for instance when polling is being performed
try {
List<CheckoutLineItem> lineItems = (List<CheckoutLineItem>) checkout.lineItems();
LineItems.UpdateLineItemsFromCheckoutLineItems(lineItems);
#pragma warning disable 0168
} catch (NoQueryException exception) { }
#pragma warning restore 0168
}
private void HandleUserError(CompletionCallback callback) {
ShopifyError error = new ShopifyError(
ShopifyError.ErrorType.UserError,
"There were issues with some of the fields sent. See `cart.UserErrors`"
);
callback(error);
}
private void OnLineItemChange(CartLineItems.LineItemChangeType type, CartLineItem lineItem) {
switch(type) {
case CartLineItems.LineItemChangeType.Remove:
DeletedLineItems.Add(lineItem.ID);
break;
}
}
private delegate void CheckoutPollQuery(QueryRootQuery query, string checkoutId);
private delegate void CheckoutPoll(CheckoutPollFinishedHandler callback);
private delegate void CheckoutPollFinishedHandler(Checkout checkout, ShopifyError error);
private delegate void PaymentPollFinishedHandler(Payment payment, ShopifyError error);
// Polls a Checkout, till isReady returns True.
private void PollCheckoutNode(CheckoutPollQuery checkoutQuery, PollUpdatedHandler isReady, CheckoutPollFinishedHandler callback) {
QueryRootQuery query = new QueryRootQuery();
checkoutQuery(query, CurrentCheckout.id());
Client.PollQuery(isReady, query, (response, error) => {
if (error != null) {
callback(null, error);
} else {
Checkout checkout = (Checkout) response.node();
callback(checkout, null);
}
});
}
// Polls a Payment node, till isReady returns True.
private void PollPaymentNode(string paymentId, PollUpdatedHandler isReady, PaymentPollFinishedHandler callback) {
QueryRootQuery query = new QueryRootQuery();
DefaultQueries.checkout.PaymentPoll(query, paymentId);
Client.PollQuery(isReady, query, (response, error) => {
if (error != null) {
callback(null, error);
} else {
Payment payment = (Payment) response.node();
callback(payment, null);
}
});
}
// Convenience method to poll a Checkout node till its ready property is True
private void PollCheckoutReady(CheckoutPollFinishedHandler callback) {
PollUpdatedHandler isReady = (updatedQueryRoot) => {
var checkout = (Checkout) updatedQueryRoot.node();
return checkout.ready();
};
PollCheckoutNode(DefaultQueries.checkout.Poll, isReady, callback);
}
// Convenience method to poll a Checkout node till its available shipping rates' ready property is True
private void PollCheckoutAvailableShippingRatesReady(CheckoutPollFinishedHandler callback) {
PollUpdatedHandler isReady = (updatedQueryRoot) => {
var checkout = (Checkout) updatedQueryRoot.node();
return checkout.availableShippingRates().ready();
};
PollCheckoutNode(DefaultQueries.checkout.AvailableShippingRatesPoll, isReady, callback);
}
// Convenience method to perform some polling on Checkout and update the Current Checkout when completed
private void PollCheckoutAndUpdate(CheckoutPoll poll, CompletionCallback callback) {
poll((Checkout checkout, ShopifyError error) => {
if (error == null && checkout != null) {
UpdateState(checkout);
}
callback(error);
});
}
// Convenience method to poll a Payment node with paymentId till its ready property is True
private void PollPaymentReady(string paymentId, PaymentPollFinishedHandler callback) {
PollUpdatedHandler isReady = (updatedQueryRoot) => {
var payment = (Payment) updatedQueryRoot.node();
return payment.ready();
};
PollPaymentNode(paymentId, isReady, callback);
}
}
}
| |
using System;
using Csla;
using SelfLoad.DataAccess;
using SelfLoad.DataAccess.ERLevel;
namespace SelfLoad.Business.ERLevel
{
/// <summary>
/// C09_Region_ReChild (editable child object).<br/>
/// This is a generated base class of <see cref="C09_Region_ReChild"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="C08_Region"/> collection.
/// </remarks>
[Serializable]
public partial class C09_Region_ReChild : BusinessBase<C09_Region_ReChild>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Region_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Region_Child_NameProperty = RegisterProperty<string>(p => p.Region_Child_Name, "Cities Child Name");
/// <summary>
/// Gets or sets the Cities Child Name.
/// </summary>
/// <value>The Cities Child Name.</value>
public string Region_Child_Name
{
get { return GetProperty(Region_Child_NameProperty); }
set { SetProperty(Region_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="C09_Region_ReChild"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="C09_Region_ReChild"/> object.</returns>
internal static C09_Region_ReChild NewC09_Region_ReChild()
{
return DataPortal.CreateChild<C09_Region_ReChild>();
}
/// <summary>
/// Factory method. Loads a <see cref="C09_Region_ReChild"/> object, based on given parameters.
/// </summary>
/// <param name="region_ID2">The Region_ID2 parameter of the C09_Region_ReChild to fetch.</param>
/// <returns>A reference to the fetched <see cref="C09_Region_ReChild"/> object.</returns>
internal static C09_Region_ReChild GetC09_Region_ReChild(int region_ID2)
{
return DataPortal.FetchChild<C09_Region_ReChild>(region_ID2);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="C09_Region_ReChild"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public C09_Region_ReChild()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="C09_Region_ReChild"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="C09_Region_ReChild"/> object from the database, based on given criteria.
/// </summary>
/// <param name="region_ID2">The Region ID2.</param>
protected void Child_Fetch(int region_ID2)
{
var args = new DataPortalHookArgs(region_ID2);
OnFetchPre(args);
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var dal = dalManager.GetProvider<IC09_Region_ReChildDal>();
var data = dal.Fetch(region_ID2);
Fetch(data);
}
OnFetchPost(args);
// check all object rules and property rules
BusinessRules.CheckRules();
}
/// <summary>
/// Loads a <see cref="C09_Region_ReChild"/> object from the given <see cref="C09_Region_ReChildDto"/>.
/// </summary>
/// <param name="data">The C09_Region_ReChildDto to use.</param>
private void Fetch(C09_Region_ReChildDto data)
{
// Value properties
LoadProperty(Region_Child_NameProperty, data.Region_Child_Name);
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="C09_Region_ReChild"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(C08_Region parent)
{
var dto = new C09_Region_ReChildDto();
dto.Parent_Region_ID = parent.Region_ID;
dto.Region_Child_Name = Region_Child_Name;
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<IC09_Region_ReChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
args = new DataPortalHookArgs(resultDto);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="C09_Region_ReChild"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(C08_Region parent)
{
if (!IsDirty)
return;
var dto = new C09_Region_ReChildDto();
dto.Parent_Region_ID = parent.Region_ID;
dto.Region_Child_Name = Region_Child_Name;
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<IC09_Region_ReChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="C09_Region_ReChild"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(C08_Region parent)
{
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IC09_Region_ReChildDal>();
using (BypassPropertyChecks)
{
dal.Delete(parent.Region_ID);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
using UnityEngine;
using System.Collections;
using LitJson;
using System;
using System.Text;
using System.Collections.Generic;
// Usage:
// AsyncJSONRequest jsonRequest = myGameObj.AddComponent<AsyncJSONRequest>();
// Dictionary<string, object> myJsonParameters = new Dictionary<string, object>();
// myJsonParameters["fieldName1"]= "stringValue";
// myJsonParameters["fieldName2"]= 3.14;
// myJsonParameters["fieldName3"]= 1;
// myJsonParameters["fieldName4"]= true;
// jsonRequest.POST("http://foo.com/MyWebAPI", myJsonParameters, myOnCompleteDelegate)
public class AsyncJSONRequest : MonoBehaviour
{
public delegate void RequestListenerDelegate(AsyncJSONRequest request);
private static string XML_PREFIX = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<string xmlns=\"http://tempuri.org/\">";
private static string XML_SUFFIX = "</string>";
public enum eRequestState
{
preflight,
pending,
failed,
succeded
}
private string m_requestURL= "";
private Dictionary<string, object> m_requestData = null;
private WWWForm m_request= null;
private WWW m_loader= null;
private string m_result= null;
private RequestListenerDelegate m_resultListener= null;
private eRequestState m_state = eRequestState.preflight;
private string m_failureReason= "";
private uint m_requestCount= 0;
public static AsyncJSONRequest Create(GameObject gameObject)
{
return gameObject.AddComponent<AsyncJSONRequest>();
}
public static void Destroy(AsyncJSONRequest request)
{
GameObject.Destroy(request);
}
public void POST(string url, Dictionary<string, object> requestData, RequestListenerDelegate onComplete)
{
SessionData sessionData= SessionData.GetInstance();
m_requestURL = url;
m_requestData = requestData;
m_request = new WWWForm();
m_resultListener = onComplete;
if (requestData != null)
{
foreach (string fieldName in requestData.Keys)
{
string fieldValue = requestData[fieldName].ToString();
m_request.AddField(fieldName, fieldValue);
}
}
//###HACK:
// For some reason you can't add a key-value pair directly to the request header
// You have to clone it, and add the cookie to that instead
Hashtable headers = m_request.headers.Clone() as Hashtable;
if (sessionData.Cookie.Length > 0)
{
headers.Add("Cookie", SessionData.GetInstance().Cookie);
}
m_loader = new WWW(m_requestURL, m_request.data, headers);
Debug.Log("Sending POST request");
StartCoroutine(ExecuteRequest());
}
public void GET(string url, RequestListenerDelegate onComplete)
{
m_requestURL = url;
m_requestData = null;
m_request = null;
m_resultListener = onComplete;
m_loader = new WWW(m_requestURL);
Debug.Log("Sending POST request");
StartCoroutine(ExecuteRequest());
}
public eRequestState GetRequestState()
{
return m_state;
}
public uint GetRequestCount()
{
return m_requestCount;
}
public string GetFailureReason()
{
return m_failureReason;
}
public Dictionary<string, object> GetRequestData()
{
return m_requestData;
}
public WWW GetLoader()
{
return m_loader;
}
public JsonData GetResult()
{
return JsonMapper.ToObject(m_result);
}
public T GetResult<T>()
{
return JsonMapper.ToObject<T>(m_result);
}
private IEnumerator ExecuteRequest()
{
m_requestCount++;
m_state = eRequestState.pending;
m_result = null;
m_failureReason = "";
Debug.Log("Sending Async Request");
Debug.Log("url: " + m_requestURL);
if (m_requestData != null)
{
Debug.Log("inputJSONData: " + m_requestData.ToString());
}
yield return m_loader;
if (m_loader.error != null && m_loader.error.Length > 0)
{
m_state = eRequestState.failed;
m_failureReason = "loaderError: " + m_loader.error;
NotifyRequestCompleted();
}
else
{
LoaderCompleteHandler();
}
}
private void NotifyRequestCompleted()
{
if (m_state == eRequestState.succeded)
{
Debug.Log("Received Async Response(SUCCESS)");
Debug.Log("url: " + m_requestURL);
if (m_result != null)
{
Debug.Log("result: "+m_result.ToString());
}
}
else
{
Debug.LogError("Received Async Response(FAILED)");
Debug.LogError("url: " + m_requestURL);
Debug.LogError("reason: " + m_failureReason);
}
if (m_resultListener != null)
{
m_resultListener(this);
}
}
private void LoaderCompleteHandler()
{
try
{
string jsonString = StripXMLWrapper(m_loader.text);
m_result = jsonString;
m_state = eRequestState.succeded;
}
catch (Exception error)
{
m_state = eRequestState.failed;
m_failureReason = "JSON Parse Error: " + error.Message;
}
NotifyRequestCompleted();
}
private static string StripXMLWrapper(string source)
{
string result = source;
if (source.IndexOf(XML_PREFIX) == 0 && result.LastIndexOf(XML_SUFFIX) > 0)
{
result = source.Substring(XML_PREFIX.Length, source.Length - XML_PREFIX.Length - XML_SUFFIX.Length);
}
return result;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
// C# translation of Whetstone Double Precision Benchmark
using Microsoft.Xunit.Performance;
using System;
using System.Runtime.CompilerServices;
using Xunit;
[assembly: OptimizeForBenchmarks]
[assembly: MeasureInstructionsRetired]
public static class Whetsto
{
#if DEBUG
public const int Iterations = 1;
#else
public const int Iterations = 50000;
#endif
private static int s_j, s_k, s_l;
private static double s_t, s_t2;
public static volatile int Volatile_out;
private static void Escape(int n, int j, int k, double x1, double x2, double x3, double x4)
{
Volatile_out = n;
Volatile_out = j;
Volatile_out = k;
Volatile_out = (int)x1;
Volatile_out = (int)x2;
Volatile_out = (int)x3;
Volatile_out = (int)x4;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static bool Bench()
{
double[] e1 = new double[4];
double x1, x2, x3, x4, x, y, z, t1;
int i, n1, n2, n3, n4, n6, n7, n8, n9, n10, n11;
s_t = 0.499975;
t1 = 0.50025;
s_t2 = 2.0;
n1 = 0 * Iterations;
n2 = 12 * Iterations;
n3 = 14 * Iterations;
n4 = 345 * Iterations;
n6 = 210 * Iterations;
n7 = 32 * Iterations;
n8 = 899 * Iterations;
n9 = 616 * Iterations;
n10 = 0 * Iterations;
n11 = 93 * Iterations;
x1 = 1.0;
x2 = x3 = x4 = -1.0;
for (i = 1; i <= n1; i += 1)
{
x1 = (x1 + x2 + x3 - x4) * s_t;
x2 = (x1 + x2 - x3 - x4) * s_t;
x3 = (x1 - x2 + x3 + x4) * s_t;
x4 = (-x1 + x2 + x3 + x4) * s_t;
}
Escape(n1, n1, n1, x1, x2, x3, x4);
/* MODULE 2: array elements */
e1[0] = 1.0;
e1[1] = e1[2] = e1[3] = -1.0;
for (i = 1; i <= n2; i += 1)
{
e1[0] = (e1[0] + e1[1] + e1[2] - e1[3]) * s_t;
e1[1] = (e1[0] + e1[1] - e1[2] + e1[3]) * s_t;
e1[2] = (e1[0] - e1[1] + e1[2] + e1[3]) * s_t;
e1[3] = (-e1[0] + e1[1] + e1[2] + e1[3]) * s_t;
}
Escape(n2, n3, n2, e1[0], e1[1], e1[2], e1[3]);
/* MODULE 3: array as parameter */
for (i = 1; i <= n3; i += 1)
{
PA(e1);
}
Escape(n3, n2, n2, e1[0], e1[1], e1[2], e1[3]);
/* MODULE 4: conditional jumps */
s_j = 1;
for (i = 1; i <= n4; i += 1)
{
if (s_j == 1)
{
s_j = 2;
}
else
{
s_j = 3;
}
if (s_j > 2)
{
s_j = 0;
}
else
{
s_j = 1;
}
if (s_j < 1)
{
s_j = 1;
}
else
{
s_j = 0;
}
}
Escape(n4, s_j, s_j, x1, x2, x3, x4);
/* MODULE 5: omitted */
/* MODULE 6: integer Math */
s_j = 1;
s_k = 2;
s_l = 3;
for (i = 1; i <= n6; i += 1)
{
s_j = s_j * (s_k - s_j) * (s_l - s_k);
s_k = s_l * s_k - (s_l - s_j) * s_k;
s_l = (s_l - s_k) * (s_k + s_j);
e1[s_l - 2] = s_j + s_k + s_l;
e1[s_k - 2] = s_j * s_k * s_l;
}
Escape(n6, s_j, s_k, e1[0], e1[1], e1[2], e1[3]);
/* MODULE 7: trig. functions */
x = y = 0.5;
for (i = 1; i <= n7; i += 1)
{
x = s_t * System.Math.Atan(s_t2 * System.Math.Sin(x) * System.Math.Cos(x) / (System.Math.Cos(x + y) + System.Math.Cos(x - y) - 1.0));
y = s_t * System.Math.Atan(s_t2 * System.Math.Sin(y) * System.Math.Cos(y) / (System.Math.Cos(x + y) + System.Math.Cos(x - y) - 1.0));
}
Escape(n7, s_j, s_k, x, x, y, y);
/* MODULE 8: procedure calls */
x = y = z = 1.0;
for (i = 1; i <= n8; i += 1)
{
P3(x, y, out z);
}
Escape(n8, s_j, s_k, x, y, z, z);
/* MODULE9: array references */
s_j = 1;
s_k = 2;
s_l = 3;
e1[0] = 1.0;
e1[1] = 2.0;
e1[2] = 3.0;
for (i = 1; i <= n9; i += 1)
{
P0(e1);
}
Escape(n9, s_j, s_k, e1[0], e1[1], e1[2], e1[3]);
/* MODULE10: integer System.Math */
s_j = 2;
s_k = 3;
for (i = 1; i <= n10; i += 1)
{
s_j = s_j + s_k;
s_k = s_j + s_k;
s_j = s_k - s_j;
s_k = s_k - s_j - s_j;
}
Escape(n10, s_j, s_k, x1, x2, x3, x4);
/* MODULE11: standard functions */
x = 0.75;
for (i = 1; i <= n11; i += 1)
{
x = System.Math.Sqrt(System.Math.Exp(System.Math.Log(x) / t1));
}
Escape(n11, s_j, s_k, x, x, x, x);
return true;
}
private static void PA(double[] e)
{
int j;
j = 0;
lab:
e[0] = (e[0] + e[1] + e[2] - e[3]) * s_t;
e[1] = (e[0] + e[1] - e[2] + e[3]) * s_t;
e[2] = (e[0] - e[1] + e[2] + e[3]) * s_t;
e[3] = (-e[0] + e[1] + e[2] + e[3]) / s_t2;
j += 1;
if (j < 6)
{
goto lab;
}
}
private static void P3(double x, double y, out double z)
{
x = s_t * (x + y);
y = s_t * (x + y);
z = (x + y) / s_t2;
}
private static void P0(double[] e1)
{
e1[s_j] = e1[s_k];
e1[s_k] = e1[s_l];
e1[s_l] = e1[s_j];
}
[Benchmark]
public static void Test()
{
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
Bench();
}
}
}
private static bool TestBase()
{
bool result = Bench();
return result;
}
public static int Main()
{
bool result = TestBase();
return (result ? 100 : -1);
}
}
| |
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 PCSComProduction.DCP.DS
{
public class PRO_PGProductDS
{
public PRO_PGProductDS()
{
}
private const string THIS = "PCSComProduction.DCP.DS.PRO_PGProductDS";
//**************************************************************************
/// <Description>
/// This method uses to add data to PRO_PGProduct
/// </Description>
/// <Inputs>
/// PRO_PGProductVO
/// </Inputs>
/// <Outputs>
/// newly inserted primarkey value
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Thursday, May 18, 2006
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Add(object pobjObjectVO)
{
const string METHOD_NAME = THIS + ".Add()";
return;
}
//**************************************************************************
/// <Description>
/// This method uses to delete data from PRO_PGProduct
/// </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 " + PRO_PGProductTable.TABLE_NAME + " WHERE " + "PGProductID" + "=" + 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.Count > 1)
{
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 PRO_PGProduct
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// PRO_PGProductVO
/// </Outputs>
/// <Returns>
/// PRO_PGProductVO
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Thursday, May 18, 2006
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetObjectVO(int pintID)
{
const string METHOD_NAME = THIS + ".GetObjectVO()";
return null;
}
//**************************************************************************
/// <Description>
/// This method uses to update data to PRO_PGProduct
/// </Description>
/// <Inputs>
/// PRO_PGProductVO
/// </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()";
return;
}
//**************************************************************************
/// <Description>
/// This method uses to get all data from PRO_PGProduct
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Thursday, May 18, 2006
/// </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 "
+ PRO_PGProductTable.PGPRODUCTID_FLD + ","
+ PRO_PGProductTable.PRODUCTIONGROUPID_FLD + ","
+ PRO_PGProductTable.PRODUCTID_FLD
+ " FROM " + PRO_PGProductTable.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,PRO_PGProductTable.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();
}
}
}
}
public DataTable GetAllData()
{
const string METHOD_NAME = THIS + ".GetAllData()";
DataTable dtbResult = new DataTable(PRO_PGProductTable.TABLE_NAME);
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql = "SELECT PRO_ProductionGroup.Description AS PRO_ProductionGroupDescription,";
strSql += " PRO_ProductionLine.Code AS PRO_ProductionLineCode,";
strSql += " PRO_ProductionGroup.GroupProductionMax,";
strSql += " ITM_Product.Code as ITM_ProductCode,";
strSql += " ITM_Product.Description as ITM_ProductDescription,";
strSql += " ITM_Product.Revision as ITM_ProductRevision,";
strSql += " ITM_Category.Code AS ITM_CategoryCode,";
strSql += " PRO_PGProduct.PGProductID,";
strSql += " PRO_PGProduct.ProductionGroupID,";
strSql += " PRO_ProductionLine.ProductionLineID, ";
strSql += " PRO_PGProduct.ProductID";
strSql += " FROM PRO_PGProduct ";
strSql += " INNER JOIN ITM_Product ON PRO_PGProduct.ProductID = ITM_Product.ProductID ";
strSql += " INNER JOIN PRO_ProductionGroup ON PRO_PGProduct.ProductionGroupID = PRO_ProductionGroup.ProductionGroupID";
strSql += " INNER JOIN PRO_ProductionLine ON PRO_ProductionGroup.ProductionLineID = PRO_ProductionLine.ProductionLineID";
strSql += " LEFT JOIN ITM_Category ON ITM_Category.CategoryID = ITM_Product.CategoryID";
strSql += " ORDER BY PRO_ProductionGroup.Description, ITM_Product.Code";
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(dtbResult);
return dtbResult;
}
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>
/// Thursday, May 18, 2006
/// </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 "
+ PRO_PGProductTable.PGPRODUCTID_FLD + ","
+ PRO_PGProductTable.PRODUCTIONGROUPID_FLD + ","
+ PRO_PGProductTable.PRODUCTID_FLD
+ " FROM " + PRO_PGProductTable.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, PRO_PGProductTable.TABLE_NAME);
}
catch(OleDbException ex)
{
if(ex.Errors.Count > 1)
{
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();
}
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace webfolio.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
/*
* Copyright (c) 2007-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
// Gear Joint:
// C0 = (coordinate1 + ratio * coordinate2)_initial
// C = (coordinate1 + ratio * coordinate2) - C0 = 0
// J = [J1 ratio * J2]
// K = J * invM * JT
// = J1 * invM1 * J1T + ratio * ratio * J2 * invM2 * J2T
//
// Revolute:
// coordinate = rotation
// Cdot = angularVelocity
// J = [0 0 1]
// K = J * invM * JT = invI
//
// Prismatic:
// coordinate = dot(p - pg, ug)
// Cdot = dot(v + cross(w, r), ug)
// J = [ug cross(r, ug)]
// K = J * invM * JT = invMass + invI * cross(r, ug)^2
using System;
using System.Diagnostics;
using Box2D.Common;
namespace Box2D.Dynamics.Joints
{
/// A gear joint is used to connect two joints together. Either joint
/// can be a revolute or prismatic joint. You specify a gear ratio
/// to bind the motions together:
/// coordinate1 + ratio * coordinate2 = constant
/// The ratio can be negative or positive. If one joint is a revolute joint
/// and the other joint is a prismatic joint, then the ratio will have units
/// of length or units of 1/length.
/// @warning You have to manually destroy the gear joint if joint1 or joint2
/// is destroyed.
public class b2GearJoint : b2Joint
{
protected b2Joint m_joint1;
protected b2Joint m_joint2;
protected b2JointType m_typeA;
protected b2JointType m_typeB;
// Body A is connected to body C
// Body B is connected to body D
protected b2Body m_bodyC;
protected b2Body m_bodyD;
// Solver shared
protected b2Vec2 m_localAnchorA;
protected b2Vec2 m_localAnchorB;
protected b2Vec2 m_localAnchorC;
protected b2Vec2 m_localAnchorD;
protected b2Vec2 m_localAxisC;
protected b2Vec2 m_localAxisD;
protected float m_referenceAngleA;
protected float m_referenceAngleB;
protected float m_constant;
protected float m_ratio;
protected float m_impulse;
// Solver temp
protected int m_indexA, m_indexB, m_indexC, m_indexD;
protected b2Vec2 m_lcA, m_lcB, m_lcC, m_lcD;
protected float m_mA, m_mB, m_mC, m_mD;
protected float m_iA, m_iB, m_iC, m_iD;
protected b2Vec2 m_JvAC, m_JvBD;
protected float m_JwA, m_JwB, m_JwC, m_JwD;
protected float m_mass;
public b2GearJoint(b2GearJointDef def)
: base(def)
{
m_joint1 = def.joint1;
m_joint2 = def.joint2;
m_typeA = m_joint1.GetJointType();
m_typeB = m_joint2.GetJointType();
Debug.Assert(m_typeA == b2JointType.e_revoluteJoint || m_typeA == b2JointType.e_prismaticJoint);
Debug.Assert(m_typeB == b2JointType.e_revoluteJoint || m_typeB == b2JointType.e_prismaticJoint);
float coordinateA, coordinateB;
// TODO_ERIN there might be some problem with the joint edges in b2Joint.
m_bodyC = m_joint1.GetBodyA();
m_bodyA = m_joint1.GetBodyB();
// Get geometry of joint1
b2Transform xfA = m_bodyA.XF;
float aA = m_bodyA.Sweep.a;
b2Transform xfC = m_bodyC.XF;
float aC = m_bodyC.Sweep.a;
if (m_typeA == b2JointType.e_revoluteJoint)
{
b2RevoluteJoint revolute = (b2RevoluteJoint)def.joint1;
m_localAnchorC = revolute.GetLocalAnchorA();
m_localAnchorA = revolute.GetLocalAnchorB();
m_referenceAngleA = revolute.GetReferenceAngle();
m_localAxisC.SetZero();
coordinateA = aA - aC - m_referenceAngleA;
}
else
{
b2PrismaticJoint prismatic = (b2PrismaticJoint)def.joint1;
m_localAnchorC = prismatic.GetLocalAnchorA();
m_localAnchorA = prismatic.GetLocalAnchorB();
m_referenceAngleA = prismatic.GetReferenceAngle();
m_localAxisC = prismatic.GetLocalXAxisA();
b2Vec2 pC = m_localAnchorC;
b2Vec2 pA = b2Math.b2MulT(xfC.q, b2Math.b2Mul(xfA.q, m_localAnchorA) + (xfA.p - xfC.p));
coordinateA = b2Math.b2Dot(pA - pC, m_localAxisC);
}
m_bodyD = m_joint2.GetBodyA();
m_bodyB = m_joint2.GetBodyB();
// Get geometry of joint2
b2Transform xfB = m_bodyB.XF;
float aB = m_bodyB.Sweep.a;
b2Transform xfD = m_bodyD.XF;
float aD = m_bodyD.Sweep.a;
if (m_typeB == b2JointType.e_revoluteJoint)
{
b2RevoluteJoint revolute = (b2RevoluteJoint)def.joint2;
m_localAnchorD = revolute.GetLocalAnchorA();
m_localAnchorB = revolute.GetLocalAnchorB();
m_referenceAngleB = revolute.GetReferenceAngle();
m_localAxisD.SetZero();
coordinateB = aB - aD - m_referenceAngleB;
}
else
{
b2PrismaticJoint prismatic = (b2PrismaticJoint)def.joint2;
m_localAnchorD = prismatic.GetLocalAnchorA();
m_localAnchorB = prismatic.GetLocalAnchorB();
m_referenceAngleB = prismatic.GetReferenceAngle();
m_localAxisD = prismatic.GetLocalXAxisA();
b2Vec2 pD = m_localAnchorD;
b2Vec2 pB = b2Math.b2MulT(xfD.q, b2Math.b2Mul(xfB.q, m_localAnchorB) + (xfB.p - xfD.p));
coordinateB = b2Math.b2Dot(pB - pD, m_localAxisD);
}
m_ratio = def.ratio;
m_constant = coordinateA + m_ratio * coordinateB;
m_impulse = 0.0f;
}
/// Get the first joint.
public virtual b2Joint GetJoint1() { return m_joint1; }
/// Get the second joint.
public virtual b2Joint GetJoint2() { return m_joint2; }
public override void InitVelocityConstraints(b2SolverData data)
{
m_indexA = m_bodyA.IslandIndex;
m_indexB = m_bodyB.IslandIndex;
m_indexC = m_bodyC.IslandIndex;
m_indexD = m_bodyD.IslandIndex;
m_lcA = m_bodyA.Sweep.localCenter;
m_lcB = m_bodyB.Sweep.localCenter;
m_lcC = m_bodyC.Sweep.localCenter;
m_lcD = m_bodyD.Sweep.localCenter;
m_mA = m_bodyA.InvertedMass;
m_mB = m_bodyB.InvertedMass;
m_mC = m_bodyC.InvertedMass;
m_mD = m_bodyD.InvertedMass;
m_iA = m_bodyA.InvertedI;
m_iB = m_bodyB.InvertedI;
m_iC = m_bodyC.InvertedI;
m_iD = m_bodyD.InvertedI;
b2Vec2 cA = m_bodyA.InternalPosition.c;
float aA = m_bodyA.InternalPosition.a;
b2Vec2 vA = m_bodyA.InternalVelocity.v;
float wA = m_bodyA.InternalVelocity.w;
b2Vec2 cB = m_bodyB.InternalPosition.c;
float aB = m_bodyB.InternalPosition.a;
b2Vec2 vB = m_bodyB.InternalVelocity.v;
float wB = m_bodyB.InternalVelocity.w;
b2Vec2 cC = m_bodyC.InternalPosition.c;
float aC = m_bodyC.InternalPosition.a;
b2Vec2 vC = m_bodyC.InternalVelocity.v;
float wC = m_bodyC.InternalVelocity.w;
b2Vec2 cD = m_bodyD.InternalPosition.c;
float aD = m_bodyD.InternalPosition.a;
b2Vec2 vD = m_bodyD.InternalVelocity.v;
float wD = m_bodyD.InternalVelocity.w;
b2Rot qA = new b2Rot(aA);
b2Rot qB = new b2Rot(aB);
b2Rot qC = new b2Rot(aC);
b2Rot qD = new b2Rot(aD);
m_mass = 0.0f;
if (m_typeA == b2JointType.e_revoluteJoint)
{
m_JvAC.SetZero();
m_JwA = 1.0f;
m_JwC = 1.0f;
m_mass += m_iA + m_iC;
}
else
{
b2Vec2 u = b2Math.b2Mul(qC, m_localAxisC);
b2Vec2 rC = b2Math.b2Mul(qC, m_localAnchorC - m_lcC);
b2Vec2 rA = b2Math.b2Mul(qA, m_localAnchorA - m_lcA);
m_JvAC = u;
m_JwC = b2Math.b2Cross(rC, u);
m_JwA = b2Math.b2Cross(rA, u);
m_mass += m_mC + m_mA + m_iC * m_JwC * m_JwC + m_iA * m_JwA * m_JwA;
}
if (m_typeB == b2JointType.e_revoluteJoint)
{
m_JvBD.SetZero();
m_JwB = m_ratio;
m_JwD = m_ratio;
m_mass += m_ratio * m_ratio * (m_iB + m_iD);
}
else
{
b2Vec2 u = b2Math.b2Mul(qD, m_localAxisD);
b2Vec2 rD = b2Math.b2Mul(qD, m_localAnchorD - m_lcD);
b2Vec2 rB = b2Math.b2Mul(qB, m_localAnchorB - m_lcB);
m_JvBD = m_ratio * u;
m_JwD = m_ratio * b2Math.b2Cross(rD, u);
m_JwB = m_ratio * b2Math.b2Cross(rB, u);
m_mass += m_ratio * m_ratio * (m_mD + m_mB) + m_iD * m_JwD * m_JwD + m_iB * m_JwB * m_JwB;
}
// Compute effective mass.
m_mass = m_mass > 0.0f ? 1.0f / m_mass : 0.0f;
if (data.step.warmStarting)
{
vA += (m_mA * m_impulse) * m_JvAC;
wA += m_iA * m_impulse * m_JwA;
vB += (m_mB * m_impulse) * m_JvBD;
wB += m_iB * m_impulse * m_JwB;
vC -= (m_mC * m_impulse) * m_JvAC;
wC -= m_iC * m_impulse * m_JwC;
vD -= (m_mD * m_impulse) * m_JvBD;
wD -= m_iD * m_impulse * m_JwD;
}
else
{
m_impulse = 0.0f;
}
m_bodyA.InternalVelocity.v = vA;
m_bodyA.InternalVelocity.w = wA;
m_bodyB.InternalVelocity.v = vB;
m_bodyB.InternalVelocity.w = wB;
m_bodyC.InternalVelocity.v = vC;
m_bodyC.InternalVelocity.w = wC;
m_bodyD.InternalVelocity.v = vD;
m_bodyD.InternalVelocity.w = wD;
}
public override void SolveVelocityConstraints(b2SolverData data)
{
b2Vec2 vA = m_bodyA.InternalVelocity.v;
float wA = m_bodyA.InternalVelocity.w;
b2Vec2 vB = m_bodyB.InternalVelocity.v;
float wB = m_bodyB.InternalVelocity.w;
b2Vec2 vC = m_bodyC.InternalVelocity.v;
float wC = m_bodyC.InternalVelocity.w;
b2Vec2 vD = m_bodyD.InternalVelocity.v;
float wD = m_bodyD.InternalVelocity.w;
float Cdot = b2Math.b2Dot(m_JvAC, vA - vC) + b2Math.b2Dot(m_JvBD, vB - vD);
Cdot += (m_JwA * wA - m_JwC * wC) + (m_JwB * wB - m_JwD * wD);
float impulse = -m_mass * Cdot;
m_impulse += impulse;
vA += (m_mA * impulse) * m_JvAC;
wA += m_iA * impulse * m_JwA;
vB += (m_mB * impulse) * m_JvBD;
wB += m_iB * impulse * m_JwB;
vC -= (m_mC * impulse) * m_JvAC;
wC -= m_iC * impulse * m_JwC;
vD -= (m_mD * impulse) * m_JvBD;
wD -= m_iD * impulse * m_JwD;
m_bodyA.InternalVelocity.v = vA;
m_bodyA.InternalVelocity.w = wA;
m_bodyB.InternalVelocity.v = vB;
m_bodyB.InternalVelocity.w = wB;
m_bodyC.InternalVelocity.v = vC;
m_bodyC.InternalVelocity.w = wC;
m_bodyD.InternalVelocity.v = vD;
m_bodyD.InternalVelocity.w = wD;
}
public override bool SolvePositionConstraints(b2SolverData data)
{
b2Vec2 cA = m_bodyA.InternalPosition.c;
float aA = m_bodyA.InternalPosition.a;
b2Vec2 cB = m_bodyB.InternalPosition.c;
float aB = m_bodyB.InternalPosition.a;
b2Vec2 cC = m_bodyC.InternalPosition.c;
float aC = m_bodyC.InternalPosition.a;
b2Vec2 cD = m_bodyD.InternalPosition.c;
float aD = m_bodyD.InternalPosition.a;
b2Rot qA = new b2Rot(aA);
b2Rot qB = new b2Rot(aB);
b2Rot qC = new b2Rot(aC);
b2Rot qD = new b2Rot(aD);
float linearError = 0.0f;
float coordinateA, coordinateB;
b2Vec2 JvAC = b2Vec2.Zero, JvBD = b2Vec2.Zero;
float JwA, JwB, JwC, JwD;
float mass = 0.0f;
if (m_typeA == b2JointType.e_revoluteJoint)
{
JvAC.SetZero();
JwA = 1.0f;
JwC = 1.0f;
mass += m_iA + m_iC;
coordinateA = aA - aC - m_referenceAngleA;
}
else
{
b2Vec2 u = b2Math.b2Mul(qC, m_localAxisC);
b2Vec2 rC = b2Math.b2Mul(qC, m_localAnchorC - m_lcC);
b2Vec2 rA = b2Math.b2Mul(qA, m_localAnchorA - m_lcA);
JvAC = u;
JwC = b2Math.b2Cross(rC, u);
JwA = b2Math.b2Cross(rA, u);
mass += m_mC + m_mA + m_iC * JwC * JwC + m_iA * JwA * JwA;
b2Vec2 pC = m_localAnchorC - m_lcC;
b2Vec2 pA = b2Math.b2MulT(qC, rA + (cA - cC));
coordinateA = b2Math.b2Dot(pA - pC, m_localAxisC);
}
if (m_typeB == b2JointType.e_revoluteJoint)
{
JvBD.SetZero();
JwB = m_ratio;
JwD = m_ratio;
mass += m_ratio * m_ratio * (m_iB + m_iD);
coordinateB = aB - aD - m_referenceAngleB;
}
else
{
b2Vec2 u = b2Math.b2Mul(qD, m_localAxisD);
b2Vec2 rD = b2Math.b2Mul(qD, m_localAnchorD - m_lcD);
b2Vec2 rB = b2Math.b2Mul(qB, m_localAnchorB - m_lcB);
JvBD = m_ratio * u;
JwD = m_ratio * b2Math.b2Cross(rD, u);
JwB = m_ratio * b2Math.b2Cross(rB, u);
mass += m_ratio * m_ratio * (m_mD + m_mB) + m_iD * JwD * JwD + m_iB * JwB * JwB;
b2Vec2 pD = m_localAnchorD - m_lcD;
b2Vec2 pB = b2Math.b2MulT(qD, rB + (cB - cD));
coordinateB = b2Math.b2Dot(pB - pD, m_localAxisD);
}
float C = (coordinateA + m_ratio * coordinateB) - m_constant;
float impulse = 0.0f;
if (mass > 0.0f)
{
impulse = -C / mass;
}
cA += m_mA * impulse * JvAC;
aA += m_iA * impulse * JwA;
cB += m_mB * impulse * JvBD;
aB += m_iB * impulse * JwB;
cC -= m_mC * impulse * JvAC;
aC -= m_iC * impulse * JwC;
cD -= m_mD * impulse * JvBD;
aD -= m_iD * impulse * JwD;
m_bodyA.InternalPosition.c = cA;
m_bodyA.InternalPosition.a = aA;
m_bodyB.InternalPosition.c = cB;
m_bodyB.InternalPosition.a = aB;
m_bodyC.InternalPosition.c = cC;
m_bodyC.InternalPosition.a = aC;
m_bodyD.InternalPosition.c = cD;
m_bodyD.InternalPosition.a = aD;
// TODO_ERIN not implemented
return linearError < b2Settings.b2_linearSlop;
}
public override b2Vec2 GetAnchorA()
{
return m_bodyA.GetWorldPoint(m_localAnchorA);
}
public override b2Vec2 GetAnchorB()
{
return m_bodyB.GetWorldPoint(m_localAnchorB);
}
public virtual b2Vec2 GetReactionForce(float inv_dt)
{
b2Vec2 P = m_impulse * m_JvAC;
return inv_dt * P;
}
public virtual float GetReactionTorque(float inv_dt)
{
float L = m_impulse * m_JwA;
return inv_dt * L;
}
public virtual void SetRatio(float ratio)
{
Debug.Assert(b2Math.b2IsValid(ratio));
m_ratio = ratio;
}
public virtual float GetRatio()
{
return m_ratio;
}
public override void Dump()
{
int indexA = m_bodyA.IslandIndex;
int indexB = m_bodyB.IslandIndex;
int index1 = m_joint1.Index;
int index2 = m_joint2.Index;
b2Settings.b2Log(" b2GearJointDef jd;\n");
b2Settings.b2Log(" jd.bodyA = bodies[{0}];\n", indexA);
b2Settings.b2Log(" jd.bodyB = bodies[{0}];\n", indexB);
b2Settings.b2Log(" jd.collideConnected = bool({0});\n", m_collideConnected);
b2Settings.b2Log(" jd.joint1 = joints[{0}];\n", index1);
b2Settings.b2Log(" jd.joint2 = joints[{0}];\n", index2);
b2Settings.b2Log(" jd.ratio = {0:F5};\n", m_ratio);
b2Settings.b2Log(" joints[{0}] = m_world.CreateJoint(&jd);\n", m_index);
}
}
}
| |
#if !UNITY_WINRT || UNITY_EDITOR || (UNITY_WP8 && !UNITY_WP_8_1)
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Linq;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Generic;
using PlayFab.Json.Linq;
using PlayFab.Json.Utilities;
using PlayFab.Json.Serialization;
namespace PlayFab.Json.Schema
{
/// <summary>
/// Generates a <see cref="JsonSchema"/> from a specified <see cref="Type"/>.
/// </summary>
public class JsonSchemaGenerator
{
/// <summary>
/// Gets or sets how undefined schemas are handled by the serializer.
/// </summary>
public UndefinedSchemaIdHandling UndefinedSchemaIdHandling { get; set; }
private IContractResolver _contractResolver;
/// <summary>
/// Gets or sets the contract resolver.
/// </summary>
/// <value>The contract resolver.</value>
public IContractResolver ContractResolver
{
get
{
if (_contractResolver == null)
return DefaultContractResolver.Instance;
return _contractResolver;
}
set { _contractResolver = value; }
}
private class TypeSchema
{
public Type Type { get; private set; }
public JsonSchema Schema { get; private set;}
public TypeSchema(Type type, JsonSchema schema)
{
ValidationUtils.ArgumentNotNull(type, "type");
ValidationUtils.ArgumentNotNull(schema, "schema");
Type = type;
Schema = schema;
}
}
private JsonSchemaResolver _resolver;
private IList<TypeSchema> _stack = new List<TypeSchema>();
private JsonSchema _currentSchema;
private JsonSchema CurrentSchema
{
get { return _currentSchema; }
}
private void Push(TypeSchema typeSchema)
{
_currentSchema = typeSchema.Schema;
_stack.Add(typeSchema);
_resolver.LoadedSchemas.Add(typeSchema.Schema);
}
private TypeSchema Pop()
{
TypeSchema popped = _stack[_stack.Count - 1];
_stack.RemoveAt(_stack.Count - 1);
TypeSchema newValue = _stack.LastOrDefault();
if (newValue != null)
{
_currentSchema = newValue.Schema;
}
else
{
_currentSchema = null;
}
return popped;
}
/// <summary>
/// Generate a <see cref="JsonSchema"/> from the specified type.
/// </summary>
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
public JsonSchema Generate(Type type)
{
return Generate(type, new JsonSchemaResolver(), false);
}
/// <summary>
/// Generate a <see cref="JsonSchema"/> from the specified type.
/// </summary>
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <param name="resolver">The <see cref="JsonSchemaResolver"/> used to resolve schema references.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
public JsonSchema Generate(Type type, JsonSchemaResolver resolver)
{
return Generate(type, resolver, false);
}
/// <summary>
/// Generate a <see cref="JsonSchema"/> from the specified type.
/// </summary>
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JsonSchema"/> will be nullable.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
public JsonSchema Generate(Type type, bool rootSchemaNullable)
{
return Generate(type, new JsonSchemaResolver(), rootSchemaNullable);
}
/// <summary>
/// Generate a <see cref="JsonSchema"/> from the specified type.
/// </summary>
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <param name="resolver">The <see cref="JsonSchemaResolver"/> used to resolve schema references.</param>
/// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JsonSchema"/> will be nullable.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
public JsonSchema Generate(Type type, JsonSchemaResolver resolver, bool rootSchemaNullable)
{
ValidationUtils.ArgumentNotNull(type, "type");
ValidationUtils.ArgumentNotNull(resolver, "resolver");
_resolver = resolver;
return GenerateInternal(type, (!rootSchemaNullable) ? Required.Always : Required.Default, false);
}
private string GetTitle(Type type)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Title))
return containerAttribute.Title;
return null;
}
private string GetDescription(Type type)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Description))
return containerAttribute.Description;
DescriptionAttribute descriptionAttribute = ReflectionUtils.GetAttribute<DescriptionAttribute>(type);
if (descriptionAttribute != null)
return descriptionAttribute.Description;
return null;
}
private string GetTypeId(Type type, bool explicitOnly)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Id))
return containerAttribute.Id;
if (explicitOnly)
return null;
switch (UndefinedSchemaIdHandling)
{
case UndefinedSchemaIdHandling.UseTypeName:
return type.FullName;
case UndefinedSchemaIdHandling.UseAssemblyQualifiedName:
return type.AssemblyQualifiedName;
default:
return null;
}
}
private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required)
{
ValidationUtils.ArgumentNotNull(type, "type");
string resolvedId = GetTypeId(type, false);
string explicitId = GetTypeId(type, true);
if (!string.IsNullOrEmpty(resolvedId))
{
JsonSchema resolvedSchema = _resolver.GetSchema(resolvedId);
if (resolvedSchema != null)
{
// resolved schema is not null but referencing member allows nulls
// change resolved schema to allow nulls. hacky but what are ya gonna do?
if (valueRequired != Required.Always && !HasFlag(resolvedSchema.Type, JsonSchemaType.Null))
resolvedSchema.Type |= JsonSchemaType.Null;
if (required && resolvedSchema.Required != true)
resolvedSchema.Required = true;
return resolvedSchema;
}
}
// test for unresolved circular reference
if (_stack.Any(tc => tc.Type == type))
{
throw new Exception("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.".FormatWith(CultureInfo.InvariantCulture, type));
}
JsonContract contract = ContractResolver.ResolveContract(type);
JsonConverter converter;
if ((converter = contract.Converter) != null || (converter = contract.InternalConverter) != null)
{
JsonSchema converterSchema = converter.GetSchema();
if (converterSchema != null)
return converterSchema;
}
Push(new TypeSchema(type, new JsonSchema()));
if (explicitId != null)
CurrentSchema.Id = explicitId;
if (required)
CurrentSchema.Required = true;
CurrentSchema.Title = GetTitle(type);
CurrentSchema.Description = GetDescription(type);
if (converter != null)
{
// todo: Add GetSchema to JsonConverter and use here?
CurrentSchema.Type = JsonSchemaType.Any;
}
else if (contract is JsonDictionaryContract)
{
CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
Type keyType;
Type valueType;
ReflectionUtils.GetDictionaryKeyValueTypes(type, out keyType, out valueType);
if (keyType != null)
{
// can be converted to a string
if (typeof (IConvertible).IsAssignableFrom(keyType))
{
CurrentSchema.AdditionalProperties = GenerateInternal(valueType, Required.Default, false);
}
}
}
else if (contract is JsonArrayContract)
{
CurrentSchema.Type = AddNullType(JsonSchemaType.Array, valueRequired);
CurrentSchema.Id = GetTypeId(type, false);
JsonArrayAttribute arrayAttribute = JsonTypeReflector.GetJsonContainerAttribute(type) as JsonArrayAttribute;
bool allowNullItem = (arrayAttribute != null) ? arrayAttribute.AllowNullItems : true;
Type collectionItemType = ReflectionUtils.GetCollectionItemType(type);
if (collectionItemType != null)
{
CurrentSchema.Items = new List<JsonSchema>();
CurrentSchema.Items.Add(GenerateInternal(collectionItemType, (!allowNullItem) ? Required.Always : Required.Default, false));
}
}
else if (contract is JsonPrimitiveContract)
{
CurrentSchema.Type = GetJsonSchemaType(type, valueRequired);
if (CurrentSchema.Type == JsonSchemaType.Integer && type.IsEnum && !type.IsDefined(typeof(FlagsAttribute), true))
{
CurrentSchema.Enum = new List<JToken>();
CurrentSchema.Options = new Dictionary<JToken, string>();
EnumValues<long> enumValues = EnumUtils.GetNamesAndValues<long>(type);
foreach (EnumValue<long> enumValue in enumValues)
{
JToken value = JToken.FromObject(enumValue.Value);
CurrentSchema.Enum.Add(value);
CurrentSchema.Options.Add(value, enumValue.Name);
}
}
}
else if (contract is JsonObjectContract)
{
CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
CurrentSchema.Id = GetTypeId(type, false);
GenerateObjectSchema(type, (JsonObjectContract)contract);
}
else if (contract is JsonISerializableContract)
{
CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
CurrentSchema.Id = GetTypeId(type, false);
GenerateISerializableContract(type, (JsonISerializableContract) contract);
}
else if (contract is JsonStringContract)
{
JsonSchemaType schemaType = (!ReflectionUtils.IsNullable(contract.UnderlyingType))
? JsonSchemaType.String
: AddNullType(JsonSchemaType.String, valueRequired);
CurrentSchema.Type = schemaType;
}
else if (contract is JsonLinqContract)
{
CurrentSchema.Type = JsonSchemaType.Any;
}
else
{
throw new Exception("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, contract));
}
return Pop().Schema;
}
private JsonSchemaType AddNullType(JsonSchemaType type, Required valueRequired)
{
if (valueRequired != Required.Always)
return type | JsonSchemaType.Null;
return type;
}
private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag)
{
return ((value & flag) == flag);
}
private void GenerateObjectSchema(Type type, JsonObjectContract contract)
{
CurrentSchema.Properties = new Dictionary<string, JsonSchema>();
foreach (JsonProperty property in contract.Properties)
{
if (!property.Ignored)
{
bool optional = property.NullValueHandling == NullValueHandling.Ignore ||
HasFlag(property.DefaultValueHandling.GetValueOrDefault(), DefaultValueHandling.Ignore) ||
property.ShouldSerialize != null ||
property.GetIsSpecified != null;
JsonSchema propertySchema = GenerateInternal(property.PropertyType, property.Required, !optional);
if (property.DefaultValue != null)
propertySchema.Default = JToken.FromObject(property.DefaultValue);
CurrentSchema.Properties.Add(property.PropertyName, propertySchema);
}
}
if (type.IsSealed)
CurrentSchema.AllowAdditionalProperties = false;
}
private void GenerateISerializableContract(Type type, JsonISerializableContract contract)
{
CurrentSchema.AllowAdditionalProperties = true;
}
internal static bool HasFlag(JsonSchemaType? value, JsonSchemaType flag)
{
// default value is Any
if (value == null)
return true;
return ((value & flag) == flag);
}
private JsonSchemaType GetJsonSchemaType(Type type, Required valueRequired)
{
JsonSchemaType schemaType = JsonSchemaType.None;
if (valueRequired != Required.Always && ReflectionUtils.IsNullable(type))
{
schemaType = JsonSchemaType.Null;
if (ReflectionUtils.IsNullableType(type))
type = Nullable.GetUnderlyingType(type);
}
TypeCode typeCode = Type.GetTypeCode(type);
switch (typeCode)
{
case TypeCode.Empty:
case TypeCode.Object:
return schemaType | JsonSchemaType.String;
case TypeCode.DBNull:
return schemaType | JsonSchemaType.Null;
case TypeCode.Boolean:
return schemaType | JsonSchemaType.Boolean;
case TypeCode.Char:
return schemaType | JsonSchemaType.String;
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
return schemaType | JsonSchemaType.Integer;
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return schemaType | JsonSchemaType.Float;
// convert to string?
case TypeCode.DateTime:
return schemaType | JsonSchemaType.String;
case TypeCode.String:
return schemaType | JsonSchemaType.String;
default:
throw new Exception("Unexpected type code '{0}' for type '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeCode, type));
}
}
}
}
#endif
| |
//
// 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.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure.Management.Sql;
using Microsoft.Azure.Management.Sql.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Sql
{
/// <summary>
/// Represents all the operations for operating on Azure SQL Database
/// database backups.
/// </summary>
internal partial class DatabaseBackupOperations : IServiceOperations<SqlManagementClient>, IDatabaseBackupOperations
{
/// <summary>
/// Initializes a new instance of the DatabaseBackupOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal DatabaseBackupOperations(SqlManagementClient client)
{
this._client = client;
}
private SqlManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Sql.SqlManagementClient.
/// </summary>
public SqlManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Returns an Azure SQL deleted database backup (a resource
/// representing a deleted database that can be restored).
/// </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 Database Server to retrieve
/// deleted databases for.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database Database to retrieve
/// deleted databases for.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a Get Azure Sql Database deleted
/// database backup request.
/// </returns>
public async Task<DeletedDatabaseBackupGetResponse> GetDeletedDatabaseBackupAsync(string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
// 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("databaseName", databaseName);
TracingAdapter.Enter(invocationId, this, "GetDeletedDatabaseBackupAsync", 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 + "/restorabledroppeddatabases/";
url = url + Uri.EscapeDataString(databaseName);
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
DeletedDatabaseBackupGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DeletedDatabaseBackupGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
DeletedDatabaseBackup deletedDatabaseBackupInstance = new DeletedDatabaseBackup();
result.DeletedDatabaseBackup = deletedDatabaseBackupInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
DeletedDatabaseBackupProperties propertiesInstance = new DeletedDatabaseBackupProperties();
deletedDatabaseBackupInstance.Properties = propertiesInstance;
JToken databaseNameValue = propertiesValue["databaseName"];
if (databaseNameValue != null && databaseNameValue.Type != JTokenType.Null)
{
string databaseNameInstance = ((string)databaseNameValue);
propertiesInstance.DatabaseName = databaseNameInstance;
}
JToken editionValue = propertiesValue["edition"];
if (editionValue != null && editionValue.Type != JTokenType.Null)
{
string editionInstance = ((string)editionValue);
propertiesInstance.Edition = editionInstance;
}
JToken maxSizeBytesValue = propertiesValue["maxSizeBytes"];
if (maxSizeBytesValue != null && maxSizeBytesValue.Type != JTokenType.Null)
{
long maxSizeBytesInstance = ((long)maxSizeBytesValue);
propertiesInstance.MaxSizeBytes = maxSizeBytesInstance;
}
JToken serviceLevelObjectiveValue = propertiesValue["serviceLevelObjective"];
if (serviceLevelObjectiveValue != null && serviceLevelObjectiveValue.Type != JTokenType.Null)
{
string serviceLevelObjectiveInstance = ((string)serviceLevelObjectiveValue);
propertiesInstance.ServiceLevelObjective = serviceLevelObjectiveInstance;
}
JToken elasticPoolNameValue = propertiesValue["elasticPoolName"];
if (elasticPoolNameValue != null && elasticPoolNameValue.Type != JTokenType.Null)
{
string elasticPoolNameInstance = ((string)elasticPoolNameValue);
propertiesInstance.ElasticPoolName = elasticPoolNameInstance;
}
JToken creationDateValue = propertiesValue["creationDate"];
if (creationDateValue != null && creationDateValue.Type != JTokenType.Null)
{
DateTime creationDateInstance = ((DateTime)creationDateValue);
propertiesInstance.CreationDate = creationDateInstance;
}
JToken deletionDateValue = propertiesValue["deletionDate"];
if (deletionDateValue != null && deletionDateValue.Type != JTokenType.Null)
{
DateTime deletionDateInstance = ((DateTime)deletionDateValue);
propertiesInstance.DeletionDate = deletionDateInstance;
}
JToken earliestRestoreDateValue = propertiesValue["earliestRestoreDate"];
if (earliestRestoreDateValue != null && earliestRestoreDateValue.Type != JTokenType.Null)
{
DateTime earliestRestoreDateInstance = ((DateTime)earliestRestoreDateValue);
propertiesInstance.EarliestRestoreDate = earliestRestoreDateInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
deletedDatabaseBackupInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
deletedDatabaseBackupInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
deletedDatabaseBackupInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
deletedDatabaseBackupInstance.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);
deletedDatabaseBackupInstance.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>
/// Returns an Azure SQL Database geo backup.
/// </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 Database Server to retrieve geo
/// backups for.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database to retrieve geo
/// backups for.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a Get Azure Sql Database geo backup
/// request.
/// </returns>
public async Task<GeoBackupGetResponse> GetGeoBackupAsync(string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
// 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("databaseName", databaseName);
TracingAdapter.Enter(invocationId, this, "GetGeoBackupAsync", 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 + "/recoverabledatabases/";
url = url + Uri.EscapeDataString(databaseName);
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
GeoBackupGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new GeoBackupGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
GeoBackup geoBackupInstance = new GeoBackup();
result.GeoBackup = geoBackupInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
GeoBackupProperties propertiesInstance = new GeoBackupProperties();
geoBackupInstance.Properties = propertiesInstance;
JToken editionValue = propertiesValue["edition"];
if (editionValue != null && editionValue.Type != JTokenType.Null)
{
string editionInstance = ((string)editionValue);
propertiesInstance.Edition = editionInstance;
}
JToken serviceLevelObjectiveValue = propertiesValue["serviceLevelObjective"];
if (serviceLevelObjectiveValue != null && serviceLevelObjectiveValue.Type != JTokenType.Null)
{
string serviceLevelObjectiveInstance = ((string)serviceLevelObjectiveValue);
propertiesInstance.ServiceLevelObjective = serviceLevelObjectiveInstance;
}
JToken elasticPoolNameValue = propertiesValue["elasticPoolName"];
if (elasticPoolNameValue != null && elasticPoolNameValue.Type != JTokenType.Null)
{
string elasticPoolNameInstance = ((string)elasticPoolNameValue);
propertiesInstance.ElasticPoolName = elasticPoolNameInstance;
}
JToken lastAvailableBackupDateValue = propertiesValue["lastAvailableBackupDate"];
if (lastAvailableBackupDateValue != null && lastAvailableBackupDateValue.Type != JTokenType.Null)
{
DateTime lastAvailableBackupDateInstance = ((DateTime)lastAvailableBackupDateValue);
propertiesInstance.LastAvailableBackupDate = lastAvailableBackupDateInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
geoBackupInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
geoBackupInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
geoBackupInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
geoBackupInstance.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);
geoBackupInstance.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>
/// Returns a list of Azure SQL deleted database backups (a resource
/// representing a deleted database that can be restored).
/// </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 Database Server to retrieve
/// deleted databases for.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Database deleted
/// database backups request.
/// </returns>
public async Task<DeletedDatabaseBackupListResponse> ListDeletedDatabaseBackupsAsync(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, "ListDeletedDatabaseBackupsAsync", 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 + "/restorabledroppeddatabases";
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
DeletedDatabaseBackupListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DeletedDatabaseBackupListResponse();
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))
{
DeletedDatabaseBackup deletedDatabaseBackupInstance = new DeletedDatabaseBackup();
result.DeletedDatabaseBackups.Add(deletedDatabaseBackupInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
DeletedDatabaseBackupProperties propertiesInstance = new DeletedDatabaseBackupProperties();
deletedDatabaseBackupInstance.Properties = propertiesInstance;
JToken databaseNameValue = propertiesValue["databaseName"];
if (databaseNameValue != null && databaseNameValue.Type != JTokenType.Null)
{
string databaseNameInstance = ((string)databaseNameValue);
propertiesInstance.DatabaseName = databaseNameInstance;
}
JToken editionValue = propertiesValue["edition"];
if (editionValue != null && editionValue.Type != JTokenType.Null)
{
string editionInstance = ((string)editionValue);
propertiesInstance.Edition = editionInstance;
}
JToken maxSizeBytesValue = propertiesValue["maxSizeBytes"];
if (maxSizeBytesValue != null && maxSizeBytesValue.Type != JTokenType.Null)
{
long maxSizeBytesInstance = ((long)maxSizeBytesValue);
propertiesInstance.MaxSizeBytes = maxSizeBytesInstance;
}
JToken serviceLevelObjectiveValue = propertiesValue["serviceLevelObjective"];
if (serviceLevelObjectiveValue != null && serviceLevelObjectiveValue.Type != JTokenType.Null)
{
string serviceLevelObjectiveInstance = ((string)serviceLevelObjectiveValue);
propertiesInstance.ServiceLevelObjective = serviceLevelObjectiveInstance;
}
JToken elasticPoolNameValue = propertiesValue["elasticPoolName"];
if (elasticPoolNameValue != null && elasticPoolNameValue.Type != JTokenType.Null)
{
string elasticPoolNameInstance = ((string)elasticPoolNameValue);
propertiesInstance.ElasticPoolName = elasticPoolNameInstance;
}
JToken creationDateValue = propertiesValue["creationDate"];
if (creationDateValue != null && creationDateValue.Type != JTokenType.Null)
{
DateTime creationDateInstance = ((DateTime)creationDateValue);
propertiesInstance.CreationDate = creationDateInstance;
}
JToken deletionDateValue = propertiesValue["deletionDate"];
if (deletionDateValue != null && deletionDateValue.Type != JTokenType.Null)
{
DateTime deletionDateInstance = ((DateTime)deletionDateValue);
propertiesInstance.DeletionDate = deletionDateInstance;
}
JToken earliestRestoreDateValue = propertiesValue["earliestRestoreDate"];
if (earliestRestoreDateValue != null && earliestRestoreDateValue.Type != JTokenType.Null)
{
DateTime earliestRestoreDateInstance = ((DateTime)earliestRestoreDateValue);
propertiesInstance.EarliestRestoreDate = earliestRestoreDateInstance;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
deletedDatabaseBackupInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
deletedDatabaseBackupInstance.Name = nameInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
deletedDatabaseBackupInstance.Type = typeInstance;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
deletedDatabaseBackupInstance.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);
deletedDatabaseBackupInstance.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>
/// Returns a list of Azure SQL Database geo backups.
/// </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 Database Server to retrieve geo
/// backups for.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Database geo backups
/// request.
/// </returns>
public async Task<GeoBackupListResponse> ListGeoBackupsAsync(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, "ListGeoBackupsAsync", 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 + "/recoverabledatabases";
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
GeoBackupListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new GeoBackupListResponse();
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))
{
GeoBackup geoBackupInstance = new GeoBackup();
result.GeoBackups.Add(geoBackupInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
GeoBackupProperties propertiesInstance = new GeoBackupProperties();
geoBackupInstance.Properties = propertiesInstance;
JToken editionValue = propertiesValue["edition"];
if (editionValue != null && editionValue.Type != JTokenType.Null)
{
string editionInstance = ((string)editionValue);
propertiesInstance.Edition = editionInstance;
}
JToken serviceLevelObjectiveValue = propertiesValue["serviceLevelObjective"];
if (serviceLevelObjectiveValue != null && serviceLevelObjectiveValue.Type != JTokenType.Null)
{
string serviceLevelObjectiveInstance = ((string)serviceLevelObjectiveValue);
propertiesInstance.ServiceLevelObjective = serviceLevelObjectiveInstance;
}
JToken elasticPoolNameValue = propertiesValue["elasticPoolName"];
if (elasticPoolNameValue != null && elasticPoolNameValue.Type != JTokenType.Null)
{
string elasticPoolNameInstance = ((string)elasticPoolNameValue);
propertiesInstance.ElasticPoolName = elasticPoolNameInstance;
}
JToken lastAvailableBackupDateValue = propertiesValue["lastAvailableBackupDate"];
if (lastAvailableBackupDateValue != null && lastAvailableBackupDateValue.Type != JTokenType.Null)
{
DateTime lastAvailableBackupDateInstance = ((DateTime)lastAvailableBackupDateValue);
propertiesInstance.LastAvailableBackupDate = lastAvailableBackupDateInstance;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
geoBackupInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
geoBackupInstance.Name = nameInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
geoBackupInstance.Type = typeInstance;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
geoBackupInstance.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);
geoBackupInstance.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>
/// Returns a list of Azure SQL Database restore points.
/// </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 Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database from which to retrieve
/// available restore points.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Database restore points
/// request.
/// </returns>
public async Task<RestorePointListResponse> ListRestorePointsAsync(string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
// 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("databaseName", databaseName);
TracingAdapter.Enter(invocationId, this, "ListRestorePointsAsync", 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 + "/databases/";
url = url + Uri.EscapeDataString(databaseName);
url = url + "/restorePoints";
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
RestorePointListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new RestorePointListResponse();
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))
{
RestorePoint restorePointInstance = new RestorePoint();
result.RestorePoints.Add(restorePointInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
RestorePointProperties propertiesInstance = new RestorePointProperties();
restorePointInstance.Properties = propertiesInstance;
JToken restorePointTypeValue = propertiesValue["restorePointType"];
if (restorePointTypeValue != null && restorePointTypeValue.Type != JTokenType.Null)
{
string restorePointTypeInstance = ((string)restorePointTypeValue);
propertiesInstance.RestorePointType = restorePointTypeInstance;
}
JToken restorePointCreationDateValue = propertiesValue["restorePointCreationDate"];
if (restorePointCreationDateValue != null && restorePointCreationDateValue.Type != JTokenType.Null)
{
DateTime restorePointCreationDateInstance = ((DateTime)restorePointCreationDateValue);
propertiesInstance.RestorePointCreationDate = restorePointCreationDateInstance;
}
JToken earliestRestoreDateValue = propertiesValue["earliestRestoreDate"];
if (earliestRestoreDateValue != null && earliestRestoreDateValue.Type != JTokenType.Null)
{
DateTime earliestRestoreDateInstance = ((DateTime)earliestRestoreDateValue);
propertiesInstance.EarliestRestoreDate = earliestRestoreDateInstance;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
restorePointInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
restorePointInstance.Name = nameInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
restorePointInstance.Type = typeInstance;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
restorePointInstance.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);
restorePointInstance.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();
}
}
}
}
}
| |
namespace javax.microedition.khronos.opengles
{
[global::MonoJavaBridge.JavaInterface(typeof(global::javax.microedition.khronos.opengles.GL10_))]
public partial interface GL10 : GL
{
void glActiveTexture(int arg0);
void glAlphaFunc(int arg0, float arg1);
void glAlphaFuncx(int arg0, int arg1);
void glBindTexture(int arg0, int arg1);
void glBlendFunc(int arg0, int arg1);
void glClear(int arg0);
void glClearColor(float arg0, float arg1, float arg2, float arg3);
void glClearColorx(int arg0, int arg1, int arg2, int arg3);
void glClearDepthf(float arg0);
void glClearDepthx(int arg0);
void glClearStencil(int arg0);
void glClientActiveTexture(int arg0);
void glColor4f(float arg0, float arg1, float arg2, float arg3);
void glColor4x(int arg0, int arg1, int arg2, int arg3);
void glColorMask(bool arg0, bool arg1, bool arg2, bool arg3);
void glColorPointer(int arg0, int arg1, int arg2, java.nio.Buffer arg3);
void glCompressedTexImage2D(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, java.nio.Buffer arg7);
void glCompressedTexSubImage2D(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, java.nio.Buffer arg8);
void glCopyTexImage2D(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7);
void glCopyTexSubImage2D(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7);
void glCullFace(int arg0);
void glDeleteTextures(int arg0, int[] arg1, int arg2);
void glDeleteTextures(int arg0, java.nio.IntBuffer arg1);
void glDepthFunc(int arg0);
void glDepthMask(bool arg0);
void glDepthRangef(float arg0, float arg1);
void glDepthRangex(int arg0, int arg1);
void glDisable(int arg0);
void glDisableClientState(int arg0);
void glDrawArrays(int arg0, int arg1, int arg2);
void glDrawElements(int arg0, int arg1, int arg2, java.nio.Buffer arg3);
void glEnable(int arg0);
void glEnableClientState(int arg0);
void glFinish();
void glFlush();
void glFogf(int arg0, float arg1);
void glFogfv(int arg0, float[] arg1, int arg2);
void glFogfv(int arg0, java.nio.FloatBuffer arg1);
void glFogx(int arg0, int arg1);
void glFogxv(int arg0, int[] arg1, int arg2);
void glFogxv(int arg0, java.nio.IntBuffer arg1);
void glFrontFace(int arg0);
void glFrustumf(float arg0, float arg1, float arg2, float arg3, float arg4, float arg5);
void glFrustumx(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5);
void glGenTextures(int arg0, int[] arg1, int arg2);
void glGenTextures(int arg0, java.nio.IntBuffer arg1);
int glGetError();
void glGetIntegerv(int arg0, int[] arg1, int arg2);
void glGetIntegerv(int arg0, java.nio.IntBuffer arg1);
global::java.lang.String glGetString(int arg0);
void glHint(int arg0, int arg1);
void glLightModelf(int arg0, float arg1);
void glLightModelfv(int arg0, float[] arg1, int arg2);
void glLightModelfv(int arg0, java.nio.FloatBuffer arg1);
void glLightModelx(int arg0, int arg1);
void glLightModelxv(int arg0, int[] arg1, int arg2);
void glLightModelxv(int arg0, java.nio.IntBuffer arg1);
void glLightf(int arg0, int arg1, float arg2);
void glLightfv(int arg0, int arg1, float[] arg2, int arg3);
void glLightfv(int arg0, int arg1, java.nio.FloatBuffer arg2);
void glLightx(int arg0, int arg1, int arg2);
void glLightxv(int arg0, int arg1, int[] arg2, int arg3);
void glLightxv(int arg0, int arg1, java.nio.IntBuffer arg2);
void glLineWidth(float arg0);
void glLineWidthx(int arg0);
void glLoadIdentity();
void glLoadMatrixf(float[] arg0, int arg1);
void glLoadMatrixf(java.nio.FloatBuffer arg0);
void glLoadMatrixx(int[] arg0, int arg1);
void glLoadMatrixx(java.nio.IntBuffer arg0);
void glLogicOp(int arg0);
void glMaterialf(int arg0, int arg1, float arg2);
void glMaterialfv(int arg0, int arg1, float[] arg2, int arg3);
void glMaterialfv(int arg0, int arg1, java.nio.FloatBuffer arg2);
void glMaterialx(int arg0, int arg1, int arg2);
void glMaterialxv(int arg0, int arg1, int[] arg2, int arg3);
void glMaterialxv(int arg0, int arg1, java.nio.IntBuffer arg2);
void glMatrixMode(int arg0);
void glMultMatrixf(float[] arg0, int arg1);
void glMultMatrixf(java.nio.FloatBuffer arg0);
void glMultMatrixx(int[] arg0, int arg1);
void glMultMatrixx(java.nio.IntBuffer arg0);
void glMultiTexCoord4f(int arg0, float arg1, float arg2, float arg3, float arg4);
void glMultiTexCoord4x(int arg0, int arg1, int arg2, int arg3, int arg4);
void glNormal3f(float arg0, float arg1, float arg2);
void glNormal3x(int arg0, int arg1, int arg2);
void glNormalPointer(int arg0, int arg1, java.nio.Buffer arg2);
void glOrthof(float arg0, float arg1, float arg2, float arg3, float arg4, float arg5);
void glOrthox(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5);
void glPixelStorei(int arg0, int arg1);
void glPointSize(float arg0);
void glPointSizex(int arg0);
void glPolygonOffset(float arg0, float arg1);
void glPolygonOffsetx(int arg0, int arg1);
void glPopMatrix();
void glPushMatrix();
void glReadPixels(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, java.nio.Buffer arg6);
void glRotatef(float arg0, float arg1, float arg2, float arg3);
void glRotatex(int arg0, int arg1, int arg2, int arg3);
void glSampleCoverage(float arg0, bool arg1);
void glSampleCoveragex(int arg0, bool arg1);
void glScalef(float arg0, float arg1, float arg2);
void glScalex(int arg0, int arg1, int arg2);
void glScissor(int arg0, int arg1, int arg2, int arg3);
void glShadeModel(int arg0);
void glStencilFunc(int arg0, int arg1, int arg2);
void glStencilMask(int arg0);
void glStencilOp(int arg0, int arg1, int arg2);
void glTexCoordPointer(int arg0, int arg1, int arg2, java.nio.Buffer arg3);
void glTexEnvf(int arg0, int arg1, float arg2);
void glTexEnvfv(int arg0, int arg1, float[] arg2, int arg3);
void glTexEnvfv(int arg0, int arg1, java.nio.FloatBuffer arg2);
void glTexEnvx(int arg0, int arg1, int arg2);
void glTexEnvxv(int arg0, int arg1, int[] arg2, int arg3);
void glTexEnvxv(int arg0, int arg1, java.nio.IntBuffer arg2);
void glTexImage2D(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, java.nio.Buffer arg8);
void glTexParameterf(int arg0, int arg1, float arg2);
void glTexParameterx(int arg0, int arg1, int arg2);
void glTexSubImage2D(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, java.nio.Buffer arg8);
void glTranslatef(float arg0, float arg1, float arg2);
void glTranslatex(int arg0, int arg1, int arg2);
void glVertexPointer(int arg0, int arg1, int arg2, java.nio.Buffer arg3);
void glViewport(int arg0, int arg1, int arg2, int arg3);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::javax.microedition.khronos.opengles.GL10))]
internal sealed partial class GL10_ : java.lang.Object, GL10
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal GL10_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
void javax.microedition.khronos.opengles.GL10.glActiveTexture(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glActiveTexture", "(I)V", ref global::javax.microedition.khronos.opengles.GL10_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m1;
void javax.microedition.khronos.opengles.GL10.glAlphaFunc(int arg0, float arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glAlphaFunc", "(IF)V", ref global::javax.microedition.khronos.opengles.GL10_._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m2;
void javax.microedition.khronos.opengles.GL10.glAlphaFuncx(int arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glAlphaFuncx", "(II)V", ref global::javax.microedition.khronos.opengles.GL10_._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m3;
void javax.microedition.khronos.opengles.GL10.glBindTexture(int arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glBindTexture", "(II)V", ref global::javax.microedition.khronos.opengles.GL10_._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m4;
void javax.microedition.khronos.opengles.GL10.glBlendFunc(int arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glBlendFunc", "(II)V", ref global::javax.microedition.khronos.opengles.GL10_._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m5;
void javax.microedition.khronos.opengles.GL10.glClear(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glClear", "(I)V", ref global::javax.microedition.khronos.opengles.GL10_._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m6;
void javax.microedition.khronos.opengles.GL10.glClearColor(float arg0, float arg1, float arg2, float arg3)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glClearColor", "(FFFF)V", ref global::javax.microedition.khronos.opengles.GL10_._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
private static global::MonoJavaBridge.MethodId _m7;
void javax.microedition.khronos.opengles.GL10.glClearColorx(int arg0, int arg1, int arg2, int arg3)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glClearColorx", "(IIII)V", ref global::javax.microedition.khronos.opengles.GL10_._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
private static global::MonoJavaBridge.MethodId _m8;
void javax.microedition.khronos.opengles.GL10.glClearDepthf(float arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glClearDepthf", "(F)V", ref global::javax.microedition.khronos.opengles.GL10_._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m9;
void javax.microedition.khronos.opengles.GL10.glClearDepthx(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glClearDepthx", "(I)V", ref global::javax.microedition.khronos.opengles.GL10_._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m10;
void javax.microedition.khronos.opengles.GL10.glClearStencil(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glClearStencil", "(I)V", ref global::javax.microedition.khronos.opengles.GL10_._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m11;
void javax.microedition.khronos.opengles.GL10.glClientActiveTexture(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glClientActiveTexture", "(I)V", ref global::javax.microedition.khronos.opengles.GL10_._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m12;
void javax.microedition.khronos.opengles.GL10.glColor4f(float arg0, float arg1, float arg2, float arg3)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glColor4f", "(FFFF)V", ref global::javax.microedition.khronos.opengles.GL10_._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
private static global::MonoJavaBridge.MethodId _m13;
void javax.microedition.khronos.opengles.GL10.glColor4x(int arg0, int arg1, int arg2, int arg3)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glColor4x", "(IIII)V", ref global::javax.microedition.khronos.opengles.GL10_._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
private static global::MonoJavaBridge.MethodId _m14;
void javax.microedition.khronos.opengles.GL10.glColorMask(bool arg0, bool arg1, bool arg2, bool arg3)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glColorMask", "(ZZZZ)V", ref global::javax.microedition.khronos.opengles.GL10_._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
private static global::MonoJavaBridge.MethodId _m15;
void javax.microedition.khronos.opengles.GL10.glColorPointer(int arg0, int arg1, int arg2, java.nio.Buffer arg3)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glColorPointer", "(IIILjava/nio/Buffer;)V", ref global::javax.microedition.khronos.opengles.GL10_._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
private static global::MonoJavaBridge.MethodId _m16;
void javax.microedition.khronos.opengles.GL10.glCompressedTexImage2D(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, java.nio.Buffer arg7)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glCompressedTexImage2D", "(IIIIIIILjava/nio/Buffer;)V", ref global::javax.microedition.khronos.opengles.GL10_._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg7));
}
private static global::MonoJavaBridge.MethodId _m17;
void javax.microedition.khronos.opengles.GL10.glCompressedTexSubImage2D(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, java.nio.Buffer arg8)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glCompressedTexSubImage2D", "(IIIIIIIILjava/nio/Buffer;)V", ref global::javax.microedition.khronos.opengles.GL10_._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg7), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg8));
}
private static global::MonoJavaBridge.MethodId _m18;
void javax.microedition.khronos.opengles.GL10.glCopyTexImage2D(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glCopyTexImage2D", "(IIIIIIII)V", ref global::javax.microedition.khronos.opengles.GL10_._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg7));
}
private static global::MonoJavaBridge.MethodId _m19;
void javax.microedition.khronos.opengles.GL10.glCopyTexSubImage2D(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glCopyTexSubImage2D", "(IIIIIIII)V", ref global::javax.microedition.khronos.opengles.GL10_._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg7));
}
private static global::MonoJavaBridge.MethodId _m20;
void javax.microedition.khronos.opengles.GL10.glCullFace(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glCullFace", "(I)V", ref global::javax.microedition.khronos.opengles.GL10_._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m21;
void javax.microedition.khronos.opengles.GL10.glDeleteTextures(int arg0, int[] arg1, int arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glDeleteTextures", "(I[II)V", ref global::javax.microedition.khronos.opengles.GL10_._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m22;
void javax.microedition.khronos.opengles.GL10.glDeleteTextures(int arg0, java.nio.IntBuffer arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glDeleteTextures", "(ILjava/nio/IntBuffer;)V", ref global::javax.microedition.khronos.opengles.GL10_._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m23;
void javax.microedition.khronos.opengles.GL10.glDepthFunc(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glDepthFunc", "(I)V", ref global::javax.microedition.khronos.opengles.GL10_._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m24;
void javax.microedition.khronos.opengles.GL10.glDepthMask(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glDepthMask", "(Z)V", ref global::javax.microedition.khronos.opengles.GL10_._m24, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m25;
void javax.microedition.khronos.opengles.GL10.glDepthRangef(float arg0, float arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glDepthRangef", "(FF)V", ref global::javax.microedition.khronos.opengles.GL10_._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m26;
void javax.microedition.khronos.opengles.GL10.glDepthRangex(int arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glDepthRangex", "(II)V", ref global::javax.microedition.khronos.opengles.GL10_._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m27;
void javax.microedition.khronos.opengles.GL10.glDisable(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glDisable", "(I)V", ref global::javax.microedition.khronos.opengles.GL10_._m27, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m28;
void javax.microedition.khronos.opengles.GL10.glDisableClientState(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glDisableClientState", "(I)V", ref global::javax.microedition.khronos.opengles.GL10_._m28, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m29;
void javax.microedition.khronos.opengles.GL10.glDrawArrays(int arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glDrawArrays", "(III)V", ref global::javax.microedition.khronos.opengles.GL10_._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m30;
void javax.microedition.khronos.opengles.GL10.glDrawElements(int arg0, int arg1, int arg2, java.nio.Buffer arg3)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glDrawElements", "(IIILjava/nio/Buffer;)V", ref global::javax.microedition.khronos.opengles.GL10_._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
private static global::MonoJavaBridge.MethodId _m31;
void javax.microedition.khronos.opengles.GL10.glEnable(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glEnable", "(I)V", ref global::javax.microedition.khronos.opengles.GL10_._m31, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m32;
void javax.microedition.khronos.opengles.GL10.glEnableClientState(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glEnableClientState", "(I)V", ref global::javax.microedition.khronos.opengles.GL10_._m32, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m33;
void javax.microedition.khronos.opengles.GL10.glFinish()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glFinish", "()V", ref global::javax.microedition.khronos.opengles.GL10_._m33);
}
private static global::MonoJavaBridge.MethodId _m34;
void javax.microedition.khronos.opengles.GL10.glFlush()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glFlush", "()V", ref global::javax.microedition.khronos.opengles.GL10_._m34);
}
private static global::MonoJavaBridge.MethodId _m35;
void javax.microedition.khronos.opengles.GL10.glFogf(int arg0, float arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glFogf", "(IF)V", ref global::javax.microedition.khronos.opengles.GL10_._m35, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m36;
void javax.microedition.khronos.opengles.GL10.glFogfv(int arg0, float[] arg1, int arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glFogfv", "(I[FI)V", ref global::javax.microedition.khronos.opengles.GL10_._m36, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m37;
void javax.microedition.khronos.opengles.GL10.glFogfv(int arg0, java.nio.FloatBuffer arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glFogfv", "(ILjava/nio/FloatBuffer;)V", ref global::javax.microedition.khronos.opengles.GL10_._m37, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m38;
void javax.microedition.khronos.opengles.GL10.glFogx(int arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glFogx", "(II)V", ref global::javax.microedition.khronos.opengles.GL10_._m38, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m39;
void javax.microedition.khronos.opengles.GL10.glFogxv(int arg0, int[] arg1, int arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glFogxv", "(I[II)V", ref global::javax.microedition.khronos.opengles.GL10_._m39, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m40;
void javax.microedition.khronos.opengles.GL10.glFogxv(int arg0, java.nio.IntBuffer arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glFogxv", "(ILjava/nio/IntBuffer;)V", ref global::javax.microedition.khronos.opengles.GL10_._m40, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m41;
void javax.microedition.khronos.opengles.GL10.glFrontFace(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glFrontFace", "(I)V", ref global::javax.microedition.khronos.opengles.GL10_._m41, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m42;
void javax.microedition.khronos.opengles.GL10.glFrustumf(float arg0, float arg1, float arg2, float arg3, float arg4, float arg5)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glFrustumf", "(FFFFFF)V", ref global::javax.microedition.khronos.opengles.GL10_._m42, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5));
}
private static global::MonoJavaBridge.MethodId _m43;
void javax.microedition.khronos.opengles.GL10.glFrustumx(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glFrustumx", "(IIIIII)V", ref global::javax.microedition.khronos.opengles.GL10_._m43, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5));
}
private static global::MonoJavaBridge.MethodId _m44;
void javax.microedition.khronos.opengles.GL10.glGenTextures(int arg0, int[] arg1, int arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glGenTextures", "(I[II)V", ref global::javax.microedition.khronos.opengles.GL10_._m44, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m45;
void javax.microedition.khronos.opengles.GL10.glGenTextures(int arg0, java.nio.IntBuffer arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glGenTextures", "(ILjava/nio/IntBuffer;)V", ref global::javax.microedition.khronos.opengles.GL10_._m45, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m46;
int javax.microedition.khronos.opengles.GL10.glGetError()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glGetError", "()I", ref global::javax.microedition.khronos.opengles.GL10_._m46);
}
private static global::MonoJavaBridge.MethodId _m47;
void javax.microedition.khronos.opengles.GL10.glGetIntegerv(int arg0, int[] arg1, int arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glGetIntegerv", "(I[II)V", ref global::javax.microedition.khronos.opengles.GL10_._m47, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m48;
void javax.microedition.khronos.opengles.GL10.glGetIntegerv(int arg0, java.nio.IntBuffer arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glGetIntegerv", "(ILjava/nio/IntBuffer;)V", ref global::javax.microedition.khronos.opengles.GL10_._m48, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m49;
global::java.lang.String javax.microedition.khronos.opengles.GL10.glGetString(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glGetString", "(I)Ljava/lang/String;", ref global::javax.microedition.khronos.opengles.GL10_._m49, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m50;
void javax.microedition.khronos.opengles.GL10.glHint(int arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glHint", "(II)V", ref global::javax.microedition.khronos.opengles.GL10_._m50, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m51;
void javax.microedition.khronos.opengles.GL10.glLightModelf(int arg0, float arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glLightModelf", "(IF)V", ref global::javax.microedition.khronos.opengles.GL10_._m51, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m52;
void javax.microedition.khronos.opengles.GL10.glLightModelfv(int arg0, float[] arg1, int arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glLightModelfv", "(I[FI)V", ref global::javax.microedition.khronos.opengles.GL10_._m52, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m53;
void javax.microedition.khronos.opengles.GL10.glLightModelfv(int arg0, java.nio.FloatBuffer arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glLightModelfv", "(ILjava/nio/FloatBuffer;)V", ref global::javax.microedition.khronos.opengles.GL10_._m53, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m54;
void javax.microedition.khronos.opengles.GL10.glLightModelx(int arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glLightModelx", "(II)V", ref global::javax.microedition.khronos.opengles.GL10_._m54, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m55;
void javax.microedition.khronos.opengles.GL10.glLightModelxv(int arg0, int[] arg1, int arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glLightModelxv", "(I[II)V", ref global::javax.microedition.khronos.opengles.GL10_._m55, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m56;
void javax.microedition.khronos.opengles.GL10.glLightModelxv(int arg0, java.nio.IntBuffer arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glLightModelxv", "(ILjava/nio/IntBuffer;)V", ref global::javax.microedition.khronos.opengles.GL10_._m56, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m57;
void javax.microedition.khronos.opengles.GL10.glLightf(int arg0, int arg1, float arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glLightf", "(IIF)V", ref global::javax.microedition.khronos.opengles.GL10_._m57, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m58;
void javax.microedition.khronos.opengles.GL10.glLightfv(int arg0, int arg1, float[] arg2, int arg3)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glLightfv", "(II[FI)V", ref global::javax.microedition.khronos.opengles.GL10_._m58, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
private static global::MonoJavaBridge.MethodId _m59;
void javax.microedition.khronos.opengles.GL10.glLightfv(int arg0, int arg1, java.nio.FloatBuffer arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glLightfv", "(IILjava/nio/FloatBuffer;)V", ref global::javax.microedition.khronos.opengles.GL10_._m59, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m60;
void javax.microedition.khronos.opengles.GL10.glLightx(int arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glLightx", "(III)V", ref global::javax.microedition.khronos.opengles.GL10_._m60, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m61;
void javax.microedition.khronos.opengles.GL10.glLightxv(int arg0, int arg1, int[] arg2, int arg3)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glLightxv", "(II[II)V", ref global::javax.microedition.khronos.opengles.GL10_._m61, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
private static global::MonoJavaBridge.MethodId _m62;
void javax.microedition.khronos.opengles.GL10.glLightxv(int arg0, int arg1, java.nio.IntBuffer arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glLightxv", "(IILjava/nio/IntBuffer;)V", ref global::javax.microedition.khronos.opengles.GL10_._m62, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m63;
void javax.microedition.khronos.opengles.GL10.glLineWidth(float arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glLineWidth", "(F)V", ref global::javax.microedition.khronos.opengles.GL10_._m63, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m64;
void javax.microedition.khronos.opengles.GL10.glLineWidthx(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glLineWidthx", "(I)V", ref global::javax.microedition.khronos.opengles.GL10_._m64, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m65;
void javax.microedition.khronos.opengles.GL10.glLoadIdentity()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glLoadIdentity", "()V", ref global::javax.microedition.khronos.opengles.GL10_._m65);
}
private static global::MonoJavaBridge.MethodId _m66;
void javax.microedition.khronos.opengles.GL10.glLoadMatrixf(float[] arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glLoadMatrixf", "([FI)V", ref global::javax.microedition.khronos.opengles.GL10_._m66, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m67;
void javax.microedition.khronos.opengles.GL10.glLoadMatrixf(java.nio.FloatBuffer arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glLoadMatrixf", "(Ljava/nio/FloatBuffer;)V", ref global::javax.microedition.khronos.opengles.GL10_._m67, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m68;
void javax.microedition.khronos.opengles.GL10.glLoadMatrixx(int[] arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glLoadMatrixx", "([II)V", ref global::javax.microedition.khronos.opengles.GL10_._m68, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m69;
void javax.microedition.khronos.opengles.GL10.glLoadMatrixx(java.nio.IntBuffer arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glLoadMatrixx", "(Ljava/nio/IntBuffer;)V", ref global::javax.microedition.khronos.opengles.GL10_._m69, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m70;
void javax.microedition.khronos.opengles.GL10.glLogicOp(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glLogicOp", "(I)V", ref global::javax.microedition.khronos.opengles.GL10_._m70, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m71;
void javax.microedition.khronos.opengles.GL10.glMaterialf(int arg0, int arg1, float arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glMaterialf", "(IIF)V", ref global::javax.microedition.khronos.opengles.GL10_._m71, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m72;
void javax.microedition.khronos.opengles.GL10.glMaterialfv(int arg0, int arg1, float[] arg2, int arg3)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glMaterialfv", "(II[FI)V", ref global::javax.microedition.khronos.opengles.GL10_._m72, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
private static global::MonoJavaBridge.MethodId _m73;
void javax.microedition.khronos.opengles.GL10.glMaterialfv(int arg0, int arg1, java.nio.FloatBuffer arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glMaterialfv", "(IILjava/nio/FloatBuffer;)V", ref global::javax.microedition.khronos.opengles.GL10_._m73, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m74;
void javax.microedition.khronos.opengles.GL10.glMaterialx(int arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glMaterialx", "(III)V", ref global::javax.microedition.khronos.opengles.GL10_._m74, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m75;
void javax.microedition.khronos.opengles.GL10.glMaterialxv(int arg0, int arg1, int[] arg2, int arg3)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glMaterialxv", "(II[II)V", ref global::javax.microedition.khronos.opengles.GL10_._m75, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
private static global::MonoJavaBridge.MethodId _m76;
void javax.microedition.khronos.opengles.GL10.glMaterialxv(int arg0, int arg1, java.nio.IntBuffer arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glMaterialxv", "(IILjava/nio/IntBuffer;)V", ref global::javax.microedition.khronos.opengles.GL10_._m76, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m77;
void javax.microedition.khronos.opengles.GL10.glMatrixMode(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glMatrixMode", "(I)V", ref global::javax.microedition.khronos.opengles.GL10_._m77, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m78;
void javax.microedition.khronos.opengles.GL10.glMultMatrixf(float[] arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glMultMatrixf", "([FI)V", ref global::javax.microedition.khronos.opengles.GL10_._m78, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m79;
void javax.microedition.khronos.opengles.GL10.glMultMatrixf(java.nio.FloatBuffer arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glMultMatrixf", "(Ljava/nio/FloatBuffer;)V", ref global::javax.microedition.khronos.opengles.GL10_._m79, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m80;
void javax.microedition.khronos.opengles.GL10.glMultMatrixx(int[] arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glMultMatrixx", "([II)V", ref global::javax.microedition.khronos.opengles.GL10_._m80, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m81;
void javax.microedition.khronos.opengles.GL10.glMultMatrixx(java.nio.IntBuffer arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glMultMatrixx", "(Ljava/nio/IntBuffer;)V", ref global::javax.microedition.khronos.opengles.GL10_._m81, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m82;
void javax.microedition.khronos.opengles.GL10.glMultiTexCoord4f(int arg0, float arg1, float arg2, float arg3, float arg4)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glMultiTexCoord4f", "(IFFFF)V", ref global::javax.microedition.khronos.opengles.GL10_._m82, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
}
private static global::MonoJavaBridge.MethodId _m83;
void javax.microedition.khronos.opengles.GL10.glMultiTexCoord4x(int arg0, int arg1, int arg2, int arg3, int arg4)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glMultiTexCoord4x", "(IIIII)V", ref global::javax.microedition.khronos.opengles.GL10_._m83, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
}
private static global::MonoJavaBridge.MethodId _m84;
void javax.microedition.khronos.opengles.GL10.glNormal3f(float arg0, float arg1, float arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glNormal3f", "(FFF)V", ref global::javax.microedition.khronos.opengles.GL10_._m84, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m85;
void javax.microedition.khronos.opengles.GL10.glNormal3x(int arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glNormal3x", "(III)V", ref global::javax.microedition.khronos.opengles.GL10_._m85, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m86;
void javax.microedition.khronos.opengles.GL10.glNormalPointer(int arg0, int arg1, java.nio.Buffer arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glNormalPointer", "(IILjava/nio/Buffer;)V", ref global::javax.microedition.khronos.opengles.GL10_._m86, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m87;
void javax.microedition.khronos.opengles.GL10.glOrthof(float arg0, float arg1, float arg2, float arg3, float arg4, float arg5)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glOrthof", "(FFFFFF)V", ref global::javax.microedition.khronos.opengles.GL10_._m87, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5));
}
private static global::MonoJavaBridge.MethodId _m88;
void javax.microedition.khronos.opengles.GL10.glOrthox(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glOrthox", "(IIIIII)V", ref global::javax.microedition.khronos.opengles.GL10_._m88, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5));
}
private static global::MonoJavaBridge.MethodId _m89;
void javax.microedition.khronos.opengles.GL10.glPixelStorei(int arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glPixelStorei", "(II)V", ref global::javax.microedition.khronos.opengles.GL10_._m89, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m90;
void javax.microedition.khronos.opengles.GL10.glPointSize(float arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glPointSize", "(F)V", ref global::javax.microedition.khronos.opengles.GL10_._m90, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m91;
void javax.microedition.khronos.opengles.GL10.glPointSizex(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glPointSizex", "(I)V", ref global::javax.microedition.khronos.opengles.GL10_._m91, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m92;
void javax.microedition.khronos.opengles.GL10.glPolygonOffset(float arg0, float arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glPolygonOffset", "(FF)V", ref global::javax.microedition.khronos.opengles.GL10_._m92, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m93;
void javax.microedition.khronos.opengles.GL10.glPolygonOffsetx(int arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glPolygonOffsetx", "(II)V", ref global::javax.microedition.khronos.opengles.GL10_._m93, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m94;
void javax.microedition.khronos.opengles.GL10.glPopMatrix()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glPopMatrix", "()V", ref global::javax.microedition.khronos.opengles.GL10_._m94);
}
private static global::MonoJavaBridge.MethodId _m95;
void javax.microedition.khronos.opengles.GL10.glPushMatrix()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glPushMatrix", "()V", ref global::javax.microedition.khronos.opengles.GL10_._m95);
}
private static global::MonoJavaBridge.MethodId _m96;
void javax.microedition.khronos.opengles.GL10.glReadPixels(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, java.nio.Buffer arg6)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glReadPixels", "(IIIIIILjava/nio/Buffer;)V", ref global::javax.microedition.khronos.opengles.GL10_._m96, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6));
}
private static global::MonoJavaBridge.MethodId _m97;
void javax.microedition.khronos.opengles.GL10.glRotatef(float arg0, float arg1, float arg2, float arg3)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glRotatef", "(FFFF)V", ref global::javax.microedition.khronos.opengles.GL10_._m97, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
private static global::MonoJavaBridge.MethodId _m98;
void javax.microedition.khronos.opengles.GL10.glRotatex(int arg0, int arg1, int arg2, int arg3)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glRotatex", "(IIII)V", ref global::javax.microedition.khronos.opengles.GL10_._m98, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
private static global::MonoJavaBridge.MethodId _m99;
void javax.microedition.khronos.opengles.GL10.glSampleCoverage(float arg0, bool arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glSampleCoverage", "(FZ)V", ref global::javax.microedition.khronos.opengles.GL10_._m99, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m100;
void javax.microedition.khronos.opengles.GL10.glSampleCoveragex(int arg0, bool arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glSampleCoveragex", "(IZ)V", ref global::javax.microedition.khronos.opengles.GL10_._m100, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m101;
void javax.microedition.khronos.opengles.GL10.glScalef(float arg0, float arg1, float arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glScalef", "(FFF)V", ref global::javax.microedition.khronos.opengles.GL10_._m101, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m102;
void javax.microedition.khronos.opengles.GL10.glScalex(int arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glScalex", "(III)V", ref global::javax.microedition.khronos.opengles.GL10_._m102, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m103;
void javax.microedition.khronos.opengles.GL10.glScissor(int arg0, int arg1, int arg2, int arg3)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glScissor", "(IIII)V", ref global::javax.microedition.khronos.opengles.GL10_._m103, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
private static global::MonoJavaBridge.MethodId _m104;
void javax.microedition.khronos.opengles.GL10.glShadeModel(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glShadeModel", "(I)V", ref global::javax.microedition.khronos.opengles.GL10_._m104, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m105;
void javax.microedition.khronos.opengles.GL10.glStencilFunc(int arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glStencilFunc", "(III)V", ref global::javax.microedition.khronos.opengles.GL10_._m105, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m106;
void javax.microedition.khronos.opengles.GL10.glStencilMask(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glStencilMask", "(I)V", ref global::javax.microedition.khronos.opengles.GL10_._m106, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m107;
void javax.microedition.khronos.opengles.GL10.glStencilOp(int arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glStencilOp", "(III)V", ref global::javax.microedition.khronos.opengles.GL10_._m107, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m108;
void javax.microedition.khronos.opengles.GL10.glTexCoordPointer(int arg0, int arg1, int arg2, java.nio.Buffer arg3)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glTexCoordPointer", "(IIILjava/nio/Buffer;)V", ref global::javax.microedition.khronos.opengles.GL10_._m108, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
private static global::MonoJavaBridge.MethodId _m109;
void javax.microedition.khronos.opengles.GL10.glTexEnvf(int arg0, int arg1, float arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glTexEnvf", "(IIF)V", ref global::javax.microedition.khronos.opengles.GL10_._m109, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m110;
void javax.microedition.khronos.opengles.GL10.glTexEnvfv(int arg0, int arg1, float[] arg2, int arg3)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glTexEnvfv", "(II[FI)V", ref global::javax.microedition.khronos.opengles.GL10_._m110, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
private static global::MonoJavaBridge.MethodId _m111;
void javax.microedition.khronos.opengles.GL10.glTexEnvfv(int arg0, int arg1, java.nio.FloatBuffer arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glTexEnvfv", "(IILjava/nio/FloatBuffer;)V", ref global::javax.microedition.khronos.opengles.GL10_._m111, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m112;
void javax.microedition.khronos.opengles.GL10.glTexEnvx(int arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glTexEnvx", "(III)V", ref global::javax.microedition.khronos.opengles.GL10_._m112, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m113;
void javax.microedition.khronos.opengles.GL10.glTexEnvxv(int arg0, int arg1, int[] arg2, int arg3)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glTexEnvxv", "(II[II)V", ref global::javax.microedition.khronos.opengles.GL10_._m113, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
private static global::MonoJavaBridge.MethodId _m114;
void javax.microedition.khronos.opengles.GL10.glTexEnvxv(int arg0, int arg1, java.nio.IntBuffer arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glTexEnvxv", "(IILjava/nio/IntBuffer;)V", ref global::javax.microedition.khronos.opengles.GL10_._m114, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m115;
void javax.microedition.khronos.opengles.GL10.glTexImage2D(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, java.nio.Buffer arg8)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glTexImage2D", "(IIIIIIIILjava/nio/Buffer;)V", ref global::javax.microedition.khronos.opengles.GL10_._m115, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg7), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg8));
}
private static global::MonoJavaBridge.MethodId _m116;
void javax.microedition.khronos.opengles.GL10.glTexParameterf(int arg0, int arg1, float arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glTexParameterf", "(IIF)V", ref global::javax.microedition.khronos.opengles.GL10_._m116, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m117;
void javax.microedition.khronos.opengles.GL10.glTexParameterx(int arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glTexParameterx", "(III)V", ref global::javax.microedition.khronos.opengles.GL10_._m117, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m118;
void javax.microedition.khronos.opengles.GL10.glTexSubImage2D(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, java.nio.Buffer arg8)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glTexSubImage2D", "(IIIIIIIILjava/nio/Buffer;)V", ref global::javax.microedition.khronos.opengles.GL10_._m118, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg7), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg8));
}
private static global::MonoJavaBridge.MethodId _m119;
void javax.microedition.khronos.opengles.GL10.glTranslatef(float arg0, float arg1, float arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glTranslatef", "(FFF)V", ref global::javax.microedition.khronos.opengles.GL10_._m119, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m120;
void javax.microedition.khronos.opengles.GL10.glTranslatex(int arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glTranslatex", "(III)V", ref global::javax.microedition.khronos.opengles.GL10_._m120, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m121;
void javax.microedition.khronos.opengles.GL10.glVertexPointer(int arg0, int arg1, int arg2, java.nio.Buffer arg3)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glVertexPointer", "(IIILjava/nio/Buffer;)V", ref global::javax.microedition.khronos.opengles.GL10_._m121, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
private static global::MonoJavaBridge.MethodId _m122;
void javax.microedition.khronos.opengles.GL10.glViewport(int arg0, int arg1, int arg2, int arg3)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.microedition.khronos.opengles.GL10_.staticClass, "glViewport", "(IIII)V", ref global::javax.microedition.khronos.opengles.GL10_._m122, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
static GL10_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::javax.microedition.khronos.opengles.GL10_.staticClass = @__env.NewGlobalRef(@__env.FindClass("javax/microedition/khronos/opengles/GL10"));
}
}
}
| |
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
namespace UnityEditor.Experimental.Rendering.HDPipeline
{
class TerrainLitGUI : LitGUI, ITerrainLayerCustomUI
{
protected override uint defaultExpandedState { get { return (uint)(Expandable.Input | Expandable.Other | Expandable.Advance); } }
private class StylesLayer
{
public readonly string terrainText = "Terrain";
public readonly GUIContent enableHeightBlend = new GUIContent("Enable Height-based Blend", "Blend terrain layers based on height values.");
public readonly GUIContent heightTransition = new GUIContent("Height Transition", "Size in world units of the smooth transition between layers.");
public readonly GUIContent enableInstancedPerPixelNormal = new GUIContent("Enable Per-pixel Normal", "Enable per-pixel normal when the terrain uses instanced rendering.");
public readonly GUIContent diffuseTexture = new GUIContent("Diffuse");
public readonly GUIContent colorTint = new GUIContent("Color Tint");
public readonly GUIContent opacityAsDensity = new GUIContent("Opacity as Density", "Enable Density Blend");
public readonly GUIContent normalMapTexture = new GUIContent("Normal Map");
public readonly GUIContent normalScale = new GUIContent("Normal Scale");
public readonly GUIContent maskMapTexture = new GUIContent("Mask", "R: Metallic\nG: Ambient Occlusion\nB: Height\nA: Smoothness.");
public readonly GUIContent maskMapTextureWithoutHeight = new GUIContent("Mask Map", "R: Metallic\nG: Ambient Occlusion\nA: Smoothness.");
public readonly GUIContent channelRemapping = new GUIContent("Channel Remapping");
public readonly GUIContent defaultValues = new GUIContent("Channel Default Values");
public readonly GUIContent metallic = new GUIContent("R: Metallic");
public readonly GUIContent ao = new GUIContent("G: AO");
public readonly GUIContent height = new GUIContent("B: Height");
public readonly GUIContent heightParametrization = new GUIContent("Parametrization");
public readonly GUIContent heightAmplitude = new GUIContent("Amplitude (cm)");
public readonly GUIContent heightBase = new GUIContent("Base");
public readonly GUIContent heightMin = new GUIContent("Min (cm)");
public readonly GUIContent heightMax = new GUIContent("Max (cm)");
public readonly GUIContent heightCm = new GUIContent("B: Height (cm)");
public readonly GUIContent smoothness = new GUIContent("A: Smoothness");
}
static StylesLayer s_Styles = null;
private static StylesLayer styles { get { if (s_Styles == null) s_Styles = new StylesLayer(); return s_Styles; } }
public TerrainLitGUI()
{
}
MaterialProperty enableHeightBlend;
const string kEnableHeightBlend = "_EnableHeightBlend";
// Height blend
MaterialProperty heightTransition = null;
const string kHeightTransition = "_HeightTransition";
MaterialProperty enableInstancedPerPixelNormal = null;
const string kEnableInstancedPerPixelNormal = "_EnableInstancedPerPixelNormal";
// Custom fields
List<MaterialProperty> customProperties = new List<MaterialProperty>();
protected override void FindMaterialProperties(MaterialProperty[] props)
{
customProperties.Clear();
foreach (var prop in props)
{
if (prop.name == kEnableHeightBlend)
enableHeightBlend = prop;
else if (prop.name == kHeightTransition)
heightTransition = prop;
else if (prop.name == kEnableInstancedPerPixelNormal)
enableInstancedPerPixelNormal = prop;
else if ((prop.flags & (MaterialProperty.PropFlags.HideInInspector | MaterialProperty.PropFlags.PerRendererData)) == 0)
customProperties.Add(prop);
}
}
protected override bool ShouldEmissionBeEnabled(Material mat)
{
return false;
}
protected override void SetupMaterialKeywordsAndPassInternal(Material material)
{
SetupMaterialKeywordsAndPass(material);
}
static public void SetupLayersMappingKeywords(Material material)
{
const string kLayerMappingPlanar = "_LAYER_MAPPING_PLANAR";
const string kLayerMappingTriplanar = "_LAYER_MAPPING_TRIPLANAR";
for (int i = 0; i < kMaxLayerCount; ++i)
{
string layerUVBaseParam = string.Format("{0}{1}", kUVBase, i);
UVBaseMapping layerUVBaseMapping = (UVBaseMapping)material.GetFloat(layerUVBaseParam);
string currentLayerMappingPlanar = string.Format("{0}{1}", kLayerMappingPlanar, i);
CoreUtils.SetKeyword(material, currentLayerMappingPlanar, layerUVBaseMapping == UVBaseMapping.Planar);
string currentLayerMappingTriplanar = string.Format("{0}{1}", kLayerMappingTriplanar, i);
CoreUtils.SetKeyword(material, currentLayerMappingTriplanar, layerUVBaseMapping == UVBaseMapping.Triplanar);
}
}
// All Setup Keyword functions must be static. It allow to create script to automatically update the shaders with a script if code change
static new public void SetupMaterialKeywordsAndPass(Material material)
{
SetupBaseLitKeywords(material);
SetupBaseLitMaterialPass(material);
// TODO: planar/triplannar supprt
//SetupLayersMappingKeywords(material);
bool enableHeightBlend = material.HasProperty(kEnableHeightBlend) && material.GetFloat(kEnableHeightBlend) > 0;
CoreUtils.SetKeyword(material, "_TERRAIN_BLEND_HEIGHT", enableHeightBlend);
bool enableInstancedPerPixelNormal = material.GetFloat(kEnableInstancedPerPixelNormal) > 0.0f;
CoreUtils.SetKeyword(material, "_TERRAIN_INSTANCED_PERPIXEL_NORMAL", enableInstancedPerPixelNormal);
}
protected override void MaterialPropertiesGUI(Material material)
{
// Don't draw the header if we have empty content
if (enableHeightBlend == null && enableInstancedPerPixelNormal == null && customProperties.Count == 0)
return;
using (var header = new HeaderScope(styles.terrainText, (uint)Expandable.Other, this))
{
if (header.expanded)
{
if (enableHeightBlend != null)
{
m_MaterialEditor.ShaderProperty(enableHeightBlend, styles.enableHeightBlend);
if (enableHeightBlend.floatValue > 0)
{
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(heightTransition, styles.heightTransition);
EditorGUI.indentLevel--;
}
}
if (enableInstancedPerPixelNormal != null)
{
EditorGUI.BeginDisabledGroup(!m_MaterialEditor.IsInstancingEnabled());
m_MaterialEditor.ShaderProperty(enableInstancedPerPixelNormal, styles.enableInstancedPerPixelNormal);
EditorGUI.EndDisabledGroup();
}
foreach (var prop in customProperties)
m_MaterialEditor.ShaderProperty(prop, prop.displayName);
}
}
}
protected override void MaterialPropertiesAdvanceGUI(Material material)
{
// do nothing
}
private bool m_ShowChannelRemapping = false;
enum HeightParametrization
{
Amplitude,
MinMax
};
private HeightParametrization m_HeightParametrization = HeightParametrization.Amplitude;
private static bool DoesTerrainUseMaskMaps(TerrainLayer[] terrainLayers)
{
for (int i = 0; i < terrainLayers.Length; ++i)
{
if (terrainLayers[i].maskMapTexture != null)
return true;
}
return false;
}
bool ITerrainLayerCustomUI.OnTerrainLayerGUI(TerrainLayer terrainLayer, Terrain terrain)
{
var terrainLayers = terrain.terrainData.terrainLayers;
if (!DoesTerrainUseMaskMaps(terrainLayers))
return false;
// Don't use the member field enableHeightBlend as ShaderGUI.OnGUI might not be called if the material UI is folded.
bool heightBlend = terrain.materialTemplate.HasProperty(kEnableHeightBlend) && terrain.materialTemplate.GetFloat(kEnableHeightBlend) > 0;
terrainLayer.diffuseTexture = EditorGUILayout.ObjectField(styles.diffuseTexture, terrainLayer.diffuseTexture, typeof(Texture2D), false) as Texture2D;
TerrainLayerUtility.ValidateDiffuseTextureUI(terrainLayer.diffuseTexture);
var diffuseRemapMin = terrainLayer.diffuseRemapMin;
var diffuseRemapMax = terrainLayer.diffuseRemapMax;
EditorGUI.BeginChangeCheck();
bool enableDensity = false;
if (terrainLayer.diffuseTexture != null)
{
var rect = GUILayoutUtility.GetLastRect();
rect.y += 16 + 4;
rect.width = EditorGUIUtility.labelWidth + 64;
rect.height = 16;
++EditorGUI.indentLevel;
var diffuseTint = new Color(diffuseRemapMax.x, diffuseRemapMax.y, diffuseRemapMax.z);
diffuseTint = EditorGUI.ColorField(rect, styles.colorTint, diffuseTint, true, false, false);
diffuseRemapMax.x = diffuseTint.r;
diffuseRemapMax.y = diffuseTint.g;
diffuseRemapMax.z = diffuseTint.b;
diffuseRemapMin.x = diffuseRemapMin.y = diffuseRemapMin.z = 0;
if (!heightBlend)
{
rect.y = rect.yMax + 2;
enableDensity = EditorGUI.Toggle(rect, styles.opacityAsDensity, diffuseRemapMin.w > 0);
}
--EditorGUI.indentLevel;
}
diffuseRemapMax.w = 1;
diffuseRemapMin.w = enableDensity ? 1 : 0;
if (EditorGUI.EndChangeCheck())
{
terrainLayer.diffuseRemapMin = diffuseRemapMin;
terrainLayer.diffuseRemapMax = diffuseRemapMax;
}
terrainLayer.normalMapTexture = EditorGUILayout.ObjectField(styles.normalMapTexture, terrainLayer.normalMapTexture, typeof(Texture2D), false) as Texture2D;
TerrainLayerUtility.ValidateNormalMapTextureUI(terrainLayer.normalMapTexture, TerrainLayerUtility.CheckNormalMapTextureType(terrainLayer.normalMapTexture));
if (terrainLayer.normalMapTexture != null)
{
var rect = GUILayoutUtility.GetLastRect();
rect.y += 16 + 4;
rect.width = EditorGUIUtility.labelWidth + 64;
rect.height = 16;
++EditorGUI.indentLevel;
terrainLayer.normalScale = EditorGUI.FloatField(rect, styles.normalScale, terrainLayer.normalScale);
--EditorGUI.indentLevel;
}
terrainLayer.maskMapTexture = EditorGUILayout.ObjectField(heightBlend ? styles.maskMapTexture : styles.maskMapTextureWithoutHeight, terrainLayer.maskMapTexture, typeof(Texture2D), false) as Texture2D;
TerrainLayerUtility.ValidateMaskMapTextureUI(terrainLayer.maskMapTexture);
var maskMapRemapMin = terrainLayer.maskMapRemapMin;
var maskMapRemapMax = terrainLayer.maskMapRemapMax;
++EditorGUI.indentLevel;
EditorGUI.BeginChangeCheck();
m_ShowChannelRemapping = EditorGUILayout.Foldout(m_ShowChannelRemapping, terrainLayer.maskMapTexture != null ? s_Styles.channelRemapping : s_Styles.defaultValues);
if (m_ShowChannelRemapping)
{
if (terrainLayer.maskMapTexture != null)
{
float min, max;
min = maskMapRemapMin.x; max = maskMapRemapMax.x;
EditorGUILayout.MinMaxSlider(s_Styles.metallic, ref min, ref max, 0, 1);
maskMapRemapMin.x = min; maskMapRemapMax.x = max;
min = maskMapRemapMin.y; max = maskMapRemapMax.y;
EditorGUILayout.MinMaxSlider(s_Styles.ao, ref min, ref max, 0, 1);
maskMapRemapMin.y = min; maskMapRemapMax.y = max;
if (heightBlend)
{
EditorGUILayout.LabelField(styles.height);
++EditorGUI.indentLevel;
m_HeightParametrization = (HeightParametrization)EditorGUILayout.EnumPopup(styles.heightParametrization, m_HeightParametrization);
if (m_HeightParametrization == HeightParametrization.Amplitude)
{
// (height - heightBase) * amplitude
float amplitude = Mathf.Max(maskMapRemapMax.z - maskMapRemapMin.z, Mathf.Epsilon); // to avoid divide by zero
float heightBase = -maskMapRemapMin.z / amplitude;
amplitude = EditorGUILayout.FloatField(styles.heightAmplitude, amplitude * 100) / 100;
heightBase = EditorGUILayout.FloatField(styles.heightBase, heightBase);
maskMapRemapMin.z = -heightBase * amplitude;
maskMapRemapMax.z = (1 - heightBase) * amplitude;
}
else
{
maskMapRemapMin.z = EditorGUILayout.FloatField(styles.heightMin, maskMapRemapMin.z * 100) / 100;
maskMapRemapMax.z = EditorGUILayout.FloatField(styles.heightMax, maskMapRemapMax.z * 100) / 100;
}
--EditorGUI.indentLevel;
}
min = maskMapRemapMin.w; max = maskMapRemapMax.w;
EditorGUILayout.MinMaxSlider(s_Styles.smoothness, ref min, ref max, 0, 1);
maskMapRemapMin.w = min; maskMapRemapMax.w = max;
}
else
{
maskMapRemapMin.x = maskMapRemapMax.x = EditorGUILayout.Slider(s_Styles.metallic, maskMapRemapMin.x, 0, 1);
maskMapRemapMin.y = maskMapRemapMax.y = EditorGUILayout.Slider(s_Styles.ao, maskMapRemapMin.y, 0, 1);
if (heightBlend)
maskMapRemapMin.z = maskMapRemapMax.z = EditorGUILayout.FloatField(s_Styles.heightCm, maskMapRemapMin.z * 100) / 100;
maskMapRemapMin.w = maskMapRemapMax.w = EditorGUILayout.Slider(s_Styles.smoothness, maskMapRemapMin.w, 0, 1);
}
}
if (EditorGUI.EndChangeCheck())
{
terrainLayer.maskMapRemapMin = maskMapRemapMin;
terrainLayer.maskMapRemapMax = maskMapRemapMax;
}
--EditorGUI.indentLevel;
EditorGUILayout.Space();
TerrainLayerUtility.TilingSettingsUI(terrainLayer);
return true;
}
}
} // namespace UnityEditor
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Alerts.Alerts
File: AlertSettingsPanel.xaml.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Alerts
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using Ecng.Collections;
using Ecng.Common;
using Ecng.ComponentModel;
using Ecng.Reflection;
using StockSharp.Localization;
/// <summary>
/// Panel schema parameter modification.
/// </summary>
public partial class AlertSettingsPanel
{
private static readonly Tuple<string, PropertyInfo> _nullField = new Tuple<string, PropertyInfo>(LocalizedStrings.Select, null);
private readonly ObservableCollection<ComparisonOperator> _operators = new ObservableCollection<ComparisonOperator>();
private readonly ObservableCollection<Tuple<string, PropertyInfo>> _fields;
private static readonly HashSet<string> _ignoringFields = new HashSet<string>
{
"ExtensionInfo", "Type", "OriginalTransactionId"
};
/// <summary>
/// Initializes a new instance of the <see cref="AlertSettingsPanel"/>.
/// </summary>
public AlertSettingsPanel()
{
InitializeComponent();
OperatorCtrl.ItemsSource = _operators;
_fields = new ObservableCollection<Tuple<string, PropertyInfo>> { _nullField };
PropertyCtrl.ItemsSource = _fields;
PropertyCtrl.SelectedValue = _nullField;
}
/// <summary>
/// <see cref="DependencyProperty"/> for <see cref="AlertSettingsPanel.MessageType"/>.
/// </summary>
public static readonly DependencyProperty MessageTypeProperty =
DependencyProperty.Register(nameof(MessageType), typeof(Type), typeof(AlertSettingsPanel), new PropertyMetadata(null, MessageTypeChanged));
private static void MessageTypeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((AlertSettingsPanel)d).MessageType = (Type)e.NewValue;
}
/// <summary>
/// <see cref="DependencyProperty"/> for <see cref="AlertSettingsPanel.Property"/>.
/// </summary>
public static readonly DependencyProperty PropertyProperty =
DependencyProperty.Register(nameof(Property), typeof(PropertyInfo), typeof(AlertSettingsPanel), new PropertyMetadata(null, PropertyChanged));
private static void PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var ctrl = (AlertSettingsPanel)d;
var prop = (PropertyInfo)e.NewValue;
if (ctrl.MessageType == null)
ctrl.MessageType = prop.ReflectedType;
ctrl.PropertyCtrl.SelectedValue = prop == null ? _nullField : ctrl._fields.First(t => t.Item2 == prop);
}
/// <summary>
/// <see cref="DependencyProperty"/> for <see cref="AlertSettingsPanel.Operator"/>.
/// </summary>
public static readonly DependencyProperty OperatorProperty =
DependencyProperty.Register(nameof(Operator), typeof(ComparisonOperator?), typeof(AlertSettingsPanel), new PropertyMetadata(null, OperatorChanged));
private static void OperatorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((AlertSettingsPanel)d).OperatorCtrl.SelectedValue = (ComparisonOperator?)e.NewValue;
}
/// <summary>
/// <see cref="DependencyProperty"/> for <see cref="Value"/>.
/// </summary>
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register(nameof(Value), typeof(object), typeof(AlertSettingsPanel), new PropertyMetadata(null, ValueChanged));
private static void ValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var ctrl = (AlertSettingsPanel)d;
var value = e.NewValue;
if (ctrl.DecimalValue.Visibility == Visibility.Visible)
ctrl.DecimalValue.Value = (decimal?)value;
else if (ctrl.TextValue.Visibility == Visibility.Visible)
ctrl.TextValue.Text = (string)value;
else if (ctrl.TimeValue.Visibility == Visibility.Visible)
ctrl.TimeValue.Value = DateTime.Today + (TimeSpan?)value;
else if (ctrl.DateValue.Visibility == Visibility.Visible)
ctrl.DateValue.Value = (DateTime?)value;
//else if (ctrl.SecurityValue.Visibility == Visibility.Visible)
// ctrl.SecurityValue.SelectedSecurity = (Security)value;
//else if (ctrl.PortfolioValue.Visibility == Visibility.Visible)
// ctrl.PortfolioValue.SelectedPortfolio = (Portfolio)value;
else if (ctrl.EnumValue.Visibility == Visibility.Visible)
ctrl.EnumValue.SelectedValue = value;
}
private Type _messageType;
/// <summary>
/// Message type.
/// </summary>
public Type MessageType
{
get { return _messageType; }
set
{
_messageType = value;
_fields.AddRange(value
.GetMembers<PropertyInfo>(BindingFlags.Public | BindingFlags.Instance)
.Where(pi =>
{
if (_ignoringFields.Contains(pi.Name))
return false;
var ba = pi.GetAttribute<BrowsableAttribute>();
return ba == null || ba.Browsable;
})
.Select(pi =>
{
var nameAttr = pi.GetAttribute<DisplayNameAttribute>();
return Tuple.Create(nameAttr == null ? pi.Name : nameAttr.DisplayName, pi);
}));
}
}
/// <summary>
/// Message property, which will be made a comparison with the value of <see cref="AlertSettingsPanel.Value"/> based on the criterion <see cref="AlertSettingsPanel.Operator"/>.
/// </summary>
public PropertyInfo Property
{
get { return (PropertyInfo)GetValue(PropertyProperty); }
set { SetValue(PropertyProperty, value); }
}
/// <summary>
/// The criterion of comparison values <see cref="AlertSettingsPanel.Value"/>.
/// </summary>
public ComparisonOperator? Operator
{
get { return (ComparisonOperator?)GetValue(OperatorProperty); }
set { SetValue(OperatorProperty, value); }
}
/// <summary>
/// Comparison value.
/// </summary>
public object Value
{
get { return GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
private void PropertyCtrl_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selectedValue = (Tuple<string, PropertyInfo>)PropertyCtrl.SelectedItem;
if (selectedValue == null)
return;
var field = selectedValue.Equals(_nullField) ? null : selectedValue.Item2;
Property = field;
if (field == null)
{
OperatorCtrl.IsEnabled = false;
return;
}
_operators.Clear();
OperatorCtrl.IsEnabled = true;
var type = field.PropertyType;
if (type.IsNullable())
type = type.GetUnderlyingType();
EnumValue.Visibility = TimeValue.Visibility = DateValue.Visibility = DecimalValue.Visibility =
TextValue.Visibility = /*SecurityValue.Visibility = PortfolioValue.Visibility = */Visibility.Collapsed;
if (type == typeof(string) || type.IsEnum)// || typeof(Security).IsAssignableFrom(type) || typeof(Portfolio).IsAssignableFrom(type))
{
if (type == typeof(string))
TextValue.Visibility = Visibility.Visible;
//else if (typeof(Security).IsAssignableFrom(type))
// SecurityValue.Visibility = Visibility.Visible;
//else if (typeof(Portfolio).IsAssignableFrom(type))
// PortfolioValue.Visibility = Visibility.Visible;
else if (type.IsEnum)
{
EnumValue.Visibility = Visibility.Visible;
EnumValue.EnumType = type;
}
_operators.Add(ComparisonOperator.Equal);
_operators.Add(ComparisonOperator.NotEqual);
_operators.Add(ComparisonOperator.Any);
}
else if (
type == typeof(sbyte) || type == typeof(short) || type == typeof(int) || type == typeof(long) ||
type == typeof(byte) || type == typeof(ushort) || type == typeof(uint) || type == typeof(ulong) ||
type == typeof(decimal) || type == typeof(double) || type == typeof(float))
{
_operators.AddRange(Enumerator.GetValues<ComparisonOperator>());
DecimalValue.Visibility = Visibility.Visible;
}
else if (type == typeof(TimeSpan))
{
_operators.AddRange(Enumerator.GetValues<ComparisonOperator>());
TimeValue.Visibility = Visibility.Visible;
}
else if (type == typeof(DateTime))
{
_operators.AddRange(Enumerator.GetValues<ComparisonOperator>());
DateValue.Visibility = Visibility.Visible;
}
}
private void OperatorCtrl_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
Operator = (ComparisonOperator?)OperatorCtrl.SelectedItem;
switch (Operator)
{
case ComparisonOperator.Equal:
case ComparisonOperator.NotEqual:
case ComparisonOperator.Greater:
case ComparisonOperator.GreaterOrEqual:
case ComparisonOperator.Less:
case ComparisonOperator.LessOrEqual:
ValuePanel.Visibility = Visibility.Visible;
break;
case ComparisonOperator.Any:
case null:
ValuePanel.Visibility = Visibility.Collapsed;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
private void TextValue_OnTextChanged(object sender, TextChangedEventArgs e)
{
Value = TextValue.Text;
}
private void DecimalValue_OnValueChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
Value = DecimalValue.Value;
}
//private void PortfolioValue_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
//{
// Value = PortfolioValue.SelectedPortfolio;
//}
//private void SecurityValue_OnSecuritySelected()
//{
// Value = SecurityValue.SelectedSecurity;
//}
private void TimeValue_OnValueChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
Value = TimeValue.Value;
}
private void DateValue_OnValueChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
Value = DateValue.Value;
}
private void EnumValue_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
Value = EnumValue.SelectedItem;
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the SysZona class.
/// </summary>
[Serializable]
public partial class SysZonaCollection : ActiveList<SysZona, SysZonaCollection>
{
public SysZonaCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>SysZonaCollection</returns>
public SysZonaCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
SysZona o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the Sys_Zona table.
/// </summary>
[Serializable]
public partial class SysZona : ActiveRecord<SysZona>, IActiveRecord
{
#region .ctors and Default Settings
public SysZona()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public SysZona(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public SysZona(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public SysZona(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("Sys_Zona", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdZona = new TableSchema.TableColumn(schema);
colvarIdZona.ColumnName = "idZona";
colvarIdZona.DataType = DbType.Int32;
colvarIdZona.MaxLength = 0;
colvarIdZona.AutoIncrement = true;
colvarIdZona.IsNullable = false;
colvarIdZona.IsPrimaryKey = true;
colvarIdZona.IsForeignKey = false;
colvarIdZona.IsReadOnly = false;
colvarIdZona.DefaultSetting = @"";
colvarIdZona.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdZona);
TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema);
colvarNombre.ColumnName = "nombre";
colvarNombre.DataType = DbType.String;
colvarNombre.MaxLength = 50;
colvarNombre.AutoIncrement = false;
colvarNombre.IsNullable = false;
colvarNombre.IsPrimaryKey = false;
colvarNombre.IsForeignKey = false;
colvarNombre.IsReadOnly = false;
colvarNombre.DefaultSetting = @"";
colvarNombre.ForeignKeyTableName = "";
schema.Columns.Add(colvarNombre);
TableSchema.TableColumn colvarIdLocalidad = new TableSchema.TableColumn(schema);
colvarIdLocalidad.ColumnName = "idLocalidad";
colvarIdLocalidad.DataType = DbType.Int32;
colvarIdLocalidad.MaxLength = 0;
colvarIdLocalidad.AutoIncrement = false;
colvarIdLocalidad.IsNullable = false;
colvarIdLocalidad.IsPrimaryKey = false;
colvarIdLocalidad.IsForeignKey = false;
colvarIdLocalidad.IsReadOnly = false;
colvarIdLocalidad.DefaultSetting = @"";
colvarIdLocalidad.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdLocalidad);
TableSchema.TableColumn colvarResponsable = new TableSchema.TableColumn(schema);
colvarResponsable.ColumnName = "responsable";
colvarResponsable.DataType = DbType.String;
colvarResponsable.MaxLength = 100;
colvarResponsable.AutoIncrement = false;
colvarResponsable.IsNullable = false;
colvarResponsable.IsPrimaryKey = false;
colvarResponsable.IsForeignKey = false;
colvarResponsable.IsReadOnly = false;
colvarResponsable.DefaultSetting = @"";
colvarResponsable.ForeignKeyTableName = "";
schema.Columns.Add(colvarResponsable);
TableSchema.TableColumn colvarZona = new TableSchema.TableColumn(schema);
colvarZona.ColumnName = "Zona";
colvarZona.DataType = DbType.String;
colvarZona.MaxLength = 3;
colvarZona.AutoIncrement = false;
colvarZona.IsNullable = true;
colvarZona.IsPrimaryKey = false;
colvarZona.IsForeignKey = false;
colvarZona.IsReadOnly = false;
colvarZona.DefaultSetting = @"";
colvarZona.ForeignKeyTableName = "";
schema.Columns.Add(colvarZona);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("Sys_Zona",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdZona")]
[Bindable(true)]
public int IdZona
{
get { return GetColumnValue<int>(Columns.IdZona); }
set { SetColumnValue(Columns.IdZona, value); }
}
[XmlAttribute("Nombre")]
[Bindable(true)]
public string Nombre
{
get { return GetColumnValue<string>(Columns.Nombre); }
set { SetColumnValue(Columns.Nombre, value); }
}
[XmlAttribute("IdLocalidad")]
[Bindable(true)]
public int IdLocalidad
{
get { return GetColumnValue<int>(Columns.IdLocalidad); }
set { SetColumnValue(Columns.IdLocalidad, value); }
}
[XmlAttribute("Responsable")]
[Bindable(true)]
public string Responsable
{
get { return GetColumnValue<string>(Columns.Responsable); }
set { SetColumnValue(Columns.Responsable, value); }
}
[XmlAttribute("Zona")]
[Bindable(true)]
public string Zona
{
get { return GetColumnValue<string>(Columns.Zona); }
set { SetColumnValue(Columns.Zona, value); }
}
#endregion
#region PrimaryKey Methods
protected override void SetPrimaryKey(object oValue)
{
base.SetPrimaryKey(oValue);
SetPKValues();
}
private DalSic.SysEfectorCollection colSysEfectorRecords;
public DalSic.SysEfectorCollection SysEfectorRecords
{
get
{
if(colSysEfectorRecords == null)
{
colSysEfectorRecords = new DalSic.SysEfectorCollection().Where(SysEfector.Columns.IdZona, IdZona).Load();
colSysEfectorRecords.ListChanged += new ListChangedEventHandler(colSysEfectorRecords_ListChanged);
}
return colSysEfectorRecords;
}
set
{
colSysEfectorRecords = value;
colSysEfectorRecords.ListChanged += new ListChangedEventHandler(colSysEfectorRecords_ListChanged);
}
}
void colSysEfectorRecords_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colSysEfectorRecords[e.NewIndex].IdZona = IdZona;
}
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varNombre,int varIdLocalidad,string varResponsable,string varZona)
{
SysZona item = new SysZona();
item.Nombre = varNombre;
item.IdLocalidad = varIdLocalidad;
item.Responsable = varResponsable;
item.Zona = varZona;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdZona,string varNombre,int varIdLocalidad,string varResponsable,string varZona)
{
SysZona item = new SysZona();
item.IdZona = varIdZona;
item.Nombre = varNombre;
item.IdLocalidad = varIdLocalidad;
item.Responsable = varResponsable;
item.Zona = varZona;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdZonaColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn NombreColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn IdLocalidadColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn ResponsableColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn ZonaColumn
{
get { return Schema.Columns[4]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdZona = @"idZona";
public static string Nombre = @"nombre";
public static string IdLocalidad = @"idLocalidad";
public static string Responsable = @"responsable";
public static string Zona = @"Zona";
}
#endregion
#region Update PK Collections
public void SetPKValues()
{
if (colSysEfectorRecords != null)
{
foreach (DalSic.SysEfector item in colSysEfectorRecords)
{
if (item.IdZona != IdZona)
{
item.IdZona = IdZona;
}
}
}
}
#endregion
#region Deep Save
public void DeepSave()
{
Save();
if (colSysEfectorRecords != null)
{
colSysEfectorRecords.SaveAll();
}
}
#endregion
}
}
| |
using System;
namespace QuickCheck.Random
{
public static class RandomDistribution
{
/// <summary>
/// Generate a normally distributed <see cref="double"/> with
/// mean 0 and standard deviation 1.
/// </summary>
public static double Normal(this IRandom random)
{
// Use Box-Muller algorithm
double u1 = random.Double();
double u2 = random.Double();
double r = Math.Sqrt(-2.0 * Math.Log(u1));
double theta = 2.0 * Math.PI * u2;
return r * Math.Sin(theta);
}
/// <summary>
/// Generate a normally distributed <see cref="double"/>.
/// </summary>
public static double Normal(this IRandom random, double mean, double standardDeviation)
{
if (standardDeviation <= 0.0)
{
throw new ArgumentOutOfRangeException(
"standardDeviation", standardDeviation, "Standard deviation must be positive.");
}
return mean + standardDeviation * random.Normal();
}
/// <summary>
/// Generate an exponentially distributed <see cref="double"/> with mean 1.
/// </summary>
public static double Exponential(this IRandom random)
{
return -Math.Log(random.Double());
}
/// <summary>
/// Generate a exponentially distributed <see cref="double"/>.
/// </summary>
public static double Exponential(this IRandom random, double mean)
{
if (mean <= 0.0)
{
throw new ArgumentOutOfRangeException(
"mean", mean, "Mean must be positive.");
}
return mean * random.Exponential();
}
/// <summary>
/// Generate a gamma distributed <see cref="double"/>.
/// </summary>
public static double Gamma(this IRandom random, double shape, double scale)
{
// Implementation based on "A Simple Method for Generating Gamma Variables"
// by George Marsaglia and Wai Wan Tsang. ACM Transactions on Mathematical Software
// Vol 26, No 3, September 2000, pages 363-372.
if (shape >= 1.0)
{
double d = shape - 1.0 / 3.0;
double c = 1.0 / Math.Sqrt(9.0 * d);
for (;;)
{
double v;
double x;
do
{
x = random.Normal();
v = 1.0 + c * x;
} while (v <= 0.0);
v = v * v * v;
double u = random.Double();
double xsquared = x * x;
if (u < 1.0 - .0331 * xsquared * xsquared ||
Math.Log(u) < 0.5 * xsquared + d * (1.0 - v + Math.Log(v)))
{
return scale * d * v;
}
}
}
if (shape <= 0.0)
{
throw new ArgumentOutOfRangeException(
"shape", shape, "Shape must be positive.");
}
double g = random.Gamma(shape + 1.0, 1.0);
double w = random.Double();
return scale * g * Math.Pow(w, 1.0 / shape);
}
/// <summary>
/// Generate a chi-squared distributed <see cref="double"/>.
/// </summary>
public static double ChiSquared(this IRandom random, double degreesOfFreedom)
{
// A chi squared distribution with n degrees of freedom
// is a gamma distribution with shape n/2 and scale 2.
return random.Gamma(0.5 * degreesOfFreedom, 2.0);
}
/// <summary>
/// Generate an inverse-gamma distributed <see cref="double"/>.
/// </summary>
public static double InverseGamma(this IRandom random, double shape, double scale)
{
// If X is gamma(shape, scale) then
// 1/Y is inverse gamma(shape, 1/scale)
return 1.0 / random.Gamma(shape, 1.0 / scale);
}
/// <summary>
/// Generate Weibull distributed <see cref="double"/>.
/// </summary>
public static double Weibull(this IRandom random, double shape, double scale)
{
if (shape <= 0.0)
{
throw new ArgumentOutOfRangeException(
"shape", shape, "Shape must be positive.");
}
if (shape <= 0.0 || scale <= 0.0)
{
throw new ArgumentOutOfRangeException(
"scale", scale, "Scale must be positive.");
}
return scale * Math.Pow(-Math.Log(random.Double()), 1.0 / shape);
}
/// <summary>
/// Generate Cauchy distributed <see cref="double"/>.
/// </summary>
public static double Cauchy(this IRandom random, double median, double scale)
{
if (scale <= 0)
{
throw new ArgumentOutOfRangeException(
"scale", scale, "Scale must be positive.");
}
double p = random.Double();
// Apply inverse of the Cauchy distribution function to a uniform
return median + scale * Math.Tan(Math.PI * (p - 0.5));
}
/// <summary>
/// Generate a t-distributed <see cref="double"/>.
/// </summary>
public static double StudentT(this IRandom random, double degreesOfFreedom)
{
if (degreesOfFreedom <= 0)
{
throw new ArgumentOutOfRangeException(
"degreesOfFreedom", degreesOfFreedom, "Degrees of freedom must be positive.");
}
// See Seminumerical Algorithms by Knuth
double y1 = random.Normal();
double y2 = random.ChiSquared(degreesOfFreedom);
return y1 / Math.Sqrt(y2 / degreesOfFreedom);
}
/// <summary>
/// Generate a Laplace distributed <see cref="double"/>.
/// </summary>
public static double Laplace(this IRandom random, double mean, double scale)
{
double u = random.Double();
return (u < 0.5)
? mean + scale * Math.Log(2.0 * u)
: mean - scale * Math.Log(2 * (1 - u));
}
/// <summary>
/// Generate a log-normally distributed <see cref="double"/>.
/// </summary>
public static double LogNormal(this IRandom random, double mu, double sigma)
{
return Math.Exp(random.Normal(mu, sigma));
}
/// <summary>
/// Generate a beta distributed <see cref="double"/>.
/// </summary>
public static double Beta(this IRandom random, double a, double b)
{
if (a <= 0)
{
throw new ArgumentOutOfRangeException(
"a", a, "Beta parameters must be positive.");
}
if (b <= 0)
{
throw new ArgumentOutOfRangeException(
"b", b, "Beta parameters must be positive.");
}
// There are more efficient methods for generating beta samples.
// However such methods are a little more efficient and much more complicated.
// For an explanation of why the following method works, see
// http://www.johndcook.com/distribution_chart.html#gamma_beta
double u = random.Gamma(a, 1.0);
double v = random.Gamma(b, 1.0);
return u / (u + v);
}
}
}
| |
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Debugger.Common;
using Debugger.SbDebuggerRpc;
using Grpc.Core;
using LldbApi;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;
using YetiVSI.DebugEngine;
namespace DebuggerGrpcServer
{
/// <summary>
/// Server implementation of the SBDebugger RPC.
/// </summary>
class SbDebuggerRpcServiceImpl : SbDebuggerRpcService.SbDebuggerRpcServiceBase,
SbDebuggerService, SbDebuggerManager
{
readonly LLDBDebuggerFactory sbDebuggerFactory;
readonly RemoteTargetFactory remoteTargetFactory;
readonly object thisLock = new object();
SbDebugger sbDebugger = null;
ConcurrentDictionary<long, RemoteTarget> targetStore;
readonly ObjectStore<SbCommandInterpreter> interpreterStore;
SbPlatformManager sbPlatformManager;
public SbDebuggerRpcServiceImpl(ConcurrentDictionary<long, RemoteTarget> targetStore,
ObjectStore<SbCommandInterpreter> interpreterStore)
: this(targetStore, interpreterStore, new LLDBDebuggerFactory(),
new RemoteTargetFactory(new RemoteBreakpointFactory())) {}
/// <summary>
/// Constructor that can be used by tests to pass in mock objects.
/// </summary>
public SbDebuggerRpcServiceImpl(ConcurrentDictionary<long, RemoteTarget> targetStore,
ObjectStore<SbCommandInterpreter> interpreterStore,
LLDBDebuggerFactory sbDebuggerFactory, RemoteTargetFactory remoteTargetFactory)
{
this.targetStore = targetStore;
this.interpreterStore = interpreterStore;
this.sbDebuggerFactory = sbDebuggerFactory;
this.remoteTargetFactory = remoteTargetFactory;
}
#region SbDebuggerService
public void Initialize(SbPlatformManager sbPlatformManager)
{
this.sbPlatformManager = sbPlatformManager;
}
#endregion
#region SbDebuggerManager
public SbDebugger GetDebugger()
{
lock(thisLock)
{
return sbDebugger;
}
}
#endregion
#region SbDebuggerRpcService.SbDebuggerRpcServiceBase
/// <summary>
/// Create a new LLDB SBDebugger object locally. This SBDebugger object is then used for
/// all subsecent requests.
/// </summary>
public override Task<CreateResponse> Create(CreateRequest request,
ServerCallContext context)
{
// Lock around sbDebugger.
lock (thisLock)
{
// We only support creating one SBDebugger object, fail if there is an attempt to
// create more.
if (sbDebugger != null)
{
ErrorUtils.ThrowError(StatusCode.FailedPrecondition,
"Creating multiple SBDebugger objects is not supported.");
}
sbDebugger = sbDebuggerFactory.Create(request.SourceInitFiles);
if (sbDebugger == null)
{
ErrorUtils.ThrowError(StatusCode.Internal, "Could not create SBDebugger.");
}
return Task.FromResult(new CreateResponse());
}
}
/// <summary>
/// Set async execution for the command interpreter.
/// </summary>
public override Task<SkipLLDBInitFilesResponse> SkipLLDBInitFiles(
SkipLLDBInitFilesRequest request,
ServerCallContext context)
{
SbDebuggerPreconditionCheck();
sbDebugger.SkipLLDBInitFiles(request.Skip);
return Task.FromResult(new SkipLLDBInitFilesResponse());
}
public override Task<SetAsyncResponse> SetAsync(SetAsyncRequest request,
ServerCallContext context)
{
SbDebuggerPreconditionCheck();
sbDebugger.SetAsync(request.Async);
return Task.FromResult(new SetAsyncResponse());
}
public override Task<GetCommandInterpreterResponse> GetCommandInterpreter(
GetCommandInterpreterRequest request,
ServerCallContext context)
{
SbDebuggerPreconditionCheck();
SbCommandInterpreter interpreter = sbDebugger.GetCommandInterpreter();
if (interpreter == null) {
return Task.FromResult(new GetCommandInterpreterResponse());
}
var response = new GetCommandInterpreterResponse()
{
Interpreter = new GrpcSbCommandInterpreter {
Id = interpreterStore.AddObject(interpreter)
}
};
return Task.FromResult(response);
}
/// <summary>
/// Create a new LLDB SBTarget locally, and return a GrpcSbTarget object to the client.
/// Locally we then map GrpcSbTarget objects to RemoteTarget objects.
/// </summary>
public override Task<CreateTargetResponse> CreateTarget(CreateTargetRequest request,
ServerCallContext context)
{
SbDebuggerPreconditionCheck();
SbTarget sbTarget = sbDebugger.CreateTarget(request.Filename);
if (sbTarget == null)
{
ErrorUtils.ThrowError(StatusCode.Internal, "Could not create SBTarget.");
}
if (!targetStore.TryAdd(sbTarget.GetId(), remoteTargetFactory.Create(sbTarget)))
{
ErrorUtils.ThrowError(
StatusCode.Internal, "Could not add target to store: " + sbTarget.GetId());
}
var grpcSbTarget = new GrpcSbTarget { Id = sbTarget.GetId() };
var response = new CreateTargetResponse { GrpcSbTarget = grpcSbTarget };
return Task.FromResult(response);
}
/// <summary>
/// Set the selected platform.
/// </summary>
public override Task<SetSelectedPlatformResponse> SetSelectedPlatform(
SetSelectedPlatformRequest request, ServerCallContext context)
{
SbDebuggerPreconditionCheck();
// We currently only support one platform, so get it from the manager instead of the
// request.
SbPlatform sbPlatform = sbPlatformManager.GetPlatform();
if (sbPlatform == null)
{
ErrorUtils.ThrowError(StatusCode.NotFound,
"Could not find SBPlatform, make sure one has been created.");
}
sbDebugger.SetSelectedPlatform(sbPlatform);
return Task.FromResult(new SetSelectedPlatformResponse());
}
/// <summary>
/// Gets the currently selected platform.
/// </summary>
public override Task<GetSelectedPlatformResponse> GetSelectedPlatform(
GetSelectedPlatformRequest request, ServerCallContext context)
{
SbDebuggerPreconditionCheck();
// We currently only support one platform, so just return an empty response. Since
// for all platform APIs we assume it's the single instance we have created.
var response = new GetSelectedPlatformResponse();
return Task.FromResult(response);
}
/// <summary>
/// Enable LLDB internal logging. Takes a log channel and a list of log types.
/// </summary>
public override Task<EnableLogResponse> EnableLog(EnableLogRequest request,
ServerCallContext context)
{
SbDebuggerPreconditionCheck();
var result = sbDebugger.EnableLog(request.Channel, new List<string>(request.Types_));
var response = new EnableLogResponse { Result = result };
return Task.FromResult(response);
}
/// <summary>
/// Checks whether specified platform is available.
/// </summary>
public override Task<IsPlatformAvailableResponse> IsPlatformAvailable(
IsPlatformAvailableRequest request, ServerCallContext context)
{
SbDebuggerPreconditionCheck();
bool result = sbDebugger.IsPlatformAvailable(request.PlatformName);
var response = new IsPlatformAvailableResponse { Result = result };
return Task.FromResult(response);
}
#endregion
/// <summary>
/// Checks general preconditions for SBDebugger APIs.
/// </summary>
void SbDebuggerPreconditionCheck()
{
if (sbDebugger == null)
{
ErrorUtils.ThrowError(StatusCode.FailedPrecondition,
"Call 'Create' before calling any other API.");
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace FrontRangeSystems.WebTechnologies.Web.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Threading;
using System.Threading.Tasks;
using NuGet;
using NuGet.VisualStudio;
using NuGet.VisualStudio.Resources;
namespace NuGetConsole.Host.PowerShell.Implementation
{
internal abstract class PowerShellHost : IHost, IPathExpansion, IDisposable
{
private static readonly object _initScriptsLock = new object();
private readonly string _name;
private readonly IRunspaceManager _runspaceManager;
private readonly IVsPackageSourceProvider _packageSourceProvider;
private readonly ISolutionManager _solutionManager;
private IConsole _activeConsole;
private RunspaceDispatcher _runspace;
private NuGetPSHost _nugetHost;
// indicates whether this host has been initialized.
// null = not initilized, true = initialized successfully, false = initialized unsuccessfully
private bool? _initialized;
// store the current (non-truncated) project names displayed in the project name combobox
private string[] _projectSafeNames;
// store the current command typed so far
private ComplexCommand _complexCommand;
protected PowerShellHost(string name, IRunspaceManager runspaceManager)
{
_runspaceManager = runspaceManager;
// TODO: Take these as ctor arguments
_packageSourceProvider = ServiceLocator.GetInstance<IVsPackageSourceProvider>();
_solutionManager = ServiceLocator.GetInstance<ISolutionManager>();
_name = name;
IsCommandEnabled = true;
}
protected Pipeline ExecutingPipeline { get; set; }
/// <summary>
/// The host is associated with a particular console on a per-command basis.
/// This gets set every time a command is executed on this host.
/// </summary>
protected IConsole ActiveConsole
{
get
{
return _activeConsole;
}
set
{
_activeConsole = value;
if (_nugetHost != null)
{
_nugetHost.ActiveConsole = value;
}
}
}
public bool IsCommandEnabled
{
get;
private set;
}
protected RunspaceDispatcher Runspace
{
get
{
return _runspace;
}
}
private ComplexCommand ComplexCommand
{
get
{
if (_complexCommand == null)
{
_complexCommand = new ComplexCommand((allLines, lastLine) =>
{
Collection<PSParseError> errors;
PSParser.Tokenize(allLines, out errors);
// If there is a parse error token whose END is past input END, consider
// it a multi-line command.
if (errors.Count > 0)
{
if (errors.Any(e => (e.Token.Start + e.Token.Length) >= allLines.Length))
{
return false;
}
}
return true;
});
}
return _complexCommand;
}
}
public string Prompt
{
get
{
return ComplexCommand.IsComplete ? EvaluatePrompt() : ">> ";
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private string EvaluatePrompt()
{
string prompt = "PM>";
try
{
PSObject output = this.Runspace.Invoke("prompt", null, outputResults: false).FirstOrDefault();
if (output != null)
{
string result = output.BaseObject.ToString();
if (!String.IsNullOrEmpty(result))
{
prompt = result;
}
}
}
catch (Exception ex)
{
ExceptionHelper.WriteToActivityLog(ex);
}
return prompt;
}
/// <summary>
/// Doing all necessary initialization works before the console accepts user inputs
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public void Initialize(IConsole console)
{
ActiveConsole = console;
if (_initialized.HasValue)
{
if (_initialized.Value && console.ShowDisclaimerHeader)
{
DisplayDisclaimerAndHelpText();
}
}
else
{
try
{
Tuple<RunspaceDispatcher, NuGetPSHost> result = _runspaceManager.GetRunspace(console, _name);
_runspace = result.Item1;
_nugetHost = result.Item2;
_initialized = true;
if (console.ShowDisclaimerHeader)
{
DisplayDisclaimerAndHelpText();
}
UpdateWorkingDirectory();
ExecuteInitScripts();
// Hook up solution events
_solutionManager.SolutionOpened += (o, e) =>
{
Task.Factory.StartNew(() =>
{
UpdateWorkingDirectory();
ExecuteInitScripts();
},
CancellationToken.None,
TaskCreationOptions.None,
TaskScheduler.Default);
};
_solutionManager.SolutionClosed += (o, e) => UpdateWorkingDirectory();
}
catch (Exception ex)
{
// catch all exception as we don't want it to crash VS
_initialized = false;
IsCommandEnabled = false;
ReportError(ex);
ExceptionHelper.WriteToActivityLog(ex);
}
}
}
private void UpdateWorkingDirectory()
{
if (Runspace.RunspaceAvailability == RunspaceAvailability.Available)
{
// if there is no solution open, we set the active directory to be user profile folder
string targetDir = _solutionManager.IsSolutionOpen ?
_solutionManager.SolutionDirectory :
Environment.GetEnvironmentVariable("USERPROFILE");
Runspace.ChangePSDirectory(targetDir);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We don't want execution of init scripts to crash our console.")]
private void ExecuteInitScripts()
{
// Fix for Bug 1426 Disallow ExecuteInitScripts from being executed concurrently by multiple threads.
lock (_initScriptsLock)
{
if (!_solutionManager.IsSolutionOpen)
{
return;
}
IRepositorySettings repositorySettings = ServiceLocator.GetInstance<IRepositorySettings>();
Debug.Assert(repositorySettings != null);
if (repositorySettings == null)
{
return;
}
try
{
var localRepository = new SharedPackageRepository(repositorySettings.RepositoryPath);
// invoke init.ps1 files in the order of package dependency.
// if A -> B, we invoke B's init.ps1 before A's.
var sorter = new PackageSorter(targetFramework: null);
var sortedPackages = sorter.GetPackagesByDependencyOrder(localRepository);
foreach (var package in sortedPackages)
{
string installPath = localRepository.PathResolver.GetInstallPath(package);
AddPathToEnvironment(Path.Combine(installPath, "tools"));
Runspace.ExecuteScript(installPath, "tools\\init.ps1", package);
}
}
catch (Exception ex)
{
// if execution of Init scripts fails, do not let it crash our console
ReportError(ex);
ExceptionHelper.WriteToActivityLog(ex);
}
}
}
private static void AddPathToEnvironment(string path)
{
if (Directory.Exists(path))
{
string environmentPath = Environment.GetEnvironmentVariable("path", EnvironmentVariableTarget.Process);
environmentPath = environmentPath + ";" + path;
Environment.SetEnvironmentVariable("path", environmentPath, EnvironmentVariableTarget.Process);
}
}
protected abstract bool ExecuteHost(string fullCommand, string command, params object[] inputs);
public bool Execute(IConsole console, string command, params object[] inputs)
{
if (console == null)
{
throw new ArgumentNullException("console");
}
if (command == null)
{
throw new ArgumentNullException("command");
}
NuGetEventTrigger.Instance.TriggerEvent(NuGetEvent.PackageManagerConsoleCommandExecutionBegin);
ActiveConsole = console;
string fullCommand;
if (ComplexCommand.AddLine(command, out fullCommand) && !string.IsNullOrEmpty(fullCommand))
{
return ExecuteHost(fullCommand, command, inputs);
}
return false; // constructing multi-line command
}
protected static void OnExecuteCommandEnd()
{
NuGetEventTrigger.Instance.TriggerEvent(NuGetEvent.PackageManagerConsoleCommandExecutionEnd);
}
public void Abort()
{
if (ExecutingPipeline != null)
{
ExecutingPipeline.StopAsync();
}
ComplexCommand.Clear();
}
protected void SetSyncModeOnHost(bool isSync)
{
if (_nugetHost != null)
{
PSPropertyInfo property = _nugetHost.PrivateData.Properties["IsSyncMode"];
if (property == null)
{
property = new PSNoteProperty("IsSyncMode", isSync);
_nugetHost.PrivateData.Properties.Add(property);
}
else
{
property.Value = isSync;
}
}
}
public void SetDefaultRunspace()
{
Runspace.MakeDefault();
}
private void DisplayDisclaimerAndHelpText()
{
WriteLine(VsResources.Console_DisclaimerText);
WriteLine();
WriteLine(String.Format(CultureInfo.CurrentCulture, Resources.PowerShellHostTitle, _nugetHost.Version.ToString()));
WriteLine();
WriteLine(VsResources.Console_HelpText);
WriteLine();
}
protected void ReportError(ErrorRecord record)
{
WriteErrorLine(Runspace.ExtractErrorFromErrorRecord(record));
}
protected void ReportError(Exception exception)
{
exception = ExceptionUtility.Unwrap(exception);
WriteErrorLine(exception.Message);
}
private void WriteErrorLine(string message)
{
if (ActiveConsole != null)
{
ActiveConsole.Write(message + Environment.NewLine, System.Windows.Media.Colors.Red, null);
}
}
private void WriteLine(string message = "")
{
if (ActiveConsole != null)
{
ActiveConsole.WriteLine(message);
}
}
public string ActivePackageSource
{
get
{
var activePackageSource = _packageSourceProvider.ActivePackageSource;
if (activePackageSource.IsAggregate())
{
// Starting from 2.7, we will not show the All option if there's only one package source.
// Hence, if All is the active package source in that case, we set the sole package source as active,
// and save it to settings
PackageSource[] packageSources = _packageSourceProvider.GetEnabledPackageSourcesWithAggregate().ToArray();
if (packageSources.Length == 1)
{
_packageSourceProvider.ActivePackageSource = packageSources[0];
return packageSources[0].Name;
}
}
return activePackageSource == null ? null : activePackageSource.Name;
}
set
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentNullException("value");
}
_packageSourceProvider.ActivePackageSource =
_packageSourceProvider.GetEnabledPackageSourcesWithAggregate().FirstOrDefault(
ps => ps.Name.Equals(value, StringComparison.OrdinalIgnoreCase));
}
}
public string[] GetPackageSources()
{
// Starting NuGet 3.0 RC, AggregateSource will not be displayed in the Package source dropdown box of PowerShell console.
return _packageSourceProvider.GetEnabledPackageSources().Select(ps => ps.Name).ToArray();
}
public string DefaultProject
{
get
{
Debug.Assert(_solutionManager != null);
if (_solutionManager.DefaultProject == null)
{
return null;
}
return _solutionManager.DefaultProject.GetDisplayName(_solutionManager);
}
}
public void SetDefaultProjectIndex(int selectedIndex)
{
Debug.Assert(_solutionManager != null);
if (_projectSafeNames != null && selectedIndex >= 0 && selectedIndex < _projectSafeNames.Length)
{
_solutionManager.DefaultProjectName = _projectSafeNames[selectedIndex];
}
else
{
_solutionManager.DefaultProjectName = null;
}
}
public string[] GetAvailableProjects()
{
Debug.Assert(_solutionManager != null);
var allProjects = _solutionManager.GetProjects();
_projectSafeNames = allProjects.Select(_solutionManager.GetProjectSafeName).ToArray();
var displayNames = allProjects.Select(p => p.GetDisplayName(_solutionManager)).ToArray();
Array.Sort(displayNames, _projectSafeNames, StringComparer.CurrentCultureIgnoreCase);
return displayNames;
}
#region ITabExpansion
public string[] GetExpansions(string line, string lastWord)
{
var query = from s in Runspace.Invoke(
@"$__pc_args=@();$input|%{$__pc_args+=$_};if(Test-Path Function:\TabExpansion2){(TabExpansion2 $__pc_args[0] $__pc_args[0].length).CompletionMatches|%{$_.CompletionText}}else{TabExpansion $__pc_args[0] $__pc_args[1]};Remove-Variable __pc_args -Scope 0;",
new string[] { line, lastWord },
outputResults: false)
select (s == null ? null : s.ToString());
return query.ToArray();
}
#endregion
#region IPathExpansion
public SimpleExpansion GetPathExpansions(string line)
{
PSObject expansion = Runspace.Invoke(
"$input|%{$__pc_args=$_}; _TabExpansionPath $__pc_args; Remove-Variable __pc_args -Scope 0",
new object[] { line },
outputResults: false).FirstOrDefault();
if (expansion != null)
{
int replaceStart = (int)expansion.Properties["ReplaceStart"].Value;
IList<string> paths = ((IEnumerable<object>)expansion.Properties["Paths"].Value).Select(o => o.ToString()).ToList();
return new SimpleExpansion(replaceStart, line.Length - replaceStart, paths);
}
return null;
}
#endregion
#region IDisposable
public void Dispose()
{
if (_runspace != null)
{
_runspace.Dispose();
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace Loader {
/**
* <summary>
* A class containing all the necessary data for a mesh: Points, normal vectors, UV coordinates,
* and indices into each.
* Regardless of how the mesh file represents geometry, this is what we load it into,
* because this is most similar to how OpenGL represents geometry.
* We store data as arrays of vertices, UV coordinates and normals, and then a list of Triangle
* structures. A Triangle is a struct which contains integer offsets into the vertex/normal/texcoord
* arrays to define a face.
* </summary>
*/
// XXX: Sources: http://www.opentk.com/files/ObjMeshLoader.cs, OOGL (MS3D), Icarus (Colladia)
public class MeshData {
public Vector3[] Vertices;
public Vector2[] TexCoords;
public Vector3[] Normals;
public Tri[] Tris;
/// <summary>
///Creates a new MeshData object
/// </summary>
/// <param name="vert">
/// A <see cref="Vector3[]"/>
/// </param>
/// <param name="norm">
/// A <see cref="Vector3[]"/>
/// </param>
/// <param name="tex">
/// A <see cref="Vector2[]"/>
/// </param>
/// <param name="tri">
/// A <see cref="Tri[]"/>
/// </param>
public MeshData(Vector3[] vert, Vector3[] norm, Vector2[] tex, Tri[] tri) {
Vertices = vert;
TexCoords = tex;
Normals = norm;
Tris = tri;
Verify();
}
/// <summary>
/// Returns an array containing the coordinates of all the <value>Vertices</value>.
/// So {<1,1,1>, <2,2,2>} will turn into {1,1,1,2,2,2}
/// </summary>
/// <returns>
/// A <see cref="System.Double[]"/>
/// </returns>
///
public double[] VertexArray() {
double[] verts = new double[Vertices.Length*3];
for(int i = 0; i < Vertices.Length; i++) {
verts[i*3] = Vertices[i].X;
verts[i*3+1] = Vertices[i].Y;
verts[i*3+2] = Vertices[i].Z;
}
return verts;
}
/// <summary>
/// Returns an array containing the coordinates of the <value>Normals<,value>, similar to VertexArray.
/// </summary>
/// <returns>
/// A <see cref="System.Double[]"/>
/// </returns>
public double[] NormalArray() {
double[] norms = new double[Normals.Length * 3];
for(int i = 0; i < Normals.Length; i++) {
norms[i * 3] = Normals[i].X;
norms[i * 3 + 1] = Normals[i].Y;
norms[i * 3 + 2] = Normals[i].Z;
}
return norms;
}
/// <summary>
/// Returns an array containing the coordinates of the <value>TexCoords<value>, similar to VertexArray.
/// </summary>
/// <returns>
/// A <see cref="System.Double[]"/>
/// </returns>
public double[] TexcoordArray() {
double[] tcs = new double[TexCoords.Length*2];
for(int i = 0; i < TexCoords.Length; i++) {
tcs[i*3] = TexCoords[i].X;
tcs[i*3+1] = TexCoords[i].Y;
}
return tcs;
}
/*
public void IndexArrays(out int[] verts, out int[] norms, out int[] texcoords) {
List<int> v = new List<int>();
List<int> n = new List<int>();
List<int> t = new List<int>();
foreach(Face f in Faces) {
foreach(Point p in f.Points) {
v.Add(p.Vertex);
n.Add(p.Normal);
t.Add(p.TexCoord);
}
}
verts = v.ToArray();
norms = n.ToArray();
texcoords = t.ToArray();
}
*/
/// <summary>
/// Turns the Triangles into an array of Points.
/// </summary>
/// <returns>
/// A <see cref="Point[]"/>
/// </returns>
protected Point[] Points() {
List<Point> points = new List<Point>();
foreach(Tri t in Tris) {
points.Add(t.P1);
points.Add(t.P2);
points.Add(t.P3);
}
return points.ToArray();
}
// OpenGL's vertex buffers use the same index to refer to vertices, normals and floats,
// and just duplicate data as necessary. So, we do the same.
// XXX: This... may or may not be correct, and is certainly not efficient.
// But when in doubt, use brute force.
public void OpenGLArrays(out float[] verts, out float[] norms, out float[] texcoords, out uint[] indices) {
Point[] points = Points();
verts = new float[points.Length * 3];
norms = new float[points.Length * 3];
texcoords = new float[points.Length * 2];
indices = new uint[points.Length];
for(uint i = 0; i < points.Length; i++) {
Point p = points[i];
verts[i*3] = (float) Vertices[p.Vertex].X;
verts[i*3+1] = (float) Vertices[p.Vertex].Y;
verts[i*3+2] = (float) Vertices[p.Vertex].Z;
norms[i*3] = (float) Normals[p.Normal].X;
norms[i*3+1] = (float) Normals[p.Normal].Y;
norms[i*3+2] = (float) Normals[p.Normal].Z;
texcoords[i*2] = (float) TexCoords[p.TexCoord].X;
texcoords[i*2+1] = (float) TexCoords[p.TexCoord].Y;
indices[i] = i;
}
}
public override string ToString() {
StringBuilder s = new StringBuilder();
s.AppendLine("Vertices:");
foreach(Vector3 v in Vertices) {
s.AppendLine(v.ToString());
}
s.AppendLine("Normals:");
foreach(Vector3 n in Normals) {
s.AppendLine(n.ToString());
}
s.AppendLine("TexCoords:");
foreach(Vector2 t in TexCoords) {
s.AppendLine(t.ToString());
}
s.AppendLine("Tris:");
foreach(Tri t in Tris) {
s.AppendLine(t.ToString());
}
return s.ToString();
}
// XXX: Might technically be incorrect, since a (malformed) file could have vertices
// that aren't actually in any face.
// XXX: Don't take the names of the out parameters too literally...
public void Dimensions(out double width, out double length, out double height) {
double maxx, minx, maxy, miny, maxz, minz;
maxx = maxy = maxz = minx = miny = minz = 0;
foreach(Vector3 vert in Vertices) {
if(vert.X > maxx) maxx = vert.X;
if(vert.Y > maxy) maxy = vert.Y;
if(vert.Z > maxz) maxz = vert.Z;
if(vert.X < minx) minx = vert.X;
if(vert.Y < miny) miny = vert.Y;
if(vert.Z < minz) minz = vert.Z;
}
width = maxx - minx;
length = maxy - miny;
height = maxz - minz;
}
/// <summary>
/// Does some simple sanity checking to make sure that the offsets of the Triangles
/// actually refer to real points. Throws an
/// <exception cref="IndexOutOfRangeException">IndexOutOfRangeException</exception> if not.
/// </summary>
///
public void Verify() {
foreach(Tri t in Tris) {
foreach(Point p in t.Points()) {
if(p.Vertex >= Vertices.Length) {
string message = String.Format("Vertex {0} >= length of vertices {1}", p.Vertex, Vertices.Length);
throw new IndexOutOfRangeException(message);
}
if(p.Normal >= Normals.Length) {
string message = String.Format("Normal {0} >= number of normals {1}", p.Normal, Normals.Length);
throw new IndexOutOfRangeException(message);
}
if(p.TexCoord > TexCoords.Length) {
string message = String.Format("TexCoord {0} > number of texcoords {1}", p.TexCoord, TexCoords.Length);
throw new IndexOutOfRangeException(message);
}
}
}
}
}
public struct Vector2 {
public double X;
public double Y;
public Vector2(double x, double y) {
X = x;
Y = y;
}
public override string ToString() {return String.Format("<{0},{1}>", X, Y);}
}
public struct Vector3 {
public double X;
public double Y;
public double Z;
public Vector3(double x, double y, double z) {
X = x;
Y = y;
Z = z;
}
public override string ToString() {return String.Format("<{0},{1},{2}>", X, Y, Z);}
}
public struct Point {
public int Vertex;
public int Normal;
public int TexCoord;
public Point(int v, int n, int t) {
Vertex = v;
Normal = n;
TexCoord = t;
}
public override string ToString() {return String.Format("Point: {0},{1},{2}", Vertex, Normal, TexCoord);}
}
public class Tri {
public Point P1, P2, P3;
public Tri() {
P1 = new Point();
P2 = new Point();
P3 = new Point();
}
public Tri(Point a, Point b, Point c) {
P1 = a;
P2 = b;
P3 = c;
}
public Point[] Points() {
return new Point[3]{P1, P2, P3};
}
public override string ToString() {return String.Format("Tri: {0}, {1}, {2}", P1, P2, P3);}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.Runtime.Serialization
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Reflection;
using System.Threading;
using System.Text;
using System.Xml;
using System.Security;
#if USE_REFEMIT
public sealed class EnumDataContract : DataContract
#else
internal sealed class EnumDataContract : DataContract
#endif
{
[Fx.Tag.SecurityNote(Critical = "Holds instance of CriticalHelper which keeps state that is cached statically for serialization."
+ " Static fields are marked SecurityCritical or readonly to prevent data from being modified or leaked to other components in appdomain.")]
[SecurityCritical]
EnumDataContractCriticalHelper helper;
[Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.",
Safe = "Doesn't leak anything.")]
[SecuritySafeCritical]
internal EnumDataContract()
: base(new EnumDataContractCriticalHelper())
{
helper = base.Helper as EnumDataContractCriticalHelper;
}
[Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.",
Safe = "Doesn't leak anything.")]
[SecuritySafeCritical]
internal EnumDataContract(Type type)
: base(new EnumDataContractCriticalHelper(type))
{
helper = base.Helper as EnumDataContractCriticalHelper;
}
[Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical static cache to look up base contract name for a type.",
Safe = "Read only access.")]
[SecuritySafeCritical]
static internal XmlQualifiedName GetBaseContractName(Type type)
{
return EnumDataContractCriticalHelper.GetBaseContractName(type);
}
[Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical static cache to look up a base contract name.",
Safe = "Read only access.")]
[SecuritySafeCritical]
static internal Type GetBaseType(XmlQualifiedName baseContractName)
{
return EnumDataContractCriticalHelper.GetBaseType(baseContractName);
}
internal XmlQualifiedName BaseContractName
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical BaseContractName property.",
Safe = "BaseContractName only needs to be protected for write.")]
[SecuritySafeCritical]
get { return helper.BaseContractName; }
[Fx.Tag.SecurityNote(Critical = "Sets the critical BaseContractName property.")]
[SecurityCritical]
set { helper.BaseContractName = value; }
}
internal List<DataMember> Members
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical Members property.",
Safe = "Members only needs to be protected for write.")]
[SecuritySafeCritical]
get { return helper.Members; }
[Fx.Tag.SecurityNote(Critical = "Sets the critical Members property.")]
[SecurityCritical]
set { helper.Members = value; }
}
internal List<long> Values
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical Values property.",
Safe = "Values only needs to be protected for write.")]
[SecuritySafeCritical]
get { return helper.Values; }
[Fx.Tag.SecurityNote(Critical = "Sets the critical Values property.")]
[SecurityCritical]
set { helper.Values = value; }
}
internal bool IsFlags
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical IsFlags property.",
Safe = "IsFlags only needs to be protected for write.")]
[SecuritySafeCritical]
get { return helper.IsFlags; }
[Fx.Tag.SecurityNote(Critical = "Sets the critical IsFlags property.")]
[SecurityCritical]
set { helper.IsFlags = value; }
}
internal bool IsULong
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical IsULong property.",
Safe = "IsULong only needs to be protected for write.")]
[SecuritySafeCritical]
get { return helper.IsULong; }
}
XmlDictionaryString[] ChildElementNames
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical ChildElementNames property.",
Safe = "ChildElementNames only needs to be protected for write.")]
[SecuritySafeCritical]
get { return helper.ChildElementNames; }
}
internal override bool CanContainReferences
{
get { return false; }
}
[Fx.Tag.SecurityNote(Critical = "Holds all state used for (de)serializing enums."
+ " Since the data is cached statically, we lock down access to it.")]
#if !NO_SECURITY_ATTRIBUTES
[SecurityCritical(SecurityCriticalScope.Everything)]
#endif
class EnumDataContractCriticalHelper : DataContract.DataContractCriticalHelper
{
static Dictionary<Type, XmlQualifiedName> typeToName;
static Dictionary<XmlQualifiedName, Type> nameToType;
XmlQualifiedName baseContractName;
List<DataMember> members;
List<long> values;
bool isULong;
bool isFlags;
bool hasDataContract;
XmlDictionaryString[] childElementNames;
static EnumDataContractCriticalHelper()
{
typeToName = new Dictionary<Type, XmlQualifiedName>();
nameToType = new Dictionary<XmlQualifiedName, Type>();
Add(typeof(sbyte), "byte");
Add(typeof(byte), "unsignedByte");
Add(typeof(short), "short");
Add(typeof(ushort), "unsignedShort");
Add(typeof(int), "int");
Add(typeof(uint), "unsignedInt");
Add(typeof(long), "long");
Add(typeof(ulong), "unsignedLong");
}
[SuppressMessage(FxCop.Category.Usage, "CA2301:EmbeddableTypesInContainersRule", MessageId = "typeToName", Justification = "No need to support type equivalence here.")]
static internal void Add(Type type, string localName)
{
XmlQualifiedName stableName = CreateQualifiedName(localName, Globals.SchemaNamespace);
typeToName.Add(type, stableName);
nameToType.Add(stableName, type);
}
static internal XmlQualifiedName GetBaseContractName(Type type)
{
XmlQualifiedName retVal = null;
typeToName.TryGetValue(type, out retVal);
return retVal;
}
static internal Type GetBaseType(XmlQualifiedName baseContractName)
{
Type retVal = null;
nameToType.TryGetValue(baseContractName, out retVal);
return retVal;
}
internal EnumDataContractCriticalHelper()
{
IsValueType = true;
}
internal EnumDataContractCriticalHelper(Type type)
: base(type)
{
this.StableName = DataContract.GetStableName(type, out hasDataContract);
Type baseType = Enum.GetUnderlyingType(type);
baseContractName = GetBaseContractName(baseType);
ImportBaseType(baseType);
IsFlags = type.IsDefined(Globals.TypeOfFlagsAttribute, false);
ImportDataMembers();
XmlDictionary dictionary = new XmlDictionary(2 + Members.Count);
Name = dictionary.Add(StableName.Name);
Namespace = dictionary.Add(StableName.Namespace);
childElementNames = new XmlDictionaryString[Members.Count];
for (int i = 0; i < Members.Count; i++)
childElementNames[i] = dictionary.Add(Members[i].Name);
DataContractAttribute dataContractAttribute;
if (TryGetDCAttribute(type, out dataContractAttribute))
{
if (dataContractAttribute.IsReference)
{
DataContract.ThrowInvalidDataContractException(
SR.GetString(SR.EnumTypeCannotHaveIsReference,
DataContract.GetClrTypeFullName(type),
dataContractAttribute.IsReference,
false),
type);
}
}
}
internal XmlQualifiedName BaseContractName
{
get
{
return baseContractName;
}
set
{
baseContractName = value;
Type baseType = GetBaseType(baseContractName);
if (baseType == null)
ThrowInvalidDataContractException(SR.GetString(SR.InvalidEnumBaseType, value.Name, value.Namespace, StableName.Name, StableName.Namespace));
ImportBaseType(baseType);
}
}
internal List<DataMember> Members
{
get { return members; }
set { members = value; }
}
internal List<long> Values
{
get { return values; }
set { values = value; }
}
internal bool IsFlags
{
get { return isFlags; }
set { isFlags = value; }
}
internal bool IsULong
{
get { return isULong; }
}
internal XmlDictionaryString[] ChildElementNames
{
get { return childElementNames; }
}
void ImportBaseType(Type baseType)
{
isULong = (baseType == Globals.TypeOfULong);
}
void ImportDataMembers()
{
Type type = this.UnderlyingType;
FieldInfo[] fields = type.GetFields(BindingFlags.Static | BindingFlags.Public);
Dictionary<string, DataMember> memberValuesTable = new Dictionary<string, DataMember>();
List<DataMember> tempMembers = new List<DataMember>(fields.Length);
List<long> tempValues = new List<long>(fields.Length);
for (int i = 0; i < fields.Length; i++)
{
FieldInfo field = fields[i];
bool enumMemberValid = false;
if (hasDataContract)
{
object[] memberAttributes = field.GetCustomAttributes(Globals.TypeOfEnumMemberAttribute, false);
if (memberAttributes != null && memberAttributes.Length > 0)
{
if (memberAttributes.Length > 1)
ThrowInvalidDataContractException(SR.GetString(SR.TooManyEnumMembers, DataContract.GetClrTypeFullName(field.DeclaringType), field.Name));
EnumMemberAttribute memberAttribute = (EnumMemberAttribute)memberAttributes[0];
DataMember memberContract = new DataMember(field);
if (memberAttribute.IsValueSetExplicit)
{
if (memberAttribute.Value == null || memberAttribute.Value.Length == 0)
ThrowInvalidDataContractException(SR.GetString(SR.InvalidEnumMemberValue, field.Name, DataContract.GetClrTypeFullName(type)));
memberContract.Name = memberAttribute.Value;
}
else
memberContract.Name = field.Name;
ClassDataContract.CheckAndAddMember(tempMembers, memberContract, memberValuesTable);
enumMemberValid = true;
}
object[] dataMemberAttributes = field.GetCustomAttributes(Globals.TypeOfDataMemberAttribute, false);
if (dataMemberAttributes != null && dataMemberAttributes.Length > 0)
ThrowInvalidDataContractException(SR.GetString(SR.DataMemberOnEnumField, DataContract.GetClrTypeFullName(field.DeclaringType), field.Name));
}
else
{
if (!field.IsNotSerialized)
{
DataMember memberContract = new DataMember(field);
memberContract.Name = field.Name;
ClassDataContract.CheckAndAddMember(tempMembers, memberContract, memberValuesTable);
enumMemberValid = true;
}
}
if (enumMemberValid)
{
object enumValue = field.GetValue(null);
if (isULong)
tempValues.Add((long)((IConvertible)enumValue).ToUInt64(null));
else
tempValues.Add(((IConvertible)enumValue).ToInt64(null));
}
}
Thread.MemoryBarrier();
members = tempMembers;
values = tempValues;
}
}
internal void WriteEnumValue(XmlWriterDelegator writer, object value)
{
long longValue = IsULong ? (long)((IConvertible)value).ToUInt64(null) : ((IConvertible)value).ToInt64(null);
for (int i = 0; i < Values.Count; i++)
{
if (longValue == Values[i])
{
writer.WriteString(ChildElementNames[i].Value);
return;
}
}
if (IsFlags)
{
int zeroIndex = -1;
bool noneWritten = true;
for (int i = 0; i < Values.Count; i++)
{
long current = Values[i];
if (current == 0)
{
zeroIndex = i;
continue;
}
if (longValue == 0)
break;
if ((current & longValue) == current)
{
if (noneWritten)
noneWritten = false;
else
writer.WriteString(DictionaryGlobals.Space.Value);
writer.WriteString(ChildElementNames[i].Value);
longValue &= ~current;
}
}
// enforce that enum value was completely parsed
if (longValue != 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.InvalidEnumValueOnWrite, value, DataContract.GetClrTypeFullName(UnderlyingType))));
if (noneWritten && zeroIndex >= 0)
writer.WriteString(ChildElementNames[zeroIndex].Value);
}
else
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.InvalidEnumValueOnWrite, value, DataContract.GetClrTypeFullName(UnderlyingType))));
}
internal object ReadEnumValue(XmlReaderDelegator reader)
{
string stringValue = reader.ReadElementContentAsString();
long longValue = 0;
int i = 0;
if (IsFlags)
{
// Skip initial spaces
for (; i < stringValue.Length; i++)
if (stringValue[i] != ' ')
break;
// Read space-delimited values
int startIndex = i;
int count = 0;
for (; i < stringValue.Length; i++)
{
if (stringValue[i] == ' ')
{
count = i - startIndex;
if (count > 0)
longValue |= ReadEnumValue(stringValue, startIndex, count);
for (++i; i < stringValue.Length; i++)
if (stringValue[i] != ' ')
break;
startIndex = i;
if (i == stringValue.Length)
break;
}
}
count = i - startIndex;
if (count > 0)
longValue |= ReadEnumValue(stringValue, startIndex, count);
}
else
{
if (stringValue.Length == 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.InvalidEnumValueOnRead, stringValue, DataContract.GetClrTypeFullName(UnderlyingType))));
longValue = ReadEnumValue(stringValue, 0, stringValue.Length);
}
if (IsULong)
return Enum.ToObject(UnderlyingType, (ulong)longValue);
return Enum.ToObject(UnderlyingType, longValue);
}
long ReadEnumValue(string value, int index, int count)
{
for (int i = 0; i < Members.Count; i++)
{
string memberName = Members[i].Name;
if (memberName.Length == count && String.CompareOrdinal(value, index, memberName, 0, count) == 0)
{
return Values[i];
}
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.InvalidEnumValueOnRead, value.Substring(index, count), DataContract.GetClrTypeFullName(UnderlyingType))));
}
internal string GetStringFromEnumValue(long value)
{
if (IsULong)
return XmlConvert.ToString((ulong)value);
else
return XmlConvert.ToString(value);
}
internal long GetEnumValueFromString(string value)
{
if (IsULong)
return (long)XmlConverter.ToUInt64(value);
else
return XmlConverter.ToInt64(value);
}
internal override bool Equals(object other, Dictionary<DataContractPairKey, object> checkedContracts)
{
if (IsEqualOrChecked(other, checkedContracts))
return true;
if (base.Equals(other, null))
{
EnumDataContract dataContract = other as EnumDataContract;
if (dataContract != null)
{
if (Members.Count != dataContract.Members.Count || Values.Count != dataContract.Values.Count)
return false;
string[] memberNames1 = new string[Members.Count], memberNames2 = new string[Members.Count];
for (int i = 0; i < Members.Count; i++)
{
memberNames1[i] = Members[i].Name;
memberNames2[i] = dataContract.Members[i].Name;
}
Array.Sort(memberNames1);
Array.Sort(memberNames2);
for (int i = 0; i < Members.Count; i++)
{
if (memberNames1[i] != memberNames2[i])
return false;
}
return (IsFlags == dataContract.IsFlags);
}
}
return false;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
{
WriteEnumValue(xmlWriter, obj);
}
public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
{
object obj = ReadEnumValue(xmlReader);
if (context != null)
context.AddNewObject(obj);
return obj;
}
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace Simple.OData.Client.Office365.ExampleB
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Linq.Expressions;
using System.Reflection;
namespace System.Dynamic.Utils
{
internal static class TypeUtils
{
public static Type GetNonNullableType(this Type type) => IsNullableType(type) ? type.GetGenericArguments()[0] : type;
public static Type GetNullableType(this Type type)
{
Debug.Assert(type != null, "type cannot be null");
if (type.IsValueType && !IsNullableType(type))
{
return typeof(Nullable<>).MakeGenericType(type);
}
return type;
}
public static bool IsNullableType(this Type type) => type.IsConstructedGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
public static bool IsNullableOrReferenceType(this Type type) => !type.IsValueType || IsNullableType(type);
public static bool IsBool(this Type type) => GetNonNullableType(type) == typeof(bool);
public static bool IsNumeric(this Type type)
{
type = GetNonNullableType(type);
if (!type.IsEnum)
{
switch (type.GetTypeCode())
{
case TypeCode.Char:
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Double:
case TypeCode.Single:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return true;
}
}
return false;
}
public static bool IsInteger(this Type type)
{
type = GetNonNullableType(type);
if (!type.IsEnum)
{
switch (type.GetTypeCode())
{
case TypeCode.Byte:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return true;
}
}
return false;
}
public static bool IsInteger64(this Type type)
{
type = GetNonNullableType(type);
if (!type.IsEnum)
{
switch (type.GetTypeCode())
{
case TypeCode.Int64:
case TypeCode.UInt64:
return true;
}
}
return false;
}
public static bool IsArithmetic(this Type type)
{
type = GetNonNullableType(type);
if (!type.IsEnum)
{
switch (type.GetTypeCode())
{
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Double:
case TypeCode.Single:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return true;
}
}
return false;
}
public static bool IsUnsignedInt(this Type type)
{
type = GetNonNullableType(type);
if (!type.IsEnum)
{
switch (type.GetTypeCode())
{
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return true;
}
}
return false;
}
public static bool IsIntegerOrBool(this Type type)
{
type = GetNonNullableType(type);
if (!type.IsEnum)
{
switch (type.GetTypeCode())
{
case TypeCode.Int64:
case TypeCode.Int32:
case TypeCode.Int16:
case TypeCode.UInt64:
case TypeCode.UInt32:
case TypeCode.UInt16:
case TypeCode.Boolean:
case TypeCode.SByte:
case TypeCode.Byte:
return true;
}
}
return false;
}
public static bool IsNumericOrBool(this Type type) => IsNumeric(type) || IsBool(type);
// Checks if the type is a valid target for an instance call
public static bool IsValidInstanceType(MemberInfo member, Type instanceType)
{
Type targetType = member.DeclaringType;
if (AreReferenceAssignable(targetType, instanceType))
{
return true;
}
if (targetType == null)
{
return false;
}
if (instanceType.IsValueType)
{
if (AreReferenceAssignable(targetType, typeof(object)))
{
return true;
}
if (AreReferenceAssignable(targetType, typeof(ValueType)))
{
return true;
}
if (instanceType.IsEnum && AreReferenceAssignable(targetType, typeof(Enum)))
{
return true;
}
// A call to an interface implemented by a struct is legal whether the struct has
// been boxed or not.
if (targetType.IsInterface)
{
foreach (Type interfaceType in instanceType.GetTypeInfo().ImplementedInterfaces)
{
if (AreReferenceAssignable(targetType, interfaceType))
{
return true;
}
}
}
}
return false;
}
public static bool HasIdentityPrimitiveOrNullableConversionTo(this Type source, Type dest)
{
Debug.Assert(source != null && dest != null);
// Identity conversion
if (AreEquivalent(source, dest))
{
return true;
}
// Nullable conversions
if (IsNullableType(source) && AreEquivalent(dest, GetNonNullableType(source)))
{
return true;
}
if (IsNullableType(dest) && AreEquivalent(source, GetNonNullableType(dest)))
{
return true;
}
// Primitive runtime conversions
// All conversions amongst enum, bool, char, integer and float types
// (and their corresponding nullable types) are legal except for
// nonbool==>bool and nonbool==>bool? which are only legal from
// bool-backed enums.
return IsConvertible(source) && IsConvertible(dest)
&& (GetNonNullableType(dest) != typeof(bool)
|| source.IsEnum && source.GetEnumUnderlyingType() == typeof(bool));
}
public static bool HasReferenceConversionTo(this Type source, Type dest)
{
Debug.Assert(source != null && dest != null);
// void -> void conversion is handled elsewhere
// (it's an identity conversion)
// All other void conversions are disallowed.
if (source == typeof(void) || dest == typeof(void))
{
return false;
}
Type nnSourceType = GetNonNullableType(source);
Type nnDestType = GetNonNullableType(dest);
// Down conversion
if (nnSourceType.IsAssignableFrom(nnDestType))
{
return true;
}
// Up conversion
if (nnDestType.IsAssignableFrom(nnSourceType))
{
return true;
}
// Interface conversion
if (source.IsInterface || dest.IsInterface)
{
return true;
}
// Variant delegate conversion
if (IsLegalExplicitVariantDelegateConversion(source, dest))
{
return true;
}
// Object conversion
return source == typeof(object) || dest == typeof(object);
}
private static bool IsCovariant(Type t)
{
Debug.Assert(t != null);
return 0 != (t.GenericParameterAttributes & GenericParameterAttributes.Covariant);
}
private static bool IsContravariant(Type t)
{
Debug.Assert(t != null);
return 0 != (t.GenericParameterAttributes & GenericParameterAttributes.Contravariant);
}
private static bool IsInvariant(Type t)
{
Debug.Assert(t != null);
return 0 == (t.GenericParameterAttributes & GenericParameterAttributes.VarianceMask);
}
private static bool IsDelegate(Type t)
{
Debug.Assert(t != null);
return t.IsSubclassOf(typeof(MulticastDelegate));
}
public static bool IsLegalExplicitVariantDelegateConversion(Type source, Type dest)
{
Debug.Assert(source != null && dest != null);
// There *might* be a legal conversion from a generic delegate type S to generic delegate type T,
// provided all of the follow are true:
// o Both types are constructed generic types of the same generic delegate type, D<X1,... Xk>.
// That is, S = D<S1...>, T = D<T1...>.
// o If type parameter Xi is declared to be invariant then Si must be identical to Ti.
// o If type parameter Xi is declared to be covariant ("out") then Si must be convertible
// to Ti via an identify conversion, implicit reference conversion, or explicit reference conversion.
// o If type parameter Xi is declared to be contravariant ("in") then either Si must be identical to Ti,
// or Si and Ti must both be reference types.
if (!IsDelegate(source) || !IsDelegate(dest) || !source.IsGenericType || !dest.IsGenericType)
{
return false;
}
Type genericDelegate = source.GetGenericTypeDefinition();
if (dest.GetGenericTypeDefinition() != genericDelegate)
{
return false;
}
Type[] genericParameters = genericDelegate.GetGenericArguments();
Type[] sourceArguments = source.GetGenericArguments();
Type[] destArguments = dest.GetGenericArguments();
Debug.Assert(genericParameters != null);
Debug.Assert(sourceArguments != null);
Debug.Assert(destArguments != null);
Debug.Assert(genericParameters.Length == sourceArguments.Length);
Debug.Assert(genericParameters.Length == destArguments.Length);
for (int iParam = 0; iParam < genericParameters.Length; ++iParam)
{
Type sourceArgument = sourceArguments[iParam];
Type destArgument = destArguments[iParam];
Debug.Assert(sourceArgument != null && destArgument != null);
// If the arguments are identical then this one is automatically good, so skip it.
if (AreEquivalent(sourceArgument, destArgument))
{
continue;
}
Type genericParameter = genericParameters[iParam];
Debug.Assert(genericParameter != null);
if (IsInvariant(genericParameter))
{
return false;
}
if (IsCovariant(genericParameter))
{
if (!sourceArgument.HasReferenceConversionTo(destArgument))
{
return false;
}
}
else if (IsContravariant(genericParameter) && (sourceArgument.IsValueType || destArgument.IsValueType))
{
return false;
}
}
return true;
}
public static bool IsConvertible(this Type type)
{
type = GetNonNullableType(type);
if (type.IsEnum)
{
return true;
}
switch (type.GetTypeCode())
{
case TypeCode.Boolean:
case TypeCode.Byte:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Char:
return true;
default:
return false;
}
}
public static bool HasReferenceEquality(Type left, Type right)
{
if (left.IsValueType || right.IsValueType)
{
return false;
}
// If we have an interface and a reference type then we can do
// reference equality.
// If we have two reference types and one is assignable to the
// other then we can do reference equality.
return left.IsInterface || right.IsInterface || AreReferenceAssignable(left, right)
|| AreReferenceAssignable(right, left);
}
public static bool HasBuiltInEqualityOperator(Type left, Type right)
{
// If we have an interface and a reference type then we can do
// reference equality.
if (left.IsInterface && !right.IsValueType)
{
return true;
}
if (right.IsInterface && !left.IsValueType)
{
return true;
}
// If we have two reference types and one is assignable to the
// other then we can do reference equality.
if (!left.IsValueType && !right.IsValueType)
{
if (AreReferenceAssignable(left, right) || AreReferenceAssignable(right, left))
{
return true;
}
}
// Otherwise, if the types are not the same then we definitely
// do not have a built-in equality operator.
if (!AreEquivalent(left, right))
{
return false;
}
// We have two identical value types, modulo nullability. (If they were both the
// same reference type then we would have returned true earlier.)
Debug.Assert(left.IsValueType);
// Equality between struct types is only defined for numerics, bools, enums,
// and their nullable equivalents.
Type nnType = GetNonNullableType(left);
return nnType == typeof(bool) || IsNumeric(nnType) || nnType.IsEnum;
}
public static bool IsImplicitlyConvertibleTo(this Type source, Type destination) =>
AreEquivalent(source, destination) // identity conversion
|| IsImplicitNumericConversion(source, destination)
|| IsImplicitReferenceConversion(source, destination)
|| IsImplicitBoxingConversion(source, destination)
|| IsImplicitNullableConversion(source, destination);
public static MethodInfo GetUserDefinedCoercionMethod(Type convertFrom, Type convertToType)
{
Type nnExprType = GetNonNullableType(convertFrom);
Type nnConvType = GetNonNullableType(convertToType);
// try exact match on types
MethodInfo[] eMethods = nnExprType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
MethodInfo method = FindConversionOperator(eMethods, convertFrom, convertToType);
if (method != null)
{
return method;
}
MethodInfo[] cMethods = nnConvType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
method = FindConversionOperator(cMethods, convertFrom, convertToType);
if (method != null)
{
return method;
}
if (AreEquivalent(nnExprType, convertFrom) && AreEquivalent(nnConvType, convertToType))
{
return null;
}
// try lifted conversion
return FindConversionOperator(eMethods, nnExprType, nnConvType)
?? FindConversionOperator(cMethods, nnExprType, nnConvType)
?? FindConversionOperator(eMethods, nnExprType, convertToType)
?? FindConversionOperator(cMethods, nnExprType, convertToType);
}
private static MethodInfo FindConversionOperator(MethodInfo[] methods, Type typeFrom, Type typeTo)
{
foreach (MethodInfo mi in methods)
{
if ((mi.Name == "op_Implicit" || mi.Name == "op_Explicit") && AreEquivalent(mi.ReturnType, typeTo))
{
ParameterInfo[] pis = mi.GetParametersCached();
if (pis.Length == 1 && AreEquivalent(pis[0].ParameterType, typeFrom))
{
return mi;
}
}
}
return null;
}
[Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
private static bool IsImplicitNumericConversion(Type source, Type destination)
{
TypeCode tcSource = source.GetTypeCode();
TypeCode tcDest = destination.GetTypeCode();
switch (tcSource)
{
case TypeCode.SByte:
switch (tcDest)
{
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.Byte:
switch (tcDest)
{
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.Int16:
switch (tcDest)
{
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.UInt16:
switch (tcDest)
{
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.Int32:
switch (tcDest)
{
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.UInt32:
switch (tcDest)
{
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.Int64:
case TypeCode.UInt64:
switch (tcDest)
{
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.Char:
switch (tcDest)
{
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.Single:
return tcDest == TypeCode.Double;
}
return false;
}
private static bool IsImplicitReferenceConversion(Type source, Type destination) =>
destination.IsAssignableFrom(source);
private static bool IsImplicitBoxingConversion(Type source, Type destination) =>
source.IsValueType && (destination == typeof(object) || destination == typeof(ValueType)) || source.IsEnum && destination == typeof(Enum);
private static bool IsImplicitNullableConversion(Type source, Type destination) =>
IsNullableType(destination) && IsImplicitlyConvertibleTo(GetNonNullableType(source), GetNonNullableType(destination));
public static Type FindGenericType(Type definition, Type type)
{
while ((object)type != null && type != typeof(object))
{
if (type.IsConstructedGenericType && AreEquivalent(type.GetGenericTypeDefinition(), definition))
{
return type;
}
if (definition.IsInterface)
{
foreach (Type itype in type.GetTypeInfo().ImplementedInterfaces)
{
Type found = FindGenericType(definition, itype);
if (found != null)
{
return found;
}
}
}
type = type.BaseType;
}
return null;
}
/// <summary>
/// Searches for an operator method on the type. The method must have
/// the specified signature, no generic arguments, and have the
/// SpecialName bit set. Also searches inherited operator methods.
///
/// NOTE: This was designed to satisfy the needs of op_True and
/// op_False, because we have to do runtime lookup for those. It may
/// not work right for unary operators in general.
/// </summary>
public static MethodInfo GetBooleanOperator(Type type, string name)
{
do
{
MethodInfo result = type.GetAnyStaticMethodValidated(name, new[] {type});
if (result != null && result.IsSpecialName && !result.ContainsGenericParameters)
{
return result;
}
type = type.BaseType;
} while (type != null);
return null;
}
public static Type GetNonRefType(this Type type) => type.IsByRef ? type.GetElementType() : type;
public static bool AreEquivalent(Type t1, Type t2) => t1 != null && t1.IsEquivalentTo(t2);
public static bool AreReferenceAssignable(Type dest, Type src)
{
// This actually implements "Is this identity assignable and/or reference assignable?"
if (AreEquivalent(dest, src))
{
return true;
}
return !dest.IsValueType && !src.IsValueType && dest.IsAssignableFrom(src);
}
public static bool IsSameOrSubclass(Type type, Type subType) =>
AreEquivalent(type, subType) || subType.IsSubclassOf(type);
public static void ValidateType(Type type, string paramName) => ValidateType(type, paramName, -1);
public static void ValidateType(Type type, string paramName, int index)
{
if (type != typeof(void))
{
// A check to avoid a bunch of reflection (currently not supported) during cctor
if (type.ContainsGenericParameters)
{
throw type.IsGenericTypeDefinition
? Error.TypeIsGeneric(type, paramName, index)
: Error.TypeContainsGenericParameters(type, paramName, index);
}
}
}
private static Assembly s_mscorlib;
private static Assembly MsCorLib => s_mscorlib ?? (s_mscorlib = typeof(object).Assembly);
/// <summary>
/// We can cache references to types, as long as they aren't in
/// collectible assemblies. Unfortunately, we can't really distinguish
/// between different flavors of assemblies. But, we can at least
/// create a cache for types in mscorlib (so we get the primitives, etc).
/// </summary>
public static bool CanCache(this Type t)
{
// Note: we don't have to scan base or declaring types here.
// There's no way for a type in mscorlib to derive from or be
// contained in a type from another assembly. The only thing we
// need to look at is the generic arguments, which are the thing
// that allows mscorlib types to be specialized by types in other
// assemblies.
Assembly asm = t.Assembly;
if (asm != MsCorLib)
{
// Not in mscorlib or our assembly
return false;
}
if (t.IsGenericType)
{
foreach (Type g in t.GetGenericArguments())
{
if (!g.CanCache())
{
return false;
}
}
}
return true;
}
public static MethodInfo GetInvokeMethod(this Type delegateType)
{
Debug.Assert(typeof(Delegate).IsAssignableFrom(delegateType));
return delegateType.GetMethod("Invoke", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
}
#if FEATURE_COMPILE
internal static bool IsUnsigned(this Type type) => IsUnsigned(GetNonNullableType(type).GetTypeCode());
internal static bool IsUnsigned(this TypeCode typeCode)
{
switch (typeCode)
{
case TypeCode.Byte:
case TypeCode.UInt16:
case TypeCode.Char:
case TypeCode.UInt32:
case TypeCode.UInt64:
return true;
default:
return false;
}
}
internal static bool IsFloatingPoint(this Type type) => IsFloatingPoint(GetNonNullableType(type).GetTypeCode());
internal static bool IsFloatingPoint(this TypeCode typeCode)
{
switch (typeCode)
{
case TypeCode.Single:
case TypeCode.Double:
return true;
default:
return false;
}
}
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Net.Test.Common;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Sockets.Tests
{
public class SocketAsyncEventArgsTest
{
[Fact]
public void Usertoken_Roundtrips()
{
using (var args = new SocketAsyncEventArgs())
{
object o = new object();
Assert.Null(args.UserToken);
args.UserToken = o;
Assert.Same(o, args.UserToken);
}
}
[Fact]
public void SocketFlags_Roundtrips()
{
using (var args = new SocketAsyncEventArgs())
{
Assert.Equal(SocketFlags.None, args.SocketFlags);
args.SocketFlags = SocketFlags.Broadcast;
Assert.Equal(SocketFlags.Broadcast, args.SocketFlags);
}
}
[Fact]
public void SendPacketsSendSize_Roundtrips()
{
using (var args = new SocketAsyncEventArgs())
{
Assert.Equal(0, args.SendPacketsSendSize);
args.SendPacketsSendSize = 4;
Assert.Equal(4, args.SendPacketsSendSize);
}
}
[Fact]
public void SendPacketsFlags_Roundtrips()
{
using (var args = new SocketAsyncEventArgs())
{
Assert.Equal((TransmitFileOptions)0, args.SendPacketsFlags);
args.SendPacketsFlags = TransmitFileOptions.UseDefaultWorkerThread;
Assert.Equal(TransmitFileOptions.UseDefaultWorkerThread, args.SendPacketsFlags);
}
}
[Fact]
public void Dispose_MultipleCalls_Success()
{
using (var args = new SocketAsyncEventArgs())
{
args.Dispose();
}
}
[Fact]
public async Task Dispose_WhileInUse_DisposeDelayed()
{
using (var listen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listen.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listen.Listen(1);
Task<Socket> acceptTask = listen.AcceptAsync();
await Task.WhenAll(
acceptTask,
client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listen.LocalEndPoint).Port)));
using (Socket server = await acceptTask)
using (var receiveSaea = new SocketAsyncEventArgs())
{
var tcs = new TaskCompletionSource<bool>();
receiveSaea.SetBuffer(new byte[1], 0, 1);
receiveSaea.Completed += delegate { tcs.SetResult(true); };
Assert.True(client.ReceiveAsync(receiveSaea));
Assert.Throws<InvalidOperationException>(() => client.ReceiveAsync(receiveSaea)); // already in progress
receiveSaea.Dispose();
server.Send(new byte[1]);
await tcs.Task; // completes successfully even though it was disposed
Assert.Throws<ObjectDisposedException>(() => client.ReceiveAsync(receiveSaea));
}
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task ExecutionContext_FlowsIfNotSuppressed(bool suppressed)
{
using (var listen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listen.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listen.Listen(1);
Task<Socket> acceptTask = listen.AcceptAsync();
await Task.WhenAll(
acceptTask,
client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listen.LocalEndPoint).Port)));
using (Socket server = await acceptTask)
using (var receiveSaea = new SocketAsyncEventArgs())
{
if (suppressed)
{
ExecutionContext.SuppressFlow();
}
var local = new AsyncLocal<int>();
local.Value = 42;
int threadId = Environment.CurrentManagedThreadId;
var mres = new ManualResetEventSlim();
receiveSaea.SetBuffer(new byte[1], 0, 1);
receiveSaea.Completed += delegate
{
Assert.NotEqual(threadId, Environment.CurrentManagedThreadId);
Assert.Equal(suppressed ? 0 : 42, local.Value);
mres.Set();
};
Assert.True(client.ReceiveAsync(receiveSaea));
server.Send(new byte[1]);
mres.Wait();
}
}
}
[Fact]
public void SetBuffer_InvalidArgs_Throws()
{
using (var saea = new SocketAsyncEventArgs())
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => saea.SetBuffer(new byte[1], -1, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => saea.SetBuffer(new byte[1], 2, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => saea.SetBuffer(new byte[1], 0, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => saea.SetBuffer(new byte[1], 0, 2));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => saea.SetBuffer(new byte[1], 1, 2));
}
}
[Fact]
public void SetBuffer_NoBuffer_ResetsCountOffset()
{
using (var saea = new SocketAsyncEventArgs())
{
saea.SetBuffer(42, 84);
Assert.Equal(0, saea.Offset);
Assert.Equal(0, saea.Count);
saea.SetBuffer(new byte[3], 1, 2);
Assert.Equal(1, saea.Offset);
Assert.Equal(2, saea.Count);
saea.SetBuffer(null, 1, 2);
Assert.Equal(0, saea.Offset);
Assert.Equal(0, saea.Count);
}
}
[Fact]
public void SetBufferListWhenBufferSet_Throws()
{
using (var saea = new SocketAsyncEventArgs())
{
var bufferList = new List<ArraySegment<byte>> { new ArraySegment<byte>(new byte[1]) };
byte[] buffer = new byte[1];
saea.SetBuffer(buffer, 0, 1);
AssertExtensions.Throws<ArgumentException>(null, () => saea.BufferList = bufferList);
Assert.Same(buffer, saea.Buffer);
Assert.Null(saea.BufferList);
saea.SetBuffer(null, 0, 0);
saea.BufferList = bufferList; // works fine when Buffer has been set back to null
}
}
[Fact]
public void SetBufferWhenBufferListSet_Throws()
{
using (var saea = new SocketAsyncEventArgs())
{
var bufferList = new List<ArraySegment<byte>> { new ArraySegment<byte>(new byte[1]) };
saea.BufferList = bufferList;
AssertExtensions.Throws<ArgumentException>(null, () => saea.SetBuffer(new byte[1], 0, 1));
Assert.Same(bufferList, saea.BufferList);
Assert.Null(saea.Buffer);
saea.BufferList = null;
saea.SetBuffer(new byte[1], 0, 1); // works fine when BufferList has been set back to null
}
}
[Fact]
public void SetBufferListWhenBufferListSet_Succeeds()
{
using (var saea = new SocketAsyncEventArgs())
{
Assert.Null(saea.BufferList);
saea.BufferList = null;
Assert.Null(saea.BufferList);
var bufferList1 = new List<ArraySegment<byte>> { new ArraySegment<byte>(new byte[1]) };
saea.BufferList = bufferList1;
Assert.Same(bufferList1, saea.BufferList);
saea.BufferList = bufferList1;
Assert.Same(bufferList1, saea.BufferList);
var bufferList2 = new List<ArraySegment<byte>> { new ArraySegment<byte>(new byte[1]) };
saea.BufferList = bufferList2;
Assert.Same(bufferList2, saea.BufferList);
}
}
[Fact]
public void SetBufferWhenBufferSet_Succeeds()
{
using (var saea = new SocketAsyncEventArgs())
{
byte[] buffer1 = new byte[1];
saea.SetBuffer(buffer1, 0, buffer1.Length);
Assert.Same(buffer1, saea.Buffer);
saea.SetBuffer(buffer1, 0, buffer1.Length);
Assert.Same(buffer1, saea.Buffer);
byte[] buffer2 = new byte[1];
saea.SetBuffer(buffer2, 0, buffer1.Length);
Assert.Same(buffer2, saea.Buffer);
}
}
[Theory]
[InlineData(1, -1, 0)] // offset low
[InlineData(1, 2, 0)] // offset high
[InlineData(1, 0, -1)] // count low
[InlineData(1, 1, 2)] // count high
public void BufferList_InvalidArguments_Throws(int length, int offset, int count)
{
using (var e = new SocketAsyncEventArgs())
{
ArraySegment<byte> invalidBuffer = new FakeArraySegment { Array = new byte[length], Offset = offset, Count = count }.ToActual();
Assert.Throws<ArgumentOutOfRangeException>(() => e.BufferList = new List<ArraySegment<byte>> { invalidBuffer });
ArraySegment<byte> validBuffer = new ArraySegment<byte>(new byte[1]);
Assert.Throws<ArgumentOutOfRangeException>(() => e.BufferList = new List<ArraySegment<byte>> { validBuffer, invalidBuffer });
}
}
[Fact]
public async Task Completed_RegisterThenInvoked_UnregisterThenNotInvoked()
{
using (var listen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listen.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listen.Listen(1);
Task<Socket> acceptTask = listen.AcceptAsync();
await Task.WhenAll(
acceptTask,
client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listen.LocalEndPoint).Port)));
using (Socket server = await acceptTask)
using (var receiveSaea = new SocketAsyncEventArgs())
{
receiveSaea.SetBuffer(new byte[1], 0, 1);
TaskCompletionSource<bool> tcs1 = null, tcs2 = null;
EventHandler<SocketAsyncEventArgs> handler1 = (_, __) => tcs1.SetResult(true);
EventHandler<SocketAsyncEventArgs> handler2 = (_, __) => tcs2.SetResult(true);
receiveSaea.Completed += handler2;
receiveSaea.Completed += handler1;
tcs1 = new TaskCompletionSource<bool>();
tcs2 = new TaskCompletionSource<bool>();
Assert.True(client.ReceiveAsync(receiveSaea));
server.Send(new byte[1]);
await Task.WhenAll(tcs1.Task, tcs2.Task);
receiveSaea.Completed -= handler2;
tcs1 = new TaskCompletionSource<bool>();
tcs2 = new TaskCompletionSource<bool>();
Assert.True(client.ReceiveAsync(receiveSaea));
server.Send(new byte[1]);
await tcs1.Task;
Assert.False(tcs2.Task.IsCompleted);
}
}
}
[Fact]
public void CancelConnectAsync_InstanceConnect_CancelsInProgressConnect()
{
using (var listen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listen.Bind(new IPEndPoint(IPAddress.Loopback, 0));
using (var connectSaea = new SocketAsyncEventArgs())
{
var tcs = new TaskCompletionSource<SocketError>();
connectSaea.Completed += (s, e) => tcs.SetResult(e.SocketError);
connectSaea.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listen.LocalEndPoint).Port);
Assert.True(client.ConnectAsync(connectSaea), $"ConnectAsync completed synchronously with SocketError == {connectSaea.SocketError}");
if (tcs.Task.IsCompleted)
{
Assert.NotEqual(SocketError.Success, tcs.Task.Result);
}
Socket.CancelConnectAsync(connectSaea);
Assert.False(client.Connected, "Expected Connected to be false");
}
}
}
[Fact]
public void CancelConnectAsync_StaticConnect_CancelsInProgressConnect()
{
using (var listen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listen.Bind(new IPEndPoint(IPAddress.Loopback, 0));
using (var connectSaea = new SocketAsyncEventArgs())
{
var tcs = new TaskCompletionSource<SocketError>();
connectSaea.Completed += (s, e) => tcs.SetResult(e.SocketError);
connectSaea.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listen.LocalEndPoint).Port);
bool pending = Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, connectSaea);
if (!pending) tcs.SetResult(connectSaea.SocketError);
if (tcs.Task.IsCompleted)
{
Assert.NotEqual(SocketError.Success, tcs.Task.Result);
}
Socket.CancelConnectAsync(connectSaea);
}
}
}
[Fact]
public async Task ReuseSocketAsyncEventArgs_SameInstance_MultipleSockets()
{
using (var listen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listen.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listen.Listen(1);
Task<Socket> acceptTask = listen.AcceptAsync();
await Task.WhenAll(
acceptTask,
client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listen.LocalEndPoint).Port)));
using (Socket server = await acceptTask)
{
TaskCompletionSource<bool> tcs = null;
var args = new SocketAsyncEventArgs();
args.SetBuffer(new byte[1024], 0, 1024);
args.Completed += (_,__) => tcs.SetResult(true);
for (int i = 1; i <= 10; i++)
{
tcs = new TaskCompletionSource<bool>();
args.Buffer[0] = (byte)i;
args.SetBuffer(0, 1);
if (server.SendAsync(args))
{
await tcs.Task;
}
args.Buffer[0] = 0;
tcs = new TaskCompletionSource<bool>();
if (client.ReceiveAsync(args))
{
await tcs.Task;
}
Assert.Equal(1, args.BytesTransferred);
Assert.Equal(i, args.Buffer[0]);
}
}
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task ReuseSocketAsyncEventArgs_MutateBufferList()
{
using (var listen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listen.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listen.Listen(1);
Task<Socket> acceptTask = listen.AcceptAsync();
await Task.WhenAll(
acceptTask,
client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listen.LocalEndPoint).Port)));
using (Socket server = await acceptTask)
{
TaskCompletionSource<bool> tcs = null;
var sendBuffer = new byte[64];
var sendBufferList = new List<ArraySegment<byte>>();
sendBufferList.Add(new ArraySegment<byte>(sendBuffer, 0, 1));
var sendArgs = new SocketAsyncEventArgs();
sendArgs.BufferList = sendBufferList;
sendArgs.Completed += (_,__) => tcs.SetResult(true);
var recvBuffer = new byte[64];
var recvBufferList = new List<ArraySegment<byte>>();
recvBufferList.Add(new ArraySegment<byte>(recvBuffer, 0, 1));
var recvArgs = new SocketAsyncEventArgs();
recvArgs.BufferList = recvBufferList;
recvArgs.Completed += (_,__) => tcs.SetResult(true);
for (int i = 1; i <= 10; i++)
{
tcs = new TaskCompletionSource<bool>();
sendBuffer[0] = (byte)i;
if (server.SendAsync(sendArgs))
{
await tcs.Task;
}
recvBuffer[0] = 0;
tcs = new TaskCompletionSource<bool>();
if (client.ReceiveAsync(recvArgs))
{
await tcs.Task;
}
Assert.Equal(1, recvArgs.BytesTransferred);
Assert.Equal(i, recvBuffer[0]);
// Mutate the send/recv BufferLists
// This should not affect Send or Receive behavior, since the buffer list is cached
// at the time it is set.
sendBufferList[0] = new ArraySegment<byte>(sendBuffer, i, 1);
sendBufferList.Insert(0, new ArraySegment<byte>(sendBuffer, i * 2, 1));
recvBufferList[0] = new ArraySegment<byte>(recvBuffer, i, 1);
recvBufferList.Add(new ArraySegment<byte>(recvBuffer, i * 2, 1));
}
}
}
}
public void OnAcceptCompleted(object sender, SocketAsyncEventArgs args)
{
EventWaitHandle handle = (EventWaitHandle)args.UserToken;
handle.Set();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Unix platforms don't yet support receiving data with AcceptAsync.
public void AcceptAsync_WithReceiveBuffer_Success()
{
Assert.True(Capability.IPv4Support());
AutoResetEvent accepted = new AutoResetEvent(false);
using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
int port = server.BindToAnonymousPort(IPAddress.Loopback);
server.Listen(1);
const int acceptBufferOverheadSize = 288; // see https://msdn.microsoft.com/en-us/library/system.net.sockets.socket.acceptasync(v=vs.110).aspx
const int acceptBufferDataSize = 256;
const int acceptBufferSize = acceptBufferOverheadSize + acceptBufferDataSize;
byte[] sendBuffer = new byte[acceptBufferDataSize];
new Random().NextBytes(sendBuffer);
SocketAsyncEventArgs acceptArgs = new SocketAsyncEventArgs();
acceptArgs.Completed += OnAcceptCompleted;
acceptArgs.UserToken = accepted;
acceptArgs.SetBuffer(new byte[acceptBufferSize], 0, acceptBufferSize);
Assert.True(server.AcceptAsync(acceptArgs));
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
client.Connect(IPAddress.Loopback, port);
client.Send(sendBuffer);
client.Shutdown(SocketShutdown.Both);
}
Assert.True(
accepted.WaitOne(TestSettings.PassingTestTimeout), "Test completed in allotted time");
Assert.Equal(
SocketError.Success, acceptArgs.SocketError);
Assert.Equal(
acceptBufferDataSize, acceptArgs.BytesTransferred);
Assert.Equal(
new ArraySegment<byte>(sendBuffer),
new ArraySegment<byte>(acceptArgs.Buffer, 0, acceptArgs.BytesTransferred));
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Unix platforms don't yet support receiving data with AcceptAsync.
public void AcceptAsync_WithTooSmallReceiveBuffer_Failure()
{
using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
int port = server.BindToAnonymousPort(IPAddress.Loopback);
server.Listen(1);
SocketAsyncEventArgs acceptArgs = new SocketAsyncEventArgs();
acceptArgs.Completed += OnAcceptCompleted;
acceptArgs.UserToken = new ManualResetEvent(false);
byte[] buffer = new byte[1];
acceptArgs.SetBuffer(buffer, 0, buffer.Length);
AssertExtensions.Throws<ArgumentException>(null, () => server.AcceptAsync(acceptArgs));
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Unix platforms don't yet support receiving data with AcceptAsync.
public void AcceptAsync_WithReceiveBuffer_Failure()
{
Assert.True(Capability.IPv4Support());
using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
int port = server.BindToAnonymousPort(IPAddress.Loopback);
server.Listen(1);
SocketAsyncEventArgs acceptArgs = new SocketAsyncEventArgs();
acceptArgs.Completed += OnAcceptCompleted;
acceptArgs.UserToken = new ManualResetEvent(false);
byte[] buffer = new byte[1024];
acceptArgs.SetBuffer(buffer, 0, buffer.Length);
Assert.Throws<PlatformNotSupportedException>(() => server.AcceptAsync(acceptArgs));
}
}
}
}
| |
/*
* Naiad ver. 0.5
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR
* A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Research.Naiad.Scheduling;
using Microsoft.Research.Naiad.Frameworks;
using System.Collections.Concurrent;
using Microsoft.Research.Naiad.Serialization;
using System.Diagnostics;
using Microsoft.Research.Naiad.Dataflow;
using Microsoft.Research.Naiad.Diagnostics;
using Microsoft.Research.Naiad.Runtime.Networking;
using Microsoft.Research.Naiad.Runtime.Controlling;
using Microsoft.Research.Naiad.Runtime.Progress;
namespace Microsoft.Research.Naiad.Dataflow.Channels
{
internal class ProgressChannel : Cable<Update, Empty>
{
private class Mailbox : Mailbox<Update, Empty>//, UntypedMailbox
{
private readonly PostOffice postOffice;
private readonly Runtime.Progress.ProgressUpdateConsumer consumer;
private readonly int id;
private readonly int vertexId;
private readonly int graphid;
public int GraphId { get { return this.graphid; } }
public int ChannelId { get { return this.id; } }
public int VertexId { get { return this.vertexId; } }
public int ThreadIndex { get { return this.consumer.scheduler.Index; } }
private readonly AutoSerializedMessageDecoder<Update, Empty> decoder;
private int[] nextSequenceNumbers;
public void DeliverSerializedMessage(SerializedMessage message, ReturnAddress from)
{
lock (this)
{
if (true) //(message.Header.SequenceNumber == this.nextSequenceNumbers[from.VertexID])
{
//Console.Error.WriteLine("Delivering message {0} L = {1} A = {2}", message.Header.SequenceNumber, message.Header.Length, message.Body.Available);
//foreach (Pair<Int64, Pointstamp> currentRecord in this.decoder.Elements(message))
// Console.Error.WriteLine("-- {0}", currentRecord);
//this.nextSequenceNumber++;
this.nextSequenceNumbers[from.VertexID]++;
foreach (var typedMessage in this.decoder.AsTypedMessages(message))
{
this.consumer.ProcessCountChange(typedMessage);
typedMessage.Release(AllocationReason.Deserializer);
}
this.RequestFlush(from);
}
else
{
//Console.Error.WriteLine("Discarding message {0} (expecting {1}) L = {2} A = {3}", message.Header.SequenceNumber, this.nextSequenceNumber, message.Header.Length, message.Body.Available);
//foreach (Pair<Int64, Pointstamp> currentRecord in this.decoder.Elements(message))
// Console.Error.WriteLine("-- {0}", currentRecord);
}
}
}
internal long recordsReceived = 0;
public void Send(Message<Update, Empty> message, ReturnAddress from)
{
this.recordsReceived += message.length;
this.consumer.scheduler.statistics[(int)RuntimeStatistic.ProgressLocalRecords] += message.length;
this.consumer.ProcessCountChange(message);
}
public void Drain() { }
public void RequestFlush(ReturnAddress from) { }
public Mailbox(PostOffice postOffice, Runtime.Progress.ProgressUpdateConsumer consumer, int id, int vertexId, int numProducers)
{
this.postOffice = postOffice;
this.consumer = consumer;
this.graphid = this.consumer.Stage.InternalComputation.Index;
this.id = id;
this.vertexId = vertexId;
this.nextSequenceNumbers = new int[numProducers];
this.decoder = new AutoSerializedMessageDecoder<Update, Empty>(consumer.SerializationFormat);
}
}
private class Fiber : SendChannel<Update, Empty>
{
private readonly NetworkChannel networkChannel;
private readonly int channelID;
private readonly int vertexID;
private readonly VertexOutput<Update, Empty> sender;
private readonly ProgressChannel.Mailbox localMailbox;
private readonly int numProcesses;
private readonly int processId;
private AutoSerializedMessageEncoder<Update, Empty> encoder;
public Fiber(int channelID, int vertexID, VertexOutput<Update, Empty> sender, ProgressChannel.Mailbox localMailbox, InternalController controller)
{
this.processId = controller.Configuration.ProcessID;
this.channelID = channelID;
this.vertexID = vertexID;
this.sender = sender;
this.localMailbox = localMailbox;
this.networkChannel = controller.NetworkChannel;
this.numProcesses = controller.Configuration.Processes;
int processID = controller.Configuration.ProcessID;
if (this.networkChannel != null)
{
this.encoder = new AutoSerializedMessageEncoder<Update, Empty>(-1, this.sender.Vertex.Stage.InternalComputation.Index << 16 | this.channelID, this.networkChannel.GetBufferPool(-1, -1), this.networkChannel.SendPageSize, controller.SerializationFormat, SerializedMessageType.Data, () => this.GetNextSequenceNumber());
this.encoder.CompletedMessage += (o, a) => { this.BroadcastPageContents(a.Hdr, a.Segment); /* Console.WriteLine("Sending progress message"); */};
}
}
private int nextSequenceNumber = 0;
public int GetNextSequenceNumber()
{
return nextSequenceNumber++;
}
public void Send(Message<Update, Empty> records)
{
if (this.networkChannel != null)
this.encoder.Write(new ArraySegment<Update>(records.payload, 0, records.length), this.vertexID);
this.localMailbox.Send(records, new ReturnAddress());
}
internal long bytesSent = 0;
internal long messagesSent = 0;
private void BroadcastPageContents(MessageHeader hdr, BufferSegment segment)
{
var nmsgs = this.networkChannel.BroadcastBufferSegment(hdr, segment);
this.bytesSent += nmsgs * segment.Length;
this.messagesSent += nmsgs;
var s = sender.Vertex.scheduler;
s.statistics[(int)RuntimeStatistic.TxProgressMessages] += nmsgs;
s.statistics[(int)RuntimeStatistic.TxProgressBytes] += nmsgs * segment.Length;
}
public void Flush()
{
if (this.networkChannel != null)
{
this.encoder.Flush();
}
}
}
private readonly int channelID;
public int ChannelId { get { return channelID; } }
private readonly StageOutput<Update, Empty> sendBundle;
private readonly StageInput<Update, Empty> recvBundle;
private readonly Dictionary<int, Fiber> postboxes;
private readonly Mailbox mailbox;
public ProgressChannel(int producerPlacementCount,
ProgressUpdateConsumer consumerVertex,
StageOutput<Update, Empty> stream,
StageInput<Update, Empty> recvPort,
InternalController controller,
int channelId)
{
this.sendBundle = stream;
this.recvBundle = recvPort;
this.channelID = channelId;
var computation = sendBundle.ForStage.InternalComputation;
var recvFiber = this.recvBundle.GetPin(computation.Controller.Configuration.ProcessID);
this.mailbox = new Mailbox(recvFiber.Vertex.Scheduler.State(computation).PostOffice, consumerVertex, this.channelID, consumerVertex.VertexId, producerPlacementCount);
// recvFiber.Vertex.Scheduler.State(graphManager).PostOffice.RegisterMailbox(this.mailbox);
this.postboxes = new Dictionary<int, Fiber>();
foreach (VertexLocation loc in sendBundle.ForStage.Placement)
if (loc.ProcessId == controller.Configuration.ProcessID)
this.postboxes[loc.VertexId] = new Fiber(this.channelID, loc.VertexId, this.sendBundle.GetFiber(loc.VertexId), this.mailbox, controller);
if (controller.NetworkChannel != null)
controller.NetworkChannel.RegisterMailbox(this.mailbox);
Logging.Info("Allocated progress channel [{0}]: {1} -> {2}", this.channelID, sendBundle, recvBundle);
NaiadTracing.Trace.ChannelInfo(ChannelId, SourceStage.StageId, DestinationStage.StageId, true, true);
}
public Dataflow.Stage SourceStage { get { return this.sendBundle.ForStage; } }
public Dataflow.Stage DestinationStage { get { return this.recvBundle.ForStage; } }
public SendChannel<Update, Empty> GetSendChannel(int i)
{
return this.postboxes[i];
}
internal long TotalBytesSent { get { return this.postboxes.Values.Sum(x => x.bytesSent); } }
internal long TotalMessagesSent { get { return this.postboxes.Values.Sum(x => x.messagesSent); } }
internal long TotalRecordsReceived { get { return this.mailbox.recordsReceived; } }
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using bv.common.Core;
using bv.model.BLToolkit;
using DevExpress.XtraReports.UI;
using eidss.model.Reports;
using eidss.model.Reports.AZ;
using eidss.model.Reports.Common;
using EIDSS.Reports.BaseControls.Report;
using EIDSS.Reports.Factory;
using EIDSS.Reports.Parameterized.Human.AJ.DataSets;
namespace EIDSS.Reports.Parameterized.Human.AJ.Reports
{
[CanWorkWithArchive]
public sealed partial class TuberculosisCasesTestedReport : BaseReport
{
private readonly Dictionary<XRTableCell, IList<XRTableCell>> m_HeaderCellDictionary;
public TuberculosisCasesTestedReport()
{
InitializeComponent();
m_HeaderCellDictionary = CreateHeaderCellDictionary();
}
public void SetParameters(TuberculosisSurrogateModel model, DbManagerProxy manager, DbManagerProxy archiveManager)
{
Utils.CheckNotNull(model, "model");
Utils.CheckNotNullOrEmpty(model.Language, "lang");
if (model.YearCheckedItems == null || model.YearCheckedItems.Length == 0)
{
model.YearCheckedItems = new[] {"2000"};
}
ShowWarningIfDataInArchive(manager, new DateTime(model.MinYear, 1, 1), model.UseArchive);
SetLanguage(model, manager);
DateTimeCell.Text = ReportRebinder.ToDateTimeString(DateTime.Now);
SetHeaderYears(model);
RemoveUnusedCells(model);
TuberculosisCasesTestedDataSet.TuberculosisTableDataTable table = m_DataSet.TuberculosisTable;
Action<SqlConnection, SqlTransaction> action = ((connection, transaction) =>
{
m_Adapter.Connection = connection;
m_Adapter.Transaction = transaction;
m_Adapter.CommandTimeout = CommandTimeout;
m_DataSet.EnforceConstraints = false;
m_Adapter.Fill(table,
model.Language,
model.YearsToXml(), model.StartMonth, model.EndMonth,
model.DiagnosisId,
model.SiteId);
});
FillDataTableWithArchive(action,
manager, archiveManager,
table,
model.Mode,
new[] {"idfsRayon"},
new[] {"blnIsTransportCHE", "intRegionOrder"});
CalculatePercent(table);
string diagnosis = TuberculosisLabel.Text;
if (table.Count > 0 && model.DiagnosisId.HasValue)
{
diagnosis = table[0].strDiagnosisName;
}
BindReportHeader(model, diagnosis);
ReportRtlHelper.SetRTL(this);
}
private void CalculatePercent(IEnumerable<TuberculosisCasesTestedDataSet.TuberculosisTableRow> table)
{
const int diagnosisCount = 5;
var totalTested = new int[diagnosisCount];
var totalNumber = new int[diagnosisCount];
foreach (TuberculosisCasesTestedDataSet.TuberculosisTableRow row in table)
{
if (row.IsintNumberOfCases_1Null() || row.intNumberOfCases_1 == 0)
{
row.SetintPercentRegistered_1Null();
}
else
{
row.intPercentRegistered_1 = (double) row.intTestedForHIV_1 / row.intNumberOfCases_1;
totalTested[0] += row.intTestedForHIV_1;
totalNumber[0] += row.intNumberOfCases_1;
}
if (row.IsintNumberOfCases_2Null() || row.intNumberOfCases_2 == 0)
{
row.SetintPercentRegistered_2Null();
}
else
{
row.intPercentRegistered_2 = (double) row.intTestedForHIV_2 / row.intNumberOfCases_2;
totalTested[1] += row.intTestedForHIV_2;
totalNumber[1] += row.intNumberOfCases_2;
}
if (row.IsintNumberOfCases_3Null() || row.intNumberOfCases_3 == 0)
{
row.SetintPercentRegistered_3Null();
}
else
{
row.intPercentRegistered_3 = (double) row.intTestedForHIV_3 / row.intNumberOfCases_3;
totalTested[2] += row.intTestedForHIV_3;
totalNumber[2] += row.intNumberOfCases_3;
}
if (row.IsintNumberOfCases_4Null() || row.intNumberOfCases_4 == 0)
{
row.SetintPercentRegistered_4Null();
}
else
{
row.intPercentRegistered_4 = (double) row.intTestedForHIV_4 / row.intNumberOfCases_4;
totalTested[3] += row.intTestedForHIV_4;
totalNumber[3] += row.intNumberOfCases_4;
}
if (row.IsintNumberOfCases_5Null() || row.intNumberOfCases_5 == 0)
{
row.SetintPercentRegistered_5Null();
}
else
{
row.intPercentRegistered_5 = (double) row.intTestedForHIV_5 / row.intNumberOfCases_5;
totalTested[4] += row.intTestedForHIV_5;
totalNumber[4] += row.intNumberOfCases_5;
}
}
if (totalNumber[0] != 0)
{
TotalPercentCell1.Text = string.Format("{0:P2}", (double) totalTested[0] / totalNumber[0]);
}
if (totalNumber[1] != 0)
{
TotalPercentCell2.Text = string.Format("{0:P2}", (double)totalTested[1] / totalNumber[1]);
}
if (totalNumber[2] != 0)
{
TotalPercentCell3.Text = string.Format("{0:P2}", (double)totalTested[2] / totalNumber[2]);
}
if (totalNumber[3] != 0)
{
TotalPercentCell4.Text = string.Format("{0:P2}", (double)totalTested[3] / totalNumber[3]);
}
if (totalNumber[4] != 0)
{
TotalPercentCell5.Text = string.Format("{0:P2}", (double)totalTested[4] / totalNumber[4]);
}
}
private void BindReportHeader(TuberculosisSurrogateModel model, string diagnosis)
{
Utils.CheckNotNull(model, "model");
string monthRange = string.Empty;
if (model.StartMonth.HasValue && model.EndMonth.HasValue)
{
List<ItemWrapper> monthCollection = FilterHelper.GetWinMonthList();
monthRange = model.StartMonth == model.EndMonth
? monthCollection[model.StartMonth.Value - 1].ToString()
: string.Format("{0} - {1}", monthCollection[model.StartMonth.Value - 1], monthCollection[model.EndMonth.Value - 1]);
}
FirstHeaderCell.Text = string.Format(FirstHeaderCell.Text, diagnosis);
SecondHeaderCell.Text = string.Format(SecondHeaderCell.Text, model.YearsToString(), monthRange);
}
private void SetHeaderYears(TuberculosisSurrogateModel model)
{
XRTableCell[] headerCells = m_HeaderCellDictionary.Keys.ToArray();
int realYearsCount = Math.Min(headerCells.Length, model.YearCheckedItems.Length);
for (int i = 0; i < realYearsCount; i++)
{
headerCells[realYearsCount - i - 1].Text = model.YearCheckedItems[i];
}
}
private void RemoveUnusedCells(TuberculosisSurrogateModel model)
{
HeaderTable.BeginInit();
DetailTable.BeginInit();
for (int i = m_HeaderCellDictionary.Count - 1; i >= model.YearCheckedItems.Length; i--)
{
KeyValuePair<XRTableCell, IList<XRTableCell>> pair = m_HeaderCellDictionary.ElementAt(i);
foreach (XRTableCell dependedCell in pair.Value)
{
if (dependedCell.Row != null)
{
dependedCell.Row.Cells.Remove(dependedCell);
}
}
XRTableCell keyCell = pair.Key;
if (keyCell.Row != null)
{
keyCell.Row.Cells.Remove(keyCell);
}
}
DetailTable.EndInit();
HeaderTable.EndInit();
}
private Dictionary<XRTableCell, IList<XRTableCell>> CreateHeaderCellDictionary()
{
var headerCellDictionary = new Dictionary<XRTableCell, IList<XRTableCell>>
{
{
HeaderYearCell1, new List<XRTableCell>
{
HeaderCasesCell1,
HeaderTestedCell1,
HeaderPercentCell1,
CasesCell1,
TestedCell1,
PercentCell1,
TotalCasesCell1,
TotalTestedCell1,
TotalPercentCell1
}
},
{
HeaderYearCell2, new List<XRTableCell>
{
HeaderCasesCell2,
HeaderTestedCell2,
HeaderPercentCell2,
CasesCell2,
TestedCell2,
PercentCell2,
TotalCasesCell2,
TotalTestedCell2,
TotalPercentCell2,
}
},
{
HeaderYearCell3, new List<XRTableCell>
{
HeaderCasesCell3,
HeaderTestedCell3,
HeaderPercentCell3,
CasesCell3,
TestedCell3,
PercentCell3,
TotalCasesCell3,
TotalTestedCell3,
TotalPercentCell3,
}
},
{
HeaderYearCell4, new List<XRTableCell>
{
HeaderCasesCell4,
HeaderTestedCell4,
HeaderPercentCell4,
CasesCell4,
TestedCell4,
PercentCell4,
TotalCasesCell4,
TotalTestedCell4,
TotalPercentCell4,
}
},
{
HeaderYearCell5, new List<XRTableCell>
{
HeaderCasesCell5,
HeaderTestedCell5,
HeaderPercentCell5,
CasesCell5,
TestedCell5,
PercentCell5,
TotalCasesCell5,
TotalTestedCell5,
TotalPercentCell5,
}
}
};
return headerCellDictionary;
}
// private void TotalPercentCell_SummaryReset(object sender, EventArgs e)
// {
// int n = int.Parse(((XRTableCell) sender).Tag.ToString());
// m_TotalTested[n] = 0;
// m_TotalNumber[n] = 0;
// }
//
// private void TotalPercentCell_SummaryRowChanged(object sender, EventArgs e)
// {
// int n = int.Parse(((XRTableCell) sender).Tag.ToString());
// m_TotalTested[n] += Convert.ToInt32(GetCurrentColumnValue(String.Format("intTestedForHIV_{0}", n + 1)));
// m_TotalNumber[n] += Convert.ToInt32(GetCurrentColumnValue(String.Format("intNumberOfCases_{0}", n + 1)));
// }
//
// private void TotalPercentCell_SummaryGetResult(object sender, SummaryGetResultEventArgs e)
// {
// int n = int.Parse(((XRTableCell) sender).Tag.ToString());
// e.Result = m_TotalNumber[n] == 0
// ? (object) ""
// : (double) m_TotalTested[n] / m_TotalNumber[n];
// e.Handled = true;
// }
// private void PercentCell_BeforePrint(object sender, PrintEventArgs e)
// {
// if (string.IsNullOrEmpty(((XRTableCell) sender).Text))
// {
// ((XRTableCell) sender).Text = "";
// }
// }
}
}
| |
// *****************************************************************************
//
// Copyright 2004, Weifen Luo
// All rights reserved. The software and associated documentation
// supplied hereunder are the proprietary information of Weifen Luo
// and are supplied subject to licence terms.
//
// WinFormsUI Library Version 1.0
// *****************************************************************************
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Windows.Forms;
using System.ComponentModel;
namespace SoftLogik.Win.UI.Docking
{
[ToolboxItem(false)]
public class PopupButton : Button
{
private enum RepeatClickStatus : int
{
Disabled,
Started,
Repeating,
Stopped
}
private class RepeatClickEventArgs : System.EventArgs
{
private static RepeatClickEventArgs _empty;
static RepeatClickEventArgs()
{
_empty = new RepeatClickEventArgs();
}
public static new RepeatClickEventArgs Empty
{
get
{
return _empty;
}
}
}
#region Private fields
private IContainer components = new Container();
private bool m_isActivated = false;
private int m_borderWidth = 1;
private bool m_mouseOver = false;
private bool m_mouseCapture = false;
private bool m_isPopup = false;
private Image m_imageEnabled = null;
private Image m_imageDisabled = null;
private int m_imageIndexEnabled = -1;
private int m_imageIndexDisabled = -1;
private bool m_monochrom = true;
private ToolTip m_toolTip = null;
private string m_toolTipText = "";
private Color m_borderColor = Color.Empty;
private Color m_activeGradientBegin = Color.Empty;
private Color m_activeGradientEnd = Color.Empty;
private Color m_inactiveGradientBegin = Color.Empty;
private Color m_inactiveGradientEnd = Color.Empty;
private RepeatClickStatus m_clickStatus = RepeatClickStatus.Disabled;
private int m_repeatClickDelay = 500;
private int m_repeatClickInterval = 100;
private Timer m_timer;
#endregion
#region Public Methods
public PopupButton()
{
InternalConstruct(null, null);
}
public PopupButton(Image c_imageEnabled)
{
InternalConstruct(c_imageEnabled, null);
}
public PopupButton(Image c_imageEnabled, Image c_imageDisabled)
{
InternalConstruct(c_imageEnabled, c_imageDisabled);
}
#endregion
#region Private Methods
private void InternalConstruct(Image c_imageEnabled, Image c_imageDisabled)
{
// Remember parameters
this.ImageEnabled = c_imageEnabled;
this.ImageDisabled = c_imageDisabled;
// Prevent drawing flicker by blitting from memory in WM_PAINT
SetStyle(ControlStyles.ResizeRedraw, true);
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
// Prevent base class from trying to generate double click events and
// so testing clicks against the double click time and rectangle. Getting
// rid of this allows the user to press then release button very quickly.
//SetStyle(ControlStyles.StandardDoubleClick, false);
// Should not be allowed to select this control
SetStyle(ControlStyles.Selectable, false);
m_timer = new Timer();
m_timer.Enabled = false;
m_timer.Tick += new System.EventHandler(Timer_Tick);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
private bool ShouldSerializeBorderColor()
{
return (m_borderColor != Color.Empty);
}
private bool ShouldSerializeImageEnabled()
{
return (m_imageEnabled != null);
}
private bool ShouldSerializeImageDisabled()
{
return (m_imageDisabled != null);
}
private void DrawBackground(Graphics g)
{
if (m_mouseOver)
{
if (m_isActivated)
{
using (LinearGradientBrush brush = new LinearGradientBrush(ClientRectangle, Color.FromArgb(156, 182, 231), Color.FromArgb(156, 182, 231), LinearGradientMode.Vertical))
{
g.FillRectangle(brush, ClientRectangle);
}
}
else
{
using (LinearGradientBrush brush = new LinearGradientBrush(ClientRectangle, Color.FromArgb(236, 233, 216), Color.FromArgb(236, 233, 216), LinearGradientMode.Vertical))
{
g.FillRectangle(brush, ClientRectangle);
}
}
}
else
{
if (m_isActivated)
{
using (LinearGradientBrush brush = new LinearGradientBrush(ClientRectangle, ActiveBackColorGradientBegin, ActiveBackColorGradientEnd, LinearGradientMode.Vertical))
{
g.FillRectangle(brush, ClientRectangle);
}
}
else
{
using (LinearGradientBrush brush = new LinearGradientBrush(ClientRectangle, InactiveBackColorGradientBegin, InactiveBackColorGradientEnd, LinearGradientMode.Vertical))
{
g.FillRectangle(brush, ClientRectangle);
}
}
}
}
private void DrawImage(Graphics g)
{
Image image = null;
if (this.Enabled)
{
image = this.ImageEnabled;
}
else
{
if (ImageDisabled != null)
{
image = this.ImageDisabled;
}
else
{
image = this.ImageEnabled;
}
}
ImageAttributes imageAttr = null;
if (image == null)
{
return;
}
if (m_monochrom)
{
imageAttr = new ImageAttributes();
// transform the monochrom image
// white -> BackColor
// black -> ForeColor
ColorMap[] myColorMap = new ColorMap[2];
myColorMap[0] = new ColorMap();
myColorMap[0].OldColor = Color.White;
myColorMap[0].NewColor = Color.Transparent;
myColorMap[1] = new ColorMap();
myColorMap[1].OldColor = Color.Black;
myColorMap[1].NewColor = this.ForeColor;
imageAttr.SetRemapTable(myColorMap);
}
Rectangle rect = new Rectangle(0, 0, image.Width, image.Height);
if ((! Enabled) && (ImageDisabled == null))
{
using (Bitmap bitmapMono = new Bitmap(image, ClientRectangle.Size))
{
if (imageAttr != null)
{
using (Graphics gMono = Graphics.FromImage(bitmapMono))
{
gMono.DrawImage(image, new Point[3] {new Point(0, 0), new Point(image.Width - 1, 0), new Point(0, image.Height - 1)}, rect, GraphicsUnit.Pixel, imageAttr);
}
}
ControlPaint.DrawImageDisabled(g, bitmapMono, 0, 0, this.BackColor);
}
}
else
{
// Three points provided are upper-left, upper-right and
// lower-left of the destination parallelogram.
Point[] pts = new Point[3];
if (Enabled && m_mouseOver && m_mouseCapture)
{
pts[0].X = 1;
pts[0].Y = 1;
}
else
{
pts[0].X = 0;
pts[0].Y = 0;
}
pts[1].X = pts[0].X + ClientRectangle.Width;
pts[1].Y = pts[0].Y;
pts[2].X = pts[0].X;
pts[2].Y = pts[1].Y + ClientRectangle.Height;
if (imageAttr == null)
{
g.DrawImage(image, pts, rect, GraphicsUnit.Pixel);
}
else
{
g.DrawImage(image, pts, rect, GraphicsUnit.Pixel, imageAttr);
}
}
}
private void DrawText(Graphics g)
{
if (Text == string.Empty)
{
return;
}
Rectangle rect = ClientRectangle;
rect.X += BorderWidth;
rect.Y += BorderWidth;
rect.Width -= 2 * BorderWidth;
rect.Height -= 2 * BorderWidth;
StringFormat stringFormat = new StringFormat();
if (TextAlign == ContentAlignment.TopLeft)
{
stringFormat.Alignment = StringAlignment.Near;
stringFormat.LineAlignment = StringAlignment.Near;
}
else if (TextAlign == ContentAlignment.TopCenter)
{
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Near;
}
else if (TextAlign == ContentAlignment.TopRight)
{
stringFormat.Alignment = StringAlignment.Far;
stringFormat.LineAlignment = StringAlignment.Near;
}
else if (TextAlign == ContentAlignment.MiddleLeft)
{
stringFormat.Alignment = StringAlignment.Near;
stringFormat.LineAlignment = StringAlignment.Center;
}
else if (TextAlign == ContentAlignment.MiddleCenter)
{
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Center;
}
else if (TextAlign == ContentAlignment.MiddleRight)
{
stringFormat.Alignment = StringAlignment.Far;
stringFormat.LineAlignment = StringAlignment.Center;
}
else if (TextAlign == ContentAlignment.BottomLeft)
{
stringFormat.Alignment = StringAlignment.Near;
stringFormat.LineAlignment = StringAlignment.Far;
}
else if (TextAlign == ContentAlignment.BottomCenter)
{
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Far;
}
else if (TextAlign == ContentAlignment.BottomRight)
{
stringFormat.Alignment = StringAlignment.Far;
stringFormat.LineAlignment = StringAlignment.Far;
}
using (Brush brush = new SolidBrush(ForeColor))
{
g.DrawString(Text, Font, brush, rect, stringFormat);
}
}
private void DrawBorder(Graphics g)
{
ButtonBorderStyle bs = 0;
// Decide on the type of border to draw around image
if (! this.Enabled)
{
if (IsPopup)
{
bs = ButtonBorderStyle.Outset;
}
else
{
bs = ButtonBorderStyle.Solid;
}
}
else if (m_mouseOver && m_mouseCapture)
{
bs = ButtonBorderStyle.Inset;
}
else if (IsPopup || m_mouseOver)
{
if (m_isActivated)
{
BorderColor = Color.FromArgb(60, 90, 170);
}
else
{
BorderColor = Color.FromArgb(140, 134, 123);
}
bs = ButtonBorderStyle.Solid;
}
else
{
bs = ButtonBorderStyle.Solid;
}
Color colorLeftTop = new Color();
Color colorRightBottom = new Color();
if (bs == ButtonBorderStyle.Solid)
{
colorLeftTop = this.BorderColor;
colorRightBottom = this.BorderColor;
}
else if (bs == ButtonBorderStyle.Outset)
{
if (m_borderColor.IsEmpty)
{
colorLeftTop = this.BackColor;
}
else
{
colorLeftTop = m_borderColor;
}
colorRightBottom = this.BackColor;
}
else
{
colorLeftTop = this.BackColor;
if (m_borderColor.IsEmpty)
{
colorRightBottom = this.BackColor;
}
else
{
colorRightBottom = m_borderColor;
}
}
ControlPaint.DrawBorder(g, ClientRectangle, colorLeftTop, m_borderWidth, bs, colorLeftTop, m_borderWidth, bs, colorRightBottom, m_borderWidth, bs, colorRightBottom, m_borderWidth, bs);
}
#endregion
#region Properties
public bool IsActivated
{
get
{
return m_isActivated;
}
set
{
m_isActivated = value;
}
}
[Category("Appearance")]
public System.Drawing.Color ActiveBackColorGradientBegin
{
get
{
return m_activeGradientBegin;
}
set
{
m_activeGradientBegin = value;
}
}
[Category("Appearance")]
public System.Drawing.Color ActiveBackColorGradientEnd
{
get
{
return m_activeGradientEnd;
}
set
{
m_activeGradientEnd = value;
}
}
[Category("Appearance")]
public System.Drawing.Color InactiveBackColorGradientBegin
{
get
{
return m_inactiveGradientBegin;
}
set
{
m_inactiveGradientBegin = value;
}
}
[Category("Appearance")]
public System.Drawing.Color InactiveBackColorGradientEnd
{
get
{
return m_inactiveGradientEnd;
}
set
{
m_inactiveGradientEnd = value;
}
}
[Category("Appearance")]
public Color BorderColor
{
get
{
return m_borderColor;
}
set
{
if (m_borderColor != value)
{
m_borderColor = value;
Invalidate();
}
}
}
[Category("Appearance"), DefaultValue(1)]
public int BorderWidth
{
get
{
return m_borderWidth;
}
set
{
if (value < 1)
{
value = 1;
}
if (m_borderWidth != value)
{
m_borderWidth = value;
Invalidate();
}
}
}
[Category("Appearance")]
public Image ImageEnabled
{
get
{
if (m_imageEnabled != null)
{
return m_imageEnabled;
}
try
{
if (ImageList == null || ImageIndexEnabled == -1)
{
return null;
}
else
{
return ImageList.Images[m_imageIndexEnabled];
}
}
catch
{
return null;
}
}
set
{
if (value != m_imageEnabled)
{
m_imageEnabled = value;
Invalidate();
}
}
}
[Category("Appearance")]
public Image ImageDisabled
{
get
{
if (m_imageDisabled != null)
{
return m_imageDisabled;
}
try
{
if (ImageList == null || ImageIndexDisabled == -1)
{
return null;
}
else
{
return ImageList.Images[m_imageIndexDisabled];
}
}
catch
{
return null;
}
}
set
{
if (m_imageDisabled == value)
{
m_imageDisabled = value;
Invalidate();
}
}
}
[Category("Appearance"), DefaultValue(-1), Editor("System.Windows.Forms.Design.ImageIndexEditor, System.Design", "System.Drawing.Design.UITypeEditor,System.Drawing"), TypeConverter(typeof(System.Windows.Forms.ImageIndexConverter)), RefreshProperties(RefreshProperties.Repaint)]
public int ImageIndexEnabled
{
get
{
return m_imageIndexEnabled;
}
set
{
if (m_imageIndexEnabled != value)
{
m_imageIndexEnabled = value;
Invalidate();
}
}
}
[Category("Appearance"), DefaultValue(-1), Editor("System.Windows.Forms.Design.ImageIndexEditor, System.Design", "System.Drawing.Design.UITypeEditor,System.Drawing"), TypeConverter(typeof(System.Windows.Forms.ImageIndexConverter)), RefreshProperties(RefreshProperties.Repaint)]
public int ImageIndexDisabled
{
get
{
return m_imageIndexDisabled;
}
set
{
if (m_imageIndexDisabled != value)
{
m_imageIndexDisabled = value;
Invalidate();
}
}
}
[Category("Appearance"), DefaultValue(false)]
public bool IsPopup
{
get
{
return m_isPopup;
}
set
{
if (m_isPopup != value)
{
m_isPopup = value;
Invalidate();
}
}
}
[Category("Appearance"), DefaultValue(true)]
public bool Monochrome
{
get
{
return m_monochrom;
}
set
{
if (value != m_monochrom)
{
m_monochrom = value;
Invalidate();
}
}
}
[Category("Behavior"), DefaultValue(false)]
public bool RepeatClick
{
get
{
return (ClickStatus != RepeatClickStatus.Disabled);
}
set
{
ClickStatus = RepeatClickStatus.Stopped;
}
}
private RepeatClickStatus ClickStatus
{
get
{
return m_clickStatus;
}
set
{
if (m_clickStatus == value)
{
return;
}
m_clickStatus = value;
if (ClickStatus == RepeatClickStatus.Started)
{
Timer.Interval = RepeatClickDelay;
Timer.Enabled = true;
}
else if (ClickStatus == RepeatClickStatus.Repeating)
{
Timer.Interval = RepeatClickInterval;
}
else
{
Timer.Enabled = false;
}
}
}
[Category("Behavior"), DefaultValue(500)]
public int RepeatClickDelay
{
get
{
return m_repeatClickDelay;
}
set
{
m_repeatClickDelay = value;
}
}
[Category("Behavior"), DefaultValue(100)]
public int RepeatClickInterval
{
get
{
return m_repeatClickInterval;
}
set
{
m_repeatClickInterval = value;
}
}
private Timer Timer
{
get
{
return m_timer;
}
}
[Category("Appearance"), DefaultValue("")]
public string ToolTipText
{
get
{
return m_toolTipText;
}
set
{
if (m_toolTipText != value)
{
if (m_toolTip == null)
{
m_toolTip = new ToolTip(this.components);
}
m_toolTipText = value;
m_toolTip.SetToolTip(this, value);
}
}
}
#endregion
#region Events
private void Timer_Tick(object sender, EventArgs e)
{
if (m_mouseCapture && m_mouseOver)
{
OnClick(RepeatClickEventArgs.Empty);
}
if (ClickStatus == RepeatClickStatus.Started)
{
ClickStatus = RepeatClickStatus.Repeating;
}
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if (e.Button != System.Windows.Forms.MouseButtons.Left)
{
return;
}
if (m_mouseCapture == false || m_mouseOver == false)
{
m_mouseCapture = true;
m_mouseOver = true;
//Redraw to show button state
Invalidate();
}
if (RepeatClick)
{
OnClick(RepeatClickEventArgs.Empty);
ClickStatus = RepeatClickStatus.Started;
}
}
protected override void OnClick(EventArgs e)
{
if (RepeatClick && ! (e is RepeatClickEventArgs))
{
return;
}
base.OnClick(e);
}
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
if (e.Button != MouseButtons.Left)
{
return;
}
if (m_mouseOver == true || m_mouseCapture == true)
{
m_mouseOver = false;
m_mouseCapture = false;
// Redraw to show button state
Invalidate();
}
if (RepeatClick)
{
ClickStatus = RepeatClickStatus.Stopped;
}
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
// Is mouse point inside our client rectangle
bool over = this.ClientRectangle.Contains(new Point(e.X, e.Y));
// If entering the button area or leaving the button area...
if (over != m_mouseOver)
{
// Update state
m_mouseOver = over;
// Redraw to show button state
Invalidate();
}
}
protected override void OnMouseEnter(EventArgs e)
{
// Update state to reflect mouse over the button area
if (! m_mouseOver)
{
m_mouseOver = true;
// Redraw to show button state
Invalidate();
}
base.OnMouseEnter(e);
}
protected override void OnMouseLeave(EventArgs e)
{
// Update state to reflect mouse not over the button area
if (m_mouseOver)
{
m_mouseOver = false;
// Redraw to show button state
Invalidate();
}
base.OnMouseLeave(e);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
DrawBackground(e.Graphics);
DrawImage(e.Graphics);
DrawText(e.Graphics);
if (m_mouseOver | m_mouseCapture)
{
DrawBorder(e.Graphics);
}
}
protected override void OnEnabledChanged(EventArgs e)
{
base.OnEnabledChanged(e);
if (Enabled == false)
{
m_mouseOver = false;
m_mouseCapture = false;
if (RepeatClick && ClickStatus != RepeatClickStatus.Stopped)
{
ClickStatus = RepeatClickStatus.Stopped;
}
}
Invalidate();
}
#endregion
private void InitializeComponent()
{
this.SuspendLayout();
//
//PopupButton
//
this.AutoSize = true;
this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, System.Convert.ToByte(0));
this.ResumeLayout(false);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using MyWebapi.Areas.HelpPage.ModelDescriptions;
using MyWebapi.Areas.HelpPage.Models;
namespace MyWebapi.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using Examine;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Tests.PublishedContent;
using Umbraco.Tests.TestHelpers;
using Umbraco.Web;
using Umbraco.Web.PublishedCache;
using Umbraco.Web.PublishedCache.XmlPublishedCache;
using umbraco.BusinessLogic;
namespace Umbraco.Tests.PublishedCache
{
[DatabaseTestBehavior(DatabaseBehavior.NewDbFileAndSchemaPerTest)]
[TestFixture]
public class PublishMediaCacheTests : BaseWebTest
{
protected override void FreezeResolution()
{
PublishedContentModelFactoryResolver.Current = new PublishedContentModelFactoryResolver();
base.FreezeResolution();
}
[Test]
public void Get_Root_Docs()
{
var user = new User(0);
var mType = global::umbraco.cms.businesslogic.media.MediaType.MakeNew(user, "TestMediaType");
var mRoot1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("MediaRoot1", mType, user, -1);
var mRoot2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("MediaRoot2", mType, user, -1);
var mChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child1", mType, user, mRoot1.Id);
var mChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child2", mType, user, mRoot2.Id);
var ctx = GetUmbracoContext("/test", 1234);
var cache = new ContextualPublishedMediaCache(new PublishedMediaCache(), ctx);
var roots = cache.GetAtRoot();
Assert.AreEqual(2, roots.Count());
Assert.IsTrue(roots.Select(x => x.Id).ContainsAll(new[] {mRoot1.Id, mRoot2.Id}));
}
[Test]
public void Get_Item_Without_Examine()
{
var user = new User(0);
var mType = global::umbraco.cms.businesslogic.media.MediaType.MakeNew(user, "TestMediaType");
var mRoot = global::umbraco.cms.businesslogic.media.Media.MakeNew("MediaRoot", mType, user, -1);
var mChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child1", mType, user, mRoot.Id);
var publishedMedia = PublishedMediaTests.GetNode(mRoot.Id, GetUmbracoContext("/test", 1234));
Assert.AreEqual(mRoot.Id, publishedMedia.Id);
Assert.AreEqual(mRoot.CreateDateTime.ToString("dd/MM/yyyy HH:mm:ss"), publishedMedia.CreateDate.ToString("dd/MM/yyyy HH:mm:ss"));
Assert.AreEqual(mRoot.User.Id, publishedMedia.CreatorId);
Assert.AreEqual(mRoot.User.Name, publishedMedia.CreatorName);
Assert.AreEqual(mRoot.ContentType.Alias, publishedMedia.DocumentTypeAlias);
Assert.AreEqual(mRoot.ContentType.Id, publishedMedia.DocumentTypeId);
Assert.AreEqual(mRoot.Level, publishedMedia.Level);
Assert.AreEqual(mRoot.Text, publishedMedia.Name);
Assert.AreEqual(mRoot.Path, publishedMedia.Path);
Assert.AreEqual(mRoot.sortOrder, publishedMedia.SortOrder);
Assert.IsNull(publishedMedia.Parent);
}
[TestCase("id")]
[TestCase("nodeId")]
[TestCase("__NodeId")]
public void DictionaryDocument_Id_Keys(string key)
{
var dicDoc = GetDictionaryDocument(idKey: key);
DoAssert(dicDoc);
}
[TestCase("template")]
[TestCase("templateId")]
public void DictionaryDocument_Template_Keys(string key)
{
var dicDoc = GetDictionaryDocument(templateKey: key);
DoAssert(dicDoc);
}
[TestCase("nodeName")]
[TestCase("__nodeName")]
public void DictionaryDocument_NodeName_Keys(string key)
{
var dicDoc = GetDictionaryDocument(nodeNameKey: key);
DoAssert(dicDoc);
}
[TestCase("nodeTypeAlias")]
[TestCase("__NodeTypeAlias")]
public void DictionaryDocument_NodeTypeAlias_Keys(string key)
{
var dicDoc = GetDictionaryDocument(nodeTypeAliasKey: key);
DoAssert(dicDoc);
}
[TestCase("path")]
[TestCase("__Path")]
public void DictionaryDocument_Path_Keys(string key)
{
var dicDoc = GetDictionaryDocument(pathKey: key);
DoAssert(dicDoc);
}
[Test]
public void DictionaryDocument_Get_Children()
{
var child1 = GetDictionaryDocument(idVal: 222333);
var child2 = GetDictionaryDocument(idVal: 444555);
var dicDoc = GetDictionaryDocument(children: new List<IPublishedContent>()
{
child1, child2
});
Assert.AreEqual(2, dicDoc.Children.Count());
Assert.AreEqual(222333, dicDoc.Children.ElementAt(0).Id);
Assert.AreEqual(444555, dicDoc.Children.ElementAt(1).Id);
}
[Test]
public void Convert_From_Search_Result()
{
var result = new SearchResult()
{
Id = 1234,
Score = 1
};
result.Fields.Add("__IndexType", "media");
result.Fields.Add("__NodeId", "1234");
result.Fields.Add("__NodeTypeAlias", Constants.Conventions.MediaTypes.Image);
result.Fields.Add("__Path", "-1,1234");
result.Fields.Add("__nodeName", "Test");
result.Fields.Add("id", "1234");
result.Fields.Add("nodeName", "Test");
result.Fields.Add("nodeTypeAlias", Constants.Conventions.MediaTypes.Image);
result.Fields.Add("parentID", "-1");
result.Fields.Add("path", "-1,1234");
result.Fields.Add("updateDate", "2012-07-16T10:34:09");
result.Fields.Add("writerName", "Shannon");
var store = new PublishedMediaCache();
var doc = store.ConvertFromSearchResult(result);
DoAssert(doc, 1234, 0, 0, "", "Image", 0, "Shannon", "", 0, 0, "-1,1234", default(DateTime), DateTime.Parse("2012-07-16T10:34:09"), 2);
Assert.AreEqual(null, doc.Parent);
}
[Test]
public void Convert_From_XPath_Navigator()
{
var xmlDoc = GetMediaXml();
var navigator = xmlDoc.SelectSingleNode("/root/Image").CreateNavigator();
var cache = new PublishedMediaCache();
var doc = cache.ConvertFromXPathNavigator(navigator);
DoAssert(doc, 2000, 0, 2, "image1", "Image", 2044, "Shannon", "Shannon2", 22, 33, "-1,2000", DateTime.Parse("2012-06-12T14:13:17"), DateTime.Parse("2012-07-20T18:50:43"), 1);
Assert.AreEqual(null, doc.Parent);
Assert.AreEqual(2, doc.Children.Count());
Assert.AreEqual(2001, doc.Children.ElementAt(0).Id);
Assert.AreEqual(2002, doc.Children.ElementAt(1).Id);
}
private XmlDocument GetMediaXml()
{
var xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
<!DOCTYPE root[
<!ELEMENT Home ANY>
<!ATTLIST Home id ID #REQUIRED>
<!ELEMENT CustomDocument ANY>
<!ATTLIST CustomDocument id ID #REQUIRED>
]>
<root id=""-1"">
<Image id=""2000"" parentID=""-1"" level=""1"" writerID=""22"" creatorID=""33"" nodeType=""2044"" template=""0"" sortOrder=""2"" createDate=""2012-06-12T14:13:17"" updateDate=""2012-07-20T18:50:43"" nodeName=""Image1"" urlName=""image1"" writerName=""Shannon"" creatorName=""Shannon2"" path=""-1,2000"" isDoc="""">
<file><![CDATA[/media/1234/image1.png]]></file>
<Image id=""2001"" parentID=""2000"" level=""2"" writerID=""22"" creatorID=""33"" nodeType=""2044"" template=""0"" sortOrder=""2"" createDate=""2012-06-12T14:13:17"" updateDate=""2012-07-20T18:50:43"" nodeName=""Image1"" urlName=""image1"" writerName=""Shannon"" creatorName=""Shannon2"" path=""-1,2000,2001"" isDoc="""">
<file><![CDATA[/media/1234/image1.png]]></file>
</Image>
<Image id=""2002"" parentID=""2000"" level=""2"" writerID=""22"" creatorID=""33"" nodeType=""2044"" template=""0"" sortOrder=""2"" createDate=""2012-06-12T14:13:17"" updateDate=""2012-07-20T18:50:43"" nodeName=""Image1"" urlName=""image1"" writerName=""Shannon"" creatorName=""Shannon2"" path=""-1,2000,2002"" isDoc="""">
<file><![CDATA[/media/1234/image1.png]]></file>
</Image>
</Image>
</root>";
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
return xmlDoc;
}
private Dictionary<string, string> GetDictionary(
int id,
int parentId,
string idKey,
string templateKey,
string nodeNameKey,
string nodeTypeAliasKey,
string pathKey)
{
return new Dictionary<string, string>()
{
{idKey, id.ToString()},
{templateKey, "333"},
{"sortOrder", "44"},
{nodeNameKey, "Testing"},
{"urlName", "testing"},
{nodeTypeAliasKey, "myType"},
{"nodeType", "22"},
{"writerName", "Shannon"},
{"creatorName", "Shannon2"},
{"writerID", "33"},
{"creatorID", "44"},
{pathKey, "1,2,3,4,5"},
{"createDate", "2012-01-02"},
{"updateDate", "2012-01-03"},
{"level", "3"},
{"parentID", parentId.ToString()}
};
}
private PublishedMediaCache.DictionaryPublishedContent GetDictionaryDocument(
string idKey = "id",
string templateKey = "template",
string nodeNameKey = "nodeName",
string nodeTypeAliasKey = "nodeTypeAlias",
string pathKey = "path",
int idVal = 1234,
int parentIdVal = 321,
IEnumerable<IPublishedContent> children = null)
{
if (children == null)
children = new List<IPublishedContent>();
var dicDoc = new PublishedMediaCache.DictionaryPublishedContent(
//the dictionary
GetDictionary(idVal, parentIdVal, idKey, templateKey, nodeNameKey, nodeTypeAliasKey, pathKey),
//callback to get the parent
d => new PublishedMediaCache.DictionaryPublishedContent(
GetDictionary(parentIdVal, -1, idKey, templateKey, nodeNameKey, nodeTypeAliasKey, pathKey),
//there is no parent
a => null,
//we're not going to test this so ignore
a => new List<IPublishedContent>(),
(dd, a) => dd.Properties.FirstOrDefault(x => x.PropertyTypeAlias.InvariantEquals(a)),
false),
//callback to get the children
d => children,
(dd, a) => dd.Properties.FirstOrDefault(x => x.PropertyTypeAlias.InvariantEquals(a)),
false);
return dicDoc;
}
private void DoAssert(
PublishedMediaCache.DictionaryPublishedContent dicDoc,
int idVal = 1234,
int templateIdVal = 333,
int sortOrderVal = 44,
string urlNameVal = "testing",
string nodeTypeAliasVal = "myType",
int nodeTypeIdVal = 22,
string writerNameVal = "Shannon",
string creatorNameVal = "Shannon2",
int writerIdVal = 33,
int creatorIdVal = 44,
string pathVal = "1,2,3,4,5",
DateTime? createDateVal = null,
DateTime? updateDateVal = null,
int levelVal = 3,
int parentIdVal = 321)
{
if (!createDateVal.HasValue)
createDateVal = DateTime.Parse("2012-01-02");
if (!updateDateVal.HasValue)
updateDateVal = DateTime.Parse("2012-01-03");
DoAssert((IPublishedContent)dicDoc, idVal, templateIdVal, sortOrderVal, urlNameVal, nodeTypeAliasVal, nodeTypeIdVal, writerNameVal,
creatorNameVal, writerIdVal, creatorIdVal, pathVal, createDateVal, updateDateVal, levelVal);
//now validate the parentId that has been parsed, this doesn't exist on the IPublishedContent
Assert.AreEqual(parentIdVal, dicDoc.ParentId);
}
private void DoAssert(
IPublishedContent doc,
int idVal = 1234,
int templateIdVal = 333,
int sortOrderVal = 44,
string urlNameVal = "testing",
string nodeTypeAliasVal = "myType",
int nodeTypeIdVal = 22,
string writerNameVal = "Shannon",
string creatorNameVal = "Shannon2",
int writerIdVal = 33,
int creatorIdVal = 44,
string pathVal = "1,2,3,4,5",
DateTime? createDateVal = null,
DateTime? updateDateVal = null,
int levelVal = 3)
{
if (!createDateVal.HasValue)
createDateVal = DateTime.Parse("2012-01-02");
if (!updateDateVal.HasValue)
updateDateVal = DateTime.Parse("2012-01-03");
Assert.AreEqual(idVal, doc.Id);
Assert.AreEqual(templateIdVal, doc.TemplateId);
Assert.AreEqual(sortOrderVal, doc.SortOrder);
Assert.AreEqual(urlNameVal, doc.UrlName);
Assert.AreEqual(nodeTypeAliasVal, doc.DocumentTypeAlias);
Assert.AreEqual(nodeTypeIdVal, doc.DocumentTypeId);
Assert.AreEqual(writerNameVal, doc.WriterName);
Assert.AreEqual(creatorNameVal, doc.CreatorName);
Assert.AreEqual(writerIdVal, doc.WriterId);
Assert.AreEqual(creatorIdVal, doc.CreatorId);
Assert.AreEqual(pathVal, doc.Path);
Assert.AreEqual(createDateVal.Value, doc.CreateDate);
Assert.AreEqual(updateDateVal.Value, doc.UpdateDate);
Assert.AreEqual(levelVal, doc.Level);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace TimeManagment.WebApp.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Net.Http;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Subscriptions;
namespace Microsoft.WindowsAzure.Subscriptions
{
public partial class SubscriptionClient : ServiceClient<SubscriptionClient>, ISubscriptionClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private CloudCredentials _credentials;
/// <summary>
/// Credentials used to authenticate requests.
/// </summary>
public CloudCredentials Credentials
{
get { return this._credentials; }
set { this._credentials = value; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private ISubscriptionOperations _subscriptions;
public virtual ISubscriptionOperations Subscriptions
{
get { return this._subscriptions; }
}
/// <summary>
/// Initializes a new instance of the SubscriptionClient class.
/// </summary>
private SubscriptionClient()
: base()
{
this._subscriptions = new SubscriptionOperations(this);
this._apiVersion = "2013-08-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the SubscriptionClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials used to authenticate requests.
/// </param>
/// <param name='baseUri'>
/// Required. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public SubscriptionClient(CloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the SubscriptionClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials used to authenticate requests.
/// </param>
public SubscriptionClient(CloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.core.windows.net");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the SubscriptionClient class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
private SubscriptionClient(HttpClient httpClient)
: base(httpClient)
{
this._subscriptions = new SubscriptionOperations(this);
this._apiVersion = "2013-08-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the SubscriptionClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials used to authenticate requests.
/// </param>
/// <param name='baseUri'>
/// Required. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public SubscriptionClient(CloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the SubscriptionClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials used to authenticate requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public SubscriptionClient(CloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.core.windows.net");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another
/// SubscriptionClient instance
/// </summary>
/// <param name='client'>
/// Instance of SubscriptionClient to clone to
/// </param>
protected override void Clone(ServiceClient<SubscriptionClient> client)
{
base.Clone(client);
if (client is SubscriptionClient)
{
SubscriptionClient clonedClient = ((SubscriptionClient)client);
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Cluster
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Collections;
using Apache.Ignite.Core.Impl.Common;
/// <summary>
/// Cluster node implementation.
/// </summary>
internal class ClusterNodeImpl : IClusterNode
{
/** Node ID. */
private readonly Guid _id;
/** Attributes. */
private readonly IDictionary<string, object> _attrs;
/** Addresses. */
private readonly ICollection<string> _addrs;
/** Hosts. */
private readonly ICollection<string> _hosts;
/** Order. */
private readonly long _order;
/** Local flag. */
private readonly bool _isLocal;
/** Daemon flag. */
private readonly bool _isDaemon;
/** Client flag. */
private readonly bool _isClient;
/** Metrics. */
private volatile ClusterMetricsImpl _metrics;
/** Ignite reference. */
private WeakReference _igniteRef;
/// <summary>
/// Initializes a new instance of the <see cref="ClusterNodeImpl"/> class.
/// </summary>
/// <param name="reader">The reader.</param>
public ClusterNodeImpl(IBinaryRawReader reader)
{
var id = reader.ReadGuid();
Debug.Assert(id.HasValue);
_id = id.Value;
_attrs = reader.ReadDictionaryAsGeneric<string, object>().AsReadOnly();
_addrs = reader.ReadCollectionAsList<string>().AsReadOnly();
_hosts = reader.ReadCollectionAsList<string>().AsReadOnly();
_order = reader.ReadLong();
_isLocal = reader.ReadBoolean();
_isDaemon = reader.ReadBoolean();
_isClient = reader.ReadBoolean();
_metrics = reader.ReadBoolean() ? new ClusterMetricsImpl(reader) : null;
}
/** <inheritDoc /> */
public Guid Id
{
get { return _id; }
}
/** <inheritDoc /> */
public T GetAttribute<T>(string name)
{
IgniteArgumentCheck.NotNull(name, "name");
return (T)_attrs[name];
}
/** <inheritDoc /> */
public bool TryGetAttribute<T>(string name, out T attr)
{
IgniteArgumentCheck.NotNull(name, "name");
object val;
if (_attrs.TryGetValue(name, out val))
{
attr = (T)val;
return true;
}
attr = default(T);
return false;
}
/** <inheritDoc /> */
public IDictionary<string, object> GetAttributes()
{
return _attrs;
}
/** <inheritDoc /> */
public ICollection<string> Addresses
{
get { return _addrs; }
}
/** <inheritDoc /> */
public ICollection<string> HostNames
{
get { return _hosts; }
}
/** <inheritDoc /> */
public long Order
{
get { return _order; }
}
/** <inheritDoc /> */
public bool IsLocal
{
get { return _isLocal; }
}
/** <inheritDoc /> */
public bool IsDaemon
{
get { return _isDaemon; }
}
/** <inheritDoc /> */
public IClusterMetrics GetMetrics()
{
var ignite = (Ignite)_igniteRef.Target;
if (ignite == null)
return _metrics;
ClusterMetricsImpl oldMetrics = _metrics;
long lastUpdateTime = oldMetrics.LastUpdateTimeRaw;
ClusterMetricsImpl newMetrics = ignite.ClusterGroup.RefreshClusterNodeMetrics(_id, lastUpdateTime);
if (newMetrics != null)
{
lock (this)
{
if (_metrics.LastUpdateTime < newMetrics.LastUpdateTime)
_metrics = newMetrics;
}
return newMetrics;
}
return oldMetrics;
}
/** <inheritDoc /> */
public bool IsClient
{
get { return _isClient; }
}
/** <inheritDoc /> */
public override string ToString()
{
return "GridNode [id=" + Id + ']';
}
/** <inheritDoc /> */
public override bool Equals(object obj)
{
ClusterNodeImpl node = obj as ClusterNodeImpl;
if (node != null)
return _id.Equals(node._id);
return false;
}
/** <inheritDoc /> */
public override int GetHashCode()
{
// ReSharper disable once NonReadonlyMemberInGetHashCode
return _id.GetHashCode();
}
/// <summary>
/// Initializes this instance with a grid.
/// </summary>
/// <param name="grid">The grid.</param>
internal void Init(Ignite grid)
{
_igniteRef = new WeakReference(grid);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using Sprache;
namespace MinecraftCommandParser
{
public abstract class TargetSelector : IFormattable
{
private static readonly char[] _legalVariables = { 'p', 'r', 'a', 'e' };
private readonly char _variable;
private readonly IReadOnlyDictionary<TargetSelectorArgument, object> _arguments;
protected TargetSelector(char variable, IDictionary<TargetSelectorArgument, object> arguments)
{
if (!_legalVariables.Contains(variable)) throw new ArgumentException("variable must be 'p', 'r', 'a', or 'e'.", "variable");
_variable = variable;
_arguments = new ReadOnlyDictionary<TargetSelectorArgument, object>(arguments);
}
private static TargetSelector GetTargetSelector(
char variable,
IDictionary<TargetSelectorArgument, object> arguments)
{
switch (variable)
{
case 'p':
return new PlayerSelector(arguments);
case 'r':
return new RandomPlayerSelector(arguments);
case 'a':
return new AllPlayersSelector(arguments);
case 'e':
return new EntitySelector(arguments);
default:
throw new ArgumentException("variable must be 'p', 'r', 'a', or 'e'.", "variable");
}
}
public IReadOnlyDictionary<TargetSelectorArgument, object> Arguments { get { return _arguments; } }
internal static Parser<TargetSelector> GetParser()
{
return GetParser<TargetSelector>(_legalVariables);
}
internal static Parser<TTargetSelector> GetParser<TTargetSelector>(params char[] variables)
where TTargetSelector : TargetSelector
{
if (variables == null) throw new ArgumentNullException("variables");
if (variables.Length == 0)
{
variables = _legalVariables;
}
else if (variables.Any(v => !_legalVariables.Contains(v)))
{
throw new ArgumentException("variables may only contain 'p', 'r', 'a', or 'e'.", "variables");
}
else if (variables.Distinct().Count() != variables.Length)
{
throw new ArgumentException("variables may not contain duplicates.", "variables");
}
foreach (var variable in variables)
{
switch (variable)
{
case 'p':
if (!typeof(TTargetSelector).IsAssignableFrom(typeof(PlayerSelector)))
{
throw new ArgumentException(string.Format("TTargetSelector type, {0}, is not assignable to PlayerSelector type.", typeof(TTargetSelector)), "variables");
}
break;
case 'r':
if (!typeof(TTargetSelector).IsAssignableFrom(typeof(RandomPlayerSelector)))
{
throw new ArgumentException(string.Format("TTargetSelector type, {0}, is not assignable to RandomPlayerSelector type.", typeof(TTargetSelector)), "variables");
}
break;
case 'a':
if (!typeof(TTargetSelector).IsAssignableFrom(typeof(AllPlayersSelector)))
{
throw new ArgumentException(string.Format("TTargetSelector type, {0}, is not assignable to AllPlayersSelector type.", typeof(TTargetSelector)), "variables");
}
break;
case 'e':
if (!typeof(TTargetSelector).IsAssignableFrom(typeof(EntitySelector)))
{
throw new ArgumentException(string.Format("TTargetSelector type, {0}, is not assignable to EntitySelector type.", typeof(TTargetSelector)), "variables");
}
break;
}
}
var variableParser = Parse.Chars(variables);
var argumentParser = GetArgumentParser();
return
from w1 in Parse.WhiteSpace.Many()
from at in Parse.Char('@')
from variable in variableParser
from arguments in
(from openBracket in Parse.Char('[')
from items in argumentParser.OptionallyDelimitedBy(Parse.Char(',').Token()).Token()
from closeBracket in Parse.Char(']')
select items.ToDictionary(x => x.Key, x => x.Value)).Optional()
select (TTargetSelector)GetTargetSelector(variable, arguments.GetOrElse(new Dictionary<TargetSelectorArgument, object>()));
}
private static Parser<KeyValuePair<TargetSelectorArgument, object>> GetArgumentParser()
{
var argumentParser =
from argument in Parse.Char('x')
from eq in Parse.Char('=').Token()
from value in CommandParsers.CoordinateParser
select new KeyValuePair<TargetSelectorArgument, object>(TargetSelectorArgument.x, value);
argumentParser = argumentParser.Or(
from argument in Parse.Char('y')
from eq in Parse.Char('=').Token()
from value in CommandParsers.CoordinateParser
select new KeyValuePair<TargetSelectorArgument, object>(TargetSelectorArgument.y, value));
argumentParser = argumentParser.Or(
from argument in Parse.Char('z')
from eq in Parse.Char('=').Token()
from value in CommandParsers.CoordinateParser
select new KeyValuePair<TargetSelectorArgument, object>(TargetSelectorArgument.z, value));
argumentParser = argumentParser.Or(
from argument in Parse.Char('r')
from eq in Parse.Char('=').Token()
from value in Parse.Number
select new KeyValuePair<TargetSelectorArgument, object>(TargetSelectorArgument.r, Int32.Parse(value)));
argumentParser = argumentParser.Or(
from argument in Parse.String("rm")
from eq in Parse.Char('=').Token()
from value in Parse.Number
select new KeyValuePair<TargetSelectorArgument, object>(TargetSelectorArgument.rm, Int32.Parse(value)));
var modeParser = CommandParsers.GetRangeParser(-1, 5);
argumentParser = argumentParser.Or(
from argument in Parse.String("m")
from eq in Parse.Char('=').Token()
from value in modeParser
select new KeyValuePair<TargetSelectorArgument, object>(TargetSelectorArgument.m, value));
argumentParser = argumentParser.Or(
from argument in Parse.Char('c')
from eq in Parse.Char('=').Token()
from negative in Parse.Char('-').Optional()
from value in Parse.Number
select new KeyValuePair<TargetSelectorArgument, object>(TargetSelectorArgument.c, Int32.Parse(value) * (negative.IsDefined ? -1 : 1)));
argumentParser = argumentParser.Or(
from argument in Parse.Char('l')
from eq in Parse.Char('=').Token()
from value in Parse.Number
select new KeyValuePair<TargetSelectorArgument, object>(TargetSelectorArgument.l, Int32.Parse(value)));
argumentParser = argumentParser.Or(
from argument in Parse.String("lm")
from eq in Parse.Char('=').Token()
from value in Parse.Number
select new KeyValuePair<TargetSelectorArgument, object>(TargetSelectorArgument.lm, Int32.Parse(value)));
var stringValueParser = Parse.CharExcept(c => c == ']' || c == ',' || Char.IsWhiteSpace(c), "string values").AtLeastOnce().Text();
argumentParser = argumentParser.Or(
from argument in Parse.String("team")
from eq in Parse.Char('=').Token()
from not in Parse.Char('!').Token()
from value in stringValueParser
select new KeyValuePair<TargetSelectorArgument, object>(TargetSelectorArgument.not_team, value));
argumentParser = argumentParser.Or(
from argument in Parse.String("team")
from eq in Parse.Char('=').Token()
from value in stringValueParser
select new KeyValuePair<TargetSelectorArgument, object>(TargetSelectorArgument.team, value));
argumentParser = argumentParser.Or(
from argument in Parse.String("team")
from eq in Parse.Char('=').Token()
select new KeyValuePair<TargetSelectorArgument, object>(TargetSelectorArgument.not_any_team, null));
argumentParser = argumentParser.Or(
from argument in Parse.String("name")
from eq in Parse.Char('=').Token()
from not in Parse.Char('!').Token()
from value in stringValueParser
select new KeyValuePair<TargetSelectorArgument, object>(TargetSelectorArgument.not_name, value));
argumentParser = argumentParser.Or(
from argument in Parse.String("name")
from eq in Parse.Char('=').Token()
from value in stringValueParser
select new KeyValuePair<TargetSelectorArgument, object>(TargetSelectorArgument.name, value));
argumentParser = argumentParser.Or(
from argument in Parse.String("dx")
from eq in Parse.Char('=').Token()
from negative in Parse.Char('-').Optional()
from value in Parse.Number
select new KeyValuePair<TargetSelectorArgument, object>(TargetSelectorArgument.dx, Int32.Parse(value) * (negative.IsDefined ? -1 : 1)));
argumentParser = argumentParser.Or(
from argument in Parse.String("dy")
from eq in Parse.Char('=').Token()
from negative in Parse.Char('-').Optional()
from value in Parse.Number
select new KeyValuePair<TargetSelectorArgument, object>(TargetSelectorArgument.dy, Int32.Parse(value) * (negative.IsDefined ? -1 : 1)));
argumentParser = argumentParser.Or(
from argument in Parse.String("dz")
from eq in Parse.Char('=').Token()
from negative in Parse.Char('-').Optional()
from value in Parse.Number
select new KeyValuePair<TargetSelectorArgument, object>(TargetSelectorArgument.dz, Int32.Parse(value) * (negative.IsDefined ? -1 : 1)));
argumentParser = argumentParser.Or(
from argument in Parse.String("rx")
from eq in Parse.Char('=').Token()
from negative in Parse.Char('-').Optional()
from value in Parse.Number
select new KeyValuePair<TargetSelectorArgument, object>(TargetSelectorArgument.rx, Int32.Parse(value) * (negative.IsDefined ? -1 : 1)));
argumentParser = argumentParser.Or(
from argument in Parse.String("rxm")
from eq in Parse.Char('=').Token()
from negative in Parse.Char('-').Optional()
from value in Parse.Number
select new KeyValuePair<TargetSelectorArgument, object>(TargetSelectorArgument.rxm, Int32.Parse(value) * (negative.IsDefined ? -1 : 1)));
argumentParser = argumentParser.Or(
from argument in Parse.String("ry")
from eq in Parse.Char('=').Token()
from negative in Parse.Char('-').Optional()
from value in Parse.Number
select new KeyValuePair<TargetSelectorArgument, object>(TargetSelectorArgument.ry, Int32.Parse(value) * (negative.IsDefined ? -1 : 1)));
argumentParser = argumentParser.Or(
from argument in Parse.String("rym")
from eq in Parse.Char('=').Token()
from negative in Parse.Char('-').Optional()
from value in Parse.Number
select new KeyValuePair<TargetSelectorArgument, object>(TargetSelectorArgument.rym, Int32.Parse(value) * (negative.IsDefined ? -1 : 1)));
argumentParser = argumentParser.Or(
from argument in Parse.String("type")
from eq in Parse.Char('=').Token()
from not in Parse.Char('!').Token()
from value in CommandParsers.EntityParser
select new KeyValuePair<TargetSelectorArgument, object>(TargetSelectorArgument.not_type, value));
argumentParser = argumentParser.Or(
from argument in Parse.String("type")
from eq in Parse.Char('=').Token()
from value in CommandParsers.EntityParser
select new KeyValuePair<TargetSelectorArgument, object>(TargetSelectorArgument.type, value));
return argumentParser;
}
public string PrettyPrinted
{
get { return GetString(", "); }
}
public string Minified
{
get { return GetString(","); }
}
private string GetString(string separator)
{
var sb = new StringBuilder();
sb.Append("@").Append(_variable);
var arguments = Arguments.ToList();
if (arguments.Any())
{
sb.Append("[");
sb.Append(arguments[0].Key).Append("=").Append(arguments[0].Value);
for (int i = 1; i < arguments.Count; i++)
{
sb.Append(separator).Append(arguments[i].Key).Append("=").Append(arguments[i].Value);
}
sb.Append("]");
}
return sb.ToString();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace System.Runtime
{
/////////////////////////////////////////////////////////////////////////////////////////////////////
//
// **** WARNING ****
//
// A large portion of the logic present in this file is duplicated
// in src\System.Private.Reflection.Execution\Internal\Reflection\Execution\TypeLoader\TypeCast.cs
// (for dynamic type builder). If you make changes here make sure they are reflected there.
//
// **** WARNING ****
//
/////////////////////////////////////////////////////////////////////////////////////////////////////
internal static class TypeCast
{
[RuntimeExport("RhTypeCast_IsInstanceOfClass")]
static public unsafe object IsInstanceOfClass(object obj, void* pvTargetType)
{
if (obj == null)
{
return null;
}
EEType* pTargetType = (EEType*)pvTargetType;
EEType* pObjType = obj.EEType;
Debug.Assert(!pTargetType->IsParameterizedType, "IsInstanceOfClass called with parameterized EEType");
Debug.Assert(!pTargetType->IsInterface, "IsInstanceOfClass called with interface EEType");
// if the EETypes pointers match, we're done
if (pObjType == pTargetType)
{
return obj;
}
// Quick check if both types are good for simple casting: canonical, no related type via IAT, no generic variance
if (System.Runtime.EEType.BothSimpleCasting(pObjType, pTargetType))
{
// walk the type hierarchy looking for a match
do
{
pObjType = pObjType->BaseType;
if (pObjType == null)
{
return null;
}
if (pObjType == pTargetType)
{
return obj;
}
}
while (pObjType->SimpleCasting());
}
if (pTargetType->IsCloned)
{
pTargetType = pTargetType->CanonicalEEType;
}
if (pObjType->IsCloned)
{
pObjType = pObjType->CanonicalEEType;
}
// if the EETypes pointers match, we're done
if (pObjType == pTargetType)
{
return obj;
}
if (pTargetType->HasGenericVariance && pObjType->HasGenericVariance)
{
// Only generic interfaces and delegates can have generic variance and we shouldn't see
// interfaces for either input here. So if the canonical types are marked as having variance
// we know we've hit the delegate case. We've dealt with the identical case just above. And
// the regular path below will handle casting to Object, Delegate and MulticastDelegate. Since
// we don't support deriving from user delegate classes any further all we have to check here
// is that the uninstantiated generic delegate definitions are the same and the type
// parameters are compatible.
return TypesAreCompatibleViaGenericVariance(pObjType, pTargetType) ? obj : null;
}
if (pObjType->IsArray)
{
// arrays can be cast to System.Object
if (WellKnownEETypes.IsSystemObject(pTargetType))
{
return obj;
}
// arrays can be cast to System.Array
if (WellKnownEETypes.IsSystemArray(pTargetType))
{
return obj;
}
return null;
}
// walk the type hierarchy looking for a match
while (true)
{
pObjType = pObjType->NonClonedNonArrayBaseType;
if (pObjType == null)
{
return null;
}
if (pObjType->IsCloned)
pObjType = pObjType->CanonicalEEType;
if (pObjType == pTargetType)
{
return obj;
}
}
}
[RuntimeExport("RhTypeCast_CheckCastClass")]
static public unsafe object CheckCastClass(Object obj, void* pvTargetEEType)
{
// a null value can be cast to anything
if (obj == null)
return null;
object result = IsInstanceOfClass(obj, pvTargetEEType);
if (result == null)
{
// Throw the invalid cast exception defined by the classlib, using the input EEType*
// to find the correct classlib.
ExceptionIDs exID = ExceptionIDs.InvalidCast;
IntPtr addr = ((EEType*)pvTargetEEType)->GetAssociatedModuleAddress();
Exception e = EH.GetClasslibException(exID, addr);
BinderIntrinsics.TailCall_RhpThrowEx(e);
}
return result;
}
[RuntimeExport("RhTypeCast_CheckUnbox")]
static public unsafe void CheckUnbox(Object obj, byte expectedCorElementType)
{
if (obj == null)
{
return;
}
if (obj.EEType->CorElementType == (CorElementType)expectedCorElementType)
return;
// Throw the invalid cast exception defined by the classlib, using the input object's EEType*
// to find the correct classlib.
ExceptionIDs exID = ExceptionIDs.InvalidCast;
IntPtr addr = obj.EEType->GetAssociatedModuleAddress();
Exception e = EH.GetClasslibException(exID, addr);
BinderIntrinsics.TailCall_RhpThrowEx(e);
}
[RuntimeExport("RhTypeCast_IsInstanceOfArray")]
static public unsafe object IsInstanceOfArray(object obj, void* pvTargetType)
{
if (obj == null)
{
return null;
}
EEType* pTargetType = (EEType*)pvTargetType;
EEType* pObjType = obj.EEType;
Debug.Assert(pTargetType->IsArray, "IsInstanceOfArray called with non-array EEType");
Debug.Assert(!pTargetType->IsCloned, "cloned array types are disallowed");
// if the types match, we are done
if (pObjType == pTargetType)
{
return obj;
}
// if the object is not an array, we're done
if (!pObjType->IsArray)
{
return null;
}
Debug.Assert(!pObjType->IsCloned, "cloned array types are disallowed");
// compare the array types structurally
if (AreTypesAssignableInternal(pObjType->RelatedParameterType, pTargetType->RelatedParameterType, false, true))
return obj;
return null;
}
[RuntimeExport("RhTypeCast_CheckCastArray")]
static public unsafe object CheckCastArray(Object obj, void* pvTargetEEType)
{
// a null value can be cast to anything
if (obj == null)
return null;
object result = IsInstanceOfArray(obj, pvTargetEEType);
if (result == null)
{
// Throw the invalid cast exception defined by the classlib, using the input EEType*
// to find the correct classlib.
ExceptionIDs exID = ExceptionIDs.InvalidCast;
IntPtr addr = ((EEType*)pvTargetEEType)->GetAssociatedModuleAddress();
Exception e = EH.GetClasslibException(exID, addr);
BinderIntrinsics.TailCall_RhpThrowEx(e);
}
return result;
}
[RuntimeExport("RhTypeCast_IsInstanceOfInterface")]
static public unsafe object IsInstanceOfInterface(object obj, void* pvTargetType)
{
if (obj == null)
{
return null;
}
EEType* pTargetType = (EEType*)pvTargetType;
EEType* pObjType = obj.EEType;
if (ImplementsInterface(pObjType, pTargetType))
return obj;
// If object type implements ICastable then there's one more way to check whether it implements
// the interface.
if (pObjType->IsICastable)
{
// Call the ICastable.IsInstanceOfInterface method directly rather than via an interface
// dispatch since we know the method address statically. We ignore any cast error exception
// object passed back on failure (result == false) since IsInstanceOfInterface never throws.
IntPtr pfnIsInstanceOfInterface = pObjType->ICastableIsInstanceOfInterfaceMethod;
Exception castError = null;
if (CalliIntrinsics.Call<bool>(pfnIsInstanceOfInterface, obj, pTargetType, out castError))
return obj;
}
return null;
}
static internal unsafe bool ImplementsInterface(EEType* pObjType, EEType* pTargetType)
{
Debug.Assert(!pTargetType->IsParameterizedType, "did not expect paramterized type");
Debug.Assert(pTargetType->IsInterface, "IsInstanceOfInterface called with non-interface EEType");
// This can happen with generic interface types
// Debug.Assert(!pTargetType->IsCloned, "cloned interface types are disallowed");
// canonicalize target type
if (pTargetType->IsCloned)
pTargetType = pTargetType->CanonicalEEType;
int numInterfaces = pObjType->NumInterfaces;
EEInterfaceInfo* interfaceMap = pObjType->InterfaceMap;
for (int i = 0; i < numInterfaces; i++)
{
EEType* pInterfaceType = interfaceMap[i].InterfaceType;
// canonicalize the interface type
if (pInterfaceType->IsCloned)
pInterfaceType = pInterfaceType->CanonicalEEType;
if (pInterfaceType == pTargetType)
{
return true;
}
}
// We did not find the interface type in the list of supported interfaces. There's still one
// chance left: if the target interface is generic and one or more of its type parameters is co or
// contra variant then the object can still match if it implements a different instantiation of
// the interface with type compatible generic arguments.
//
// Interfaces which are only variant for arrays have the HasGenericVariance flag set even if they
// are not variant.
bool fArrayCovariance = pObjType->IsArray;
if (pTargetType->HasGenericVariance)
{
// Grab details about the instantiation of the target generic interface.
EETypeRef* pTargetInstantiation;
int targetArity;
GenericVariance* pTargetVarianceInfo;
EEType* pTargetGenericType = InternalCalls.RhGetGenericInstantiation(pTargetType,
&targetArity,
&pTargetInstantiation,
&pTargetVarianceInfo);
Debug.Assert(pTargetVarianceInfo != null, "did not expect empty variance info");
for (int i = 0; i < numInterfaces; i++)
{
EEType* pInterfaceType = interfaceMap[i].InterfaceType;
// We can ignore interfaces which are not also marked as having generic variance
// unless we're dealing with array covariance.
//
// Interfaces which are only variant for arrays have the HasGenericVariance flag set even if they
// are not variant.
if (pInterfaceType->HasGenericVariance)
{
// Grab instantiation details for the candidate interface.
EETypeRef* pInterfaceInstantiation;
int interfaceArity;
GenericVariance* pInterfaceVarianceInfo;
EEType* pInterfaceGenericType = InternalCalls.RhGetGenericInstantiation(pInterfaceType,
&interfaceArity,
&pInterfaceInstantiation,
&pInterfaceVarianceInfo);
Debug.Assert(pInterfaceVarianceInfo != null, "did not expect empty variance info");
// If the generic types aren't the same then the types aren't compatible.
if (pInterfaceGenericType != pTargetGenericType)
continue;
// The types represent different instantiations of the same generic type. The
// arity of both had better be the same.
Debug.Assert(targetArity == interfaceArity, "arity mismatch betweeen generic instantiations");
// Compare the instantiations to see if they're compatible taking variance into account.
if (TypeParametersAreCompatible(targetArity,
pInterfaceInstantiation,
pTargetInstantiation,
pTargetVarianceInfo,
fArrayCovariance))
return true;
}
}
}
return false;
}
// Compare two types to see if they are compatible via generic variance.
static private unsafe bool TypesAreCompatibleViaGenericVariance(EEType* pSourceType, EEType* pTargetType)
{
// Get generic instantiation metadata for both types.
EETypeRef* pTargetInstantiation;
int targetArity;
GenericVariance* pTargetVarianceInfo;
EEType* pTargetGenericType = InternalCalls.RhGetGenericInstantiation(pTargetType,
&targetArity,
&pTargetInstantiation,
&pTargetVarianceInfo);
Debug.Assert(pTargetVarianceInfo != null, "did not expect empty variance info");
EETypeRef* pSourceInstantiation;
int sourceArity;
GenericVariance* pSourceVarianceInfo;
EEType* pSourceGenericType = InternalCalls.RhGetGenericInstantiation(pSourceType,
&sourceArity,
&pSourceInstantiation,
&pSourceVarianceInfo);
Debug.Assert(pSourceVarianceInfo != null, "did not expect empty variance info");
// If the generic types aren't the same then the types aren't compatible.
if (pSourceGenericType == pTargetGenericType)
{
// The types represent different instantiations of the same generic type. The
// arity of both had better be the same.
Debug.Assert(targetArity == sourceArity, "arity mismatch betweeen generic instantiations");
// Compare the instantiations to see if they're compatible taking variance into account.
if (TypeParametersAreCompatible(targetArity,
pSourceInstantiation,
pTargetInstantiation,
pTargetVarianceInfo,
false))
{
return true;
}
}
return false;
}
// Compare two sets of generic type parameters to see if they're assignment compatible taking generic
// variance into account. It's assumed they've already had their type definition matched (which
// implies their arities are the same as well). The fForceCovariance argument tells the method to
// override the defined variance of each parameter and instead assume it is covariant. This is used to
// implement covariant array interfaces.
static internal unsafe bool TypeParametersAreCompatible(int arity,
EETypeRef* pSourceInstantiation,
EETypeRef* pTargetInstantiation,
GenericVariance* pVarianceInfo,
bool fForceCovariance)
{
// Walk through the instantiations comparing the cast compatibility of each pair
// of type args.
for (int i = 0; i < arity; i++)
{
EEType* pTargetArgType = pTargetInstantiation[i].Value;
EEType* pSourceArgType = pSourceInstantiation[i].Value;
GenericVariance varType;
if (fForceCovariance)
varType = GenericVariance.ArrayCovariant;
else
varType = pVarianceInfo[i];
switch (varType)
{
case GenericVariance.NonVariant:
// Non-variant type params need to be identical.
if (!AreTypesEquivalentInternal(pSourceArgType, pTargetArgType))
return false;
break;
case GenericVariance.Covariant:
// For covariance (or out type params in C#) the object must implement an
// interface with a more derived type arg than the target interface. Or
// the object interface can have a type arg that is an interface
// implemented by the target type arg.
// For instance:
// class Foo : ICovariant<String> is ICovariant<Object>
// class Foo : ICovariant<Bar> is ICovariant<IBar>
// class Foo : ICovariant<IBar> is ICovariant<Object>
if (!AreTypesAssignableInternal(pSourceArgType, pTargetArgType, false, false))
return false;
break;
case GenericVariance.ArrayCovariant:
// For array covariance the object must be an array with a type arg
// that is more derived than that the target interface, or be a primitive
// (or enum) with the same size.
// For instance:
// string[,,] is object[,,]
// int[,,] is uint[,,]
// This call is just like the call for Covariance above except true is passed
// to the fAllowSizeEquivalence parameter to allow the int/uint matching to work
if (!AreTypesAssignableInternal(pSourceArgType, pTargetArgType, false, true))
return false;
break;
case GenericVariance.Contravariant:
// For contravariance (or in type params in C#) the object must implement
// an interface with a less derived type arg than the target interface. Or
// the object interface can have a type arg that is a class implementing
// the interface that is the target type arg.
// For instance:
// class Foo : IContravariant<Object> is IContravariant<String>
// class Foo : IContravariant<IBar> is IContravariant<Bar>
// class Foo : IContravariant<Object> is IContravariant<IBar>
if (!AreTypesAssignableInternal(pTargetArgType, pSourceArgType, false, false))
return false;
break;
default:
Debug.Assert(false, "unknown generic variance type");
break;
}
}
return true;
}
//
// Determines if a value of the source type can be assigned to a location of the target type.
// It does not handle ICastable, and cannot since we do not have an actual object instance here.
// This routine assumes that the source type is boxed, i.e. a value type source is presumed to be
// compatible with Object and ValueType and an enum source is additionally compatible with Enum.
//
[RuntimeExport("RhTypeCast_AreTypesAssignable")]
static public unsafe bool AreTypesAssignable(void* pvSourceType, void* pvTargetType)
{
EEType* pSourceType = (EEType*)pvSourceType;
EEType* pTargetType = (EEType*)pvTargetType;
// Special case: Generic Type definitions are not assignable in a mrt sense
// in any way. Assignability of those types is handled by reflection logic.
// Call this case out first and here so that these only somewhat filled in
// types do not leak into the rest of the type casting logic.
if (pTargetType->IsGenericTypeDefinition || pSourceType->IsGenericTypeDefinition)
{
return false;
}
// Special case: T can be cast to Nullable<T> (where T is a value type). Call this case out here
// since this is only applicable if T is boxed, which is not true for any other callers of
// AreTypesAssignableInternal, so no sense making all the other paths pay the cost of the check.
if (pTargetType->IsNullable && pSourceType->IsValueType && !pSourceType->IsNullable)
{
EEType* pNullableType = pTargetType->GetNullableType();
return AreTypesEquivalentInternal(pSourceType, pNullableType);
}
return AreTypesAssignableInternal(pSourceType, pTargetType, true, false);
}
// Internally callable version of the export method above. Has two additional parameters:
// fBoxedSource : assume the source type is boxed so that value types and enums are
// compatible with Object, ValueType and Enum (if applicable)
// fAllowSizeEquivalence : allow identically sized integral types and enums to be considered
// equivalent (currently used only for array element types)
static internal unsafe bool AreTypesAssignableInternal(EEType* pSourceType, EEType* pTargetType, bool fBoxedSource, bool fAllowSizeEquivalence)
{
//
// Are the types identical?
//
if (AreTypesEquivalentInternal(pSourceType, pTargetType))
return true;
//
// Handle cast to interface cases.
//
if (pTargetType->IsInterface)
{
// Value types can only be cast to interfaces if they're boxed.
if (!fBoxedSource && pSourceType->IsValueType)
return false;
if (ImplementsInterface(pSourceType, pTargetType))
return true;
// Are the types compatible due to generic variance?
if (pTargetType->HasGenericVariance && pSourceType->HasGenericVariance)
return TypesAreCompatibleViaGenericVariance(pSourceType, pTargetType);
return false;
}
if (pSourceType->IsInterface)
{
// The only non-interface type an interface can be cast to is Object.
return WellKnownEETypes.IsSystemObject(pTargetType);
}
//
// Handle cast to array or pointer cases.
//
if (pTargetType->IsParameterizedType)
{
if (pSourceType->IsParameterizedType && (pTargetType->ParameterizedTypeShape == pSourceType->ParameterizedTypeShape))
{
// Source type is also a parameterized type. Are the parameter types compatible? Note that using
// AreTypesAssignableInternal here handles array covariance as well as IFoo[] -> Foo[]
// etc. Pass false for fBoxedSource since int[] is not assignable to object[].
if (pSourceType->RelatedParameterType->IsPointerTypeDefinition)
{
// If the parameter types are pointers, then only exact matches are correct.
// As we've already called AreTypesEquivalent at the start of this function,
// return false as the exact match case has already been handled.
// int** is not compatible with uint**, nor is int*[] oompatible with uint*[].
return false;
}
else
{
return AreTypesAssignableInternal(pSourceType->RelatedParameterType, pTargetType->RelatedParameterType, false, true);
}
}
// Can't cast a non-parameter type to a parameter type or a parameter type of different shape to a parameter type
return false;
}
if (pSourceType->IsArray)
{
// Target type is not an array. But we can still cast arrays to Object or System.Array.
return WellKnownEETypes.IsSystemObject(pTargetType) || WellKnownEETypes.IsSystemArray(pTargetType);
}
else if (pSourceType->IsParameterizedType)
{
return false;
}
//
// Handle cast to other (non-interface, non-array) cases.
//
if (pSourceType->IsValueType)
{
// Certain value types of the same size are treated as equivalent when the comparison is
// between array element types (indicated by fAllowSizeEquivalence). These are integer types
// of the same size (e.g. int and uint) and the base type of enums vs all integer types of the
// same size.
if (fAllowSizeEquivalence && pTargetType->IsValueType)
{
if (ArePrimitveTypesEquivalentSize(pSourceType, pTargetType))
return true;
// Non-identical value types aren't equivalent in any other case (since value types are
// sealed).
return false;
}
// If the source type is a value type but it's not boxed then we've run out of options: the types
// are not identical, the target type isn't an interface and we're not allowed to check whether
// the target type is a parent of this one since value types are sealed and thus the only matches
// would be against Object, ValueType or Enum, all of which are reference types and not compatible
// with non-boxed value types.
if (!fBoxedSource)
return false;
}
// Sub case of casting between two instantiations of the same delegate type where one or more of
// the type parameters have variance. Only interfaces and delegate types can have variance over
// their type parameters and we know that neither type is an interface due to checks above.
if (pTargetType->HasGenericVariance && pSourceType->HasGenericVariance)
{
// We've dealt with the identical case at the start of this method. And the regular path below
// will handle casting to Object, Delegate and MulticastDelegate. Since we don't support
// deriving from user delegate classes any further all we have to check here is that the
// uninstantiated generic delegate definitions are the same and the type parameters are
// compatible.
return TypesAreCompatibleViaGenericVariance(pSourceType, pTargetType);
}
// Is the source type derived from the target type?
if (IsDerived(pSourceType, pTargetType))
return true;
return false;
}
[RuntimeExport("RhTypeCast_CheckCastInterface")]
static public unsafe object CheckCastInterface(Object obj, void* pvTargetEEType)
{
// a null value can be cast to anything
if (obj == null)
{
return null;
}
EEType* pTargetType = (EEType*)pvTargetEEType;
EEType* pObjType = obj.EEType;
if (ImplementsInterface(pObjType, pTargetType))
return obj;
Exception castError = null;
// If object type implements ICastable then there's one more way to check whether it implements
// the interface.
if (pObjType->IsICastable)
{
// Call the ICastable.IsInstanceOfInterface method directly rather than via an interface
// dispatch since we know the method address statically.
IntPtr pfnIsInstanceOfInterface = pObjType->ICastableIsInstanceOfInterfaceMethod;
if (CalliIntrinsics.Call<bool>(pfnIsInstanceOfInterface, obj, pTargetType, out castError))
return obj;
}
// Throw the invalid cast exception defined by the classlib, using the input EEType* to find the
// correct classlib unless ICastable.IsInstanceOfInterface returned a more specific exception for
// us to use.
IntPtr addr = ((EEType*)pvTargetEEType)->GetAssociatedModuleAddress();
if (castError == null)
castError = EH.GetClasslibException(ExceptionIDs.InvalidCast, addr);
BinderIntrinsics.TailCall_RhpThrowEx(castError);
throw castError;
}
[RuntimeExport("RhTypeCast_CheckArrayStore")]
static public unsafe void CheckArrayStore(object array, object obj)
{
if (array == null || obj == null)
{
return;
}
Debug.Assert(array.EEType->IsArray, "first argument must be an array");
EEType* arrayElemType = array.EEType->RelatedParameterType;
bool compatible;
if (arrayElemType->IsInterface)
{
compatible = IsInstanceOfInterface(obj, arrayElemType) != null;
}
else if (arrayElemType->IsArray)
{
compatible = IsInstanceOfArray(obj, arrayElemType) != null;
}
else
{
compatible = IsInstanceOfClass(obj, arrayElemType) != null;
}
if (!compatible)
{
// Throw the array type mismatch exception defined by the classlib, using the input array's EEType*
// to find the correct classlib.
ExceptionIDs exID = ExceptionIDs.ArrayTypeMismatch;
IntPtr addr = array.EEType->GetAssociatedModuleAddress();
Exception e = EH.GetClasslibException(exID, addr);
BinderIntrinsics.TailCall_RhpThrowEx(e);
}
}
[RuntimeExport("RhTypeCast_CheckVectorElemAddr")]
static public unsafe void CheckVectorElemAddr(void* pvElemType, object array)
{
if (array == null)
{
return;
}
Debug.Assert(array.EEType->IsArray, "second argument must be an array");
EEType* elemType = (EEType*)pvElemType;
EEType* arrayElemType = array.EEType->RelatedParameterType;
if (!AreTypesEquivalentInternal(elemType, arrayElemType)
// In addition to the exactness check, add another check to allow non-exact matches through
// if the element type is a ValueType. The issue here is Universal Generics. The Universal
// Generic codegen will generate a call to this helper for all ldelema opcodes if the exact
// type is not known, and this can include ValueTypes. For ValueTypes, the exact check is not
// desireable as enum's are allowed to pass through this code if they are size matched.
// While this check is overly broad and allows non-enum valuetypes to also skip the check
// that is OK, because in the non-enum case the casting operations are sufficient to ensure
// type safety.
&& !elemType->IsValueType)
{
// Throw the array type mismatch exception defined by the classlib, using the input array's EEType*
// to find the correct classlib.
ExceptionIDs exID = ExceptionIDs.ArrayTypeMismatch;
IntPtr addr = array.EEType->GetAssociatedModuleAddress();
Exception e = EH.GetClasslibException(exID, addr);
BinderIntrinsics.TailCall_RhpThrowEx(e);
}
}
#if CORERT
// CORERT-TODO: Remove once ref locals are available in C# (https://github.com/dotnet/roslyn/issues/118)
[RuntimeImport(Redhawk.BaseName, "RhpAssignRef")]
[MethodImpl(MethodImplOptions.InternalCall)]
static private unsafe extern void RhpAssignRef(IntPtr * address, object obj);
// Size of array header in number of IntPtr-sized elements
private const int ArrayBaseIndex = 2;
[RuntimeExport("RhpStelemRef")]
static public unsafe void StelemRef(Object array, int index, object obj)
{
// This is supported only on arrays
Debug.Assert(array.EEType->IsArray, "first argument must be an array");
if (index >= array.GetArrayLength())
{
IntPtr addr = array.EEType->GetAssociatedModuleAddress();
Exception e = EH.GetClasslibException(ExceptionIDs.IndexOutOfRange, addr);
throw e;
}
if (obj != null)
{
EEType* arrayElemType = array.EEType->RelatedParameterType;
bool compatible;
if (arrayElemType->IsInterface)
{
compatible = IsInstanceOfInterface(obj, arrayElemType) != null;
}
else if (arrayElemType->IsArray)
{
compatible = IsInstanceOfArray(obj, arrayElemType) != null;
}
else
{
compatible = IsInstanceOfClass(obj, arrayElemType) != null;
}
if (!compatible)
{
// Throw the array type mismatch exception defined by the classlib, using the input array's EEType*
// to find the correct classlib.
IntPtr addr = array.EEType->GetAssociatedModuleAddress();
Exception e = EH.GetClasslibException(ExceptionIDs.ArrayTypeMismatch, addr);
BinderIntrinsics.TailCall_RhpThrowEx(e);
}
// Both bounds and type check are ok.
fixed (void * pArray = &array.m_pEEType)
{
RhpAssignRef((IntPtr*)pArray + ArrayBaseIndex + index, obj);
}
}
else
{
fixed (void * pArray = &array.m_pEEType)
{
// Storing null does not require write barrier
*((IntPtr*)pArray + ArrayBaseIndex + index) = default(IntPtr);
}
}
}
[RuntimeExport("RhpLdelemaRef")]
static public unsafe void * LdelemaRef(Object array, int index, IntPtr elementType)
{
Debug.Assert(array.EEType->IsArray, "second argument must be an array");
EEType* elemType = (EEType*)elementType;
EEType* arrayElemType = array.EEType->RelatedParameterType;
if (!AreTypesEquivalentInternal(elemType, arrayElemType))
{
// Throw the array type mismatch exception defined by the classlib, using the input array's EEType*
// to find the correct classlib.
IntPtr addr = array.EEType->GetAssociatedModuleAddress();
Exception e = EH.GetClasslibException(ExceptionIDs.ArrayTypeMismatch, addr);
BinderIntrinsics.TailCall_RhpThrowEx(e);
}
fixed (void * pArray = &array.m_pEEType)
{
// CORERT-TODO: This code has GC hole - the method return type should really be byref.
// Requires byref returns in C# to fix cleanly (https://github.com/dotnet/roslyn/issues/118)
return (IntPtr*)pArray + ArrayBaseIndex + index;
}
}
#endif
static internal unsafe bool IsDerived(EEType* pDerivedType, EEType* pBaseType)
{
Debug.Assert(!pDerivedType->IsArray, "did not expect array type");
Debug.Assert(!pDerivedType->IsParameterizedType, "did not expect parameterType");
Debug.Assert(!pBaseType->IsArray, "did not expect array type");
Debug.Assert(!pBaseType->IsInterface, "did not expect interface type");
Debug.Assert(!pBaseType->IsParameterizedType, "did not expect parameterType");
Debug.Assert(pBaseType->IsCanonical || pBaseType->IsCloned || pBaseType->IsGenericTypeDefinition, "unexpected eetype");
Debug.Assert(pDerivedType->IsCanonical || pDerivedType->IsCloned || pDerivedType->IsGenericTypeDefinition, "unexpected eetype");
// If a generic type definition reaches this function, then the function should return false unless the types are equivalent.
// This works as the NonClonedNonArrayBaseType of a GenericTypeDefinition is always null.
if (pBaseType->IsCloned)
pBaseType = pBaseType->CanonicalEEType;
do
{
if (pDerivedType->IsCloned)
pDerivedType = pDerivedType->CanonicalEEType;
if (pDerivedType == pBaseType)
return true;
pDerivedType = pDerivedType->NonClonedNonArrayBaseType;
}
while (pDerivedType != null);
return false;
}
[RuntimeExport("RhTypeCast_AreTypesEquivalent")]
static unsafe public bool AreTypesEquivalent(EETypePtr pType1, EETypePtr pType2)
{
return (AreTypesEquivalentInternal(pType1.ToPointer(), pType2.ToPointer()));
}
// Method to compare two types pointers for type equality
// We cannot just compare the pointers as there can be duplicate type instances
// for cloned and constructed types.
// There are three separate cases here
// 1. The pointers are Equal => true
// 2. Either one or both the types are CLONED, follow to the canonical EEType and check
// 3. For Arrays/Pointers, we have to further check for rank and element type equality
static internal unsafe bool AreTypesEquivalentInternal(EEType* pType1, EEType* pType2)
{
if (pType1 == pType2)
return true;
if (pType1->IsCloned)
pType1 = pType1->CanonicalEEType;
if (pType2->IsCloned)
pType2 = pType2->CanonicalEEType;
if (pType1 == pType2)
return true;
if (pType1->IsParameterizedType && pType2->IsParameterizedType)
return AreTypesEquivalentInternal(pType1->RelatedParameterType, pType2->RelatedParameterType) && pType1->ParameterizedTypeShape == pType2->ParameterizedTypeShape;
return false;
}
// this is necessary for shared generic code - Foo<T> may be executing
// for T being an interface, an array or a class
[RuntimeExport("RhTypeCast_IsInstanceOf")]
static public unsafe object IsInstanceOf(object obj, void* pvTargetType)
{
EEType* pTargetType = (EEType*)pvTargetType;
if (pTargetType->IsArray)
return IsInstanceOfArray(obj, pvTargetType);
else if (pTargetType->IsInterface)
return IsInstanceOfInterface(obj, pvTargetType);
else
return IsInstanceOfClass(obj, pvTargetType);
}
[RuntimeExport("RhTypeCast_CheckCast")]
static public unsafe object CheckCast(Object obj, void* pvTargetType)
{
EEType* pTargetType = (EEType*)pvTargetType;
if (pTargetType->IsArray)
return CheckCastArray(obj, pvTargetType);
else if (pTargetType->IsInterface)
return CheckCastInterface(obj, pvTargetType);
else
return CheckCastClass(obj, pvTargetType);
}
// Returns true of the two types are equivalent primitive types. Used by array casts.
static private unsafe bool ArePrimitveTypesEquivalentSize(EEType* pType1, EEType* pType2)
{
CorElementType sourceCorType = pType1->CorElementType;
int sourcePrimitiveTypeEquivalenceSize = GetIntegralTypeMatchSize(sourceCorType);
// Quick check to see if the first type is even primitive.
if (sourcePrimitiveTypeEquivalenceSize == 0)
return false;
CorElementType targetCorType = pType2->CorElementType;
int targetPrimitiveTypeEquivalenceSize = GetIntegralTypeMatchSize(targetCorType);
return sourcePrimitiveTypeEquivalenceSize == targetPrimitiveTypeEquivalenceSize;
}
private unsafe static int GetIntegralTypeMatchSize(CorElementType corType)
{
switch (corType)
{
case CorElementType.ELEMENT_TYPE_I1:
case CorElementType.ELEMENT_TYPE_U1:
return 1;
case CorElementType.ELEMENT_TYPE_I2:
case CorElementType.ELEMENT_TYPE_U2:
return 2;
case CorElementType.ELEMENT_TYPE_I4:
case CorElementType.ELEMENT_TYPE_U4:
return 4;
case CorElementType.ELEMENT_TYPE_I8:
case CorElementType.ELEMENT_TYPE_U8:
return 8;
case CorElementType.ELEMENT_TYPE_I:
case CorElementType.ELEMENT_TYPE_U:
return sizeof(IntPtr);
default:
return 0;
}
}
// copied from CorHdr.h
internal enum CorElementType : byte
{
ELEMENT_TYPE_END = 0x0,
ELEMENT_TYPE_VOID = 0x1,
ELEMENT_TYPE_BOOLEAN = 0x2,
ELEMENT_TYPE_CHAR = 0x3,
ELEMENT_TYPE_I1 = 0x4,
ELEMENT_TYPE_U1 = 0x5,
ELEMENT_TYPE_I2 = 0x6,
ELEMENT_TYPE_U2 = 0x7,
ELEMENT_TYPE_I4 = 0x8,
ELEMENT_TYPE_U4 = 0x9,
ELEMENT_TYPE_I8 = 0xa,
ELEMENT_TYPE_U8 = 0xb,
ELEMENT_TYPE_R4 = 0xc,
ELEMENT_TYPE_R8 = 0xd,
ELEMENT_TYPE_STRING = 0xe,
// every type above PTR will be simple type
ELEMENT_TYPE_PTR = 0xf, // PTR <type>
ELEMENT_TYPE_BYREF = 0x10, // BYREF <type>
// Please use ELEMENT_TYPE_VALUETYPE. ELEMENT_TYPE_VALUECLASS is deprecated.
ELEMENT_TYPE_VALUETYPE = 0x11, // VALUETYPE <class Token>
ELEMENT_TYPE_CLASS = 0x12, // CLASS <class Token>
ELEMENT_TYPE_VAR = 0x13, // a class type variable VAR <U1>
ELEMENT_TYPE_ARRAY = 0x14, // MDARRAY <type> <rank> <bcount> <bound1> ... <lbcount> <lb1> ...
ELEMENT_TYPE_GENERICINST = 0x15, // GENERICINST <generic type> <argCnt> <arg1> ... <argn>
ELEMENT_TYPE_TYPEDBYREF = 0x16, // TYPEDREF (it takes no args) a typed referece to some other type
ELEMENT_TYPE_I = 0x18, // native integer size
ELEMENT_TYPE_U = 0x19, // native unsigned integer size
ELEMENT_TYPE_FNPTR = 0x1B, // FNPTR <complete sig for the function including calling convention>
ELEMENT_TYPE_OBJECT = 0x1C, // Shortcut for System.Object
ELEMENT_TYPE_SZARRAY = 0x1D, // Shortcut for single dimension zero lower bound array
// SZARRAY <type>
ELEMENT_TYPE_MVAR = 0x1e, // a method type variable MVAR <U1>
// This is only for binding
ELEMENT_TYPE_CMOD_REQD = 0x1F, // required C modifier : E_T_CMOD_REQD <mdTypeRef/mdTypeDef>
ELEMENT_TYPE_CMOD_OPT = 0x20, // optional C modifier : E_T_CMOD_OPT <mdTypeRef/mdTypeDef>
// This is for signatures generated internally (which will not be persisted in any way).
ELEMENT_TYPE_INTERNAL = 0x21, // INTERNAL <typehandle>
// Note that this is the max of base type excluding modifiers
ELEMENT_TYPE_MAX = 0x22, // first invalid element type
ELEMENT_TYPE_MODIFIER = 0x40,
ELEMENT_TYPE_SENTINEL = 0x01 | ELEMENT_TYPE_MODIFIER, // sentinel for varargs
ELEMENT_TYPE_PINNED = 0x05 | ELEMENT_TYPE_MODIFIER,
}
}
}
| |
// 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;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Security.Permissions;
namespace System.Timers
{
/// <summary>
/// <para>Handles recurring events in an application.</para>
/// </summary>
[DefaultProperty("Interval"), DefaultEvent("Elapsed"), HostProtection(Synchronization = true, ExternalThreading = true)]
public partial class Timer : Component, ISupportInitialize
{
private double _interval;
private bool _enabled;
private bool _initializing;
private bool _delayedEnable;
private ElapsedEventHandler _onIntervalElapsed;
private bool _autoReset;
private ISynchronizeInvoke _synchronizingObject;
private bool _disposed;
private Threading.Timer _timer;
private TimerCallback _callback;
private object _cookie;
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Timers.Timer'/> class, with the properties
/// set to initial values.</para>
/// </summary>
public Timer()
: base()
{
_interval = 100;
_enabled = false;
_autoReset = true;
_initializing = false;
_delayedEnable = false;
_callback = new TimerCallback(MyTimerCallback);
}
/// <summary>
/// <para>
/// Initializes a new instance of the <see cref='System.Timers.Timer'/> class, setting the <see cref='System.Timers.Timer.Interval'/> property to the specified period.
/// </para>
/// </summary>
public Timer(double interval)
: this()
{
if (interval <= 0)
throw new ArgumentException(SR.Format(SR.InvalidParameter, "interval", interval));
double roundedInterval = Math.Ceiling(interval);
if (roundedInterval > int.MaxValue || roundedInterval <= 0)
{
throw new ArgumentException(SR.Format(SR.InvalidParameter, "interval", interval));
}
_interval = (int)roundedInterval;
}
/// <summary>
/// <para>Gets or sets a value indicating whether the Timer raises the Tick event each time the specified
/// Interval has elapsed,
/// when Enabled is set to true.</para>
/// </summary>
[TimersDescription(nameof(SR.TimerAutoReset), null), DefaultValue(true)]
public bool AutoReset
{
get
{
return _autoReset;
}
set
{
if (DesignMode)
_autoReset = value;
else if (_autoReset != value)
{
_autoReset = value;
if (_timer != null)
{
UpdateTimer();
}
}
}
}
/// <summary>
/// <para>Gets or sets a value indicating whether the <see cref='System.Timers.Timer'/>
/// is able
/// to raise events at a defined interval.</para>
/// </summary>
// The default value by design is false, don't change it.
[TimersDescription(nameof(SR.TimerEnabled), null), DefaultValue(false)]
public bool Enabled
{
get
{
return _enabled;
}
set
{
if (DesignMode)
{
_delayedEnable = value;
_enabled = value;
}
else if (_initializing)
_delayedEnable = value;
else if (_enabled != value)
{
if (!value)
{
if (_timer != null)
{
_cookie = null;
_timer.Dispose();
_timer = null;
}
_enabled = value;
}
else
{
_enabled = value;
if (_timer == null)
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
int i = (int)Math.Ceiling(_interval);
_cookie = new object();
_timer = new Threading.Timer(_callback, _cookie, Timeout.Infinite, Timeout.Infinite);
_timer.Change(i, _autoReset ? i : Timeout.Infinite);
}
else
{
UpdateTimer();
}
}
}
}
}
private void UpdateTimer()
{
int i = (int)Math.Ceiling(_interval);
_timer.Change(i, _autoReset ? i : Timeout.Infinite);
}
/// <summary>
/// <para>Gets or
/// sets the interval on which
/// to raise events.</para>
/// </summary>
[TimersDescription(nameof(SR.TimerInterval), null), DefaultValue(100d)]
public double Interval
{
get
{
return _interval;
}
set
{
if (value <= 0)
throw new ArgumentException(SR.Format(SR.TimerInvalidInterval, value, 0));
_interval = value;
if (_timer != null)
{
UpdateTimer();
}
}
}
/// <summary>
/// <para>Occurs when the <see cref='System.Timers.Timer.Interval'/> has
/// elapsed.</para>
/// </summary>
[TimersDescription(nameof(SR.TimerIntervalElapsed), null)]
public event ElapsedEventHandler Elapsed
{
add
{
_onIntervalElapsed += value;
}
remove
{
_onIntervalElapsed -= value;
}
}
/// <summary>
/// <para>
/// Sets the enable property in design mode to true by default.
/// </para>
/// </summary>
/// <internalonly/>
public override ISite Site
{
get
{
return base.Site;
}
set
{
base.Site = value;
if (DesignMode)
_enabled = true;
}
}
/// <summary>
/// <para>Gets or sets the object used to marshal event-handler calls that are issued when
/// an interval has elapsed.</para>
/// </summary>
[DefaultValue(null), TimersDescription(nameof(SR.TimerSynchronizingObject), null)]
public ISynchronizeInvoke SynchronizingObject
{
get
{
if (_synchronizingObject == null && DesignMode)
{
IDesignerHost host = (IDesignerHost)GetService(typeof(IDesignerHost));
if (host != null)
{
object baseComponent = host.RootComponent;
if (baseComponent != null && baseComponent is ISynchronizeInvoke)
_synchronizingObject = (ISynchronizeInvoke)baseComponent;
}
}
return _synchronizingObject;
}
set
{
_synchronizingObject = value;
}
}
/// <summary>
/// <para>
/// Notifies
/// the object that initialization is beginning and tells it to stand by.
/// </para>
/// </summary>
public void BeginInit()
{
Close();
_initializing = true;
}
/// <summary>
/// <para>Disposes of the resources (other than memory) used by
/// the <see cref='System.Timers.Timer'/>.</para>
/// </summary>
public void Close()
{
_initializing = false;
_delayedEnable = false;
_enabled = false;
if (_timer != null)
{
_timer.Dispose();
_timer = null;
}
}
protected override void Dispose(bool disposing)
{
Close();
_disposed = true;
base.Dispose(disposing);
}
/// <summary>
/// <para>
/// Notifies the object that initialization is complete.
/// </para>
/// </summary>
public void EndInit()
{
_initializing = false;
Enabled = _delayedEnable;
}
/// <summary>
/// <para>Starts the timing by setting <see cref='System.Timers.Timer.Enabled'/> to <see langword='true'/>.</para>
/// </summary>
public void Start()
{
Enabled = true;
}
/// <summary>
/// <para>
/// Stops the timing by setting <see cref='System.Timers.Timer.Enabled'/> to <see langword='false'/>.
/// </para>
/// </summary>
public void Stop()
{
Enabled = false;
}
private void MyTimerCallback(object state)
{
// System.Threading.Timer will not cancel the work item queued before the timer is stopped.
// We don't want to handle the callback after a timer is stopped.
if (state != _cookie)
{
return;
}
if (!_autoReset)
{
_enabled = false;
}
ElapsedEventArgs elapsedEventArgs = new ElapsedEventArgs(DateTime.UtcNow.ToFileTime());
try
{
// To avoid race between remove handler and raising the event
ElapsedEventHandler intervalElapsed = _onIntervalElapsed;
if (intervalElapsed != null)
{
if (SynchronizingObject != null && SynchronizingObject.InvokeRequired)
SynchronizingObject.BeginInvoke(intervalElapsed, new object[] { this, elapsedEventArgs });
else
intervalElapsed(this, elapsedEventArgs);
}
}
catch
{
}
}
}
}
| |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
using System;
namespace Org.BouncyCastle.Math.EC.Custom.Sec
{
internal class SecT163K1Point
: AbstractF2mPoint
{
/**
* @deprecated Use ECCurve.createPoint to construct points
*/
public SecT163K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y)
: this(curve, x, y, false)
{
}
/**
* @deprecated per-point compression property will be removed, refer {@link #getEncoded(bool)}
*/
public SecT163K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression)
: base(curve, x, y, withCompression)
{
if ((x == null) != (y == null))
throw new ArgumentException("Exactly one of the field elements is null");
}
internal SecT163K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression)
: base(curve, x, y, zs, withCompression)
{
}
protected override ECPoint Detach()
{
return new SecT163K1Point(null, this.AffineXCoord, this.AffineYCoord);
}
public override ECFieldElement YCoord
{
get
{
ECFieldElement X = RawXCoord, L = RawYCoord;
if (this.IsInfinity || X.IsZero)
return L;
// Y is actually Lambda (X + Y/X) here; convert to affine value on the fly
ECFieldElement Y = L.Add(X).Multiply(X);
ECFieldElement Z = RawZCoords[0];
if (!Z.IsOne)
{
Y = Y.Divide(Z);
}
return Y;
}
}
protected internal override bool CompressionYTilde
{
get
{
ECFieldElement X = this.RawXCoord;
if (X.IsZero)
return false;
ECFieldElement Y = this.RawYCoord;
// Y is actually Lambda (X + Y/X) here
return Y.TestBitZero() != X.TestBitZero();
}
}
public override ECPoint Add(ECPoint b)
{
if (this.IsInfinity)
return b;
if (b.IsInfinity)
return this;
ECCurve curve = this.Curve;
ECFieldElement X1 = this.RawXCoord;
ECFieldElement X2 = b.RawXCoord;
if (X1.IsZero)
{
if (X2.IsZero)
return curve.Infinity;
return b.Add(this);
}
ECFieldElement L1 = this.RawYCoord, Z1 = this.RawZCoords[0];
ECFieldElement L2 = b.RawYCoord, Z2 = b.RawZCoords[0];
bool Z1IsOne = Z1.IsOne;
ECFieldElement U2 = X2, S2 = L2;
if (!Z1IsOne)
{
U2 = U2.Multiply(Z1);
S2 = S2.Multiply(Z1);
}
bool Z2IsOne = Z2.IsOne;
ECFieldElement U1 = X1, S1 = L1;
if (!Z2IsOne)
{
U1 = U1.Multiply(Z2);
S1 = S1.Multiply(Z2);
}
ECFieldElement A = S1.Add(S2);
ECFieldElement B = U1.Add(U2);
if (B.IsZero)
{
if (A.IsZero)
return Twice();
return curve.Infinity;
}
ECFieldElement X3, L3, Z3;
if (X2.IsZero)
{
// TODO This can probably be optimized quite a bit
ECPoint p = this.Normalize();
X1 = p.XCoord;
ECFieldElement Y1 = p.YCoord;
ECFieldElement Y2 = L2;
ECFieldElement L = Y1.Add(Y2).Divide(X1);
//X3 = L.Square().Add(L).Add(X1).Add(curve.getA());
X3 = L.Square().Add(L).Add(X1).AddOne();
if (X3.IsZero)
{
//return new SecT163K1Point(curve, X3, curve.B.sqrt(), IsCompressed);
return new SecT163K1Point(curve, X3, curve.B, IsCompressed);
}
ECFieldElement Y3 = L.Multiply(X1.Add(X3)).Add(X3).Add(Y1);
L3 = Y3.Divide(X3).Add(X3);
Z3 = curve.FromBigInteger(BigInteger.One);
}
else
{
B = B.Square();
ECFieldElement AU1 = A.Multiply(U1);
ECFieldElement AU2 = A.Multiply(U2);
X3 = AU1.Multiply(AU2);
if (X3.IsZero)
{
//return new SecT163K1Point(curve, X3, curve.B.sqrt(), IsCompressed);
return new SecT163K1Point(curve, X3, curve.B, IsCompressed);
}
ECFieldElement ABZ2 = A.Multiply(B);
if (!Z2IsOne)
{
ABZ2 = ABZ2.Multiply(Z2);
}
L3 = AU2.Add(B).SquarePlusProduct(ABZ2, L1.Add(Z1));
Z3 = ABZ2;
if (!Z1IsOne)
{
Z3 = Z3.Multiply(Z1);
}
}
return new SecT163K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed);
}
public override ECPoint Twice()
{
if (this.IsInfinity)
{
return this;
}
ECCurve curve = this.Curve;
ECFieldElement X1 = this.RawXCoord;
if (X1.IsZero)
{
// A point with X == 0 is it's own Additive inverse
return curve.Infinity;
}
ECFieldElement L1 = this.RawYCoord, Z1 = this.RawZCoords[0];
bool Z1IsOne = Z1.IsOne;
ECFieldElement L1Z1 = Z1IsOne ? L1 : L1.Multiply(Z1);
ECFieldElement Z1Sq = Z1IsOne ? Z1 : Z1.Square();
ECFieldElement T = L1.Square().Add(L1Z1).Add(Z1Sq);
if (T.IsZero)
{
//return new SecT163K1Point(curve, T, curve.B.sqrt(), withCompression);
return new SecT163K1Point(curve, T, curve.B, IsCompressed);
}
ECFieldElement X3 = T.Square();
ECFieldElement Z3 = Z1IsOne ? T : T.Multiply(Z1Sq);
ECFieldElement t1 = L1.Add(X1).Square();
ECFieldElement L3 = t1.Add(T).Add(Z1Sq).Multiply(t1).Add(X3);
return new SecT163K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed);
}
public override ECPoint TwicePlus(ECPoint b)
{
if (this.IsInfinity)
return b;
if (b.IsInfinity)
return Twice();
ECCurve curve = this.Curve;
ECFieldElement X1 = this.RawXCoord;
if (X1.IsZero)
{
// A point with X == 0 is it's own Additive inverse
return b;
}
// NOTE: TwicePlus() only optimized for lambda-affine argument
ECFieldElement X2 = b.RawXCoord, Z2 = b.RawZCoords[0];
if (X2.IsZero || !Z2.IsOne)
{
return Twice().Add(b);
}
ECFieldElement L1 = this.RawYCoord, Z1 = this.RawZCoords[0];
ECFieldElement L2 = b.RawYCoord;
ECFieldElement X1Sq = X1.Square();
ECFieldElement L1Sq = L1.Square();
ECFieldElement Z1Sq = Z1.Square();
ECFieldElement L1Z1 = L1.Multiply(Z1);
//ECFieldElement T = curve.getA().Multiply(Z1Sq).Add(L1Sq).Add(L1Z1);
ECFieldElement T = Z1Sq.Add(L1Sq).Add(L1Z1);
ECFieldElement L2plus1 = L2.AddOne();
//ECFieldElement A = curve.getA().Add(L2plus1).Multiply(Z1Sq).Add(L1Sq).MultiplyPlusProduct(T, X1Sq, Z1Sq);
ECFieldElement A = L2.Multiply(Z1Sq).Add(L1Sq).MultiplyPlusProduct(T, X1Sq, Z1Sq);
ECFieldElement X2Z1Sq = X2.Multiply(Z1Sq);
ECFieldElement B = X2Z1Sq.Add(T).Square();
if (B.IsZero)
{
if (A.IsZero)
return b.Twice();
return curve.Infinity;
}
if (A.IsZero)
{
//return new SecT163K1Point(curve, A, curve.B.sqrt(), withCompression);
return new SecT163K1Point(curve, A, curve.B, IsCompressed);
}
ECFieldElement X3 = A.Square().Multiply(X2Z1Sq);
ECFieldElement Z3 = A.Multiply(B).Multiply(Z1Sq);
ECFieldElement L3 = A.Add(B).Square().MultiplyPlusProduct(T, L2plus1, Z3);
return new SecT163K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed);
}
public override ECPoint Negate()
{
if (this.IsInfinity)
return this;
ECFieldElement X = this.RawXCoord;
if (X.IsZero)
return this;
// L is actually Lambda (X + Y/X) here
ECFieldElement L = this.RawYCoord, Z = this.RawZCoords[0];
return new SecT163K1Point(Curve, X, L.Add(Z), new ECFieldElement[] { Z }, IsCompressed);
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Threading;
using AVFoundation;
using CoreAnimation;
using CoreFoundation;
using CoreGraphics;
using CoreMedia;
using CoreVideo;
using Foundation;
using MobileCoreServices;
using ObjCRuntime;
using UIKit;
using VideoToolbox;
namespace VideoTimeLine
{
public partial class ViewController : UIViewController, IUIImagePickerControllerDelegate, IUIPopoverControllerDelegate, IUINavigationControllerDelegate
{
DispatchQueue backgroundQueue;
List<CVPixelBuffer> outputFrames;
List<double> presentationTimes;
double lastCallbackTime;
CADisplayLink displayLink;
SemaphoreSlim bufferSemaphore;
object thisLock;
CGAffineTransform videoPreferredTransform;
AVAssetReader assetReader;
UIPopoverController popover;
VTDecompressionSession decompressionSession;
public ViewController (IntPtr handle) : base (handle)
{
thisLock = new object ();
presentationTimes = new List<double> ();
outputFrames = new List<CVPixelBuffer> ();
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
backgroundQueue = new DispatchQueue ("com.videotimeline.backgroundqueue", false);
displayLink = CADisplayLink.Create (DisplayLinkCallback);
displayLink.AddToRunLoop (NSRunLoop.Current, NSRunLoopMode.Default);
displayLink.Paused = true;
lastCallbackTime = 0.0;
bufferSemaphore = new SemaphoreSlim (0);
}
public void DisplayLinkCallback ()
{
if (Math.Abs (lastCallbackTime) < float.Epsilon)
lastCallbackTime = displayLink.Timestamp;
double timeSinceLastCallback = displayLink.Timestamp - lastCallbackTime;
if (outputFrames.Count > 0 && presentationTimes.Count > 0) {
CVPixelBuffer pixelBuffer = null;
double framePTS;
lock (thisLock) {
framePTS = presentationTimes [0];
pixelBuffer = outputFrames [0];
}
if (timeSinceLastCallback >= framePTS) {
lock (thisLock) {
if (pixelBuffer != null)
outputFrames.RemoveAt (0);
presentationTimes.RemoveAt (0);
if (presentationTimes.Count == 3)
bufferSemaphore.Release ();
}
}
if (pixelBuffer != null) {
DisplayPixelBuffer (pixelBuffer, framePTS);
MoveTimeLine ();
}
}
}
partial void ChooseVideoTapped (UIBarButtonItem sender)
{
var videoPicker = new UIImagePickerController {
ModalPresentationStyle = UIModalPresentationStyle.CurrentContext,
SourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum,
MediaTypes = new string[] { UTType.Movie }
};
videoPicker.FinishedPickingMedia += (object s, UIImagePickerMediaPickedEventArgs e) => {
displayLink.Paused = true;
playButton.Title = "Play";
popover.Dismiss (true);
outputFrames.Clear ();
presentationTimes.Clear ();
lastCallbackTime = 0.0;
var asset = AVAsset.FromUrl (e.MediaUrl);
if (assetReader != null && assetReader.Status == AVAssetReaderStatus.Reading) {
bufferSemaphore.Release ();
assetReader.CancelReading ();
}
backgroundQueue.DispatchAsync (() => ReadSampleBuffers (asset));
};
videoPicker.Canceled += (object s, EventArgs e) => DismissViewController (true, null);
if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) {
popover = new UIPopoverController (videoPicker);
popover.PresentFromBarButtonItem (sender, UIPopoverArrowDirection.Down, true);
}
}
partial void PlayButtonTapped (UIBarButtonItem sender)
{
if (!displayLink.Paused) {
displayLink.Paused = true;
sender.Title = "Play";
} else {
displayLink.Paused = false;
sender.Title = "Pause";
}
}
void DisplayPixelBuffer (CVPixelBuffer pixelBuffer, double framePTS)
{
nint width = pixelBuffer.Width;
nint height = pixelBuffer.Height;
var f = View.Frame;
if (width > f.Width || height > f.Height) {
width /= 2;
height /= 2;
}
var layer = new EAGLLayer ();
if (Math.Abs (videoPreferredTransform.xx + 1f) < float.Epsilon)
layer.AffineTransform.Rotate (NMath.PI);
else if (Math.Abs (videoPreferredTransform.yy) < float.Epsilon)
layer.AffineTransform.Rotate (NMath.PI / 2);
layer.Frame = new CGRect (0f, View.Frame.Height - 50f - height, width, height);
layer.PresentationRect = new CGSize (width, height);
layer.TimeCode = framePTS.ToString ("0.000");
layer.SetupGL ();
View.Layer.AddSublayer (layer);
layer.DisplayPixelBuffer (pixelBuffer);
}
void MoveTimeLine ()
{
var layersForRemoval = new List<CALayer> ();
foreach (CALayer layer in View.Layer.Sublayers) {
if (layer is EAGLLayer) {
CGRect frame = layer.Frame;
var newFrame = new CGRect (frame.Location.X + 20f, frame.Location.Y - 20f, frame.Width, frame.Height);
layer.Frame = newFrame;
CGRect screenBounds = UIScreen.MainScreen.Bounds;
if ((newFrame.Location.X >= screenBounds.Location.X + screenBounds.Width) ||
newFrame.Location.Y >= (screenBounds.Location.Y + screenBounds.Height)) {
layersForRemoval.Add (layer);
}
}
}
foreach (var layer in layersForRemoval) {
layer.RemoveFromSuperLayer ();
layer.Dispose ();
}
}
void ReadSampleBuffers (AVAsset asset)
{
NSError error;
assetReader = AVAssetReader.FromAsset (asset, out error);
if (error != null)
Console.WriteLine ("Error creating Asset Reader: {0}", error.Description);
AVAssetTrack[] videoTracks = asset.TracksWithMediaType (AVMediaType.Video);
AVAssetTrack videoTrack = videoTracks [0];
CreateDecompressionSession (videoTrack);
var videoTrackOutput = AVAssetReaderTrackOutput.Create (videoTrack, (AVVideoSettingsUncompressed)null);
if (assetReader.CanAddOutput (videoTrackOutput))
assetReader.AddOutput (videoTrackOutput);
if (!assetReader.StartReading ())
return;
while (assetReader.Status == AVAssetReaderStatus.Reading) {
CMSampleBuffer sampleBuffer = videoTrackOutput.CopyNextSampleBuffer ();
if (sampleBuffer != null) {
VTDecodeFrameFlags flags = VTDecodeFrameFlags.EnableAsynchronousDecompression;
VTDecodeInfoFlags flagOut;
decompressionSession.DecodeFrame (sampleBuffer, flags, IntPtr.Zero, out flagOut);
sampleBuffer.Dispose ();
if (presentationTimes.Count >= 5)
bufferSemaphore.Wait ();
} else if (assetReader.Status == AVAssetReaderStatus.Failed) {
Console.WriteLine ("Asset Reader failed with error: {0}", assetReader.Error.Description);
} else if (assetReader.Status == AVAssetReaderStatus.Completed) {
Console.WriteLine("Reached the end of the video.");
ChangeStatus ();
ReadSampleBuffers (asset);
}
}
}
void ChangeStatus ()
{
InvokeOnMainThread (() => {
displayLink.Paused = true;
playButton.Title = "Play";
popover.Dismiss (true);
});
}
void CreateDecompressionSession (AVAssetTrack videoTrack)
{
CMFormatDescription[] formatDescriptions = videoTrack.FormatDescriptions;
var formatDescription = (CMVideoFormatDescription)formatDescriptions [0];
videoPreferredTransform = videoTrack.PreferredTransform;
decompressionSession = VTDecompressionSession.Create (DidDecompress, formatDescription);
}
void DidDecompress (IntPtr sourceFrame, VTStatus status, VTDecodeInfoFlags flags, CVImageBuffer buffer, CMTime presentationTimeStamp, CMTime presentationDuration)
{
if (status != VTStatus.Ok) {
Console.WriteLine ("Error decompresssing frame at time: {0:#.###} error: {1} infoFlags: {2}",
(float)presentationTimeStamp.Value / presentationTimeStamp.TimeScale, (int)status, flags);
return;
}
if (buffer == null)
return;
// Find the correct position for this frame in the output frames array
if (presentationTimeStamp.IsInvalid) {
Console.WriteLine ("Not a valid time for image buffer");
return;
}
var framePTS = presentationTimeStamp.Seconds;
lock (thisLock) {
// since we want to keep the managed `pixelBuffer` alive outside the execution
// of the callback we need to create our own (managed) instance from the handle
var pixelBuffer = Runtime.GetINativeObject<CVPixelBuffer> (buffer.Handle, false);
int insertionIndex = presentationTimes.Count - 1;
while (insertionIndex >= 0) {
var aNumber = presentationTimes [insertionIndex];
if (aNumber <= framePTS)
break;
insertionIndex--;
}
if (insertionIndex + 1 == presentationTimes.Count) {
presentationTimes.Add (framePTS);
outputFrames.Add (pixelBuffer);
} else {
presentationTimes.Insert (insertionIndex + 1, framePTS);
outputFrames.Insert (insertionIndex + 1, pixelBuffer);
}
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.HSSF.UserModel
{
using System;
using System.IO;
using NUnit.Framework;
using NPOI.HSSF.EventModel;
using NPOI.HSSF.Record;
using NPOI.POIFS.FileSystem;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using TestCases.Exceptions;
using TestCases.HSSF;
using TestCases.HSSF.UserModel;
using TestCases.SS.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.Util;
/**
* Class for Testing Excel's data validation mechanism
*
* @author Dragos Buleandra ( [email protected] )
*/
[TestFixture]
public class TestDataValidation : BaseTestDataValidation
{
public TestDataValidation()
: base(HSSFITestDataProvider.Instance)
{
}
public void AssertDataValidation(IWorkbook wb)
{
MemoryStream baos = new MemoryStream(22000);
try
{
wb.Write(baos);
baos.Close();
}
catch (IOException e)
{
throw new RuntimeException(e);
}
byte[] generatedContent = baos.ToArray();
#if !HIDE_UNREACHABLE_CODE
bool isSame;
if (false)
{
// TODO - add proof spreadsheet and compare
Stream proofStream = HSSFTestDataSamples.OpenSampleFileStream("TestDataValidation.xls");
isSame = CompareStreams(proofStream, generatedContent);
}
isSame = true;
if (isSame)
{
return;
}
//File tempDir = new File(System.GetProperty("java.io.tmpdir"));
string tempDir = Path.GetTempFileName();
//File generatedFile = new File(tempDir, "GeneratedTestDataValidation.xls");
try
{
FileStream fileOut = new FileStream(tempDir, FileMode.Create);
fileOut.Write(generatedContent, 0, generatedContent.Length);
fileOut.Close();
}
catch (IOException e)
{
throw new RuntimeException(e);
}
Console.WriteLine("This Test case has failed because the generated file differs from proof copy '"
); // TODO+ proofFile.AbsolutePath + "'.");
Console.WriteLine("The cause is usually a change to this Test, or some common spreadsheet generation code. "
+ "The developer has to decide whether the Changes were wanted or unwanted.");
Console.WriteLine("If the Changes to the generated version were unwanted, "
+ "make the fix elsewhere (do not modify this Test or the proof spreadsheet to Get the Test working).");
Console.WriteLine("If the Changes were wanted, make sure to open the newly generated file in Excel "
+ "and verify it manually. The new proof file should be submitted After it is verified to be correct.");
Console.WriteLine("");
Console.WriteLine("One other possible (but less likely) cause of a failed Test is a problem in the "
+ "comparison logic used here. Perhaps some extra file regions need to be ignored.");
Console.WriteLine("The generated file has been saved to '" + tempDir + "' for manual inspection.");
Assert.Fail("Generated file differs from proof copy. See sysout comments for details on how to fix.");
#endif
}
private static bool CompareStreams(Stream isA, byte[] generatedContent)
{
Stream isB = new MemoryStream(generatedContent);
// The allowable regions where the generated file can differ from the
// proof should be small (i.e. much less than 1K)
int[] allowableDifferenceRegions = {
0x0228, 16, // a region of the file Containing the OS username
0x506C, 8, // See RootProperty (super fields _seconds_2 and _days_2)
};
int[] diffs = StreamUtility.DiffStreams(isA, isB, allowableDifferenceRegions);
if (diffs == null)
{
return true;
}
System.Console.Error.WriteLine("Diff from proof: ");
for (int i = 0; i < diffs.Length; i++)
{
System.Console.Error.WriteLine("diff at offset: 0x" + (diffs[i]).ToString("X2"));
}
return false;
}
/* package */
static void SetCellValue(HSSFCell cell, String text)
{
cell.SetCellValue(new HSSFRichTextString(text));
}
[Test]
public void TestAddToExistingSheet()
{
// dvEmpty.xls is a simple one sheet workbook. With a DataValidations header record but no
// DataValidations. It's important that the example has one SHEETPROTECTION record.
// Such a workbook can be Created in Excel (2007) by Adding datavalidation for one cell
// and then deleting the row that Contains the cell.
IWorkbook wb = HSSFTestDataSamples.OpenSampleWorkbook("dvEmpty.xls");
int dvRow = 0;
ISheet sheet = wb.GetSheetAt(0);
IDataValidationHelper dataValidationHelper = sheet.GetDataValidationHelper();
IDataValidationConstraint dc = dataValidationHelper.CreateintConstraint(OperatorType.EQUAL, "42", null);
IDataValidation dv = dataValidationHelper.CreateValidation(dc, new CellRangeAddressList(dvRow, dvRow, 0, 0));
dv.EmptyCellAllowed = (/*setter*/false);
dv.ErrorStyle = (/*setter*/ERRORSTYLE.STOP);
dv.ShowPromptBox = (/*setter*/true);
dv.CreateErrorBox("Xxx", "Yyy");
dv.SuppressDropDownArrow = (/*setter*/true);
sheet.AddValidationData(dv);
MemoryStream baos = new MemoryStream();
try
{
wb.Write(baos);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
byte[] wbData = baos.ToArray();
#if !HIDE_UNREACHABLE_CODE
if (false)
{ // TODO (Jul 2008) fix EventRecordFactory to process unknown records, (and DV records for that matter)
ERFListener erfListener = null; // new MyERFListener();
EventRecordFactory erf = new EventRecordFactory(erfListener, null);
try
{
POIFSFileSystem fs = new POIFSFileSystem(new MemoryStream(baos.ToArray()));
throw new NotImplementedException("The method CreateDocumentInputStream of POIFSFileSystem is not implemented.");
//erf.ProcessRecords(fs.CreateDocumentInputStream("Workbook"));
}
catch (RecordFormatException e)
{
throw new RuntimeException(e);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
// else verify record ordering by navigating the raw bytes
#endif
byte[] dvHeaderRecStart = { (byte)0xB2, 0x01, 0x12, 0x00, };
int dvHeaderOffset = FindIndex(wbData, dvHeaderRecStart);
Assert.IsTrue(dvHeaderOffset > 0);
int nextRecIndex = dvHeaderOffset + 22;
int nextSid
= ((wbData[nextRecIndex + 0] << 0) & 0x00FF)
+ ((wbData[nextRecIndex + 1] << 8) & 0xFF00)
;
// nextSid should be for a DVRecord. If anything comes between the DV header record
// and the DV records, Excel will not be able to open the workbook without error.
if (nextSid == 0x0867)
{
throw new AssertionException("Identified bug 45519");
}
Assert.AreEqual(DVRecord.sid, nextSid);
}
private int FindIndex(byte[] largeData, byte[] searchPattern)
{
byte firstByte = searchPattern[0];
for (int i = 0; i < largeData.Length; i++)
{
if (largeData[i] != firstByte)
{
continue;
}
bool match = true;
for (int j = 1; j < searchPattern.Length; j++)
{
if (searchPattern[j] != largeData[i + j])
{
match = false;
break;
}
}
if (match)
{
return i;
}
}
return -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.Linq;
using System.Xml.Linq;
using System.Xml.XPath;
using Adxstudio.Xrm.Globalization;
using Adxstudio.Xrm.Resources;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
namespace Adxstudio.Xrm.Search
{
internal class ExtendedAttributeSearchResultInfo
{
private static readonly int[] _extendedInfoAttributeQueryTypes = new[] { 64, 0 };
public ExtendedAttributeSearchResultInfo(OrganizationServiceContext context, string logicalName, IDictionary<string, EntityMetadata> metadataCache)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
Context = context;
Metadata = GetEntityMetadata(context, logicalName, metadataCache);
DisplayName = GetEntityDisplayName(Metadata);
TypeCode = GetEntityTypeCode(Metadata);
AttributeLayoutXml = GetAttributeLayoutXml(context, Metadata, TypeCode);
}
public string DisplayName { get; private set; }
public EntityMetadata Metadata { get; private set; }
public int TypeCode { get; private set; }
protected XDocument AttributeLayoutXml { get; private set; }
protected OrganizationServiceContext Context { get; private set; }
public IDictionary<string, string> GetAttributes(Entity entity, IDictionary<string, EntityMetadata> metadataCache)
{
if (AttributeLayoutXml == null || entity == null)
{
return CreateBaseAttributesDictionary();
}
var attributeLookup = Metadata.Attributes.ToDictionary(a => a.LogicalName, a => a);
var attributes = CreateBaseAttributesDictionary();
var names = from cell in AttributeLayoutXml.XPathSelectElements("//cell")
select cell.Attribute("name")
into nameAttibute where nameAttibute != null
select nameAttibute.Value
into name where !string.IsNullOrEmpty(name)
select name;
foreach (var name in names)
{
AttributeMetadata attributeMetadata;
if (!attributeLookup.TryGetValue(name, out attributeMetadata))
{
continue;
}
var resultAttribute = GetSearchResultAttribute(Context, entity, attributeMetadata, metadataCache);
if (resultAttribute == null)
{
continue;
}
attributes[resultAttribute.Value.Key] = resultAttribute.Value.Value;
}
return attributes;
}
private IDictionary<string, string> CreateBaseAttributesDictionary()
{
return new Dictionary<string, string>
{
{ "_EntityDisplayName", DisplayName },
{ "_EntityTypeCode", TypeCode.ToString() },
};
}
private static XDocument GetAttributeLayoutXml(OrganizationServiceContext context, EntityMetadata metadata, int typeCode)
{
var queries = context.CreateQuery("savedquery")
.Where(e => e.GetAttributeValue<bool?>("isdefault").GetValueOrDefault(false) && e.GetAttributeValue<int>("returnedtypecode") == typeCode)
.ToList();
return (
from queryType in _extendedInfoAttributeQueryTypes
select queries.FirstOrDefault(e => e.GetAttributeValue<int>("querytype") == queryType)
into query where query != null
select XDocument.Parse(query.GetAttributeValue<string>("layoutxml"))).FirstOrDefault();
}
private static string GetEntityDisplayName(EntityMetadata metadata)
{
if (metadata == null)
{
throw new ArgumentNullException("metadata");
}
if (metadata.DisplayName != null && metadata.DisplayName.UserLocalizedLabel != null)
{
return metadata.DisplayName.GetLocalizedLabelString();
}
throw new InvalidOperationException("Unable to retrieve the label for entity name.".FormatWith(metadata.LogicalName));
}
private static EntityMetadata GetEntityMetadata(OrganizationServiceContext context, string logicalName, IDictionary<string, EntityMetadata> metadataCache)
{
EntityMetadata cachedMetadata;
if (metadataCache.TryGetValue(logicalName, out cachedMetadata))
{
return cachedMetadata;
}
var metadataReponse = context.Execute(new RetrieveEntityRequest { LogicalName = logicalName, EntityFilters = EntityFilters.Attributes }) as RetrieveEntityResponse;
if (metadataReponse != null && metadataReponse.EntityMetadata != null)
{
metadataCache[logicalName] = metadataReponse.EntityMetadata;
return metadataReponse.EntityMetadata;
}
throw new InvalidOperationException("Unable to retrieve the metadata for entity name {0}.".FormatWith(logicalName));
}
private static int GetEntityTypeCode(EntityMetadata metadata)
{
if (metadata == null)
{
throw new ArgumentNullException("metadata");
}
if (metadata.ObjectTypeCode != null)
{
return metadata.ObjectTypeCode.Value;
}
throw new InvalidOperationException("Unable to retrieve the object type code for entity name {0}.".FormatWith(metadata.LogicalName));
}
private static KeyValuePair<string, string>? GetSearchResultAttribute(OrganizationServiceContext context, Entity entity, AttributeMetadata attributeMetadata, IDictionary<string, EntityMetadata> metadataCache)
{
var label = attributeMetadata.DisplayName.GetLocalizedLabelString();
if (AttributeTypeEqualsOneOf(attributeMetadata, "lookup", "customer"))
{
return null;
}
if (AttributeTypeEqualsOneOf(attributeMetadata, "picklist"))
{
var picklistMetadata = attributeMetadata as PicklistAttributeMetadata;
if (picklistMetadata == null)
{
return null;
}
var picklistValue = entity.GetAttributeValue<OptionSetValue>(attributeMetadata.LogicalName);
if (picklistValue == null)
{
return null;
}
var option = picklistMetadata.OptionSet.Options.FirstOrDefault(o => o.Value != null && o.Value.Value == picklistValue.Value);
if (option == null || option.Label == null || option.Label.UserLocalizedLabel == null)
{
return null;
}
new KeyValuePair<string, string>(label, option.Label.GetLocalizedLabelString());
}
var value = entity.GetAttributeValue<object>(attributeMetadata.LogicalName);
return value == null ? null : new KeyValuePair<string, string>?(new KeyValuePair<string, string>(label, value.ToString()));
}
private static bool AttributeTypeEqualsOneOf(AttributeMetadata attributeMetadata, params string[] typeNames)
{
var attributeTypeName = attributeMetadata.AttributeType.Value.ToString();
return typeNames.Any(name => string.Equals(attributeTypeName, name, StringComparison.InvariantCultureIgnoreCase));
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.