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.Diagnostics;
using System.Runtime.Serialization;
namespace System.Collections.Specialized
{
/// <devdoc>
/// <para>
/// OrderedDictionary offers IDictionary syntax with ordering. Objects
/// added or inserted in an IOrderedDictionary must have both a key and an index, and
/// can be retrieved by either.
/// OrderedDictionary is used by the ParameterCollection because MSAccess relies on ordering of
/// parameters, while almost all other DBs do not. DataKeyArray also uses it so
/// DataKeys can be retrieved by either their name or their index.
///
/// OrderedDictionary implements IDeserializationCallback because it needs to have the
/// contained ArrayList and Hashtable deserialized before it tries to get its count and objects.
/// </para>
/// </devdoc>
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class OrderedDictionary : IOrderedDictionary, ISerializable, IDeserializationCallback
{
private ArrayList? _objectsArray;
private Hashtable? _objectsTable;
private int _initialCapacity;
private IEqualityComparer? _comparer;
private bool _readOnly;
private readonly SerializationInfo? _siInfo; //A temporary variable which we need during deserialization.
private const string KeyComparerName = "KeyComparer"; // Do not rename (binary serialization)
private const string ArrayListName = "ArrayList"; // Do not rename (binary serialization)
private const string ReadOnlyName = "ReadOnly"; // Do not rename (binary serialization)
private const string InitCapacityName = "InitialCapacity"; // Do not rename (binary serialization)
public OrderedDictionary() : this(0)
{
}
public OrderedDictionary(int capacity) : this(capacity, null)
{
}
public OrderedDictionary(IEqualityComparer? comparer) : this(0, comparer)
{
}
public OrderedDictionary(int capacity, IEqualityComparer? comparer)
{
_initialCapacity = capacity;
_comparer = comparer;
}
private OrderedDictionary(OrderedDictionary dictionary)
{
Debug.Assert(dictionary != null);
_readOnly = true;
_objectsArray = dictionary._objectsArray;
_objectsTable = dictionary._objectsTable;
_comparer = dictionary._comparer;
_initialCapacity = dictionary._initialCapacity;
}
protected OrderedDictionary(SerializationInfo info, StreamingContext context)
{
// We can't do anything with the keys and values until the entire graph has been deserialized
// and getting Counts and objects won't fail. For the time being, we'll just cache this.
// The graph is not valid until OnDeserialization has been called.
_siInfo = info;
}
/// <devdoc>
/// Gets the size of the table.
/// </devdoc>
public int Count
{
get
{
if (_objectsArray == null)
{
return 0;
}
return _objectsArray.Count;
}
}
/// <devdoc>
/// Indicates that the collection can grow.
/// </devdoc>
bool IDictionary.IsFixedSize
{
get
{
return _readOnly;
}
}
/// <devdoc>
/// Indicates that the collection is not read-only
/// </devdoc>
public bool IsReadOnly
{
get
{
return _readOnly;
}
}
/// <devdoc>
/// Indicates that this class is not synchronized
/// </devdoc>
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
/// <devdoc>
/// Gets the collection of keys in the table in order.
/// </devdoc>
public ICollection Keys
{
get
{
ArrayList objectsArray = EnsureObjectsArray();
return new OrderedDictionaryKeyValueCollection(objectsArray, true);
}
}
private ArrayList EnsureObjectsArray() => _objectsArray ??= new ArrayList(_initialCapacity);
private Hashtable EnsureObjectsTable() => _objectsTable ??= new Hashtable(_initialCapacity, _comparer);
/// <devdoc>
/// The SyncRoot object. Not used because IsSynchronized is false
/// </devdoc>
object ICollection.SyncRoot => this;
/// <devdoc>
/// Gets or sets the object at the specified index
/// </devdoc>
public object? this[int index]
{
get
{
ArrayList objectsArray = EnsureObjectsArray();
return ((DictionaryEntry)objectsArray[index]!).Value;
}
set
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
if (_objectsArray == null || index < 0 || index >= _objectsArray.Count)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
ArrayList objectsArray = EnsureObjectsArray();
Hashtable objectsTable = EnsureObjectsTable();
object key = ((DictionaryEntry)objectsArray[index]!).Key;
objectsArray[index] = new DictionaryEntry(key, value);
objectsTable[key] = value;
}
}
/// <devdoc>
/// Gets or sets the object with the specified key
/// </devdoc>
public object? this[object key]
{
get
{
if (_objectsTable == null)
{
return null;
}
return _objectsTable[key];
}
set
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
Hashtable objectsTable = EnsureObjectsTable();
if (objectsTable.Contains(key))
{
objectsTable[key] = value;
ArrayList objectsArray = EnsureObjectsArray();
objectsArray[IndexOfKey(key)] = new DictionaryEntry(key, value);
}
else
{
Add(key, value);
}
}
}
/// <devdoc>
/// Returns an arrayList of the values in the table
/// </devdoc>
public ICollection Values
{
get
{
ArrayList objectsArray = EnsureObjectsArray();
return new OrderedDictionaryKeyValueCollection(objectsArray, false);
}
}
/// <devdoc>
/// Adds a new entry to the table with the lowest-available index.
/// </devdoc>
public void Add(object key, object? value)
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
Hashtable objectsTable = EnsureObjectsTable();
ArrayList objectsArray = EnsureObjectsArray();
objectsTable.Add(key, value);
objectsArray.Add(new DictionaryEntry(key, value));
}
/// <devdoc>
/// Clears all elements in the table.
/// </devdoc>
public void Clear()
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
if (_objectsTable != null)
{
_objectsTable.Clear();
}
if (_objectsArray != null)
{
_objectsArray.Clear();
}
}
/// <devdoc>
/// Returns a readonly OrderedDictionary for the given OrderedDictionary.
/// </devdoc>
public OrderedDictionary AsReadOnly()
{
return new OrderedDictionary(this);
}
/// <devdoc>
/// Returns true if the key exists in the table, false otherwise.
/// </devdoc>
public bool Contains(object key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (_objectsTable == null)
{
return false;
}
return _objectsTable.Contains(key);
}
/// <devdoc>
/// Copies the table to an array. This will not preserve order.
/// </devdoc>
public void CopyTo(Array array, int index)
{
Hashtable objectsTable = EnsureObjectsTable();
objectsTable.CopyTo(array, index);
}
private int IndexOfKey(object key)
{
if (_objectsArray == null)
{
return -1;
}
for (int i = 0; i < _objectsArray.Count; i++)
{
object o = ((DictionaryEntry)_objectsArray[i]!).Key;
if (_comparer != null)
{
if (_comparer.Equals(o, key))
{
return i;
}
}
else
{
if (o.Equals(key))
{
return i;
}
}
}
return -1;
}
/// <devdoc>
/// Inserts a new object at the given index with the given key.
/// </devdoc>
public void Insert(int index, object key, object? value)
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
if (index > Count || index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
Hashtable objectsTable = EnsureObjectsTable();
ArrayList objectsArray = EnsureObjectsArray();
objectsTable.Add(key, value);
objectsArray.Insert(index, new DictionaryEntry(key, value));
}
/// <devdoc>
/// Removes the entry at the given index.
/// </devdoc>
public void RemoveAt(int index)
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
if (index >= Count || index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
Hashtable objectsTable = EnsureObjectsTable();
ArrayList objectsArray = EnsureObjectsArray();
object key = ((DictionaryEntry)objectsArray[index]!).Key;
objectsArray.RemoveAt(index);
objectsTable.Remove(key);
}
/// <devdoc>
/// Removes the entry with the given key.
/// </devdoc>
public void Remove(object key)
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
int index = IndexOfKey(key);
if (index < 0)
{
return;
}
Hashtable objectsTable = EnsureObjectsTable();
ArrayList objectsArray = EnsureObjectsArray();
objectsTable.Remove(key);
objectsArray.RemoveAt(index);
}
#region IDictionary implementation
public virtual IDictionaryEnumerator GetEnumerator()
{
ArrayList objectsArray = EnsureObjectsArray();
return new OrderedDictionaryEnumerator(objectsArray, OrderedDictionaryEnumerator.DictionaryEntry);
}
#endregion
#region IEnumerable implementation
IEnumerator IEnumerable.GetEnumerator()
{
ArrayList objectsArray = EnsureObjectsArray();
return new OrderedDictionaryEnumerator(objectsArray, OrderedDictionaryEnumerator.DictionaryEntry);
}
#endregion
#region ISerializable implementation
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
info.AddValue(KeyComparerName, _comparer, typeof(IEqualityComparer));
info.AddValue(ReadOnlyName, _readOnly);
info.AddValue(InitCapacityName, _initialCapacity);
object[] serArray = new object[Count];
ArrayList objectsArray = EnsureObjectsArray();
objectsArray.CopyTo(serArray);
info.AddValue(ArrayListName, serArray);
}
#endregion
#region IDeserializationCallback implementation
void IDeserializationCallback.OnDeserialization(object? sender)
{
OnDeserialization(sender);
}
protected virtual void OnDeserialization(object? sender)
{
if (_siInfo == null)
{
throw new SerializationException(SR.Serialization_InvalidOnDeser);
}
_comparer = (IEqualityComparer?)_siInfo.GetValue(KeyComparerName, typeof(IEqualityComparer));
_readOnly = _siInfo.GetBoolean(ReadOnlyName);
_initialCapacity = _siInfo.GetInt32(InitCapacityName);
object[]? serArray = (object[]?)_siInfo.GetValue(ArrayListName, typeof(object[]));
if (serArray != null)
{
Hashtable objectsTable = EnsureObjectsTable();
ArrayList objectsArray = EnsureObjectsArray();
foreach (object o in serArray)
{
DictionaryEntry entry;
try
{
// DictionaryEntry is a value type, so it can only be casted.
entry = (DictionaryEntry)o;
}
catch
{
throw new SerializationException(SR.OrderedDictionary_SerializationMismatch);
}
objectsArray.Add(entry);
objectsTable.Add(entry.Key, entry.Value);
}
}
}
#endregion
/// <devdoc>
/// OrderedDictionaryEnumerator works just like any other IDictionaryEnumerator, but it retrieves DictionaryEntries
/// in the order by index.
/// </devdoc>
private class OrderedDictionaryEnumerator : IDictionaryEnumerator
{
private readonly int _objectReturnType;
internal const int Keys = 1;
internal const int Values = 2;
internal const int DictionaryEntry = 3;
private readonly IEnumerator _arrayEnumerator;
internal OrderedDictionaryEnumerator(ArrayList array, int objectReturnType)
{
_arrayEnumerator = array.GetEnumerator();
_objectReturnType = objectReturnType;
}
/// <devdoc>
/// Retrieves the current DictionaryEntry. This is the same as Entry, but not strongly-typed.
/// </devdoc>
public object? Current
{
get
{
Debug.Assert(_arrayEnumerator.Current != null);
if (_objectReturnType == Keys)
{
return ((DictionaryEntry)_arrayEnumerator.Current).Key;
}
if (_objectReturnType == Values)
{
return ((DictionaryEntry)_arrayEnumerator.Current).Value;
}
return Entry;
}
}
/// <devdoc>
/// Retrieves the current DictionaryEntry
/// </devdoc>
public DictionaryEntry Entry
{
get
{
Debug.Assert(_arrayEnumerator.Current != null);
return new DictionaryEntry(((DictionaryEntry)_arrayEnumerator.Current).Key, ((DictionaryEntry)_arrayEnumerator.Current).Value);
}
}
/// <devdoc>
/// Retrieves the key of the current DictionaryEntry
/// </devdoc>
public object Key
{
get
{
Debug.Assert(_arrayEnumerator.Current != null);
return ((DictionaryEntry)_arrayEnumerator.Current).Key;
}
}
/// <devdoc>
/// Retrieves the value of the current DictionaryEntry
/// </devdoc>
public object? Value
{
get
{
Debug.Assert(_arrayEnumerator.Current != null);
return ((DictionaryEntry)_arrayEnumerator.Current).Value;
}
}
/// <devdoc>
/// Moves the enumerator pointer to the next member
/// </devdoc>
public bool MoveNext()
{
return _arrayEnumerator.MoveNext();
}
/// <devdoc>
/// Resets the enumerator pointer to the beginning.
/// </devdoc>
public void Reset()
{
_arrayEnumerator.Reset();
}
}
/// <devdoc>
/// OrderedDictionaryKeyValueCollection implements a collection for the Values and Keys properties
/// that is "live"- it will reflect changes to the OrderedDictionary on the collection made after the getter
/// was called.
/// </devdoc>
private class OrderedDictionaryKeyValueCollection : ICollection
{
private readonly ArrayList _objects;
private readonly bool _isKeys;
public OrderedDictionaryKeyValueCollection(ArrayList array, bool isKeys)
{
_objects = array;
_isKeys = isKeys;
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum_Index);
foreach (object? o in _objects)
{
Debug.Assert(o != null);
array.SetValue(_isKeys ? ((DictionaryEntry)o).Key : ((DictionaryEntry)o).Value, index);
index++;
}
}
int ICollection.Count
{
get
{
return _objects.Count;
}
}
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
object ICollection.SyncRoot
{
get
{
return _objects.SyncRoot;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return new OrderedDictionaryEnumerator(_objects, _isKeys == true ? OrderedDictionaryEnumerator.Keys : OrderedDictionaryEnumerator.Values);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Hosting;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Xsl;
using MetX.Data;
using MetX.IO;
using MetX.Library;
using Mvp.Xml.Common.Xsl;
using Mvp.Xml.Exslt;
namespace MetX.Pipelines
{
/// <summary>Generates Data and xlg specific code</summary>
public class CodeGenerator
{
public static string AppDomainAppPath;
private static string m_FullName;
/// <summary>
/// Returns an XmlDocument containing a xlgData document with the child elements: Tables, StoredProcedures, and Xsls relative to the list indicated by the supplied include/skip lists.
/// </summary>
public XmlDocument DataXml
{
get
{
ParseDataXml();
XmlDocument xmlDoc = new XmlDocument();
XmlElement root = xmlDoc.CreateElement("xlgDoc");
if (m_XlgDataXmlDoc.DocumentElement == null)
{
return null;
}
foreach (XmlAttribute currAttribute in m_XlgDataXmlDoc.DocumentElement.Attributes)
{
root.SetAttribute(currAttribute.Name, currAttribute.Value);
}
root.SetAttribute("Namespace", Namespace);
root.SetAttribute("VDirName", VDirName);
if (DataService.Instance != null)
{
root.SetAttribute("DatabaseProvider", DataService.Instance.Provider.Name);
root.SetAttribute("ConnectionStringName", DataService.Instance.Settings.Name);
root.SetAttribute("ProviderName", DataService.Instance.Settings.ProviderName);
root.SetAttribute("MetXObjectName", DataService.Instance.MetXObjectName);
root.SetAttribute("MetXProviderAssemblyString", DataService.Instance.MetXProviderAssemblyString);
root.SetAttribute("ProviderAssemblyString", DataService.Instance.ProviderAssemblyString);
}
root.SetAttribute("OutputFolder", OutputFolder);
root.SetAttribute("Now", DateTime.Now.ToString("s"));
root.SetAttribute("XlgInstanceID", XlgInstanceID.ToString().ToUpper());
root.SetAttribute("MetXAssemblyString", MetXAssemblyString);
xmlDoc.AppendChild(root);
foreach (XmlAttribute currAttribute in m_XlgDataXmlDoc.DocumentElement.Attributes)
{
root.SetAttribute(currAttribute.Name, currAttribute.Value);
}
if (m_TablesToRender != null)
{
if (TablesXml(xmlDoc) == null) return null;
}
if (m_StoredProceduresToRender != null)
{
StoredProceduresXml(xmlDoc);
}
if (m_XslsToRender != null)
{
XslXml(xmlDoc);
}
foreach (XmlElement currChild in m_XlgDataXmlDoc.DocumentElement.ChildNodes)
{
root.AppendChild(xmlDoc.ImportNode(currChild, true));
}
// AddAttribute(root, "xmlDoc", xmlDoc.InnerXml.Replace("><", ">\n<"));
return xmlDoc;
}
}
/// <summary>Causes generation and returns the code/contents generated</summary>
public string GenerateCode()
{
string xlgXsl = GetVirtualFile(xlgFilename);
if (xlgXsl == null || xlgXsl.Length < 5)
{
throw new Exception("xlg.xsl missing (1).");
}
XlgInstanceID = Guid.NewGuid();
CodeXmlDocument = DataXml;
if (CodeXmlDocument == null) return null;
return Helper.GenerateViaXsl(CodeXmlDocument, xlgXsl).ToString();
}
public string MetXAssemblyString { get { return m_FullName; } }
public XmlDocument CodeXmlDocument = null;
/// <summary>
/// List of all the C# keywords
/// </summary>
public readonly List<string> CSharpKeywords = new List<string>(new[]
{
"abstract", "event", "new", "struct", "as", "explicit",
"null", "switch", "base", "extern", "object", "this",
"bool", "false", "operator", "throw",
"break", "finally", "out", "true",
"byte", "fixed", "override", "try",
"case", "float", "params", "typeof",
"catch", "for", "private", "uint",
"char", "foreach", "protected", "ulong",
"checked", "goto", "public", "unchecked",
"class", "if", "readonly", "unsafe",
"const", "implicit", "ref", "ushort",
"continue", "in", "return", "using",
"decimal", "int", "sbyte", "virtual",
"default", "interface", "sealed", "volatile",
"delegate", "internal", "short", "void",
"do", "is", "sizeof", "while",
"double", "lock", "stackalloc",
"else", "long", "static",
"enum", "namespace", "string"
});
public readonly Form Gui;
/// <summary>The namespace that should be passed into the XSL</summary>
public string Namespace = "xlg";
public string OutputFolder;
/// <summary>The class name to contain the Stored Procedures</summary>
public const string spClassName = "SPs";
private XmlElement m_StoredProceduresToRender;
private XmlElement m_TablesToRender;
private string m_UrlExtension;
/// <summary>Set internally (overridden externally) indicating the base vitual directory.</summary>
public string VDirName;
/// <summary>Set externally indicating the path/virtual (sub directory) path to any overriding template(s).</summary>
public string VirtualPath;
/// <summary>Set externally indicating the file of any overriding template(s)</summary>
public string VirtualxlgFilePath;
/// <summary>The Data XML file to generate against</summary>
public string xlgDataXml = "*";
private XmlDocument m_XlgDataXmlDoc = new XmlDocument();
/// <summary>The file containing the XSL to render code against.
/// <para>NOTE: This file does not have to exist. If it doesn't the internal XSL rendering C# will be used.</para>
/// </summary>
public string xlgFilename = "app.xlg.xsl";
public Guid XlgInstanceID;
private XmlElement m_XslsToRender;
/// <summary>Default constructor. Does nothing</summary>
public CodeGenerator()
{
if (m_FullName == null)
{
m_FullName = Assembly.GetExecutingAssembly().FullName;
}
}
/// <summary>Internally sets VirtualPath, VirtualxlgFilePath, xlgDataXml, Namespace, and VDirName based on VirtualxlgFilePath</summary>
public CodeGenerator(string xlgFilePath, string xlgXslFilePath, string settingsFilePath, Form gui)
: this()
{
this.Gui = gui;
Initialize(xlgFilePath, xlgXslFilePath, settingsFilePath);
}
public void Initialize(string xlgFilePath, string xlgXslFilePath, string settingsFilePath)
{
VirtualPath = Path.GetDirectoryName(xlgFilePath).AsString().Replace("\\", "/");
VirtualxlgFilePath = xlgFilePath;
xlgFilename = xlgXslFilePath;
xlgDataXml = GetVirtualFile(VirtualxlgFilePath);
Namespace = Path.GetFileNameWithoutExtension(VirtualxlgFilePath).AsString();
if (Namespace.ToUpper().EndsWith(".GLOVE"))
{
Namespace = Namespace.Substring(0, Namespace.Length - 6);
}
VDirName = Namespace;
try
{
AppDomainAppPath = HttpRuntime.AppDomainAppPath;
}
catch
{
if (!string.IsNullOrEmpty(settingsFilePath))
{
AppDomainAppPath = Path.GetDirectoryName(settingsFilePath);
}
else
{
AppDomainAppPath = Path.GetDirectoryName(xlgFilename);
}
}
if (!string.IsNullOrEmpty(settingsFilePath) && settingsFilePath.ToLower().Contains(".config"))
{
ExeConfigurationFileMap configFile = new ExeConfigurationFileMap { ExeConfigFilename = settingsFilePath };
DataService.ConnectionStrings = ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None).ConnectionStrings.ConnectionStrings;
}
}
/// <summary>Causes generation and returns the code/contents generated</summary>
public string RegenerateCode(XmlDocument xmlDoc)
{
string xlgXsl = GetVirtualFile(xlgFilename);
if (xlgXsl == null || xlgXsl.Length < 5)
{
throw new Exception("xlg.xsl missing (2).");
}
//xlgXsl = MetX.Data.xlg.xsl;
return Helper.GenerateViaXsl(xmlDoc, xlgXsl).ToString();
}
private string Dav(XmlDocument x, string name, string defaultValue)
{
string ret;
if (x.DocumentElement != null && x.DocumentElement.Attributes[name] != null)
{
ret = x.DocumentElement.Attributes[name].Value;
if (string.IsNullOrEmpty(ret))
{
return defaultValue;
}
}
else
{
return defaultValue;
}
return ret;
}
private void ParseDataXml()
{
m_XlgDataXmlDoc = new XmlDocument();
if (xlgDataXml == null || xlgDataXml.StartsWith("*"))
{
m_XlgDataXmlDoc.LoadXml(DefaultXlg.xml.Replace("[Default]", Namespace));
}
else
{
m_XlgDataXmlDoc.LoadXml(xlgDataXml);
}
m_TablesToRender = (XmlElement)m_XlgDataXmlDoc.SelectSingleNode("/*/Render/Tables");
m_StoredProceduresToRender = (XmlElement)m_XlgDataXmlDoc.SelectSingleNode("/*/Render/StoredProcedures");
m_XslsToRender = (XmlElement)m_XlgDataXmlDoc.SelectSingleNode("/*/Render/Xsls");
string connectionStringName = Dav(m_XlgDataXmlDoc, "ConnectionStringName", "Default");
//if (xlgDataXmlDoc.DocumentElement.Attributes["ConnectionStringName"] == null)
// ConnectionStringName = "Default";
//else
// ConnectionStringName = xlgDataXmlDoc.DocumentElement.Attributes["ConnectionStringName"].Value;
DataService.Instance = DataService.GetDataService(connectionStringName);
if (DataService.Instance == null)
{
throw new Exception("No valid connection name (from xlgd): " + connectionStringName);
}
AddElement(m_XslsToRender, "Exclude", "Name", "~/security/xsl/xlg");
AddElement(m_XslsToRender, "Exclude", "Name", "~/App_Code");
AddElement(m_XslsToRender, "Exclude", "Name", "~/App_Data");
AddElement(m_XslsToRender, "Exclude", "Name", "~/theme");
AddElement(m_XslsToRender, "Exclude", "Name", "~/bin");
AddElement(m_XslsToRender, "Exclude", "Name", "_svn");
AddElement(m_XslsToRender, "Exclude", "Name", ".svn");
AddElement(m_XslsToRender, "Exclude", "Name", "_vti_pvt");
AddElement(m_XslsToRender, "Exclude", "Name", "_vti_cnf");
AddElement(m_XslsToRender, "Exclude", "Name", "_vti_script");
AddElement(m_XslsToRender, "Exclude", "Name", "_vti_txt");
AddElement(m_StoredProceduresToRender, "Exclude", "Name", "sp_*");
AddElement(m_StoredProceduresToRender, "Exclude", "Name", "dt_*");
}
private string GetxlgPath(string path)
{
return path.Replace("/xsl/", "/").ToLower();
}
// ReSharper disable once UnusedMethodReturnValue.Local
private XmlDocument XslXml(XmlDocument xmlDoc)
{
string renderPath = m_XslsToRender.GetAttribute("Path");
if (renderPath.Length == 0)
{
renderPath = "~";
}
m_UrlExtension = m_XslsToRender.GetAttribute("UrlExtension");
if (string.IsNullOrEmpty(m_UrlExtension))
{
m_UrlExtension = "aspx";
}
else if (m_UrlExtension.StartsWith("."))
{
m_UrlExtension = m_UrlExtension.Substring(1);
}
XmlElement root = xmlDoc.DocumentElement;
string path = Helper.VirtualPathToPhysical(renderPath);
XmlElement xmlXsls = xmlDoc.CreateElement("XslEndpoints");
AddAttribute(xmlXsls, "VirtualPath", renderPath);
AddAttribute(xmlXsls, "xlgPath", GetxlgPath("/" + VDirName));
AddAttribute(xmlXsls, "VirtualDir", string.Empty);
AddAttribute(xmlXsls, "Path", path);
AddAttribute(xmlXsls, "Folder", path.LastToken(@"\"));
// ReSharper disable once PossibleNullReferenceException
root.AppendChild(xmlXsls);
XmlNodeList xmlNodeList = m_XslsToRender.SelectNodes("Virtual");
if (xmlNodeList != null)
{
foreach (XmlElement currVirtual in xmlNodeList)
{
string xslFile = currVirtual.GetAttribute("Name");
string classname = xslFile.Replace(" ", "_").Replace("/", ".");
XmlElement xmlXsl = xmlDoc.CreateElement("XslEndpoint");
if (CSharpKeywords.Contains(classname))
{
classname = "_" + classname;
}
if (xmlDoc.SelectSingleNode("/*/Tables/Table[@ClassName=\"" + Xml.AttributeEncode(classname) + "\"]") != null ||
xmlDoc.SelectSingleNode("/*/StoredProcedures[@ClassName=\"" + Xml.AttributeEncode(classname) + "\"]") != null)
{
classname += "PageHandler";
}
AddAttribute(xmlXsl, "xlgPath", GetxlgPath("/" + VDirName + "/" + xslFile + "." + m_UrlExtension));
AddAttribute(xmlXsl, "VirtualPath", renderPath + "/" + xslFile + "." + m_UrlExtension);
AddAttribute(xmlXsl, "ClassName", classname);
AddAttribute(xmlXsl, "Filepart", xslFile);
AddAttribute(xmlXsl, "IsVirtual", "true");
xmlXsls.AppendChild(xmlXsl);
}
}
ProcessXslPath(xmlDoc, renderPath, "/" + VDirName.ToLower(), path, xmlXsls);
return xmlDoc;
}
private void ProcessXslPath(XmlDocument xmlDoc, string renderPath, string xlgPath, string path, XmlElement parent)
{
foreach (string xslFile in Directory.GetFiles(path))
{
if (!string.IsNullOrEmpty(xslFile) && Path.GetExtension(xslFile) == ".xsl" && !xslFile.EndsWith(".xlg.xsl") && IsIncluded(m_XslsToRender, xslFile)
&& IsIncluded(m_XslsToRender, renderPath + "/" + Path.GetFileNameWithoutExtension(xslFile)))
{
XmlElement xmlXsl = xmlDoc.CreateElement("XslEndpoint");
string classname = Path.GetFileNameWithoutExtension(xslFile).Replace(" ", "_");
if (CSharpKeywords.Contains(classname))
{
classname = "_" + classname;
}
if (xmlDoc.SelectSingleNode("/*/Tables/Table[@ClassName=\"" + Xml.AttributeEncode(classname) + "\"]") != null ||
xmlDoc.SelectSingleNode("/*/StoredProcedures[@ClassName=\"" + Xml.AttributeEncode(classname) + "\"]") != null)
{
classname += "PageHandler";
}
AddAttribute(xmlXsl, "ClassName", classname);
AddAttribute(xmlXsl, "xlgPath", GetxlgPath(xlgPath + "/" + Path.GetFileNameWithoutExtension(xslFile) + "." + m_UrlExtension));
AddAttribute(xmlXsl, "FilePath", xslFile);
AddAttribute(xmlXsl, "Path", Path.GetDirectoryName(xslFile));
AddAttribute(xmlXsl, "Filename", Path.GetFileName(xslFile));
AddAttribute(xmlXsl, "Filepart", Path.GetFileNameWithoutExtension(xslFile));
AddAttribute(xmlXsl, "Extension", Path.GetExtension(xslFile));
AddAttribute(xmlXsl, "IsVirtual", "false");
parent.AppendChild(xmlXsl);
}
}
foreach (string xslFolder in Directory.GetDirectories(path))
{
string folderName = xslFolder.LastToken(@"\");
if (IsIncluded(m_XslsToRender, folderName) && IsIncluded(m_XslsToRender, renderPath + "/" + folderName))
{
XmlElement xmlXsls = xmlDoc.CreateElement("XslEndpoints");
AddAttribute(xmlXsls, "VirtualPath", renderPath + "/" + folderName);
AddAttribute(xmlXsls, "xlgPath", GetxlgPath(xlgPath + "/" + folderName));
AddAttribute(xmlXsls, "VirtualDir", folderName);
AddAttribute(xmlXsls, "Path", xslFolder);
AddAttribute(xmlXsls, "Folder", folderName);
parent.AppendChild(xmlXsls);
ProcessXslPath(xmlDoc, renderPath + "/" + folderName, GetxlgPath(xlgPath + "/" + folderName), xslFolder, xmlXsls);
}
}
}
private XmlDocument TablesXml(XmlDocument xmlDoc)
{
XmlElement root = xmlDoc.DocumentElement;
XmlElement xmlTables = xmlDoc.CreateElement("Tables");
if (root == null)
{
return null;
}
root.AppendChild(xmlTables);
string[] tables = DataService.Instance.GetTables();
foreach (string table in tables)
{
if (string.IsNullOrEmpty(table) || !IsInList(table))
{
continue;
}
TableSchema.Table tbl;
try
{
tbl = DataService.Instance.GetTableSchema(table);
}
catch (Exception)
{
if (Gui != null)
{
switch (MessageBox.Show(Gui, "Unable to get a schema for table: " + table + "\n\n\tAdd table to skip list and continue ?", "CONTINUE ?", MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Error, MessageBoxDefaultButton.Button1))
{
case DialogResult.Yes:
AddElement(m_TablesToRender, "Exclude", "Name", table);
break;
case DialogResult.No:
break;
case DialogResult.Cancel:
return null;
}
}
tbl = null;
}
if (tbl == null)
{
continue;
}
XmlElement xmlTable = xmlDoc.CreateElement("Table");
AddAttribute(xmlTable, "TableName", tbl.Name);
AddAttribute(xmlTable, "ClassName", GetClassName(tbl.Name));
if (tbl.PrimaryKey != null)
{
AddAttribute(xmlTable, "PrimaryKeyColumnName", GetProperName(tbl.Name, tbl.PrimaryKey.ColumnName, "Field"));
}
else
{
AddAttribute(xmlTable, "PrimaryKeyColumnName", string.Empty);
}
XmlElement xmlColumns = xmlDoc.CreateElement("Columns");
xmlTable.AppendChild(xmlColumns);
for (int index = 0; index < tbl.Columns.Count; index++)
{
TableSchema.TableColumn col = tbl.Columns[index];
XmlElement xmlColumn = xmlDoc.CreateElement("Column");
AddAttribute(xmlColumn, "ColumnName", col.ColumnName);
AddAttribute(xmlColumn, "PropertyName", GetProperName(tbl.Name, col.ColumnName, "Field"));
AddAttribute(xmlColumn, "CSharpVariableType", GetCSharpVariableType(col.DataType));
AddAttribute(xmlColumn, "Location", (index + 1).ToString());
AddAttribute(xmlColumn, "IsDotNetObject", GetIsDotNetObject(col.DataType).ToString());
AddAttribute(xmlColumn, "CovertToPart", GetConvertToPart(col.DataType));
AddAttribute(xmlColumn, "VBVariableType", GetVbVariableType(col.DataType));
AddAttribute(xmlColumn, "AuditField", IsAuditField(col.ColumnName).ToString());
AddAttribute(xmlColumn, "DbType", col.DataType.ToString());
AddAttribute(xmlColumn, "AutoIncrement", col.AutoIncrement.ToString());
AddAttribute(xmlColumn, "IsForiegnKey", col.IsForiegnKey.ToString());
AddAttribute(xmlColumn, "IsNullable", col.IsNullable.ToString());
AddAttribute(xmlColumn, "IsIdentity", col.IsIdentity.ToString());
AddAttribute(xmlColumn, "IsPrimaryKey", col.IsPrimaryKey.ToString());
AddAttribute(xmlColumn, "IsIndexed", col.IsIndexed.ToString());
AddAttribute(xmlColumn, "MaxLength", col.MaxLength.ToString());
AddAttribute(xmlColumn, "SourceType", col.SourceType);
AddAttribute(xmlColumn, "DomainName", col.DomainName);
AddAttribute(xmlColumn, "Precision", col.Precision.ToString());
AddAttribute(xmlColumn, "Scale", col.Scale.ToString());
xmlColumns.AppendChild(xmlColumn);
}
if (tbl.Keys.Count > 0)
{
XmlElement xmlKeys = xmlDoc.CreateElement("Keys");
xmlTable.AppendChild(xmlKeys);
for (int index = 0; index < tbl.Keys.Count; index++)
{
TableSchema.TableKey key = tbl.Keys[index];
XmlElement xmlKey = xmlDoc.CreateElement("Key");
AddAttribute(xmlKey, "Name", key.Name);
AddAttribute(xmlKey, "IsPrimary", key.IsPrimary.ToString());
AddAttribute(xmlKey, "Location", index.ToString());
XmlElement xmlKeyColumns = xmlDoc.CreateElement("Columns");
for (int i = 0; i < key.Columns.Count; i++)
{
TableSchema.TableKeyColumn col = key.Columns[i];
XmlElement xmlKeyColumn = xmlDoc.CreateElement("Column");
AddAttribute(xmlKeyColumn, "Column", col.Column);
if (col.Related != null)
{
AddAttribute(xmlKeyColumn, "Related", col.Related);
}
AddAttribute(xmlKeyColumn, "Location", i.ToString());
xmlKeyColumns.AppendChild(xmlKeyColumn);
}
xmlKey.AppendChild(xmlKeyColumns);
xmlKeys.AppendChild(xmlKey);
}
}
if (tbl.Indexes.Count > 0)
{
XmlElement xmlIndexes = xmlDoc.CreateElement("Indexes");
xmlTable.AppendChild(xmlIndexes);
for (int i = 0; i < tbl.Indexes.Count; i++)
{
TableSchema.TableIndex index = tbl.Indexes[i];
XmlElement xmlIndex = xmlDoc.CreateElement("Index");
AddAttribute(xmlIndex, "IndexName", index.Name);
AddAttribute(xmlIndex, "IsClustered", index.IsClustered.ToString());
AddAttribute(xmlIndex, "SingleColumnIndex", (index.Columns.Count == 1
? "True"
: "False"));
AddAttribute(xmlIndex, "PropertyName", GetProperName(tbl.Name, index.Name, "Index"));
AddAttribute(xmlIndex, "Location", i.ToString());
XmlElement xmlIndexColumns = xmlDoc.CreateElement("IndexColumns");
xmlIndex.AppendChild(xmlIndexColumns);
for (int columnIndex = 0; columnIndex < index.Columns.Count; columnIndex++)
{
string indexColumn = index.Columns[columnIndex];
XmlElement xmlIndexColumn = xmlDoc.CreateElement("IndexColumn");
AddAttribute(xmlIndexColumn, "IndexColumnName", indexColumn);
AddAttribute(xmlIndexColumn, "Location", columnIndex.ToString());
AddAttribute(xmlIndexColumn, "PropertyName", GetProperName(tbl.Name, indexColumn, "Field"));
xmlIndexColumns.AppendChild(xmlIndexColumn);
}
xmlIndexes.AppendChild(xmlIndex);
}
}
xmlTables.AppendChild(xmlTable);
}
return xmlDoc;
}
// ReSharper disable once UnusedMethodReturnValue.Local
private XmlDocument StoredProceduresXml(XmlDocument xmlDoc)
{
//get the SP list from the DB
string[] sPs = DataService.Instance.GetSPList();
XmlElement root = xmlDoc.DocumentElement;
XmlElement xmlStoredProcedures = xmlDoc.CreateElement("StoredProcedures");
AddAttribute(xmlStoredProcedures, "ClassName", spClassName);
// ReSharper disable once PossibleNullReferenceException
root.AppendChild(xmlStoredProcedures);
int sprocIndex = 1;
foreach (string spName in sPs)
{
// Make sure there is a stored proc to process
// (is blank when there are no stored procedures in the database)
if (spName.Length > 0 && !spName.StartsWith("dt_") && IsIncluded(m_StoredProceduresToRender, spName))
{
XmlElement xmlStoredProcedure = xmlDoc.CreateElement("StoredProcedure");
AddAttribute(xmlStoredProcedure, "StoredProcedureName", spName);
AddAttribute(xmlStoredProcedure, "MethodName", GetProperName(string.Empty, spName, string.Empty).Replace("_", string.Empty).Replace(" ", string.Empty));
AddAttribute(xmlStoredProcedure, "Location", (sprocIndex++).ToString());
//grab the parameters
IDataReader paramReader = DataService.Instance.GetSPParams(spName);
XmlElement xmlParameters = xmlDoc.CreateElement("Parameters");
xmlStoredProcedure.AppendChild(xmlParameters);
int parameterIndex = 1;
while (paramReader.Read())
{
//loop the params, pulling out the names and dataTypes
XmlElement xmlParameter = xmlDoc.CreateElement("Parameter");
DbType dbType = DataService.Instance.GetDbType(paramReader["DataType"].ToString().ToLower());
string paramName = paramReader["Name"].ToString();
if (CSharpKeywords.Contains(paramName))
{
paramName = "_" + paramName;
}
bool isInput = false, isOutput = false;
switch (paramReader["ParamType"].ToString())
{
case "IN":
case "1":
isInput = true;
break;
case "OUT":
case "2":
isOutput = true;
break;
case "":
isInput = true;
break;
default:
isInput = true;
isOutput = true;
break;
}
AddAttribute(xmlParameter, "DataType", dbType.ToString());
AddAttribute(xmlParameter, "CSharpVariableType", GetCSharpVariableType(dbType));
AddAttribute(xmlParameter, "Location", (parameterIndex++).ToString());
AddAttribute(xmlParameter, "CovertToPart", GetConvertToPart(dbType));
AddAttribute(xmlParameter, "VBVariableType", GetVbVariableType(dbType));
AddAttribute(xmlParameter, "IsDotNetObject", GetIsDotNetObject(dbType).ToString());
AddAttribute(xmlParameter, "ParameterName", paramName);
AddAttribute(xmlParameter, "VariableName", GetProperName(paramName.Replace("@", string.Empty).Replace(" ", string.Empty)));
AddAttribute(xmlParameter, "IsInput", isInput.ToString());
AddAttribute(xmlParameter, "IsOutput", isOutput.ToString());
xmlParameters.AppendChild(xmlParameter);
}
paramReader.Close();
xmlStoredProcedures.AppendChild(xmlStoredProcedure);
}
}
return xmlDoc;
}
#region "Helper Functions"
/// <summary>Loads a file from the virutal file system relative to VirtualPath</summary>
/// <param name="virtualFilename">The Virtual file to load</param>
/// <returns>The contents of the virtual file</returns>
public string GetVirtualFile(string virtualFilename)
{
if (VirtualPath != null)
{
if (virtualFilename.FirstToken(":/") != string.Empty || virtualFilename.Replace("\\", "/").StartsWith(VirtualPath))
{
return Helper.GetVirtualFile(virtualFilename);
}
else
{
return Helper.GetVirtualFile(VirtualPath + "/" + virtualFilename);
}
}
return null;
}
/// <summary>
/// Helper function for loading a virtual file from the virtual file system
/// </summary>
public static class Helper
{
/// <summary>Load a file from the virtual file system</summary>
/// <param name="virtualFilename">The virtual path and file to load</param>
/// <returns>The contents of the virtual file</returns>
public static string GetVirtualFile(string virtualFilename)
{
try
{
if (File.Exists(virtualFilename))
{
return FileSystem.FileToString(virtualFilename);
}
else
{
using (Stream inFile = VirtualPathProvider.OpenFile(virtualFilename))
{
StreamReader rdr = new StreamReader(inFile);
string contents = rdr.ReadToEnd();
rdr.Close();
rdr.Dispose();
return contents;
}
}
}
catch
{
// ignored
}
return null;
}
/// <summary>Attemptes to convert a virtual path into a physical one. Physical path is not guarenteed to exist.</summary>
/// <param name="virtualPath">The virtual path to map</param>
/// <returns>The physical file system path represented by VirtualPath</returns>
public static string VirtualPathToPhysical(string virtualPath) { return virtualPath.Replace("/", @"\").Replace("~", AppDomainAppPath).Replace(@"\\", @"\"); }
/// <summary>Performs a simple XSL transformation on a XmlDocument object</summary>
/// <param name="xmlDoc">The XmlDocument to convert</param>
/// <param name="sXsl">The XSLT contents to use in the conversion.</param>
/// <returns>The rendered content</returns>
public static StringBuilder GenerateViaXsl(XmlDocument xmlDoc, string sXsl)
{
StringBuilder sOut = new StringBuilder();
try
{
//xml Transformer = new xml();
//sOut = Transformer.xslTransform(XmlDoc, sXsl);
MvpXslTransform xslt = new MvpXslTransform
{
SupportedFunctions = ExsltFunctionNamespace.All,
MultiOutput = true
};
XsltArgumentList xal = new XsltArgumentList();
xal.AddExtensionObject("urn:xlg", new XlgUrn());
xslt.Load(XmlReader.Create(new StringReader(sXsl)));
using (StringWriter sw = new StringWriter(sOut))
{
xslt.Transform(new XmlInput(xmlDoc), xal, new XmlOutput(sw));
}
sOut.Replace("&", "&");
sOut.Replace(">", ">");
sOut.Replace("<", "<");
//string x = xslt.TemporaryFiles.BasePath;
}
catch (Exception x)
{
throw new Exception("(CodeGenerator.Helper.GenerateViaXsl) " + x.Message + "\n\n" + x.StackTrace, x);
}
return sOut;
}
}
#endregion "Helper Functions"
#region "Support Functions"
private bool IsInList(string tableName) { return tableName != "dtproperties" && IsIncluded(m_TablesToRender, tableName); }
private bool IsExcluded(XmlElement toCheck, string toFind)
{
bool ret = false;
if (toCheck != null)
{
if (toFind.EndsWith("*"))
{
toFind = toFind.Substring(0, toFind.Length - 1);
ret = (toCheck.SelectSingleNode(
"Exclude[@Name='*" +
"' or starts-with(@Name,'" + toFind +
"') or starts-with(@Name,'" + Path.GetFileName(toFind) +
"') or starts-with(@Name,'" + Path.GetFileNameWithoutExtension(toFind) + "')]") != null);
}
else
{
if (toCheck.SelectSingleNode("Include[@Name='" + toFind + "']") != null)
{
// Specifically included
// ReSharper disable once RedundantAssignment
ret = false;
}
else
{
ret = (toCheck.SelectSingleNode(
"Exclude[@Name='*" +
"' or @Name='" + toFind +
"' or @Name='" + Path.GetFileName(toFind) +
"' or @Name='" + Path.GetFileNameWithoutExtension(toFind) + "']") != null);
}
}
}
return ret;
}
private readonly Dictionary<string, Regex> m_Patterns = new Dictionary<string, Regex>();
private bool IsIncluded(XmlElement toCheck, string toFind)
{
if (toCheck.ChildNodes.Count == 0)
{
return true;
}
if (IsExcluded(toCheck, toFind))
{
return false;
}
if (toCheck.SelectSingleNode("Include[@Name=\"*\"]") != null)
{
return true;
}
XmlNodeList xmlNodeList = toCheck.SelectNodes("Include");
if (xmlNodeList == null)
{
return false;
}
foreach (XmlElement includer in xmlNodeList)
{
XmlAttribute name = includer.Attributes["Name"];
Regex regex;
if (!m_Patterns.ContainsKey(name.Value))
{
string pattern = Worker.ConvertWildcardToRegex(name.Value);
regex = new Regex(pattern, RegexOptions.Compiled);
m_Patterns.Add(name.Value, regex);
}
else
{
regex = m_Patterns[name.Value];
}
if (regex != null)
{
return regex.IsMatch(toFind);
}
}
return false;
//if(ToFind.EndsWith("*"))
// return ToCheck.SelectSingleNode("Include[starts-with(@Name,\"" + ToFind.Substring(0,ToFind.Length - 1) + "\")]") != null;
//if (!ToFind.Contains("*"))
// return ToCheck.SelectSingleNode("Include[@Name=\"" + ToFind + "\"]") != null;
//int starIndex = ToFind.IndexOf("*", StringComparison.Ordinal);
//XmlNodeList parts = ToCheck.SelectNodes("Include[starts-with(@Name,\"" + ToFind.Substring(0, starIndex - 1) + "\")]");
//if (parts == null || parts.Count == 0)
// return false;
//foreach (XmlNode part in parts)
//{
// if (part.Attributes == null) { continue; }
// XmlAttribute name = part.Attributes["Name"];
// if (name == null) { continue; }
// if (name.Value.EndsWith(ToFind.Substring(starIndex + 1)))
// return true;
//}
//return ToCheck.SelectSingleNode("Include[@Name=\"" + ToFind + "\"]") != null;
}
private bool IsAuditField(string colName)
{
bool bOut = (colName.ToLower() == "createdby" || colName.ToLower() == "createdon" || colName.ToLower() == "modifiedby" || colName.ToLower() == "modifiedon");
return bOut;
}
//bool isEnum(string tableName)
//{
// if (tableName.ToLower().EndsWith("type") || tableName.ToLower().EndsWith("status"))
// return true;
// return false;
//}
/// <summary>Translates a table name into a CLSCompliant class name</summary>
/// <param name="tableName">The name of the table, stored procedure, etc to translate</param>
/// <returns>The translated class name</returns>
public static string GetClassName(string tableName)
{
string className = GetProperName(tableName.Replace(" ", string.Empty));
//if the table is a plural, make it singular
if (className.EndsWith("ies"))
{
//remove the ies at the end
className = className.Remove(className.Length - 3, 3);
//add y
className += "y";
}
else if (!className.EndsWith("ss") && !className.EndsWith("us") && className.EndsWith("s"))
{
//remove the s
className = className.Remove(className.Length - 1, 1);
}
className = UnderscoreToCamelcase(className);
return className;
}
public static string UnderscoreToCamelcase(string toConvert)
{
if (toConvert != null && toConvert.Length > 1)
{
toConvert = toConvert.Replace("$", "_");
toConvert = toConvert.Replace("#", "_");
toConvert = toConvert.Replace("!", "_");
toConvert = toConvert.Replace("@", "_");
toConvert = toConvert.Replace("%", "_");
toConvert = toConvert.Replace("^", "_");
toConvert = toConvert.Replace("&", "_");
toConvert = toConvert.Replace("*", "_");
toConvert = toConvert.Replace("(", "_");
toConvert = toConvert.Replace(")", "_");
if (toConvert.ToLower().StartsWith("tb"))
{
toConvert = toConvert.Substring(2);
}
toConvert = toConvert.Substring(0, 1).ToUpper() + toConvert.Substring(1, toConvert.Length - 1);
toConvert = toConvert.Replace("____", "_")
.Replace("___", "_")
.Replace("__", "_")
.Replace("__", "_")
.Replace("__", "_");
while (toConvert.IndexOf("_", StringComparison.Ordinal) > -1)
{
string af = toConvert.TokensAfter(1, "_");
if (af.Length > 0)
{
af = af[0].ToString().ToUpper() + af.Substring(1);
toConvert = toConvert.FirstToken("_") + af;
}
else
{
toConvert = toConvert.FirstToken("_");
}
}
if (toConvert == "Type")
{
toConvert = "TypeTable";
}
if (toConvert[0] >= '0' && toConvert[0] <= '9')
{
toConvert = "_" + toConvert;
}
}
return toConvert;
}
/// <summary>Simplified way of adding an XmlElement to a XmlDocument</summary>
/// <param name="target">The XmlDocment to add the Element onto</param>
/// <param name="elementName">The node name of the element</param>
/// <param name="attributeName">Name of an attribute to add</param>
/// <param name="attributeValue">Value of the attribute</param>
/// <returns>The XmlElement added</returns>
public void AddElement(XmlElement target, string elementName, string attributeName, string attributeValue)
{
if (target == null)
{
return;
}
// ReSharper disable once PossibleNullReferenceException
XmlElement x = target.OwnerDocument.CreateElement(elementName);
AddAttribute(x, attributeName, attributeValue);
target.AppendChild(x);
}
/// <summary>Simplified way of adding an attribute to a XmlElement</summary>
/// <param name="target">The XmlElement to add the attribute to</param>
/// <param name="attributeName">The name of the attribute to add</param>
/// <param name="attributeValue">The value of the attribute to add</param>
public void AddAttribute(XmlElement target, string attributeName, string attributeValue)
{
if (target == null)
{
return;
}
if (target.OwnerDocument != null)
{
XmlAttribute ret = target.OwnerDocument.CreateAttribute(attributeName);
ret.Value = attributeValue;
target.Attributes.Append(ret);
}
}
// Anytime a database column is named any of these words, it causes a code issue.
// Make sure a suffix is added to property names in these cases
private static readonly List<string> m_TypeNames = new List<string>(new[] { "guid", "int", "string", "timespan", "double", "single", "float", "decimal", "array" });
/// <summary>Generates a proper case representation of a string (so "fred" becomes "Fred")</summary>
/// <returns>The proper case translation</returns>
public static string GetProperName(string tableName, string fieldName, string suffix)
{
if (fieldName != null && fieldName.Length > 1)
{
string propertyName = UnderscoreToCamelcase(fieldName);
string cleanTableName = UnderscoreToCamelcase(tableName);
string classTableName = GetClassName(tableName);
if (propertyName.EndsWith("TypeCode"))
{
propertyName = propertyName.Substring(0, propertyName.Length - 4);
}
if (tableName == fieldName || tableName == propertyName || cleanTableName == fieldName || cleanTableName == propertyName || propertyName == "TableName"
|| m_TypeNames.Contains(propertyName.ToLower()))
{
propertyName += suffix;
}
else if (classTableName == fieldName || classTableName == propertyName || m_TypeNames.Contains(classTableName.ToLower()))
{
propertyName += suffix;
}
return propertyName;
}
return fieldName;
}
/// <summary>Generates a proper case representation of a string (so "fred" becomes "Fred")</summary>
/// <returns>The proper case translation</returns>
public static string GetProperName(string fieldName)
{
if (fieldName != null && fieldName.Length > 1)
{
string propertyName = UnderscoreToCamelcase(fieldName);
if (propertyName.EndsWith("TypeCode"))
{
propertyName = propertyName.Substring(0, propertyName.Length - 4);
}
return propertyName;
}
return fieldName;
}
/// <summary>Translates a DbType into the VB.NET equivalent type (so "Currency" becomes "Decimal")</summary>
/// <param name="dbType">The DbType to convert</param>
/// <returns>The VB.NET type string</returns>
public static string GetVbVariableType(DbType dbType)
{
switch (dbType)
{
case DbType.AnsiString:
return "String";
case DbType.AnsiStringFixedLength:
return "String";
case DbType.Binary:
return "Byte()";
case DbType.Boolean:
return "Bool";
case DbType.Byte:
return "Byte";
case DbType.Currency:
return "Decimal";
case DbType.Date:
return "DateTime";
case DbType.DateTime:
return "DateTime";
case DbType.Decimal:
return "Decimal";
case DbType.Double:
return "Double";
case DbType.Guid:
return "Guid";
case DbType.Int16:
return "Short";
case DbType.Int32:
return "Int";
case DbType.Int64:
return "Long";
case DbType.Object:
return "Object";
case DbType.SByte:
return "sbyte";
case DbType.Single:
return "Float";
case DbType.String:
return "String";
case DbType.StringFixedLength:
return "String";
case DbType.Time:
return "TimeSpan";
case DbType.UInt16:
return "UShort";
case DbType.UInt32:
return "UInt";
case DbType.UInt64:
return "ULong";
case DbType.VarNumeric:
return "decimal";
default:
return "String";
}
}
/// <summary>Translates a DbType into the C# equivalent type (so "Currency" becomes "Decimal")</summary>
/// <param name="dbType">The DbType to convert</param>
/// <returns>The C# type string</returns>
public static string GetCSharpVariableType(DbType dbType)
{
switch (dbType)
{
case DbType.AnsiString:
return "string";
case DbType.AnsiStringFixedLength:
return "string";
case DbType.Binary:
return "byte[]";
case DbType.Boolean:
return "bool";
case DbType.Byte:
return "byte";
case DbType.Currency:
return "decimal";
case DbType.Date:
return "DateTime";
case DbType.DateTime:
return "DateTime";
case DbType.Decimal:
return "decimal";
case DbType.Double:
return "double";
case DbType.Guid:
return "Guid";
case DbType.Int16:
return "short";
case DbType.Int32:
return "int";
case DbType.Int64:
return "long";
case DbType.Object:
return "object";
case DbType.SByte:
return "sbyte";
case DbType.Single:
return "float";
case DbType.String:
return "string";
case DbType.StringFixedLength:
return "string";
case DbType.Time:
return "TimeSpan";
case DbType.UInt16:
return "ushort";
case DbType.UInt32:
return "uint";
case DbType.UInt64:
return "ulong";
case DbType.VarNumeric:
return "decimal";
default:
return "string";
}
}
/// <summary>Translates a DbType into the C# equivalent type (so "Currency" becomes "Decimal")</summary>
/// <param name="dbType">The DbType to convert</param>
/// <returns>The C# type string</returns>
public static bool GetIsDotNetObject(DbType dbType)
{
switch (dbType)
{
case DbType.Boolean:
return false;
case DbType.Byte:
return false;
case DbType.Currency:
return false;
case DbType.Date:
return false;
case DbType.DateTime:
return false;
case DbType.Decimal:
return false;
case DbType.Double:
return false;
case DbType.Int16:
return false;
case DbType.Int32:
return false;
case DbType.Int64:
return false;
case DbType.SByte:
return false;
case DbType.Single:
return false;
case DbType.Time:
return false;
case DbType.UInt16:
return false;
case DbType.UInt32:
return false;
case DbType.UInt64:
return false;
case DbType.VarNumeric:
return false;
}
return true;
}
/// <summary>Translates a DbType into the .net equivalent type to convert another value to (so "Currency" becomes "Convert.ToCurrency")</summary>
/// <param name="dbType">The DbType to convert</param>
/// <returns>The portion of code necessary to convert another value to the same type as this</returns>
public static string GetConvertToPart(DbType dbType)
{
switch (dbType)
{
case DbType.AnsiString:
return "Worker.AsString";
case DbType.AnsiStringFixedLength:
return "Worker.AsString";
case DbType.Binary:
return "Worker.nzByteArray";
case DbType.Boolean:
return "Worker.nzBoolean";
case DbType.Byte:
return "Worker.nzByte";
case DbType.Currency:
return "Worker.nzDecimal";
case DbType.Date:
return "Worker.nzDateTime";
case DbType.DateTime:
return "Worker.nzDateTime";
case DbType.Decimal:
return "Worker.nzDecimal";
case DbType.Double:
return "Worker.nzDouble";
case DbType.Guid:
return "Worker.nzGuid";
case DbType.Int16:
return "Worker.nzShort";
case DbType.Int32:
return "Worker.nzInteger";
case DbType.Int64:
return "Worker.nzLong";
case DbType.Object:
return string.Empty;
case DbType.SByte:
return "Worker.nzSByte";
case DbType.Single:
return "Worker.nzFloat";
case DbType.String:
return "Worker.AsString";
case DbType.StringFixedLength:
return "Worker.AsString";
case DbType.Time:
return "Worker.nzTimeSpan";
case DbType.UInt16:
return "Worker.nzUShort";
case DbType.UInt32:
return "Worker.nzUInt";
case DbType.UInt64:
return "Worker.nzULong";
case DbType.VarNumeric:
return "Worker.nzDecimal";
default:
return "Worker.AsString";
}
}
#endregion "Support Functions"
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Windows.Forms;
using OpenLiveWriter.Api;
using OpenLiveWriter.Controls;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.CoreServices.Layout;
using OpenLiveWriter.CoreServices.Marketization;
using OpenLiveWriter.Localization;
using OpenLiveWriter.Localization.Bidi;
//using OpenLiveWriter.SpellChecker;
using OpenLiveWriter.ApplicationFramework;
using OpenLiveWriter.ApplicationFramework.Preferences;
using OpenLiveWriter.PostEditor.ContentSources;
namespace OpenLiveWriter.PostEditor
{
public class PluginsPreferencesPanel : PreferencesPanel
{
private System.ComponentModel.IContainer components;
private System.Windows.Forms.Label labelInstalledPlugins;
private System.Windows.Forms.Label labelCaption;
private System.Windows.Forms.Panel panelPluginDetails;
private System.Windows.Forms.ListView listViewInstalledPlugins;
private System.Windows.Forms.GroupBox groupBoxPluginDetails;
private System.Windows.Forms.PictureBox pictureBoxPluginImage;
private System.Windows.Forms.RadioButton radioButtonEnablePlugin;
private System.Windows.Forms.RadioButton radioButtonDisablePlugin;
private System.Windows.Forms.Label labelPluginDescription;
private System.Windows.Forms.ImageList imageListPlugins;
private System.Windows.Forms.ColumnHeader columnHeaderName;
private System.Windows.Forms.ColumnHeader columnHeaderStatus;
private System.Windows.Forms.Label labelNoPluginSelected;
private System.Windows.Forms.LinkLabel linkLabelPluginName;
private ToolTip2 toolTip;
private System.Windows.Forms.Button buttonOptions;
private System.Windows.Forms.LinkLabel linkLabelDownloadPlugins;
private System.Windows.Forms.PictureBox pictureBoxAddPlugin;
private PluginsPreferences _pluginsPreferences ;
public PluginsPreferencesPanel()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
columnHeaderName.Text = Res.Get(StringId.PluginPrefNameCol);
columnHeaderStatus.Text = Res.Get(StringId.PluginPrefStatCol);
labelInstalledPlugins.Text = Res.Get(StringId.PluginPrefInstalled);
groupBoxPluginDetails.Text = Res.Get(StringId.PluginPrefDetails);
buttonOptions.Text = Res.Get(StringId.OptionsButton);
toolTip.SetToolTip(this.linkLabelPluginName, Res.Get(StringId.PluginPrefTooltip));
labelPluginDescription.Text = "";
radioButtonDisablePlugin.Text = Res.Get(StringId.PluginPrefDisable);
radioButtonEnablePlugin.Text = Res.Get(StringId.PluginPrefEnable);
labelNoPluginSelected.Text = Res.Get(StringId.PluginPrefNone);
linkLabelDownloadPlugins.Text = Res.Get(StringId.PluginPrefLink);
linkLabelDownloadPlugins.UseCompatibleTextRendering = false;
labelCaption.Text = Res.Get(StringId.PluginPrefCaption);
PanelName = Res.Get(StringId.PluginPrefName);
//marketization
if (!MarketizationOptions.IsFeatureEnabled(MarketizationOptions.Feature.WLGallery))
linkLabelDownloadPlugins.Visible = false;
else
{
pictureBoxAddPlugin.Image = ResourceHelper.LoadAssemblyResourceBitmap("Images.AddPlugin.png") ;
}
// set our bitmaps
PanelBitmap = ResourceHelper.LoadAssemblyResourceBitmap("Images.PluginsSmall.png") ;
// paramaterize caption with product name
labelCaption.Text = String.Format(CultureInfo.CurrentCulture, labelCaption.Text, ApplicationEnvironment.ProductName) ;
// initialize preferences
_pluginsPreferences = new PluginsPreferences() ;
_pluginsPreferences.PreferencesModified += new EventHandler(_pluginsPreferences_PreferencesModified) ;
// signup for events
listViewInstalledPlugins.SelectedIndexChanged +=new EventHandler(listViewInstalledPlugins_SelectedIndexChanged);
radioButtonEnablePlugin.CheckedChanged +=new EventHandler(radioButtonEnablePlugin_CheckedChanged);
radioButtonDisablePlugin.CheckedChanged +=new EventHandler(radioButtonEnablePlugin_CheckedChanged);
linkLabelPluginName.LinkClicked +=new LinkLabelLinkClickedEventHandler(linkLabelPluginName_LinkClicked);
linkLabelDownloadPlugins.LinkClicked +=new LinkLabelLinkClickedEventHandler(linkLabelDownloadPlugins_LinkClicked);
// update list of plugins
UpdatePluginList();
// signup for global plugin-list changed event
ContentSourceManager.GlobalContentSourceListChanged +=new EventHandler(ContentSourceManager_GlobalContentSourceListChanged);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad (e);
if (!DesignMode)
{
LayoutHelper.NaturalizeHeightAndDistribute(8, Controls);
linkLabelDownloadPlugins.Top = pictureBoxAddPlugin.Top + 1;
LayoutHelper.NaturalizeHeight(linkLabelPluginName);
DisplayHelper.AutoFitSystemRadioButton(radioButtonEnablePlugin, 0, int.MaxValue);
DisplayHelper.AutoFitSystemRadioButton(radioButtonDisablePlugin, 0, int.MaxValue);
radioButtonEnablePlugin.BringToFront();
DisplayHelper.AutoFitSystemButton(buttonOptions);
}
}
private void ContentSourceManager_GlobalContentSourceListChanged(object sender, EventArgs e)
{
// post back to ourselves if necessary
if ( InvokeRequired )
{
BeginInvoke(new EventHandler(ContentSourceManager_GlobalContentSourceListChanged), new object[]{ sender, e});
return ;
}
// update plugin list
UpdatePluginList() ;
}
private void UpdatePluginList()
{
// clear existing list
listViewInstalledPlugins.Items.Clear();
imageListPlugins.Images.Clear();
// re-initialize list
int imageIndex = 0 ;
ContentSourceInfo[] pluginContentSources = ContentSourceManager.PluginContentSources ;
foreach ( ContentSourceInfo pluginContentSource in pluginContentSources )
{
imageListPlugins.Images.Add(BidiHelper.Mirror(pluginContentSource.Image)) ;
ListViewItem listViewItem = new ListViewItem();
listViewItem.Tag = pluginContentSource ;
listViewItem.ImageIndex = imageIndex++ ;
RefreshListViewItem(listViewItem) ;
listViewInstalledPlugins.Items.Add(listViewItem) ;
}
// select first item if possible
if ( listViewInstalledPlugins.Items.Count > 0 )
listViewInstalledPlugins.Items[0].Selected = true ;
// update the details pane
UpdateDetailsPane() ;
}
public override void Save()
{
if ( _pluginsPreferences.IsModified() )
{
_pluginsPreferences.Save();
DisplayMessage.Show(MessageId.PluginStatusChanged, this) ;
}
}
private void _pluginsPreferences_PreferencesModified(object sender, EventArgs e)
{
OnModified(EventArgs.Empty) ;
}
private void listViewInstalledPlugins_SelectedIndexChanged(object sender, EventArgs e)
{
UpdateDetailsPane() ;
}
private void radioButtonEnablePlugin_CheckedChanged(object sender, EventArgs e)
{
ContentSourceInfo selectedContentSource = GetSelectedPlugin();
if (selectedContentSource != null)
{
// if our underlying state has changed then update underlying prefs
if (_pluginsPreferences.GetPluginEnabledState(selectedContentSource) != radioButtonEnablePlugin.Checked )
{
_pluginsPreferences.SetPluginEnabledState(selectedContentSource, radioButtonEnablePlugin.Checked );
RefreshSelectedListViewItem() ;
}
}
}
private void linkLabelPluginName_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
ContentSourceInfo selectedContentSource = GetSelectedPlugin() ;
if ( selectedContentSource != null )
{
if ( selectedContentSource.WriterPluginPublisherUrl != String.Empty )
ShellHelper.LaunchUrl(selectedContentSource.WriterPluginPublisherUrl);
}
}
private void linkLabelDownloadPlugins_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
ShellHelper.LaunchUrl(GLink.Instance.DownloadPlugins);
}
private void buttonOptions_Click(object sender, System.EventArgs e)
{
ContentSourceInfo selectedContentSource = GetSelectedPlugin() ;
if ( selectedContentSource != null )
{
if ( selectedContentSource.WriterPluginHasEditableOptions )
{
try
{
selectedContentSource.Instance.EditOptions(FindForm()) ;
}
catch(NotImplementedException ex)
{
ContentSourceManager.DisplayContentRetreivalError(FindForm(), ex, selectedContentSource);
}
catch (Exception exception)
{
Trace.Fail(exception.ToString());
DisplayableException dex = new DisplayableException(
Res.Get(StringId.UnexpectedErrorPluginTitle),
string.Format(CultureInfo.CurrentCulture, Res.Get(StringId.UnexpectedErrorPluginDescription), selectedContentSource.Name, exception.Message));
DisplayableExceptionDisplayForm.Show(FindForm(), dex);
}
}
}
}
private void RefreshSelectedListViewItem()
{
if (listViewInstalledPlugins.SelectedItems.Count > 0 )
RefreshListViewItem(listViewInstalledPlugins.SelectedItems[0]) ;
}
private void RefreshListViewItem(ListViewItem listViewItem)
{
ContentSourceInfo itemContentSource = listViewItem.Tag as ContentSourceInfo ;
listViewItem.SubItems.Clear();
listViewItem.Text = " " + itemContentSource.Name ;
listViewItem.SubItems.Add( new ListViewItem.ListViewSubItem(listViewItem, _pluginsPreferences.GetPluginEnabledState(itemContentSource) ? Res.Get(StringId.Enabled) : Res.Get(StringId.Disabled))) ;
}
private void UpdateDetailsPane()
{
ContentSourceInfo selectedContentSource = GetSelectedPlugin() ;
if ( selectedContentSource != null )
{
panelPluginDetails.Visible = true ;
labelNoPluginSelected.Visible = false ;
pictureBoxPluginImage.Image = selectedContentSource.Image ;
linkLabelPluginName.Text = selectedContentSource.Name ;
labelPluginDescription.Text = selectedContentSource.WriterPluginDescription ;
radioButtonEnablePlugin.Checked = selectedContentSource.Enabled ;
radioButtonDisablePlugin.Checked = !selectedContentSource.Enabled ;
buttonOptions.Visible = selectedContentSource.WriterPluginHasEditableOptions;
}
else
{
labelNoPluginSelected.Visible = true ;
panelPluginDetails.Visible = false ;
}
}
private ContentSourceInfo GetSelectedPlugin()
{
if ( listViewInstalledPlugins.SelectedItems.Count > 0 )
return listViewInstalledPlugins.SelectedItems[0].Tag as ContentSourceInfo ;
else
return null ;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
ContentSourceManager.GlobalContentSourceListChanged -=new EventHandler(ContentSourceManager_GlobalContentSourceListChanged);
_pluginsPreferences.PreferencesModified -= new EventHandler(_pluginsPreferences_PreferencesModified);
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(PluginsPreferencesPanel));
this.listViewInstalledPlugins = new System.Windows.Forms.ListView();
this.columnHeaderName = new System.Windows.Forms.ColumnHeader();
this.columnHeaderStatus = new System.Windows.Forms.ColumnHeader();
this.imageListPlugins = new System.Windows.Forms.ImageList(this.components);
this.labelInstalledPlugins = new System.Windows.Forms.Label();
this.groupBoxPluginDetails = new System.Windows.Forms.GroupBox();
this.panelPluginDetails = new System.Windows.Forms.Panel();
this.buttonOptions = new System.Windows.Forms.Button();
this.linkLabelPluginName = new System.Windows.Forms.LinkLabel();
this.labelPluginDescription = new System.Windows.Forms.Label();
this.radioButtonDisablePlugin = new System.Windows.Forms.RadioButton();
this.radioButtonEnablePlugin = new System.Windows.Forms.RadioButton();
this.pictureBoxPluginImage = new System.Windows.Forms.PictureBox();
this.labelNoPluginSelected = new System.Windows.Forms.Label();
this.labelCaption = new System.Windows.Forms.Label();
this.toolTip = new ToolTip2(this.components);
this.linkLabelDownloadPlugins = new System.Windows.Forms.LinkLabel();
this.pictureBoxAddPlugin = new System.Windows.Forms.PictureBox();
this.groupBoxPluginDetails.SuspendLayout();
this.panelPluginDetails.SuspendLayout();
this.SuspendLayout();
//
// listViewInstalledPlugins
//
this.listViewInstalledPlugins.AutoArrange = false;
this.listViewInstalledPlugins.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeaderName,
this.columnHeaderStatus});
this.listViewInstalledPlugins.FullRowSelect = true;
this.listViewInstalledPlugins.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.listViewInstalledPlugins.HideSelection = false;
this.listViewInstalledPlugins.Location = new System.Drawing.Point(8, 83);
this.listViewInstalledPlugins.MultiSelect = false;
this.listViewInstalledPlugins.Name = "listViewInstalledPlugins";
this.listViewInstalledPlugins.RightToLeftLayout = BidiHelper.IsRightToLeft;
this.listViewInstalledPlugins.Size = new System.Drawing.Size(348, 148);
this.listViewInstalledPlugins.SmallImageList = this.imageListPlugins;
this.listViewInstalledPlugins.TabIndex = 3;
this.listViewInstalledPlugins.View = System.Windows.Forms.View.Details;
//
// columnHeaderName
//
this.columnHeaderName.Text = "Plugin";
this.columnHeaderName.Width = 229;
//
// columnHeaderStatus
//
this.columnHeaderStatus.Text = "Status";
this.columnHeaderStatus.Width = 95;
//
// imageListPlugins
//
this.imageListPlugins.ColorDepth = System.Windows.Forms.ColorDepth.Depth32Bit;
this.imageListPlugins.ImageSize = new System.Drawing.Size(16, 16);
this.imageListPlugins.TransparentColor = System.Drawing.Color.Transparent;
//
// labelInstalledPlugins
//
this.labelInstalledPlugins.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.labelInstalledPlugins.Location = new System.Drawing.Point(8, 66);
this.labelInstalledPlugins.Name = "labelInstalledPlugins";
this.labelInstalledPlugins.Size = new System.Drawing.Size(341, 15);
this.labelInstalledPlugins.TabIndex = 2;
this.labelInstalledPlugins.Text = "&Plugins currently installed:";
//
// groupBoxPluginDetails
//
this.groupBoxPluginDetails.Controls.Add(this.panelPluginDetails);
this.groupBoxPluginDetails.Controls.Add(this.labelNoPluginSelected);
this.groupBoxPluginDetails.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.groupBoxPluginDetails.Location = new System.Drawing.Point(8, 237);
this.groupBoxPluginDetails.Name = "groupBoxPluginDetails";
this.groupBoxPluginDetails.Size = new System.Drawing.Size(349, 149);
this.groupBoxPluginDetails.TabIndex = 4;
this.groupBoxPluginDetails.TabStop = false;
this.groupBoxPluginDetails.Text = "Plugin details";
//
// panelPluginDetails
//
this.panelPluginDetails.Controls.Add(this.buttonOptions);
this.panelPluginDetails.Controls.Add(this.linkLabelPluginName);
this.panelPluginDetails.Controls.Add(this.labelPluginDescription);
this.panelPluginDetails.Controls.Add(this.radioButtonDisablePlugin);
this.panelPluginDetails.Controls.Add(this.radioButtonEnablePlugin);
this.panelPluginDetails.Controls.Add(this.pictureBoxPluginImage);
this.panelPluginDetails.Location = new System.Drawing.Point(7, 18);
this.panelPluginDetails.Name = "panelPluginDetails";
this.panelPluginDetails.Size = new System.Drawing.Size(339, 123);
this.panelPluginDetails.TabIndex = 0;
//
// buttonOptions
//
this.buttonOptions.Anchor = AnchorStyles.Top | AnchorStyles.Right;
this.buttonOptions.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.buttonOptions.Location = new System.Drawing.Point(250, 61);
this.buttonOptions.Name = "buttonOptions";
this.buttonOptions.Size = new System.Drawing.Size(83, 23);
this.buttonOptions.TabIndex = 4;
this.buttonOptions.Text = "Options...";
this.buttonOptions.Click += new System.EventHandler(this.buttonOptions_Click);
//
// linkLabelPluginName
//
this.linkLabelPluginName.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.linkLabelPluginName.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline;
this.linkLabelPluginName.LinkColor = System.Drawing.SystemColors.HotTrack;
this.linkLabelPluginName.Location = new System.Drawing.Point(21, 2);
this.linkLabelPluginName.Name = "linkLabelPluginName";
this.linkLabelPluginName.Size = new System.Drawing.Size(222, 16);
this.linkLabelPluginName.TabIndex = 0;
this.linkLabelPluginName.TabStop = true;
this.linkLabelPluginName.Text = "YouTube Video Publisher";
this.toolTip.SetToolTip(this.linkLabelPluginName, "Click here to find out more about this plugin.");
//
// labelPluginDescription
//
this.labelPluginDescription.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.labelPluginDescription.Location = new System.Drawing.Point(2, 21);
this.labelPluginDescription.Name = "labelPluginDescription";
this.labelPluginDescription.Size = new System.Drawing.Size(241, 100);
this.labelPluginDescription.TabIndex = 1;
this.labelPluginDescription.Text = "Publish videos to your weblog from YouTube, the leading free online video streami" +
"ng service.";
//
// radioButtonDisablePlugin
//
this.radioButtonDisablePlugin.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.radioButtonDisablePlugin.Location = new System.Drawing.Point(254, 30);
this.radioButtonDisablePlugin.Name = "radioButtonDisablePlugin";
this.radioButtonDisablePlugin.Size = new System.Drawing.Size(84, 24);
this.radioButtonDisablePlugin.TabIndex = 3;
this.radioButtonDisablePlugin.Text = "&Disable";
//
// radioButtonEnablePlugin
//
this.radioButtonEnablePlugin.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.radioButtonEnablePlugin.Location = new System.Drawing.Point(254, 10);
this.radioButtonEnablePlugin.Name = "radioButtonEnablePlugin";
this.radioButtonEnablePlugin.Size = new System.Drawing.Size(84, 24);
this.radioButtonEnablePlugin.TabIndex = 2;
this.radioButtonEnablePlugin.Text = "&Enable";
//
// pictureBoxPluginImage
//
this.pictureBoxPluginImage.Image = ((System.Drawing.Image)(resources.GetObject("pictureBoxPluginImage.Image")));
this.pictureBoxPluginImage.Location = new System.Drawing.Point(0, 0);
this.pictureBoxPluginImage.Name = "pictureBoxPluginImage";
this.pictureBoxPluginImage.Size = new System.Drawing.Size(20, 18);
this.pictureBoxPluginImage.TabIndex = 0;
this.pictureBoxPluginImage.TabStop = false;
//
// labelNoPluginSelected
//
this.labelNoPluginSelected.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.labelNoPluginSelected.Location = new System.Drawing.Point(16, 43);
this.labelNoPluginSelected.Name = "labelNoPluginSelected";
this.labelNoPluginSelected.Size = new System.Drawing.Size(316, 23);
this.labelNoPluginSelected.TabIndex = 1;
this.labelNoPluginSelected.Text = "(No Plugin selected)";
this.labelNoPluginSelected.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// labelCaption
//
this.labelCaption.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.labelCaption.Location = new System.Drawing.Point(8, 32);
this.labelCaption.Name = "labelCaption";
this.labelCaption.Size = new System.Drawing.Size(341, 32);
this.labelCaption.TabIndex = 1;
this.labelCaption.Text = "Plugins are programs that extend the functionality of {0}. You can enable and dis" +
"able Plugins using this dialog.";
//
// linkLabelDownloadPlugins
//
this.linkLabelDownloadPlugins.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.linkLabelDownloadPlugins.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline;
this.linkLabelDownloadPlugins.LinkColor = System.Drawing.SystemColors.HotTrack;
this.linkLabelDownloadPlugins.Location = new System.Drawing.Point(32, 394);
this.linkLabelDownloadPlugins.Name = "linkLabelDownloadPlugins";
this.linkLabelDownloadPlugins.Size = new System.Drawing.Size(316, 15);
this.linkLabelDownloadPlugins.TabIndex = 5;
this.linkLabelDownloadPlugins.TabStop = true;
this.linkLabelDownloadPlugins.Text = "Add a Plugin...";
this.linkLabelDownloadPlugins.AutoSize = true;
//
// pictureBoxAddPlugin
//
this.pictureBoxAddPlugin.Location = new System.Drawing.Point(13, 393);
this.pictureBoxAddPlugin.Name = "pictureBoxAddPlugin";
this.pictureBoxAddPlugin.Size = new System.Drawing.Size(16, 16);
this.pictureBoxAddPlugin.TabIndex = 6;
this.pictureBoxAddPlugin.TabStop = false;
//
// PluginsPreferencesPanel
//
this.Controls.Add(this.pictureBoxAddPlugin);
this.Controls.Add(this.labelCaption);
this.Controls.Add(this.linkLabelDownloadPlugins);
this.Controls.Add(this.groupBoxPluginDetails);
this.Controls.Add(this.labelInstalledPlugins);
this.Controls.Add(this.listViewInstalledPlugins);
this.Name = "PluginsPreferencesPanel";
this.PanelName = "Plugins";
this.Size = new System.Drawing.Size(370, 428);
this.Controls.SetChildIndex(this.listViewInstalledPlugins, 0);
this.Controls.SetChildIndex(this.labelInstalledPlugins, 0);
this.Controls.SetChildIndex(this.groupBoxPluginDetails, 0);
this.Controls.SetChildIndex(this.linkLabelDownloadPlugins, 0);
this.Controls.SetChildIndex(this.labelCaption, 0);
this.Controls.SetChildIndex(this.pictureBoxAddPlugin, 0);
this.groupBoxPluginDetails.ResumeLayout(false);
this.panelPluginDetails.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using Gallio.Common.Collections;
using Gallio.Common.Concurrency;
using Gallio.Common.IO;
using Gallio.Common.Messaging;
using Gallio.Common.Messaging.MessageSinks;
using Gallio.Common.Reflection;
using Gallio.Model;
using Gallio.Model.Isolation;
using Gallio.Runtime;
using Gallio.Runtime.Hosting;
using Gallio.Runtime.Logging;
using Gallio.Runtime.ProgressMonitoring;
using Microsoft.Scripting.Hosting;
namespace Gallio.DLRIntegration.Model
{
/// <summary>
/// A base class for implementing test drivers using the DLR.
/// </summary>
/// <remarks>
/// <para>
/// This class provides support for implementing test frameworks and adapters
/// in DLR-supported dynamic languages. This code takes care of entering a
/// test isolation context, initializing the DLR script runtime and then invoking
/// the provided test driver script.
/// </para>
/// <para>
/// A test driver script is a script written in a DLR language. The test driver
/// communicates with the script by setting a global variable called "ScriptParameters"
/// in the DLR interpreter environment to a dictionary that contains a verb
/// specifying the service to perform along with other parameters.
/// </para>
/// <para>
/// The "ScriptParameters" dictionary contains the following key/value pairs:
/// <list type="bullet">
/// <item>Verb: The command to perform. Either "Explore" or "Run".</item>
/// <item>TestPackage: The <see cref="TestPackage" /> object specifying test package options including the list of files to run.</item>
/// <item>TestExplorationOptions: The <see cref="TestExplorationOptions" /> object specifying test exploration options.</item>
/// <item>TestExecutionOptions: The <see cref="TestExecutionOptions" /> object specifying test execution options. Only provided when the verb is "Run".</item>
/// <item>MessageSink: The <see cref="IMessageSink" /> object providing a return-path to send test exploration and execution messages to the test runner.</item>
/// <item>ProgressMonitor: The <see cref="IProgressMonitor" /> object providing progress reporting capabilities.</item>
/// <item>Logger: The <see cref="ILogger" /> object providing logging capabilities.</item>
/// </list>
/// </para>
/// </remarks>
public abstract class DLRTestDriver : BaseTestDriver
{
/// <summary>
/// Gets the name of the variable used to pass script parameters.
/// </summary>
/// <value>"ScriptParameters"</value>
public static readonly string ScriptParametersVariableName = "ScriptParameters";
private readonly ILogger logger;
/// <summary>
/// Initializes a DLR test driver.
/// </summary>
/// <param name="logger">The logger.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="logger"/> is null.</exception>
protected DLRTestDriver(ILogger logger)
{
if (logger == null)
throw new ArgumentNullException("logger");
this.logger = logger;
}
/// <summary>
/// Gets the test driver's logger.
/// </summary>
public ILogger Logger
{
get { return logger; }
}
/// <inheritdoc />
sealed protected override void ExploreImpl(ITestIsolationContext testIsolationContext, TestPackage testPackage, TestExplorationOptions testExplorationOptions, IMessageSink messageSink, IProgressMonitor progressMonitor)
{
ExploreOrRun(testIsolationContext, testPackage, testExplorationOptions, null, messageSink, progressMonitor,
"Exploring tests.");
}
/// <inheritdoc />
sealed protected override void RunImpl(ITestIsolationContext testIsolationContext, TestPackage testPackage, TestExplorationOptions testExplorationOptions, TestExecutionOptions testExecutionOptions, IMessageSink messageSink, IProgressMonitor progressMonitor)
{
ExploreOrRun(testIsolationContext, testPackage, testExplorationOptions, testExecutionOptions, messageSink,
progressMonitor, "Running tests.");
}
private void ExploreOrRun(ITestIsolationContext testIsolationContext, TestPackage testPackage, TestExplorationOptions testExplorationOptions,
TestExecutionOptions testExecutionOptions, IMessageSink messageSink, IProgressMonitor progressMonitor, string taskName)
{
using (progressMonitor.BeginTask(taskName, 1))
{
if (progressMonitor.IsCanceled)
return;
FileInfo testDriverScriptFile = GetTestDriverScriptFile(testPackage);
if (testDriverScriptFile == null)
return;
HostSetup hostSetup = CreateHostSetup(testPackage);
ScriptRuntimeSetup scriptRuntimeSetup = CreateScriptRuntimeSetup(testPackage);
string testDriverScriptPath = testDriverScriptFile.FullName;
var remoteMessageSink = new RemoteMessageSink(messageSink);
var remoteLogger = new RemoteLogger(logger);
using (var remoteProgressMonitor = new RemoteProgressMonitor(progressMonitor.CreateSubProgressMonitor(1)))
{
testIsolationContext.RunIsolatedTask<ExploreOrRunTask>(hostSetup,
(statusMessage) => progressMonitor.SetStatus(statusMessage),
new object[] { testPackage, scriptRuntimeSetup, testDriverScriptPath, testExplorationOptions, testExecutionOptions,
remoteMessageSink, remoteProgressMonitor, remoteLogger });
}
}
}
/// <summary>
/// Gets the test driver script file to run for a test package.
/// </summary>
/// <remarks>
/// <para>
/// Subclasses must override this method to return a test driver script file for
/// test exploration or execution.
/// </para>
/// </remarks>
/// <param name="testPackage">The test package, not null.</param>
/// <returns>The test driver script file to run, or null to script the test run.</returns>
protected abstract FileInfo GetTestDriverScriptFile(TestPackage testPackage);
/// <summary>
/// Creates a host setup for a test package.
/// </summary>
/// <param name="testPackage">The test package, not null.</param>
/// <returns>The host setup setup.</returns>
protected HostSetup CreateHostSetup(TestPackage testPackage)
{
HostSetup hostSetup = testPackage.CreateHostSetup();
ConfigureHostSetup(hostSetup, testPackage);
return hostSetup;
}
/// <summary>
/// Configures the host setup prior to the initialization of the script runtime.
/// </summary>
/// <remarks>
/// <para>
/// The default implementation does nothing. Subclasses may override this method
/// to customize the host setup.
/// </para>
/// </remarks>
/// <param name="hostSetup">The host setup, not null.</param>
/// <param name="testPackage">The test package, not null.</param>
protected virtual void ConfigureHostSetup(HostSetup hostSetup, TestPackage testPackage)
{
}
/// <summary>
/// Creates a script runtime setup for a test package.
/// </summary>
/// <param name="testPackage">The test package, not null.</param>
/// <returns>The script runtime setup.</returns>
protected ScriptRuntimeSetup CreateScriptRuntimeSetup(TestPackage testPackage)
{
ScriptRuntimeSetup scriptRuntimeSetup = ReadScriptRuntimeSetupFromConfiguration();
ConfigureIronRuby(scriptRuntimeSetup);
ConfigureScriptRuntimeSetup(scriptRuntimeSetup, testPackage);
return scriptRuntimeSetup;
}
private static ScriptRuntimeSetup ReadScriptRuntimeSetupFromConfiguration()
{
string assemblyFile = AssemblyUtils.GetFriendlyAssemblyLocation(typeof(DLRTestDriver).Assembly);
string configFile = assemblyFile + ".config";
return ScriptRuntimeSetup.ReadConfiguration(configFile);
}
/// <summary>
/// Configures the script runtime setup prior to the initialization of the script runtime.
/// </summary>
/// <remarks>
/// <para>
/// The default implementation does nothing. Subclasses may override this method
/// to customize the script runtime setup.
/// </para>
/// </remarks>
/// <param name="scriptRuntimeSetup">The script runtime setup, not null.</param>
/// <param name="testPackage">The test package, not null.</param>
protected virtual void ConfigureScriptRuntimeSetup(ScriptRuntimeSetup scriptRuntimeSetup, TestPackage testPackage)
{
}
private void ConfigureIronRuby(ScriptRuntimeSetup scriptRuntimeSetup)
{
LanguageSetup languageSetup = GenericCollectionUtils.Find(scriptRuntimeSetup.LanguageSetups, x => x.Names.Contains("IronRuby"));
if (languageSetup == null)
return;
IList<string> libraryPaths = GetIronRubyLibraryPaths(languageSetup);
ConfigureIronRuby(languageSetup, libraryPaths);
CanonicalizeLibraryPaths(libraryPaths);
SetIronRubyLibraryPaths(languageSetup, libraryPaths);
}
/// <summary>
/// Configures the IronRuby language options.
/// </summary>
/// <remarks>
/// <para>
/// The default implementation does nothing. Subclasses may override to
/// configure the IronRuby language options.
/// </para>
/// </remarks>
/// <param name="languageSetup">The IronRuby language setup.</param>
/// <param name="libraryPaths">The list of IronRuby library paths.</param>
protected virtual void ConfigureIronRuby(LanguageSetup languageSetup, IList<string> libraryPaths)
{
}
private static IList<string> GetIronRubyLibraryPaths(LanguageSetup languageSetup)
{
List<string> libraryPaths = new List<string>();
object value;
if (languageSetup.Options.TryGetValue("LibraryPaths", out value))
{
libraryPaths.AddRange(((string)value).Split(';'));
}
return libraryPaths;
}
private static void SetIronRubyLibraryPaths(LanguageSetup languageSetup, IList<string> libraryPaths)
{
languageSetup.Options["LibraryPaths"] = string.Join(";", GenericCollectionUtils.ToArray(libraryPaths));
}
private static void CanonicalizeLibraryPaths(IList<string> libraryPaths)
{
string pluginBaseDirectory = RuntimeAccessor.Registry.Plugins["Gallio.DLRIntegration"].BaseDirectory.FullName;
FileUtils.CanonicalizePaths(pluginBaseDirectory, libraryPaths);
}
private sealed class ExploreOrRunTask : IsolatedTask
{
protected override object RunImpl(object[] args)
{
ExploreOrRun(
(TestPackage)args[0],
(ScriptRuntimeSetup)args[1],
(string)args[2],
(TestExplorationOptions)args[3],
(TestExecutionOptions)args[4],
(IMessageSink)args[5],
(IProgressMonitor)args[6],
(ILogger)args[7]);
return null;
}
private static void ExploreOrRun(TestPackage testPackage, ScriptRuntimeSetup scriptRuntimeSetup, string testDriverScriptPath,
TestExplorationOptions testExplorationOptions, TestExecutionOptions testExecutionOptions,
IMessageSink messageSink, IProgressMonitor progressMonitor, ILogger logger)
{
using (BufferedLogWriter outputWriter = new BufferedLogWriter(logger, LogSeverity.Info, Encoding.Default),
errorWriter = new BufferedLogWriter(logger, LogSeverity.Error, Encoding.Default))
{
using (var queuedMessageSink = new QueuedMessageSink(messageSink))
{
using (new ConsoleRedirection(outputWriter, errorWriter))
{
var scriptRuntime = new ScriptRuntime(scriptRuntimeSetup);
scriptRuntime.IO.SetInput(Stream.Null, TextReader.Null, Encoding.Default);
scriptRuntime.IO.SetOutput(new TextWriterStream(outputWriter), outputWriter);
scriptRuntime.IO.SetErrorOutput(new TextWriterStream(errorWriter), errorWriter);
try
{
var scriptParameters = new Dictionary<string, object>();
scriptParameters.Add("Verb", testExecutionOptions != null ? "Run" : "Explore");
scriptParameters.Add("TestPackage", testPackage);
scriptParameters.Add("TestExplorationOptions", testExplorationOptions);
scriptParameters.Add("TestExecutionOptions", testExecutionOptions);
scriptParameters.Add("MessageSink", queuedMessageSink);
scriptParameters.Add("ProgressMonitor", progressMonitor);
scriptParameters.Add("Logger", logger);
scriptRuntime.Globals.SetVariable(ScriptParametersVariableName, scriptParameters);
RunScript(scriptRuntime, testDriverScriptPath);
}
finally
{
scriptRuntime.Shutdown();
}
}
}
}
}
private static void RunScript(ScriptRuntime scriptRuntime, string scriptPath)
{
var scriptRunner = new ScriptRunner(scriptRuntime, scriptPath);
var thread = new Thread(scriptRunner.Run);
thread.Name = "DLR Test Driver";
thread.SetApartmentState(ApartmentState.STA);
// Suppressing flow of the execution context trims a couple of frames off the stack.
// It's kind of silly to do except that IronRuby reports the caller's full stack
// trace for each exception all the way up to the top of the Thread and it's no
// fun to see stack traces for test failures cluttered with mscorlib stuff that is
// not necessary in this scenario. This is also part of why we create a new thread
// for the test run. (But we also create a thread to force the use of STA mode.)
// -- Jeff.
using (ExecutionContext.IsFlowSuppressed() ? (IDisposable) null : ExecutionContext.SuppressFlow())
thread.Start();
thread.Join();
if (scriptRunner.ExceptionMessage != null)
throw new ModelException(scriptRunner.ExceptionMessage);
}
}
private sealed class ScriptRunner
{
private readonly ScriptRuntime scriptRuntime;
private readonly string scriptPath;
public ScriptRunner(ScriptRuntime scriptRuntime, string scriptPath)
{
this.scriptRuntime = scriptRuntime;
this.scriptPath = scriptPath;
}
public string ExceptionMessage { get; private set; }
[DebuggerNonUserCode]
public void Run()
{
ScriptEngine engine = scriptRuntime.GetEngineByFileExtension(Path.GetExtension(scriptPath));
try
{
engine.ExecuteFile(scriptPath);
}
catch (Exception ex)
{
ExceptionMessage = engine.GetService<ExceptionOperations>().FormatException(ex);
}
}
}
private sealed class TextWriterStream : Stream
{
private readonly TextWriter writer;
public TextWriterStream(TextWriter writer)
{
this.writer = writer;
}
public override void Flush()
{
writer.Flush();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
writer.Write(Encoding.Default.GetString(buffer, offset, count));
}
public override bool CanRead
{
get { return false; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return true; }
}
public override long Length
{
get
{
throw new NotSupportedException();
}
}
public override long Position
{
get
{
throw new NotSupportedException();
}
set
{
throw new NotSupportedException();
}
}
}
}
}
| |
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace NSec.Cryptography
{
// RFC 5116
[Obsolete("This type is obsolete and will be removed in a future version.")]
[DebuggerDisplay("{GetDebuggerDisplay(),nq}")]
[StructLayout(LayoutKind.Explicit)]
public readonly struct Nonce : IEquatable<Nonce>
{
private const int maxSize = 24;
public static readonly int MaxSize = maxSize;
[FieldOffset(0)]
private readonly byte _bytes;
[FieldOffset(maxSize + 0)]
private readonly byte _fixedFieldSize;
[FieldOffset(maxSize + 1)]
private readonly byte _counterFieldSize;
[FieldOffset(maxSize + 2)]
private readonly byte _reserved0;
[FieldOffset(maxSize + 3)]
private readonly byte _reserved1;
public Nonce(
int fixedFieldSize,
int counterFieldSize)
: this()
{
if (fixedFieldSize < 0 || fixedFieldSize > maxSize)
{
throw Error.ArgumentOutOfRange_NonceFixedCounterSize(nameof(fixedFieldSize), maxSize);
}
if (counterFieldSize < 0 || counterFieldSize > maxSize - fixedFieldSize)
{
throw Error.ArgumentOutOfRange_NonceCounterSize(nameof(counterFieldSize), maxSize);
}
_fixedFieldSize = (byte)fixedFieldSize;
_counterFieldSize = (byte)counterFieldSize;
}
public Nonce(
ReadOnlySpan<byte> fixedField,
int counterFieldSize)
: this()
{
if (fixedField.Length > maxSize)
{
throw Error.Argument_NonceFixedSize(nameof(fixedField), maxSize);
}
if (counterFieldSize < 0 || counterFieldSize > maxSize - fixedField.Length)
{
throw Error.ArgumentOutOfRange_NonceFixedCounterSize(nameof(counterFieldSize), maxSize);
}
_fixedFieldSize = (byte)fixedField.Length;
_counterFieldSize = (byte)counterFieldSize;
Unsafe.CopyBlockUnaligned(ref _bytes, ref Unsafe.AsRef(in fixedField.GetPinnableReference()), (uint)fixedField.Length);
}
public Nonce(
ReadOnlySpan<byte> fixedField,
ReadOnlySpan<byte> counterField)
: this()
{
if (fixedField.Length > maxSize)
{
throw Error.Argument_NonceFixedSize(nameof(fixedField), maxSize);
}
if (counterField.Length > maxSize - fixedField.Length)
{
throw Error.Argument_NonceFixedCounterSize(nameof(counterField), maxSize);
}
_fixedFieldSize = (byte)fixedField.Length;
_counterFieldSize = (byte)counterField.Length;
Unsafe.CopyBlockUnaligned(ref _bytes, ref Unsafe.AsRef(in fixedField.GetPinnableReference()), (uint)fixedField.Length);
Unsafe.CopyBlockUnaligned(ref Unsafe.Add(ref _bytes, fixedField.Length), ref Unsafe.AsRef(in counterField.GetPinnableReference()), (uint)counterField.Length);
}
public int CounterFieldSize => _counterFieldSize;
public int FixedFieldSize => _fixedFieldSize;
public int Size => _fixedFieldSize + _counterFieldSize;
public static bool Equals(
in Nonce left,
in Nonce right)
{
if (Unsafe.SizeOf<Nonce>() != 6 * sizeof(uint) + 4 * sizeof(byte))
{
throw Error.InvalidOperation_InternalError();
}
if (right.Size != left.Size)
{
return false;
}
ref byte x = ref Unsafe.AsRef(in left._bytes);
ref byte y = ref Unsafe.AsRef(in right._bytes);
return Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref x, 0 * sizeof(uint))) == Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref y, 0 * sizeof(uint)))
&& Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref x, 1 * sizeof(uint))) == Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref y, 1 * sizeof(uint)))
&& Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref x, 2 * sizeof(uint))) == Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref y, 2 * sizeof(uint)))
&& Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref x, 3 * sizeof(uint))) == Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref y, 3 * sizeof(uint)))
&& Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref x, 4 * sizeof(uint))) == Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref y, 4 * sizeof(uint)))
&& Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref x, 5 * sizeof(uint))) == Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref y, 5 * sizeof(uint)));
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static new bool Equals(
object? objA,
object? objB)
{
return object.Equals(objA, objB);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static new bool ReferenceEquals(
object? objA,
object? objB)
{
return object.ReferenceEquals(objA, objB);
}
public static bool TryAdd(
ref Nonce nonce,
int value)
{
if (value < 0)
{
throw Error.ArgumentOutOfRange_NonceAddend(nameof(value));
}
ref byte bytes = ref Unsafe.AsRef(in nonce._bytes);
uint carry = (uint)value;
int end = nonce.FixedFieldSize;
int pos = nonce.Size;
while (carry != 0)
{
if (pos > end)
{
pos--;
Debug.Assert(pos >= 0 && pos < maxSize);
ref byte n = ref Unsafe.Add(ref bytes, pos);
carry += n;
n = unchecked((byte)carry);
carry >>= 8;
}
else
{
nonce = default;
return false;
}
}
return true;
}
public static bool TryIncrement(
ref Nonce nonce)
{
return TryAdd(ref nonce, 1);
}
public static void Xor(
ref Nonce nonce,
in Nonce other)
{
if (Unsafe.SizeOf<Nonce>() != 6 * sizeof(uint) + 4 * sizeof(byte))
{
throw Error.InvalidOperation_InternalError();
}
if (other.Size != nonce.Size)
{
throw Error.Argument_NonceXorSize(nameof(other));
}
Unsafe.AsRef(in nonce._fixedFieldSize) += nonce._counterFieldSize;
Unsafe.AsRef(in nonce._counterFieldSize) = 0;
ref byte x = ref Unsafe.AsRef(in nonce._bytes);
ref byte y = ref Unsafe.AsRef(in other._bytes);
Unsafe.WriteUnaligned(ref Unsafe.Add(ref x, 0 * sizeof(uint)), Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref x, 0 * sizeof(uint))) ^ Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref y, 0 * sizeof(uint))));
Unsafe.WriteUnaligned(ref Unsafe.Add(ref x, 1 * sizeof(uint)), Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref x, 1 * sizeof(uint))) ^ Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref y, 1 * sizeof(uint))));
Unsafe.WriteUnaligned(ref Unsafe.Add(ref x, 2 * sizeof(uint)), Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref x, 2 * sizeof(uint))) ^ Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref y, 2 * sizeof(uint))));
Unsafe.WriteUnaligned(ref Unsafe.Add(ref x, 3 * sizeof(uint)), Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref x, 3 * sizeof(uint))) ^ Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref y, 3 * sizeof(uint))));
Unsafe.WriteUnaligned(ref Unsafe.Add(ref x, 4 * sizeof(uint)), Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref x, 4 * sizeof(uint))) ^ Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref y, 4 * sizeof(uint))));
Unsafe.WriteUnaligned(ref Unsafe.Add(ref x, 5 * sizeof(uint)), Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref x, 5 * sizeof(uint))) ^ Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref y, 5 * sizeof(uint))));
}
public static bool operator !=(
Nonce left,
Nonce right)
{
return !Equals(in left, in right);
}
public static Nonce operator ^(
Nonce left,
Nonce right)
{
Nonce result = left;
Xor(ref result, in right);
return result;
}
public static Nonce operator +(
Nonce nonce,
int value)
{
Nonce result = nonce;
if (!TryAdd(ref result, value))
{
throw Error.Overflow_NonceCounter();
}
return result;
}
public static Nonce operator ++(
Nonce nonce)
{
Nonce result = nonce;
if (!TryAdd(ref result, 1))
{
throw Error.Overflow_NonceCounter();
}
return result;
}
public static bool operator ==(
Nonce left,
Nonce right)
{
return Equals(in left, in right);
}
public void CopyTo(
Span<byte> destination)
{
int size = Size;
if (destination.Length < size)
{
throw Error.Argument_DestinationTooShort(nameof(destination));
}
if (size > 0)
{
Unsafe.CopyBlockUnaligned(ref destination.GetPinnableReference(), ref Unsafe.AsRef(in _bytes), (uint)size);
}
}
public bool Equals(
Nonce other)
{
return Equals(in this, in other);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(
object? obj)
{
return (obj is Nonce other) && Equals(in this, in other);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
if (Unsafe.SizeOf<Nonce>() != 6 * sizeof(uint) + 4 * sizeof(byte))
{
throw Error.InvalidOperation_InternalError();
}
ref byte x = ref Unsafe.AsRef(in _bytes);
uint hashCode = unchecked((uint)Size);
hashCode = unchecked(hashCode * 0xA5555529 + Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref x, 0 * sizeof(uint))));
hashCode = unchecked(hashCode * 0xA5555529 + Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref x, 1 * sizeof(uint))));
hashCode = unchecked(hashCode * 0xA5555529 + Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref x, 2 * sizeof(uint))));
hashCode = unchecked(hashCode * 0xA5555529 + Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref x, 3 * sizeof(uint))));
hashCode = unchecked(hashCode * 0xA5555529 + Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref x, 4 * sizeof(uint))));
hashCode = unchecked(hashCode * 0xA5555529 + Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref x, 5 * sizeof(uint))));
return unchecked((int)hashCode);
}
public byte[] ToArray()
{
int size = Size;
byte[] bytes = new byte[size];
if (size > 0)
{
Unsafe.CopyBlockUnaligned(ref bytes[0], ref Unsafe.AsRef(in _bytes), (uint)size);
}
return bytes;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override string? ToString()
{
return typeof(Nonce).ToString();
}
internal string GetDebuggerDisplay()
{
ref byte bytes = ref Unsafe.AsRef(in _bytes);
int init = FixedFieldSize;
int size = Size;
StringBuilder sb = new StringBuilder(size * 2 + 4).Append('[');
for (int i = 0; i < init; i++)
{
sb.Append(Unsafe.Add(ref bytes, i).ToString("X2", CultureInfo.InvariantCulture));
}
sb.Append(']').Append('[');
for (int i = init; i < size; i++)
{
sb.Append(Unsafe.Add(ref bytes, i).ToString("X2", CultureInfo.InvariantCulture));
}
return sb.Append(']').ToString();
}
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using System.Text;
using Autodesk.Revit.DB;
namespace Revit.SDK.Samples.Truss.CS
{
/// <summary>
/// Vector4 is a homogeneous coordinate class used to store vector
/// and contain method to handle the vector
/// </summary>
public class Vector4
{
#region Class member variables and properties
private double m_x;
private double m_y;
private double m_z;
private double m_w = 1.0f;
/// <summary>
/// X property to get/set x value of Vector4
/// </summary>
public double X
{
get
{
return m_x;
}
set
{
m_x = value;
}
}
/// <summary>
/// Y property to get/set y value of Vector4
/// </summary>
public double Y
{
get
{
return m_y;
}
set
{
m_y = value;
}
}
/// <summary>
/// Z property to get/set z value of Vector4
/// </summary>
public double Z
{
get
{
return m_z;
}
set
{
m_z = value;
}
}
/// <summary>
/// W property to get/set fourth value of Vector4
/// </summary>
public double W
{
get
{
return m_w;
}
set
{
m_w = value;
}
}
#endregion
/// <summary>
/// constructor
/// </summary>
public Vector4(double x, double y, double z)
{
this.X = x; this.Y = y; this.Z = z;
}
/// <summary>
/// constructor, transfer Autodesk.Revit.DB.XYZ to vector
/// </summary>
/// <param name="v">Autodesk.Revit.DB.XYZ structure which needs to be transferred</param>
public Vector4(Autodesk.Revit.DB.XYZ v)
{
this.X = (double)v.X; this.Y = (double)v.Y; this.Z = (double)v.Z;
}
/// <summary>
/// adds two vectors
/// </summary>
/// <param name="va">first vector</param>
/// <param name="vb">second vector</param>
public static Vector4 operator+ (Vector4 va, Vector4 vb)
{
return new Vector4(va.X + vb.X, va.Y + vb.Y, va.Z + vb.Z);
}
/// <summary>
/// subtracts two vectors
/// </summary>
/// <param name="va">first vector</param>
/// <param name="vb">second vector</param>
/// <returns>subtraction of two vectors</returns>
public static Vector4 operator- (Vector4 va, Vector4 vb)
{
return new Vector4(va.X - vb.X, va.Y - vb.Y, va.Z - vb.Z);
}
/// <summary>
/// multiplies a vector by a doubling type value
/// </summary>
/// <param name="v">vector</param>
/// <param name="factor">multiplier of doubling type</param>
/// <returns> the result vector </returns>
public static Vector4 operator* (Vector4 v,double factor)
{
return new Vector4(v.X * factor, v.Y * factor, v.Z * factor);
}
/// <summary>
/// divides vector by a double type value
/// </summary>
/// <param name="v">vector</param>
/// <param name="factor">doubling type value</param>
/// <returns> vector divided by a doubling type value </returns>
public static Vector4 operator /(Vector4 v, double factor)
{
return new Vector4(v.X / factor, v.Y / factor, v.Z / factor);
}
/// <summary>
/// dot multiply vector
/// </summary>
/// <param name="v"> the result vector </param>
public double DotProduct(Vector4 v)
{
return (this.X * v.X + this.Y * v.Y + this.Z * v.Z);
}
/// <summary>
/// get normal vector of plane contains two vectors
/// </summary>
/// <param name="v">second vector</param>
/// <returns> normal vector of two vectors</returns>
public Vector4 CrossProduct(Vector4 v)
{
return new Vector4(this.Y * v.Z - this.Z * v.Y,this.Z * v.X
- this.X * v.Z,this.X * v.Y - this.Y * v.X);
}
/// <summary>
/// dot multiply two vectors
/// </summary>
/// <param name="va">first vector</param>
/// <param name="vb">second vector</param>
public static double DotProduct(Vector4 va, Vector4 vb)
{
return (va.X * vb.X + va.Y * vb.Y + va.Z * vb.Z);
}
/// <summary>
/// get normal vector of two vectors
/// </summary>
/// <param name="va">first vector</param>
/// <param name="vb">second vector</param>
/// <returns> normal vector of two vectors </returns>
public static Vector4 CrossProduct(Vector4 va, Vector4 vb)
{
return new Vector4(va.Y * vb.Z - va.Z * vb.Y, va.Z * vb.X
- va.X * vb.Z, va.X * vb.Y - va.Y * vb.X);
}
/// <summary>
/// get unit vector
/// </summary>
public void Normalize()
{
double length = Length();
if(length == 0)
{
length = 1;
}
this.X /= length;
this.Y /= length;
this.Z /= length;
}
/// <summary>
/// calculate the length of vector
/// </summary>
public double Length()
{
return (double)Math.Sqrt(this.X * this.X + this.Y * this.Y + this.Z * this.Z);
}
};
/// <summary>
/// Matrix used to transform between ucs coordinate and world coordinate.
/// </summary>
public class Matrix4
{
#region MatrixType
/// <summary>
/// Matrix Type Enum use to define function of matrix
/// </summary>
public enum MatrixType
{
/// <summary>
/// matrix use to rotate
/// </summary>
Rotation,
/// <summary>
/// matrix used to Translation
/// </summary>
Translation,
/// <summary>
/// matrix used to Scale
/// </summary>
Scale,
/// <summary>
/// matrix used to Rotation and Translation
/// </summary>
RotationAndTranslation,
/// <summary>
/// normal matrix
/// </summary>
Normal
};
private double[,] m_matrix = new double[4,4]; // an array stores the matrix
private MatrixType m_type; //type of matrix
#endregion
/// <summary>
/// default constructor
/// </summary>
public Matrix4()
{
m_type = MatrixType.Normal;
Identity();
}
/// <summary>
/// ctor,rotation matrix,origin at (0,0,0)
/// </summary>
/// <param name="xAxis">identity of x axis</param>
/// <param name="yAxis">identity of y axis</param>
/// <param name="zAxis">identity of z axis</param>
public Matrix4(Vector4 xAxis,Vector4 yAxis, Vector4 zAxis)
{
m_type = MatrixType.Rotation;
Identity();
m_matrix[0, 0] = xAxis.X; m_matrix[0, 1] = xAxis.Y; m_matrix[0, 2] = xAxis.Z;
m_matrix[1, 0] = yAxis.X; m_matrix[1, 1] = yAxis.Y; m_matrix[1, 2] = yAxis.Z;
m_matrix[2, 0] = zAxis.X; m_matrix[2, 1] = zAxis.Y; m_matrix[2, 2] = zAxis.Z;
}
/// <summary>
/// ctor,translation matrix.
/// </summary>
/// <param name="origin">origin of ucs in world coordinate</param>
public Matrix4(Vector4 origin)
{
m_type = MatrixType.Translation;
Identity();
m_matrix[3, 0] = origin.X; m_matrix[3, 1] = origin.Y; m_matrix[3, 2] = origin.Z;
}
/// <summary>
/// rotation and translation matrix constructor
/// </summary>
/// <param name="xAxis">x Axis</param>
/// <param name="yAxis">y Axis</param>
/// <param name="zAxis">z Axis</param>
/// <param name="origin">origin</param>
public Matrix4(Vector4 xAxis, Vector4 yAxis, Vector4 zAxis, Vector4 origin)
{
m_type = MatrixType.RotationAndTranslation;
Identity();
m_matrix[0, 0] = xAxis.X; m_matrix[0, 1] = xAxis.Y; m_matrix[0, 2] = xAxis.Z;
m_matrix[1, 0] = yAxis.X; m_matrix[1, 1] = yAxis.Y; m_matrix[1, 2] = yAxis.Z;
m_matrix[2, 0] = zAxis.X; m_matrix[2, 1] = zAxis.Y; m_matrix[2, 2] = zAxis.Z;
m_matrix[3, 0] = origin.X; m_matrix[3, 1] = origin.Y; m_matrix[3, 2] = origin.Z;
}
/// <summary>
/// scale matrix constructor
/// </summary>
/// <param name="scale">scale factor</param>
public Matrix4(double scale)
{
m_type = MatrixType.Scale;
Identity();
m_matrix[0, 0] = scale;
m_matrix[1, 1] = scale;
m_matrix[2, 2] = scale;
}
/// <summary>
/// indexer of matrix
/// </summary>
/// <param name="row">row number</param>
/// <param name="column">column number</param>
/// <returns></returns>
public double this[int row, int column]
{
get
{
return this.m_matrix[row, column];
}
set
{
this.m_matrix[row, column] = value;
}
}
/// <summary>
/// Identity matrix
/// </summary>
public void Identity()
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
this.m_matrix[i, j] = 0.0f;
}
}
this.m_matrix[0, 0] = 1.0f;
this.m_matrix[1, 1] = 1.0f;
this.m_matrix[2, 2] = 1.0f;
this.m_matrix[3, 3] = 1.0f;
}
/// <summary>
/// multiply matrix left and right
/// </summary>
/// <param name="left">left matrix</param>
/// <param name="right">right matrix</param>
/// <returns></returns>
public static Matrix4 Multiply(Matrix4 left, Matrix4 right)
{
Matrix4 result = new Matrix4();
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
result[i, j] = left[i, 0] * right[0, j] + left[i, 1] * right[1, j]
+ left[i, 2] * right[2, j] + left[i, 3] * right[3, j];
}
}
return result;
}
/// <summary>
/// transform point using this matrix
/// </summary>
/// <param name="point">point to be transformed</param>
/// <returns>transform result</returns>
public Vector4 Transform(Vector4 point)
{
return new Vector4(point.X * this[0, 0] + point.Y * this[1, 0]
+ point.Z * this[2, 0]+ point.W * this[3, 0],
point.X * this[0, 1] + point.Y * this[1, 1]
+ point.Z * this[2, 1]+ point.W * this[3, 1],
point.X * this[0, 2] + point.Y * this[1, 2]
+ point.Z * this[2, 2]+ point.W * this[3, 2]);
}
/// <summary>
/// if m_matrix is a rotation matrix,this method can get the rotation inverse matrix.
/// </summary>
/// <returns>inverse of rotation matrix</returns>
public Matrix4 RotationInverse()
{
return new Matrix4(new Vector4(this[0, 0], this[1, 0], this[2, 0]),
new Vector4(this[0, 1], this[1, 1], this[2, 1]),
new Vector4(this[0, 2], this[1, 2], this[2, 2]));
}
/// <summary>
/// if this m_matrix is a translation matrix,
/// this method can get the translation inverse matrix.
/// </summary>
/// <returns>inverse of translation matrix</returns>
public Matrix4 TranslationInverse()
{
return new Matrix4(new Vector4(-this[3, 0], -this[3, 1], -this[3, 2]));
}
/// <summary>
/// get inverse matrix
/// </summary>
/// <returns>inverse matrix</returns>
public Matrix4 Inverse()
{
switch(m_type)
{
case MatrixType.Rotation:
return RotationInverse();
case MatrixType.Translation:
return TranslationInverse();
case MatrixType.RotationAndTranslation:
return Multiply(TranslationInverse(),RotationInverse());
case MatrixType.Scale:
return ScaleInverse();
case MatrixType.Normal:
return new Matrix4();
default: return null;
}
}
/// <summary>
/// if m_matrix is a scale matrix,this method can get the scale inverse matrix.
/// </summary>
/// <returns>inverse of scale matrix</returns>
public Matrix4 ScaleInverse()
{
return new Matrix4(1 / m_matrix[0,0]);
}
};
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
namespace Orleans.Storage
{
internal class HierarchicalKeyStore :
#if !NETSTANDARD_TODO
MarshalByRefObject,
#endif
ILocalDataStore
{
public string Etag { get; private set; }
private const string KEY_VALUE_PAIR_SEPERATOR = "+";
private const string KEY_VALUE_SEPERATOR = "=";
private long lastETagCounter = 1;
[NonSerialized]
private readonly IDictionary<string, IDictionary<string, object>> dataTable;
private readonly int numKeyLayers;
private readonly object lockable = new object();
public HierarchicalKeyStore(int keyLayers)
{
numKeyLayers = keyLayers;
dataTable = new Dictionary<string, IDictionary<string, object>>();
}
public string WriteRow(IList<Tuple<string, string>> keys, IDictionary<string, object> data, string eTag)
{
if (keys.Count > numKeyLayers)
{
var error = string.Format("Wrong number of keys supplied -- Expected count = {0} Received = {1}", numKeyLayers, keys.Count);
Trace.TraceError(error);
throw new ArgumentOutOfRangeException("keys", keys.Count, error);
}
lock (lockable)
{
var storedData = GetDataStore(keys);
foreach (var kv in data)
storedData[kv.Key] = kv.Value;
Etag = NewEtag();
#if DEBUG
var storeContents = DumpData(false);
Trace.TraceInformation("WriteRow: Keys={0} Data={1} Store contents after = {2} New Etag = {3}",
StorageProviderUtils.PrintKeys(keys),
StorageProviderUtils.PrintData(data),
storeContents, Etag);
#endif
return Etag;
}
}
public IDictionary<string, object> ReadRow(IList<Tuple<string, string>> keys)
{
if (keys.Count > numKeyLayers)
{
var error = string.Format("Not enough keys supplied -- Expected count = {0} Received = {1}", numKeyLayers, keys.Count);
Trace.TraceError(error);
throw new ArgumentOutOfRangeException("keys", keys.Count, error);
}
lock (lockable)
{
IDictionary<string, object> data = GetDataStore(keys);
#if DEBUG
Trace.TraceInformation("ReadMultiRow: Keys={0} returning Data={1}",
StorageProviderUtils.PrintKeys(keys), StorageProviderUtils.PrintData(data));
#endif
return data;
}
}
public IList<IDictionary<string, object>> ReadMultiRow(IList<Tuple<string, string>> keys)
{
if (keys.Count > numKeyLayers)
{
throw new ArgumentOutOfRangeException("keys", keys.Count,
string.Format("Too many key supplied -- Expected count = {0} Received = {1}", numKeyLayers, keys.Count));
}
lock (lockable)
{
IList<IDictionary<string, object>> results = FindDataStores(keys);
#if DEBUG
Trace.TraceInformation("ReadMultiRow: Keys={0} returning Results={1}",
StorageProviderUtils.PrintKeys(keys), StorageProviderUtils.PrintResults(results));
#endif
return results;
}
}
public bool DeleteRow(IList<Tuple<string, string>> keys, string eTag)
{
if (keys.Count > numKeyLayers)
{
throw new ArgumentOutOfRangeException("keys", keys.Count,
string.Format("Not enough keys supplied -- Expected count = {0} Received = {1}", numKeyLayers, keys.Count));
}
string keyStr = MakeStoreKey(keys);
bool removedEntry = false;
lock (lockable)
{
IDictionary<string, object> data;
if (dataTable.TryGetValue(keyStr, out data))
{
var kv = new KeyValuePair<string, IDictionary<string, object>>(keyStr, data);
dataTable.Remove(kv);
removedEntry = true;
}
// No change to Etag
#if DEBUG
Trace.TraceInformation("DeleteRow: Keys={0} Removed={1} Data={2} Etag={3}",
StorageProviderUtils.PrintKeys(keys),
StorageProviderUtils.PrintData(data),
removedEntry, Etag);
#endif
return removedEntry;
}
}
public void Clear()
{
#if DEBUG
Trace.TraceInformation("Clear Table");
#endif
lock (lockable)
{
dataTable.Clear();
}
}
public string DumpData(bool printDump = true)
{
var sb = new StringBuilder();
lock (lockable)
{
string[] keys = dataTable.Keys.ToArray();
foreach (var key in keys)
{
var data = dataTable[key];
sb.AppendFormat("{0} => {1}", key, StorageProviderUtils.PrintData(data)).AppendLine();
}
}
#if !DEBUG
if (printDump)
#endif
{
Trace.TraceInformation("Dump {0} Etag={1} Data= {2}", GetType(), Etag, sb);
}
return sb.ToString();
}
private IDictionary<string, object> GetDataStore(IList<Tuple<string, string>> keys)
{
string keyStr = MakeStoreKey(keys);
lock (lockable)
{
IDictionary<string, object> data;
if (dataTable.ContainsKey(keyStr))
{
data = dataTable[keyStr];
}
else
{
data = new Dictionary<string, object>(); // Empty data set
dataTable[keyStr] = data;
}
#if DEBUG
Trace.TraceInformation("Read: {0}", StorageProviderUtils.PrintOneWrite(keys, data, null));
#endif
return data;
}
}
private IList<IDictionary<string, object>> FindDataStores(IList<Tuple<string, string>> keys)
{
var results = new List<IDictionary<string, object>>();
if (numKeyLayers == keys.Count)
{
results.Add(GetDataStore(keys));
}
else
{
string keyStr = MakeStoreKey(keys);
lock (lockable)
{
foreach (var key in dataTable.Keys)
if (key.StartsWith(keyStr))
results.Add(dataTable[key]);
}
}
return results;
}
internal static string MakeStoreKey(IEnumerable<Tuple<string, string>> keys)
{
var sb = new StringBuilder();
bool first = true;
foreach (var keyPair in keys)
{
if (first)
first = false;
else
sb.Append(KEY_VALUE_PAIR_SEPERATOR);
sb.Append(keyPair.Item1 + KEY_VALUE_SEPERATOR + keyPair.Item2);
}
return sb.ToString();
}
private string NewEtag()
{
return lastETagCounter++.ToString(CultureInfo.InvariantCulture);
}
}
}
| |
namespace LeetABit.Binary
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
public readonly ref struct BitwiseSpan<T>
{
public ref struct Enumerator
{
private readonly BitwiseSpan<T> _span;
private int _index;
public ref T Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
return ref _span[_index];
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Enumerator(BitwiseSpan<T> span)
{
_span = span;
_index = -1;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
int num = _index + 1;
if (num < _span.Length)
{
_index = num;
return true;
}
return false;
}
}
private readonly Span<T> span;
private readonly int startBit;
private readonly int bitLength;
public BitwiseSpan(T value, int startBit, int bitLength)
{
this.span = MemoryMarshal.CreateSpan(ref value, 1);
this.startBit = startBit;
this.bitLength = bitLength;
}
public BitwiseSpan(ref T value, int startBit, int bitLength)
{
this.span = MemoryMarshal.CreateSpan(ref value, ((startBit + bitLength - 1) >> Bits.ByteBitIndexBitSize) + 1);
this.startBit = startBit;
this.bitLength = bitLength;
}
public BitwiseSpan(Span<T> value, int startBit, int bitLength)
{
this.span = value;
this.startBit = startBit;
this.bitLength = bitLength;
}
public BitwiseSpan(T[] array, int startBit, int bitLength)
{
this.span = new Span<T>(array);
this.startBit = startBit;
this.bitLength = bitLength;
}
public unsafe BitwiseSpan(void* pointer, int startBit, int bitLength)
{
this.span = new Span<T>(pointer, ((startBit + bitLength - 1) >> Bits.ByteBitIndexBitSize) + 1);
this.startBit = startBit;
this.bitLength = bitLength;
}
public int BitLength
{
get
{
return this.bitLength;
}
}
public int StartBit
{
get
{
return this.startBit;
}
}
public Span<T> Span
{
get
{
return this.span;
}
}
public bool IsEmpty
{
get
{
return 0u >= (uint)this.bitLength;
}
}
public static BitwiseSpan<T> Empty => default(BitwiseSpan<T>);
public static bool operator !=(BitwiseSpan<T> left, BitwiseSpan<T> right)
{
return !(left == right);
}
[Obsolete("Equals() on Span will always throw an exception. Use == instead.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj)
{
throw new NotSupportedException("SR.NotSupported_CannotCallEqualsOnSpan");
}
[Obsolete("GetHashCode() on Span will always throw an exception.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
throw new NotSupportedException("SR.NotSupported_CannotCallGetHashCodeOnSpan");
}
public static implicit operator BitwiseSpan<T>(T[]? array)
{
return new BitwiseSpan<T>(array, 0, array.Length * Unsafe.SizeOf<T>() * Bits.ByteBitSize);
}
public static implicit operator BitwiseSpan<T>(ArraySegment<T> segment)
{
return new BitwiseSpan<T>(segment, 0, segment.Count * Unsafe.SizeOf<T>() * Bits.ByteBitSize);
}
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void Clear()
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
SpanHelpers.ClearWithReferences(ref Unsafe.As<T, IntPtr>(ref _pointer.Value), (nuint)(uint)_length * (nuint)(Unsafe.SizeOf<T>() / sizeof(UIntPtr)));
}
else
{
SpanHelpers.ClearWithoutReferences(ref Unsafe.As<T, byte>(ref _pointer.Value), (nuint)(uint)_length * (nuint)Unsafe.SizeOf<T>());
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Fill(bool bitValue)
{
if (Unsafe.SizeOf<T>() == 1)
{
Unsafe.InitBlockUnaligned(ref Unsafe.As<T, byte>(ref _pointer.Value), Unsafe.As<T, byte>(ref value), (uint)_length);
}
else
{
SpanHelpers.Fill(ref _pointer.Value, (uint)_length, value);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void CopyTo(BitwiseSpan<T> destination)
{
if ((uint)_length <= (uint)destination.Length)
{
Buffer.Memmove<T>(ref destination._pointer.Value, ref _pointer.Value, (uint)_length);
}
else
{
ThrowHelper.ThrowArgumentException_DestinationTooShort();
}
}
public bool TryCopyTo(BitwiseSpan<T> destination)
{
bool result = false;
if ((uint)_length <= (uint)destination.Length)
{
Buffer.Memmove<T>(ref destination._pointer.Value, ref _pointer.Value, (uint)_length);
result = true;
}
return result;
}
public static bool operator ==(BitwiseSpan<T> left, BitwiseSpan<T> right)
{
if (left._length == right._length)
{
return Unsafe.AreSame(ref left._pointer.Value, ref right._pointer.Value);
}
return false;
}
public static implicit operator ReadOnlyBitwiseSpan<T>(BitwiseSpan<T> span)
{
return new ReadOnlyBitwiseSpan<T>(span.span, span.startBit, span.bitLength);
}
public override string ToString()
{
return $"LeetABit.Binary.BitwiseSpan<{typeof(T).Name}>[{this.bitLength}]";
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span<T> Slice(int start)
{
if ((uint)start > (uint)_length)
{
ThrowHelper.ThrowArgumentOutOfRangeException();
}
return new Span<T>(ref Unsafe.Add(ref _pointer.Value, (nint)(uint)start), _length - start);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span<T> Slice(int start, int length)
{
if ((ulong)((long)(uint)start + (long)(uint)length) > (ulong)(uint)_length)
{
ThrowHelper.ThrowArgumentOutOfRangeException();
}
return new Span<T>(ref Unsafe.Add(ref _pointer.Value, (nint)(uint)start), length);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T[] ToArray()
{
if (_length == 0)
{
return Array.Empty<T>();
}
T[] array = new T[_length];
Buffer.Memmove(ref MemoryMarshal.GetArrayDataReference(array), ref _pointer.Value, (uint)_length);
return array;
}
}
}
| |
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 MachiningCloudManager.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;
}
}
}
| |
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 RemExamenPie class.
/// </summary>
[Serializable]
public partial class RemExamenPieCollection : ActiveList<RemExamenPie, RemExamenPieCollection>
{
public RemExamenPieCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>RemExamenPieCollection</returns>
public RemExamenPieCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
RemExamenPie 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 Rem_ExamenPie table.
/// </summary>
[Serializable]
public partial class RemExamenPie : ActiveRecord<RemExamenPie>, IActiveRecord
{
#region .ctors and Default Settings
public RemExamenPie()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public RemExamenPie(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public RemExamenPie(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public RemExamenPie(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("Rem_ExamenPie", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdExamenPies = new TableSchema.TableColumn(schema);
colvarIdExamenPies.ColumnName = "idExamenPies";
colvarIdExamenPies.DataType = DbType.Int32;
colvarIdExamenPies.MaxLength = 0;
colvarIdExamenPies.AutoIncrement = true;
colvarIdExamenPies.IsNullable = false;
colvarIdExamenPies.IsPrimaryKey = true;
colvarIdExamenPies.IsForeignKey = false;
colvarIdExamenPies.IsReadOnly = false;
colvarIdExamenPies.DefaultSetting = @"";
colvarIdExamenPies.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdExamenPies);
TableSchema.TableColumn colvarIdEfector = new TableSchema.TableColumn(schema);
colvarIdEfector.ColumnName = "idEfector";
colvarIdEfector.DataType = DbType.Int32;
colvarIdEfector.MaxLength = 0;
colvarIdEfector.AutoIncrement = false;
colvarIdEfector.IsNullable = false;
colvarIdEfector.IsPrimaryKey = false;
colvarIdEfector.IsForeignKey = false;
colvarIdEfector.IsReadOnly = false;
colvarIdEfector.DefaultSetting = @"((0))";
colvarIdEfector.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdEfector);
TableSchema.TableColumn colvarIdClasificacion = new TableSchema.TableColumn(schema);
colvarIdClasificacion.ColumnName = "idClasificacion";
colvarIdClasificacion.DataType = DbType.Int32;
colvarIdClasificacion.MaxLength = 0;
colvarIdClasificacion.AutoIncrement = false;
colvarIdClasificacion.IsNullable = false;
colvarIdClasificacion.IsPrimaryKey = false;
colvarIdClasificacion.IsForeignKey = true;
colvarIdClasificacion.IsReadOnly = false;
colvarIdClasificacion.DefaultSetting = @"((0))";
colvarIdClasificacion.ForeignKeyTableName = "Rem_Clasificacion";
schema.Columns.Add(colvarIdClasificacion);
TableSchema.TableColumn colvarIdPaciente = new TableSchema.TableColumn(schema);
colvarIdPaciente.ColumnName = "idPaciente";
colvarIdPaciente.DataType = DbType.Int32;
colvarIdPaciente.MaxLength = 0;
colvarIdPaciente.AutoIncrement = false;
colvarIdPaciente.IsNullable = false;
colvarIdPaciente.IsPrimaryKey = false;
colvarIdPaciente.IsForeignKey = false;
colvarIdPaciente.IsReadOnly = false;
colvarIdPaciente.DefaultSetting = @"((0))";
colvarIdPaciente.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdPaciente);
TableSchema.TableColumn colvarFecha = new TableSchema.TableColumn(schema);
colvarFecha.ColumnName = "fecha";
colvarFecha.DataType = DbType.DateTime;
colvarFecha.MaxLength = 0;
colvarFecha.AutoIncrement = false;
colvarFecha.IsNullable = false;
colvarFecha.IsPrimaryKey = false;
colvarFecha.IsForeignKey = false;
colvarFecha.IsReadOnly = false;
colvarFecha.DefaultSetting = @"(((1)/(1))/(1900))";
colvarFecha.ForeignKeyTableName = "";
schema.Columns.Add(colvarFecha);
TableSchema.TableColumn colvarObservacion = new TableSchema.TableColumn(schema);
colvarObservacion.ColumnName = "observacion";
colvarObservacion.DataType = DbType.AnsiString;
colvarObservacion.MaxLength = 200;
colvarObservacion.AutoIncrement = false;
colvarObservacion.IsNullable = false;
colvarObservacion.IsPrimaryKey = false;
colvarObservacion.IsForeignKey = false;
colvarObservacion.IsReadOnly = false;
colvarObservacion.DefaultSetting = @"('')";
colvarObservacion.ForeignKeyTableName = "";
schema.Columns.Add(colvarObservacion);
TableSchema.TableColumn colvarSensibTermica = new TableSchema.TableColumn(schema);
colvarSensibTermica.ColumnName = "sensibTermica";
colvarSensibTermica.DataType = DbType.Int32;
colvarSensibTermica.MaxLength = 0;
colvarSensibTermica.AutoIncrement = false;
colvarSensibTermica.IsNullable = false;
colvarSensibTermica.IsPrimaryKey = false;
colvarSensibTermica.IsForeignKey = false;
colvarSensibTermica.IsReadOnly = false;
colvarSensibTermica.DefaultSetting = @"((0))";
colvarSensibTermica.ForeignKeyTableName = "";
schema.Columns.Add(colvarSensibTermica);
TableSchema.TableColumn colvarSensibAlgesica = new TableSchema.TableColumn(schema);
colvarSensibAlgesica.ColumnName = "sensibAlgesica";
colvarSensibAlgesica.DataType = DbType.Int32;
colvarSensibAlgesica.MaxLength = 0;
colvarSensibAlgesica.AutoIncrement = false;
colvarSensibAlgesica.IsNullable = false;
colvarSensibAlgesica.IsPrimaryKey = false;
colvarSensibAlgesica.IsForeignKey = false;
colvarSensibAlgesica.IsReadOnly = false;
colvarSensibAlgesica.DefaultSetting = @"((0))";
colvarSensibAlgesica.ForeignKeyTableName = "";
schema.Columns.Add(colvarSensibAlgesica);
TableSchema.TableColumn colvarReflejoPatelar = new TableSchema.TableColumn(schema);
colvarReflejoPatelar.ColumnName = "reflejoPatelar";
colvarReflejoPatelar.DataType = DbType.Int32;
colvarReflejoPatelar.MaxLength = 0;
colvarReflejoPatelar.AutoIncrement = false;
colvarReflejoPatelar.IsNullable = false;
colvarReflejoPatelar.IsPrimaryKey = false;
colvarReflejoPatelar.IsForeignKey = false;
colvarReflejoPatelar.IsReadOnly = false;
colvarReflejoPatelar.DefaultSetting = @"((0))";
colvarReflejoPatelar.ForeignKeyTableName = "";
schema.Columns.Add(colvarReflejoPatelar);
TableSchema.TableColumn colvarReflejoAquileano = new TableSchema.TableColumn(schema);
colvarReflejoAquileano.ColumnName = "reflejoAquileano";
colvarReflejoAquileano.DataType = DbType.Int32;
colvarReflejoAquileano.MaxLength = 0;
colvarReflejoAquileano.AutoIncrement = false;
colvarReflejoAquileano.IsNullable = false;
colvarReflejoAquileano.IsPrimaryKey = false;
colvarReflejoAquileano.IsForeignKey = false;
colvarReflejoAquileano.IsReadOnly = false;
colvarReflejoAquileano.DefaultSetting = @"((0))";
colvarReflejoAquileano.ForeignKeyTableName = "";
schema.Columns.Add(colvarReflejoAquileano);
TableSchema.TableColumn colvarSignoAbanico = new TableSchema.TableColumn(schema);
colvarSignoAbanico.ColumnName = "signoAbanico";
colvarSignoAbanico.DataType = DbType.Int32;
colvarSignoAbanico.MaxLength = 0;
colvarSignoAbanico.AutoIncrement = false;
colvarSignoAbanico.IsNullable = false;
colvarSignoAbanico.IsPrimaryKey = false;
colvarSignoAbanico.IsForeignKey = false;
colvarSignoAbanico.IsReadOnly = false;
colvarSignoAbanico.DefaultSetting = @"((0))";
colvarSignoAbanico.ForeignKeyTableName = "";
schema.Columns.Add(colvarSignoAbanico);
TableSchema.TableColumn colvarSensibDiapason = new TableSchema.TableColumn(schema);
colvarSensibDiapason.ColumnName = "sensibDiapason";
colvarSensibDiapason.DataType = DbType.Int32;
colvarSensibDiapason.MaxLength = 0;
colvarSensibDiapason.AutoIncrement = false;
colvarSensibDiapason.IsNullable = false;
colvarSensibDiapason.IsPrimaryKey = false;
colvarSensibDiapason.IsForeignKey = false;
colvarSensibDiapason.IsReadOnly = false;
colvarSensibDiapason.DefaultSetting = @"((0))";
colvarSensibDiapason.ForeignKeyTableName = "";
schema.Columns.Add(colvarSensibDiapason);
TableSchema.TableColumn colvarFuerzaMuscular = new TableSchema.TableColumn(schema);
colvarFuerzaMuscular.ColumnName = "fuerzaMuscular";
colvarFuerzaMuscular.DataType = DbType.Int32;
colvarFuerzaMuscular.MaxLength = 0;
colvarFuerzaMuscular.AutoIncrement = false;
colvarFuerzaMuscular.IsNullable = false;
colvarFuerzaMuscular.IsPrimaryKey = false;
colvarFuerzaMuscular.IsForeignKey = false;
colvarFuerzaMuscular.IsReadOnly = false;
colvarFuerzaMuscular.DefaultSetting = @"((0))";
colvarFuerzaMuscular.ForeignKeyTableName = "";
schema.Columns.Add(colvarFuerzaMuscular);
TableSchema.TableColumn colvarAlteracionesApoyo = new TableSchema.TableColumn(schema);
colvarAlteracionesApoyo.ColumnName = "alteracionesApoyo";
colvarAlteracionesApoyo.DataType = DbType.Int32;
colvarAlteracionesApoyo.MaxLength = 0;
colvarAlteracionesApoyo.AutoIncrement = false;
colvarAlteracionesApoyo.IsNullable = false;
colvarAlteracionesApoyo.IsPrimaryKey = false;
colvarAlteracionesApoyo.IsForeignKey = false;
colvarAlteracionesApoyo.IsReadOnly = false;
colvarAlteracionesApoyo.DefaultSetting = @"((0))";
colvarAlteracionesApoyo.ForeignKeyTableName = "";
schema.Columns.Add(colvarAlteracionesApoyo);
TableSchema.TableColumn colvarDisminucionMovilidad = new TableSchema.TableColumn(schema);
colvarDisminucionMovilidad.ColumnName = "disminucionMovilidad";
colvarDisminucionMovilidad.DataType = DbType.Int32;
colvarDisminucionMovilidad.MaxLength = 0;
colvarDisminucionMovilidad.AutoIncrement = false;
colvarDisminucionMovilidad.IsNullable = false;
colvarDisminucionMovilidad.IsPrimaryKey = false;
colvarDisminucionMovilidad.IsForeignKey = false;
colvarDisminucionMovilidad.IsReadOnly = false;
colvarDisminucionMovilidad.DefaultSetting = @"((0))";
colvarDisminucionMovilidad.ForeignKeyTableName = "";
schema.Columns.Add(colvarDisminucionMovilidad);
TableSchema.TableColumn colvarDedosMartillo = new TableSchema.TableColumn(schema);
colvarDedosMartillo.ColumnName = "dedosMartillo";
colvarDedosMartillo.DataType = DbType.Int32;
colvarDedosMartillo.MaxLength = 0;
colvarDedosMartillo.AutoIncrement = false;
colvarDedosMartillo.IsNullable = false;
colvarDedosMartillo.IsPrimaryKey = false;
colvarDedosMartillo.IsForeignKey = false;
colvarDedosMartillo.IsReadOnly = false;
colvarDedosMartillo.DefaultSetting = @"((0))";
colvarDedosMartillo.ForeignKeyTableName = "";
schema.Columns.Add(colvarDedosMartillo);
TableSchema.TableColumn colvarClinodactilia = new TableSchema.TableColumn(schema);
colvarClinodactilia.ColumnName = "clinodactilia";
colvarClinodactilia.DataType = DbType.Int32;
colvarClinodactilia.MaxLength = 0;
colvarClinodactilia.AutoIncrement = false;
colvarClinodactilia.IsNullable = false;
colvarClinodactilia.IsPrimaryKey = false;
colvarClinodactilia.IsForeignKey = false;
colvarClinodactilia.IsReadOnly = false;
colvarClinodactilia.DefaultSetting = @"((0))";
colvarClinodactilia.ForeignKeyTableName = "";
schema.Columns.Add(colvarClinodactilia);
TableSchema.TableColumn colvarHalluxValgus = new TableSchema.TableColumn(schema);
colvarHalluxValgus.ColumnName = "halluxValgus";
colvarHalluxValgus.DataType = DbType.Int32;
colvarHalluxValgus.MaxLength = 0;
colvarHalluxValgus.AutoIncrement = false;
colvarHalluxValgus.IsNullable = false;
colvarHalluxValgus.IsPrimaryKey = false;
colvarHalluxValgus.IsForeignKey = false;
colvarHalluxValgus.IsReadOnly = false;
colvarHalluxValgus.DefaultSetting = @"((0))";
colvarHalluxValgus.ForeignKeyTableName = "";
schema.Columns.Add(colvarHalluxValgus);
TableSchema.TableColumn colvarAusenciaVello = new TableSchema.TableColumn(schema);
colvarAusenciaVello.ColumnName = "ausenciaVello";
colvarAusenciaVello.DataType = DbType.Int32;
colvarAusenciaVello.MaxLength = 0;
colvarAusenciaVello.AutoIncrement = false;
colvarAusenciaVello.IsNullable = false;
colvarAusenciaVello.IsPrimaryKey = false;
colvarAusenciaVello.IsForeignKey = false;
colvarAusenciaVello.IsReadOnly = false;
colvarAusenciaVello.DefaultSetting = @"((0))";
colvarAusenciaVello.ForeignKeyTableName = "";
schema.Columns.Add(colvarAusenciaVello);
TableSchema.TableColumn colvarDisminucionPlantar = new TableSchema.TableColumn(schema);
colvarDisminucionPlantar.ColumnName = "disminucionPlantar";
colvarDisminucionPlantar.DataType = DbType.Int32;
colvarDisminucionPlantar.MaxLength = 0;
colvarDisminucionPlantar.AutoIncrement = false;
colvarDisminucionPlantar.IsNullable = false;
colvarDisminucionPlantar.IsPrimaryKey = false;
colvarDisminucionPlantar.IsForeignKey = false;
colvarDisminucionPlantar.IsReadOnly = false;
colvarDisminucionPlantar.DefaultSetting = @"((0))";
colvarDisminucionPlantar.ForeignKeyTableName = "";
schema.Columns.Add(colvarDisminucionPlantar);
TableSchema.TableColumn colvarEritroclanosis = new TableSchema.TableColumn(schema);
colvarEritroclanosis.ColumnName = "eritroclanosis";
colvarEritroclanosis.DataType = DbType.Int32;
colvarEritroclanosis.MaxLength = 0;
colvarEritroclanosis.AutoIncrement = false;
colvarEritroclanosis.IsNullable = false;
colvarEritroclanosis.IsPrimaryKey = false;
colvarEritroclanosis.IsForeignKey = false;
colvarEritroclanosis.IsReadOnly = false;
colvarEritroclanosis.DefaultSetting = @"((0))";
colvarEritroclanosis.ForeignKeyTableName = "";
schema.Columns.Add(colvarEritroclanosis);
TableSchema.TableColumn colvarHiperqueatosisPlantar = new TableSchema.TableColumn(schema);
colvarHiperqueatosisPlantar.ColumnName = "hiperqueatosisPlantar";
colvarHiperqueatosisPlantar.DataType = DbType.Int32;
colvarHiperqueatosisPlantar.MaxLength = 0;
colvarHiperqueatosisPlantar.AutoIncrement = false;
colvarHiperqueatosisPlantar.IsNullable = false;
colvarHiperqueatosisPlantar.IsPrimaryKey = false;
colvarHiperqueatosisPlantar.IsForeignKey = false;
colvarHiperqueatosisPlantar.IsReadOnly = false;
colvarHiperqueatosisPlantar.DefaultSetting = @"((0))";
colvarHiperqueatosisPlantar.ForeignKeyTableName = "";
schema.Columns.Add(colvarHiperqueatosisPlantar);
TableSchema.TableColumn colvarHiperqueatosisUnias = new TableSchema.TableColumn(schema);
colvarHiperqueatosisUnias.ColumnName = "hiperqueatosisUnias";
colvarHiperqueatosisUnias.DataType = DbType.Int32;
colvarHiperqueatosisUnias.MaxLength = 0;
colvarHiperqueatosisUnias.AutoIncrement = false;
colvarHiperqueatosisUnias.IsNullable = false;
colvarHiperqueatosisUnias.IsPrimaryKey = false;
colvarHiperqueatosisUnias.IsForeignKey = false;
colvarHiperqueatosisUnias.IsReadOnly = false;
colvarHiperqueatosisUnias.DefaultSetting = @"((0))";
colvarHiperqueatosisUnias.ForeignKeyTableName = "";
schema.Columns.Add(colvarHiperqueatosisUnias);
TableSchema.TableColumn colvarMicosisUnias = new TableSchema.TableColumn(schema);
colvarMicosisUnias.ColumnName = "micosisUnias";
colvarMicosisUnias.DataType = DbType.Int32;
colvarMicosisUnias.MaxLength = 0;
colvarMicosisUnias.AutoIncrement = false;
colvarMicosisUnias.IsNullable = false;
colvarMicosisUnias.IsPrimaryKey = false;
colvarMicosisUnias.IsForeignKey = false;
colvarMicosisUnias.IsReadOnly = false;
colvarMicosisUnias.DefaultSetting = @"";
colvarMicosisUnias.ForeignKeyTableName = "";
schema.Columns.Add(colvarMicosisUnias);
TableSchema.TableColumn colvarPresenciaLesiones = new TableSchema.TableColumn(schema);
colvarPresenciaLesiones.ColumnName = "presenciaLesiones";
colvarPresenciaLesiones.DataType = DbType.AnsiString;
colvarPresenciaLesiones.MaxLength = 200;
colvarPresenciaLesiones.AutoIncrement = false;
colvarPresenciaLesiones.IsNullable = false;
colvarPresenciaLesiones.IsPrimaryKey = false;
colvarPresenciaLesiones.IsForeignKey = false;
colvarPresenciaLesiones.IsReadOnly = false;
colvarPresenciaLesiones.DefaultSetting = @"('')";
colvarPresenciaLesiones.ForeignKeyTableName = "";
schema.Columns.Add(colvarPresenciaLesiones);
TableSchema.TableColumn colvarPuntajeNegativo = new TableSchema.TableColumn(schema);
colvarPuntajeNegativo.ColumnName = "puntajeNegativo";
colvarPuntajeNegativo.DataType = DbType.Int32;
colvarPuntajeNegativo.MaxLength = 0;
colvarPuntajeNegativo.AutoIncrement = false;
colvarPuntajeNegativo.IsNullable = true;
colvarPuntajeNegativo.IsPrimaryKey = false;
colvarPuntajeNegativo.IsForeignKey = false;
colvarPuntajeNegativo.IsReadOnly = false;
colvarPuntajeNegativo.DefaultSetting = @"((0))";
colvarPuntajeNegativo.ForeignKeyTableName = "";
schema.Columns.Add(colvarPuntajeNegativo);
TableSchema.TableColumn colvarCreatedOn = new TableSchema.TableColumn(schema);
colvarCreatedOn.ColumnName = "CreatedOn";
colvarCreatedOn.DataType = DbType.DateTime;
colvarCreatedOn.MaxLength = 0;
colvarCreatedOn.AutoIncrement = false;
colvarCreatedOn.IsNullable = true;
colvarCreatedOn.IsPrimaryKey = false;
colvarCreatedOn.IsForeignKey = false;
colvarCreatedOn.IsReadOnly = false;
colvarCreatedOn.DefaultSetting = @"";
colvarCreatedOn.ForeignKeyTableName = "";
schema.Columns.Add(colvarCreatedOn);
TableSchema.TableColumn colvarCreatedBy = new TableSchema.TableColumn(schema);
colvarCreatedBy.ColumnName = "CreatedBy";
colvarCreatedBy.DataType = DbType.AnsiString;
colvarCreatedBy.MaxLength = 50;
colvarCreatedBy.AutoIncrement = false;
colvarCreatedBy.IsNullable = true;
colvarCreatedBy.IsPrimaryKey = false;
colvarCreatedBy.IsForeignKey = false;
colvarCreatedBy.IsReadOnly = false;
colvarCreatedBy.DefaultSetting = @"";
colvarCreatedBy.ForeignKeyTableName = "";
schema.Columns.Add(colvarCreatedBy);
TableSchema.TableColumn colvarModifiedOn = new TableSchema.TableColumn(schema);
colvarModifiedOn.ColumnName = "ModifiedOn";
colvarModifiedOn.DataType = DbType.DateTime;
colvarModifiedOn.MaxLength = 0;
colvarModifiedOn.AutoIncrement = false;
colvarModifiedOn.IsNullable = true;
colvarModifiedOn.IsPrimaryKey = false;
colvarModifiedOn.IsForeignKey = false;
colvarModifiedOn.IsReadOnly = false;
colvarModifiedOn.DefaultSetting = @"";
colvarModifiedOn.ForeignKeyTableName = "";
schema.Columns.Add(colvarModifiedOn);
TableSchema.TableColumn colvarModifiedBy = new TableSchema.TableColumn(schema);
colvarModifiedBy.ColumnName = "ModifiedBy";
colvarModifiedBy.DataType = DbType.AnsiString;
colvarModifiedBy.MaxLength = 50;
colvarModifiedBy.AutoIncrement = false;
colvarModifiedBy.IsNullable = true;
colvarModifiedBy.IsPrimaryKey = false;
colvarModifiedBy.IsForeignKey = false;
colvarModifiedBy.IsReadOnly = false;
colvarModifiedBy.DefaultSetting = @"";
colvarModifiedBy.ForeignKeyTableName = "";
schema.Columns.Add(colvarModifiedBy);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("Rem_ExamenPie",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdExamenPies")]
[Bindable(true)]
public int IdExamenPies
{
get { return GetColumnValue<int>(Columns.IdExamenPies); }
set { SetColumnValue(Columns.IdExamenPies, value); }
}
[XmlAttribute("IdEfector")]
[Bindable(true)]
public int IdEfector
{
get { return GetColumnValue<int>(Columns.IdEfector); }
set { SetColumnValue(Columns.IdEfector, value); }
}
[XmlAttribute("IdClasificacion")]
[Bindable(true)]
public int IdClasificacion
{
get { return GetColumnValue<int>(Columns.IdClasificacion); }
set { SetColumnValue(Columns.IdClasificacion, value); }
}
[XmlAttribute("IdPaciente")]
[Bindable(true)]
public int IdPaciente
{
get { return GetColumnValue<int>(Columns.IdPaciente); }
set { SetColumnValue(Columns.IdPaciente, value); }
}
[XmlAttribute("Fecha")]
[Bindable(true)]
public DateTime Fecha
{
get { return GetColumnValue<DateTime>(Columns.Fecha); }
set { SetColumnValue(Columns.Fecha, value); }
}
[XmlAttribute("Observacion")]
[Bindable(true)]
public string Observacion
{
get { return GetColumnValue<string>(Columns.Observacion); }
set { SetColumnValue(Columns.Observacion, value); }
}
[XmlAttribute("SensibTermica")]
[Bindable(true)]
public int SensibTermica
{
get { return GetColumnValue<int>(Columns.SensibTermica); }
set { SetColumnValue(Columns.SensibTermica, value); }
}
[XmlAttribute("SensibAlgesica")]
[Bindable(true)]
public int SensibAlgesica
{
get { return GetColumnValue<int>(Columns.SensibAlgesica); }
set { SetColumnValue(Columns.SensibAlgesica, value); }
}
[XmlAttribute("ReflejoPatelar")]
[Bindable(true)]
public int ReflejoPatelar
{
get { return GetColumnValue<int>(Columns.ReflejoPatelar); }
set { SetColumnValue(Columns.ReflejoPatelar, value); }
}
[XmlAttribute("ReflejoAquileano")]
[Bindable(true)]
public int ReflejoAquileano
{
get { return GetColumnValue<int>(Columns.ReflejoAquileano); }
set { SetColumnValue(Columns.ReflejoAquileano, value); }
}
[XmlAttribute("SignoAbanico")]
[Bindable(true)]
public int SignoAbanico
{
get { return GetColumnValue<int>(Columns.SignoAbanico); }
set { SetColumnValue(Columns.SignoAbanico, value); }
}
[XmlAttribute("SensibDiapason")]
[Bindable(true)]
public int SensibDiapason
{
get { return GetColumnValue<int>(Columns.SensibDiapason); }
set { SetColumnValue(Columns.SensibDiapason, value); }
}
[XmlAttribute("FuerzaMuscular")]
[Bindable(true)]
public int FuerzaMuscular
{
get { return GetColumnValue<int>(Columns.FuerzaMuscular); }
set { SetColumnValue(Columns.FuerzaMuscular, value); }
}
[XmlAttribute("AlteracionesApoyo")]
[Bindable(true)]
public int AlteracionesApoyo
{
get { return GetColumnValue<int>(Columns.AlteracionesApoyo); }
set { SetColumnValue(Columns.AlteracionesApoyo, value); }
}
[XmlAttribute("DisminucionMovilidad")]
[Bindable(true)]
public int DisminucionMovilidad
{
get { return GetColumnValue<int>(Columns.DisminucionMovilidad); }
set { SetColumnValue(Columns.DisminucionMovilidad, value); }
}
[XmlAttribute("DedosMartillo")]
[Bindable(true)]
public int DedosMartillo
{
get { return GetColumnValue<int>(Columns.DedosMartillo); }
set { SetColumnValue(Columns.DedosMartillo, value); }
}
[XmlAttribute("Clinodactilia")]
[Bindable(true)]
public int Clinodactilia
{
get { return GetColumnValue<int>(Columns.Clinodactilia); }
set { SetColumnValue(Columns.Clinodactilia, value); }
}
[XmlAttribute("HalluxValgus")]
[Bindable(true)]
public int HalluxValgus
{
get { return GetColumnValue<int>(Columns.HalluxValgus); }
set { SetColumnValue(Columns.HalluxValgus, value); }
}
[XmlAttribute("AusenciaVello")]
[Bindable(true)]
public int AusenciaVello
{
get { return GetColumnValue<int>(Columns.AusenciaVello); }
set { SetColumnValue(Columns.AusenciaVello, value); }
}
[XmlAttribute("DisminucionPlantar")]
[Bindable(true)]
public int DisminucionPlantar
{
get { return GetColumnValue<int>(Columns.DisminucionPlantar); }
set { SetColumnValue(Columns.DisminucionPlantar, value); }
}
[XmlAttribute("Eritroclanosis")]
[Bindable(true)]
public int Eritroclanosis
{
get { return GetColumnValue<int>(Columns.Eritroclanosis); }
set { SetColumnValue(Columns.Eritroclanosis, value); }
}
[XmlAttribute("HiperqueatosisPlantar")]
[Bindable(true)]
public int HiperqueatosisPlantar
{
get { return GetColumnValue<int>(Columns.HiperqueatosisPlantar); }
set { SetColumnValue(Columns.HiperqueatosisPlantar, value); }
}
[XmlAttribute("HiperqueatosisUnias")]
[Bindable(true)]
public int HiperqueatosisUnias
{
get { return GetColumnValue<int>(Columns.HiperqueatosisUnias); }
set { SetColumnValue(Columns.HiperqueatosisUnias, value); }
}
[XmlAttribute("MicosisUnias")]
[Bindable(true)]
public int MicosisUnias
{
get { return GetColumnValue<int>(Columns.MicosisUnias); }
set { SetColumnValue(Columns.MicosisUnias, value); }
}
[XmlAttribute("PresenciaLesiones")]
[Bindable(true)]
public string PresenciaLesiones
{
get { return GetColumnValue<string>(Columns.PresenciaLesiones); }
set { SetColumnValue(Columns.PresenciaLesiones, value); }
}
[XmlAttribute("PuntajeNegativo")]
[Bindable(true)]
public int? PuntajeNegativo
{
get { return GetColumnValue<int?>(Columns.PuntajeNegativo); }
set { SetColumnValue(Columns.PuntajeNegativo, value); }
}
[XmlAttribute("CreatedOn")]
[Bindable(true)]
public DateTime? CreatedOn
{
get { return GetColumnValue<DateTime?>(Columns.CreatedOn); }
set { SetColumnValue(Columns.CreatedOn, value); }
}
[XmlAttribute("CreatedBy")]
[Bindable(true)]
public string CreatedBy
{
get { return GetColumnValue<string>(Columns.CreatedBy); }
set { SetColumnValue(Columns.CreatedBy, value); }
}
[XmlAttribute("ModifiedOn")]
[Bindable(true)]
public DateTime? ModifiedOn
{
get { return GetColumnValue<DateTime?>(Columns.ModifiedOn); }
set { SetColumnValue(Columns.ModifiedOn, value); }
}
[XmlAttribute("ModifiedBy")]
[Bindable(true)]
public string ModifiedBy
{
get { return GetColumnValue<string>(Columns.ModifiedBy); }
set { SetColumnValue(Columns.ModifiedBy, value); }
}
#endregion
#region PrimaryKey Methods
protected override void SetPrimaryKey(object oValue)
{
base.SetPrimaryKey(oValue);
SetPKValues();
}
private DalSic.RemTablaExamanCollection colRemTablaExamen;
public DalSic.RemTablaExamanCollection RemTablaExamen
{
get
{
if(colRemTablaExamen == null)
{
colRemTablaExamen = new DalSic.RemTablaExamanCollection().Where(RemTablaExaman.Columns.IdExamenPies, IdExamenPies).Load();
colRemTablaExamen.ListChanged += new ListChangedEventHandler(colRemTablaExamen_ListChanged);
}
return colRemTablaExamen;
}
set
{
colRemTablaExamen = value;
colRemTablaExamen.ListChanged += new ListChangedEventHandler(colRemTablaExamen_ListChanged);
}
}
void colRemTablaExamen_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colRemTablaExamen[e.NewIndex].IdExamenPies = IdExamenPies;
}
}
#endregion
#region ForeignKey Properties
/// <summary>
/// Returns a RemClasificacion ActiveRecord object related to this RemExamenPie
///
/// </summary>
public DalSic.RemClasificacion RemClasificacion
{
get { return DalSic.RemClasificacion.FetchByID(this.IdClasificacion); }
set { SetColumnValue("idClasificacion", value.IdClasificacion); }
}
#endregion
//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(int varIdEfector,int varIdClasificacion,int varIdPaciente,DateTime varFecha,string varObservacion,int varSensibTermica,int varSensibAlgesica,int varReflejoPatelar,int varReflejoAquileano,int varSignoAbanico,int varSensibDiapason,int varFuerzaMuscular,int varAlteracionesApoyo,int varDisminucionMovilidad,int varDedosMartillo,int varClinodactilia,int varHalluxValgus,int varAusenciaVello,int varDisminucionPlantar,int varEritroclanosis,int varHiperqueatosisPlantar,int varHiperqueatosisUnias,int varMicosisUnias,string varPresenciaLesiones,int? varPuntajeNegativo,DateTime? varCreatedOn,string varCreatedBy,DateTime? varModifiedOn,string varModifiedBy)
{
RemExamenPie item = new RemExamenPie();
item.IdEfector = varIdEfector;
item.IdClasificacion = varIdClasificacion;
item.IdPaciente = varIdPaciente;
item.Fecha = varFecha;
item.Observacion = varObservacion;
item.SensibTermica = varSensibTermica;
item.SensibAlgesica = varSensibAlgesica;
item.ReflejoPatelar = varReflejoPatelar;
item.ReflejoAquileano = varReflejoAquileano;
item.SignoAbanico = varSignoAbanico;
item.SensibDiapason = varSensibDiapason;
item.FuerzaMuscular = varFuerzaMuscular;
item.AlteracionesApoyo = varAlteracionesApoyo;
item.DisminucionMovilidad = varDisminucionMovilidad;
item.DedosMartillo = varDedosMartillo;
item.Clinodactilia = varClinodactilia;
item.HalluxValgus = varHalluxValgus;
item.AusenciaVello = varAusenciaVello;
item.DisminucionPlantar = varDisminucionPlantar;
item.Eritroclanosis = varEritroclanosis;
item.HiperqueatosisPlantar = varHiperqueatosisPlantar;
item.HiperqueatosisUnias = varHiperqueatosisUnias;
item.MicosisUnias = varMicosisUnias;
item.PresenciaLesiones = varPresenciaLesiones;
item.PuntajeNegativo = varPuntajeNegativo;
item.CreatedOn = varCreatedOn;
item.CreatedBy = varCreatedBy;
item.ModifiedOn = varModifiedOn;
item.ModifiedBy = varModifiedBy;
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 varIdExamenPies,int varIdEfector,int varIdClasificacion,int varIdPaciente,DateTime varFecha,string varObservacion,int varSensibTermica,int varSensibAlgesica,int varReflejoPatelar,int varReflejoAquileano,int varSignoAbanico,int varSensibDiapason,int varFuerzaMuscular,int varAlteracionesApoyo,int varDisminucionMovilidad,int varDedosMartillo,int varClinodactilia,int varHalluxValgus,int varAusenciaVello,int varDisminucionPlantar,int varEritroclanosis,int varHiperqueatosisPlantar,int varHiperqueatosisUnias,int varMicosisUnias,string varPresenciaLesiones,int? varPuntajeNegativo,DateTime? varCreatedOn,string varCreatedBy,DateTime? varModifiedOn,string varModifiedBy)
{
RemExamenPie item = new RemExamenPie();
item.IdExamenPies = varIdExamenPies;
item.IdEfector = varIdEfector;
item.IdClasificacion = varIdClasificacion;
item.IdPaciente = varIdPaciente;
item.Fecha = varFecha;
item.Observacion = varObservacion;
item.SensibTermica = varSensibTermica;
item.SensibAlgesica = varSensibAlgesica;
item.ReflejoPatelar = varReflejoPatelar;
item.ReflejoAquileano = varReflejoAquileano;
item.SignoAbanico = varSignoAbanico;
item.SensibDiapason = varSensibDiapason;
item.FuerzaMuscular = varFuerzaMuscular;
item.AlteracionesApoyo = varAlteracionesApoyo;
item.DisminucionMovilidad = varDisminucionMovilidad;
item.DedosMartillo = varDedosMartillo;
item.Clinodactilia = varClinodactilia;
item.HalluxValgus = varHalluxValgus;
item.AusenciaVello = varAusenciaVello;
item.DisminucionPlantar = varDisminucionPlantar;
item.Eritroclanosis = varEritroclanosis;
item.HiperqueatosisPlantar = varHiperqueatosisPlantar;
item.HiperqueatosisUnias = varHiperqueatosisUnias;
item.MicosisUnias = varMicosisUnias;
item.PresenciaLesiones = varPresenciaLesiones;
item.PuntajeNegativo = varPuntajeNegativo;
item.CreatedOn = varCreatedOn;
item.CreatedBy = varCreatedBy;
item.ModifiedOn = varModifiedOn;
item.ModifiedBy = varModifiedBy;
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 IdExamenPiesColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdEfectorColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn IdClasificacionColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn IdPacienteColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn FechaColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn ObservacionColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn SensibTermicaColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn SensibAlgesicaColumn
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn ReflejoPatelarColumn
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn ReflejoAquileanoColumn
{
get { return Schema.Columns[9]; }
}
public static TableSchema.TableColumn SignoAbanicoColumn
{
get { return Schema.Columns[10]; }
}
public static TableSchema.TableColumn SensibDiapasonColumn
{
get { return Schema.Columns[11]; }
}
public static TableSchema.TableColumn FuerzaMuscularColumn
{
get { return Schema.Columns[12]; }
}
public static TableSchema.TableColumn AlteracionesApoyoColumn
{
get { return Schema.Columns[13]; }
}
public static TableSchema.TableColumn DisminucionMovilidadColumn
{
get { return Schema.Columns[14]; }
}
public static TableSchema.TableColumn DedosMartilloColumn
{
get { return Schema.Columns[15]; }
}
public static TableSchema.TableColumn ClinodactiliaColumn
{
get { return Schema.Columns[16]; }
}
public static TableSchema.TableColumn HalluxValgusColumn
{
get { return Schema.Columns[17]; }
}
public static TableSchema.TableColumn AusenciaVelloColumn
{
get { return Schema.Columns[18]; }
}
public static TableSchema.TableColumn DisminucionPlantarColumn
{
get { return Schema.Columns[19]; }
}
public static TableSchema.TableColumn EritroclanosisColumn
{
get { return Schema.Columns[20]; }
}
public static TableSchema.TableColumn HiperqueatosisPlantarColumn
{
get { return Schema.Columns[21]; }
}
public static TableSchema.TableColumn HiperqueatosisUniasColumn
{
get { return Schema.Columns[22]; }
}
public static TableSchema.TableColumn MicosisUniasColumn
{
get { return Schema.Columns[23]; }
}
public static TableSchema.TableColumn PresenciaLesionesColumn
{
get { return Schema.Columns[24]; }
}
public static TableSchema.TableColumn PuntajeNegativoColumn
{
get { return Schema.Columns[25]; }
}
public static TableSchema.TableColumn CreatedOnColumn
{
get { return Schema.Columns[26]; }
}
public static TableSchema.TableColumn CreatedByColumn
{
get { return Schema.Columns[27]; }
}
public static TableSchema.TableColumn ModifiedOnColumn
{
get { return Schema.Columns[28]; }
}
public static TableSchema.TableColumn ModifiedByColumn
{
get { return Schema.Columns[29]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdExamenPies = @"idExamenPies";
public static string IdEfector = @"idEfector";
public static string IdClasificacion = @"idClasificacion";
public static string IdPaciente = @"idPaciente";
public static string Fecha = @"fecha";
public static string Observacion = @"observacion";
public static string SensibTermica = @"sensibTermica";
public static string SensibAlgesica = @"sensibAlgesica";
public static string ReflejoPatelar = @"reflejoPatelar";
public static string ReflejoAquileano = @"reflejoAquileano";
public static string SignoAbanico = @"signoAbanico";
public static string SensibDiapason = @"sensibDiapason";
public static string FuerzaMuscular = @"fuerzaMuscular";
public static string AlteracionesApoyo = @"alteracionesApoyo";
public static string DisminucionMovilidad = @"disminucionMovilidad";
public static string DedosMartillo = @"dedosMartillo";
public static string Clinodactilia = @"clinodactilia";
public static string HalluxValgus = @"halluxValgus";
public static string AusenciaVello = @"ausenciaVello";
public static string DisminucionPlantar = @"disminucionPlantar";
public static string Eritroclanosis = @"eritroclanosis";
public static string HiperqueatosisPlantar = @"hiperqueatosisPlantar";
public static string HiperqueatosisUnias = @"hiperqueatosisUnias";
public static string MicosisUnias = @"micosisUnias";
public static string PresenciaLesiones = @"presenciaLesiones";
public static string PuntajeNegativo = @"puntajeNegativo";
public static string CreatedOn = @"CreatedOn";
public static string CreatedBy = @"CreatedBy";
public static string ModifiedOn = @"ModifiedOn";
public static string ModifiedBy = @"ModifiedBy";
}
#endregion
#region Update PK Collections
public void SetPKValues()
{
if (colRemTablaExamen != null)
{
foreach (DalSic.RemTablaExaman item in colRemTablaExamen)
{
if (item.IdExamenPies != IdExamenPies)
{
item.IdExamenPies = IdExamenPies;
}
}
}
}
#endregion
#region Deep Save
public void DeepSave()
{
Save();
if (colRemTablaExamen != null)
{
colRemTablaExamen.SaveAll();
}
}
#endregion
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Controls.dll
// Description: The Windows Forms user interface controls like the map, legend, toolbox, ribbon and others.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 11/17/2008 10:20:46 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// Kyle Ellison 01/07/2010 Changed Draw*Feature from private to public to expose label functionality
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Linq;
using System.Windows.Forms;
using DotSpatial.Data;
using DotSpatial.Serialization;
using DotSpatial.Symbology;
using GeoAPI.Geometries;
using NetTopologySuite.Geometries;
namespace DotSpatial.Controls
{
/// <summary>
/// This is a specialized FeatureLayer that specifically handles label drawing.
/// </summary>
public class MapLabelLayer : LabelLayer, IMapLabelLayer
{
#region Fields
private static readonly Caches _caches = new Caches();
/// <summary>
/// The existing labels, accessed for all map label layers, not just this instance
/// </summary>
private static readonly List<RectangleF> ExistingLabels = new List<RectangleF>(); // for collision prevention, tracks existing labels.
private Image _backBuffer; // draw to the back buffer, and swap to the stencil when done.
private Envelope _bufferExtent; // the geographic extent of the current buffer.
private Rectangle _bufferRectangle;
private int _chunkSize;
private bool _isInitialized;
private Image _stencil; // draw features to the stencil
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of GeoLabelLayer
/// </summary>
public MapLabelLayer()
{
Configure();
}
/// <summary>
/// Creates a new label layer based on the specified featureset
/// </summary>
/// <param name="inFeatureSet"></param>
public MapLabelLayer(IFeatureSet inFeatureSet)
: base(inFeatureSet)
{
Configure();
}
/// <summary>
/// Creates a new label layer based on the specified feature layer
/// </summary>
/// <param name="inFeatureLayer">The feature layer to build layers from</param>
public MapLabelLayer(IFeatureLayer inFeatureLayer)
: base(inFeatureLayer)
{
Configure();
}
#endregion
#region Events
/// <summary>
/// Fires an event that indicates to the parent map-frame that it should first
/// redraw the specified clip
/// </summary>
public event EventHandler<ClipArgs> BufferChanged;
#endregion
#region Properties
/// <summary>
/// Gets or sets the back buffer that will be drawn to as part of the initialization process.
/// </summary>
[ShallowCopy, Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Image BackBuffer
{
get { return _backBuffer; }
set { _backBuffer = value; }
}
/// <summary>
/// Gets the current buffer.
/// </summary>
[ShallowCopy, Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Image Buffer
{
get { return _stencil; }
set { _stencil = value; }
}
/// <summary>
/// Gets or sets the geographic region represented by the buffer
/// Calling Initialize will set this automatically.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Envelope BufferEnvelope
{
get { return _bufferExtent; }
set { _bufferExtent = value; }
}
/// <summary>
/// Gets or sets the rectangle in pixels to use as the back buffer.
/// Calling Initialize will set this automatically.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Rectangle BufferRectangle
{
get { return _bufferRectangle; }
set { _bufferRectangle = value; }
}
/// <summary>
/// Gets or sets the maximum number of labels that will be rendered before
/// refreshing the screen.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public int ChunkSize
{
get { return _chunkSize; }
set { _chunkSize = value; }
}
/// <summary>
/// Gets or sets the MapFeatureLayer that this label layer is attached to.
/// </summary>
[ShallowCopy, Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new IMapFeatureLayer FeatureLayer
{
get { return base.FeatureLayer as IMapFeatureLayer; }
set { base.FeatureLayer = value; }
}
/// <summary>
/// Gets or sets whether or not this layer has been initialized.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new bool IsInitialized
{
get { return _isInitialized; }
set { _isInitialized = value; }
}
#endregion
#region Methods
/// <summary>
/// Call StartDrawing before using this.
/// </summary>
/// <param name="rectangles">The rectangular region in pixels to clear.</param>
/// <param name= "color">The color to use when clearing. Specifying transparent
/// will replace content with transparent pixels.</param>
public void Clear(List<Rectangle> rectangles, Color color)
{
if (_backBuffer == null) return;
Graphics g = Graphics.FromImage(_backBuffer);
foreach (Rectangle r in rectangles)
{
if (r.IsEmpty == false)
{
g.Clip = new Region(r);
g.Clear(color);
}
}
g.Dispose();
}
/// <summary>
/// Cleaer all existing labels for all layers
/// </summary>
public static void ClearAllExistingLabels()
{
ExistingLabels.Clear();
}
/// <summary>
/// Checks whether the given rectangle collides with the drawnRectangles.
/// </summary>
/// <param name="rectangle">Rectangle that we want to draw next.</param>
/// <param name="drawnRectangles">Rectangle that were already drawn.</param>
/// <returns>True, if the rectangle collides with a rectancle that was already drawn.</returns>
private static bool Collides(RectangleF rectangle, IEnumerable<RectangleF> drawnRectangles)
{
return drawnRectangles.Any(rectangle.IntersectsWith);
}
/// <summary>
/// Draws the given text if it is on screen. If PreventCollision is set only labels that don't collide with existingLables are drawn.
/// </summary>
/// <param name="txt">Text that should be drawn.</param>
/// <param name="g">Graphics object that does the drawing.</param>
/// <param name="symb">Symbolizer to figure out the look of the label.</param>
/// <param name="f">Feature, the label belongs to.</param>
/// <param name="e"></param>
/// <param name="labelBounds"></param>
/// <param name="existingLabels">List with labels that were already drawn.</param>
/// <param name="angle">Angle in degree the label gets rotated by.</param>
private static void CollisionDraw(string txt, Graphics g, ILabelSymbolizer symb, IFeature f, MapArgs e, RectangleF labelBounds, List<RectangleF> existingLabels, float angle)
{
if (labelBounds.IsEmpty || !e.ImageRectangle.IntersectsWith(labelBounds)) return;
if (symb.PreventCollisions)
{
if (!Collides(labelBounds, existingLabels))
{
DrawLabel(g, txt, labelBounds, symb, f, angle);
existingLabels.Add(labelBounds);
}
}
else
{
DrawLabel(g, txt, labelBounds, symb, f, angle);
}
}
private void Configure()
{
_chunkSize = 10000;
}
/// <summary>
/// Draws the labels for the given features.
/// </summary>
/// <param name="args">The GeoArgs that control how these features should be drawn.</param>
/// <param name="features">The features that should be drawn.</param>
/// <param name="clipRectangles">If an entire chunk is drawn and an update is specified, this clarifies the changed rectangles.</param>
/// <param name="useChunks">Boolean, if true, this will refresh the buffer in chunks.</param>
public virtual void DrawFeatures(MapArgs args, List<IFeature> features, List<Rectangle> clipRectangles, bool useChunks)
{
if (useChunks == false)
{
DrawFeatures(args, features);
return;
}
int count = features.Count;
int numChunks = (int)Math.Ceiling(count / (double)ChunkSize);
for (int chunk = 0; chunk < numChunks; chunk++)
{
int numFeatures = ChunkSize;
if (chunk == numChunks - 1) numFeatures = features.Count - (chunk * ChunkSize);
DrawFeatures(args, features.GetRange(chunk * ChunkSize, numFeatures));
if (numChunks > 0 && chunk < numChunks - 1)
{
OnBufferChanged(clipRectangles);
Application.DoEvents();
}
}
}
/// <summary>
/// Draws the labels for the given features.
/// </summary>
/// <param name="args">The GeoArgs that control how these features should be drawn.</param>
/// <param name="features">The features that should be drawn.</param>
/// <param name="clipRectangles">If an entire chunk is drawn and an update is specified, this clarifies the changed rectangles.</param>
/// <param name="useChunks">Boolean, if true, this will refresh the buffer in chunks.</param>
public virtual void DrawFeatures(MapArgs args, List<int> features, List<Rectangle> clipRectangles, bool useChunks)
{
if (useChunks == false)
{
DrawFeatures(args, features);
return;
}
int count = features.Count;
int numChunks = (int)Math.Ceiling(count / (double)ChunkSize);
for (int chunk = 0; chunk < numChunks; chunk++)
{
int numFeatures = ChunkSize;
if (chunk == numChunks - 1) numFeatures = features.Count - (chunk * ChunkSize);
DrawFeatures(args, features.GetRange(chunk * ChunkSize, numFeatures));
if (numChunks > 0 && chunk < numChunks - 1)
{
OnBufferChanged(clipRectangles);
Application.DoEvents();
}
}
}
/// <summary>
/// Draws the labels for the given features.
/// </summary>
/// <param name="e">MapArgs to get Graphics object from.</param>
/// <param name="features">Indizes of the features whose labels get drawn.</param>
private void DrawFeatures(MapArgs e, IEnumerable<int> features)
{
// Check that exists at least one category with Expression
if (Symbology.Categories.All(_ => string.IsNullOrEmpty(_.Expression))) return;
Graphics g = e.Device ?? Graphics.FromImage(_backBuffer);
Matrix origTransform = g.Transform;
// Only draw features that are currently visible.
if (FastDrawnStates == null)
{
CreateIndexedLabels();
}
FastLabelDrawnState[] drawStates = FastDrawnStates;
if (drawStates == null) return;
//Sets the graphics objects smoothing modes
g.TextRenderingHint = TextRenderingHint.AntiAlias;
g.SmoothingMode = SmoothingMode.AntiAlias;
Action<int, IFeature> drawFeature;
switch (FeatureSet.FeatureType)
{
case FeatureType.Polygon:
drawFeature = (fid, feature) => DrawPolygonFeature(e, g, feature, drawStates[fid].Category, drawStates[fid].Selected, ExistingLabels);
break;
case FeatureType.Line:
drawFeature = (fid, feature) => DrawLineFeature(e, g, feature, drawStates[fid].Category, drawStates[fid].Selected, ExistingLabels);
break;
case FeatureType.Point:
case FeatureType.MultiPoint:
drawFeature = (fid, feature) => DrawPointFeature(e, g, feature, drawStates[fid].Category, drawStates[fid].Selected, ExistingLabels);
break;
default:
return; // Can't draw something else
}
foreach (var category in Symbology.Categories)
{
category.UpdateExpressionColumns(FeatureSet.DataTable.Columns);
var catFeatures = new List<int>();
foreach (int fid in features)
{
if (drawStates[fid] == null || drawStates[fid].Category == null) continue;
if (drawStates[fid].Category == category)
{
catFeatures.Add(fid);
}
}
// Now that we are restricted to a certain category, we can look at priority
if (category.Symbolizer.PriorityField != "FID")
{
Feature.ComparisonField = category.Symbolizer.PriorityField;
catFeatures.Sort();
// When preventing collisions, we want to do high priority first.
// Otherwise, do high priority last.
if (category.Symbolizer.PreventCollisions)
{
if (!category.Symbolizer.PrioritizeLowValues)
{
catFeatures.Reverse();
}
}
else
{
if (category.Symbolizer.PrioritizeLowValues)
{
catFeatures.Reverse();
}
}
}
foreach (var fid in catFeatures)
{
if (!FeatureLayer.DrawnStates[fid].Visible) continue;
var feature = FeatureSet.GetFeature(fid);
drawFeature(fid, feature);
}
}
if (e.Device == null) g.Dispose();
else g.Transform = origTransform;
}
/// <summary>
/// Draws the labels for the given features.
/// </summary>
/// <param name="e">MapArgs to get Graphics object from.</param>
/// <param name="features">Features, whose labels get drawn.</param>
private void DrawFeatures(MapArgs e, IEnumerable<IFeature> features)
{
// Check that exists at least one category with Expression
if (Symbology.Categories.All(_ => string.IsNullOrEmpty(_.Expression))) return;
Graphics g = e.Device ?? Graphics.FromImage(_backBuffer);
Matrix origTransform = g.Transform;
// Only draw features that are currently visible.
if (DrawnStates == null || !DrawnStates.ContainsKey(features.First()))
{
CreateLabels();
}
Dictionary<IFeature, LabelDrawState> drawStates = DrawnStates;
if (drawStates == null) return;
//Sets the graphics objects smoothing modes
g.TextRenderingHint = TextRenderingHint.AntiAlias;
g.SmoothingMode = SmoothingMode.AntiAlias;
Action<IFeature> drawFeature;
switch (features.First().FeatureType)
{
case FeatureType.Polygon:
drawFeature = f => DrawPolygonFeature(e, g, f, drawStates[f].Category, drawStates[f].Selected, ExistingLabels);
break;
case FeatureType.Line:
drawFeature = f => DrawLineFeature(e, g, f, drawStates[f].Category, drawStates[f].Selected, ExistingLabels);
break;
case FeatureType.Point:
case FeatureType.MultiPoint:
drawFeature = f => DrawPointFeature(e, g, f, drawStates[f].Category, drawStates[f].Selected, ExistingLabels);
break;
default:
return; // Can't draw something else
}
foreach (ILabelCategory category in Symbology.Categories)
{
category.UpdateExpressionColumns(FeatureSet.DataTable.Columns);
var cat = category; // prevent access to unmodified closure problems
List<IFeature> catFeatures = new List<IFeature>();
foreach (IFeature f in features)
{
if (drawStates.ContainsKey(f) && drawStates[f].Category == cat)
{
catFeatures.Add(f);
}
}
// Now that we are restricted to a certain category, we can look at
// priority
if (category.Symbolizer.PriorityField != "FID")
{
Feature.ComparisonField = cat.Symbolizer.PriorityField;
catFeatures.Sort();
// When preventing collisions, we want to do high priority first.
// otherwise, do high priority last.
if (cat.Symbolizer.PreventCollisions)
{
if (!cat.Symbolizer.PrioritizeLowValues)
{
catFeatures.Reverse();
}
}
else
{
if (cat.Symbolizer.PrioritizeLowValues)
{
catFeatures.Reverse();
}
}
}
for (int i = 0; i < catFeatures.Count; i++)
{
if (!FeatureLayer.DrawnStates[i].Visible) continue;
drawFeature(catFeatures[i]);
}
}
if (e.Device == null) g.Dispose();
else g.Transform = origTransform;
}
/// <summary>
/// Draws labels in a specified rectangle
/// </summary>
/// <param name="g">The graphics object to draw to</param>
/// <param name="labelText">The label text to draw</param>
/// <param name="labelBounds">The rectangle of the label</param>
/// <param name="symb">the Label Symbolizer to use when drawing the label</param>
/// <param name="feature">Feature to draw</param>
/// <param name="angle">Angle in degree the label gets rotated by.</param>
private static void DrawLabel(Graphics g, string labelText, RectangleF labelBounds, ILabelSymbolizer symb, IFeature feature, float angle)
{
//Sets up the brushes and such for the labeling
Font textFont = _caches.GetFont(symb);
var format = new StringFormat { Alignment = symb.Alignment };
//Text graphics path
var gp = new GraphicsPath();
gp.AddString(labelText, textFont.FontFamily, (int)textFont.Style, textFont.SizeInPoints * 96F / 72F, labelBounds, format);
// Rotate text
RotateAt(g, labelBounds.X, labelBounds.Y, angle);
// Draws the text outline
if (symb.BackColorEnabled && symb.BackColor != Color.Transparent)
{
var backBrush = _caches.GetSolidBrush(symb.BackColor);
if (symb.FontColor == Color.Transparent)
{
using (var backgroundGp = new GraphicsPath())
{
backgroundGp.AddRectangle(labelBounds);
backgroundGp.FillMode = FillMode.Alternate;
backgroundGp.AddPath(gp, true);
g.FillPath(backBrush, backgroundGp);
}
}
else
{
g.FillRectangle(backBrush, labelBounds);
}
}
// Draws the border if its enabled
if (symb.BorderVisible && symb.BorderColor != Color.Transparent)
{
var borderPen = _caches.GetPen(symb.BorderColor);
g.DrawRectangle(borderPen, labelBounds.X, labelBounds.Y, labelBounds.Width, labelBounds.Height);
}
// Draws the drop shadow
if (symb.DropShadowEnabled && symb.DropShadowColor != Color.Transparent)
{
var shadowBrush = _caches.GetSolidBrush(symb.DropShadowColor);
var gpTrans = new Matrix();
gpTrans.Translate(symb.DropShadowPixelOffset.X, symb.DropShadowPixelOffset.Y);
gp.Transform(gpTrans);
g.FillPath(shadowBrush, gp);
gpTrans = new Matrix();
gpTrans.Translate(-symb.DropShadowPixelOffset.X, -symb.DropShadowPixelOffset.Y);
gp.Transform(gpTrans);
gpTrans.Dispose();
}
// Draws the text halo
if (symb.HaloEnabled && symb.HaloColor != Color.Transparent)
{
using (var haloPen = new Pen(symb.HaloColor) { Width = 2, Alignment = PenAlignment.Outset })
g.DrawPath(haloPen, gp);
}
// Draws the text if its not transparent
if (symb.FontColor != Color.Transparent)
{
var foreBrush = _caches.GetSolidBrush(symb.FontColor);
g.FillPath(foreBrush, gp);
}
gp.Dispose();
}
/// <summary>
/// Draws a label on a line with various different methods.
/// </summary>
public static void DrawLineFeature(MapArgs e, Graphics g, IFeature f, ILabelCategory category, bool selected, List<RectangleF> existingLabels)
{
var symb = selected ? category.SelectionSymbolizer : category.Symbolizer;
//Gets the features text and calculate the label size
string txt = category.CalculateExpression(f.DataRow, selected, f.Fid);
if (txt == null) return;
Func<SizeF> labelSize = () => g.MeasureString(txt, _caches.GetFont(symb));
IGeometry geo = f.Geometry;
if (geo.NumGeometries == 1)
{
var angle = GetAngleToRotate(symb, f, f.Geometry);
RectangleF labelBounds = PlaceLineLabel(f.Geometry, labelSize, e, symb, angle);
CollisionDraw(txt, g, symb, f, e, labelBounds, existingLabels, angle);
}
else
{
//Depending on the labeling strategy we do diff things
if (symb.PartsLabelingMethod == PartLabelingMethod.LabelAllParts)
{
for (int n = 0; n < geo.NumGeometries; n++)
{
var angle = GetAngleToRotate(symb, f, geo.GetGeometryN(n));
RectangleF labelBounds = PlaceLineLabel(geo.GetGeometryN(n), labelSize, e, symb, angle);
CollisionDraw(txt, g, symb, f, e, labelBounds, existingLabels, angle);
}
}
else
{
double longestLine = 0;
int longestIndex = 0;
for (int n = 0; n < geo.NumGeometries; n++)
{
ILineString ls = geo.GetGeometryN(n) as ILineString;
double tempLength = 0;
if (ls != null) tempLength = ls.Length;
if (longestLine < tempLength)
{
longestLine = tempLength;
longestIndex = n;
}
}
var angle = GetAngleToRotate(symb, f, geo.GetGeometryN(longestIndex));
RectangleF labelBounds = PlaceLineLabel(geo.GetGeometryN(longestIndex), labelSize, e, symb, angle);
CollisionDraw(txt, g, symb, f, e, labelBounds, existingLabels, angle);
}
}
}
/// <summary>
/// Draws a label on a point with various different methods.
/// </summary>
/// <param name="e"></param>
/// <param name="g"></param>
/// <param name="f"></param>
/// <param name="category"></param>
/// <param name="selected"></param>
/// <param name="existingLabels"></param>
public static void DrawPointFeature(MapArgs e, Graphics g, IFeature f, ILabelCategory category, bool selected, List<RectangleF> existingLabels)
{
var symb = selected ? category.SelectionSymbolizer : category.Symbolizer;
//Gets the features text and calculate the label size
string txt = category.CalculateExpression(f.DataRow, selected, f.Fid);
if (txt == null) return;
var angle = GetAngleToRotate(symb, f);
Func<SizeF> labelSize = () => g.MeasureString(txt, _caches.GetFont(symb));
//Depending on the labeling strategy we do different things
if (symb.PartsLabelingMethod == PartLabelingMethod.LabelAllParts)
{
for (int n = 0; n < f.Geometry.NumGeometries; n++)
{
RectangleF labelBounds = PlacePointLabel(f.Geometry.GetGeometryN(n), e, labelSize, symb, angle);
CollisionDraw(txt, g, symb, f, e, labelBounds, existingLabels, angle);
}
}
else
{
RectangleF labelBounds = PlacePointLabel(f.Geometry, e, labelSize, symb, angle);
CollisionDraw(txt, g, symb, f, e, labelBounds, existingLabels, angle);
}
}
/// <summary>
/// Draws a label on a polygon with various different methods
/// </summary>
public static void DrawPolygonFeature(MapArgs e, Graphics g, IFeature f, ILabelCategory category, bool selected, List<RectangleF> existingLabels)
{
var symb = selected ? category.SelectionSymbolizer : category.Symbolizer;
//Gets the features text and calculate the label size
string txt = category.CalculateExpression(f.DataRow, selected, f.Fid);
if (txt == null) return;
var angle = GetAngleToRotate(symb, f);
Func<SizeF> labelSize = () => g.MeasureString(txt, _caches.GetFont(symb));
IGeometry geo = f.Geometry;
if (geo.NumGeometries == 1)
{
RectangleF labelBounds = PlacePolygonLabel(f.Geometry, e, labelSize, symb, angle);
CollisionDraw(txt, g, symb, f, e, labelBounds, existingLabels, angle);
}
else
{
if (symb.PartsLabelingMethod == PartLabelingMethod.LabelAllParts)
{
for (int n = 0; n < geo.NumGeometries; n++)
{
RectangleF labelBounds = PlacePolygonLabel(geo.GetGeometryN(n), e, labelSize, symb, angle);
CollisionDraw(txt, g, symb, f, e, labelBounds, existingLabels, angle);
}
}
else
{
double largestArea = 0;
IPolygon largest = null;
for (int n = 0; n < geo.NumGeometries; n++)
{
IPolygon pg = geo.GetGeometryN(n) as IPolygon;
if (pg == null) continue;
double tempArea = pg.Area;
if (largestArea < tempArea)
{
largestArea = tempArea;
largest = pg;
}
}
RectangleF labelBounds = PlacePolygonLabel(largest, e, labelSize, symb, angle);
CollisionDraw(txt, g, symb, f, e, labelBounds, existingLabels, angle);
}
}
}
/// <summary>
/// This will draw any features that intersect this region. To specify the features
/// directly, use OnDrawFeatures. This will not clear existing buffer content.
/// For that call Initialize instead.
/// </summary>
/// <param name="args">A GeoArgs clarifying the transformation from geographic to image space</param>
/// <param name="regions">The geographic regions to draw</param>
public void DrawRegions(MapArgs args, List<Extent> regions)
{
if (FeatureSet == null) return;
#if DEBUG
var sw = new Stopwatch();
sw.Start();
#endif
if (FeatureSet.IndexMode)
{
// First determine the number of features we are talking about based on region.
List<int> drawIndices = new List<int>();
foreach (Extent region in regions)
{
if (region != null)
{
// We need to consider labels that go off the screen. Figure a region that is larger.
Extent sur = region.Copy();
sur.ExpandBy(region.Width, region.Height);
// Use union to prevent duplicates. No sense in drawing more than we have to.
drawIndices = drawIndices.Union(FeatureSet.SelectIndices(sur)).ToList();
}
}
List<Rectangle> clips = args.ProjToPixel(regions);
DrawFeatures(args, drawIndices, clips, true);
}
else
{
// First determine the number of features we are talking about based on region.
List<IFeature> drawList = new List<IFeature>();
foreach (Extent region in regions)
{
if (region != null)
{
// We need to consider labels that go off the screen. Figure a region that is larger.
Extent r = region.Copy();
r.ExpandBy(region.Width, region.Height);
// Use union to prevent duplicates. No sense in drawing more than we have to.
drawList = drawList.Union(FeatureSet.Select(r)).ToList();
}
}
List<Rectangle> clipRects = args.ProjToPixel(regions);
DrawFeatures(args, drawList, clipRects, true);
}
#if DEBUG
sw.Stop();
Debug.WriteLine("MapLabelLayer {0} DrawRegions: {1} ms", FeatureSet.Name, sw.ElapsedMilliseconds);
#endif
}
/// <summary>
/// Indicates that the drawing process has been finalized and swaps the back buffer
/// to the front buffer.
/// </summary>
public void FinishDrawing()
{
OnFinishDrawing();
if (_stencil != null && _stencil != _backBuffer) _stencil.Dispose();
_stencil = _backBuffer;
FeatureLayer.Invalidate();
}
/// <summary>
/// Rotates the label for the given feature by the angle of the LabelSymbolizer.
/// </summary>
/// <param name="symb">LabelSymbolizer that indicates the angle to use.</param>
/// <param name="feature">Feature whose label gets rotated.</param>
/// <param name="lineString"></param>
/// <returns>Resulting angle in degree.</returns>
private static float GetAngleToRotate(ILabelSymbolizer symb, IFeature feature, IGeometry lineString = null)
{
if (symb.UseAngle)
{
return ToSingle(symb.Angle);
}
else if (symb.UseLabelAngleField)
{
var angleField = symb.LabelAngleField;
if (string.IsNullOrEmpty(angleField)) return 0;
return ToSingle(feature.DataRow[angleField]);
}
else if (symb.UseLineOrientation)
{
LineString ls = lineString as LineString;
if (ls != null)
{
ls = GetSegment(ls, symb);
if (ls == null) return 0;
if (symb.LineOrientation == LineOrientation.Parallel)
return ToSingle(-ls.Angle);
return ToSingle(-ls.Angle - 90);
}
}
return 0;
}
/// <summary>
/// Gets the segment of the LineString that is used to position and rotate the label.
/// </summary>
/// <param name="lineString">LineString to get the segment from.</param>
/// <param name="symb">Symbolizer to get the LineLabelPlacement from.</param>
/// <returns>Null on unnown LineLabelPlacementMethod else the calculated segment. </returns>
private static LineString GetSegment(LineString lineString, ILabelSymbolizer symb)
{
if (lineString.Coordinates.Length <= 2) return lineString;
var coords = lineString.Coordinates;
switch (symb.LineLabelPlacementMethod)
{
case LineLabelPlacementMethod.FirstSegment:
return new LineString(new[] { coords[0], coords[1] });
case LineLabelPlacementMethod.LastSegment:
return new LineString(new[] { coords[coords.Length - 2], coords[coords.Length - 1] });
case LineLabelPlacementMethod.MiddleSegment:
int start = (int)Math.Ceiling(coords.Length / 2D) - 1;
return new LineString(new[] { coords[start], coords[start + 1] });
case LineLabelPlacementMethod.LongestSegment:
double length = 0;
LineString temp = null;
for (int i = 0; i < coords.Length - 1; i++)
{
LineString l = new LineString(new[] { coords[i], coords[i + 1] });
if (l.Length > length)
{
length = l.Length;
temp = l;
}
}
return temp;
}
return null;
}
/// <summary>
/// Fires the OnBufferChanged event
/// </summary>
/// <param name="clipRectangles">The Rectangle in pixels</param>
protected virtual void OnBufferChanged(List<Rectangle> clipRectangles)
{
var h = BufferChanged;
if (h != null)
{
h(this, new ClipArgs(clipRectangles));
}
}
/// <summary>
/// Indiciates that whatever drawing is going to occur has finished and the contents
/// are about to be flipped forward to the front buffer.
/// </summary>
protected virtual void OnFinishDrawing()
{
}
/// <summary>
/// Occurs when a new drawing is started, but after the BackBuffer has been established.
/// </summary>
protected virtual void OnStartDrawing()
{
}
/// <summary>
/// Creates the RectangleF for the label.
/// </summary>
/// <param name="c">Coordinate, where the label should be placed.</param>
/// <param name="e">MapArgs for calculating the position of the label on the output medium.</param>
/// <param name="labelSize">Function that calculates the labelSize.</param>
/// <param name="symb">ILabelSymbolizer to calculate the orientation based adjustment.</param>
/// <param name="angle">Angle in degree used to rotate the label.</param>
/// <returns>Empty Rectangle if Coordinate is outside of the drawn extent, otherwise Rectangle needed to draw the label.</returns>
private static RectangleF PlaceLabel(Coordinate c, MapArgs e, Func<SizeF> labelSize, ILabelSymbolizer symb, double angle)
{
if (!e.GeographicExtents.Intersects(c)) return RectangleF.Empty;
var lz = labelSize();
PointF adjustment = Position(symb, lz);
RotatePoint(ref adjustment, angle); //rotates the adjustment according to the given angle
float x = Convert.ToSingle((c.X - e.MinX) * e.Dx) + e.ImageRectangle.X + adjustment.X;
float y = Convert.ToSingle((e.MaxY - c.Y) * e.Dy) + e.ImageRectangle.Y + adjustment.Y;
return new RectangleF(x, y, lz.Width, lz.Height);
}
/// <summary>
/// Places the label according to the selected LabelPlacementMethode.
/// </summary>
/// <param name="lineString">LineString, whose label gets drawn.</param>
/// <param name="labelSize">Function that calculates the size of the label.</param>
/// <param name="e"></param>
/// <param name="symb">Symbolizer to figure out the look of the label.</param>
/// <param name="angle">Angle in degree the label gets rotated by.</param>
/// <returns>The RectangleF that is needed to draw the label.</returns>
private static RectangleF PlaceLineLabel(IGeometry lineString, Func<SizeF> labelSize, MapArgs e, ILabelSymbolizer symb, float angle)
{
LineString ls = lineString as LineString;
if (ls == null) return Rectangle.Empty;
ls = GetSegment(ls, symb);
if (ls == null) return Rectangle.Empty;
return PlaceLabel(ls.Centroid.Coordinate, e, labelSize, symb, angle);
}
private static RectangleF PlacePointLabel(IGeometry f, MapArgs e, Func<SizeF> labelSize, ILabelSymbolizer symb, float angle)
{
Coordinate c = f.GetGeometryN(1).Coordinates[0];
return PlaceLabel(c, e, labelSize, symb, angle);
}
/// <summary>
/// Calculates the position of the polygon label.
/// </summary>
/// <param name="geom"></param>
/// <param name="e"></param>
/// <param name="labelSize"></param>
/// <param name="symb"></param>
/// <param name="angle"></param>
/// <returns></returns>
private static RectangleF PlacePolygonLabel(IGeometry geom, MapArgs e, Func<SizeF> labelSize, ILabelSymbolizer symb, float angle)
{
IPolygon pg = geom as IPolygon;
if (pg == null) return RectangleF.Empty;
Coordinate c;
switch (symb.LabelPlacementMethod)
{
case LabelPlacementMethod.Centroid:
c = pg.Centroid.Coordinates[0];
break;
case LabelPlacementMethod.InteriorPoint:
c = pg.InteriorPoint.Coordinate;
break;
default:
c = geom.EnvelopeInternal.Centre;
break;
}
return PlaceLabel(c, e, labelSize, symb, angle);
}
/// <summary>
/// Calculates the adjustment of the the label's position based on the symbolizers orientation.
/// </summary>
/// <param name="symb">ILabelSymbolizer whose orientation should be considered.</param>
/// <param name="size">Size of the label.</param>
/// <returns>New label-position based on label-size and symbolizer-orientation.</returns>
private static PointF Position(ILabelSymbolizer symb, SizeF size)
{
ContentAlignment orientation = symb.Orientation;
float x = symb.OffsetX;
float y = -symb.OffsetY;
switch (orientation)
{
case ContentAlignment.TopLeft:
return new PointF(-size.Width + x, -size.Height + y);
case ContentAlignment.TopCenter:
return new PointF(-size.Width / 2 + x, -size.Height + y);
case ContentAlignment.TopRight:
return new PointF(0 + x, -size.Height + y);
case ContentAlignment.MiddleLeft:
return new PointF(-size.Width + x, -size.Height / 2 + y);
case ContentAlignment.MiddleCenter:
return new PointF(-size.Width / 2 + x, -size.Height / 2 + y);
case ContentAlignment.MiddleRight:
return new PointF(0 + x, -size.Height / 2 + y);
case ContentAlignment.BottomLeft:
return new PointF(-size.Width + x, 0 + y);
case ContentAlignment.BottomCenter:
return new PointF(-size.Width / 2 + x, 0 + y);
case ContentAlignment.BottomRight:
return new PointF(0 + x, 0 + y);
}
return new PointF(0, 0);
}
private static void RotateAt(Graphics gr, float cx, float cy, float angle)
{
gr.ResetTransform();
gr.TranslateTransform(-cx, -cy, MatrixOrder.Append);
gr.RotateTransform(angle, MatrixOrder.Append);
gr.TranslateTransform(cx, cy, MatrixOrder.Append);
}
/// <summary>
/// Rotates the given point by angle around (0,0).
/// </summary>
/// <param name="point">Point that gets rotated.</param>
/// <param name="angle">Angle in degree.</param>
private static void RotatePoint(ref PointF point, double angle)
{
double rad = angle * Math.PI / 180;
double x = (Math.Cos(rad) * (point.X) - Math.Sin(rad) * (point.Y));
double y = (Math.Sin(rad) * (point.X) + Math.Cos(rad) * (point.Y));
point.X = (float)x;
point.Y = (float)y;
}
/// <summary>
/// Copies any current content to the back buffer so that drawing should occur on the
/// back buffer (instead of the fore-buffer). Calling draw methods without
/// calling this may cause exceptions.
/// </summary>
/// <param name="preserve">Boolean, true if the front buffer content should be copied to the back buffer
/// where drawing will be taking place.</param>
public void StartDrawing(bool preserve)
{
Bitmap backBuffer = new Bitmap(BufferRectangle.Width, BufferRectangle.Height);
if (Buffer != null && preserve && Buffer.Width == backBuffer.Width && Buffer.Height == backBuffer.Height)
{
Graphics g = Graphics.FromImage(backBuffer);
g.DrawImageUnscaled(Buffer, 0, 0);
}
if (BackBuffer != null && BackBuffer != Buffer) BackBuffer.Dispose();
BackBuffer = backBuffer;
OnStartDrawing();
}
/// <summary>
/// Converts the given value to single.
/// </summary>
/// <param name="value">Value that gets converted to single.</param>
/// <returns>0 on error else the resulting value.</returns>
private static float ToSingle(object value)
{
try
{
return Convert.ToSingle(value);
}
catch (Exception)
{
return 0;
}
}
#endregion
#region Classes
private class Caches
{
#region Fields
private readonly Dictionary<Color, Pen> _pens = new Dictionary<Color, Pen>();
private readonly Dictionary<Color, Brush> _solidBrushes = new Dictionary<Color, Brush>();
private readonly Dictionary<string, Font> _symbFonts = new Dictionary<string, Font>();
#endregion
#region Methods
public Font GetFont(ILabelSymbolizer symb)
{
var fontDesc = string.Format("{0};{1};{2}", symb.FontFamily, symb.FontSize, symb.FontStyle);
return _symbFonts.GetOrAdd(fontDesc, _ => symb.GetFont());
}
public Pen GetPen(Color color)
{
return _pens.GetOrAdd(color, _ => new Pen(color));
}
public Brush GetSolidBrush(Color color)
{
return _solidBrushes.GetOrAdd(color, _ => new SolidBrush(color));
}
#endregion
}
#endregion
}
internal static class DictionaryExtensions
{
#region Methods
public static TValue GetOrAdd<TKey, TValue>(this Dictionary<TKey, TValue> dic, TKey key, Func<TKey, TValue> valueFactory)
{
TValue value;
if (!dic.TryGetValue(key, out value))
{
value = valueFactory(key);
dic.Add(key, value);
}
return value;
}
#endregion
}
}
| |
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;
// <auto-generated />
namespace NorthwindRepository
{
/// <summary>
/// Strongly-typed collection for the EmployeeTerritory class.
/// </summary>
[Serializable]
public partial class EmployeeTerritoryCollection : RepositoryList<EmployeeTerritory, EmployeeTerritoryCollection>
{
public EmployeeTerritoryCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>EmployeeTerritoryCollection</returns>
public EmployeeTerritoryCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
EmployeeTerritory 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 EmployeeTerritories table.
/// </summary>
[Serializable]
public partial class EmployeeTerritory : RepositoryRecord<EmployeeTerritory>, IRecordBase
{
#region .ctors and Default Settings
public EmployeeTerritory()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public EmployeeTerritory(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
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("EmployeeTerritories", TableType.Table, DataService.GetInstance("NorthwindRepository"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarEmployeeID = new TableSchema.TableColumn(schema);
colvarEmployeeID.ColumnName = "EmployeeID";
colvarEmployeeID.DataType = DbType.Int32;
colvarEmployeeID.MaxLength = 0;
colvarEmployeeID.AutoIncrement = false;
colvarEmployeeID.IsNullable = false;
colvarEmployeeID.IsPrimaryKey = true;
colvarEmployeeID.IsForeignKey = true;
colvarEmployeeID.IsReadOnly = false;
colvarEmployeeID.DefaultSetting = @"";
colvarEmployeeID.ForeignKeyTableName = "Employees";
schema.Columns.Add(colvarEmployeeID);
TableSchema.TableColumn colvarTerritoryID = new TableSchema.TableColumn(schema);
colvarTerritoryID.ColumnName = "TerritoryID";
colvarTerritoryID.DataType = DbType.String;
colvarTerritoryID.MaxLength = 20;
colvarTerritoryID.AutoIncrement = false;
colvarTerritoryID.IsNullable = false;
colvarTerritoryID.IsPrimaryKey = true;
colvarTerritoryID.IsForeignKey = true;
colvarTerritoryID.IsReadOnly = false;
colvarTerritoryID.DefaultSetting = @"";
colvarTerritoryID.ForeignKeyTableName = "Territories";
schema.Columns.Add(colvarTerritoryID);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["NorthwindRepository"].AddSchema("EmployeeTerritories",schema);
}
}
#endregion
#region Props
[XmlAttribute("EmployeeID")]
[Bindable(true)]
public int EmployeeID
{
get { return GetColumnValue<int>(Columns.EmployeeID); }
set { SetColumnValue(Columns.EmployeeID, value); }
}
[XmlAttribute("TerritoryID")]
[Bindable(true)]
public string TerritoryID
{
get { return GetColumnValue<string>(Columns.TerritoryID); }
set { SetColumnValue(Columns.TerritoryID, value); }
}
#endregion
//no foreign key tables defined (2)
//no ManyToMany tables defined (0)
#region Typed Columns
public static TableSchema.TableColumn EmployeeIDColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn TerritoryIDColumn
{
get { return Schema.Columns[1]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string EmployeeID = @"EmployeeID";
public static string TerritoryID = @"TerritoryID";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using Xunit;
namespace System.Reflection.Tests
{
public static partial class MetadataLoadContextTests
{
[Fact]
public static void NoResolver()
{
using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver()))
{
Assembly derived = lc.LoadFromByteArray(TestData.s_DerivedClassWithVariationsOnFooImage);
Type t = derived.GetType("Derived1", throwOnError: true);
Assert.Throws<FileNotFoundException>(() => t.BaseType);
}
}
[Fact]
public static void ResolverMissingCore()
{
var resolver = new ResolverReturnsNull();
using (MetadataLoadContext lc = new MetadataLoadContext(resolver, "EmptyCore"))
{
Assert.Same(lc, resolver.Context);
Assert.Equal(1, resolver.CallCount);
Assembly derived = lc.LoadFromByteArray(TestData.s_DerivedClassWithVariationsOnFooImage);
Type t = derived.GetType("Derived1", throwOnError: true);
Assert.Throws<FileNotFoundException>(() => t.BaseType);
Assert.Same(lc, resolver.Context);
Assert.Equal("Foo", resolver.AssemblyName.Name);
Assert.Equal(2, resolver.CallCount);
}
}
[Fact]
public static void ResolverReturnsSomething()
{
var resolver = new ResolverReturnsSomething();
using (MetadataLoadContext lc = new MetadataLoadContext(resolver))
{
Assert.Same(lc, resolver.Context);
Assert.Equal(1, resolver.CallCount);
Assembly derived = lc.LoadFromByteArray(TestData.s_DerivedClassWithVariationsOnFooImage);
Type t = derived.GetType("Derived1", throwOnError: true);
Type bt = t.BaseType;
Assert.Same(lc, resolver.Context);
Assert.Equal("Foo", resolver.AssemblyName.Name);
Assert.Equal(2, resolver.CallCount);
Assembly a = bt.Assembly;
Assert.Equal(a, resolver.Assembly);
}
}
[Fact]
public static void ResolverThrows()
{
var resolver = new ResolverThrows();
using (MetadataLoadContext lc = new MetadataLoadContext(resolver, "EmptyCore"))
{
Assert.Null(resolver.Context);
Assert.Equal(0, resolver.CallCount);
Assembly derived = lc.LoadFromByteArray(TestData.s_DerivedClassWithVariationsOnFooImage);
Type t = derived.GetType("Derived1", throwOnError: true);
TargetParameterCountException e = Assert.Throws<TargetParameterCountException>(() => t.BaseType);
Assert.Same(lc, resolver.Context);
Assert.Equal(1, resolver.CallCount);
Assert.Equal("Hi!", e.Message);
}
}
[Fact]
public static void ResolverNoUnnecessaryCalls()
{
int resolveHandlerCallCount = 0;
Assembly resolveEventHandlerResult = null;
var resolver = new FuncMetadataAssemblyResolver(
delegate (MetadataLoadContext context, AssemblyName name)
{
if (name.Name == "Foo")
{
resolveHandlerCallCount++;
resolveEventHandlerResult = context.LoadFromByteArray(TestData.s_BaseClassesImage);
return resolveEventHandlerResult;
}
if (name.Name == "mscorlib")
{
return context.LoadFromByteArray(TestData.s_SimpleNameOnlyImage);
}
return null;
});
// In a single-threaded scenario at least, MetadataLoadContexts shouldn't ask the resolver to bind the same name twice.
using (MetadataLoadContext lc = new MetadataLoadContext(resolver))
{
Assembly derived = lc.LoadFromByteArray(TestData.s_DerivedClassWithVariationsOnFooImage);
Type t1 = derived.GetType("Derived1", throwOnError: true);
Type bt1 = t1.BaseType;
Type t2 = derived.GetType("Derived2", throwOnError: true);
Type bt2 = t2.BaseType;
Assert.Equal(1, resolveHandlerCallCount);
Assert.Equal(resolveEventHandlerResult, bt1.Assembly);
Assert.Equal(resolveEventHandlerResult, bt2.Assembly);
}
}
[Fact]
public static void ResolverMultipleCalls()
{
var resolver = new ResolverReturnsSomething();
using (MetadataLoadContext lc = new MetadataLoadContext(resolver))
{
Assembly derived = lc.LoadFromByteArray(TestData.s_DerivedClassWithVariationsOnFooImage);
int expectedCount = 2; // Includes the initial probe for mscorelib
foreach (string typeName in new string[] { "Derived1", "Derived3", "Derived4", "Derived5", "Derived6" })
{
Type t = derived.GetType(typeName, throwOnError: true);
Type bt = t.BaseType;
Assert.Equal(bt.Assembly, resolver.Assembly);
Assert.Equal(expectedCount++, resolver.CallCount);
}
}
}
[Fact]
public static void ResolverFromReferencedAssembliesUsingFullPublicKeyReference()
{
// Ecma-335 allows an assembly reference to specify a full public key rather than the token. Ensure that those references
// still hand out usable AssemblyNames to resolve handlers.
AssemblyName assemblyNameReceivedByHandler = null;
var resolver = new FuncMetadataAssemblyResolver(
delegate (MetadataLoadContext context, AssemblyName name)
{
if (name.Name == "RedirectCore")
{
return context.LoadFromByteArray(TestData.s_SimpleNameOnlyImage);
}
assemblyNameReceivedByHandler = name;
return null;
});
using (MetadataLoadContext lc = new MetadataLoadContext(resolver, "RedirectCore"))
{
Assembly a = lc.LoadFromByteArray(TestData.s_AssemblyRefUsingFullPublicKeyImage);
Type t = a.GetType("C", throwOnError: true);
// We expect this next to call to throw since it asks the MetadataLoadContext to resolve [mscorlib]System.Object and our
// resolve handler doesn't return anything for that.
Assert.Throws<FileNotFoundException> (() => t.BaseType);
// But it did get called with a request to resolve "mscorlib" and we got the correct PKT calculated from the PK.
// Note that the original PK is not made available (which follows prior precedent with these apis.) It's not like
// anyone binds with the full PK...
Assert.NotNull(assemblyNameReceivedByHandler);
byte[] expectedPkt = "b77a5c561934e089".HexToByteArray();
byte[] actualPkt = assemblyNameReceivedByHandler.GetPublicKeyToken();
Assert.Equal<byte>(expectedPkt, actualPkt);
}
}
}
public class ResolverReturnsNull : MetadataAssemblyResolver
{
public override Assembly Resolve(System.Reflection.MetadataLoadContext context, AssemblyName assemblyName)
{
Context = context;
AssemblyName = assemblyName;
CallCount++;
if (assemblyName.Name == "EmptyCore")
{
return context.LoadFromByteArray(TestData.s_SimpleNameOnlyImage);
}
return null;
}
public AssemblyName AssemblyName { get; private set; }
public MetadataLoadContext Context { get; private set; }
public int CallCount { get; private set; }
}
public class ResolverReturnsSomething : MetadataAssemblyResolver
{
public override Assembly Resolve(System.Reflection.MetadataLoadContext context, AssemblyName assemblyName)
{
Context = context;
AssemblyName = assemblyName;
CallCount++;
Assembly = context.LoadFromByteArray(TestData.s_BaseClassesImage);
return Assembly;
}
public Assembly Assembly { get; private set; }
public AssemblyName AssemblyName { get; private set; }
public MetadataLoadContext Context { get; private set; }
public int CallCount { get; private set; }
}
public class ResolverThrows : MetadataAssemblyResolver
{
public override Assembly Resolve(System.Reflection.MetadataLoadContext context, AssemblyName assemblyName)
{
if (assemblyName.Name == "EmptyCore")
{
return context.LoadFromByteArray(TestData.s_SimpleNameOnlyImage);
}
Context = context;
AssemblyName = assemblyName;
CallCount++;
throw new TargetParameterCountException("Hi!");
}
public AssemblyName AssemblyName { get; private set; }
public MetadataLoadContext Context { get; private set; }
public int CallCount { get; private set; }
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BlackFox.U2F.Client;
using BlackFox.U2F.Client.impl;
using BlackFox.U2F.Codec;
using BlackFox.U2F.Gnubby;
using BlackFox.U2F.Gnubby.Messages;
using BlackFox.U2F.Server.messages;
using JetBrains.Annotations;
namespace BlackFox.U2F.GnubbyApi
{
public class U2FClient : IU2FClient
{
public delegate Task<bool> CheckAppIdOrOrigin(string origin, ICollection<string> appIds, CancellationToken cancellationToken);
public static readonly CheckAppIdOrOrigin NoAppIdOrOriginCheck = (o, a, ct) => TaskEx.FromResult(true);
[NotNull] readonly ISender sender;
readonly IClientCrypto crypto;
/// <summary>
/// Check that an origin should be allowed to claim all the specified AppIds.
/// </summary>
/// <remarks>
/// Should check if the eTLD+1 is the same (google.com) or if there is a redirection in place with the header :
/// FIDO-AppID-Redirect-Authorized
/// </remarks>
[NotNull] readonly CheckAppIdOrOrigin originChecker;
/// <summary>
/// Check that an origin accept the specified appids using the 'trustedFacets' in a JSON document
/// </summary>
[NotNull] readonly CheckAppIdOrOrigin appIdChecker;
[NotNull] readonly IKeyOperations keyOperations;
public U2FClient([NotNull] ISender sender, [NotNull] IKeyFactory keyFactory)
: this(sender, null, null, new KeyOperations(keyFactory), BouncyCastleClientCrypto.Instance)
{
}
public U2FClient([NotNull] ISender sender, [CanBeNull] CheckAppIdOrOrigin originChecker,
[CanBeNull] CheckAppIdOrOrigin appIdChecker, [NotNull] IKeyFactory keyFactory,
[NotNull] IClientCrypto crypto)
: this(sender, originChecker, appIdChecker, new KeyOperations(keyFactory), crypto)
{
}
public U2FClient([NotNull] ISender sender, [NotNull] IKeyOperations keyOperations)
: this(sender, null, null, keyOperations, BouncyCastleClientCrypto.Instance)
{
}
public U2FClient([NotNull] ISender sender, [CanBeNull] CheckAppIdOrOrigin originChecker,
[CanBeNull] CheckAppIdOrOrigin appIdChecker, [NotNull] IKeyOperations keyOperations,
[NotNull] IClientCrypto crypto)
{
if (sender == null)
{
throw new ArgumentNullException(nameof(sender));
}
if (keyOperations == null)
{
throw new ArgumentNullException(nameof(keyOperations));
}
if (crypto == null)
{
throw new ArgumentNullException(nameof(crypto));
}
this.sender = sender;
this.originChecker = originChecker ?? NoAppIdOrOriginCheck;
this.appIdChecker = appIdChecker ?? NoAppIdOrOriginCheck;
this.keyOperations = keyOperations;
this.crypto = crypto;
}
struct SignInfo
{
public string ClientDataBase64 { get; }
public KeySignRequest KeySignRequest { get; }
public SignRequest SignRequest { get; }
public SignInfo(SignRequest signRequest, string clientDataBase64, KeySignRequest keySignRequest)
{
ClientDataBase64 = clientDataBase64;
KeySignRequest = keySignRequest;
SignRequest = signRequest;
}
}
SignInfo GenerateSignInfo(SignRequest signRequest)
{
var clientDataB64 = ClientDataCodec.EncodeClientData(ClientDataCodec.RequestTypeAuthenticate, signRequest.Challenge,
sender.Origin, sender.ChannelId);
var clientDataSha256 = crypto.ComputeSha256(clientDataB64);
var appIdSha256 = crypto.ComputeSha256(signRequest.AppId);
var keyHandle = WebSafeBase64Converter.FromBase64String(signRequest.KeyHandle);
var authRequest = new KeySignRequest(U2FVersion.V2,
clientDataSha256, appIdSha256, keyHandle);
return new SignInfo(signRequest, clientDataB64, authRequest);
}
public async Task<SignResponse> Sign(ICollection<SignRequest> requests,
CancellationToken cancellationToken = default(CancellationToken))
{
var appIds = requests.Select(r => r.AppId).Distinct().ToList();
await CheckOriginAndAppIdsAsync(appIds, cancellationToken);
var signInfos = requests.Select(GenerateSignInfo).ToDictionary(s => s.KeySignRequest);
var keyRequests = signInfos.Keys.ToList();
var result = await keyOperations.Sign(keyRequests, cancellationToken);
if (!result.IsSuccess)
{
return null;
}
var signInfo = signInfos[result.Request];
return new SignResponse(
WebSafeBase64Converter.ToBase64String(signInfo.ClientDataBase64),
WebSafeBase64Converter.ToBase64String(RawMessageCodec.EncodeKeySignResponse(result.Response)),
signInfo.SignRequest.Challenge,
signInfo.SignRequest.SessionId,
signInfo.SignRequest.AppId);
}
async Task CheckOriginAndAppIdsAsync(List<string> appIds, CancellationToken cancellationToken)
{
var originsOk = await originChecker(sender.Origin, appIds, cancellationToken);
if (!originsOk)
{
throw new Exception("Bad origins for appid");
}
var appIdsOk = await appIdChecker(sender.Origin, appIds, cancellationToken);
if (!appIdsOk)
{
throw new Exception("App IDs not allowed by this origin");
}
}
struct RegisterInfo
{
public string ClientDataBase64 { get; }
public RegisterRequest RegisterRequest { get; }
public KeyRegisterRequest KeyRegisterRequest { get; }
public RegisterInfo(RegisterRequest registerRequest, string clientDataBase64, KeyRegisterRequest keyRegisterRequest)
{
RegisterRequest = registerRequest;
ClientDataBase64 = clientDataBase64;
KeyRegisterRequest = keyRegisterRequest;
}
}
RegisterInfo GenerateRegisterInfo(RegisterRequest registerRequest)
{
var clientDataB64 = ClientDataCodec.EncodeClientData(ClientDataCodec.RequestTypeRegister, registerRequest.Challenge,
sender.Origin, sender.ChannelId);
var clientDataSha256 = crypto.ComputeSha256(clientDataB64);
var appIdSha256 = crypto.ComputeSha256(registerRequest.AppId);
return new RegisterInfo(registerRequest, clientDataB64, new KeyRegisterRequest(appIdSha256, clientDataSha256));
}
public async Task<RegisterResponse> Register(ICollection<RegisterRequest> registrationRequests,
ICollection<SignRequest> signRequests, CancellationToken cancellationToken = default(CancellationToken))
{
var appIds = registrationRequests
.Select(r => r.AppId)
.Concat(signRequests.Select(r => r.AppId))
.Distinct()
.ToList();
await CheckOriginAndAppIdsAsync(appIds, cancellationToken);
var signInfos = signRequests.Select(GenerateSignInfo).ToDictionary(s => s.KeySignRequest);
var keySignRequests = signInfos.Keys.ToList();
var registerInfos = registrationRequests.Select(GenerateRegisterInfo).ToDictionary(s => s.KeyRegisterRequest);
var keyRegisterRequests = registerInfos.Keys.ToList();
var result = await keyOperations.Register(keyRegisterRequests, keySignRequests,
cancellationToken);
if (!result.IsSuccess)
{
return null;
}
var registerInfo = registerInfos[result.Request];
return new RegisterResponse(
WebSafeBase64Converter.ToBase64String(RawMessageCodec.EncodeKeyRegisterResponse(result.Response)),
WebSafeBase64Converter.ToBase64String(registerInfo.ClientDataBase64),
registerInfo.RegisterRequest.SessionId);
}
}
}
| |
// 2c4ad224-afdb-498b-b402-885d12711254
#pragma warning disable 219
using System;
using Neutrino.Unity3D;
namespace Neutrino
{
public class Effect_Magic02 : NeutrinoRenderer
{
public class Model : EffectModel
{
public class Emitter_Sparks : EmitterModel
{
public class ParticleImpl : Particle
{
public float _lifetime;
public _math.vec3 _Position;
public _math.vec3 _Velocity;
public float _Angle;
public float _Size;
public float _Color;
public override _math.vec2 origin() { return _math.vec2_(0.5F,0.5F); }
public override float angle() { return _Angle; }
public override _math.quat rotation() { return _math.quat_(1, 0, 0, 0); }
public float size1_;
public override float size1() { return size1_; }
public override _math.vec2 size2() { return _math.vec2_(0, 0); }
public _math.vec3 color_;
public override _math.vec3 color() { return color_; }
public override float alpha() { return 1; }
public override float gridIndex() { return 0; }
public override AttachedEmitter[] attachedEmitters() { return null; }
}
public class EmitterData
{
public _math.vec3 _Color1 = _math.vec3_(1F,1F,1F);
public _math.vec3 _Color2 = _math.vec3_(1F,1F,1F);
}
public class GeneratorImpl : GeneratorPeriodic.Impl
{
public float burst() { return 100F; }
public float? fixedTime() { return null; }
public float? fixedShots() { return 1F; }
public float startPhase() { return 1F; }
public float rate() { return 5F; }
}
float [][][] _plot =
{
new float[][] { new float[]{ 1F,0F,0F }}
};
public class ConstructorImpl : ConstructorQuads.Impl
{
public ConstructorQuads.RotationType rotationType() { return ConstructorQuads.RotationType.Faced; }
public ConstructorQuads.SizeType sizeType() { return ConstructorQuads.SizeType.Quad; }
public ConstructorQuads.TexMapType texMapType() { return ConstructorQuads.TexMapType.WholeRect; }
public _math.vec2 gridSize() { return _math.vec2_(0, 0); }
public ushort renderStyleIndex() { return 0; }
}
public override void updateEmitter(Emitter emitter)
{
EmitterData emitterData = (EmitterData)emitter.data();
GeneratorPeriodic generator = (GeneratorPeriodic)emitter.generator();
GeneratorImpl generatorImpl = (GeneratorImpl)generator.impl();
}
public override void initParticle(Emitter emitter, Particle particle)
{
ParticleImpl particleImpl = (ParticleImpl)particle;
float dt = 0;
EmitterData emitterData = (EmitterData)emitter.data();
GeneratorPeriodic generator = (GeneratorPeriodic)emitter.generator();
GeneratorImpl generatorImpl = (GeneratorImpl)generator.impl();
particleImpl._lifetime = 0F;
_math.vec3 value_ = _math.vec3_(0F, 0F, 0F);
particleImpl._Position = _math.addv3_(value_, emitter.position());
float rnd_ = 100F + emitter.random()() * (500F - 100F);
_math.vec3 randvec_ = _math.randv3gen_(rnd_, emitter.random());
particleImpl._Velocity = randvec_;
particleImpl._Angle = 0F;
float rnd_a = 10F + emitter.random()() * (20F - 10F);
particleImpl._Size = rnd_a;
float rnd_b = 0F + emitter.random()() * (1F - 0F);
particleImpl._Color = rnd_b;
particle.position_ = particleImpl._Position;
}
public override void initBurstParticle(Emitter emitter, Particle particle)
{
ParticleImpl particleImpl = (ParticleImpl)particle;
float dt = 0;
EmitterData emitterData = (EmitterData)emitter.data();
GeneratorPeriodic generator = (GeneratorPeriodic)emitter.generator();
GeneratorImpl generatorImpl = (GeneratorImpl)generator.impl();
particleImpl._lifetime = 0F;
_math.vec3 value_ = _math.vec3_(0F, 0F, 0F);
particleImpl._Position = _math.addv3_(value_, emitter.position());
float rnd_ = 100F + emitter.random()() * (500F - 100F);
_math.vec3 randvec_ = _math.randv3gen_(rnd_, emitter.random());
particleImpl._Velocity = randvec_;
particleImpl._Angle = 0F;
float rnd_a = 10F + emitter.random()() * (20F - 10F);
particleImpl._Size = rnd_a;
float rnd_b = 0F + emitter.random()() * (1F - 0F);
particleImpl._Color = rnd_b;
particle.position_ = particleImpl._Position;
}
public override void updateParticle(Emitter emitter, Particle particle, float dt)
{
ParticleImpl particleImpl = (ParticleImpl)particle;
EmitterData emitterData = (EmitterData)emitter.data();
GeneratorPeriodic generator = (GeneratorPeriodic)emitter.generator();
GeneratorImpl generatorImpl = (GeneratorImpl)generator.impl();
particleImpl._lifetime += dt;
_math.vec3 noise_a = _math.mulv3scalar_(_math.vec3_(100F,50F,30F), emitter.effect().time());
_math.addv3(out noise_a, noise_a, particleImpl._Position);
_math.vec3 noise_i = _math.mulv3scalar_(noise_a, 1.0F / 500F);
_math.vec3 noise = _math.noisePixelLinear3_(noise_i);
_math.mulv3(out noise, noise, _math.vec3_(0.0078125F,0.0078125F,0.0078125F));
_math.addv3(out noise, noise, _math.vec3_(-1F,-1F,-1F));
_math.mulv3scalar(out noise, noise, 600F);
_math.vec3 fmove_fs = noise;
_math.vec3 fmove_vs = _math.vec3_(0F,0F,0F);
float fmove_dtl = dt;
_math.vec3 fmove_v = particleImpl._Velocity;
_math.vec3 fmove_p = particleImpl._Position;
while (fmove_dtl > 0.0001F) {
float fmove_dtp = fmove_dtl;
_math.vec3 fmove_fsd = fmove_fs;
_math.vec3 fmove_rw = _math.subv3_(fmove_vs, fmove_v);
float fmove_rwl = _math.lengthv3sq_(fmove_rw);
if (fmove_rwl > 0.0001F) {
fmove_rwl = (float)Math.Sqrt(fmove_rwl);
_math.vec3 fmove_rwn = _math.divv3scalar_(fmove_rw, fmove_rwl);
float fmove_df = 0.01F * 1F * fmove_rwl;
if (fmove_df * fmove_dtp > 0.2F)
fmove_dtp = 0.2F / fmove_df;
_math.addv3(out fmove_fsd, fmove_fsd, _math.mulv3scalar_(fmove_rwn, fmove_rwl * fmove_df));
}
_math.addv3(out fmove_v, fmove_v, _math.mulv3scalar_(fmove_fsd, fmove_dtp));
_math.addv3(out fmove_p, fmove_p, _math.mulv3scalar_(fmove_v, fmove_dtp));
fmove_dtl -= fmove_dtp;
}
particleImpl._Position = fmove_p;
particleImpl._Velocity = fmove_v;
particle.position_ = particleImpl._Position;
float value_ = 2F;
if (particleImpl._lifetime > value_)
{
particle.dead_ = true;
}
float expr_ = (particleImpl._lifetime / value_);
float _plot_out;
float _plot_in0=(expr_<0F?0F:(expr_>1F?1F:expr_));
_math.PathRes _plot_srch0 = _math.pathRes(0,(_plot_in0-0F)*1F);
_math.funcLerp(out _plot_out, this._plot[0][_plot_srch0.s],_plot_srch0.i);
float expr_a = (particleImpl._Size * _plot_out);
_math.vec3 expr_b = _math.addv3_(emitterData._Color1, _math.mulv3scalar_(_math.subv3_(emitterData._Color2, emitterData._Color1), particleImpl._Color));
particleImpl.size1_ = expr_a;
particleImpl.color_ = expr_b;
}
public Emitter_Sparks()
{
addProperty("Color1", PropertyType.VEC3,
(object emitterData) => { return ((EmitterData)emitterData)._Color1; },
(object emitterData, object value) => { _math.copyv3(out ((EmitterData)emitterData)._Color1, (_math.vec3)value); });
addProperty("Color2", PropertyType.VEC3,
(object emitterData) => { return ((EmitterData)emitterData)._Color2; },
(object emitterData, object value) => { _math.copyv3(out ((EmitterData)emitterData)._Color2, (_math.vec3)value); });
generatorCreator_ = (Emitter emitter) => { return new GeneratorPeriodic(emitter, new GeneratorImpl()); };
constructorCreator_ = (Emitter emitter) => { return new ConstructorQuads(emitter, new ConstructorImpl()); };
name_ = "Sparks";
maxNumParticles_ = 100;
sorting_ = Emitter.Sorting.OldToYoung;
particleCreator_ = (Effect effect) => { return new ParticleImpl(); };
emitterDataCreator_ = () => { return new EmitterData(); };
}
}
public class Emitter_Splash : EmitterModel
{
public class ParticleImpl : Particle
{
public float _lifetime;
public _math.vec3 _Position;
public float _Angle;
public override _math.vec2 origin() { return _math.vec2_(0.5F,0.5F); }
public override float angle() { return _Angle; }
public override _math.quat rotation() { return _math.quat_(1, 0, 0, 0); }
public float size1_;
public override float size1() { return size1_; }
public override _math.vec2 size2() { return _math.vec2_(0, 0); }
public _math.vec3 color_;
public override _math.vec3 color() { return color_; }
public override float alpha() { return 1; }
public override float gridIndex() { return 0; }
public AttachedEmitter[] attachedEmitters_;
public override AttachedEmitter[] attachedEmitters() { return attachedEmitters_; }
}
public class EmitterData
{
public _math.vec3 _Color = _math.vec3_(1F,1F,0F);
public _math.vec3 _SparksColor1 = _math.vec3_(1F,0F,0F);
public _math.vec3 _SparksColor2 = _math.vec3_(1F,1F,0F);
}
public class GeneratorImpl : GeneratorPeriodic.Impl
{
public float burst() { return 1F; }
public float? fixedTime() { return null; }
public float? fixedShots() { return null; }
public float startPhase() { return 1F; }
public float rate() { return 0.5F; }
}
float [][][] _plot =
{
new float[][] { new float[]{ 0F,1F,1F }, new float[]{ 1F,0.986912F,0.950467F,0.89382F,0.820641F,0.734959F,0.640978F,0.542886F,0.444666F,0.349964F,0.261977F,0.183403F,0.116434F,0.0627696F,0.0236687F,0F,0F }}
};
public class ConstructorImpl : ConstructorQuads.Impl
{
public ConstructorQuads.RotationType rotationType() { return ConstructorQuads.RotationType.Faced; }
public ConstructorQuads.SizeType sizeType() { return ConstructorQuads.SizeType.Quad; }
public ConstructorQuads.TexMapType texMapType() { return ConstructorQuads.TexMapType.WholeRect; }
public _math.vec2 gridSize() { return _math.vec2_(0, 0); }
public ushort renderStyleIndex() { return 1; }
}
public override void updateEmitter(Emitter emitter)
{
EmitterData emitterData = (EmitterData)emitter.data();
GeneratorPeriodic generator = (GeneratorPeriodic)emitter.generator();
GeneratorImpl generatorImpl = (GeneratorImpl)generator.impl();
}
public override void initParticle(Emitter emitter, Particle particle)
{
ParticleImpl particleImpl = (ParticleImpl)particle;
float dt = 0;
EmitterData emitterData = (EmitterData)emitter.data();
GeneratorPeriodic generator = (GeneratorPeriodic)emitter.generator();
GeneratorImpl generatorImpl = (GeneratorImpl)generator.impl();
particleImpl._lifetime = 0F;
_math.vec3 value_ = _math.vec3_(0F, 0F, 0F);
particleImpl._Position = _math.addv3_(value_, emitter.position());
particleImpl._Angle = 0F;
particle.position_ = particleImpl._Position;
particleImpl.attachedEmitters_[0].emitter_.reset(particle.position_, null);
particleImpl.attachedEmitters_[0].emitter_.start();
((Emitter_Sparks.EmitterData)particleImpl.attachedEmitters_[0].emitter_.data())._Color1 = emitterData._SparksColor1;
((Emitter_Sparks.EmitterData)particleImpl.attachedEmitters_[0].emitter_.data())._Color2 = emitterData._SparksColor2;
}
public override void initBurstParticle(Emitter emitter, Particle particle)
{
ParticleImpl particleImpl = (ParticleImpl)particle;
float dt = 0;
EmitterData emitterData = (EmitterData)emitter.data();
GeneratorPeriodic generator = (GeneratorPeriodic)emitter.generator();
GeneratorImpl generatorImpl = (GeneratorImpl)generator.impl();
particleImpl._lifetime = 0F;
_math.vec3 value_ = _math.vec3_(0F, 0F, 0F);
particleImpl._Position = _math.addv3_(value_, emitter.position());
particleImpl._Angle = 0F;
particle.position_ = particleImpl._Position;
particleImpl.attachedEmitters_[0].emitter_.reset(particle.position_, null);
particleImpl.attachedEmitters_[0].emitter_.start();
((Emitter_Sparks.EmitterData)particleImpl.attachedEmitters_[0].emitter_.data())._Color1 = emitterData._SparksColor1;
((Emitter_Sparks.EmitterData)particleImpl.attachedEmitters_[0].emitter_.data())._Color2 = emitterData._SparksColor2;
}
public override void updateParticle(Emitter emitter, Particle particle, float dt)
{
ParticleImpl particleImpl = (ParticleImpl)particle;
EmitterData emitterData = (EmitterData)emitter.data();
GeneratorPeriodic generator = (GeneratorPeriodic)emitter.generator();
GeneratorImpl generatorImpl = (GeneratorImpl)generator.impl();
particleImpl._lifetime += dt;
particle.position_ = particleImpl._Position;
((Emitter_Sparks.EmitterData)particleImpl.attachedEmitters_[0].emitter_.data())._Color1 = emitterData._SparksColor1;
((Emitter_Sparks.EmitterData)particleImpl.attachedEmitters_[0].emitter_.data())._Color2 = emitterData._SparksColor2;
particleImpl.attachedEmitters_[0].emitter_.update(dt, particle.position_, null);
float value_ = 0.3F;
if (particleImpl._lifetime > value_)
{
particle.dead_ = true;
particleImpl.attachedEmitters_[0].emitter_.stop();
}
float value_a = 100F;
float expr_ = (particleImpl._lifetime / value_);
float _plot_out;
float _plot_in0=(expr_<0F?0F:(expr_>1F?1F:expr_));
_math.PathRes _plot_srch0 = _plot_in0<0.0292826?_math.pathRes(0,(_plot_in0-0F)*34.15F):_math.pathRes(1,(_plot_in0-0.0292826F)*15.4525F);
_math.funcLerp(out _plot_out, this._plot[0][_plot_srch0.s],_plot_srch0.i);
float expr_a = (value_a * _plot_out);
particleImpl.size1_ = expr_a;
particleImpl.color_ = emitterData._Color;
}
public Emitter_Splash()
{
addProperty("Color", PropertyType.VEC3,
(object emitterData) => { return ((EmitterData)emitterData)._Color; },
(object emitterData, object value) => { _math.copyv3(out ((EmitterData)emitterData)._Color, (_math.vec3)value); });
addProperty("SparksColor1", PropertyType.VEC3,
(object emitterData) => { return ((EmitterData)emitterData)._SparksColor1; },
(object emitterData, object value) => { _math.copyv3(out ((EmitterData)emitterData)._SparksColor1, (_math.vec3)value); });
addProperty("SparksColor2", PropertyType.VEC3,
(object emitterData) => { return ((EmitterData)emitterData)._SparksColor2; },
(object emitterData, object value) => { _math.copyv3(out ((EmitterData)emitterData)._SparksColor2, (_math.vec3)value); });
generatorCreator_ = (Emitter emitter) => { return new GeneratorPeriodic(emitter, new GeneratorImpl()); };
constructorCreator_ = (Emitter emitter) => { return new ConstructorQuads(emitter, new ConstructorImpl()); };
name_ = "Splash";
maxNumParticles_ = 2;
sorting_ = Emitter.Sorting.OldToYoung;
particleCreator_ = (Effect effect) => {
ParticleImpl particle = new ParticleImpl();
particle.attachedEmitters_ = new AttachedEmitter[]
{
new AttachedEmitter(new Emitter(effect, effect.model().emitterModels()[0]), AttachedEmitter.DrawOrder.After, AttachedEmitter.ActivationMode.OnCreate)
};
return particle;
};
emitterDataCreator_ = () => { return new EmitterData(); };
}
}
public Model()
{
textures_ = new string[] { "glowing_dot.png","flare.png" };
materials_ = new RenderMaterial[] { RenderMaterial.Normal };
renderStyles_ = new RenderStyle[] { new RenderStyle(0,new uint[] {0}),new RenderStyle(0,new uint[] {1}) };
frameTime_ = 0.0333333F;
presimulateTime_ = 0F;
maxNumRenderCalls_ = 202;
maxNumParticles_ = 202;
emitterModels_ = new EmitterModel[]{ new Emitter_Sparks(), new Emitter_Splash() };
activeEmitterModels_ = new uint[] { 1 };
randomGeneratorCreator_ = () => { return _math.rand_; };
}
}
static Model modelInstance_ = null;
public override EffectModel createModel()
{
if (modelInstance_ == null)
modelInstance_ = new Model();
NeutrinoContext.Instance.ensureNoiseIsGeneratedAndGenerateIfNecessary();
return modelInstance_;
}
}
}
#pragma warning restore 219
| |
//
// how to capture still images, video and audio using iOS AVFoundation and the AVCAptureSession
//
// This sample handles all of the low-level AVFoundation and capture graph setup required to capture and save media. This code also exposes the
// capture, configuration and notification capabilities in a more '.Netish' way of programming. The client code will not need to deal with threads, delegate classes
// buffer management, or objective-C data types but instead will create .NET objects and handle standard .NET events. The underlying iOS concepts and classes are detailed in
// the iOS developer online help (TP40010188-CH5-SW2).
//
// https://developer.apple.com/library/mac/#documentation/AudioVideo/Conceptual/AVFoundationPG/Articles/04_MediaCapture.html#//apple_ref/doc/uid/TP40010188-CH5-SW2
//
// Enhancements, suggestions and bug reports can be sent to steve.millar@infinitekdev.com
//
using System;
using System.Collections.Concurrent;
using CoreGraphics;
using System.IO;
using Foundation;
using UIKit;
using AVFoundation;
using CoreVideo;
using CoreMedia;
using CoreFoundation;
using System.Runtime.InteropServices;
namespace MediaCapture
{
public class CaptureManager
{
// capture session
private AVCaptureSession session = null;
private bool isCapturing = false;
private bool captureImages = false;
private bool captureAudio = false;
private bool captureVideo = false;
private string movieRecordingDirectory;
private CameraType cameraType = CameraType.RearFacing;
private Resolution resolution = Resolution.Medium;
// camera input objects
private AVCaptureDevice videoCaptureDevice = null;
private AVCaptureDeviceInput videoInput = null;
// microphone input objects
private AVCaptureDevice audioCaptureDevice = null;
private AVCaptureDeviceInput audioInput = null;
// frame grabber objects
private AVCaptureVideoDataOutput frameGrabberOutput = null;
private VideoFrameSamplerDelegate videoFrameSampler = null;
private DispatchQueue queue = null;
// movie recorder objects
private AVCaptureMovieFileOutput movieFileOutput = null;
private MovieSegmentWriterDelegate movieSegmentWriter = null;
private string currentSegmentFile = null;
private DateTime currentSegmentStartedAt;
private uint nextMovieIndex = 1;
private int movieSegmentDurationInMilliSeconds = 20000;
private bool breakMovieIntoSegments = true;
private CaptureManager(){}
public CaptureManager(
Resolution resolution,
bool captureImages,
bool captureAudio,
bool captureVideo,
CameraType cameraType,
string movieRecordingDirectory,
int movieSegmentDurationInMilliSeconds,
bool breakMovieIntoSegments )
{
this.resolution = resolution;
this.captureImages = captureImages;
this.captureAudio = captureAudio;
this.captureVideo = captureVideo;
this.cameraType = cameraType;
this.movieSegmentDurationInMilliSeconds = movieSegmentDurationInMilliSeconds;
this.breakMovieIntoSegments = breakMovieIntoSegments;
if ( captureAudio || captureVideo )
{
this.movieRecordingDirectory = Path.Combine( movieRecordingDirectory, getDateTimeDirectoryName( DateTime.Now ) );
if ( Directory.Exists( this.movieRecordingDirectory ) == false )
{
Directory.CreateDirectory( this.movieRecordingDirectory );
}
}
}
#region events
public EventHandler<MovieSegmentCapturedEventArgs> MovieSegmentCaptured;
private void onMovieSegmentCaptured( MovieSegmentCapturedEventArgs args )
{
if ( MovieSegmentCaptured != null )
{
MovieSegmentCaptured( this, args );
}
}
public EventHandler<CaptureErrorEventArgs> CaptureError;
private void onCaptureError( CaptureErrorEventArgs args )
{
if ( CaptureError != null )
{
CaptureError( this, args );
}
}
public EventHandler<ImageCaptureEventArgs> ImageCaptured;
private void onImageCaptured( ImageCaptureEventArgs args )
{
if ( ImageCaptured != null )
{
ImageCaptured( this, args );
}
}
#endregion
public int MovieSegmentDurationInMilliSeconds
{
get
{
return movieSegmentDurationInMilliSeconds;
}
}
public bool IsCapturing
{
get
{
return this.isCapturing;
}
set
{
isCapturing = value;
}
}
private bool shouldRecord
{
get
{
return ( ( this.captureAudio || this.captureVideo ) && ( string.IsNullOrEmpty(this.movieRecordingDirectory) == false ) );
}
}
public bool StartCapture( out string message )
{
message = "";
if ( isCapturing == true )
{
message = "already capturing";
return true;
}
isCapturing = true;
if ( setupCaptureSessionInternal( out message ) == false )
{
return false;
}
// start the capture
session.StartRunning();
// start recording (if configured)
if ( shouldRecord )
{
startMovieWriter();
}
return true;
}
public void StopCapture()
{
if ( isCapturing == false )
{
return;
}
isCapturing = false;
// stop recording
if ( shouldRecord )
{
stopMovieWriter();
}
// stop the capture session
session.StopRunning();
unsubscribeDelegateEvents();
}
private void startMovieWriter()
{
if ( movieFileOutput == null )
{
return;
}
startRecordingNextMovieFilename();
}
private void startRecordingNextMovieFilename()
{
// generate file name
currentSegmentFile = System.IO.Path.Combine( this.movieRecordingDirectory, string.Format("video_{0}.mov", nextMovieIndex++) );
NSUrl segmentUrl = NSUrl.FromFilename( currentSegmentFile );
// start recording
movieFileOutput.StartRecordingToOutputFile( segmentUrl, movieSegmentWriter);
}
private void stopMovieWriter()
{
if ( movieFileOutput == null )
{
return;
}
movieFileOutput.StopRecording();
}
private bool setupCaptureSessionInternal( out string errorMessage )
{
errorMessage = "";
// create the capture session
session = new AVCaptureSession();
switch ( resolution )
{
case Resolution.Low:
session.SessionPreset = AVCaptureSession.PresetLow;
break;
case Resolution.High:
session.SessionPreset = AVCaptureSession.PresetHigh;
break;
case Resolution.Medium:
default:
session.SessionPreset = AVCaptureSession.PresetMedium;
break;
}
// conditionally configure the camera input
if ( captureVideo || captureImages)
{
if ( addCameraInput( out errorMessage ) == false )
{
return false;
}
}
// conditionally configure the microphone input
if ( captureAudio )
{
if ( addAudioInput( out errorMessage ) == false )
{
return false;
}
}
// conditionally configure the sample buffer output
if ( captureImages )
{
int minimumSampleIntervalInMilliSeconds = captureVideo ? 1000 : 100;
if ( addImageSamplerOutput( out errorMessage, minimumSampleIntervalInMilliSeconds ) == false )
{
return false;
}
}
// conditionally configure the movie file output
if ( shouldRecord )
{
if ( addMovieFileOutput( out errorMessage ) == false )
{
return false;
}
}
return true;
}
private bool addCameraInput( out string errorMessage )
{
errorMessage = "";
videoCaptureDevice = this.cameraType == CameraType.FrontFacing ? MediaDevices.FrontCamera : MediaDevices.BackCamera;
videoInput = AVCaptureDeviceInput.FromDevice(videoCaptureDevice);
if (videoInput == null)
{
errorMessage = "No video capture device";
return false;
}
session.AddInput (videoInput);
return true;
}
private bool addAudioInput( out string errorMessage )
{
errorMessage = "";
audioCaptureDevice = MediaDevices.Microphone;
audioInput = AVCaptureDeviceInput.FromDevice(audioCaptureDevice);
if (audioInput == null)
{
errorMessage = "No audio capture device";
return false;
}
session.AddInput (audioInput);
return true;
}
private bool addMovieFileOutput( out string errorMessage )
{
errorMessage = "";
// create a movie file output and add it to the capture session
movieFileOutput = new AVCaptureMovieFileOutput();
if ( movieSegmentDurationInMilliSeconds > 0 )
{
movieFileOutput.MaxRecordedDuration = new CMTime( movieSegmentDurationInMilliSeconds, 1000 );
}
// setup the delegate that handles the writing
movieSegmentWriter = new MovieSegmentWriterDelegate();
// subscribe to the delegate events
movieSegmentWriter.MovieSegmentRecordingStarted += new EventHandler<MovieSegmentRecordingStartedEventArgs>( handleMovieSegmentRecordingStarted );
movieSegmentWriter.MovieSegmentRecordingComplete += new EventHandler<MovieSegmentRecordingCompleteEventArgs>( handleMovieSegmentRecordingComplete );
movieSegmentWriter.CaptureError += new EventHandler<CaptureErrorEventArgs>( handleMovieCaptureError );
session.AddOutput (movieFileOutput);
return true;
}
private bool addImageSamplerOutput( out string errorMessage, int minimumSampleIntervalInMilliSeconds )
{
errorMessage = "";
// create a VideoDataOutput and add it to the capture session
frameGrabberOutput = new AVCaptureVideoDataOutput();
frameGrabberOutput.WeakVideoSettings = new CVPixelBufferAttributes () { PixelFormatType = CVPixelFormatType.CV32BGRA }.Dictionary;
// set up the output queue and delegate
queue = new CoreFoundation.DispatchQueue ("captureQueue");
videoFrameSampler = new VideoFrameSamplerDelegate();
frameGrabberOutput.SetSampleBufferDelegateQueue (videoFrameSampler, queue);
// subscribe to from capture events
videoFrameSampler.CaptureError += new EventHandler<CaptureErrorEventArgs>( handleImageCaptureError );
videoFrameSampler.ImageCaptured += new EventHandler<ImageCaptureEventArgs>( handleImageCaptured );
// add the output to the session
session.AddOutput (frameGrabberOutput);
// set minimum time interval between image samples (if possible).
try
{
AVCaptureConnection connection = (AVCaptureConnection)frameGrabberOutput.Connections[0];
connection.VideoMinFrameDuration = new CMTime(minimumSampleIntervalInMilliSeconds, 1000);
}
catch
{
}
return true;
}
private void handleMovieSegmentRecordingStarted( object sender, MovieSegmentRecordingStartedEventArgs args )
{
currentSegmentStartedAt = DateTime.Now;
}
#region event handlers
private void handleMovieSegmentRecordingComplete(object sender, MovieSegmentRecordingCompleteEventArgs args )
{
try
{
// grab the pertinent event data
MovieSegmentCapturedEventArgs captureInfo = new MovieSegmentCapturedEventArgs();
captureInfo.StartedAt = currentSegmentStartedAt;
captureInfo.DurationMilliSeconds = movieSegmentDurationInMilliSeconds;
captureInfo.File = args.Path;
// conditionally start recording the next segment
if ( args.ErrorOccured == false && breakMovieIntoSegments && isCapturing)
{
startRecordingNextMovieFilename();
}
// raise the capture event to external listeners
onMovieSegmentCaptured( captureInfo );
}
catch
{
}
}
private void handleMovieCaptureError(object sender, CaptureErrorEventArgs args )
{
// bubble up
onCaptureError( args );
}
private void handleImageCaptured( object sender, ImageCaptureEventArgs args)
{
// bubble up
onImageCaptured( args);
}
private void handleImageCaptureError( object sender, CaptureErrorEventArgs args )
{
// bubble up
onCaptureError( args );
}
#endregion
private void unsubscribeDelegateEvents()
{
try
{
if ( videoFrameSampler != null )
{
videoFrameSampler.CaptureError -= new EventHandler<CaptureErrorEventArgs>( handleImageCaptureError );
videoFrameSampler.ImageCaptured -= new EventHandler<ImageCaptureEventArgs>( handleImageCaptured );
}
if ( movieSegmentWriter != null )
{
movieSegmentWriter.MovieSegmentRecordingStarted -= new EventHandler<MovieSegmentRecordingStartedEventArgs>( handleMovieSegmentRecordingStarted );
movieSegmentWriter.MovieSegmentRecordingComplete -= new EventHandler<MovieSegmentRecordingCompleteEventArgs>( handleMovieSegmentRecordingComplete );
movieSegmentWriter.CaptureError -= new EventHandler<CaptureErrorEventArgs>( handleMovieCaptureError );
}
}
catch
{
}
}
private string getDateTimeDirectoryName( DateTime dateTime )
{
return dateTime.ToString().Replace(":","-").Replace ("/","-").Replace (" ","-").Replace ("\\","-");
}
}
public enum Resolution
{
Low,
Medium,
High
}
public enum CameraType
{
FrontFacing,
RearFacing
}
}
| |
#region License
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using Gremlin.Net.Process.Remote;
using Gremlin.Net.Process.Traversal.Strategy.Decoration;
using Gremlin.Net.Structure;
// THIS IS A GENERATED FILE - DO NOT MODIFY THIS FILE DIRECTLY - see pom.xml
namespace Gremlin.Net.Process.Traversal
{
#pragma warning disable 1591
/// <summary>
/// A <see cref="GraphTraversalSource" /> is the primary DSL of the Gremlin traversal machine.
/// It provides access to all the configurations and steps for Turing complete graph computing.
/// </summary>
public class GraphTraversalSource
{
/// <summary>
/// Gets or sets the traversal strategies associated with this graph traversal source.
/// </summary>
public ICollection<ITraversalStrategy> TraversalStrategies { get; set; }
/// <summary>
/// Gets or sets the <see cref="Traversal.Bytecode" /> associated with the current state of this graph traversal
/// source.
/// </summary>
public Bytecode Bytecode { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="GraphTraversalSource" /> class.
/// </summary>
public GraphTraversalSource()
: this(new List<ITraversalStrategy>(), new Bytecode())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="GraphTraversalSource" /> class.
/// </summary>
/// <param name="traversalStrategies">The traversal strategies associated with this graph traversal source.</param>
/// <param name="bytecode">
/// The <see cref="Traversal.Bytecode" /> associated with the current state of this graph traversal
/// source.
/// </param>
public GraphTraversalSource(ICollection<ITraversalStrategy> traversalStrategies, Bytecode bytecode)
{
TraversalStrategies = traversalStrategies;
Bytecode = bytecode;
}
public GraphTraversalSource With(string key)
{
var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies),
new Bytecode(Bytecode));
source.Bytecode.AddSource("with", key);
return source;
}
public GraphTraversalSource With(string key, object value)
{
var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies),
new Bytecode(Bytecode));
source.Bytecode.AddSource("with", key, value);
return source;
}
public GraphTraversalSource WithBulk(bool useBulk)
{
var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies),
new Bytecode(Bytecode));
source.Bytecode.AddSource("withBulk", useBulk);
return source;
}
public GraphTraversalSource WithPath()
{
var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies),
new Bytecode(Bytecode));
source.Bytecode.AddSource("withPath");
return source;
}
public GraphTraversalSource WithSack(object initialValue)
{
var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies),
new Bytecode(Bytecode));
source.Bytecode.AddSource("withSack", initialValue);
return source;
}
public GraphTraversalSource WithSack(object initialValue, IBinaryOperator mergeOperator)
{
var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies),
new Bytecode(Bytecode));
source.Bytecode.AddSource("withSack", initialValue, mergeOperator);
return source;
}
public GraphTraversalSource WithSack(object initialValue, IUnaryOperator splitOperator)
{
var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies),
new Bytecode(Bytecode));
source.Bytecode.AddSource("withSack", initialValue, splitOperator);
return source;
}
public GraphTraversalSource WithSack(object initialValue, IUnaryOperator splitOperator, IBinaryOperator mergeOperator)
{
var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies),
new Bytecode(Bytecode));
source.Bytecode.AddSource("withSack", initialValue, splitOperator, mergeOperator);
return source;
}
public GraphTraversalSource WithSack(ISupplier initialValue)
{
var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies),
new Bytecode(Bytecode));
source.Bytecode.AddSource("withSack", initialValue);
return source;
}
public GraphTraversalSource WithSack(ISupplier initialValue, IBinaryOperator mergeOperator)
{
var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies),
new Bytecode(Bytecode));
source.Bytecode.AddSource("withSack", initialValue, mergeOperator);
return source;
}
public GraphTraversalSource WithSack(ISupplier initialValue, IUnaryOperator splitOperator)
{
var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies),
new Bytecode(Bytecode));
source.Bytecode.AddSource("withSack", initialValue, splitOperator);
return source;
}
public GraphTraversalSource WithSack(ISupplier initialValue, IUnaryOperator splitOperator, IBinaryOperator mergeOperator)
{
var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies),
new Bytecode(Bytecode));
source.Bytecode.AddSource("withSack", initialValue, splitOperator, mergeOperator);
return source;
}
public GraphTraversalSource WithSideEffect(string key, object initialValue)
{
var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies),
new Bytecode(Bytecode));
source.Bytecode.AddSource("withSideEffect", key, initialValue);
return source;
}
public GraphTraversalSource WithSideEffect(string key, object initialValue, IBinaryOperator reducer)
{
var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies),
new Bytecode(Bytecode));
source.Bytecode.AddSource("withSideEffect", key, initialValue, reducer);
return source;
}
public GraphTraversalSource WithSideEffect(string key, ISupplier initialValue)
{
var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies),
new Bytecode(Bytecode));
source.Bytecode.AddSource("withSideEffect", key, initialValue);
return source;
}
public GraphTraversalSource WithSideEffect(string key, ISupplier initialValue, IBinaryOperator reducer)
{
var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies),
new Bytecode(Bytecode));
source.Bytecode.AddSource("withSideEffect", key, initialValue, reducer);
return source;
}
public GraphTraversalSource WithStrategies(params ITraversalStrategy[] traversalStrategies)
{
var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies),
new Bytecode(Bytecode));
var args = new List<object>(0 + traversalStrategies.Length) {};
args.AddRange(traversalStrategies);
source.Bytecode.AddSource("withStrategies", args.ToArray());
return source;
}
public GraphTraversalSource WithoutStrategies(params Type[] traversalStrategyClasses)
{
var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies),
new Bytecode(Bytecode));
var args = new List<object>(0 + traversalStrategyClasses.Length) {};
args.AddRange(traversalStrategyClasses);
source.Bytecode.AddSource("withoutStrategies", args.ToArray());
return source;
}
[Obsolete("Use the Bindings class instead.", false)]
public GraphTraversalSource WithBindings(object bindings)
{
return this;
}
/// <summary>
/// Configures the <see cref="GraphTraversalSource" /> as a "remote" to issue the
/// <see cref="GraphTraversal{SType, EType}" /> for execution elsewhere.
/// </summary>
/// <param name="remoteConnection">
/// The <see cref="IRemoteConnection" /> instance to use to submit the
/// <see cref="GraphTraversal{SType, EType}" />.
/// </param>
/// <returns>A <see cref="GraphTraversalSource" /> configured to use the provided <see cref="IRemoteConnection" />.</returns>
public GraphTraversalSource WithRemote(IRemoteConnection remoteConnection)
{
var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies),
new Bytecode(Bytecode));
source.TraversalStrategies.Add(new RemoteStrategy(remoteConnection));
return source;
}
/// <summary>
/// Add a GraphComputer class used to execute the traversal.
/// This adds a <see cref="VertexProgramStrategy" /> to the strategies.
/// </summary>
public GraphTraversalSource WithComputer(string graphComputer = null, int? workers = null, string persist = null,
string result = null, ITraversal vertices = null, ITraversal edges = null,
Dictionary<string, dynamic> configuration = null)
{
return WithStrategies(new VertexProgramStrategy(graphComputer, workers, persist, result, vertices, edges, configuration));
}
/// <summary>
/// Spawns a <see cref="GraphTraversal{SType, EType}" /> off this graph traversal source and adds the E step to that
/// traversal.
/// </summary>
public GraphTraversal<Edge, Edge> E(params object[] edgesIds)
{
var traversal = new GraphTraversal<Edge, Edge>(TraversalStrategies, new Bytecode(Bytecode));
var args = new List<object>(0 + edgesIds.Length) {};
args.AddRange(edgesIds);
traversal.Bytecode.AddStep("E", args.ToArray());
return traversal;
}
/// <summary>
/// Spawns a <see cref="GraphTraversal{SType, EType}" /> off this graph traversal source and adds the V step to that
/// traversal.
/// </summary>
public GraphTraversal<Vertex, Vertex> V(params object[] vertexIds)
{
var traversal = new GraphTraversal<Vertex, Vertex>(TraversalStrategies, new Bytecode(Bytecode));
var args = new List<object>(0 + vertexIds.Length) {};
args.AddRange(vertexIds);
traversal.Bytecode.AddStep("V", args.ToArray());
return traversal;
}
/// <summary>
/// Spawns a <see cref="GraphTraversal{SType, EType}" /> off this graph traversal source and adds the addE step to that
/// traversal.
/// </summary>
public GraphTraversal<Edge, Edge> AddE(string label)
{
var traversal = new GraphTraversal<Edge, Edge>(TraversalStrategies, new Bytecode(Bytecode));
traversal.Bytecode.AddStep("addE", label);
return traversal;
}
/// <summary>
/// Spawns a <see cref="GraphTraversal{SType, EType}" /> off this graph traversal source and adds the addE step to that
/// traversal.
/// </summary>
public GraphTraversal<Edge, Edge> AddE(ITraversal edgeLabelTraversal)
{
var traversal = new GraphTraversal<Edge, Edge>(TraversalStrategies, new Bytecode(Bytecode));
traversal.Bytecode.AddStep("addE", edgeLabelTraversal);
return traversal;
}
/// <summary>
/// Spawns a <see cref="GraphTraversal{SType, EType}" /> off this graph traversal source and adds the addV step to that
/// traversal.
/// </summary>
public GraphTraversal<Vertex, Vertex> AddV()
{
var traversal = new GraphTraversal<Vertex, Vertex>(TraversalStrategies, new Bytecode(Bytecode));
traversal.Bytecode.AddStep("addV");
return traversal;
}
/// <summary>
/// Spawns a <see cref="GraphTraversal{SType, EType}" /> off this graph traversal source and adds the addV step to that
/// traversal.
/// </summary>
public GraphTraversal<Vertex, Vertex> AddV(string label)
{
var traversal = new GraphTraversal<Vertex, Vertex>(TraversalStrategies, new Bytecode(Bytecode));
traversal.Bytecode.AddStep("addV", label);
return traversal;
}
/// <summary>
/// Spawns a <see cref="GraphTraversal{SType, EType}" /> off this graph traversal source and adds the addV step to that
/// traversal.
/// </summary>
public GraphTraversal<Vertex, Vertex> AddV(ITraversal vertexLabelTraversal)
{
var traversal = new GraphTraversal<Vertex, Vertex>(TraversalStrategies, new Bytecode(Bytecode));
traversal.Bytecode.AddStep("addV", vertexLabelTraversal);
return traversal;
}
/// <summary>
/// Spawns a <see cref="GraphTraversal{SType, EType}" /> off this graph traversal source and adds the inject step to that
/// traversal.
/// </summary>
public GraphTraversal<S, S> Inject<S>(params S[] starts)
{
var traversal = new GraphTraversal<S, S>(TraversalStrategies, new Bytecode(Bytecode));
var args = new List<object>(0 + starts.Length) {};
args.AddRange(starts.Cast<object>());
traversal.Bytecode.AddStep("inject", args.ToArray());
return traversal;
}
/// <summary>
/// Spawns a <see cref="GraphTraversal{SType, EType}" /> off this graph traversal source and adds the io step to that
/// traversal.
/// </summary>
public GraphTraversal<S, S> Io<S>(string file)
{
var traversal = new GraphTraversal<S, S>(TraversalStrategies, new Bytecode(Bytecode));
traversal.Bytecode.AddStep("io", file);
return traversal;
}
}
#pragma warning restore 1591
}
| |
//using com.google.zxing.qrcode.decoder;
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//using BitSource = com.google.zxing.common.BitSource;
//using CharacterSetECI = com.google.zxing.common.CharacterSetECI;
//using DecoderResult = com.google.zxing.common.DecoderResult;
using System;
using System.Collections.Generic;
using System.Text;
using ZXing.Common;
using ZXing.QrCode.Internal;
namespace ZXing.MicroQrCode.Internal
{
/// <summary> <p>QR Codes can encode text as bits in one of several modes, and can use multiple modes
/// in one QR Code. This class decodes the bits back into text.</p>
///
/// <p>See ISO 18004:2006, 6.4.3 - 6.4.7</p>
/// <author>Sean Owen</author>
/// </summary>
internal static class DecodedBitStreamParser
{
/// <summary>
/// See ISO 18004:2006, 6.4.4 Table 5
/// </summary>
private static readonly char[] ALPHANUMERIC_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:".ToCharArray();
private const int GB2312_SUBSET = 1;
internal static DecoderResult decode(byte[] bytes,
Version version,
QrCode.Internal.ErrorCorrectionLevel ecLevel,
IDictionary<DecodeHintType, object> hints)
{
var bits = new BitSource(bytes);
var result = new StringBuilder(50);
var byteSegments = new List<byte[]>(1);
var symbolSequence = -1;
var parityData = -1;
CharacterSetECI currentCharacterSetECI = null;
bool fc1InEffect = false;
Mode mode = Mode.TERMINATOR;
int bitLen = Mode.NUMERIC.getBitsLength(version.VersionNumber);
if (version.VersionNumber > 1)
{
try
{
mode = Mode.forBits(bits.readBits(bitLen));
}
catch (System.ArgumentException iae)
{
throw ReaderException.Instance;
}
}
else
mode = Mode.NUMERIC;
if (!mode.Equals(Mode.TERMINATOR))
{
// How many characters will follow, encoded in this mode?
int count = bits.readBits(mode.getCharacterCountBits(version));
if (mode.Equals(Mode.NUMERIC))
{
decodeNumericSegment(bits, result, count);
}
else if (mode.Equals(Mode.ALPHANUMERIC))
{
decodeAlphanumericSegment(bits, result, count, fc1InEffect);
}
else if (mode.Equals(Mode.BYTE))
{
decodeByteSegment(bits, result, count, currentCharacterSetECI, byteSegments,hints);
}
else if (mode.Equals(Mode.KANJI))
{
decodeKanjiSegment(bits, result, count);
}
else
{
throw ReaderException.Instance;
}
}
return new DecoderResult(bytes, result.ToString(), byteSegments.Count == 0 ? null : byteSegments, ecLevel == null ? null : ecLevel.ToString(),
symbolSequence, parityData);
}
/// <summary>
/// See specification GBT 18284-2000
/// </summary>
/// <param name="bits">The bits.</param>
/// <param name="result">The result.</param>
/// <param name="count">The count.</param>
/// <returns></returns>
private static bool decodeHanziSegment(BitSource bits,
StringBuilder result,
int count)
{
// Don't crash trying to read more bits than we have available.
if (count * 13 > bits.available())
{
return false;
}
// Each character will require 2 bytes. Read the characters as 2-byte pairs
// and decode as GB2312 afterwards
byte[] buffer = new byte[2 * count];
int offset = 0;
while (count > 0)
{
// Each 13 bits encodes a 2-byte character
int twoBytes = bits.readBits(13);
int assembledTwoBytes = ((twoBytes / 0x060) << 8) | (twoBytes % 0x060);
if (assembledTwoBytes < 0x003BF)
{
// In the 0xA1A1 to 0xAAFE range
assembledTwoBytes += 0x0A1A1;
}
else
{
// In the 0xB0A1 to 0xFAFE range
assembledTwoBytes += 0x0A6A1;
}
buffer[offset] = (byte)((assembledTwoBytes >> 8) & 0xFF);
buffer[offset + 1] = (byte)(assembledTwoBytes & 0xFF);
offset += 2;
count--;
}
try
{
result.Append(Encoding.GetEncoding(StringUtils.GB2312).GetString(buffer, 0, buffer.Length));
}
#if (WINDOWS_PHONE70 || WINDOWS_PHONE71 || SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE || MONOANDROID || MONOTOUCH)
catch (ArgumentException)
{
try
{
// Silverlight only supports a limited number of character sets, trying fallback to UTF-8
result.Append(Encoding.GetEncoding("UTF-8").GetString(buffer, 0, buffer.Length));
}
catch (Exception)
{
return false;
}
}
#endif
catch (Exception)
{
return false;
}
return true;
}
private static bool decodeKanjiSegment(BitSource bits,
StringBuilder result,
int count)
{
// Don't crash trying to read more bits than we have available.
if (count * 13 > bits.available())
{
return false;
}
// Each character will require 2 bytes. Read the characters as 2-byte pairs
// and decode as Shift_JIS afterwards
byte[] buffer = new byte[2 * count];
int offset = 0;
while (count > 0)
{
// Each 13 bits encodes a 2-byte character
int twoBytes = bits.readBits(13);
int assembledTwoBytes = ((twoBytes / 0x0C0) << 8) | (twoBytes % 0x0C0);
if (assembledTwoBytes < 0x01F00)
{
// In the 0x8140 to 0x9FFC range
assembledTwoBytes += 0x08140;
}
else
{
// In the 0xE040 to 0xEBBF range
assembledTwoBytes += 0x0C140;
}
buffer[offset] = (byte)(assembledTwoBytes >> 8);
buffer[offset + 1] = (byte)assembledTwoBytes;
offset += 2;
count--;
}
// Shift_JIS may not be supported in some environments:
try
{
result.Append(Encoding.GetEncoding(StringUtils.SHIFT_JIS).GetString(buffer, 0, buffer.Length));
}
#if (WINDOWS_PHONE70 || WINDOWS_PHONE71 || SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE || MONOANDROID || MONOTOUCH)
catch (ArgumentException)
{
try
{
// Silverlight only supports a limited number of character sets, trying fallback to UTF-8
result.Append(Encoding.GetEncoding("UTF-8").GetString(buffer, 0, buffer.Length));
}
catch (Exception)
{
return false;
}
}
#endif
catch (Exception)
{
return false;
}
return true;
}
private static bool decodeByteSegment(BitSource bits,
StringBuilder result,
int count,
CharacterSetECI currentCharacterSetECI,
IList<byte[]> byteSegments,
IDictionary<DecodeHintType, object> hints)
{
// Don't crash trying to read more bits than we have available.
if (count << 3 > bits.available())
{
return false;
}
byte[] readBytes = new byte[count];
for (int i = 0; i < count; i++)
{
readBytes[i] = (byte)bits.readBits(8);
}
String encoding;
if (currentCharacterSetECI == null)
{
// The spec isn't clear on this mode; see
// section 6.4.5: t does not say which encoding to assuming
// upon decoding. I have seen ISO-8859-1 used as well as
// Shift_JIS -- without anything like an ECI designator to
// give a hint.
encoding = StringUtils.guessEncoding(readBytes, hints);
}
else
{
encoding = currentCharacterSetECI.EncodingName;
}
try
{
result.Append(Encoding.GetEncoding(encoding).GetString(readBytes, 0, readBytes.Length));
}
#if (WINDOWS_PHONE70 || WINDOWS_PHONE71 || SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE || MONOANDROID || MONOTOUCH)
catch (ArgumentException)
{
try
{
// Silverlight only supports a limited number of character sets, trying fallback to UTF-8
result.Append(Encoding.GetEncoding("UTF-8").GetString(readBytes, 0, readBytes.Length));
}
catch (Exception)
{
return false;
}
}
#endif
#if WindowsCE
catch (PlatformNotSupportedException)
{
try
{
// WindowsCE doesn't support all encodings. But it is device depended.
// So we try here the some different ones
if (encoding == "ISO-8859-1")
{
result.Append(Encoding.GetEncoding(1252).GetString(readBytes, 0, readBytes.Length));
}
else
{
result.Append(Encoding.GetEncoding("UTF-8").GetString(readBytes, 0, readBytes.Length));
}
}
catch (Exception)
{
return false;
}
}
#endif
catch (Exception)
{
return false;
}
byteSegments.Add(readBytes);
return true;
}
private static char toAlphaNumericChar(int value)
{
if (value >= ALPHANUMERIC_CHARS.Length)
{
throw FormatException.Instance;
}
return ALPHANUMERIC_CHARS[value];
}
private static bool decodeAlphanumericSegment(BitSource bits,
StringBuilder result,
int count,
bool fc1InEffect)
{
// Read two characters at a time
int start = result.Length;
while (count > 1)
{
if (bits.available() < 11)
{
return false;
}
int nextTwoCharsBits = bits.readBits(11);
result.Append(toAlphaNumericChar(nextTwoCharsBits / 45));
result.Append(toAlphaNumericChar(nextTwoCharsBits % 45));
count -= 2;
}
if (count == 1)
{
// special case: one character left
if (bits.available() < 6)
{
return false;
}
result.Append(toAlphaNumericChar(bits.readBits(6)));
}
// See section 6.4.8.1, 6.4.8.2
if (fc1InEffect)
{
// We need to massage the result a bit if in an FNC1 mode:
for (int i = start; i < result.Length; i++)
{
if (result[i] == '%')
{
if (i < result.Length - 1 && result[i + 1] == '%')
{
// %% is rendered as %
result.Remove(i + 1, 1);
}
else
{
// In alpha mode, % should be converted to FNC1 separator 0x1D
result.Remove(i, 1);
result.Insert(i, new[] { (char)0x1D });
}
}
}
}
return true;
}
private static bool decodeNumericSegment(BitSource bits,
StringBuilder result,
int count)
{
// Read three digits at a time
while (count >= 3)
{
// Each 10 bits encodes three digits
if (bits.available() < 10)
{
return false;
}
int threeDigitsBits = bits.readBits(10);
if (threeDigitsBits >= 1000)
{
return false;
}
result.Append(toAlphaNumericChar(threeDigitsBits / 100));
result.Append(toAlphaNumericChar((threeDigitsBits / 10) % 10));
result.Append(toAlphaNumericChar(threeDigitsBits % 10));
count -= 3;
}
if (count == 2)
{
// Two digits left over to read, encoded in 7 bits
if (bits.available() < 7)
{
return false;
}
int twoDigitsBits = bits.readBits(7);
if (twoDigitsBits >= 100)
{
return false;
}
result.Append(toAlphaNumericChar(twoDigitsBits / 10));
result.Append(toAlphaNumericChar(twoDigitsBits % 10));
}
else if (count == 1)
{
// One digit left over to read
if (bits.available() < 4)
{
return false;
}
int digitBits = bits.readBits(4);
if (digitBits >= 10)
{
return false;
}
result.Append(toAlphaNumericChar(digitBits));
}
return true;
}
private static int parseECIValue(BitSource bits)
{
int firstByte = bits.readBits(8);
if ((firstByte & 0x80) == 0)
{
// just one byte
return firstByte & 0x7F;
}
if ((firstByte & 0xC0) == 0x80)
{
// two bytes
int secondByte = bits.readBits(8);
return ((firstByte & 0x3F) << 8) | secondByte;
}
if ((firstByte & 0xE0) == 0xC0)
{
// three bytes
int secondThirdBytes = bits.readBits(16);
return ((firstByte & 0x1F) << 16) | secondThirdBytes;
}
throw new ArgumentException("Bad ECI bits starting with byte " + firstByte);
}
}
}
| |
//***************************************************
//* This file was generated by tool
//* SharpKit
//* At: 29/08/2012 03:59:39 p.m.
//***************************************************
using SharpKit.JavaScript;
namespace Ext.data
{
#region Operation
/// <inheritdocs />
/// <summary>
/// <p>Represents a single read or write operation performed by a <see cref="Ext.data.proxy.Proxy">Proxy</see>. Operation objects are
/// used to enable communication between Stores and Proxies. Application developers should rarely need to interact with
/// Operation objects directly.</p>
/// <p>Several Operations can be batched together in a <see cref="Ext.data.Batch">batch</see>.</p>
/// </summary>
[JsType(JsMode.Prototype, Export=false, OmitOptionalParameters=true)]
public partial class Operation : Ext.Base
{
/// <summary>
/// The action being performed by this Operation. Should be one of 'create', 'read', 'update' or 'destroy'.
/// </summary>
public JsString action;
/// <summary>
/// The batch that this Operation is a part of.
/// </summary>
public Batch batch;
/// <summary>
/// Function to execute when operation completed.
/// </summary>
public System.Delegate callback;
/// <summary>
/// Optional array of filter objects. Only applies to 'read' actions.
/// </summary>
public Ext.util.Filter filters;
/// <summary>
/// Optional grouping configuration. Only applies to 'read' actions where grouping is desired.
/// </summary>
public Ext.util.Grouper groupers;
/// <summary>
/// The number of records to load. Used on 'read' actions when paging is being used.
/// </summary>
public JsNumber limit;
/// <summary>
/// Parameters to pass along with the request when performing the operation.
/// </summary>
public JsObject @params;
/// <summary>
/// Scope for the callback function.
/// </summary>
public JsObject scope;
/// <summary>
/// Optional array of sorter objects. Only applies to 'read' actions.
/// </summary>
public Ext.util.Sorter sorters;
/// <summary>
/// The start index (offset), used in paging when running a 'read' action.
/// </summary>
public JsNumber start;
/// <summary>
/// True if this Operation is to be executed synchronously. This property is inspected by a
/// Batch to see if a series of Operations can be executed in parallel or not.
/// Defaults to: <c>true</c>
/// </summary>
public bool synchronous;
/// <summary>
/// The RegExp used to categorize actions that require record commits.
/// Defaults to: <c>/^(?:create|update)$/i</c>
/// </summary>
public JsRegExp actionCommitRecordsRe{get;set;}
/// <summary>
/// The RegExp used to categorize actions that skip local record synchronization. This defaults
/// to match 'destroy'.
/// Defaults to: <c>/^destroy$/i</c>
/// </summary>
public JsRegExp actionSkipSyncRe{get;set;}
/// <summary>
/// The completion status of this Operation. Use isComplete.
/// Defaults to: <c>false</c>
/// </summary>
private bool complete{get;set;}
/// <summary>
/// The error object passed when setException was called. This could be any object or primitive.
/// </summary>
private object error{get;set;}
/// <summary>
/// The exception status of this Operation. Use hasException and see getError.
/// Defaults to: <c>false</c>
/// </summary>
private bool exception{get;set;}
/// <summary>
/// The run status of this Operation. Use isRunning.
/// Defaults to: <c>false</c>
/// </summary>
private bool running{get;set;}
/// <summary>
/// The start status of this Operation. Use isStarted.
/// Defaults to: <c>false</c>
/// </summary>
private bool started{get;set;}
/// <summary>
/// Whether the Operation was successful or not. This starts as undefined and is set to true
/// or false by the Proxy that is executing the Operation. It is also set to false by setException. Use
/// wasSuccessful to query success status.
/// </summary>
private bool success{get;set;}
/// <summary>
/// Creates new Operation object.
/// </summary>
/// <param name="config"><p>Config object.</p>
/// </param>
/// <returns>
/// <span><see cref="Object">Object</see></span><div>
/// </div>
/// </returns>
public Operation(object config=null){}
/// <summary>
/// Checks whether this operation should cause writing to occur.
/// </summary>
/// <returns>
/// <span><see cref="bool">Boolean</see></span><div><p>Whether the operation should cause a write to occur.</p>
/// </div>
/// </returns>
public bool allowWrite(){return false;}
/// <summary>
/// This method is called to commit data to this instance's records given the records in
/// the server response. This is followed by calling Ext.data.Model.commit on all
/// those records (for 'create' and 'update' actions).
/// If this <see cref="Ext.data.OperationConfig.action">action</see> is 'destroy', any server records are ignored and the
/// <see cref="Ext.data.Model.commit">Ext.data.Model.commit</see> method is not called.
/// </summary>
/// <param name="serverRecords"><p>An array of <see cref="Ext.data.Model">Ext.data.Model</see> objects returned by
/// the server.</p>
/// </param>
public void commitRecords(JsArray<Ext.data.Model> serverRecords){}
/// <summary>
/// Returns the error string or object that was set using setException
/// </summary>
/// <returns>
/// <span><see cref="String">String</see>/<see cref="Object">Object</see></span><div><p>The error object</p>
/// </div>
/// </returns>
public object getError(){return null;}
/// <summary>
/// Returns the records associated with this operation. For read operations the records as set by the Proxy will be returned (returns null if the proxy has not yet set the records).
/// For create, update, and destroy operations the operation's initially configured records will be returned, although the proxy may modify these records' data at some point after the operation is initialized.
/// </summary>
/// <returns>
/// <span><see cref="Ext.data.Model">Ext.data.Model</see>[]</span><div>
/// </div>
/// </returns>
public Ext.data.Model[] getRecords(){return null;}
/// <summary>
/// Returns the ResultSet object (if set by the Proxy). This object will contain the model
/// instances as well as meta data such as number of instances fetched, number available etc
/// </summary>
/// <returns>
/// <span><see cref="Ext.data.ResultSet">Ext.data.ResultSet</see></span><div><p>The ResultSet object</p>
/// </div>
/// </returns>
public ResultSet getResultSet(){return null;}
/// <summary>
/// Returns true if this Operation encountered an exception (see also getError)
/// </summary>
/// <returns>
/// <span><see cref="bool">Boolean</see></span><div><p>True if there was an exception</p>
/// </div>
/// </returns>
public bool hasException(){return false;}
/// <summary>
/// Returns true if the Operation has been completed
/// </summary>
/// <returns>
/// <span><see cref="bool">Boolean</see></span><div><p>True if the Operation is complete</p>
/// </div>
/// </returns>
public bool isComplete(){return false;}
/// <summary>
/// Returns true if the Operation has been started but has not yet completed.
/// </summary>
/// <returns>
/// <span><see cref="bool">Boolean</see></span><div><p>True if the Operation is currently running</p>
/// </div>
/// </returns>
public bool isRunning(){return false;}
/// <summary>
/// Returns true if the Operation has been started. Note that the Operation may have started AND completed, see
/// isRunning to test if the Operation is currently running.
/// </summary>
/// <returns>
/// <span><see cref="bool">Boolean</see></span><div><p>True if the Operation has started</p>
/// </div>
/// </returns>
public bool isStarted(){return false;}
/// <summary>
/// Associates this Operation with a Batch
/// </summary>
/// <param name="batch"><p>The batch</p>
/// </param>
private void setBatch(Batch batch){}
/// <summary>
/// Marks the Operation as completed.
/// </summary>
public void setCompleted(){}
/// <summary>
/// Marks the Operation as having experienced an exception. Can be supplied with an option error message/object.
/// </summary>
/// <param name="error"><p>error string/object</p>
/// </param>
public void setException(object error=null){}
/// <summary>
/// Marks the Operation as started.
/// </summary>
public void setStarted(){}
/// <summary>
/// Marks the Operation as successful.
/// </summary>
public void setSuccessful(){}
/// <summary>
/// Returns true if the Operation has completed and was successful
/// </summary>
/// <returns>
/// <span><see cref="bool">Boolean</see></span><div><p>True if successful</p>
/// </div>
/// </returns>
public bool wasSuccessful(){return false;}
public Operation(OperationConfig config){}
public Operation(params object[] args){}
}
#endregion
#region OperationConfig
/// <inheritdocs />
[JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)]
public partial class OperationConfig : Ext.BaseConfig
{
/// <summary>
/// The action being performed by this Operation. Should be one of 'create', 'read', 'update' or 'destroy'.
/// </summary>
public JsString action;
/// <summary>
/// The batch that this Operation is a part of.
/// </summary>
public Batch batch;
/// <summary>
/// Function to execute when operation completed.
/// </summary>
public System.Delegate callback;
/// <summary>
/// Optional array of filter objects. Only applies to 'read' actions.
/// </summary>
public Ext.util.Filter filters;
/// <summary>
/// Optional grouping configuration. Only applies to 'read' actions where grouping is desired.
/// </summary>
public Ext.util.Grouper groupers;
/// <summary>
/// The number of records to load. Used on 'read' actions when paging is being used.
/// </summary>
public JsNumber limit;
/// <summary>
/// Parameters to pass along with the request when performing the operation.
/// </summary>
public JsObject @params;
/// <summary>
/// Scope for the callback function.
/// </summary>
public JsObject scope;
/// <summary>
/// Optional array of sorter objects. Only applies to 'read' actions.
/// </summary>
public Ext.util.Sorter sorters;
/// <summary>
/// The start index (offset), used in paging when running a 'read' action.
/// </summary>
public JsNumber start;
/// <summary>
/// True if this Operation is to be executed synchronously. This property is inspected by a
/// Batch to see if a series of Operations can be executed in parallel or not.
/// Defaults to: <c>true</c>
/// </summary>
public bool synchronous;
public OperationConfig(params object[] args){}
}
#endregion
#region OperationEvents
/// <inheritdocs />
[JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)]
public partial class OperationEvents : Ext.BaseEvents
{
public OperationEvents(params object[] args){}
}
#endregion
}
| |
/*
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.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Adxstudio.Xrm.Cms;
using Adxstudio.Xrm.Core;
using Adxstudio.Xrm.Mapping;
using Adxstudio.Xrm.Notes;
using Adxstudio.Xrm.Resources;
using Adxstudio.Xrm.Services.Query;
using Adxstudio.Xrm.Text;
using Adxstudio.Xrm.Web.UI.EntityForm;
using Adxstudio.Xrm.Web.UI.WebControls;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using Site.Helpers;
using Site.Pages;
using CrmEntityReference = Microsoft.Xrm.Client.CrmEntityReference;
namespace Site.Areas.Service311.Pages
{
public partial class ServiceRequestDetails : PortalPage
{
public Entity ServiceRequest { get; set; }
private Entity _serviceRequestRollupRecord;
private Entity ServiceRequestRollupRecord
{
get
{
if (_serviceRequestRollupRecord == null)
{
var reference = Entity.GetAttributeValue<EntityReference>("adx_entityform");
var entityFormRecord =
XrmContext.CreateQuery("adx_entityform").FirstOrDefault(
ef => ef.GetAttributeValue<Guid>("adx_entityformid") == reference.Id);
if (entityFormRecord == null) return null;
var recordEntityLogicalName = entityFormRecord.GetAttributeValue<string>("adx_entityname");
Guid recordId;
if (!Guid.TryParse(Request["id"], out recordId))
{
return null;
}
var metadataRequest = new RetrieveEntityRequest
{
LogicalName = recordEntityLogicalName,
EntityFilters = EntityFilters.Attributes
};
var metadataResponse = (RetrieveEntityResponse)XrmContext.Execute(metadataRequest);
var primaryFieldLogicalName = metadataResponse.EntityMetadata.PrimaryIdAttribute;
_serviceRequestRollupRecord =
XrmContext.CreateQuery(recordEntityLogicalName).FirstOrDefault(
r => r.GetAttributeValue<Guid>(primaryFieldLogicalName) == recordId);
}
return _serviceRequestRollupRecord;
}
}
public string ServiceRequestNumber
{
get
{
var number = ServiceRequestRollupRecord.GetAttributeValue<string>("adx_servicerequestnumber");
return number;
}
}
private string RegardingContactFieldName { get; set; }
protected void Page_Init(object sender, EventArgs e)
{
if (ServiceRequestRollupRecord != null)
{
var serviceRequestTypeReference =
ServiceRequestRollupRecord.GetAttributeValue<EntityReference>("adx_servicerequesttype");
var serviceRequestType =
XrmContext.CreateQuery("adx_servicerequesttype").FirstOrDefault(
srt => srt.GetAttributeValue<Guid>("adx_servicerequesttypeid") == serviceRequestTypeReference.Id);
var entityName = serviceRequestType.GetAttributeValue<string>("adx_entityname");
RegardingContactFieldName = serviceRequestType.GetAttributeValue<string>("adx_regardingcontactfieldname");
var trueMetadataRequest = new RetrieveEntityRequest
{
LogicalName = entityName,
EntityFilters = EntityFilters.Attributes
};
var trueMetadataResponse = (RetrieveEntityResponse)XrmContext.Execute(trueMetadataRequest);
var primaryFieldName = trueMetadataResponse.EntityMetadata.PrimaryIdAttribute;
var entityId = ServiceRequestRollupRecord.GetAttributeValue<string>("adx_entityid");
var trueRecordId = Guid.Parse(entityId);
var trueRecord =
XrmContext.CreateQuery(entityName).FirstOrDefault(r => r.GetAttributeValue<Guid>(primaryFieldName) == trueRecordId);
ServiceRequest = trueRecord;
var regardingContact = ServiceRequest.GetAttributeValue<EntityReference>(RegardingContactFieldName);
if (regardingContact == null || Contact == null || regardingContact.Id != Contact.Id)
{
AddANote.Enabled = false;
AddANote.Visible = false;
AddNoteInline.Visible = false;
AddNoteInline.Enabled = false;
RenderCrmEntityFormView(entityName, primaryFieldName, serviceRequestType, trueRecordId, FormViewMode.ReadOnly);
var dataAdapterDependencies =
new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: PortalName);
var dataAdapter = new AnnotationDataAdapter(dataAdapterDependencies);
var annotations = dataAdapter.GetAnnotations(ServiceRequest.ToEntityReference(),
new List<Order> { new Order("createdon") }, respectPermissions: false);
if (!annotations.Any())
{
NotesLabel.Visible = false;
NotesList.Visible = false;
}
NotesList.DataSource = annotations;
NotesList.DataBind();
}
else
{
RenderCrmEntityFormView(entityName, primaryFieldName, serviceRequestType, trueRecordId, FormViewMode.Edit);
var dataAdapterDependencies =
new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: PortalName);
var dataAdapter = new AnnotationDataAdapter(dataAdapterDependencies);
var annotations = dataAdapter.GetAnnotations(ServiceRequest.ToEntityReference(),
new List<Order> { new Order("createdon") },
privacy: AnnotationPrivacy.Web | AnnotationPrivacy.Private | AnnotationPrivacy.Public, respectPermissions: false);
NotesList.DataSource = annotations;
NotesList.DataBind();
}
if (Request.IsAuthenticated && Contact != null)
{
var dataAdapter = CreateAlertDataAdapter();
var hasAlert = dataAdapter.HasAlert(Contact.ToEntityReference());
AddAlert.Visible = !hasAlert;
RemoveAlert.Visible = hasAlert;
}
else
{
AddAlertLoginLink.Visible = true;
}
DisplaySlaDetails(serviceRequestType);
}
}
private void RenderCrmEntityFormView(string entityName, string primaryFieldName, Entity serviceRequestType, Guid trueRecordId, FormViewMode formMode)
{
var serviceRequestDataSource = CreateDataSource("SeriveRequestDataSource", entityName, primaryFieldName, trueRecordId);
Entity entityForm = null;
entityForm = (serviceRequestType.GetAttributeValue<EntityReference>("adx_entityformid") != null)
? XrmContext.CreateQuery("adx_entityform").FirstOrDefault(e => e.GetAttributeValue<Guid>("adx_entityformid") ==
serviceRequestType.GetAttributeValue<EntityReference>("adx_entityformid").Id) :
XrmContext.CreateQuery("adx_entityform").FirstOrDefault(ef => ef.GetAttributeValue<string>("adx_name")
== "Web Service Request Details" && ef.GetAttributeValue<string>("adx_entityname") == entityName);
if (entityForm != null)
{
var formRecordSourceDefinition = new FormEntitySourceDefinition(entityName, primaryFieldName, trueRecordId);
var entityFormControl = new EntityForm(entityForm.ToEntityReference(), formRecordSourceDefinition)
{
ID = "CustomEntityFormControl",
FormCssClass = "crmEntityFormView",
PreviousButtonCssClass = "btn btn-default",
NextButtonCssClass = "btn btn-primary",
SubmitButtonCssClass = "btn btn-primary",
ClientIDMode = ClientIDMode.Static/*,
EntityFormReference = entityForm.ToEntityReference(),
EntitySourceDefinition = formRecordSourceDefinition*/
};
var languageCodeSetting = ServiceContext.GetSiteSettingValueByName(Portal.Website, "Language Code");
if (!string.IsNullOrWhiteSpace(languageCodeSetting))
{
int languageCode;
if (int.TryParse(languageCodeSetting, out languageCode)) entityFormControl.LanguageCode = languageCode;
}
CrmEntityFormViewPanel.Controls.Add(entityFormControl);
}
else
{
var mappingFieldCollection = new MappingFieldMetadataCollection()
{
FormattedLocationFieldName = serviceRequestType.GetAttributeValue<string>("adx_locationfieldname"),
LatitudeFieldName = serviceRequestType.GetAttributeValue<string>("adx_latitudefieldname"),
LongitudeFieldName = serviceRequestType.GetAttributeValue<string>("adx_longitudefieldname")
};
var serviceRequestFormView = new CrmEntityFormView()
{
FormName = "Web Details",
Mode = formMode,
EntityName = entityName,
CssClass = "crmEntityFormView",
SubmitButtonCssClass = "btn btn-primary",
AutoGenerateSteps = false,
ClientIDMode = ClientIDMode.Static,
MappingFieldCollection = mappingFieldCollection
};
var languageCodeSetting = ServiceContext.GetSiteSettingValueByName(Portal.Website, "Language Code");
if (!string.IsNullOrWhiteSpace(languageCodeSetting))
{
int languageCode;
if (int.TryParse(languageCodeSetting, out languageCode))
{
serviceRequestFormView.LanguageCode = languageCode;
serviceRequestFormView.ContextName = languageCode.ToString(CultureInfo.InvariantCulture);
serviceRequestDataSource.CrmDataContextName = languageCode.ToString(CultureInfo.InvariantCulture);
}
}
CrmEntityFormViewPanel.Controls.Add(serviceRequestFormView);
serviceRequestFormView.DataSourceID = serviceRequestDataSource.ID;
}
}
private CrmDataSource CreateDataSource(string dataSourceId, string entityName, string entityIdAttribute, Guid? entityId)
{
var formViewDataSource = new CrmDataSource
{
ID = dataSourceId,
FetchXml = string.Format(@"<fetch mapping='logical'> <entity name='{0}'> <all-attributes /> <filter type='and'> <condition attribute = '{1}' operator='eq' value='{{{2}}}'/> </filter> </entity> </fetch>",
entityName,
entityIdAttribute,
entityId)
};
CrmEntityFormViewPanel.Controls.Add(formViewDataSource);
return formViewDataSource;
}
protected static IHtmlString FormatNote(object text)
{
return text == null ? null : new SimpleHtmlFormatter().Format(text.ToString().Replace("*WEB* ", string.Empty).Replace("*PUBLIC* ", string.Empty));
}
protected void AddNote_Click(object sender, EventArgs e)
{
var regardingContact = ServiceRequest.GetAttributeValue<EntityReference>(RegardingContactFieldName);
if (regardingContact == null || Contact == null || regardingContact.Id != Contact.Id)
{
throw new InvalidOperationException("Unable to retrieve the order.");
}
var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(
requestContext: Request.RequestContext, portalName: PortalName);
var serviceContext = dataAdapterDependencies.GetServiceContext();
var dataAdapter = new AnnotationDataAdapter(dataAdapterDependencies);
if (NewNotePublic.Checked)
{
if (!string.IsNullOrEmpty(NewNoteText.Text) || (NewNoteAttachment.PostedFile != null && NewNoteAttachment.PostedFile.ContentLength > 0))
{
var annotation = new Annotation
{
NoteText = string.Format("{0}{1}", AnnotationHelper.PublicAnnotationPrefix, NewNoteText.Text),
Subject = AnnotationHelper.BuildNoteSubject(dataAdapterDependencies),
Regarding = ServiceRequest.ToEntityReference()
};
if (NewNoteAttachment.PostedFile != null && NewNoteAttachment.PostedFile.ContentLength > 0)
{
annotation.FileAttachment = AnnotationDataAdapter.CreateFileAttachment(new HttpPostedFileWrapper(NewNoteAttachment.PostedFile));
}
dataAdapter.CreateAnnotation(annotation);
}
}
else
{
if (!string.IsNullOrEmpty(NewNoteText.Text) ||
(NewNoteAttachment.PostedFile != null && NewNoteAttachment.PostedFile.ContentLength > 0))
{
var annotation = new Annotation
{
NoteText = string.Format("{0}{1}", AnnotationHelper.WebAnnotationPrefix, NewNoteText.Text),
Subject = AnnotationHelper.BuildNoteSubject(dataAdapterDependencies),
Regarding = ServiceRequest.ToEntityReference()
};
if (NewNoteAttachment.PostedFile != null && NewNoteAttachment.PostedFile.ContentLength > 0)
{
annotation.FileAttachment = AnnotationDataAdapter.CreateFileAttachment(new HttpPostedFileWrapper(NewNoteAttachment.PostedFile));
}
dataAdapter.CreateAnnotation(annotation);
}
}
Response.Redirect(Request.Url.PathAndQuery);
}
private IAlertSubscriptionDataAdapter CreateAlertDataAdapter()
{
return new ActivityEnabledEntityDataAdapter(ServiceRequest.ToEntityReference(), new Adxstudio.Xrm.Cms.PortalContextDataAdapterDependencies(Portal, requestContext: Request.RequestContext));
}
protected void AddAlertLoginLink_Click(object sender, EventArgs e)
{
var url = Url.SignInUrl();
Response.Redirect(url);
}
protected void AddAlert_Click(object sender, EventArgs e)
{
if (!Request.IsAuthenticated)
{
return;
}
var user = Portal.User;
if (user == null)
{
return;
}
var dataAdapter = CreateAlertDataAdapter();
var url = XrmContext.GetUrl(Entity);
var id = ServiceRequest.GetAttributeValue<EntityReference>("adx_servicerequest").Id.ToString();
dataAdapter.CreateAlert(user.ToEntityReference(), url, id);
Response.Redirect(Request.Url.PathAndQuery);
}
protected void RemoveAlert_Click(object sender, EventArgs e)
{
if (!Request.IsAuthenticated)
{
return;
}
var user = Portal.User;
if (user == null)
{
return;
}
var dataAdapter = CreateAlertDataAdapter();
dataAdapter.DeleteAlert(user.ToEntityReference());
Response.Redirect(Request.Url.PathAndQuery);
}
private void DisplaySlaDetails(Entity serviceRequestType)
{
SlaLabel.Text = serviceRequestType.GetAttributeValue<string>("adx_name") + ResourceManager.GetString("SLA_Details");
var slaResponseTime = serviceRequestType.GetAttributeValue<int?>("adx_responsesla");
if (slaResponseTime != null)
{
var slaResponseTimeInHours = slaResponseTime / 60;
SlaResponseTime.Text = string.Format(ResourceManager.GetString("SLA_Response_Time"), slaResponseTimeInHours.ToString());
}
var slaResolutionTime = serviceRequestType.GetAttributeValue<int?>("adx_resolutionsla");
if (slaResolutionTime != null)
{
var slaResolutionTimeInHours = slaResolutionTime / 60;
SlaResponseTime.Text = string.Format(ResourceManager.GetString("SLA_Resolution_Time"), slaResolutionTimeInHours.ToString());
}
if (slaResolutionTime == null && slaResponseTime == null)
{
SLAPanel.Visible = false;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics;
namespace System.Collections.Generic
{
// The SortedDictionary class implements a generic sorted list of keys
// and values. Entries in a sorted list are sorted by their keys and
// are accessible both by key and by index. The keys of a sorted dictionary
// can be ordered either according to a specific IComparer
// implementation given when the sorted dictionary is instantiated, or
// according to the IComparable implementation provided by the keys
// themselves. In either case, a sorted dictionary does not allow entries
// with duplicate or null keys.
//
// A sorted list internally maintains two arrays that store the keys and
// values of the entries. The capacity of a sorted list is the allocated
// length of these internal arrays. As elements are added to a sorted list, the
// capacity of the sorted list is automatically increased as required by
// reallocating the internal arrays. The capacity is never automatically
// decreased, but users can call either TrimExcess or
// Capacity explicitly.
//
// The GetKeyList and GetValueList methods of a sorted list
// provides access to the keys and values of the sorted list in the form of
// List implementations. The List objects returned by these
// methods are aliases for the underlying sorted list, so modifications
// made to those lists are directly reflected in the sorted list, and vice
// versa.
//
// The SortedList class provides a convenient way to create a sorted
// copy of another dictionary, such as a Hashtable. For example:
//
// Hashtable h = new Hashtable();
// h.Add(...);
// h.Add(...);
// ...
// SortedList s = new SortedList(h);
//
// The last line above creates a sorted list that contains a copy of the keys
// and values stored in the hashtable. In this particular example, the keys
// will be ordered according to the IComparable interface, which they
// all must implement. To impose a different ordering, SortedList also
// has a constructor that allows a specific IComparer implementation to
// be specified.
//
[DebuggerTypeProxy(typeof(IDictionaryDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
public class SortedList<TKey, TValue> :
IDictionary<TKey, TValue>, System.Collections.IDictionary, IReadOnlyDictionary<TKey, TValue>
{
private TKey[] _keys;
private TValue[] _values;
private int _size;
private int _version;
private IComparer<TKey> _comparer;
private KeyList _keyList;
private ValueList _valueList;
private Object _syncRoot;
private const int DefaultCapacity = 4;
// Constructs a new sorted list. The sorted list is initially empty and has
// a capacity of zero. Upon adding the first element to the sorted list the
// capacity is increased to DefaultCapacity, and then increased in multiples of two as
// required. The elements of the sorted list are ordered according to the
// IComparable interface, which must be implemented by the keys of
// all entries added to the sorted list.
public SortedList()
{
_keys = Array.Empty<TKey>();
_values = Array.Empty<TValue>();
_size = 0;
_comparer = Comparer<TKey>.Default;
}
// Constructs a new sorted list. The sorted list is initially empty and has
// a capacity of zero. Upon adding the first element to the sorted list the
// capacity is increased to 16, and then increased in multiples of two as
// required. The elements of the sorted list are ordered according to the
// IComparable interface, which must be implemented by the keys of
// all entries added to the sorted list.
//
public SortedList(int capacity)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_NeedNonNegNumRequired);
_keys = new TKey[capacity];
_values = new TValue[capacity];
_comparer = Comparer<TKey>.Default;
}
// Constructs a new sorted list with a given IComparer
// implementation. The sorted list is initially empty and has a capacity of
// zero. Upon adding the first element to the sorted list the capacity is
// increased to 16, and then increased in multiples of two as required. The
// elements of the sorted list are ordered according to the given
// IComparer implementation. If comparer is null, the
// elements are compared to each other using the IComparable
// interface, which in that case must be implemented by the keys of all
// entries added to the sorted list.
//
public SortedList(IComparer<TKey> comparer)
: this()
{
if (comparer != null)
{
_comparer = comparer;
}
}
// Constructs a new sorted dictionary with a given IComparer
// implementation and a given initial capacity. The sorted list is
// initially empty, but will have room for the given number of elements
// before any reallocations are required. The elements of the sorted list
// are ordered according to the given IComparer implementation. If
// comparer is null, the elements are compared to each other using
// the IComparable interface, which in that case must be implemented
// by the keys of all entries added to the sorted list.
//
public SortedList(int capacity, IComparer<TKey> comparer)
: this(comparer)
{
Capacity = capacity;
}
// Constructs a new sorted list containing a copy of the entries in the
// given dictionary. The elements of the sorted list are ordered according
// to the IComparable interface, which must be implemented by the
// keys of all entries in the the given dictionary as well as keys
// subsequently added to the sorted list.
//
public SortedList(IDictionary<TKey, TValue> dictionary)
: this(dictionary, null)
{
}
// Constructs a new sorted list containing a copy of the entries in the
// given dictionary. The elements of the sorted list are ordered according
// to the given IComparer implementation. If comparer is
// null, the elements are compared to each other using the
// IComparable interface, which in that case must be implemented
// by the keys of all entries in the the given dictionary as well as keys
// subsequently added to the sorted list.
//
public SortedList(IDictionary<TKey, TValue> dictionary, IComparer<TKey> comparer)
: this((dictionary != null ? dictionary.Count : 0), comparer)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");
dictionary.Keys.CopyTo(_keys, 0);
dictionary.Values.CopyTo(_values, 0);
Array.Sort<TKey, TValue>(_keys, _values, comparer);
_size = dictionary.Count;
}
// Adds an entry with the given key and value to this sorted list. An
// ArgumentException is thrown if the key is already present in the sorted list.
//
public void Add(TKey key, TValue value)
{
if (key == null) throw new ArgumentNullException("key");
int i = Array.BinarySearch<TKey>(_keys, 0, _size, key, _comparer);
if (i >= 0)
throw new ArgumentException(SR.Argument_AddingDuplicate);
Insert(~i, key, value);
}
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair)
{
Add(keyValuePair.Key, keyValuePair.Value);
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair)
{
int index = IndexOfKey(keyValuePair.Key);
if (index >= 0 && EqualityComparer<TValue>.Default.Equals(_values[index], keyValuePair.Value))
{
return true;
}
return false;
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair)
{
int index = IndexOfKey(keyValuePair.Key);
if (index >= 0 && EqualityComparer<TValue>.Default.Equals(_values[index], keyValuePair.Value))
{
RemoveAt(index);
return true;
}
return false;
}
// Returns the capacity of this sorted list. The capacity of a sorted list
// represents the allocated length of the internal arrays used to store the
// keys and values of the list, and thus also indicates the maximum number
// of entries the list can contain before a reallocation of the internal
// arrays is required.
//
public int Capacity
{
get
{
return _keys.Length;
}
set
{
if (value != _keys.Length)
{
if (value < _size)
{
throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_SmallCapacity);
}
if (value > 0)
{
TKey[] newKeys = new TKey[value];
TValue[] newValues = new TValue[value];
if (_size > 0)
{
Array.Copy(_keys, 0, newKeys, 0, _size);
Array.Copy(_values, 0, newValues, 0, _size);
}
_keys = newKeys;
_values = newValues;
}
else
{
_keys = Array.Empty<TKey>();
_values = Array.Empty<TValue>();
}
}
}
}
public IComparer<TKey> Comparer
{
get
{
return _comparer;
}
}
void System.Collections.IDictionary.Add(Object key, Object value)
{
if (key == null)
{
throw new ArgumentNullException("key");
}
if (value == null && !(default(TValue) == null))
throw new ArgumentNullException("value");
try
{
TKey tempKey = (TKey)key;
try
{
Add(tempKey, (TValue)value);
}
catch (InvalidCastException)
{
throw new ArgumentException(SR.Format(SR.Arg_WrongType, value, typeof(TValue)), "value");
}
}
catch (InvalidCastException)
{
throw new ArgumentException(SR.Format(SR.Arg_WrongType, key, typeof(TKey)), "key");
}
}
// Returns the number of entries in this sorted list.
//
public int Count
{
get
{
return _size;
}
}
// Returns a collection representing the keys of this sorted list. This
// method returns the same object as GetKeyList, but typed as an
// ICollection instead of an IList.
//
public IList<TKey> Keys
{
get
{
return GetKeyListHelper();
}
}
ICollection<TKey> IDictionary<TKey, TValue>.Keys
{
get
{
return GetKeyListHelper();
}
}
System.Collections.ICollection System.Collections.IDictionary.Keys
{
get
{
return GetKeyListHelper();
}
}
IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys
{
get
{
return GetKeyListHelper();
}
}
// Returns a collection representing the values of this sorted list. This
// method returns the same object as GetValueList, but typed as an
// ICollection instead of an IList.
//
public IList<TValue> Values
{
get
{
return GetValueListHelper();
}
}
ICollection<TValue> IDictionary<TKey, TValue>.Values
{
get
{
return GetValueListHelper();
}
}
System.Collections.ICollection System.Collections.IDictionary.Values
{
get
{
return GetValueListHelper();
}
}
IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values
{
get
{
return GetValueListHelper();
}
}
private KeyList GetKeyListHelper()
{
if (_keyList == null)
_keyList = new KeyList(this);
return _keyList;
}
private ValueList GetValueListHelper()
{
if (_valueList == null)
_valueList = new ValueList(this);
return _valueList;
}
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get { return false; }
}
bool System.Collections.IDictionary.IsReadOnly
{
get { return false; }
}
bool System.Collections.IDictionary.IsFixedSize
{
get { return false; }
}
bool System.Collections.ICollection.IsSynchronized
{
get { return false; }
}
// Synchronization root for this object.
Object System.Collections.ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
System.Threading.Interlocked.CompareExchange(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
// Removes all entries from this sorted list.
public void Clear()
{
// clear does not change the capacity
_version++;
// Don't need to doc this but we clear the elements so that the gc can reclaim the references.
Array.Clear(_keys, 0, _size);
Array.Clear(_values, 0, _size);
_size = 0;
}
bool System.Collections.IDictionary.Contains(Object key)
{
if (IsCompatibleKey(key))
{
return ContainsKey((TKey)key);
}
return false;
}
// Checks if this sorted list contains an entry with the given key.
//
public bool ContainsKey(TKey key)
{
return IndexOfKey(key) >= 0;
}
// Checks if this sorted list contains an entry with the given value. The
// values of the entries of the sorted list are compared to the given value
// using the Object.Equals method. This method performs a linear
// search and is substantially slower than the Contains
// method.
//
public bool ContainsValue(TValue value)
{
return IndexOfValue(value) >= 0;
}
// Copies the values in this SortedList to an array.
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
if (array == null)
{
throw new ArgumentNullException("array");
}
if (arrayIndex < 0 || arrayIndex > array.Length)
{
throw new ArgumentOutOfRangeException("arrayIndex", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - arrayIndex < Count)
{
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
}
for (int i = 0; i < Count; i++)
{
KeyValuePair<TKey, TValue> entry = new KeyValuePair<TKey, TValue>(_keys[i], _values[i]);
array[arrayIndex + i] = entry;
}
}
void System.Collections.ICollection.CopyTo(Array array, int arrayIndex)
{
if (array == null)
{
throw new ArgumentNullException("array");
}
if (array.Rank != 1)
{
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported);
}
if (array.GetLowerBound(0) != 0)
{
throw new ArgumentException(SR.Arg_NonZeroLowerBound);
}
if (arrayIndex < 0 || arrayIndex > array.Length)
{
throw new ArgumentOutOfRangeException("arrayIndex", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - arrayIndex < Count)
{
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
}
KeyValuePair<TKey, TValue>[] keyValuePairArray = array as KeyValuePair<TKey, TValue>[];
if (keyValuePairArray != null)
{
for (int i = 0; i < Count; i++)
{
keyValuePairArray[i + arrayIndex] = new KeyValuePair<TKey, TValue>(_keys[i], _values[i]);
}
}
else
{
object[] objects = array as object[];
if (objects == null)
{
throw new ArgumentException(SR.Argument_InvalidArrayType);
}
try
{
for (int i = 0; i < Count; i++)
{
objects[i + arrayIndex] = new KeyValuePair<TKey, TValue>(_keys[i], _values[i]);
}
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_InvalidArrayType);
}
}
}
private const int MaxArrayLength = 0X7FEFFFFF;
// Ensures that the capacity of this sorted list is at least the given
// minimum value. If the currect capacity of the list is less than
// min, the capacity is increased to twice the current capacity or
// to min, whichever is larger.
private void EnsureCapacity(int min)
{
int newCapacity = _keys.Length == 0 ? DefaultCapacity : _keys.Length * 2;
// Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow.
// Note that this check works even when _items.Length overflowed thanks to the (uint) cast
if ((uint)newCapacity > MaxArrayLength) newCapacity = MaxArrayLength;
if (newCapacity < min) newCapacity = min;
Capacity = newCapacity;
}
// Returns the value of the entry at the given index.
//
private TValue GetByIndex(int index)
{
if (index < 0 || index >= _size)
throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index);
return _values[index];
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return new Enumerator(this, Enumerator.KeyValuePair);
}
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return new Enumerator(this, Enumerator.KeyValuePair);
}
System.Collections.IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator()
{
return new Enumerator(this, Enumerator.DictEntry);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new Enumerator(this, Enumerator.KeyValuePair);
}
// Returns the key of the entry at the given index.
//
private TKey GetKey(int index)
{
if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index);
return _keys[index];
}
// Returns the value associated with the given key. If an entry with the
// given key is not found, the returned value is null.
//
public TValue this[TKey key]
{
get
{
int i = IndexOfKey(key);
if (i >= 0)
return _values[i];
throw new KeyNotFoundException();
// return default(TValue);
}
set
{
if (((Object)key) == null) throw new ArgumentNullException("key");
int i = Array.BinarySearch<TKey>(_keys, 0, _size, key, _comparer);
if (i >= 0)
{
_values[i] = value;
_version++;
return;
}
Insert(~i, key, value);
}
}
Object System.Collections.IDictionary.this[Object key]
{
get
{
if (IsCompatibleKey(key))
{
int i = IndexOfKey((TKey)key);
if (i >= 0)
{
return _values[i];
}
}
return null;
}
set
{
if (!IsCompatibleKey(key))
{
throw new ArgumentNullException("key");
}
if (value == null && !(default(TValue) == null))
throw new ArgumentNullException("value");
try
{
TKey tempKey = (TKey)key;
try
{
this[tempKey] = (TValue)value;
}
catch (InvalidCastException)
{
throw new ArgumentException(SR.Format(SR.Arg_WrongType, value, typeof(TValue)), "value");
}
}
catch (InvalidCastException)
{
throw new ArgumentException(SR.Format(SR.Arg_WrongType, key, typeof(TKey)), "key");
}
}
}
// Returns the index of the entry with a given key in this sorted list. The
// key is located through a binary search, and thus the average execution
// time of this method is proportional to Log2(size), where
// size is the size of this sorted list. The returned value is -1 if
// the given key does not occur in this sorted list. Null is an invalid
// key value.
//
public int IndexOfKey(TKey key)
{
if (key == null)
throw new ArgumentNullException("key");
int ret = Array.BinarySearch<TKey>(_keys, 0, _size, key, _comparer);
return ret >= 0 ? ret : -1;
}
// Returns the index of the first occurrence of an entry with a given value
// in this sorted list. The entry is located through a linear search, and
// thus the average execution time of this method is proportional to the
// size of this sorted list. The elements of the list are compared to the
// given value using the Object.Equals method.
//
public int IndexOfValue(TValue value)
{
return Array.IndexOf(_values, value, 0, _size);
}
// Inserts an entry with a given key and value at a given index.
private void Insert(int index, TKey key, TValue value)
{
if (_size == _keys.Length) EnsureCapacity(_size + 1);
if (index < _size)
{
Array.Copy(_keys, index, _keys, index + 1, _size - index);
Array.Copy(_values, index, _values, index + 1, _size - index);
}
_keys[index] = key;
_values[index] = value;
_size++;
_version++;
}
public bool TryGetValue(TKey key, out TValue value)
{
int i = IndexOfKey(key);
if (i >= 0)
{
value = _values[i];
return true;
}
value = default(TValue);
return false;
}
// Removes the entry at the given index. The size of the sorted list is
// decreased by one.
//
public void RemoveAt(int index)
{
if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index);
_size--;
if (index < _size)
{
Array.Copy(_keys, index + 1, _keys, index, _size - index);
Array.Copy(_values, index + 1, _values, index, _size - index);
}
_keys[_size] = default(TKey);
_values[_size] = default(TValue);
_version++;
}
// Removes an entry from this sorted list. If an entry with the specified
// key exists in the sorted list, it is removed. An ArgumentException is
// thrown if the key is null.
//
public bool Remove(TKey key)
{
int i = IndexOfKey(key);
if (i >= 0)
RemoveAt(i);
return i >= 0;
}
void System.Collections.IDictionary.Remove(Object key)
{
if (IsCompatibleKey(key))
{
Remove((TKey)key);
}
}
// Sets the capacity of this sorted list to the size of the sorted list.
// This method can be used to minimize a sorted list's memory overhead once
// it is known that no new elements will be added to the sorted list. To
// completely clear a sorted list and release all memory referenced by the
// sorted list, execute the following statements:
//
// SortedList.Clear();
// SortedList.TrimExcess();
//
public void TrimExcess()
{
int threshold = (int)(((double)_keys.Length) * 0.9);
if (_size < threshold)
{
Capacity = _size;
}
}
private static bool IsCompatibleKey(object key)
{
if (key == null)
{
throw new ArgumentNullException("key");
}
return (key is TKey);
}
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedListEnumerator"]/*' />
private struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, System.Collections.IDictionaryEnumerator
{
private SortedList<TKey, TValue> _sortedList;
private TKey _key;
private TValue _value;
private int _index;
private int _version;
private int _getEnumeratorRetType; // What should Enumerator.Current return?
internal const int KeyValuePair = 1;
internal const int DictEntry = 2;
internal Enumerator(SortedList<TKey, TValue> sortedList, int getEnumeratorRetType)
{
_sortedList = sortedList;
_index = 0;
_version = _sortedList._version;
_getEnumeratorRetType = getEnumeratorRetType;
_key = default(TKey);
_value = default(TValue);
}
public void Dispose()
{
_index = 0;
_key = default(TKey);
_value = default(TValue);
}
Object System.Collections.IDictionaryEnumerator.Key
{
get
{
if (_index == 0 || (_index == _sortedList.Count + 1))
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return _key;
}
}
public bool MoveNext()
{
if (_version != _sortedList._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if ((uint)_index < (uint)_sortedList.Count)
{
_key = _sortedList._keys[_index];
_value = _sortedList._values[_index];
_index++;
return true;
}
_index = _sortedList.Count + 1;
_key = default(TKey);
_value = default(TValue);
return false;
}
DictionaryEntry System.Collections.IDictionaryEnumerator.Entry
{
get
{
if (_index == 0 || (_index == _sortedList.Count + 1))
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return new DictionaryEntry(_key, _value);
}
}
public KeyValuePair<TKey, TValue> Current
{
get
{
return new KeyValuePair<TKey, TValue>(_key, _value);
}
}
Object System.Collections.IEnumerator.Current
{
get
{
if (_index == 0 || (_index == _sortedList.Count + 1))
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
if (_getEnumeratorRetType == DictEntry)
{
return new System.Collections.DictionaryEntry(_key, _value);
}
else
{
return new KeyValuePair<TKey, TValue>(_key, _value);
}
}
}
Object System.Collections.IDictionaryEnumerator.Value
{
get
{
if (_index == 0 || (_index == _sortedList.Count + 1))
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return _value;
}
}
void System.Collections.IEnumerator.Reset()
{
if (_version != _sortedList._version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
_index = 0;
_key = default(TKey);
_value = default(TValue);
}
}
private sealed class SortedListKeyEnumerator : IEnumerator<TKey>, System.Collections.IEnumerator
{
private SortedList<TKey, TValue> _sortedList;
private int _index;
private int _version;
private TKey _currentKey;
internal SortedListKeyEnumerator(SortedList<TKey, TValue> sortedList)
{
_sortedList = sortedList;
_version = sortedList._version;
}
public void Dispose()
{
_index = 0;
_currentKey = default(TKey);
}
public bool MoveNext()
{
if (_version != _sortedList._version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
if ((uint)_index < (uint)_sortedList.Count)
{
_currentKey = _sortedList._keys[_index];
_index++;
return true;
}
_index = _sortedList.Count + 1;
_currentKey = default(TKey);
return false;
}
public TKey Current
{
get
{
return _currentKey;
}
}
Object System.Collections.IEnumerator.Current
{
get
{
if (_index == 0 || (_index == _sortedList.Count + 1))
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return _currentKey;
}
}
void System.Collections.IEnumerator.Reset()
{
if (_version != _sortedList._version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
_index = 0;
_currentKey = default(TKey);
}
}
private sealed class SortedListValueEnumerator : IEnumerator<TValue>, System.Collections.IEnumerator
{
private SortedList<TKey, TValue> _sortedList;
private int _index;
private int _version;
private TValue _currentValue;
internal SortedListValueEnumerator(SortedList<TKey, TValue> sortedList)
{
_sortedList = sortedList;
_version = sortedList._version;
}
public void Dispose()
{
_index = 0;
_currentValue = default(TValue);
}
public bool MoveNext()
{
if (_version != _sortedList._version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
if ((uint)_index < (uint)_sortedList.Count)
{
_currentValue = _sortedList._values[_index];
_index++;
return true;
}
_index = _sortedList.Count + 1;
_currentValue = default(TValue);
return false;
}
public TValue Current
{
get
{
return _currentValue;
}
}
Object System.Collections.IEnumerator.Current
{
get
{
if (_index == 0 || (_index == _sortedList.Count + 1))
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return _currentValue;
}
}
void System.Collections.IEnumerator.Reset()
{
if (_version != _sortedList._version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
_index = 0;
_currentValue = default(TValue);
}
}
[DebuggerTypeProxy(typeof(DictionaryKeyCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
private sealed class KeyList : IList<TKey>, System.Collections.ICollection
{
private SortedList<TKey, TValue> _dict;
internal KeyList(SortedList<TKey, TValue> dictionary)
{
_dict = dictionary;
}
public int Count
{
get { return _dict._size; }
}
public bool IsReadOnly
{
get { return true; }
}
bool System.Collections.ICollection.IsSynchronized
{
get { return false; }
}
Object System.Collections.ICollection.SyncRoot
{
get { return ((ICollection)_dict).SyncRoot; }
}
public void Add(TKey key)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
public void Clear()
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
public bool Contains(TKey key)
{
return _dict.ContainsKey(key);
}
public void CopyTo(TKey[] array, int arrayIndex)
{
// defer error checking to Array.Copy
Array.Copy(_dict._keys, 0, array, arrayIndex, _dict.Count);
}
void System.Collections.ICollection.CopyTo(Array array, int arrayIndex)
{
if (array != null && array.Rank != 1)
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported);
try
{
// defer error checking to Array.Copy
Array.Copy(_dict._keys, 0, array, arrayIndex, _dict.Count);
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_InvalidArrayType);
}
}
public void Insert(int index, TKey value)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
public TKey this[int index]
{
get
{
return _dict.GetKey(index);
}
set
{
throw new NotSupportedException(SR.NotSupported_KeyCollectionSet);
}
}
public IEnumerator<TKey> GetEnumerator()
{
return new SortedListKeyEnumerator(_dict);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new SortedListKeyEnumerator(_dict);
}
public int IndexOf(TKey key)
{
if (((Object)key) == null)
throw new ArgumentNullException("key");
int i = Array.BinarySearch<TKey>(_dict._keys, 0,
_dict.Count, key, _dict._comparer);
if (i >= 0) return i;
return -1;
}
public bool Remove(TKey key)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
// return false;
}
public void RemoveAt(int index)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
}
[DebuggerTypeProxy(typeof(DictionaryValueCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
private sealed class ValueList : IList<TValue>, System.Collections.ICollection
{
private SortedList<TKey, TValue> _dict;
internal ValueList(SortedList<TKey, TValue> dictionary)
{
_dict = dictionary;
}
public int Count
{
get { return _dict._size; }
}
public bool IsReadOnly
{
get { return true; }
}
bool System.Collections.ICollection.IsSynchronized
{
get { return false; }
}
Object System.Collections.ICollection.SyncRoot
{
get { return ((ICollection)_dict).SyncRoot; }
}
public void Add(TValue key)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
public void Clear()
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
public bool Contains(TValue value)
{
return _dict.ContainsValue(value);
}
public void CopyTo(TValue[] array, int arrayIndex)
{
// defer error checking to Array.Copy
Array.Copy(_dict._values, 0, array, arrayIndex, _dict.Count);
}
void System.Collections.ICollection.CopyTo(Array array, int arrayIndex)
{
if (array != null && array.Rank != 1)
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported);
try
{
// defer error checking to Array.Copy
Array.Copy(_dict._values, 0, array, arrayIndex, _dict.Count);
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_InvalidArrayType);
}
}
public void Insert(int index, TValue value)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
public TValue this[int index]
{
get
{
return _dict.GetByIndex(index);
}
set
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
}
public IEnumerator<TValue> GetEnumerator()
{
return new SortedListValueEnumerator(_dict);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new SortedListValueEnumerator(_dict);
}
public int IndexOf(TValue value)
{
return Array.IndexOf(_dict._values, value, 0, _dict.Count);
}
public bool Remove(TValue value)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
// return false;
}
public void RemoveAt(int index)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
}
}
}
| |
/*--------------------------------------------------------------------------
* Nessus Report File Format for .NET
* May 8, 2014
*
* Copyright (c) 2014-2016 takutoy <takutoy@live.jp>
* https://github.com/takutoy/Nessus6Client
*
* licensed under MIT License.
* http://opensource.org/licenses/MIT
*--------------------------------------------------------------------------*/
using System;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
namespace Sussen
{
[XmlRoot("NessusClientData_v2", Namespace = "")]
public class NessusResult
{
[XmlElement("Policy")]
public NessusPolicy Policy { get; set; }
[XmlElement("Report")]
public NessusReport Report { get; set; }
public static NessusResult Load(string fname)
{
using (var fs = new FileStream(fname, FileMode.Open, FileAccess.Read, FileShare.Read))
{
return Load(fs);
}
}
public static NessusResult Load(Stream stream)
{
XmlSerializer xmlserializer = new XmlSerializer(typeof(NessusResult));
var nessus = xmlserializer.Deserialize(stream) as NessusResult;
return nessus;
}
}
[XmlRoot("Policy", Namespace = "")]
public class NessusPolicy
{
[XmlElement("policyName")]
public string PolicyName { get; set; }
[XmlElement("policyComment")]
public string PolicyComment { get; set; }
[XmlElement("Preferences")]
public NessusPolicyPreference Preferences { get; set; }
[XmlElement("PluginSelection")]
public NessusPolicyPluginSelection PluginSelection { get; set; }
}
[XmlRoot("Preferences", Namespace = "")]
public class NessusPolicyPreference
{
[XmlArray(ElementName = "ServerPreferences")]
[XmlArrayItem(ElementName = "preference", Type = typeof(NessusPolicyServerPreference))]
public NessusPolicyServerPreference[] ServerPreferences { get; set; }
[XmlArray(ElementName = "PluginsPreferences")]
[XmlArrayItem(ElementName = "item", Type = typeof(NessusPolicyPluginPreference))]
public NessusPolicyPluginPreference[] PluginPreferences { get; set; }
}
[XmlRoot("preference", Namespace = "")]
public class NessusPolicyServerPreference
{
[XmlElement("name")]
public string Name { get; set; }
[XmlElement("value")]
public string Value { get; set; }
}
[XmlRoot("item", Namespace = "")]
public class NessusPolicyPluginPreference
{
[XmlElement("pluginName")]
public string PluginName { get; set; }
[XmlElement("pluginId")]
public string PluginId { get; set; }
[XmlElement("fullName")]
public string FullName { get; set; }
[XmlElement("preferenceName")]
public string PreferenceName { get; set; }
[XmlElement("preferenceType")]
public string PreferenceType { get; set; }
[XmlElement("preferenceValues")]
public string PreferenceValues { get; set; }
[XmlElement("selectedValue")]
public string SelectedValue { get; set; }
}
[XmlRoot("PluginSelection", Namespace = "")]
public class NessusPolicyPluginSelection
{
[XmlArray(ElementName = "FamilySelection")]
[XmlArrayItem(ElementName = "FamilyItem", Type = typeof(NessusPolicyFamilyItem))]
public NessusPolicyFamilyItem[] FamilySelection { get; set; }
[XmlArray(ElementName = "IndividualPluginSelection")]
[XmlArrayItem(ElementName = "PluginItem", Type = typeof(NessusPolicyPluginItem))]
public NessusPolicyPluginItem[] IndividualPluginSelection { get; set; }
}
[XmlRoot("FamilyItem", Namespace = "")]
public class NessusPolicyFamilyItem
{
[XmlElement("FamilyName")]
public string FamilyName { get; set; }
[XmlElement("Status")]
public NessusPluginFamilySelection Status { get; set; }
}
[XmlRoot("PluginItem", Namespace = "")]
public class NessusPolicyPluginItem
{
[XmlElement("PluginId")]
public string PluginId { get; set; }
[XmlElement("PluginName")]
public string PluginName { get; set; }
[XmlElement("Family")]
public string Family { get; set; }
[XmlElement("Status")]
public NessusPluginEnabled Status { get; set; }
}
[XmlRoot("Report")]
public class NessusReport
{
[XmlAttribute("name")]
public string Name { get; set; }
[XmlElement("ReportHost")]
public NessusReportHost[] ReportHosts { get; set; }
}
[XmlRoot("ReportHost")]
public class NessusReportHost
{
[XmlAttribute("name")]
public string Name { get; set; }
[XmlArray(ElementName = "HostProperties")]
[XmlArrayItem(ElementName = "tag", Type = typeof(NessusReportHostProperty))]
public NessusReportHostProperty[] HostProperties { get; set; }
[XmlElement("ReportItem")]
public NessusReportItem[] ReportItems { get; set; }
public string IPAddress
{
get { return GetPropertyValue("host-ip"); }
}
public string FQDN
{
get { return GetPropertyValue("host-fqdn"); }
}
public string OperatingSystem
{
get { return GetPropertyValue("operating-system"); }
}
public string NetBiosName
{
get { return GetPropertyValue("netbios-name"); }
}
public string MacAddress
{
get { return GetPropertyValue("mac-address"); }
}
public string[] Traceroute
{
get
{
var traceroute = HostProperties.Where(_ => _.Name.StartsWith("traceroute-hop-")).OrderBy(_ => int.Parse(_.Name.Substring(15)));
return traceroute.Select(_ => _.Value).ToArray();
}
}
public DateTime HostStart
{
get
{
return DateTime.ParseExact(GetPropertyValue("HOST_START"), "ddd MMM d HH:mm:ss yyyy"
, System.Globalization.DateTimeFormatInfo.InvariantInfo
, System.Globalization.DateTimeStyles.AllowWhiteSpaces);
}
}
public DateTime HostEnd
{
get
{
return DateTime.ParseExact(GetPropertyValue("HOST_END"), "ddd MMM d HH:mm:ss yyyy"
, System.Globalization.DateTimeFormatInfo.InvariantInfo
, System.Globalization.DateTimeStyles.AllowWhiteSpaces);
}
}
public TimeSpan HostDuration
{
get { return HostEnd - HostStart; }
}
public string GetPropertyValue(string name)
{
var prop = HostProperties.FirstOrDefault(_ => _.Name == name);
return prop?.Value ?? string.Empty;
}
}
[XmlRoot("tag")]
public class NessusReportHostProperty
{
[XmlAttribute("name")]
public string Name { get; set; }
[XmlText]
public string Value { get; set; }
public override string ToString()
{
return string.Format("{0}/{1}", Name, Value);
}
}
[XmlRoot("ReportItem")]
public class NessusReportItem
{
[XmlAttribute("port")]
public int Port { get; set; }
[XmlAttribute("svc_name")]
public string ServiceName { get; set; }
[XmlAttribute("protocol")]
public string Protocol { get; set; }
[XmlAttribute("severity")]
public NessusSeverity Severity { get; set; }
[XmlAttribute("pluginID")]
public string PluginID { get; set; }
[XmlAttribute("pluginName")]
public string PluginName { get; set; }
[XmlAttribute("pluginFamily")]
public string PluginFamily { get; set; }
[XmlAttribute("pluginType")]
public string PluginType { get; set; }
[XmlElement("exploitability_ease")]
public string ExploitabilityEase { get; set; }
[XmlElement("vuln_publication_date")]
public string _VulnPublicationDate { get; set; }
public DateTime VulnPublicationDate
{
get
{
DateTime test;
if (DateTime.TryParseExact(_VulnPublicationDate, "yyyy/MM/dd", null, System.Globalization.DateTimeStyles.None, out test)) return test;
return DateTime.MinValue;
}
}
[XmlElement("cvss_temporal_vector")]
public string CvssTemporalVector { get; set; }
[XmlElement("solution")]
public string Solution { get; set; }
[XmlElement("cvss_temporal_score")]
public float CvssTemporalScore { get; set; }
[XmlElement("risk_factor")]
public string RiskFactor { get; set; }
[XmlElement("description")]
public string Description { get; set; }
[XmlElement("plugin_publication_date")]
public string PluginPublicationDate { get; set; }
[XmlElement("cvss_vector")]
public string CvssVector { get; set; }
[XmlElement("synopsis")]
public string Synopsis { get; set; }
[XmlElement("patch_publication_date")]
public string _PatchPublicationDate { get; set; }
public DateTime PatchPublicationDate
{
get
{
DateTime test;
if (DateTime.TryParseExact(_PatchPublicationDate, "yyyy/MM/dd", null, System.Globalization.DateTimeStyles.None, out test)) return test;
return DateTime.MinValue;
}
}
[XmlElement("see_also")]
public string[] SeeAlso { get; set; }
[XmlElement("exploit_available")]
public bool ExploitAvailable { get; set; }
[XmlElement("plugin_modification_date")]
public string _PluginModificationDate { get; set; }
public DateTime PluginModificationDate
{
get
{
DateTime test;
if (DateTime.TryParseExact(_PluginModificationDate, "yyyy/MM/dd", null, System.Globalization.DateTimeStyles.None, out test)) return test;
return DateTime.MinValue;
}
}
[XmlElement("cvss_base_score")]
public float CvssBaseScore { get; set; }
[XmlElement("bid")]
public int Bid { get; set; }
[XmlElement("xref")]
public string[] Xref { get; set; }
[XmlElement("plugin_output")]
public string PluginOutput { get; set; }
[XmlElement("plugin_version")]
public string PluginVersion { get; set; }
[XmlElement("cpe")]
public string Cpe { get; set; }
[XmlElement("cve")]
public string Cve { get; set; }
[XmlElement("cwe")]
public int Cwe { get; set; }
[XmlElement("osvdb")]
public int OsvDb { get; set; }
[XmlElement("edb-id")]
public int ExploitDb { get; set; }
[XmlElement("script_version")]
public string ScriptVersion { get; set; }
[XmlElement("d2_elliot_name")]
public string D2ElliotName { get; set; }
[XmlElement("metasploit_name")]
public string MetasploitName { get; set; }
[XmlElement("exploit_framework_canvas")]
public bool ExploitFrameworkCanvas { get; set; }
[XmlElement("exploit_framework_core")]
public bool ExploitFrameworkCore { get; set; }
[XmlElement("exploit_framework_d2_elliot")]
public bool ExploitFrameworkD2Elliot { get; set; }
[XmlElement("exploit_framework_metasploit")]
public bool ExploitFrameworkMetasploit { get; set; }
[XmlElement("fname")]
public string FileName { get; set; }
[XmlElement("fullName")]
public string FullName { get; set; }
[XmlElement("iava")]
public string Iava { get; set; }
[XmlElement("iavb")]
public string Iavb { get; set; }
[XmlElement("owasp")]
public string Owasp { get; set; }
[XmlElement("secunia")]
public string Secunia { get; set; }
}
public enum NessusSeverity
{
[XmlEnum("0")]
Information = 0,
[XmlEnum("1")]
Low = 1,
[XmlEnum("2")]
Medium = 2,
[XmlEnum("3")]
High = 3,
[XmlEnum("4")]
Critical = 4
}
public enum NessusPluginFamilySelection
{
[XmlEnum("enabled")]
Enabled,
[XmlEnum("disabled")]
Disabled,
[XmlEnum("partial")]
Partial,
}
public enum NessusPluginEnabled
{
[XmlEnum("enabled")]
Enabled,
[XmlEnum("disabled")]
Disabled,
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using Nini.Config;
using NUnit.Framework;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.CoreModules.Framework.EntityTransfer;
using OpenSim.Region.CoreModules.Framework.InventoryAccess;
using OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation;
using OpenSim.Region.CoreModules.World.Permissions;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenSim.Tests.Common;
namespace OpenSim.Region.Framework.Scenes.Tests
{
/// <summary>
/// Tests derez of scene objects.
/// </summary>
/// <remarks>
/// This is at a level above the SceneObjectBasicTests, which act on the scene directly.
/// TODO: These tests are incomplete - need to test more kinds of derez (e.g. return object).
/// </remarks>
[TestFixture]
public class SceneObjectDeRezTests : OpenSimTestCase
{
[TestFixtureSetUp]
public void FixtureInit()
{
// Don't allow tests to be bamboozled by asynchronous events. Execute everything on the same thread.
// This facility was added after the original async delete tests were written, so it may be possible now
// to not bother explicitly disabling their async (since everything will be running sync).
Util.FireAndForgetMethod = FireAndForgetMethod.RegressionTest;
}
[TestFixtureTearDown]
public void TearDown()
{
// We must set this back afterwards, otherwise later tests will fail since they're expecting multiple
// threads. Possibly, later tests should be rewritten so none of them require async stuff (which regression
// tests really shouldn't).
Util.FireAndForgetMethod = Util.DefaultFireAndForgetMethod;
}
/// <summary>
/// Test deleting an object from a scene.
/// </summary>
[Test]
public void TestDeRezSceneObject()
{
TestHelpers.InMethod();
UUID userId = UUID.Parse("10000000-0000-0000-0000-000000000001");
TestScene scene = new SceneHelpers().SetupScene();
SceneHelpers.SetupSceneModules(scene, new PermissionsModule());
TestClient client = (TestClient)SceneHelpers.AddScenePresence(scene, userId).ControllingClient;
// Turn off the timer on the async sog deleter - we'll crank it by hand for this test.
AsyncSceneObjectGroupDeleter sogd = scene.SceneObjectGroupDeleter;
sogd.Enabled = false;
SceneObjectGroup so = SceneHelpers.AddSceneObject(scene, "so1", userId);
uint soLocalId = so.LocalId;
List<uint> localIds = new List<uint>();
localIds.Add(so.LocalId);
scene.DeRezObjects(client, localIds, UUID.Zero, DeRezAction.Delete, UUID.Zero);
// Check that object isn't deleted until we crank the sogd handle.
SceneObjectPart retrievedPart = scene.GetSceneObjectPart(so.LocalId);
Assert.That(retrievedPart, Is.Not.Null);
Assert.That(retrievedPart.ParentGroup.IsDeleted, Is.False);
sogd.InventoryDeQueueAndDelete();
SceneObjectPart retrievedPart2 = scene.GetSceneObjectPart(so.LocalId);
Assert.That(retrievedPart2, Is.Null);
Assert.That(client.ReceivedKills.Count, Is.EqualTo(1));
Assert.That(client.ReceivedKills[0], Is.EqualTo(soLocalId));
}
/// <summary>
/// Test that child and root agents correctly receive KillObject notifications.
/// </summary>
[Test]
public void TestDeRezSceneObjectToAgents()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
SceneHelpers sh = new SceneHelpers();
TestScene sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000);
TestScene sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1000, 999);
// We need this so that the creation of the root client for userB in sceneB can trigger the creation of a child client in sceneA
LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule();
EntityTransferModule etmB = new EntityTransferModule();
IConfigSource config = new IniConfigSource();
IConfig modulesConfig = config.AddConfig("Modules");
modulesConfig.Set("EntityTransferModule", etmB.Name);
modulesConfig.Set("SimulationServices", lscm.Name);
SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm);
SceneHelpers.SetupSceneModules(sceneB, config, etmB);
// We need this for derez
SceneHelpers.SetupSceneModules(sceneA, new PermissionsModule());
UserAccount uaA = UserAccountHelpers.CreateUserWithInventory(sceneA, "Andy", "AAA", 0x1, "");
UserAccount uaB = UserAccountHelpers.CreateUserWithInventory(sceneA, "Brian", "BBB", 0x2, "");
TestClient clientA = (TestClient)SceneHelpers.AddScenePresence(sceneA, uaA).ControllingClient;
// This is the more long-winded route we have to take to get a child client created for userB in sceneA
// rather than just calling AddScenePresence() as for userA
AgentCircuitData acd = SceneHelpers.GenerateAgentData(uaB);
TestClient clientB = new TestClient(acd, sceneB);
List<TestClient> childClientsB = new List<TestClient>();
EntityTransferHelpers.SetupInformClientOfNeighbourTriggersNeighbourClientCreate(clientB, childClientsB);
SceneHelpers.AddScenePresence(sceneB, clientB, acd);
SceneObjectGroup so = SceneHelpers.AddSceneObject(sceneA);
uint soLocalId = so.LocalId;
sceneA.DeleteSceneObject(so, false);
Assert.That(clientA.ReceivedKills.Count, Is.EqualTo(1));
Assert.That(clientA.ReceivedKills[0], Is.EqualTo(soLocalId));
Assert.That(childClientsB[0].ReceivedKills.Count, Is.EqualTo(1));
Assert.That(childClientsB[0].ReceivedKills[0], Is.EqualTo(soLocalId));
}
/// <summary>
/// Test deleting an object from a scene where the deleter is not the owner
/// </summary>
/// <remarks>
/// This test assumes that the deleter is not a god.
/// </remarks>
[Test]
public void TestDeRezSceneObjectNotOwner()
{
TestHelpers.InMethod();
// log4net.Config.XmlConfigurator.Configure();
UUID userId = UUID.Parse("10000000-0000-0000-0000-000000000001");
UUID objectOwnerId = UUID.Parse("20000000-0000-0000-0000-000000000001");
TestScene scene = new SceneHelpers().SetupScene();
SceneHelpers.SetupSceneModules(scene, new PermissionsModule());
IClientAPI client = SceneHelpers.AddScenePresence(scene, userId).ControllingClient;
// Turn off the timer on the async sog deleter - we'll crank it by hand for this test.
AsyncSceneObjectGroupDeleter sogd = scene.SceneObjectGroupDeleter;
sogd.Enabled = false;
SceneObjectPart part
= new SceneObjectPart(objectOwnerId, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero);
part.Name = "obj1";
scene.AddNewSceneObject(new SceneObjectGroup(part), false);
List<uint> localIds = new List<uint>();
localIds.Add(part.LocalId);
scene.DeRezObjects(client, localIds, UUID.Zero, DeRezAction.Delete, UUID.Zero);
sogd.InventoryDeQueueAndDelete();
// Object should still be in the scene.
SceneObjectPart retrievedPart = scene.GetSceneObjectPart(part.LocalId);
Assert.That(retrievedPart.UUID, Is.EqualTo(part.UUID));
}
/// <summary>
/// Test deleting an object asynchronously to user inventory.
/// </summary>
[Test]
public void TestDeleteSceneObjectAsyncToUserInventory()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
UUID agentId = UUID.Parse("00000000-0000-0000-0000-000000000001");
string myObjectName = "Fred";
TestScene scene = new SceneHelpers().SetupScene();
IConfigSource configSource = new IniConfigSource();
IConfig config = configSource.AddConfig("Modules");
config.Set("InventoryAccessModule", "BasicInventoryAccessModule");
SceneHelpers.SetupSceneModules(
scene, configSource, new object[] { new BasicInventoryAccessModule() });
SceneHelpers.SetupSceneModules(scene, new object[] { });
// Turn off the timer on the async sog deleter - we'll crank it by hand for this test.
AsyncSceneObjectGroupDeleter sogd = scene.SceneObjectGroupDeleter;
sogd.Enabled = false;
SceneObjectGroup so = SceneHelpers.AddSceneObject(scene, myObjectName, agentId);
UserAccount ua = UserAccountHelpers.CreateUserWithInventory(scene, agentId);
InventoryFolderBase folder1
= UserInventoryHelpers.CreateInventoryFolder(scene.InventoryService, ua.PrincipalID, "folder1", false);
IClientAPI client = SceneHelpers.AddScenePresence(scene, agentId).ControllingClient;
scene.DeRezObjects(client, new List<uint>() { so.LocalId }, UUID.Zero, DeRezAction.Take, folder1.ID);
SceneObjectPart retrievedPart = scene.GetSceneObjectPart(so.LocalId);
Assert.That(retrievedPart, Is.Not.Null);
Assert.That(so.IsDeleted, Is.False);
sogd.InventoryDeQueueAndDelete();
Assert.That(so.IsDeleted, Is.True);
SceneObjectPart retrievedPart2 = scene.GetSceneObjectPart(so.LocalId);
Assert.That(retrievedPart2, Is.Null);
// SceneSetupHelpers.DeleteSceneObjectAsync(scene, part, DeRezAction.Take, userInfo.RootFolder.ID, client);
InventoryItemBase retrievedItem
= UserInventoryHelpers.GetInventoryItem(
scene.InventoryService, ua.PrincipalID, "folder1/" + myObjectName);
// Check that we now have the taken part in our inventory
Assert.That(retrievedItem, Is.Not.Null);
// Check that the taken part has actually disappeared
// SceneObjectPart retrievedPart = scene.GetSceneObjectPart(part.LocalId);
// Assert.That(retrievedPart, Is.Null);
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0.
// See THIRD-PARTY-NOTICES.TXT in the project root for license information.
using System.Diagnostics;
namespace System.Net.Http.HPack
{
internal class Huffman
{
// TODO: this can be constructed from _decodingTable
private static readonly (uint code, int bitLength)[] _encodingTable = new (uint code, int bitLength)[]
{
(0b11111111_11000000_00000000_00000000, 13),
(0b11111111_11111111_10110000_00000000, 23),
(0b11111111_11111111_11111110_00100000, 28),
(0b11111111_11111111_11111110_00110000, 28),
(0b11111111_11111111_11111110_01000000, 28),
(0b11111111_11111111_11111110_01010000, 28),
(0b11111111_11111111_11111110_01100000, 28),
(0b11111111_11111111_11111110_01110000, 28),
(0b11111111_11111111_11111110_10000000, 28),
(0b11111111_11111111_11101010_00000000, 24),
(0b11111111_11111111_11111111_11110000, 30),
(0b11111111_11111111_11111110_10010000, 28),
(0b11111111_11111111_11111110_10100000, 28),
(0b11111111_11111111_11111111_11110100, 30),
(0b11111111_11111111_11111110_10110000, 28),
(0b11111111_11111111_11111110_11000000, 28),
(0b11111111_11111111_11111110_11010000, 28),
(0b11111111_11111111_11111110_11100000, 28),
(0b11111111_11111111_11111110_11110000, 28),
(0b11111111_11111111_11111111_00000000, 28),
(0b11111111_11111111_11111111_00010000, 28),
(0b11111111_11111111_11111111_00100000, 28),
(0b11111111_11111111_11111111_11111000, 30),
(0b11111111_11111111_11111111_00110000, 28),
(0b11111111_11111111_11111111_01000000, 28),
(0b11111111_11111111_11111111_01010000, 28),
(0b11111111_11111111_11111111_01100000, 28),
(0b11111111_11111111_11111111_01110000, 28),
(0b11111111_11111111_11111111_10000000, 28),
(0b11111111_11111111_11111111_10010000, 28),
(0b11111111_11111111_11111111_10100000, 28),
(0b11111111_11111111_11111111_10110000, 28),
(0b01010000_00000000_00000000_00000000, 6),
(0b11111110_00000000_00000000_00000000, 10),
(0b11111110_01000000_00000000_00000000, 10),
(0b11111111_10100000_00000000_00000000, 12),
(0b11111111_11001000_00000000_00000000, 13),
(0b01010100_00000000_00000000_00000000, 6),
(0b11111000_00000000_00000000_00000000, 8),
(0b11111111_01000000_00000000_00000000, 11),
(0b11111110_10000000_00000000_00000000, 10),
(0b11111110_11000000_00000000_00000000, 10),
(0b11111001_00000000_00000000_00000000, 8),
(0b11111111_01100000_00000000_00000000, 11),
(0b11111010_00000000_00000000_00000000, 8),
(0b01011000_00000000_00000000_00000000, 6),
(0b01011100_00000000_00000000_00000000, 6),
(0b01100000_00000000_00000000_00000000, 6),
(0b00000000_00000000_00000000_00000000, 5),
(0b00001000_00000000_00000000_00000000, 5),
(0b00010000_00000000_00000000_00000000, 5),
(0b01100100_00000000_00000000_00000000, 6),
(0b01101000_00000000_00000000_00000000, 6),
(0b01101100_00000000_00000000_00000000, 6),
(0b01110000_00000000_00000000_00000000, 6),
(0b01110100_00000000_00000000_00000000, 6),
(0b01111000_00000000_00000000_00000000, 6),
(0b01111100_00000000_00000000_00000000, 6),
(0b10111000_00000000_00000000_00000000, 7),
(0b11111011_00000000_00000000_00000000, 8),
(0b11111111_11111000_00000000_00000000, 15),
(0b10000000_00000000_00000000_00000000, 6),
(0b11111111_10110000_00000000_00000000, 12),
(0b11111111_00000000_00000000_00000000, 10),
(0b11111111_11010000_00000000_00000000, 13),
(0b10000100_00000000_00000000_00000000, 6),
(0b10111010_00000000_00000000_00000000, 7),
(0b10111100_00000000_00000000_00000000, 7),
(0b10111110_00000000_00000000_00000000, 7),
(0b11000000_00000000_00000000_00000000, 7),
(0b11000010_00000000_00000000_00000000, 7),
(0b11000100_00000000_00000000_00000000, 7),
(0b11000110_00000000_00000000_00000000, 7),
(0b11001000_00000000_00000000_00000000, 7),
(0b11001010_00000000_00000000_00000000, 7),
(0b11001100_00000000_00000000_00000000, 7),
(0b11001110_00000000_00000000_00000000, 7),
(0b11010000_00000000_00000000_00000000, 7),
(0b11010010_00000000_00000000_00000000, 7),
(0b11010100_00000000_00000000_00000000, 7),
(0b11010110_00000000_00000000_00000000, 7),
(0b11011000_00000000_00000000_00000000, 7),
(0b11011010_00000000_00000000_00000000, 7),
(0b11011100_00000000_00000000_00000000, 7),
(0b11011110_00000000_00000000_00000000, 7),
(0b11100000_00000000_00000000_00000000, 7),
(0b11100010_00000000_00000000_00000000, 7),
(0b11100100_00000000_00000000_00000000, 7),
(0b11111100_00000000_00000000_00000000, 8),
(0b11100110_00000000_00000000_00000000, 7),
(0b11111101_00000000_00000000_00000000, 8),
(0b11111111_11011000_00000000_00000000, 13),
(0b11111111_11111110_00000000_00000000, 19),
(0b11111111_11100000_00000000_00000000, 13),
(0b11111111_11110000_00000000_00000000, 14),
(0b10001000_00000000_00000000_00000000, 6),
(0b11111111_11111010_00000000_00000000, 15),
(0b00011000_00000000_00000000_00000000, 5),
(0b10001100_00000000_00000000_00000000, 6),
(0b00100000_00000000_00000000_00000000, 5),
(0b10010000_00000000_00000000_00000000, 6),
(0b00101000_00000000_00000000_00000000, 5),
(0b10010100_00000000_00000000_00000000, 6),
(0b10011000_00000000_00000000_00000000, 6),
(0b10011100_00000000_00000000_00000000, 6),
(0b00110000_00000000_00000000_00000000, 5),
(0b11101000_00000000_00000000_00000000, 7),
(0b11101010_00000000_00000000_00000000, 7),
(0b10100000_00000000_00000000_00000000, 6),
(0b10100100_00000000_00000000_00000000, 6),
(0b10101000_00000000_00000000_00000000, 6),
(0b00111000_00000000_00000000_00000000, 5),
(0b10101100_00000000_00000000_00000000, 6),
(0b11101100_00000000_00000000_00000000, 7),
(0b10110000_00000000_00000000_00000000, 6),
(0b01000000_00000000_00000000_00000000, 5),
(0b01001000_00000000_00000000_00000000, 5),
(0b10110100_00000000_00000000_00000000, 6),
(0b11101110_00000000_00000000_00000000, 7),
(0b11110000_00000000_00000000_00000000, 7),
(0b11110010_00000000_00000000_00000000, 7),
(0b11110100_00000000_00000000_00000000, 7),
(0b11110110_00000000_00000000_00000000, 7),
(0b11111111_11111100_00000000_00000000, 15),
(0b11111111_10000000_00000000_00000000, 11),
(0b11111111_11110100_00000000_00000000, 14),
(0b11111111_11101000_00000000_00000000, 13),
(0b11111111_11111111_11111111_11000000, 28),
(0b11111111_11111110_01100000_00000000, 20),
(0b11111111_11111111_01001000_00000000, 22),
(0b11111111_11111110_01110000_00000000, 20),
(0b11111111_11111110_10000000_00000000, 20),
(0b11111111_11111111_01001100_00000000, 22),
(0b11111111_11111111_01010000_00000000, 22),
(0b11111111_11111111_01010100_00000000, 22),
(0b11111111_11111111_10110010_00000000, 23),
(0b11111111_11111111_01011000_00000000, 22),
(0b11111111_11111111_10110100_00000000, 23),
(0b11111111_11111111_10110110_00000000, 23),
(0b11111111_11111111_10111000_00000000, 23),
(0b11111111_11111111_10111010_00000000, 23),
(0b11111111_11111111_10111100_00000000, 23),
(0b11111111_11111111_11101011_00000000, 24),
(0b11111111_11111111_10111110_00000000, 23),
(0b11111111_11111111_11101100_00000000, 24),
(0b11111111_11111111_11101101_00000000, 24),
(0b11111111_11111111_01011100_00000000, 22),
(0b11111111_11111111_11000000_00000000, 23),
(0b11111111_11111111_11101110_00000000, 24),
(0b11111111_11111111_11000010_00000000, 23),
(0b11111111_11111111_11000100_00000000, 23),
(0b11111111_11111111_11000110_00000000, 23),
(0b11111111_11111111_11001000_00000000, 23),
(0b11111111_11111110_11100000_00000000, 21),
(0b11111111_11111111_01100000_00000000, 22),
(0b11111111_11111111_11001010_00000000, 23),
(0b11111111_11111111_01100100_00000000, 22),
(0b11111111_11111111_11001100_00000000, 23),
(0b11111111_11111111_11001110_00000000, 23),
(0b11111111_11111111_11101111_00000000, 24),
(0b11111111_11111111_01101000_00000000, 22),
(0b11111111_11111110_11101000_00000000, 21),
(0b11111111_11111110_10010000_00000000, 20),
(0b11111111_11111111_01101100_00000000, 22),
(0b11111111_11111111_01110000_00000000, 22),
(0b11111111_11111111_11010000_00000000, 23),
(0b11111111_11111111_11010010_00000000, 23),
(0b11111111_11111110_11110000_00000000, 21),
(0b11111111_11111111_11010100_00000000, 23),
(0b11111111_11111111_01110100_00000000, 22),
(0b11111111_11111111_01111000_00000000, 22),
(0b11111111_11111111_11110000_00000000, 24),
(0b11111111_11111110_11111000_00000000, 21),
(0b11111111_11111111_01111100_00000000, 22),
(0b11111111_11111111_11010110_00000000, 23),
(0b11111111_11111111_11011000_00000000, 23),
(0b11111111_11111111_00000000_00000000, 21),
(0b11111111_11111111_00001000_00000000, 21),
(0b11111111_11111111_10000000_00000000, 22),
(0b11111111_11111111_00010000_00000000, 21),
(0b11111111_11111111_11011010_00000000, 23),
(0b11111111_11111111_10000100_00000000, 22),
(0b11111111_11111111_11011100_00000000, 23),
(0b11111111_11111111_11011110_00000000, 23),
(0b11111111_11111110_10100000_00000000, 20),
(0b11111111_11111111_10001000_00000000, 22),
(0b11111111_11111111_10001100_00000000, 22),
(0b11111111_11111111_10010000_00000000, 22),
(0b11111111_11111111_11100000_00000000, 23),
(0b11111111_11111111_10010100_00000000, 22),
(0b11111111_11111111_10011000_00000000, 22),
(0b11111111_11111111_11100010_00000000, 23),
(0b11111111_11111111_11111000_00000000, 26),
(0b11111111_11111111_11111000_01000000, 26),
(0b11111111_11111110_10110000_00000000, 20),
(0b11111111_11111110_00100000_00000000, 19),
(0b11111111_11111111_10011100_00000000, 22),
(0b11111111_11111111_11100100_00000000, 23),
(0b11111111_11111111_10100000_00000000, 22),
(0b11111111_11111111_11110110_00000000, 25),
(0b11111111_11111111_11111000_10000000, 26),
(0b11111111_11111111_11111000_11000000, 26),
(0b11111111_11111111_11111001_00000000, 26),
(0b11111111_11111111_11111011_11000000, 27),
(0b11111111_11111111_11111011_11100000, 27),
(0b11111111_11111111_11111001_01000000, 26),
(0b11111111_11111111_11110001_00000000, 24),
(0b11111111_11111111_11110110_10000000, 25),
(0b11111111_11111110_01000000_00000000, 19),
(0b11111111_11111111_00011000_00000000, 21),
(0b11111111_11111111_11111001_10000000, 26),
(0b11111111_11111111_11111100_00000000, 27),
(0b11111111_11111111_11111100_00100000, 27),
(0b11111111_11111111_11111001_11000000, 26),
(0b11111111_11111111_11111100_01000000, 27),
(0b11111111_11111111_11110010_00000000, 24),
(0b11111111_11111111_00100000_00000000, 21),
(0b11111111_11111111_00101000_00000000, 21),
(0b11111111_11111111_11111010_00000000, 26),
(0b11111111_11111111_11111010_01000000, 26),
(0b11111111_11111111_11111111_11010000, 28),
(0b11111111_11111111_11111100_01100000, 27),
(0b11111111_11111111_11111100_10000000, 27),
(0b11111111_11111111_11111100_10100000, 27),
(0b11111111_11111110_11000000_00000000, 20),
(0b11111111_11111111_11110011_00000000, 24),
(0b11111111_11111110_11010000_00000000, 20),
(0b11111111_11111111_00110000_00000000, 21),
(0b11111111_11111111_10100100_00000000, 22),
(0b11111111_11111111_00111000_00000000, 21),
(0b11111111_11111111_01000000_00000000, 21),
(0b11111111_11111111_11100110_00000000, 23),
(0b11111111_11111111_10101000_00000000, 22),
(0b11111111_11111111_10101100_00000000, 22),
(0b11111111_11111111_11110111_00000000, 25),
(0b11111111_11111111_11110111_10000000, 25),
(0b11111111_11111111_11110100_00000000, 24),
(0b11111111_11111111_11110101_00000000, 24),
(0b11111111_11111111_11111010_10000000, 26),
(0b11111111_11111111_11101000_00000000, 23),
(0b11111111_11111111_11111010_11000000, 26),
(0b11111111_11111111_11111100_11000000, 27),
(0b11111111_11111111_11111011_00000000, 26),
(0b11111111_11111111_11111011_01000000, 26),
(0b11111111_11111111_11111100_11100000, 27),
(0b11111111_11111111_11111101_00000000, 27),
(0b11111111_11111111_11111101_00100000, 27),
(0b11111111_11111111_11111101_01000000, 27),
(0b11111111_11111111_11111101_01100000, 27),
(0b11111111_11111111_11111111_11100000, 28),
(0b11111111_11111111_11111101_10000000, 27),
(0b11111111_11111111_11111101_10100000, 27),
(0b11111111_11111111_11111101_11000000, 27),
(0b11111111_11111111_11111101_11100000, 27),
(0b11111111_11111111_11111110_00000000, 27),
(0b11111111_11111111_11111011_10000000, 26),
(0b11111111_11111111_11111111_11111100, 30)
};
private static readonly (int codeLength, int[] codes)[] _decodingTable = new[]
{
(5, new[] { 48, 49, 50, 97, 99, 101, 105, 111, 115, 116 }),
(6, new[] { 32, 37, 45, 46, 47, 51, 52, 53, 54, 55, 56, 57, 61, 65, 95, 98, 100, 102, 103, 104, 108, 109, 110, 112, 114, 117 }),
(7, new[] { 58, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 89, 106, 107, 113, 118, 119, 120, 121, 122 }),
(8, new[] { 38, 42, 44, 59, 88, 90 }),
(10, new[] { 33, 34, 40, 41, 63 }),
(11, new[] { 39, 43, 124 }),
(12, new[] { 35, 62 }),
(13, new[] { 0, 36, 64, 91, 93, 126 }),
(14, new[] { 94, 125 }),
(15, new[] { 60, 96, 123 }),
(19, new[] { 92, 195, 208 }),
(20, new[] { 128, 130, 131, 162, 184, 194, 224, 226 }),
(21, new[] { 153, 161, 167, 172, 176, 177, 179, 209, 216, 217, 227, 229, 230 }),
(22, new[] { 129, 132, 133, 134, 136, 146, 154, 156, 160, 163, 164, 169, 170, 173, 178, 181, 185, 186, 187, 189, 190, 196, 198, 228, 232, 233 }),
(23, new[] { 1, 135, 137, 138, 139, 140, 141, 143, 147, 149, 150, 151, 152, 155, 157, 158, 165, 166, 168, 174, 175, 180, 182, 183, 188, 191, 197, 231, 239 }),
(24, new[] { 9, 142, 144, 145, 148, 159, 171, 206, 215, 225, 236, 237 }),
(25, new[] { 199, 207, 234, 235 }),
(26, new[] { 192, 193, 200, 201, 202, 205, 210, 213, 218, 219, 238, 240, 242, 243, 255 }),
(27, new[] { 203, 204, 211, 212, 214, 221, 222, 223, 241, 244, 245, 246, 247, 248, 250, 251, 252, 253, 254 }),
(28, new[] { 2, 3, 4, 5, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26, 27, 28, 29, 30, 31, 127, 220, 249 }),
(30, new[] { 10, 13, 22, 256 })
};
public static (uint encoded, int bitLength) Encode(int data)
{
return _encodingTable[data];
}
/// <summary>
/// Decodes a Huffman encoded string from a byte array.
/// </summary>
/// <param name="src">The source byte array containing the encoded data.</param>
/// <param name="dstArray">The destination byte array to store the decoded data. This may grow if its size is insufficient.</param>
/// <returns>The number of decoded symbols.</returns>
public static int Decode(ReadOnlySpan<byte> src, ref byte[] dstArray)
{
Span<byte> dst = dstArray;
Debug.Assert(dst != null && dst.Length > 0);
int i = 0;
int j = 0;
int lastDecodedBits = 0;
while (i < src.Length)
{
// Note that if lastDecodeBits is 3 or more, then we will only get 5 bits (or less)
// from src[i]. Thus we need to read 5 bytes here to ensure that we always have
// at least 30 bits available for decoding.
// TODO ISSUE 31751: Rework this as part of Huffman perf improvements
uint next = (uint)(src[i] << 24 + lastDecodedBits);
next |= (i + 1 < src.Length ? (uint)(src[i + 1] << 16 + lastDecodedBits) : 0);
next |= (i + 2 < src.Length ? (uint)(src[i + 2] << 8 + lastDecodedBits) : 0);
next |= (i + 3 < src.Length ? (uint)(src[i + 3] << lastDecodedBits) : 0);
next |= (i + 4 < src.Length ? (uint)(src[i + 4] >> (8 - lastDecodedBits)) : 0);
uint ones = (uint)(int.MinValue >> (8 - lastDecodedBits - 1));
if (i == src.Length - 1 && lastDecodedBits > 0 && (next & ones) == ones)
{
// The remaining 7 or less bits are all 1, which is padding.
// We specifically check that lastDecodedBits > 0 because padding
// longer than 7 bits should be treated as a decoding error.
// http://httpwg.org/specs/rfc7541.html#rfc.section.5.2
break;
}
// The longest possible symbol size is 30 bits. If we're at the last 4 bytes
// of the input, we need to make sure we pass the correct number of valid bits
// left, otherwise the trailing 0s in next may form a valid symbol.
int validBits = Math.Min(30, (8 - lastDecodedBits) + (src.Length - i - 1) * 8);
int ch = DecodeValue(next, validBits, out int decodedBits);
if (ch == -1)
{
// No valid symbol could be decoded with the bits in next
throw new HuffmanDecodingException();
}
else if (ch == 256)
{
// A Huffman-encoded string literal containing the EOS symbol MUST be treated as a decoding error.
// http://httpwg.org/specs/rfc7541.html#rfc.section.5.2
throw new HuffmanDecodingException();
}
if (j == dst.Length)
{
Array.Resize(ref dstArray, dst.Length * 2);
dst = dstArray;
}
dst[j++] = (byte)ch;
// If we crossed a byte boundary, advance i so we start at the next byte that's not fully decoded.
lastDecodedBits += decodedBits;
i += lastDecodedBits / 8;
// Modulo 8 since we only care about how many bits were decoded in the last byte that we processed.
lastDecodedBits %= 8;
}
return j;
}
/// <summary>
/// Decodes a single symbol from a 32-bit word.
/// </summary>
/// <param name="data">A 32-bit word containing a Huffman encoded symbol.</param>
/// <param name="validBits">
/// The number of bits in <paramref name="data"/> that may contain an encoded symbol.
/// This is not the exact number of bits that encode the symbol. Instead, it prevents
/// decoding the lower bits of <paramref name="data"/> if they don't contain any
/// encoded data.
/// </param>
/// <param name="decodedBits">The number of bits decoded from <paramref name="data"/>.</param>
/// <returns>The decoded symbol.</returns>
internal static int DecodeValue(uint data, int validBits, out int decodedBits)
{
// The code below implements the decoding logic for a canonical Huffman code.
//
// To decode a symbol, we scan the decoding table, which is sorted by ascending symbol bit length.
// For each bit length b, we determine the maximum b-bit encoded value, plus one (that is codeMax).
// This is done with the following logic:
//
// if we're at the first entry in the table,
// codeMax = the # of symbols encoded in b bits
// else,
// left-shift codeMax by the difference between b and the previous entry's bit length,
// then increment codeMax by the # of symbols encoded in b bits
//
// Next, we look at the value v encoded in the highest b bits of data. If v is less than codeMax,
// those bits correspond to a Huffman encoded symbol. We find the corresponding decoded
// symbol in the list of values associated with bit length b in the decoding table by indexing it
// with codeMax - v.
int codeMax = 0;
for (int i = 0; i < _decodingTable.Length && _decodingTable[i].codeLength <= validBits; i++)
{
(int codeLength, int[] codes) = _decodingTable[i];
if (i > 0)
{
codeMax <<= codeLength - _decodingTable[i - 1].codeLength;
}
codeMax += codes.Length;
int mask = int.MinValue >> (codeLength - 1);
long masked = (data & mask) >> (32 - codeLength);
if (masked < codeMax)
{
decodedBits = codeLength;
return codes[codes.Length - (codeMax - masked)];
}
}
decodedBits = 0;
return -1;
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2011 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Reflection;
using System.Globalization;
using NUnit.Common;
using NUnit.Options;
using NUnit.Framework;
namespace NUnitLite.Tests
{
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NUnit.TestUtilities;
[TestFixture]
public class CommandLineTests
{
#region Argument PreProcessor Tests
[TestCase("--arg", "--arg")]
[TestCase("--ArG", "--ArG")]
[TestCase("--arg1 --arg2", "--arg1", "--arg2")]
[TestCase("--arg1 data --arg2", "--arg1", "data", "--arg2")]
[TestCase("")]
[TestCase(" ")]
[TestCase("\"--arg 1\" --arg2", "--arg 1", "--arg2")]
[TestCase("--arg1 \"--arg 2\"", "--arg1", "--arg 2")]
[TestCase("\"--arg 1\" \"--arg 2\"", "--arg 1", "--arg 2")]
[TestCase("\"--arg 1\" \"--arg 2\" arg3 \"arg 4\"", "--arg 1", "--arg 2", "arg3", "arg 4")]
[TestCase("--arg1 \"--arg 2\" arg3 \"arg 4\"", "--arg1", "--arg 2", "arg3", "arg 4")]
[TestCase("\"--arg 1\" \"--arg 2\" arg3 \"arg 4\" \"--arg 1\" \"--arg 2\" arg3 \"arg 4\"",
"--arg 1", "--arg 2", "arg3", "arg 4", "--arg 1", "--arg 2", "arg3", "arg 4")]
[TestCase("\"--arg\"", "--arg")]
[TestCase("\"--arg 1\"", "--arg 1")]
[TestCase("\"--arg abc\"", "--arg abc")]
[TestCase("\"--arg abc\"", "--arg abc")]
[TestCase("\" --arg abc \"", " --arg abc ")]
[TestCase("\"--arg=abc\"", "--arg=abc")]
[TestCase("\"--arg=aBc\"", "--arg=aBc")]
[TestCase("\"--arg = abc\"", "--arg = abc")]
[TestCase("\"--arg=abc,xyz\"", "--arg=abc,xyz")]
[TestCase("\"--arg=abc, xyz\"", "--arg=abc, xyz")]
[TestCase("\"@arg = ~ ` ! @ # $ % ^ & * ( ) _ - : ; + ' ' { } [ ] | \\ ? / . , , xYz\"",
"@arg = ~ ` ! @ # $ % ^ & * ( ) _ - : ; + ' ' { } [ ] | \\ ? / . , , xYz")]
public void GetArgsFromCommandLine(string cmdline, params string[] expectedArgs)
{
var actualArgs = CommandLineOptions.GetArgs(cmdline);
Assert.AreEqual(expectedArgs, actualArgs);
}
[TestCase("--arg1 @file1.txt --arg2", "file1.txt:--filearg1 --filearg2", "--arg1", "--filearg1", "--filearg2", "--arg2")]
[TestCase("--arg1 @file1.txt --arg2", "file1.txt:--filearg1\r\n--filearg2", "--arg1", "--filearg1", "--filearg2", "--arg2")]
[TestCase("--arg1 @file1.txt --arg2", "file1.txt:--filearg1 data", "--arg1", "--filearg1", "data", "--arg2")]
[TestCase("--arg1 @file1.txt --arg2", "file1.txt:--filearg1 \"data in quotes\"", "--arg1", "--filearg1", "data in quotes", "--arg2")]
[TestCase("--arg1 @file1.txt --arg2", "file1.txt:--filearg1 \"data in quotes with 'single' quotes\"", "--arg1", "--filearg1", "data in quotes with 'single' quotes", "--arg2")]
[TestCase("--arg1 @file1.txt --arg2", "file1.txt:--filearg1 \"data in quotes with /slashes/\"", "--arg1", "--filearg1", "data in quotes with /slashes/", "--arg2")]
[TestCase("--arg1 @file1.txt --arg2 @file2.txt", "file1.txt:--filearg1 --filearg2,file2.txt:--filearg3", "--arg1", "--filearg1", "--filearg2", "--arg2", "--filearg3")]
[TestCase("--arg1 @file1.txt --arg2", "file1.txt:", "--arg1", "--arg2")]
// Blank lines
[TestCase("--arg1 @file1.txt --arg2", "file1.txt:--fileArg1\n\n\n--fileArg2", "--arg1", "--fileArg1", "--fileArg2", "--arg2")]
[TestCase("--arg1 @file1.txt --arg2", "file1.txt:--fileArg1\n \n\t\t\n--fileArg2", "--arg1", "--fileArg1", "--fileArg2", "--arg2")]
[TestCase("--arg1 @file1.txt --arg2", "file1.txt:--fileArg1\r\n\r\n\r\n--fileArg2", "--arg1", "--fileArg1", "--fileArg2", "--arg2")]
[TestCase("--arg1 @file1.txt --arg2", "file1.txt:--fileArg1\r\n \r\n\t\t\r\n--fileArg2", "--arg1", "--fileArg1", "--fileArg2", "--arg2")]
[TestCase("--arg1 @file1.txt --arg2", "file1.txt:--filearg1 --filearg2\r\n\n--filearg3 --filearg4", "--arg1", "--filearg1", "--filearg2", "--filearg3", "--filearg4", "--arg2")]
// Comments
[TestCase("--arg1 @file1.txt --arg2", "file1.txt:--fileArg1\nThis is NOT treated as a COMMENT\n--fileArg2", "--arg1", "--fileArg1", "This", "is", "NOT", "treated", "as", "a", "COMMENT", "--fileArg2", "--arg2")]
[TestCase("--arg1 @file1.txt --arg2", "file1.txt:--fileArg1\n#This is treated as a COMMENT\n--fileArg2", "--arg1", "--fileArg1", "--fileArg2", "--arg2")]
// Nested files
[TestCase("--arg1 @file1.txt --arg2 @file2.txt", "file1.txt:--filearg1 --filearg2,file2.txt:--filearg3 @file3.txt,file3.txt:--filearg4", "--arg1", "--filearg1", "--filearg2", "--arg2", "--filearg3", "--filearg4")]
// Where clauses
[TestCase("testfile.dll @file1.txt --arg2", "file1.txt:--where test==somelongname", "testfile.dll", "--where", "test==somelongname", "--arg2")]
// NOTE: The next is not valid. Where clause is spread over several args and therefore won't parse. Quotes are required.
[TestCase("testfile.dll @file1.txt --arg2", "file1.txt:--where test == somelongname", "testfile.dll", "--where", "test", "==", "somelongname", "--arg2")]
[TestCase("testfile.dll @file1.txt --arg2",
"file1.txt:--where \"test == somelongname\"",
"testfile.dll", "--where", "test == somelongname", "--arg2")]
[TestCase("testfile.dll @file1.txt --arg2",
"file1.txt:--where\n \"test == somelongname\"",
"testfile.dll", "--where", "test == somelongname", "--arg2")]
[TestCase("testfile.dll @file1.txt --arg2",
"file1.txt:--where\n \"test == somelongname or test == /another long name/ or cat == SomeCategory\"",
"testfile.dll", "--where", "test == somelongname or test == /another long name/ or cat == SomeCategory", "--arg2")]
[TestCase("testfile.dll @file1.txt --arg2",
"file1.txt:--where\n \"test == somelongname or\ntest == /another long name/ or\ncat == SomeCategory\"",
"testfile.dll", "--where", "test == somelongname or test == /another long name/ or cat == SomeCategory", "--arg2")]
[TestCase("testfile.dll @file1.txt --arg2",
"file1.txt:--where\n \"test == somelongname ||\ntest == /another long name/ ||\ncat == SomeCategory\"",
"testfile.dll", "--where", "test == somelongname || test == /another long name/ || cat == SomeCategory", "--arg2")]
public void GetArgsFromFiles(string commandLine, string files, params string[] expectedArgs)
{
var filespecs = files.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
var testFiles = new TestFile[filespecs.Length];
for (int ix = 0; ix < filespecs.Length; ++ix)
{
var filespec = filespecs[ix];
var split = filespec.IndexOf( ':' );
if (split < 0) throw new Exception("Invalid test data");
var fileName = filespec.Substring(0, split);
var fileContent = filespec.Substring(split + 1);
testFiles[ix] = new TestFile(Path.Combine(TestContext.CurrentContext.TestDirectory, fileName), fileContent, true);
}
var options = new NUnitLiteOptions();
string[] expandedArgs;
try
{
expandedArgs = options.PreParse(CommandLineOptions.GetArgs(commandLine)).ToArray();
}
finally
{
foreach (var tf in testFiles)
tf.Dispose();
}
Assert.AreEqual(expectedArgs, expandedArgs);
Assert.Zero(options.ErrorMessages.Count);
}
[TestCase("--arg1 @file1.txt --arg2", "The file \"file1.txt\" was not found.")]
[TestCase("--arg1 @ --arg2", "You must include a file name after @.")]
public void GetArgsFromFiles_FailureTests(string args, string errorMessage)
{
var options = new NUnitLiteOptions();
options.PreParse(CommandLineOptions.GetArgs(args));
Assert.That(options.ErrorMessages, Is.EqualTo(new object[] { errorMessage }));
}
//[Test]
public void GetArgsFromFiles_NestingOverflow()
{
var options = new NUnitLiteOptions();
var args = new[] { "--arg1", "@file1.txt", "--arg2" };
var expectedErrors = new string[] { "@ nesting exceeds maximum depth of 3." };
using (new TestFile(Path.Combine(TestContext.CurrentContext.TestDirectory, "file1.txt"), "@file1.txt", true))
{
var expandedArgs = options.PreParse(args);
Assert.AreEqual(args, expandedArgs);
Assert.AreEqual(expectedErrors, options.ErrorMessages);
}
}
#endregion
#region General Tests
[Test]
public void NoInputFiles()
{
var options = new NUnitLiteOptions();
Assert.True(options.Validate());
Assert.Null(options.InputFile);
}
[TestCase("ShowHelp", "help|h")]
[TestCase("ShowVersion", "version|V")]
[TestCase("StopOnError", "stoponerror")]
[TestCase("WaitBeforeExit", "wait")]
[TestCase("NoHeader", "noheader|noh")]
[TestCase("TeamCity", "teamcity")]
public void CanRecognizeBooleanOptions(string propertyName, string pattern)
{
Console.WriteLine("Testing " + propertyName);
string[] prototypes = pattern.Split('|');
PropertyInfo property = GetPropertyInfo(propertyName);
Assert.AreEqual(typeof(bool), property.PropertyType, "Property '{0}' is wrong type", propertyName);
NUnitLiteOptions options;
foreach (string option in prototypes)
{
if (option.Length == 1)
{
options = new NUnitLiteOptions("-" + option);
Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize -" + option);
}
else
{
options = new NUnitLiteOptions("--" + option);
Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize --" + option);
}
options = new NUnitLiteOptions("/" + option);
Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize /" + option);
}
}
[TestCase("WhereClause", "where", new string[] { "cat==Fast" }, new string[0])]
[TestCase("DisplayTestLabels", "labels", new string[] { "Off", "On", "Before", "After", "All" }, new string[] { "JUNK" })]
[TestCase("OutFile", "output|out", new string[] { "output.txt" }, new string[0])]
[TestCase("ErrFile", "err", new string[] { "error.txt" }, new string[0])]
[TestCase("WorkDirectory", "work", new string[] { "results" }, new string[0])]
[TestCase("InternalTraceLevel", "trace", new string[] { "Off", "Error", "Warning", "Info", "Debug", "Verbose" }, new string[] { "JUNK" })]
public void CanRecognizeStringOptions(string propertyName, string pattern, string[] goodValues, string[] badValues)
{
string[] prototypes = pattern.Split('|');
PropertyInfo property = GetPropertyInfo(propertyName);
Assert.AreEqual(typeof(string), property.PropertyType);
foreach (string option in prototypes)
{
foreach (string value in goodValues)
{
string optionPlusValue = string.Format("--{0}:{1}", option, value);
var options = new NUnitLiteOptions(optionPlusValue);
Assert.True(options.Validate(), "Should be valid: " + optionPlusValue);
Assert.AreEqual(value, (string)property.GetValue(options, null), "Didn't recognize " + optionPlusValue);
}
foreach (string value in badValues)
{
string optionPlusValue = string.Format("--{0}:{1}", option, value);
var options = new NUnitLiteOptions(optionPlusValue);
Assert.False(options.Validate(), "Should not be valid: " + optionPlusValue);
}
}
}
[TestCase("DisplayTestLabels", "labels", new string[] { "Off", "On", "All" })]
[TestCase("InternalTraceLevel", "trace", new string[] { "Off", "Error", "Warning", "Info", "Debug", "Verbose" })]
public void CanRecognizeLowerCaseOptionValues(string propertyName, string optionName, string[] canonicalValues)
{
PropertyInfo property = GetPropertyInfo(propertyName);
Assert.AreEqual(typeof(string), property.PropertyType);
foreach (string canonicalValue in canonicalValues)
{
string lowercaseValue = canonicalValue.ToLowerInvariant();
string optionPlusValue = string.Format("--{0}:{1}", optionName, lowercaseValue);
var options = new NUnitLiteOptions(optionPlusValue);
Assert.True(options.Validate(), "Should be valid: " + optionPlusValue);
Assert.AreEqual(canonicalValue, (string)property.GetValue(options, null), "Didn't recognize " + optionPlusValue);
}
}
#if !NETSTANDARD1_3 && !NETSTANDARD1_6
[TestCase("DefaultTimeout", "timeout")]
#endif
[TestCase("RandomSeed", "seed")]
#if PARALLEL
[TestCase("NumberOfTestWorkers", "workers")]
#endif
public void CanRecognizeIntOptions(string propertyName, string pattern)
{
string[] prototypes = pattern.Split('|');
PropertyInfo property = GetPropertyInfo(propertyName);
Assert.AreEqual(typeof(int), property.PropertyType);
foreach (string option in prototypes)
{
var options = new NUnitLiteOptions("--" + option + ":42");
Assert.AreEqual(42, (int)property.GetValue(options, null), "Didn't recognize --" + option + ":text");
}
}
// [TestCase("InternalTraceLevel", "trace", typeof(InternalTraceLevel))]
// public void CanRecognizeEnumOptions(string propertyName, string pattern, Type enumType)
// {
// string[] prototypes = pattern.Split('|');
// PropertyInfo property = GetPropertyInfo(propertyName);
// Assert.IsNotNull(property, "Property {0} not found", propertyName);
// Assert.IsTrue(property.PropertyType.IsEnum, "Property {0} is not an enum", propertyName);
// Assert.AreEqual(enumType, property.PropertyType);
// foreach (string option in prototypes)
// {
// foreach (string name in Enum.GetNames(enumType))
// {
// {
// ConsoleOptions options = new ConsoleOptions("--" + option + ":" + name);
// Assert.AreEqual(name, property.GetValue(options, null).ToString(), "Didn't recognize -" + option + ":" + name);
// }
// }
// }
// }
[TestCase("--where")]
[TestCase("--output")]
[TestCase("--err")]
[TestCase("--work")]
[TestCase("--trace")]
#if !NETSTANDARD1_3 && !NETSTANDARD1_6
[TestCase("--timeout")]
#endif
public void MissingValuesAreReported(string option)
{
var options = new NUnitLiteOptions(option + "=");
Assert.False(options.Validate(), "Missing value should not be valid");
Assert.AreEqual("Missing required value for option '" + option + "'.", options.ErrorMessages[0]);
}
[Test]
public void AssemblyIsInvalidByDefault()
{
var options = new NUnitLiteOptions("nunit.tests.dll");
Assert.False(options.Validate());
Assert.AreEqual(1, options.ErrorMessages.Count);
Assert.That(options.ErrorMessages[0], Contains.Substring("Invalid entry: nunit.tests.dll"));
}
[Test]
public void MultipleAssembliesAreInvalidByDefault()
{
var options = new NUnitLiteOptions("nunit.tests.dll", "another.dll");
Assert.False(options.Validate());
Assert.AreEqual(2, options.ErrorMessages.Count);
Assert.That(options.ErrorMessages[0], Contains.Substring("Invalid entry: nunit.tests.dll"));
Assert.That(options.ErrorMessages[1], Contains.Substring("Invalid entry: another.dll"));
}
[Test]
public void AssemblyIsValidIfAllowed()
{
var options = new NUnitLiteOptions(true, "nunit.tests.dll");
Assert.True(options.Validate());
Assert.AreEqual(0, options.ErrorMessages.Count);
}
[Test]
public void MultipleAssembliesAreInvalidEvenIfOneIsAllowed()
{
var options = new NUnitLiteOptions(true, "nunit.tests.dll", "another.dll");
Assert.False(options.Validate());
Assert.AreEqual(1, options.ErrorMessages.Count);
Assert.That(options.ErrorMessages[0], Contains.Substring("Invalid entry: another.dll"));
}
[Test]
public void InvalidOption()
{
var options = new NUnitLiteOptions("-asembly:nunit.tests.dll");
Assert.False(options.Validate());
Assert.AreEqual(1, options.ErrorMessages.Count);
Assert.AreEqual("Invalid argument: -asembly:nunit.tests.dll", options.ErrorMessages[0]);
}
[Test]
public void InvalidCommandLineParms()
{
var options = new NUnitLiteOptions("-garbage:TestFixture", "-assembly:Tests.dll");
Assert.False(options.Validate());
Assert.AreEqual(2, options.ErrorMessages.Count);
Assert.AreEqual("Invalid argument: -garbage:TestFixture", options.ErrorMessages[0]);
Assert.AreEqual("Invalid argument: -assembly:Tests.dll", options.ErrorMessages[1]);
}
#endregion
#region Timeout Option
[Test]
public void TimeoutIsMinusOneIfNoOptionIsProvided()
{
var options = new NUnitLiteOptions();
Assert.True(options.Validate());
Assert.AreEqual(-1, options.DefaultTimeout);
}
#if !NETSTANDARD1_3 && !NETSTANDARD1_6
[Test]
public void TimeoutThrowsExceptionIfOptionHasNoValue()
{
Assert.Throws<OptionException>(() => new NUnitLiteOptions("-timeout"));
}
[Test]
public void TimeoutParsesIntValueCorrectly()
{
var options = new NUnitLiteOptions("-timeout:5000");
Assert.True(options.Validate());
Assert.AreEqual(5000, options.DefaultTimeout);
}
[Test]
public void TimeoutCausesErrorIfValueIsNotInteger()
{
var options = new NUnitLiteOptions("-timeout:abc");
Assert.False(options.Validate());
Assert.AreEqual(-1, options.DefaultTimeout);
}
#endif
#endregion
#region EngineResult Option
[Test]
public void FileNameWithoutResultOptionLooksLikeParameter()
{
var options = new NUnitLiteOptions(true, "results.xml");
Assert.True(options.Validate());
Assert.AreEqual(0, options.ErrorMessages.Count);
//Assert.That(options.ErrorMessages[0], Contains.Substring("Invalid entry: results.xml"));
Assert.AreEqual("results.xml", options.InputFile);
}
[Test]
public void ResultOptionWithFilePath()
{
var options = new NUnitLiteOptions("-result:results.xml");
Assert.True(options.Validate());
OutputSpecification spec = options.ResultOutputSpecifications[0];
Assert.AreEqual("results.xml", spec.OutputPath);
Assert.AreEqual("nunit3", spec.Format);
}
[Test]
public void ResultOptionWithFilePathAndFormat()
{
var options = new NUnitLiteOptions("-result:results.xml;format=nunit2");
Assert.True(options.Validate());
OutputSpecification spec = options.ResultOutputSpecifications[0];
Assert.AreEqual("results.xml", spec.OutputPath);
Assert.AreEqual("nunit2", spec.Format);
}
[Test]
public void ResultOptionWithoutFileNameIsInvalid()
{
var options = new NUnitLiteOptions("-result:");
Assert.False(options.Validate(), "Should not be valid");
Assert.AreEqual(1, options.ErrorMessages.Count, "An error was expected");
}
[Test]
public void ResultOptionMayBeRepeated()
{
var options = new NUnitLiteOptions("-result:results.xml", "-result:nunit2results.xml;format=nunit2");
Assert.True(options.Validate(), "Should be valid");
var specs = options.ResultOutputSpecifications;
Assert.That(specs, Has.Count.EqualTo(2));
var spec1 = specs[0];
Assert.AreEqual("results.xml", spec1.OutputPath);
Assert.AreEqual("nunit3", spec1.Format);
var spec2 = specs[1];
Assert.AreEqual("nunit2results.xml", spec2.OutputPath);
Assert.AreEqual("nunit2", spec2.Format);
}
[Test]
public void DefaultResultSpecification()
{
var options = new NUnitLiteOptions();
Assert.AreEqual(1, options.ResultOutputSpecifications.Count);
var spec = options.ResultOutputSpecifications[0];
Assert.AreEqual("TestResult.xml", spec.OutputPath);
Assert.AreEqual("nunit3", spec.Format);
}
[Test]
public void NoResultSuppressesDefaultResultSpecification()
{
var options = new NUnitLiteOptions("-noresult");
Assert.AreEqual(0, options.ResultOutputSpecifications.Count);
}
[Test]
public void NoResultSuppressesAllResultSpecifications()
{
var options = new NUnitLiteOptions("-result:results.xml", "-noresult", "-result:nunit2results.xml;format=nunit2");
Assert.AreEqual(0, options.ResultOutputSpecifications.Count);
}
[Test]
public void InvalidResultSpecRecordsError()
{
var options = new NUnitLiteOptions("test.dll", "-result:userspecifed.xml;format=nunit2;format=nunit3");
Assert.That(options.ResultOutputSpecifications, Has.Exactly(1).Items
.And.Exactly(1).Property(nameof(OutputSpecification.OutputPath)).EqualTo("TestResult.xml"));
Assert.That(options.ErrorMessages, Has.Exactly(1).Contains("invalid output spec").IgnoreCase);
}
#endregion
#region Explore Option
[Test]
public void ExploreOptionWithoutPath()
{
var options = new NUnitLiteOptions("-explore");
Assert.True(options.Validate());
Assert.True(options.Explore);
}
[Test]
public void ExploreOptionWithFilePath()
{
var options = new NUnitLiteOptions("-explore:results.xml");
Assert.True(options.Validate());
Assert.True(options.Explore);
OutputSpecification spec = options.ExploreOutputSpecifications[0];
Assert.AreEqual("results.xml", spec.OutputPath);
Assert.AreEqual("nunit3", spec.Format);
}
[Test]
public void ExploreOptionWithFilePathAndFormat()
{
var options = new NUnitLiteOptions("-explore:results.xml;format=cases");
Assert.True(options.Validate());
Assert.True(options.Explore);
OutputSpecification spec = options.ExploreOutputSpecifications[0];
Assert.AreEqual("results.xml", spec.OutputPath);
Assert.AreEqual("cases", spec.Format);
}
[Test]
public void ExploreOptionWithFilePathUsingEqualSign()
{
var options = new NUnitLiteOptions("-explore=C:/nunit/tests/bin/Debug/console-test.xml");
Assert.True(options.Validate());
Assert.True(options.Explore);
Assert.AreEqual("C:/nunit/tests/bin/Debug/console-test.xml", options.ExploreOutputSpecifications[0].OutputPath);
}
[TestCase(true, null, true)]
[TestCase(false, null, false)]
[TestCase(true, false, true)]
[TestCase(false, false, false)]
[TestCase(true, true, true)]
[TestCase(false, true, true)]
public void ShouldSetTeamCityFlagAccordingToArgsAndDefaults(bool hasTeamcityInCmd, bool? defaultTeamcity, bool expectedTeamCity)
{
// Given
List<string> args = new List<string> { "tests.dll" };
if (hasTeamcityInCmd)
{
args.Add("--teamcity");
}
CommandLineOptions options;
if (defaultTeamcity.HasValue)
{
options = new NUnitLiteOptions(new DefaultOptionsProviderStub(defaultTeamcity.Value), args.ToArray());
}
else
{
options = new NUnitLiteOptions(args.ToArray());
}
// When
var actualTeamCity = options.TeamCity;
// Then
Assert.AreEqual(actualTeamCity, expectedTeamCity);
}
#endregion
#region Test Parameters
[Test]
public void SingleTestParameter()
{
var options = new NUnitLiteOptions("--params=X=5");
Assert.That(options.ErrorMessages, Is.Empty);
Assert.That(options.TestParameters, Is.EqualTo(new Dictionary<string, string> { {"X", "5" } }));
}
[Test]
public void TwoTestParametersInOneOption()
{
var options = new NUnitLiteOptions("--params:X=5;Y=7");
Assert.That(options.ErrorMessages, Is.Empty);
Assert.That(options.TestParameters, Is.EqualTo(new Dictionary<string, string> { { "X", "5" }, { "Y", "7" } }));
}
[Test]
public void TwoTestParametersInSeparateOptions()
{
var options = new NUnitLiteOptions("-p:X=5", "-p:Y=7");
Assert.That(options.ErrorMessages, Is.Empty);
Assert.That(options.TestParameters, Is.EqualTo(new Dictionary<string, string> { { "X", "5" }, { "Y", "7" } }));
}
[Test]
public void ThreeTestParametersInTwoOptions()
{
var options = new NUnitLiteOptions("--params:X=5;Y=7", "-p:Z=3");
Assert.That(options.ErrorMessages, Is.Empty);
Assert.That(options.TestParameters, Is.EqualTo(new Dictionary<string, string> { { "X", "5" }, { "Y", "7" }, { "Z", "3" } }));
}
[Test]
public void ParameterWithoutEqualSignIsInvalid()
{
var options = new NUnitLiteOptions("--params=X5");
Assert.That(options.ErrorMessages.Count, Is.EqualTo(1));
}
[Test]
public void DisplayTestParameters()
{
if (TestContext.Parameters.Count == 0)
{
Console.WriteLine("No Test Parameters were passed");
return;
}
Console.WriteLine("Test Parameters---");
foreach (var name in TestContext.Parameters.Names)
Console.WriteLine(" Name: {0} Value: {1}", name, TestContext.Parameters[name]);
}
#endregion
#region Helper Methods
//private static FieldInfo GetFieldInfo(string fieldName)
//{
// FieldInfo field = typeof(NUnitLiteOptions).GetField(fieldName);
// Assert.IsNotNull(field, "The field '{0}' is not defined", fieldName);
// return field;
//}
private static PropertyInfo GetPropertyInfo(string propertyName)
{
PropertyInfo property = typeof(NUnitLiteOptions).GetProperty(propertyName);
Assert.IsNotNull(property, "The property '{0}' is not defined", propertyName);
return property;
}
#endregion
internal sealed class DefaultOptionsProviderStub : IDefaultOptionsProvider
{
public DefaultOptionsProviderStub(bool teamCity)
{
TeamCity = teamCity;
}
public bool TeamCity { get; private set; }
}
}
}
| |
using Android.Runtime;
using System;
using System.Collections;
using System.Collections.Generic;
namespace Com.Baidu.Platform.Comapi.Basestruct
{
public partial class GeoPoint : Java.Lang.Object { };
}
namespace Com.Baidu.Platform.Comapi.Map.Base
{
public abstract partial class SDKLayerImageBase : SDKLayerBase
{
//public SDKLayerImageBase() { }
protected SDKLayerImageBase(IntPtr javaReference, JniHandleOwnership transfer, bool imknown) : base(javaReference, transfer, imknown) { }
}
public abstract partial class SDKLayerBase : Com.Baidu.Mapapi.Map.Overlay
{
//public SDKLayerBase() { }
protected SDKLayerBase(IntPtr javaReference, JniHandleOwnership transfer, bool imknown) : base(javaReference, transfer, imknown) { }
}
public abstract partial class Overlay : Java.Lang.Object
{
protected Overlay(IntPtr javaReference, JniHandleOwnership transfer, bool imknown) : base(javaReference, transfer) { }
}
public partial class SDKLayerDataModelImageBase : SDKLayerDataModelBase
{
}
public partial class SDKLayerDataModelBase : Java.Lang.Object
{
}
}
namespace Com.Baidu.Mapapi.Map
{
public abstract partial class Overlay : Com.Baidu.Platform.Comapi.Map.Base.Overlay
{
protected Overlay(IntPtr javaReference, JniHandleOwnership transfer, bool imknown) : base(javaReference, transfer, imknown) { }
}
public partial class MapView : global::Android.Views.ViewGroup
{
}
public partial class OverlayItem : Com.Baidu.Platform.Comapi.Map.Base.SDKLayerDataModelImageBase
{
}
// Metadata.xml XPath class reference: path="/api/package[@name='com.baidu.mapapi.map']/class[@name='ItemizedOverlay']"
[global::Android.Runtime.Register("com/baidu/mapapi/map/ItemizedOverlay", DoNotGenerateAcw = true)]
public partial class ItemizedOverlay<T> : Com.Baidu.Platform.Comapi.Map.Base.SDKLayerImageBase, Java.Util.IComparator
where T : Com.Baidu.Mapapi.Map.OverlayItem
{
internal static new IntPtr java_class_handle;
internal static new IntPtr class_ref
{
get
{
return JNIEnv.FindClass("com/baidu/mapapi/map/ItemizedOverlay", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass
{
get { return class_ref; }
}
protected override global::System.Type ThresholdType
{
get { return typeof(ItemizedOverlay<T>); }
}
protected ItemizedOverlay(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer, true) { }
static IntPtr id_ctor_Landroid_graphics_drawable_Drawable_Lcom_baidu_mapapi_map_MapView_;
// Metadata.xml XPath constructor reference: path="/api/package[@name='com.baidu.mapapi.map']/class[@name='ItemizedOverlay']/constructor[@name='ItemizedOverlay' and count(parameter)=2 and parameter[1][@type='android.graphics.drawable.Drawable'] and parameter[2][@type='com.baidu.mapapi.map.MapView']]"
[Register(".ctor", "(Landroid/graphics/drawable/Drawable;Lcom/baidu/mapapi/map/MapView;)V", "")]
public ItemizedOverlay(global::Android.Graphics.Drawables.Drawable p0, global::Com.Baidu.Mapapi.Map.MapView p1)
: base(IntPtr.Zero, JniHandleOwnership.DoNotTransfer, true)
{
if (Handle != IntPtr.Zero)
return;
if (GetType() != typeof(ItemizedOverlay<T>))
{
SetHandle(
global::Android.Runtime.JNIEnv.StartCreateInstance(GetType(), "(Landroid/graphics/drawable/Drawable;Lcom/baidu/mapapi/map/MapView;)V", new JValue(p0), new JValue(p1)),
JniHandleOwnership.TransferLocalRef);
global::Android.Runtime.JNIEnv.FinishCreateInstance(Handle, "(Landroid/graphics/drawable/Drawable;Lcom/baidu/mapapi/map/MapView;)V", new JValue(p0), new JValue(p1));
return;
}
if (id_ctor_Landroid_graphics_drawable_Drawable_Lcom_baidu_mapapi_map_MapView_ == IntPtr.Zero)
id_ctor_Landroid_graphics_drawable_Drawable_Lcom_baidu_mapapi_map_MapView_ = JNIEnv.GetMethodID(class_ref, "<init>", "(Landroid/graphics/drawable/Drawable;Lcom/baidu/mapapi/map/MapView;)V");
SetHandle(
global::Android.Runtime.JNIEnv.StartCreateInstance(class_ref, id_ctor_Landroid_graphics_drawable_Drawable_Lcom_baidu_mapapi_map_MapView_, new JValue(p0), new JValue(p1)),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance(Handle, class_ref, id_ctor_Landroid_graphics_drawable_Drawable_Lcom_baidu_mapapi_map_MapView_, new JValue(p0), new JValue(p1));
}
static Delegate cb_getAllItem;
#pragma warning disable 0169
static Delegate GetGetAllItemHandler()
{
if (cb_getAllItem == null)
cb_getAllItem = JNINativeWrapper.CreateDelegate((Func<IntPtr, IntPtr, IntPtr>)n_GetAllItem);
return cb_getAllItem;
}
static IntPtr n_GetAllItem(IntPtr jnienv, IntPtr native__this)
{
global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T> __this = global::Java.Lang.Object.GetObject<global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T>>(jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return global::Android.Runtime.JavaList<global::Com.Baidu.Mapapi.Map.OverlayItem>.ToLocalJniHandle(__this.AllItem);
}
#pragma warning restore 0169
static IntPtr id_getAllItem;
public virtual global::System.Collections.Generic.IList<global::Com.Baidu.Mapapi.Map.OverlayItem> AllItem
{
// Metadata.xml XPath method reference: path="/api/package[@name='com.baidu.mapapi.map']/class[@name='ItemizedOverlay']/method[@name='getAllItem' and count(parameter)=0]"
[Register("getAllItem", "()Ljava/util/ArrayList;", "GetGetAllItemHandler")]
get
{
if (id_getAllItem == IntPtr.Zero)
id_getAllItem = JNIEnv.GetMethodID(class_ref, "getAllItem", "()Ljava/util/ArrayList;");
if (GetType() == ThresholdType)
return global::Android.Runtime.JavaList<global::Com.Baidu.Mapapi.Map.OverlayItem>.FromJniHandle(JNIEnv.CallObjectMethod(Handle, id_getAllItem), JniHandleOwnership.TransferLocalRef);
else
return global::Android.Runtime.JavaList<global::Com.Baidu.Mapapi.Map.OverlayItem>.FromJniHandle(JNIEnv.CallNonvirtualObjectMethod(Handle, ThresholdClass, id_getAllItem), JniHandleOwnership.TransferLocalRef);
}
}
static Delegate cb_getCenter;
#pragma warning disable 0169
static Delegate GetGetCenterHandler()
{
if (cb_getCenter == null)
cb_getCenter = JNINativeWrapper.CreateDelegate((Func<IntPtr, IntPtr, IntPtr>)n_GetCenter);
return cb_getCenter;
}
static IntPtr n_GetCenter(IntPtr jnienv, IntPtr native__this)
{
global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T> __this = global::Java.Lang.Object.GetObject<global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T>>(jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.ToLocalJniHandle(__this.Center);
}
#pragma warning restore 0169
static IntPtr id_getCenter;
public virtual global::Com.Baidu.Platform.Comapi.Basestruct.GeoPoint Center
{
// Metadata.xml XPath method reference: path="/api/package[@name='com.baidu.mapapi.map']/class[@name='ItemizedOverlay']/method[@name='getCenter' and count(parameter)=0]"
[Register("getCenter", "()Lcom/baidu/platform/comapi/basestruct/GeoPoint;", "GetGetCenterHandler")]
get
{
if (id_getCenter == IntPtr.Zero)
id_getCenter = JNIEnv.GetMethodID(class_ref, "getCenter", "()Lcom/baidu/platform/comapi/basestruct/GeoPoint;");
if (GetType() == ThresholdType)
return global::Java.Lang.Object.GetObject<global::Com.Baidu.Platform.Comapi.Basestruct.GeoPoint>(JNIEnv.CallObjectMethod(Handle, id_getCenter), JniHandleOwnership.TransferLocalRef);
else
return global::Java.Lang.Object.GetObject<global::Com.Baidu.Platform.Comapi.Basestruct.GeoPoint>(JNIEnv.CallNonvirtualObjectMethod(Handle, ThresholdClass, id_getCenter), JniHandleOwnership.TransferLocalRef);
}
}
static Delegate cb_getLatSpanE6;
#pragma warning disable 0169
static Delegate GetGetLatSpanE6Handler()
{
if (cb_getLatSpanE6 == null)
cb_getLatSpanE6 = JNINativeWrapper.CreateDelegate((Func<IntPtr, IntPtr, int>)n_GetLatSpanE6);
return cb_getLatSpanE6;
}
static int n_GetLatSpanE6(IntPtr jnienv, IntPtr native__this)
{
global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T> __this = global::Java.Lang.Object.GetObject<global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T>>(jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.LatSpanE6;
}
#pragma warning restore 0169
static IntPtr id_getLatSpanE6;
public virtual int LatSpanE6
{
// Metadata.xml XPath method reference: path="/api/package[@name='com.baidu.mapapi.map']/class[@name='ItemizedOverlay']/method[@name='getLatSpanE6' and count(parameter)=0]"
[Register("getLatSpanE6", "()I", "GetGetLatSpanE6Handler")]
get
{
if (id_getLatSpanE6 == IntPtr.Zero)
id_getLatSpanE6 = JNIEnv.GetMethodID(class_ref, "getLatSpanE6", "()I");
if (GetType() == ThresholdType)
return JNIEnv.CallIntMethod(Handle, id_getLatSpanE6);
else
return JNIEnv.CallNonvirtualIntMethod(Handle, ThresholdClass, id_getLatSpanE6);
}
}
static Delegate cb_getLonSpanE6;
#pragma warning disable 0169
static Delegate GetGetLonSpanE6Handler()
{
if (cb_getLonSpanE6 == null)
cb_getLonSpanE6 = JNINativeWrapper.CreateDelegate((Func<IntPtr, IntPtr, int>)n_GetLonSpanE6);
return cb_getLonSpanE6;
}
static int n_GetLonSpanE6(IntPtr jnienv, IntPtr native__this)
{
global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T> __this = global::Java.Lang.Object.GetObject<global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T>>(jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.LonSpanE6;
}
#pragma warning restore 0169
static IntPtr id_getLonSpanE6;
public virtual int LonSpanE6
{
// Metadata.xml XPath method reference: path="/api/package[@name='com.baidu.mapapi.map']/class[@name='ItemizedOverlay']/method[@name='getLonSpanE6' and count(parameter)=0]"
[Register("getLonSpanE6", "()I", "GetGetLonSpanE6Handler")]
get
{
if (id_getLonSpanE6 == IntPtr.Zero)
id_getLonSpanE6 = JNIEnv.GetMethodID(class_ref, "getLonSpanE6", "()I");
if (GetType() == ThresholdType)
return JNIEnv.CallIntMethod(Handle, id_getLonSpanE6);
else
return JNIEnv.CallNonvirtualIntMethod(Handle, ThresholdClass, id_getLonSpanE6);
}
}
static Delegate cb_addItem_Lcom_baidu_mapapi_map_OverlayItem_;
#pragma warning disable 0169
static Delegate GetAddItem_Lcom_baidu_mapapi_map_OverlayItem_Handler()
{
if (cb_addItem_Lcom_baidu_mapapi_map_OverlayItem_ == null)
cb_addItem_Lcom_baidu_mapapi_map_OverlayItem_ = JNINativeWrapper.CreateDelegate((Action<IntPtr, IntPtr, IntPtr>)n_AddItem_Lcom_baidu_mapapi_map_OverlayItem_);
return cb_addItem_Lcom_baidu_mapapi_map_OverlayItem_;
}
static void n_AddItem_Lcom_baidu_mapapi_map_OverlayItem_(IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T> __this = global::Java.Lang.Object.GetObject<global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T>>(jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Com.Baidu.Mapapi.Map.OverlayItem p0 = global::Java.Lang.Object.GetObject<global::Com.Baidu.Mapapi.Map.OverlayItem>(native_p0, JniHandleOwnership.DoNotTransfer);
__this.AddItem(p0);
}
#pragma warning restore 0169
static IntPtr id_addItem_Lcom_baidu_mapapi_map_OverlayItem_;
// Metadata.xml XPath method reference: path="/api/package[@name='com.baidu.mapapi.map']/class[@name='ItemizedOverlay']/method[@name='addItem' and count(parameter)=1 and parameter[1][@type='com.baidu.mapapi.map.OverlayItem']]"
[Register("addItem", "(Lcom/baidu/mapapi/map/OverlayItem;)V", "GetAddItem_Lcom_baidu_mapapi_map_OverlayItem_Handler")]
public virtual void AddItem(global::Com.Baidu.Mapapi.Map.OverlayItem p0)
{
if (id_addItem_Lcom_baidu_mapapi_map_OverlayItem_ == IntPtr.Zero)
id_addItem_Lcom_baidu_mapapi_map_OverlayItem_ = JNIEnv.GetMethodID(class_ref, "addItem", "(Lcom/baidu/mapapi/map/OverlayItem;)V");
if (GetType() == ThresholdType)
JNIEnv.CallVoidMethod(Handle, id_addItem_Lcom_baidu_mapapi_map_OverlayItem_, new JValue(p0));
else
JNIEnv.CallNonvirtualVoidMethod(Handle, ThresholdClass, id_addItem_Lcom_baidu_mapapi_map_OverlayItem_, new JValue(p0));
}
static Delegate cb_addItem_Ljava_util_List_;
#pragma warning disable 0169
static Delegate GetAddItem_Ljava_util_List_Handler()
{
if (cb_addItem_Ljava_util_List_ == null)
cb_addItem_Ljava_util_List_ = JNINativeWrapper.CreateDelegate((Action<IntPtr, IntPtr, IntPtr>)n_AddItem_Ljava_util_List_);
return cb_addItem_Ljava_util_List_;
}
static void n_AddItem_Ljava_util_List_(IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T> __this = global::Java.Lang.Object.GetObject<global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T>>(jnienv, native__this, JniHandleOwnership.DoNotTransfer);
System.Collections.Generic.IList<Com.Baidu.Mapapi.Map.OverlayItem> p0 = global::Android.Runtime.JavaList<global::Com.Baidu.Mapapi.Map.OverlayItem>.FromJniHandle(native_p0, JniHandleOwnership.DoNotTransfer);
__this.AddItem(p0);
}
#pragma warning restore 0169
static IntPtr id_addItem_Ljava_util_List_;
// Metadata.xml XPath method reference: path="/api/package[@name='com.baidu.mapapi.map']/class[@name='ItemizedOverlay']/method[@name='addItem' and count(parameter)=1 and parameter[1][@type='java.util.List']]"
[Register("addItem", "(Ljava/util/List;)V", "GetAddItem_Ljava_util_List_Handler")]
public virtual void AddItem(global::System.Collections.Generic.IList<global::Com.Baidu.Mapapi.Map.OverlayItem> p0)
{
if (id_addItem_Ljava_util_List_ == IntPtr.Zero)
id_addItem_Ljava_util_List_ = JNIEnv.GetMethodID(class_ref, "addItem", "(Ljava/util/List;)V");
IntPtr native_p0 = global::Android.Runtime.JavaList<global::Com.Baidu.Mapapi.Map.OverlayItem>.ToLocalJniHandle(p0);
if (GetType() == ThresholdType)
JNIEnv.CallVoidMethod(Handle, id_addItem_Ljava_util_List_, new JValue(native_p0));
else
JNIEnv.CallNonvirtualVoidMethod(Handle, ThresholdClass, id_addItem_Ljava_util_List_, new JValue(native_p0));
JNIEnv.DeleteLocalRef(native_p0);
}
static IntPtr id_boundCenter_Lcom_baidu_mapapi_map_OverlayItem_;
// Metadata.xml XPath method reference: path="/api/package[@name='com.baidu.mapapi.map']/class[@name='ItemizedOverlay']/method[@name='boundCenter' and count(parameter)=1 and parameter[1][@type='com.baidu.mapapi.map.OverlayItem']]"
[Register("boundCenter", "(Lcom/baidu/mapapi/map/OverlayItem;)V", "")]
protected static void BoundCenter(global::Com.Baidu.Mapapi.Map.OverlayItem p0)
{
if (id_boundCenter_Lcom_baidu_mapapi_map_OverlayItem_ == IntPtr.Zero)
id_boundCenter_Lcom_baidu_mapapi_map_OverlayItem_ = JNIEnv.GetStaticMethodID(class_ref, "boundCenter", "(Lcom/baidu/mapapi/map/OverlayItem;)V");
JNIEnv.CallStaticVoidMethod(class_ref, id_boundCenter_Lcom_baidu_mapapi_map_OverlayItem_, new JValue(p0));
}
static IntPtr id_boundCenterBottom_Lcom_baidu_mapapi_map_OverlayItem_;
// Metadata.xml XPath method reference: path="/api/package[@name='com.baidu.mapapi.map']/class[@name='ItemizedOverlay']/method[@name='boundCenterBottom' and count(parameter)=1 and parameter[1][@type='com.baidu.mapapi.map.OverlayItem']]"
[Register("boundCenterBottom", "(Lcom/baidu/mapapi/map/OverlayItem;)V", "")]
protected static void BoundCenterBottom(global::Com.Baidu.Mapapi.Map.OverlayItem p0)
{
if (id_boundCenterBottom_Lcom_baidu_mapapi_map_OverlayItem_ == IntPtr.Zero)
id_boundCenterBottom_Lcom_baidu_mapapi_map_OverlayItem_ = JNIEnv.GetStaticMethodID(class_ref, "boundCenterBottom", "(Lcom/baidu/mapapi/map/OverlayItem;)V");
JNIEnv.CallStaticVoidMethod(class_ref, id_boundCenterBottom_Lcom_baidu_mapapi_map_OverlayItem_, new JValue(p0));
}
static Delegate cb_compare_Ljava_lang_Integer_Ljava_lang_Integer_;
#pragma warning disable 0169
static Delegate GetCompare_Ljava_lang_Integer_Ljava_lang_Integer_Handler()
{
if (cb_compare_Ljava_lang_Integer_Ljava_lang_Integer_ == null)
cb_compare_Ljava_lang_Integer_Ljava_lang_Integer_ = JNINativeWrapper.CreateDelegate((Func<IntPtr, IntPtr, IntPtr, IntPtr, int>)n_Compare_Ljava_lang_Integer_Ljava_lang_Integer_);
return cb_compare_Ljava_lang_Integer_Ljava_lang_Integer_;
}
static int n_Compare_Ljava_lang_Integer_Ljava_lang_Integer_(IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1)
{
global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T> __this = global::Java.Lang.Object.GetObject<global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T>>(jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Java.Lang.Integer p0 = global::Java.Lang.Object.GetObject<global::Java.Lang.Integer>(native_p0, JniHandleOwnership.DoNotTransfer);
global::Java.Lang.Integer p1 = global::Java.Lang.Object.GetObject<global::Java.Lang.Integer>(native_p1, JniHandleOwnership.DoNotTransfer);
int __ret = __this.Compare(p0, p1);
return __ret;
}
#pragma warning restore 0169
static IntPtr id_compare_Ljava_lang_Integer_Ljava_lang_Integer_;
// Metadata.xml XPath method reference: path="/api/package[@name='com.baidu.mapapi.map']/class[@name='ItemizedOverlay']/method[@name='compare' and count(parameter)=2 and parameter[1][@type='java.lang.Integer'] and parameter[2][@type='java.lang.Integer']]"
[Register("compare", "(Ljava/lang/Integer;Ljava/lang/Integer;)I", "GetCompare_Ljava_lang_Integer_Ljava_lang_Integer_Handler")]
public virtual int Compare(global::Java.Lang.Integer p0, global::Java.Lang.Integer p1)
{
if (id_compare_Ljava_lang_Integer_Ljava_lang_Integer_ == IntPtr.Zero)
id_compare_Ljava_lang_Integer_Ljava_lang_Integer_ = JNIEnv.GetMethodID(class_ref, "compare", "(Ljava/lang/Integer;Ljava/lang/Integer;)I");
int __ret;
if (GetType() == ThresholdType)
__ret = JNIEnv.CallIntMethod(Handle, id_compare_Ljava_lang_Integer_Ljava_lang_Integer_, new JValue(p0), new JValue(p1));
else
__ret = JNIEnv.CallNonvirtualIntMethod(Handle, ThresholdClass, id_compare_Ljava_lang_Integer_Ljava_lang_Integer_, new JValue(p0), new JValue(p1));
return __ret;
}
static Delegate cb_createItem_I;
#pragma warning disable 0169
static Delegate GetCreateItem_IHandler()
{
if (cb_createItem_I == null)
cb_createItem_I = JNINativeWrapper.CreateDelegate((Func<IntPtr, IntPtr, int, IntPtr>)n_CreateItem_I);
return cb_createItem_I;
}
static IntPtr n_CreateItem_I(IntPtr jnienv, IntPtr native__this, int p0)
{
global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T> __this = global::Java.Lang.Object.GetObject<global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T>>(jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.ToLocalJniHandle(__this.CreateItem(p0));
}
#pragma warning restore 0169
static IntPtr id_createItem_I;
// Metadata.xml XPath method reference: path="/api/package[@name='com.baidu.mapapi.map']/class[@name='ItemizedOverlay']/method[@name='createItem' and count(parameter)=1 and parameter[1][@type='int']]"
[Register("createItem", "(I)Lcom/baidu/mapapi/map/OverlayItem;", "GetCreateItem_IHandler")]
protected virtual global::Java.Lang.Object CreateItem(int p0)
{
if (id_createItem_I == IntPtr.Zero)
id_createItem_I = JNIEnv.GetMethodID(class_ref, "createItem", "(I)Lcom/baidu/mapapi/map/OverlayItem;");
if (GetType() == ThresholdType)
return (Java.Lang.Object)global::Java.Lang.Object.GetObject<global::Java.Lang.Object>(JNIEnv.CallObjectMethod(Handle, id_createItem_I, new JValue(p0)), JniHandleOwnership.TransferLocalRef);
else
return (Java.Lang.Object)global::Java.Lang.Object.GetObject<global::Java.Lang.Object>(JNIEnv.CallNonvirtualObjectMethod(Handle, ThresholdClass, id_createItem_I, new JValue(p0)), JniHandleOwnership.TransferLocalRef);
}
static Delegate cb_getIndexToDraw_I;
#pragma warning disable 0169
static Delegate GetGetIndexToDraw_IHandler()
{
if (cb_getIndexToDraw_I == null)
cb_getIndexToDraw_I = JNINativeWrapper.CreateDelegate((Func<IntPtr, IntPtr, int, int>)n_GetIndexToDraw_I);
return cb_getIndexToDraw_I;
}
static int n_GetIndexToDraw_I(IntPtr jnienv, IntPtr native__this, int p0)
{
global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T> __this = global::Java.Lang.Object.GetObject<global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T>>(jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.GetIndexToDraw(p0);
}
#pragma warning restore 0169
static IntPtr id_getIndexToDraw_I;
// Metadata.xml XPath method reference: path="/api/package[@name='com.baidu.mapapi.map']/class[@name='ItemizedOverlay']/method[@name='getIndexToDraw' and count(parameter)=1 and parameter[1][@type='int']]"
[Register("getIndexToDraw", "(I)I", "GetGetIndexToDraw_IHandler")]
protected virtual int GetIndexToDraw(int p0)
{
if (id_getIndexToDraw_I == IntPtr.Zero)
id_getIndexToDraw_I = JNIEnv.GetMethodID(class_ref, "getIndexToDraw", "(I)I");
if (GetType() == ThresholdType)
return JNIEnv.CallIntMethod(Handle, id_getIndexToDraw_I, new JValue(p0));
else
return JNIEnv.CallNonvirtualIntMethod(Handle, ThresholdClass, id_getIndexToDraw_I, new JValue(p0));
}
static IntPtr id_getItem_I;
// Metadata.xml XPath method reference: path="/api/package[@name='com.baidu.mapapi.map']/class[@name='ItemizedOverlay']/method[@name='getItem' and count(parameter)=1 and parameter[1][@type='int']]"
[Register("getItem", "(I)Lcom/baidu/mapapi/map/OverlayItem;", "")]
public global::Com.Baidu.Mapapi.Map.OverlayItem GetItem(int p0)
{
if (id_getItem_I == IntPtr.Zero)
id_getItem_I = JNIEnv.GetMethodID(class_ref, "getItem", "(I)Lcom/baidu/mapapi/map/OverlayItem;");
return global::Java.Lang.Object.GetObject<global::Com.Baidu.Mapapi.Map.OverlayItem>(JNIEnv.CallObjectMethod(Handle, id_getItem_I, new JValue(p0)), JniHandleOwnership.TransferLocalRef);
}
static Delegate cb_hitTest_Lcom_baidu_mapapi_map_OverlayItem_Landroid_graphics_drawable_Drawable_II;
#pragma warning disable 0169
static Delegate GetHitTest_Lcom_baidu_mapapi_map_OverlayItem_Landroid_graphics_drawable_Drawable_IIHandler()
{
if (cb_hitTest_Lcom_baidu_mapapi_map_OverlayItem_Landroid_graphics_drawable_Drawable_II == null)
cb_hitTest_Lcom_baidu_mapapi_map_OverlayItem_Landroid_graphics_drawable_Drawable_II = JNINativeWrapper.CreateDelegate((Func<IntPtr, IntPtr, IntPtr, IntPtr, int, int, bool>)n_HitTest_Lcom_baidu_mapapi_map_OverlayItem_Landroid_graphics_drawable_Drawable_II);
return cb_hitTest_Lcom_baidu_mapapi_map_OverlayItem_Landroid_graphics_drawable_Drawable_II;
}
static bool n_HitTest_Lcom_baidu_mapapi_map_OverlayItem_Landroid_graphics_drawable_Drawable_II(IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1, int p2, int p3)
{
global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T> __this = global::Java.Lang.Object.GetObject<global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T>>(jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Com.Baidu.Mapapi.Map.OverlayItem p0 = global::Java.Lang.Object.GetObject<global::Com.Baidu.Mapapi.Map.OverlayItem>(native_p0, JniHandleOwnership.DoNotTransfer);
global::Android.Graphics.Drawables.Drawable p1 = global::Java.Lang.Object.GetObject<global::Android.Graphics.Drawables.Drawable>(native_p1, JniHandleOwnership.DoNotTransfer);
bool __ret = __this.HitTest(p0, p1, p2, p3);
return __ret;
}
#pragma warning restore 0169
static IntPtr id_hitTest_Lcom_baidu_mapapi_map_OverlayItem_Landroid_graphics_drawable_Drawable_II;
// Metadata.xml XPath method reference: path="/api/package[@name='com.baidu.mapapi.map']/class[@name='ItemizedOverlay']/method[@name='hitTest' and count(parameter)=4 and parameter[1][@type='com.baidu.mapapi.map.OverlayItem'] and parameter[2][@type='android.graphics.drawable.Drawable'] and parameter[3][@type='int'] and parameter[4][@type='int']]"
[Register("hitTest", "(Lcom/baidu/mapapi/map/OverlayItem;Landroid/graphics/drawable/Drawable;II)Z", "GetHitTest_Lcom_baidu_mapapi_map_OverlayItem_Landroid_graphics_drawable_Drawable_IIHandler")]
protected virtual bool HitTest(global::Com.Baidu.Mapapi.Map.OverlayItem p0, global::Android.Graphics.Drawables.Drawable p1, int p2, int p3)
{
if (id_hitTest_Lcom_baidu_mapapi_map_OverlayItem_Landroid_graphics_drawable_Drawable_II == IntPtr.Zero)
id_hitTest_Lcom_baidu_mapapi_map_OverlayItem_Landroid_graphics_drawable_Drawable_II = JNIEnv.GetMethodID(class_ref, "hitTest", "(Lcom/baidu/mapapi/map/OverlayItem;Landroid/graphics/drawable/Drawable;II)Z");
bool __ret;
if (GetType() == ThresholdType)
__ret = JNIEnv.CallBooleanMethod(Handle, id_hitTest_Lcom_baidu_mapapi_map_OverlayItem_Landroid_graphics_drawable_Drawable_II, new JValue(p0), new JValue(p1), new JValue(p2), new JValue(p3));
else
__ret = JNIEnv.CallNonvirtualBooleanMethod(Handle, ThresholdClass, id_hitTest_Lcom_baidu_mapapi_map_OverlayItem_Landroid_graphics_drawable_Drawable_II, new JValue(p0), new JValue(p1), new JValue(p2), new JValue(p3));
return __ret;
}
static Delegate cb_onTap_Lcom_baidu_platform_comapi_basestruct_GeoPoint_Lcom_baidu_mapapi_map_MapView_;
#pragma warning disable 0169
static Delegate GetOnTap_Lcom_baidu_platform_comapi_basestruct_GeoPoint_Lcom_baidu_mapapi_map_MapView_Handler()
{
if (cb_onTap_Lcom_baidu_platform_comapi_basestruct_GeoPoint_Lcom_baidu_mapapi_map_MapView_ == null)
cb_onTap_Lcom_baidu_platform_comapi_basestruct_GeoPoint_Lcom_baidu_mapapi_map_MapView_ = JNINativeWrapper.CreateDelegate((Func<IntPtr, IntPtr, IntPtr, IntPtr, bool>)n_OnTap_Lcom_baidu_platform_comapi_basestruct_GeoPoint_Lcom_baidu_mapapi_map_MapView_);
return cb_onTap_Lcom_baidu_platform_comapi_basestruct_GeoPoint_Lcom_baidu_mapapi_map_MapView_;
}
static bool n_OnTap_Lcom_baidu_platform_comapi_basestruct_GeoPoint_Lcom_baidu_mapapi_map_MapView_(IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1)
{
global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T> __this = global::Java.Lang.Object.GetObject<global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T>>(jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Com.Baidu.Platform.Comapi.Basestruct.GeoPoint p0 = global::Java.Lang.Object.GetObject<global::Com.Baidu.Platform.Comapi.Basestruct.GeoPoint>(native_p0, JniHandleOwnership.DoNotTransfer);
global::Com.Baidu.Mapapi.Map.MapView p1 = global::Java.Lang.Object.GetObject<global::Com.Baidu.Mapapi.Map.MapView>(native_p1, JniHandleOwnership.DoNotTransfer);
bool __ret = __this.OnTap(p0, p1);
return __ret;
}
#pragma warning restore 0169
static IntPtr id_onTap_Lcom_baidu_platform_comapi_basestruct_GeoPoint_Lcom_baidu_mapapi_map_MapView_;
// Metadata.xml XPath method reference: path="/api/package[@name='com.baidu.mapapi.map']/class[@name='ItemizedOverlay']/method[@name='onTap' and count(parameter)=2 and parameter[1][@type='com.baidu.platform.comapi.basestruct.GeoPoint'] and parameter[2][@type='com.baidu.mapapi.map.MapView']]"
[Register("onTap", "(Lcom/baidu/platform/comapi/basestruct/GeoPoint;Lcom/baidu/mapapi/map/MapView;)Z", "GetOnTap_Lcom_baidu_platform_comapi_basestruct_GeoPoint_Lcom_baidu_mapapi_map_MapView_Handler")]
public virtual bool OnTap(global::Com.Baidu.Platform.Comapi.Basestruct.GeoPoint p0, global::Com.Baidu.Mapapi.Map.MapView p1)
{
if (id_onTap_Lcom_baidu_platform_comapi_basestruct_GeoPoint_Lcom_baidu_mapapi_map_MapView_ == IntPtr.Zero)
id_onTap_Lcom_baidu_platform_comapi_basestruct_GeoPoint_Lcom_baidu_mapapi_map_MapView_ = JNIEnv.GetMethodID(class_ref, "onTap", "(Lcom/baidu/platform/comapi/basestruct/GeoPoint;Lcom/baidu/mapapi/map/MapView;)Z");
bool __ret;
if (GetType() == ThresholdType)
__ret = JNIEnv.CallBooleanMethod(Handle, id_onTap_Lcom_baidu_platform_comapi_basestruct_GeoPoint_Lcom_baidu_mapapi_map_MapView_, new JValue(p0), new JValue(p1));
else
__ret = JNIEnv.CallNonvirtualBooleanMethod(Handle, ThresholdClass, id_onTap_Lcom_baidu_platform_comapi_basestruct_GeoPoint_Lcom_baidu_mapapi_map_MapView_, new JValue(p0), new JValue(p1));
return __ret;
}
static Delegate cb_onTap_I;
#pragma warning disable 0169
static Delegate GetOnTap_IHandler()
{
if (cb_onTap_I == null)
cb_onTap_I = JNINativeWrapper.CreateDelegate((Func<IntPtr, IntPtr, int, bool>)n_OnTap_I);
return cb_onTap_I;
}
static bool n_OnTap_I(IntPtr jnienv, IntPtr native__this, int p0)
{
global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T> __this = global::Java.Lang.Object.GetObject<global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T>>(jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.OnTap(p0);
}
#pragma warning restore 0169
static IntPtr id_onTap_I;
// Metadata.xml XPath method reference: path="/api/package[@name='com.baidu.mapapi.map']/class[@name='ItemizedOverlay']/method[@name='onTap' and count(parameter)=1 and parameter[1][@type='int']]"
[Register("onTap", "(I)Z", "GetOnTap_IHandler")]
protected virtual bool OnTap(int p0)
{
if (id_onTap_I == IntPtr.Zero)
id_onTap_I = JNIEnv.GetMethodID(class_ref, "onTap", "(I)Z");
if (GetType() == ThresholdType)
return JNIEnv.CallBooleanMethod(Handle, id_onTap_I, new JValue(p0));
else
return JNIEnv.CallNonvirtualBooleanMethod(Handle, ThresholdClass, id_onTap_I, new JValue(p0));
}
static Delegate cb_removeAll;
#pragma warning disable 0169
static Delegate GetRemoveAllHandler()
{
if (cb_removeAll == null)
cb_removeAll = JNINativeWrapper.CreateDelegate((Func<IntPtr, IntPtr, bool>)n_RemoveAll);
return cb_removeAll;
}
static bool n_RemoveAll(IntPtr jnienv, IntPtr native__this)
{
global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T> __this = global::Java.Lang.Object.GetObject<global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T>>(jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.RemoveAll();
}
#pragma warning restore 0169
static IntPtr id_removeAll;
// Metadata.xml XPath method reference: path="/api/package[@name='com.baidu.mapapi.map']/class[@name='ItemizedOverlay']/method[@name='removeAll' and count(parameter)=0]"
[Register("removeAll", "()Z", "GetRemoveAllHandler")]
public virtual bool RemoveAll()
{
if (id_removeAll == IntPtr.Zero)
id_removeAll = JNIEnv.GetMethodID(class_ref, "removeAll", "()Z");
if (GetType() == ThresholdType)
return JNIEnv.CallBooleanMethod(Handle, id_removeAll);
else
return JNIEnv.CallNonvirtualBooleanMethod(Handle, ThresholdClass, id_removeAll);
}
static Delegate cb_removeItem_Lcom_baidu_mapapi_map_OverlayItem_;
#pragma warning disable 0169
static Delegate GetRemoveItem_Lcom_baidu_mapapi_map_OverlayItem_Handler()
{
if (cb_removeItem_Lcom_baidu_mapapi_map_OverlayItem_ == null)
cb_removeItem_Lcom_baidu_mapapi_map_OverlayItem_ = JNINativeWrapper.CreateDelegate((Func<IntPtr, IntPtr, IntPtr, bool>)n_RemoveItem_Lcom_baidu_mapapi_map_OverlayItem_);
return cb_removeItem_Lcom_baidu_mapapi_map_OverlayItem_;
}
static bool n_RemoveItem_Lcom_baidu_mapapi_map_OverlayItem_(IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T> __this = global::Java.Lang.Object.GetObject<global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T>>(jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Com.Baidu.Mapapi.Map.OverlayItem p0 = global::Java.Lang.Object.GetObject<global::Com.Baidu.Mapapi.Map.OverlayItem>(native_p0, JniHandleOwnership.DoNotTransfer);
bool __ret = __this.RemoveItem(p0);
return __ret;
}
#pragma warning restore 0169
static IntPtr id_removeItem_Lcom_baidu_mapapi_map_OverlayItem_;
// Metadata.xml XPath method reference: path="/api/package[@name='com.baidu.mapapi.map']/class[@name='ItemizedOverlay']/method[@name='removeItem' and count(parameter)=1 and parameter[1][@type='com.baidu.mapapi.map.OverlayItem']]"
[Register("removeItem", "(Lcom/baidu/mapapi/map/OverlayItem;)Z", "GetRemoveItem_Lcom_baidu_mapapi_map_OverlayItem_Handler")]
public virtual bool RemoveItem(global::Com.Baidu.Mapapi.Map.OverlayItem p0)
{
if (id_removeItem_Lcom_baidu_mapapi_map_OverlayItem_ == IntPtr.Zero)
id_removeItem_Lcom_baidu_mapapi_map_OverlayItem_ = JNIEnv.GetMethodID(class_ref, "removeItem", "(Lcom/baidu/mapapi/map/OverlayItem;)Z");
bool __ret;
if (GetType() == ThresholdType)
__ret = JNIEnv.CallBooleanMethod(Handle, id_removeItem_Lcom_baidu_mapapi_map_OverlayItem_, new JValue(p0));
else
__ret = JNIEnv.CallNonvirtualBooleanMethod(Handle, ThresholdClass, id_removeItem_Lcom_baidu_mapapi_map_OverlayItem_, new JValue(p0));
return __ret;
}
static Delegate cb_size;
#pragma warning disable 0169
static Delegate GetSizeHandler()
{
if (cb_size == null)
cb_size = JNINativeWrapper.CreateDelegate((Func<IntPtr, IntPtr, int>)n_Size);
return cb_size;
}
static int n_Size(IntPtr jnienv, IntPtr native__this)
{
global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T> __this = global::Java.Lang.Object.GetObject<global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T>>(jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.Size();
}
#pragma warning restore 0169
static IntPtr id_size;
// Metadata.xml XPath method reference: path="/api/package[@name='com.baidu.mapapi.map']/class[@name='ItemizedOverlay']/method[@name='size' and count(parameter)=0]"
[Register("size", "()I", "GetSizeHandler")]
public virtual int Size()
{
if (id_size == IntPtr.Zero)
id_size = JNIEnv.GetMethodID(class_ref, "size", "()I");
if (GetType() == ThresholdType)
return JNIEnv.CallIntMethod(Handle, id_size);
else
return JNIEnv.CallNonvirtualIntMethod(Handle, ThresholdClass, id_size);
}
static Delegate cb_updateItem_Lcom_baidu_mapapi_map_OverlayItem_;
#pragma warning disable 0169
static Delegate GetUpdateItem_Lcom_baidu_mapapi_map_OverlayItem_Handler()
{
if (cb_updateItem_Lcom_baidu_mapapi_map_OverlayItem_ == null)
cb_updateItem_Lcom_baidu_mapapi_map_OverlayItem_ = JNINativeWrapper.CreateDelegate((Func<IntPtr, IntPtr, IntPtr, bool>)n_UpdateItem_Lcom_baidu_mapapi_map_OverlayItem_);
return cb_updateItem_Lcom_baidu_mapapi_map_OverlayItem_;
}
static bool n_UpdateItem_Lcom_baidu_mapapi_map_OverlayItem_(IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T> __this = global::Java.Lang.Object.GetObject<global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T>>(jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Com.Baidu.Mapapi.Map.OverlayItem p0 = global::Java.Lang.Object.GetObject<global::Com.Baidu.Mapapi.Map.OverlayItem>(native_p0, JniHandleOwnership.DoNotTransfer);
bool __ret = __this.UpdateItem(p0);
return __ret;
}
#pragma warning restore 0169
static IntPtr id_updateItem_Lcom_baidu_mapapi_map_OverlayItem_;
// Metadata.xml XPath method reference: path="/api/package[@name='com.baidu.mapapi.map']/class[@name='ItemizedOverlay']/method[@name='updateItem' and count(parameter)=1 and parameter[1][@type='com.baidu.mapapi.map.OverlayItem']]"
[Register("updateItem", "(Lcom/baidu/mapapi/map/OverlayItem;)Z", "GetUpdateItem_Lcom_baidu_mapapi_map_OverlayItem_Handler")]
public virtual bool UpdateItem(global::Com.Baidu.Mapapi.Map.OverlayItem p0)
{
if (id_updateItem_Lcom_baidu_mapapi_map_OverlayItem_ == IntPtr.Zero)
id_updateItem_Lcom_baidu_mapapi_map_OverlayItem_ = JNIEnv.GetMethodID(class_ref, "updateItem", "(Lcom/baidu/mapapi/map/OverlayItem;)Z");
bool __ret;
if (GetType() == ThresholdType)
__ret = JNIEnv.CallBooleanMethod(Handle, id_updateItem_Lcom_baidu_mapapi_map_OverlayItem_, new JValue(p0));
else
__ret = JNIEnv.CallNonvirtualBooleanMethod(Handle, ThresholdClass, id_updateItem_Lcom_baidu_mapapi_map_OverlayItem_, new JValue(p0));
return __ret;
}
static Delegate cb_Compare_Ljava_lang_Object_Ljava_lang_Object_;
#pragma warning disable 0169
static Delegate GetCompare_Ljava_lang_Object_Ljava_lang_Object_Handler()
{
if (cb_Compare_Ljava_lang_Object_Ljava_lang_Object_ == null)
cb_Compare_Ljava_lang_Object_Ljava_lang_Object_ = JNINativeWrapper.CreateDelegate((Func<IntPtr, IntPtr, IntPtr, IntPtr, int>)n_Compare_Ljava_lang_Object_Ljava_lang_Object_);
return cb_Compare_Ljava_lang_Object_Ljava_lang_Object_;
}
static int n_Compare_Ljava_lang_Object_Ljava_lang_Object_(IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1)
{
global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T> __this = global::Java.Lang.Object.GetObject<global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T>>(jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Java.Lang.Object p0 = global::Java.Lang.Object.GetObject<global::Java.Lang.Object>(native_p0, JniHandleOwnership.DoNotTransfer);
global::Java.Lang.Object p1 = global::Java.Lang.Object.GetObject<global::Java.Lang.Object>(native_p1, JniHandleOwnership.DoNotTransfer);
int __ret = __this.Compare(p0, p1);
return __ret;
}
#pragma warning restore 0169
static IntPtr id_Compare_Ljava_lang_Object_Ljava_lang_Object_;
// Metadata.xml XPath method reference: path="/api/package[@name='com.baidu.mapapi.map']/class[@name='ItemizedOverlay']/method[@name='Compare' and count(parameter)=2 and parameter[1][@type='java.lang.Object'] and parameter[2][@type='java.lang.Object']]"
[Register("Compare", "(Ljava/lang/Object;Ljava/lang/Object;)I", "GetCompare_Ljava_lang_Object_Ljava_lang_Object_Handler")]
public virtual int Compare(global::Java.Lang.Object p0, global::Java.Lang.Object p1)
{
if (id_Compare_Ljava_lang_Object_Ljava_lang_Object_ == IntPtr.Zero)
id_Compare_Ljava_lang_Object_Ljava_lang_Object_ = JNIEnv.GetMethodID(class_ref, "Compare", "(Ljava/lang/Object;Ljava/lang/Object;)I");
int __ret;
if (GetType() == ThresholdType)
__ret = JNIEnv.CallIntMethod(Handle, id_Compare_Ljava_lang_Object_Ljava_lang_Object_, new JValue(p0), new JValue(p1));
else
__ret = JNIEnv.CallNonvirtualIntMethod(Handle, ThresholdClass, id_Compare_Ljava_lang_Object_Ljava_lang_Object_, new JValue(p0), new JValue(p1));
return __ret;
}
static Delegate cb_Equals_Ljava_lang_Object_;
#pragma warning disable 0169
static Delegate GetEquals_Ljava_lang_Object_Handler()
{
if (cb_Equals_Ljava_lang_Object_ == null)
cb_Equals_Ljava_lang_Object_ = JNINativeWrapper.CreateDelegate((Func<IntPtr, IntPtr, IntPtr, bool>)n_Equals_Ljava_lang_Object_);
return cb_Equals_Ljava_lang_Object_;
}
static bool n_Equals_Ljava_lang_Object_(IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T> __this = global::Java.Lang.Object.GetObject<global::Com.Baidu.Mapapi.Map.ItemizedOverlay<T>>(jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Java.Lang.Object p0 = global::Java.Lang.Object.GetObject<global::Java.Lang.Object>(native_p0, JniHandleOwnership.DoNotTransfer);
bool __ret = __this.Equals(p0);
return __ret;
}
#pragma warning restore 0169
static IntPtr id_Equals_Ljava_lang_Object_;
// Metadata.xml XPath method reference: path="/api/package[@name='com.baidu.mapapi.map']/class[@name='ItemizedOverlay']/method[@name='Equals' and count(parameter)=1 and parameter[1][@type='java.lang.Object']]"
[Register("Equals", "(Ljava/lang/Object;)Z", "GetEquals_Ljava_lang_Object_Handler")]
public override bool Equals(global::Java.Lang.Object p0)
{
if (id_Equals_Ljava_lang_Object_ == IntPtr.Zero)
id_Equals_Ljava_lang_Object_ = JNIEnv.GetMethodID(class_ref, "Equals", "(Ljava/lang/Object;)Z");
bool __ret;
if (GetType() == ThresholdType)
__ret = JNIEnv.CallBooleanMethod(Handle, id_Equals_Ljava_lang_Object_, new JValue(p0));
else
__ret = JNIEnv.CallNonvirtualBooleanMethod(Handle, ThresholdClass, id_Equals_Ljava_lang_Object_, new JValue(p0));
return __ret;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Common.Internals;
using Microsoft.WindowsAzure.Management.Network;
using Microsoft.WindowsAzure.Management.Network.Models;
namespace Microsoft.WindowsAzure.Management.Network
{
/// <summary>
/// The Network Management API includes operations for managing the client
/// root certificates for your subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj154113.aspx for
/// more information)
/// </summary>
internal partial class ClientRootCertificateOperations : IServiceOperations<NetworkManagementClient>, Microsoft.WindowsAzure.Management.Network.IClientRootCertificateOperations
{
/// <summary>
/// Initializes a new instance of the ClientRootCertificateOperations
/// class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ClientRootCertificateOperations(NetworkManagementClient client)
{
this._client = client;
}
private NetworkManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.Network.NetworkManagementClient.
/// </summary>
public NetworkManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// The Upload Client Root Certificate operation is used to upload a
/// new client root certificate to Azure. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn205129.aspx
/// for more information)
/// </summary>
/// <param name='networkName'>
/// Required. The name of the virtual network for this gateway.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Upload Client Root Certificate
/// Virtual Network Gateway operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Network.Models.GatewayOperationResponse> CreateAsync(string networkName, ClientRootCertificateCreateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (networkName == null)
{
throw new ArgumentNullException("networkName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Certificate == null)
{
throw new ArgumentNullException("parameters.Certificate");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("networkName", networkName);
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "CreateAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/networking/" + networkName.Trim() + "/gateway/clientrootcertificates";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = parameters.Certificate;
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
GatewayOperationResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new GatewayOperationResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement gatewayOperationAsyncResponseElement = responseDoc.Element(XName.Get("GatewayOperationAsyncResponse", "http://schemas.microsoft.com/windowsazure"));
if (gatewayOperationAsyncResponseElement != null)
{
XElement idElement = gatewayOperationAsyncResponseElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
result.OperationId = idInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Delete Client Root Certificate operation deletes a previously
/// uploaded client root certificate from Azure. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn205128.aspx
/// for more information)
/// </summary>
/// <param name='networkName'>
/// Required. The name of the virtual network for this gateway.
/// </param>
/// <param name='certificateThumbprint'>
/// Required. The X509 certificate thumbprint.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Network.Models.GatewayOperationResponse> DeleteAsync(string networkName, string certificateThumbprint, CancellationToken cancellationToken)
{
// Validate
if (networkName == null)
{
throw new ArgumentNullException("networkName");
}
if (certificateThumbprint == null)
{
throw new ArgumentNullException("certificateThumbprint");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("networkName", networkName);
tracingParameters.Add("certificateThumbprint", certificateThumbprint);
Tracing.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/networking/" + networkName.Trim() + "/gateway/clientrootcertificates/" + certificateThumbprint.Trim();
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.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)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
GatewayOperationResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new GatewayOperationResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement gatewayOperationAsyncResponseElement = responseDoc.Element(XName.Get("GatewayOperationAsyncResponse", "http://schemas.microsoft.com/windowsazure"));
if (gatewayOperationAsyncResponseElement != null)
{
XElement idElement = gatewayOperationAsyncResponseElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
result.OperationId = idInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Get Client Root Certificate operation returns the public
/// portion of a previously uploaded client root certificate in a
/// base-64-encoded format from Azure. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn205127.aspx
/// for more information)
/// </summary>
/// <param name='networkName'>
/// Required. The name of the virtual network for this gateway.
/// </param>
/// <param name='certificateThumbprint'>
/// Required. The X509 certificate thumbprint.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response to the Get Client Root Certificate operation.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Network.Models.ClientRootCertificateGetResponse> GetAsync(string networkName, string certificateThumbprint, CancellationToken cancellationToken)
{
// Validate
if (networkName == null)
{
throw new ArgumentNullException("networkName");
}
if (certificateThumbprint == null)
{
throw new ArgumentNullException("certificateThumbprint");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("networkName", networkName);
tracingParameters.Add("certificateThumbprint", certificateThumbprint);
Tracing.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/networking/" + networkName.Trim() + "/gateway/clientrootcertificates/" + certificateThumbprint.Trim();
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.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)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ClientRootCertificateGetResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ClientRootCertificateGetResponse();
result.Certificate = responseContent;
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The List Client Root Certificates operation returns a list of all
/// the client root certificates that are associated with the
/// specified virtual network in Azure. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn205130.aspx
/// for more information)
/// </summary>
/// <param name='networkName'>
/// Required. The name of the virtual network for this gateway.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response for the List Client Root Certificates operation.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Network.Models.ClientRootCertificateListResponse> ListAsync(string networkName, CancellationToken cancellationToken)
{
// Validate
if (networkName == null)
{
throw new ArgumentNullException("networkName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("networkName", networkName);
Tracing.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/networking/" + networkName.Trim() + "/gateway/clientrootcertificates";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.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)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ClientRootCertificateListResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ClientRootCertificateListResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement clientRootCertificatesSequenceElement = responseDoc.Element(XName.Get("ClientRootCertificates", "http://schemas.microsoft.com/windowsazure"));
if (clientRootCertificatesSequenceElement != null)
{
foreach (XElement clientRootCertificatesElement in clientRootCertificatesSequenceElement.Elements(XName.Get("ClientRootCertificate", "http://schemas.microsoft.com/windowsazure")))
{
ClientRootCertificateListResponse.ClientRootCertificate clientRootCertificateInstance = new ClientRootCertificateListResponse.ClientRootCertificate();
result.ClientRootCertificates.Add(clientRootCertificateInstance);
XElement expirationTimeElement = clientRootCertificatesElement.Element(XName.Get("ExpirationTime", "http://schemas.microsoft.com/windowsazure"));
if (expirationTimeElement != null)
{
DateTime expirationTimeInstance = DateTime.Parse(expirationTimeElement.Value, CultureInfo.InvariantCulture);
clientRootCertificateInstance.ExpirationTime = expirationTimeInstance;
}
XElement subjectElement = clientRootCertificatesElement.Element(XName.Get("Subject", "http://schemas.microsoft.com/windowsazure"));
if (subjectElement != null)
{
string subjectInstance = subjectElement.Value;
clientRootCertificateInstance.Subject = subjectInstance;
}
XElement thumbprintElement = clientRootCertificatesElement.Element(XName.Get("Thumbprint", "http://schemas.microsoft.com/windowsazure"));
if (thumbprintElement != null)
{
string thumbprintInstance = thumbprintElement.Value;
clientRootCertificateInstance.Thumbprint = thumbprintInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// --------------------------------------------------
// 3DS Theme Editor - MainWindow.Images.cs
// --------------------------------------------------
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Microsoft.Win32;
using ThemeEditor.Common.Graphics;
using ThemeEditor.WPF.Localization;
using ThemeEditor.WPF.Markup;
namespace ThemeEditor.WPF
{
partial class MainWindow
{
static readonly string[] VALID_IMAGE_EXT = { ".jpg", ".jpeg", ".png", ".bmp" };
public ICommand CopyResizeSMDHIconCommandCommand { get; private set; }
public ICommand DragImageCommand { get; set; }
public ICommand DropBottomImageCommand { get; set; }
public ICommand DropTopImageCommand { get; set; }
public ICommand DropTopAltImageCommand { get; set; }
public ICommand DropFileLargeImageCommand { get; set; }
public ICommand DropFileSmallImageCommand { get; set; }
public ICommand DropFolderOpenImageCommand { get; set; }
public ICommand DropFolderClosedImageCommand { get; set; }
public ICommand ExportImageCommand { get; private set; }
public ICommand RemoveImageCommand { get; private set; }
public ICommand ReplaceImageCommand { get; private set; }
private bool CanExecute_ImageExists(TargetImage args)
{
if (!CanExecute_ViewModelLoaded())
return false;
switch (args)
{
case TargetImage.Top:
return ViewModel.Textures.Top.Exists;
case TargetImage.Bottom:
return ViewModel.Textures.Bottom.Exists;
case TargetImage.FileLarge:
return ViewModel.Textures.FileLarge.Exists;
case TargetImage.FileSmall:
return ViewModel.Textures.FileSmall.Exists;
case TargetImage.FolderOpen:
return ViewModel.Textures.FolderOpen.Exists;
case TargetImage.FolderClosed:
return ViewModel.Textures.FolderClosed.Exists;
case TargetImage.TopAlt:
return ViewModel.Textures.TopAlt.Exists;
case TargetImage.SmallIcon:
return ViewModel.Info.SmallIcon.Exists;
case TargetImage.LargeIcon:
return ViewModel.Info.LargeIcon.Exists;
default:
throw new ArgumentOutOfRangeException();
}
}
private void DragImage_Execute(DragEventArgs args)
{
args.Handled = true;
args.Effects = DragDropEffects.None;
var hasFileDrop = args.Data.GetDataPresent(DataFormats.FileDrop);
if (hasFileDrop)
{
var file = args.Data.GetData(DataFormats.FileDrop) as string[];
if (file?.Length != 1)
return;
var ext = Path.GetExtension(file[0]);
if (VALID_IMAGE_EXT.Contains(ext, StringComparer.OrdinalIgnoreCase))
args.Effects = DragDropEffects.Copy;
}
}
private Task<LoadImageResults> DropImage_Execute(DragEventArgs args, TargetImage target)
{
var task = new Task<LoadImageResults>(() =>
{
var results = new LoadImageResults()
{
Loaded = false,
Target = target
};
if (args.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] files = (string[])args.Data.GetData(DataFormats.FileDrop);
var file = files[0];
try
{
using (var fs = File.OpenRead(file))
{
BitmapImage bmp = new BitmapImage();
bmp.BeginInit();
bmp.StreamSource = fs;
bmp.CacheOption = BitmapCacheOption.OnLoad;
bmp.EndInit();
bmp.Freeze();
results.OriginalWidth = bmp.PixelWidth;
results.OriginalHeight = bmp.PixelHeight;
var potBmp = bmp.CreateResizedNextPot();
potBmp.Freeze();
results.Loaded = true;
results.Image = potBmp;
}
}
catch
{
// ignored
}
}
return results;
});
task.Start();
args.Handled = true;
return task;
}
private Task<SaveImageResults> ExportImage_Execute(TargetImage targetImage)
{
var busyPickingFile = MainResources.Busy_PickingFile;
var busySavingImage = MainResources.Busy_SavingImage;
BitmapSource target;
switch (targetImage)
{
case TargetImage.Top:
target = ViewModel.Textures.Top.Bitmap;
break;
case TargetImage.Bottom:
target = ViewModel.Textures.Bottom.Bitmap;
break;
case TargetImage.FileLarge:
target = ViewModel.Textures.FileLarge.Bitmap;
break;
case TargetImage.FileSmall:
target = ViewModel.Textures.FileSmall.Bitmap;
break;
case TargetImage.FolderOpen:
target = ViewModel.Textures.FolderOpen.Bitmap;
break;
case TargetImage.FolderClosed:
target = ViewModel.Textures.FolderClosed.Bitmap;
break;
case TargetImage.TopAlt:
target = ViewModel.Textures.TopAlt.Bitmap;
break;
case TargetImage.SmallIcon:
target = ViewModel.Info.SmallIcon.Bitmap;
break;
case TargetImage.LargeIcon:
target = ViewModel.Info.LargeIcon.Bitmap;
break;
default:
throw new IndexOutOfRangeException();
}
var task = new Task<SaveImageResults>(() =>
{
BusyText = busyPickingFile;
var svfl = new SaveFileDialog
{
Filter = "PNG Files|*.png",
FileName = targetImage.ToString().ToLower()
};
var dlg = svfl.ShowDialog();
SaveImageResults results = new SaveImageResults
{
Saved = false,
Target = targetImage,
Path = svfl.FileName
};
if (!dlg.HasValue || dlg.Value)
{
BusyText = busySavingImage;
try
{
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(target));
using (var fs = File.Open(results.Path, FileMode.Create))
{
encoder.Save(fs);
results.Saved = true;
}
}
catch
{
// Ignore;
}
}
return results;
});
task.Start();
return task;
}
private void ExportImage_PostExecute(SaveImageResults obj)
{
IsBusy = false;
}
private Task<LoadImageResults> LoadImage_Execute(TargetImage targetImage)
{
var busyPickingFile = MainResources.Busy_PickingFile;
var busyOpeningImage = MainResources.Busy_OpeningImage;
var task = new Task<LoadImageResults>(() =>
{
BusyText = busyPickingFile;
var opfl = new OpenFileDialog
{
Filter = "Image Files|*.jpg;*.jpeg;*.png;*.bmp",
Multiselect = false
};
var dlg = opfl.ShowDialog();
LoadImageResults results = new LoadImageResults
{
Loaded = false,
Target = targetImage
};
if (!dlg.HasValue || dlg.Value)
{
BusyText = busyOpeningImage;
try
{
using (var fs = File.OpenRead(opfl.FileName))
{
BitmapImage bmp = new BitmapImage();
bmp.BeginInit();
bmp.StreamSource = fs;
bmp.CacheOption = BitmapCacheOption.OnLoad;
bmp.EndInit();
bmp.Freeze();
results.OriginalWidth = bmp.PixelWidth;
results.OriginalHeight = bmp.PixelHeight;
BitmapSource bmpSrc;
switch (targetImage)
{
case TargetImage.Bottom:
case TargetImage.Top:
case TargetImage.FileLarge:
case TargetImage.FileSmall:
case TargetImage.FolderOpen:
case TargetImage.FolderClosed:
case TargetImage.TopAlt:
bmpSrc = bmp.CreateResizedNextPot();
bmpSrc.Freeze();
break;
case TargetImage.SmallIcon:
case TargetImage.LargeIcon:
default:
bmpSrc = bmp;
break;
}
results.Loaded = true;
results.Image = bmpSrc;
}
}
catch
{
// ignored
}
}
return results;
});
task.Start();
return task;
}
private void LoadImage_PostExecute(LoadImageResults args)
{
var errInvalidSize = MainResources.Message_InvalidImageSize;
var errValidSize = MainResources.Message_InvalidImageSize_AllowedSizes;
if (args.Loaded)
{
var bmp = args.Image;
var bmpW = bmp.PixelWidth;
var bmpH = bmp.PixelHeight;
var target = args.Target;
var validSizes = _validImageSizes[target];
try
{
var targetSize = validSizes.First(pair => pair.X == bmpW && pair.Y == bmpH);
switch (target)
{
case TargetImage.Top:
{
ViewModel.Textures.Top.EncodeTexture(args.Image, targetSize.Format);
ViewModel.Textures.Top.EdgeBleed(0, 0, args.OriginalWidth, args.OriginalHeight);
break;
}
case TargetImage.Bottom:
{
ViewModel.Textures.Bottom.EncodeTexture(args.Image, targetSize.Format);
ViewModel.Textures.Bottom.EdgeBleed(0, 0, args.OriginalWidth, args.OriginalHeight);
break;
}
case TargetImage.FileLarge:
{
ViewModel.Textures.FileLarge.EncodeTexture(args.Image, targetSize.Format);
ViewModel.Textures.FileLarge.EdgeBleed(0, 0, args.OriginalWidth, args.OriginalHeight);
break;
}
case TargetImage.FileSmall:
{
ViewModel.Textures.FileSmall.EncodeTexture(args.Image, targetSize.Format);
ViewModel.Textures.FileSmall.EdgeBleed(0, 0, args.OriginalWidth, args.OriginalHeight);
break;
}
case TargetImage.FolderOpen:
{
ViewModel.Textures.FolderOpen.EncodeTexture(args.Image, targetSize.Format);
ViewModel.Textures.FolderOpen.EdgeBleed(0, 0, args.OriginalWidth, args.OriginalHeight);
break;
}
case TargetImage.FolderClosed:
{
ViewModel.Textures.FolderClosed.EncodeTexture(args.Image, targetSize.Format);
ViewModel.Textures.FolderClosed.EdgeBleed(0, 0, args.OriginalWidth, args.OriginalHeight);
break;
}
case TargetImage.TopAlt:
{
ViewModel.Textures.TopAlt.EncodeTexture(args.Image, targetSize.Format);
ViewModel.Textures.TopAlt.EdgeBleed(0, 0, args.OriginalWidth, args.OriginalHeight);
break;
}
case TargetImage.SmallIcon:
{
ViewModel.Info.SmallIcon.EncodeTexture(args.Image, targetSize.Format);
break;
}
case TargetImage.LargeIcon:
{
ViewModel.Info.LargeIcon.EncodeTexture(args.Image, targetSize.Format);
var sml = Extensions.CreateResizedImage(args.Image, 24, 24);
ViewModel.Info.SmallIcon.EncodeTexture((BitmapSource)sml, targetSize.Format);
break;
}
default:
{
throw new ArgumentOutOfRangeException();
}
}
}
catch (InvalidOperationException)
{
var sb = new StringBuilder();
sb.AppendFormat("{2}: {0}x{1}\n", bmpW, bmpH, errInvalidSize);
sb.AppendFormat("{0}:\n", errValidSize);
foreach (var pair in validSizes)
sb.AppendFormat("\t- {0}x{1}\n", pair.X, pair.Y);
MessageBox.Show(sb.ToString(), Title, MessageBoxButton.OK, MessageBoxImage.Error);
}
}
IsBusy = false;
}
private void RemoveImage_Execute(TargetImage args)
{
switch (args)
{
case TargetImage.Top:
ViewModel.Textures.Top.ClearTexture();
break;
case TargetImage.Bottom:
ViewModel.Textures.Bottom.ClearTexture();
break;
case TargetImage.FileLarge:
ViewModel.Textures.FileLarge.ClearTexture();
break;
case TargetImage.FileSmall:
ViewModel.Textures.FileSmall.ClearTexture();
break;
case TargetImage.FolderOpen:
ViewModel.Textures.FolderOpen.ClearTexture();
break;
case TargetImage.FolderClosed:
ViewModel.Textures.FolderClosed.ClearTexture();
break;
case TargetImage.TopAlt:
ViewModel.Textures.TopAlt.ClearTexture();
break;
case TargetImage.SmallIcon:
{
var icex = new IconExtension(@"/ThemeEditor.WPF;component/Resources/Icons/app_icn.ico", 24);
var large = ((BitmapSource)icex.ProvideValue(null)).CreateResizedImage(24, 24);
ViewModel.Info.SmallIcon.EncodeTexture(large, RawTexture.DataFormat.Bgr565);
break;
}
case TargetImage.LargeIcon:
{
var icex = new IconExtension(@"/ThemeEditor.WPF;component/Resources/Icons/app_icn.ico", 48);
var large = ((BitmapSource)icex.ProvideValue(null)).CreateResizedImage(48, 48);
ViewModel.Info.LargeIcon.EncodeTexture(large, RawTexture.DataFormat.Bgr565);
break;
}
default:
throw new ArgumentOutOfRangeException();
}
}
partial void SetupImageCommands()
{
// Menus
RemoveImageCommand = new RelayCommand<TargetImage>(RemoveImage_Execute, CanExecute_ImageExists);
ReplaceImageCommand = new RelayCommandAsync<TargetImage, LoadImageResults>(LoadImage_Execute,
image => CanExecute_ViewModelLoaded(),
image => PreExecute_SetBusy(),
LoadImage_PostExecute);
ExportImageCommand = new RelayCommandAsync<TargetImage, SaveImageResults>(ExportImage_Execute,
CanExecute_ImageExists,
image => PreExecute_SetBusy(),
ExportImage_PostExecute);
// Drop Targets
DragImageCommand = new RelayCommand<DragEventArgs>(DragImage_Execute, image => CanExecute_ViewModelLoaded());
Func<TargetImage, ICommand> genCommand = target => new RelayCommandAsync<DragEventArgs, LoadImageResults>(
e => DropImage_Execute(e, target),
image => CanExecute_ViewModelLoaded(),
image => PreExecute_SetBusy(),
LoadImage_PostExecute);
DropTopImageCommand = genCommand(TargetImage.Top);
DropTopAltImageCommand = genCommand(TargetImage.TopAlt);
DropBottomImageCommand = genCommand(TargetImage.Bottom);
DropFileLargeImageCommand = genCommand(TargetImage.FileLarge);
DropFileSmallImageCommand = genCommand(TargetImage.FileSmall);
DropFolderClosedImageCommand = genCommand(TargetImage.FolderClosed);
DropFolderOpenImageCommand = genCommand(TargetImage.FolderOpen);
// SMDH Icon
CopyResizeSMDHIconCommandCommand = new RelayCommand<bool>(CopySMDHLargeToSmall_Execute);
}
private void CopySMDHLargeToSmall_Execute(bool direction)
{
if (direction)
{
var sml = Extensions.CreateResizedImage(ViewModel.Info.LargeIcon.Bitmap, 24, 24);
ViewModel.Info.SmallIcon.EncodeTexture((BitmapSource)sml, ViewModel.Info.SmallIcon.DataFormat);
}
else
{
var sml = Extensions.CreateResizedImage(ViewModel.Info.SmallIcon.Bitmap, 48, 48);
ViewModel.Info.LargeIcon.EncodeTexture((BitmapSource)sml, ViewModel.Info.LargeIcon.DataFormat);
}
}
private class SaveImageResults
{
public string Path;
public bool Saved;
public TargetImage Target;
}
private class LoadImageResults
{
public int OriginalWidth;
public int OriginalHeight;
public BitmapSource Image;
public bool Loaded;
public TargetImage Target;
}
}
}
| |
using System;
using Raksha.Crypto.Parameters;
namespace Raksha.Crypto.Engines
{
/**
* Implementation of the SEED algorithm as described in RFC 4009
*/
public class SeedEngine
: IBlockCipher
{
private const int BlockSize = 16;
private static readonly uint[] SS0 =
{
0x2989a1a8, 0x05858184, 0x16c6d2d4, 0x13c3d3d0, 0x14445054, 0x1d0d111c, 0x2c8ca0ac, 0x25052124,
0x1d4d515c, 0x03434340, 0x18081018, 0x1e0e121c, 0x11415150, 0x3cccf0fc, 0x0acac2c8, 0x23436360,
0x28082028, 0x04444044, 0x20002020, 0x1d8d919c, 0x20c0e0e0, 0x22c2e2e0, 0x08c8c0c8, 0x17071314,
0x2585a1a4, 0x0f8f838c, 0x03030300, 0x3b4b7378, 0x3b8bb3b8, 0x13031310, 0x12c2d2d0, 0x2ecee2ec,
0x30407070, 0x0c8c808c, 0x3f0f333c, 0x2888a0a8, 0x32023230, 0x1dcdd1dc, 0x36c6f2f4, 0x34447074,
0x2ccce0ec, 0x15859194, 0x0b0b0308, 0x17475354, 0x1c4c505c, 0x1b4b5358, 0x3d8db1bc, 0x01010100,
0x24042024, 0x1c0c101c, 0x33437370, 0x18889098, 0x10001010, 0x0cccc0cc, 0x32c2f2f0, 0x19c9d1d8,
0x2c0c202c, 0x27c7e3e4, 0x32427270, 0x03838380, 0x1b8b9398, 0x11c1d1d0, 0x06868284, 0x09c9c1c8,
0x20406060, 0x10405050, 0x2383a3a0, 0x2bcbe3e8, 0x0d0d010c, 0x3686b2b4, 0x1e8e929c, 0x0f4f434c,
0x3787b3b4, 0x1a4a5258, 0x06c6c2c4, 0x38487078, 0x2686a2a4, 0x12021210, 0x2f8fa3ac, 0x15c5d1d4,
0x21416160, 0x03c3c3c0, 0x3484b0b4, 0x01414140, 0x12425250, 0x3d4d717c, 0x0d8d818c, 0x08080008,
0x1f0f131c, 0x19899198, 0x00000000, 0x19091118, 0x04040004, 0x13435350, 0x37c7f3f4, 0x21c1e1e0,
0x3dcdf1fc, 0x36467274, 0x2f0f232c, 0x27072324, 0x3080b0b0, 0x0b8b8388, 0x0e0e020c, 0x2b8ba3a8,
0x2282a2a0, 0x2e4e626c, 0x13839390, 0x0d4d414c, 0x29496168, 0x3c4c707c, 0x09090108, 0x0a0a0208,
0x3f8fb3bc, 0x2fcfe3ec, 0x33c3f3f0, 0x05c5c1c4, 0x07878384, 0x14041014, 0x3ecef2fc, 0x24446064,
0x1eced2dc, 0x2e0e222c, 0x0b4b4348, 0x1a0a1218, 0x06060204, 0x21012120, 0x2b4b6368, 0x26466264,
0x02020200, 0x35c5f1f4, 0x12829290, 0x0a8a8288, 0x0c0c000c, 0x3383b3b0, 0x3e4e727c, 0x10c0d0d0,
0x3a4a7278, 0x07474344, 0x16869294, 0x25c5e1e4, 0x26062224, 0x00808080, 0x2d8da1ac, 0x1fcfd3dc,
0x2181a1a0, 0x30003030, 0x37073334, 0x2e8ea2ac, 0x36063234, 0x15051114, 0x22022220, 0x38083038,
0x34c4f0f4, 0x2787a3a4, 0x05454144, 0x0c4c404c, 0x01818180, 0x29c9e1e8, 0x04848084, 0x17879394,
0x35053134, 0x0bcbc3c8, 0x0ecec2cc, 0x3c0c303c, 0x31417170, 0x11011110, 0x07c7c3c4, 0x09898188,
0x35457174, 0x3bcbf3f8, 0x1acad2d8, 0x38c8f0f8, 0x14849094, 0x19495158, 0x02828280, 0x04c4c0c4,
0x3fcff3fc, 0x09494148, 0x39093138, 0x27476364, 0x00c0c0c0, 0x0fcfc3cc, 0x17c7d3d4, 0x3888b0b8,
0x0f0f030c, 0x0e8e828c, 0x02424240, 0x23032320, 0x11819190, 0x2c4c606c, 0x1bcbd3d8, 0x2484a0a4,
0x34043034, 0x31c1f1f0, 0x08484048, 0x02c2c2c0, 0x2f4f636c, 0x3d0d313c, 0x2d0d212c, 0x00404040,
0x3e8eb2bc, 0x3e0e323c, 0x3c8cb0bc, 0x01c1c1c0, 0x2a8aa2a8, 0x3a8ab2b8, 0x0e4e424c, 0x15455154,
0x3b0b3338, 0x1cccd0dc, 0x28486068, 0x3f4f737c, 0x1c8c909c, 0x18c8d0d8, 0x0a4a4248, 0x16465254,
0x37477374, 0x2080a0a0, 0x2dcde1ec, 0x06464244, 0x3585b1b4, 0x2b0b2328, 0x25456164, 0x3acaf2f8,
0x23c3e3e0, 0x3989b1b8, 0x3181b1b0, 0x1f8f939c, 0x1e4e525c, 0x39c9f1f8, 0x26c6e2e4, 0x3282b2b0,
0x31013130, 0x2acae2e8, 0x2d4d616c, 0x1f4f535c, 0x24c4e0e4, 0x30c0f0f0, 0x0dcdc1cc, 0x08888088,
0x16061214, 0x3a0a3238, 0x18485058, 0x14c4d0d4, 0x22426260, 0x29092128, 0x07070304, 0x33033330,
0x28c8e0e8, 0x1b0b1318, 0x05050104, 0x39497178, 0x10809090, 0x2a4a6268, 0x2a0a2228, 0x1a8a9298
};
private static readonly uint[] SS1 =
{
0x38380830, 0xe828c8e0, 0x2c2d0d21, 0xa42686a2, 0xcc0fcfc3, 0xdc1eced2, 0xb03383b3, 0xb83888b0,
0xac2f8fa3, 0x60204060, 0x54154551, 0xc407c7c3, 0x44044440, 0x6c2f4f63, 0x682b4b63, 0x581b4b53,
0xc003c3c3, 0x60224262, 0x30330333, 0xb43585b1, 0x28290921, 0xa02080a0, 0xe022c2e2, 0xa42787a3,
0xd013c3d3, 0x90118191, 0x10110111, 0x04060602, 0x1c1c0c10, 0xbc3c8cb0, 0x34360632, 0x480b4b43,
0xec2fcfe3, 0x88088880, 0x6c2c4c60, 0xa82888a0, 0x14170713, 0xc404c4c0, 0x14160612, 0xf434c4f0,
0xc002c2c2, 0x44054541, 0xe021c1e1, 0xd416c6d2, 0x3c3f0f33, 0x3c3d0d31, 0x8c0e8e82, 0x98188890,
0x28280820, 0x4c0e4e42, 0xf436c6f2, 0x3c3e0e32, 0xa42585a1, 0xf839c9f1, 0x0c0d0d01, 0xdc1fcfd3,
0xd818c8d0, 0x282b0b23, 0x64264662, 0x783a4a72, 0x24270723, 0x2c2f0f23, 0xf031c1f1, 0x70324272,
0x40024242, 0xd414c4d0, 0x40014141, 0xc000c0c0, 0x70334373, 0x64274763, 0xac2c8ca0, 0x880b8b83,
0xf437c7f3, 0xac2d8da1, 0x80008080, 0x1c1f0f13, 0xc80acac2, 0x2c2c0c20, 0xa82a8aa2, 0x34340430,
0xd012c2d2, 0x080b0b03, 0xec2ecee2, 0xe829c9e1, 0x5c1d4d51, 0x94148490, 0x18180810, 0xf838c8f0,
0x54174753, 0xac2e8ea2, 0x08080800, 0xc405c5c1, 0x10130313, 0xcc0dcdc1, 0x84068682, 0xb83989b1,
0xfc3fcff3, 0x7c3d4d71, 0xc001c1c1, 0x30310131, 0xf435c5f1, 0x880a8a82, 0x682a4a62, 0xb03181b1,
0xd011c1d1, 0x20200020, 0xd417c7d3, 0x00020202, 0x20220222, 0x04040400, 0x68284860, 0x70314171,
0x04070703, 0xd81bcbd3, 0x9c1d8d91, 0x98198991, 0x60214161, 0xbc3e8eb2, 0xe426c6e2, 0x58194951,
0xdc1dcdd1, 0x50114151, 0x90108090, 0xdc1cccd0, 0x981a8a92, 0xa02383a3, 0xa82b8ba3, 0xd010c0d0,
0x80018181, 0x0c0f0f03, 0x44074743, 0x181a0a12, 0xe023c3e3, 0xec2ccce0, 0x8c0d8d81, 0xbc3f8fb3,
0x94168692, 0x783b4b73, 0x5c1c4c50, 0xa02282a2, 0xa02181a1, 0x60234363, 0x20230323, 0x4c0d4d41,
0xc808c8c0, 0x9c1e8e92, 0x9c1c8c90, 0x383a0a32, 0x0c0c0c00, 0x2c2e0e22, 0xb83a8ab2, 0x6c2e4e62,
0x9c1f8f93, 0x581a4a52, 0xf032c2f2, 0x90128292, 0xf033c3f3, 0x48094941, 0x78384870, 0xcc0cccc0,
0x14150511, 0xf83bcbf3, 0x70304070, 0x74354571, 0x7c3f4f73, 0x34350531, 0x10100010, 0x00030303,
0x64244460, 0x6c2d4d61, 0xc406c6c2, 0x74344470, 0xd415c5d1, 0xb43484b0, 0xe82acae2, 0x08090901,
0x74364672, 0x18190911, 0xfc3ecef2, 0x40004040, 0x10120212, 0xe020c0e0, 0xbc3d8db1, 0x04050501,
0xf83acaf2, 0x00010101, 0xf030c0f0, 0x282a0a22, 0x5c1e4e52, 0xa82989a1, 0x54164652, 0x40034343,
0x84058581, 0x14140410, 0x88098981, 0x981b8b93, 0xb03080b0, 0xe425c5e1, 0x48084840, 0x78394971,
0x94178793, 0xfc3cccf0, 0x1c1e0e12, 0x80028282, 0x20210121, 0x8c0c8c80, 0x181b0b13, 0x5c1f4f53,
0x74374773, 0x54144450, 0xb03282b2, 0x1c1d0d11, 0x24250521, 0x4c0f4f43, 0x00000000, 0x44064642,
0xec2dcde1, 0x58184850, 0x50124252, 0xe82bcbe3, 0x7c3e4e72, 0xd81acad2, 0xc809c9c1, 0xfc3dcdf1,
0x30300030, 0x94158591, 0x64254561, 0x3c3c0c30, 0xb43686b2, 0xe424c4e0, 0xb83b8bb3, 0x7c3c4c70,
0x0c0e0e02, 0x50104050, 0x38390931, 0x24260622, 0x30320232, 0x84048480, 0x68294961, 0x90138393,
0x34370733, 0xe427c7e3, 0x24240420, 0xa42484a0, 0xc80bcbc3, 0x50134353, 0x080a0a02, 0x84078783,
0xd819c9d1, 0x4c0c4c40, 0x80038383, 0x8c0f8f83, 0xcc0ecec2, 0x383b0b33, 0x480a4a42, 0xb43787b3
};
private static readonly uint[] SS2 =
{
0xa1a82989, 0x81840585, 0xd2d416c6, 0xd3d013c3, 0x50541444, 0x111c1d0d, 0xa0ac2c8c, 0x21242505,
0x515c1d4d, 0x43400343, 0x10181808, 0x121c1e0e, 0x51501141, 0xf0fc3ccc, 0xc2c80aca, 0x63602343,
0x20282808, 0x40440444, 0x20202000, 0x919c1d8d, 0xe0e020c0, 0xe2e022c2, 0xc0c808c8, 0x13141707,
0xa1a42585, 0x838c0f8f, 0x03000303, 0x73783b4b, 0xb3b83b8b, 0x13101303, 0xd2d012c2, 0xe2ec2ece,
0x70703040, 0x808c0c8c, 0x333c3f0f, 0xa0a82888, 0x32303202, 0xd1dc1dcd, 0xf2f436c6, 0x70743444,
0xe0ec2ccc, 0x91941585, 0x03080b0b, 0x53541747, 0x505c1c4c, 0x53581b4b, 0xb1bc3d8d, 0x01000101,
0x20242404, 0x101c1c0c, 0x73703343, 0x90981888, 0x10101000, 0xc0cc0ccc, 0xf2f032c2, 0xd1d819c9,
0x202c2c0c, 0xe3e427c7, 0x72703242, 0x83800383, 0x93981b8b, 0xd1d011c1, 0x82840686, 0xc1c809c9,
0x60602040, 0x50501040, 0xa3a02383, 0xe3e82bcb, 0x010c0d0d, 0xb2b43686, 0x929c1e8e, 0x434c0f4f,
0xb3b43787, 0x52581a4a, 0xc2c406c6, 0x70783848, 0xa2a42686, 0x12101202, 0xa3ac2f8f, 0xd1d415c5,
0x61602141, 0xc3c003c3, 0xb0b43484, 0x41400141, 0x52501242, 0x717c3d4d, 0x818c0d8d, 0x00080808,
0x131c1f0f, 0x91981989, 0x00000000, 0x11181909, 0x00040404, 0x53501343, 0xf3f437c7, 0xe1e021c1,
0xf1fc3dcd, 0x72743646, 0x232c2f0f, 0x23242707, 0xb0b03080, 0x83880b8b, 0x020c0e0e, 0xa3a82b8b,
0xa2a02282, 0x626c2e4e, 0x93901383, 0x414c0d4d, 0x61682949, 0x707c3c4c, 0x01080909, 0x02080a0a,
0xb3bc3f8f, 0xe3ec2fcf, 0xf3f033c3, 0xc1c405c5, 0x83840787, 0x10141404, 0xf2fc3ece, 0x60642444,
0xd2dc1ece, 0x222c2e0e, 0x43480b4b, 0x12181a0a, 0x02040606, 0x21202101, 0x63682b4b, 0x62642646,
0x02000202, 0xf1f435c5, 0x92901282, 0x82880a8a, 0x000c0c0c, 0xb3b03383, 0x727c3e4e, 0xd0d010c0,
0x72783a4a, 0x43440747, 0x92941686, 0xe1e425c5, 0x22242606, 0x80800080, 0xa1ac2d8d, 0xd3dc1fcf,
0xa1a02181, 0x30303000, 0x33343707, 0xa2ac2e8e, 0x32343606, 0x11141505, 0x22202202, 0x30383808,
0xf0f434c4, 0xa3a42787, 0x41440545, 0x404c0c4c, 0x81800181, 0xe1e829c9, 0x80840484, 0x93941787,
0x31343505, 0xc3c80bcb, 0xc2cc0ece, 0x303c3c0c, 0x71703141, 0x11101101, 0xc3c407c7, 0x81880989,
0x71743545, 0xf3f83bcb, 0xd2d81aca, 0xf0f838c8, 0x90941484, 0x51581949, 0x82800282, 0xc0c404c4,
0xf3fc3fcf, 0x41480949, 0x31383909, 0x63642747, 0xc0c000c0, 0xc3cc0fcf, 0xd3d417c7, 0xb0b83888,
0x030c0f0f, 0x828c0e8e, 0x42400242, 0x23202303, 0x91901181, 0x606c2c4c, 0xd3d81bcb, 0xa0a42484,
0x30343404, 0xf1f031c1, 0x40480848, 0xc2c002c2, 0x636c2f4f, 0x313c3d0d, 0x212c2d0d, 0x40400040,
0xb2bc3e8e, 0x323c3e0e, 0xb0bc3c8c, 0xc1c001c1, 0xa2a82a8a, 0xb2b83a8a, 0x424c0e4e, 0x51541545,
0x33383b0b, 0xd0dc1ccc, 0x60682848, 0x737c3f4f, 0x909c1c8c, 0xd0d818c8, 0x42480a4a, 0x52541646,
0x73743747, 0xa0a02080, 0xe1ec2dcd, 0x42440646, 0xb1b43585, 0x23282b0b, 0x61642545, 0xf2f83aca,
0xe3e023c3, 0xb1b83989, 0xb1b03181, 0x939c1f8f, 0x525c1e4e, 0xf1f839c9, 0xe2e426c6, 0xb2b03282,
0x31303101, 0xe2e82aca, 0x616c2d4d, 0x535c1f4f, 0xe0e424c4, 0xf0f030c0, 0xc1cc0dcd, 0x80880888,
0x12141606, 0x32383a0a, 0x50581848, 0xd0d414c4, 0x62602242, 0x21282909, 0x03040707, 0x33303303,
0xe0e828c8, 0x13181b0b, 0x01040505, 0x71783949, 0x90901080, 0x62682a4a, 0x22282a0a, 0x92981a8a
};
private static readonly uint[] SS3 =
{
0x08303838, 0xc8e0e828, 0x0d212c2d, 0x86a2a426, 0xcfc3cc0f, 0xced2dc1e, 0x83b3b033, 0x88b0b838,
0x8fa3ac2f, 0x40606020, 0x45515415, 0xc7c3c407, 0x44404404, 0x4f636c2f, 0x4b63682b, 0x4b53581b,
0xc3c3c003, 0x42626022, 0x03333033, 0x85b1b435, 0x09212829, 0x80a0a020, 0xc2e2e022, 0x87a3a427,
0xc3d3d013, 0x81919011, 0x01111011, 0x06020406, 0x0c101c1c, 0x8cb0bc3c, 0x06323436, 0x4b43480b,
0xcfe3ec2f, 0x88808808, 0x4c606c2c, 0x88a0a828, 0x07131417, 0xc4c0c404, 0x06121416, 0xc4f0f434,
0xc2c2c002, 0x45414405, 0xc1e1e021, 0xc6d2d416, 0x0f333c3f, 0x0d313c3d, 0x8e828c0e, 0x88909818,
0x08202828, 0x4e424c0e, 0xc6f2f436, 0x0e323c3e, 0x85a1a425, 0xc9f1f839, 0x0d010c0d, 0xcfd3dc1f,
0xc8d0d818, 0x0b23282b, 0x46626426, 0x4a72783a, 0x07232427, 0x0f232c2f, 0xc1f1f031, 0x42727032,
0x42424002, 0xc4d0d414, 0x41414001, 0xc0c0c000, 0x43737033, 0x47636427, 0x8ca0ac2c, 0x8b83880b,
0xc7f3f437, 0x8da1ac2d, 0x80808000, 0x0f131c1f, 0xcac2c80a, 0x0c202c2c, 0x8aa2a82a, 0x04303434,
0xc2d2d012, 0x0b03080b, 0xcee2ec2e, 0xc9e1e829, 0x4d515c1d, 0x84909414, 0x08101818, 0xc8f0f838,
0x47535417, 0x8ea2ac2e, 0x08000808, 0xc5c1c405, 0x03131013, 0xcdc1cc0d, 0x86828406, 0x89b1b839,
0xcff3fc3f, 0x4d717c3d, 0xc1c1c001, 0x01313031, 0xc5f1f435, 0x8a82880a, 0x4a62682a, 0x81b1b031,
0xc1d1d011, 0x00202020, 0xc7d3d417, 0x02020002, 0x02222022, 0x04000404, 0x48606828, 0x41717031,
0x07030407, 0xcbd3d81b, 0x8d919c1d, 0x89919819, 0x41616021, 0x8eb2bc3e, 0xc6e2e426, 0x49515819,
0xcdd1dc1d, 0x41515011, 0x80909010, 0xccd0dc1c, 0x8a92981a, 0x83a3a023, 0x8ba3a82b, 0xc0d0d010,
0x81818001, 0x0f030c0f, 0x47434407, 0x0a12181a, 0xc3e3e023, 0xcce0ec2c, 0x8d818c0d, 0x8fb3bc3f,
0x86929416, 0x4b73783b, 0x4c505c1c, 0x82a2a022, 0x81a1a021, 0x43636023, 0x03232023, 0x4d414c0d,
0xc8c0c808, 0x8e929c1e, 0x8c909c1c, 0x0a32383a, 0x0c000c0c, 0x0e222c2e, 0x8ab2b83a, 0x4e626c2e,
0x8f939c1f, 0x4a52581a, 0xc2f2f032, 0x82929012, 0xc3f3f033, 0x49414809, 0x48707838, 0xccc0cc0c,
0x05111415, 0xcbf3f83b, 0x40707030, 0x45717435, 0x4f737c3f, 0x05313435, 0x00101010, 0x03030003,
0x44606424, 0x4d616c2d, 0xc6c2c406, 0x44707434, 0xc5d1d415, 0x84b0b434, 0xcae2e82a, 0x09010809,
0x46727436, 0x09111819, 0xcef2fc3e, 0x40404000, 0x02121012, 0xc0e0e020, 0x8db1bc3d, 0x05010405,
0xcaf2f83a, 0x01010001, 0xc0f0f030, 0x0a22282a, 0x4e525c1e, 0x89a1a829, 0x46525416, 0x43434003,
0x85818405, 0x04101414, 0x89818809, 0x8b93981b, 0x80b0b030, 0xc5e1e425, 0x48404808, 0x49717839,
0x87939417, 0xccf0fc3c, 0x0e121c1e, 0x82828002, 0x01212021, 0x8c808c0c, 0x0b13181b, 0x4f535c1f,
0x47737437, 0x44505414, 0x82b2b032, 0x0d111c1d, 0x05212425, 0x4f434c0f, 0x00000000, 0x46424406,
0xcde1ec2d, 0x48505818, 0x42525012, 0xcbe3e82b, 0x4e727c3e, 0xcad2d81a, 0xc9c1c809, 0xcdf1fc3d,
0x00303030, 0x85919415, 0x45616425, 0x0c303c3c, 0x86b2b436, 0xc4e0e424, 0x8bb3b83b, 0x4c707c3c,
0x0e020c0e, 0x40505010, 0x09313839, 0x06222426, 0x02323032, 0x84808404, 0x49616829, 0x83939013,
0x07333437, 0xc7e3e427, 0x04202424, 0x84a0a424, 0xcbc3c80b, 0x43535013, 0x0a02080a, 0x87838407,
0xc9d1d819, 0x4c404c0c, 0x83838003, 0x8f838c0f, 0xcec2cc0e, 0x0b33383b, 0x4a42480a, 0x87b3b437
};
private static readonly uint[] KC =
{
0x9e3779b9, 0x3c6ef373, 0x78dde6e6, 0xf1bbcdcc,
0xe3779b99, 0xc6ef3733, 0x8dde6e67, 0x1bbcdccf,
0x3779b99e, 0x6ef3733c, 0xdde6e678, 0xbbcdccf1,
0x779b99e3, 0xef3733c6, 0xde6e678d, 0xbcdccf1b
};
private int[] wKey;
private bool forEncryption;
public void Init(
bool forEncryption,
ICipherParameters parameters)
{
this.forEncryption = forEncryption;
wKey = createWorkingKey(((KeyParameter)parameters).GetKey());
}
public string AlgorithmName
{
get { return "SEED"; }
}
public bool IsPartialBlockOkay
{
get { return false; }
}
public int GetBlockSize()
{
return BlockSize;
}
public int ProcessBlock(
byte[] inBuf,
int inOff,
byte[] outBuf,
int outOff)
{
if (wKey == null)
throw new InvalidOperationException("SEED engine not initialised");
if (inOff + BlockSize > inBuf.Length)
throw new DataLengthException("input buffer too short");
if (outOff + BlockSize > outBuf.Length)
throw new DataLengthException("output buffer too short");
long l = bytesToLong(inBuf, inOff + 0);
long r = bytesToLong(inBuf, inOff + 8);
if (forEncryption)
{
for (int i = 0; i < 16; i++)
{
long nl = r;
r = l ^ F(wKey[2 * i], wKey[(2 * i) + 1], r);
l = nl;
}
}
else
{
for (int i = 15; i >= 0; i--)
{
long nl = r;
r = l ^ F(wKey[2 * i], wKey[(2 * i) + 1], r);
l = nl;
}
}
longToBytes(outBuf, outOff + 0, r);
longToBytes(outBuf, outOff + 8, l);
return BlockSize;
}
public void Reset()
{
}
private int[] createWorkingKey(
byte[] inKey)
{
int[] key = new int[32];
long lower = bytesToLong(inKey, 0);
long upper = bytesToLong(inKey, 8);
int key0 = extractW0(lower);
int key1 = extractW1(lower);
int key2 = extractW0(upper);
int key3 = extractW1(upper);
for (int i = 0; i < 16; i++)
{
key[2 * i] = G(key0 + key2 - (int)KC[i]);
key[2 * i + 1] = G(key1 - key3 + (int)KC[i]);
if (i % 2 == 0)
{
lower = rotateRight8(lower);
key0 = extractW0(lower);
key1 = extractW1(lower);
}
else
{
upper = rotateLeft8(upper);
key2 = extractW0(upper);
key3 = extractW1(upper);
}
}
return key;
}
private int extractW1(
long lVal)
{
return (int)lVal;
}
private int extractW0(
long lVal)
{
return (int)(lVal >> 32);
}
private long rotateLeft8(
long x)
{
return (x << 8) | ((long)((ulong) x >> 56));
}
private long rotateRight8(
long x)
{
return ((long)((ulong) x >> 8)) | (x << 56);
}
private long bytesToLong(
byte[] src,
int srcOff)
{
long word = 0;
for (int i = 0; i <= 7; i++)
{
word = (word << 8) + (src[i + srcOff] & 0xff);
}
return word;
}
private void longToBytes(
byte[] dest,
int destOff,
long value)
{
for (int i = 0; i < 8; i++)
{
dest[i + destOff] = (byte)(value >> ((7 - i) * 8));
}
}
private int G(
int x)
{
return (int)(SS0[x & 0xff] ^ SS1[(x >> 8) & 0xff] ^ SS2[(x >> 16) & 0xff] ^ SS3[(x >> 24) & 0xff]);
}
private long F(
int ki0,
int ki1,
long r)
{
int r0 = (int)(r >> 32);
int r1 = (int)r;
int rd1 = phaseCalc2(r0, ki0, r1, ki1);
int rd0 = rd1 + phaseCalc1(r0, ki0, r1, ki1);
return ((long)rd0 << 32) | (rd1 & 0xffffffffL);
}
private int phaseCalc1(
int r0,
int ki0,
int r1,
int ki1)
{
return G(G((r0 ^ ki0) ^ (r1 ^ ki1)) + (r0 ^ ki0));
}
private int phaseCalc2(
int r0,
int ki0,
int r1,
int ki1)
{
return G(phaseCalc1(r0, ki0, r1, ki1) + G((r0 ^ ki0) ^ (r1 ^ ki1)));
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using OpenMetaverse;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.UserAccounts
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "LocalUserAccountServicesConnector")]
public class LocalUserAccountServicesConnector : ISharedRegionModule, IUserAccountService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// This is not on the IUserAccountService. It's only being used so that standalone scenes can punch through
/// to a local UserAccountService when setting up an estate manager.
/// </summary>
public IUserAccountService UserAccountService { get; private set; }
private UserAccountCache m_Cache;
private bool m_Enabled = false;
#region ISharedRegionModule
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "LocalUserAccountServicesConnector"; }
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("UserAccountServices", "");
if (name == Name)
{
IConfig userConfig = source.Configs["UserAccountService"];
if (userConfig == null)
{
m_log.Error("[LOCAL USER ACCOUNT SERVICE CONNECTOR]: UserAccountService missing from OpenSim.ini");
return;
}
string serviceDll = userConfig.GetString("LocalServiceModule", String.Empty);
if (serviceDll == String.Empty)
{
m_log.Error("[LOCAL USER ACCOUNT SERVICE CONNECTOR]: No LocalServiceModule named in section UserService");
return;
}
Object[] args = new Object[] { source };
UserAccountService = ServerUtils.LoadPlugin<IUserAccountService>(serviceDll, args);
if (UserAccountService == null)
{
m_log.ErrorFormat(
"[LOCAL USER ACCOUNT SERVICE CONNECTOR]: Cannot load user account service specified as {0}", serviceDll);
return;
}
m_Enabled = true;
m_Cache = new UserAccountCache();
m_log.Info("[LOCAL USER ACCOUNT SERVICE CONNECTOR]: Local user connector enabled");
}
}
}
public void PostInitialise()
{
if (!m_Enabled)
return;
}
public void Close()
{
if (!m_Enabled)
return;
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
// FIXME: Why do we bother setting this module and caching up if we just end up registering the inner
// user account service?!
scene.RegisterModuleInterface<IUserAccountService>(UserAccountService);
}
public void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
}
public void RegionLoaded(Scene scene)
{
if (!m_Enabled)
return;
m_log.InfoFormat("[LOCAL USER ACCOUNT SERVICE CONNECTOR]: Enabled local user accounts for region {0}", scene.RegionInfo.RegionName);
}
#endregion
#region IUserAccountService
public UserAccount GetUserAccount(UUID scopeID, UUID userID)
{
bool inCache = false;
UserAccount account = m_Cache.Get(userID, out inCache);
if (inCache)
return account;
account = UserAccountService.GetUserAccount(scopeID, userID);
m_Cache.Cache(userID, account);
return account;
}
public UserAccount GetUserAccount(UUID scopeID, string firstName, string lastName)
{
bool inCache = false;
UserAccount account = m_Cache.Get(firstName + " " + lastName, out inCache);
if (inCache)
return account;
account = UserAccountService.GetUserAccount(scopeID, firstName, lastName);
if (account != null)
m_Cache.Cache(account.PrincipalID, account);
return account;
}
public UserAccount GetUserAccount(UUID scopeID, string Email)
{
return UserAccountService.GetUserAccount(scopeID, Email);
}
public List<UserAccount> GetUserAccounts(UUID scopeID, string query)
{
return UserAccountService.GetUserAccounts(scopeID, query);
}
// Update all updatable fields
//
public bool StoreUserAccount(UserAccount data)
{
bool ret = UserAccountService.StoreUserAccount(data);
if (ret)
m_Cache.Cache(data.PrincipalID, data);
return ret;
}
public void InvalidateCache(UUID userID)
{
m_Cache.Invalidate(userID);
}
#endregion
}
}
| |
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 NewEmployee.WebApi.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
/// Copyright (C) 2012-2014 Soomla Inc.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
using System.Collections;
using System.Collections.Generic;
using System;
using SoomlaWpCore.util;
using SoomlaWpCore.data;
namespace SoomlaWpCore
{
public class Schedule {
private static string TAG = "SOOMLA Schedule";
public enum Recurrence {
EVERY_MONTH,
EVERY_WEEK,
EVERY_DAY,
EVERY_HOUR,
NONE
}
public class DateTimeRange {
public DateTime Start;
public DateTime End;
public DateTimeRange(DateTime start, DateTime end) {
Start = start;
End = end;
}
}
public Recurrence RequiredRecurrence;
public List<DateTimeRange> TimeRanges;
public int ActivationLimit;
public static Schedule AnyTimeOnce() {
return new Schedule(1);
}
public static Schedule AnyTimeLimited(int activationLimit) {
return new Schedule(activationLimit);
}
public static Schedule AnyTimeUnLimited() {
return new Schedule(0);
}
public Schedule(int activationLimit) :
this(null, Recurrence.NONE, activationLimit)
{
}
public Schedule(DateTime startTime, DateTime endTime, Recurrence recurrence, int activationLimit) :
this(new List<DateTimeRange> { new DateTimeRange(startTime, endTime) }, recurrence, activationLimit)
{
}
public Schedule(List<DateTimeRange> timeRanges, Recurrence recurrence, int activationLimit)
{
TimeRanges = timeRanges;
RequiredRecurrence = recurrence;
ActivationLimit = activationLimit;
}
public Schedule(JSONObject jsonSched)
{
if(jsonSched[JSONConsts.SOOM_SCHE_REC]) {
RequiredRecurrence = (Recurrence) jsonSched[JSONConsts.SOOM_SCHE_REC].n;
} else {
RequiredRecurrence = Recurrence.NONE;
}
ActivationLimit = (int)Math.Ceiling(jsonSched[JSONConsts.SOOM_SCHE_APPROVALS].n);
TimeRanges = new List<DateTimeRange>();
if (jsonSched[JSONConsts.SOOM_SCHE_RANGES]) {
List<JSONObject> RangesObjs = jsonSched[JSONConsts.SOOM_SCHE_RANGES].list;
foreach(JSONObject RangeObj in RangesObjs) {
TimeSpan tmpTime = TimeSpan.FromMilliseconds((long)RangeObj[JSONConsts.SOOM_SCHE_RANGE_START].n);
DateTime start = new DateTime(tmpTime.Ticks);
tmpTime = TimeSpan.FromMilliseconds((long)RangeObj[JSONConsts.SOOM_SCHE_RANGE_END].n);
DateTime end = new DateTime(tmpTime.Ticks);
TimeRanges.Add(new DateTimeRange(start, end));
}
}
}
public JSONObject toJSONObject() {
JSONObject obj = new JSONObject(JSONObject.Type.OBJECT);
obj.AddField(JSONConsts.SOOM_CLASSNAME, SoomlaUtils.GetClassName(this));
obj.AddField(JSONConsts.SOOM_SCHE_REC, (int)RequiredRecurrence);
obj.AddField(JSONConsts.SOOM_SCHE_APPROVALS, ActivationLimit);
JSONObject rangesObj = new JSONObject(JSONObject.Type.ARRAY);
if (TimeRanges != null)
{
foreach(DateTimeRange dtr in TimeRanges)
{
long startMillis = dtr.Start.Ticks / TimeSpan.TicksPerMillisecond;
long endMillis = dtr.End.Ticks / TimeSpan.TicksPerMillisecond;
JSONObject singleRange = new JSONObject(JSONObject.Type.OBJECT);
singleRange.AddField(JSONConsts.SOOM_CLASSNAME, SoomlaUtils.GetClassName(dtr));
singleRange.AddField(JSONConsts.SOOM_SCHE_RANGE_START, startMillis);
singleRange.AddField(JSONConsts.SOOM_SCHE_RANGE_END, endMillis);
rangesObj.Add(singleRange);
}
}
obj.AddField(JSONConsts.SOOM_SCHE_RANGES, rangesObj);
return obj;
}
public bool Approve(int activationTimes) {
DateTime now = DateTime.Now;
if (ActivationLimit < 1 && (TimeRanges == null || TimeRanges.Count == 0)) {
SoomlaUtils.LogDebug(TAG, "There's no activation limit and no TimeRanges. APPROVED!");
return true;
}
if (ActivationLimit>0 && activationTimes >= ActivationLimit) {
SoomlaUtils.LogDebug(TAG, "Activation limit exceeded.");
return false;
}
if ((TimeRanges == null || TimeRanges.Count == 0)) {
SoomlaUtils.LogDebug(TAG, "We have an activation limit that was not reached. Also, we don't have any time ranges. APPROVED!");
return true;
}
// NOTE: From this point on ... we know that we didn't reach the activation limit AND we have TimeRanges.
// We'll just make sure the time ranges and the Recurrence copmlies.
foreach(DateTimeRange dtr in TimeRanges) {
if (now >= dtr.Start && now <= dtr.End) {
SoomlaUtils.LogDebug(TAG, "We are just in one of the time spans, it can't get any better then that. APPROVED!");
return true;
}
}
// we don't need to continue if RequiredRecurrence is NONE
if (RequiredRecurrence == Recurrence.NONE) {
return false;
}
foreach(DateTimeRange dtr in TimeRanges) {
if (now.Minute >= dtr.Start.Minute && now.Minute <= dtr.End.Minute) {
SoomlaUtils.LogDebug(TAG, "Now is in one of the time ranges' minutes span.");
if (RequiredRecurrence == Recurrence.EVERY_HOUR) {
SoomlaUtils.LogDebug(TAG, "It's a EVERY_HOUR recurrence. APPROVED!");
return true;
}
if (now.Hour >= dtr.Start.Hour && now.Hour <= dtr.End.Hour) {
SoomlaUtils.LogDebug(TAG, "Now is in one of the time ranges' hours span.");
if (RequiredRecurrence == Recurrence.EVERY_DAY) {
SoomlaUtils.LogDebug(TAG, "It's a EVERY_DAY recurrence. APPROVED!");
return true;
}
if (now.DayOfWeek >= dtr.Start.DayOfWeek && now.DayOfWeek <= dtr.End.DayOfWeek) {
SoomlaUtils.LogDebug(TAG, "Now is in one of the time ranges' day-of-week span.");
if (RequiredRecurrence == Recurrence.EVERY_WEEK) {
SoomlaUtils.LogDebug(TAG, "It's a EVERY_WEEK recurrence. APPROVED!");
return true;
}
if (now.Day >= dtr.Start.Day && now.Day <= dtr.End.Day) {
SoomlaUtils.LogDebug(TAG, "Now is in one of the time ranges' days span.");
if (RequiredRecurrence == Recurrence.EVERY_MONTH) {
SoomlaUtils.LogDebug(TAG, "It's a EVERY_MONTH recurrence. APPROVED!");
return true;
}
}
}
}
}
}
return false;
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.2.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Reservations
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// OperationOperations operations.
/// </summary>
internal partial class OperationOperations : IServiceOperations<AzureReservationAPIClient>, IOperationOperations
{
/// <summary>
/// Initializes a new instance of the OperationOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal OperationOperations(AzureReservationAPIClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AzureReservationAPIClient
/// </summary>
public AzureReservationAPIClient Client { get; private set; }
/// <summary>
/// Get operations.
/// </summary>
/// <remarks>
/// List all the operations.
/// </remarks>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="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<OperationResponse>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Capacity/operations").ToString();
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<OperationResponse>>();
_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<OperationResponse>>(_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>
/// Get operations.
/// </summary>
/// <remarks>
/// List all the operations.
/// </remarks>
/// <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="ErrorException">
/// 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<OperationResponse>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<OperationResponse>>();
_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<OperationResponse>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
#if FEATURE_SERIALIZATION
using System.Runtime.Serialization.Formatters.Binary;
#endif
#if !FEATURE_REMOTING
using MarshalByRefObject = System.Object;
#endif
#if FEATURE_COM
using ComTypeLibInfo = Microsoft.Scripting.ComInterop.ComTypeLibInfo;
using ComTypeLibDesc = Microsoft.Scripting.ComInterop.ComTypeLibDesc;
#endif
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using Microsoft.Scripting;
using Microsoft.Scripting.Actions;
using Microsoft.Scripting.Generation;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython;
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
[assembly: PythonModule("clr", typeof(IronPython.Runtime.ClrModule))]
namespace IronPython.Runtime {
/// <summary>
/// this class contains objecs and static methods used for
/// .NET/CLS interop with Python.
/// </summary>
public static class ClrModule {
#if NETCOREAPP
public static readonly bool IsNetCoreApp = true;
#else
public static readonly bool IsNetCoreApp = false;
#endif
public static string TargetFramework => typeof(ClrModule).Assembly.GetCustomAttribute<TargetFrameworkAttribute>()?.FrameworkName;
internal static string FileVersion => typeof(ClrModule).Assembly.GetCustomAttribute<AssemblyFileVersionAttribute>()?.Version;
#if DEBUG
public static readonly bool IsDebug = true;
#else
public static readonly bool IsDebug = false;
#endif
internal static string FrameworkDescription {
get {
#if FEATURE_RUNTIMEINFORMATION
var frameworkDescription = RuntimeInformation.FrameworkDescription;
if (frameworkDescription.StartsWith(".NET Core 4.6.", StringComparison.OrdinalIgnoreCase)) {
return $".NET Core 2.x ({frameworkDescription.Substring(10)})";
}
return frameworkDescription;
#else
// try reflection since we're probably running on a newer runtime anyway
if (typeof(void).Assembly.GetType("System.Runtime.InteropServices.RuntimeInformation")?.GetProperty("FrameworkDescription")?.GetValue(null) is string frameworkDescription) {
return frameworkDescription;
}
return (IsMono ? "Mono " : ".NET Framework ") + Environment.Version.ToString();
#endif
}
}
private static int _isMono = -1;
public static bool IsMono {
get {
if(_isMono == -1) {
_isMono = Type.GetType ("Mono.Runtime") != null ? 1 : 0;
}
return _isMono == 1;
}
}
private static int _isMacOS = -1;
public static bool IsMacOS {
get {
if(_isMacOS == -1) {
_isMacOS = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? 1 : 0;
}
return _isMacOS == 1;
}
}
[SpecialName]
public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) {
if (!dict.ContainsKey("References")) {
dict["References"] = context.ReferencedAssemblies;
}
}
#region Public methods
/// <summary>
/// Gets the current ScriptDomainManager that IronPython is loaded into. The
/// ScriptDomainManager can then be used to work with the language portion of the
/// DLR hosting APIs.
/// </summary>
public static ScriptDomainManager/*!*/ GetCurrentRuntime(CodeContext/*!*/ context) {
return context.LanguageContext.DomainManager;
}
[Documentation(@"Adds a reference to a .NET assembly. Parameters can be an already loaded
Assembly object, a full assembly name, or a partial assembly name. After the
load the assemblies namespaces and top-level types will be available via
import Namespace.")]
public static void AddReference(CodeContext/*!*/ context, params object[] references) {
if (references == null) throw new TypeErrorException("Expected string or Assembly, got NoneType");
if (references.Length == 0) throw new ValueErrorException("Expected at least one name, got none");
ContractUtils.RequiresNotNull(context, "context");
foreach (object reference in references) {
AddReference(context, reference);
}
}
[Documentation(@"Adds a reference to a .NET assembly. One or more assembly names can
be provided. The assembly is searched for in the directories specified in
sys.path and dependencies will be loaded from sys.path as well. The assembly
name should be the filename on disk without a directory specifier and
optionally including the .EXE or .DLL extension. After the load the assemblies
namespaces and top-level types will be available via import Namespace.")]
public static void AddReferenceToFile(CodeContext/*!*/ context, params string[] files) {
if (files == null) throw new TypeErrorException("Expected string, got NoneType");
if (files.Length == 0) throw new ValueErrorException("Expected at least one name, got none");
ContractUtils.RequiresNotNull(context, "context");
foreach (string file in files) {
AddReferenceToFile(context, file);
}
}
[Documentation(@"Adds a reference to a .NET assembly. Parameters are an assembly name.
After the load the assemblies namespaces and top-level types will be available via
import Namespace.")]
public static void AddReferenceByName(CodeContext/*!*/ context, params string[] names) {
if (names == null) throw new TypeErrorException("Expected string, got NoneType");
if (names.Length == 0) throw new ValueErrorException("Expected at least one name, got none");
ContractUtils.RequiresNotNull(context, "context");
foreach (string name in names) {
AddReferenceByName(context, name);
}
}
#if FEATURE_LOADWITHPARTIALNAME
[Documentation(@"Adds a reference to a .NET assembly. Parameters are a partial assembly name.
After the load the assemblies namespaces and top-level types will be available via
import Namespace.")]
public static void AddReferenceByPartialName(CodeContext/*!*/ context, params string[] names) {
if (names == null) throw new TypeErrorException("Expected string, got NoneType");
if (names.Length == 0) throw new ValueErrorException("Expected at least one name, got none");
ContractUtils.RequiresNotNull(context, "context");
foreach (string name in names) {
AddReferenceByPartialName(context, name);
}
}
#endif
#if FEATURE_FILESYSTEM
[Documentation(@"Adds a reference to a .NET assembly. Parameters are a full path to an.
assembly on disk. After the load the assemblies namespaces and top-level types
will be available via import Namespace.")]
public static Assembly/*!*/ LoadAssemblyFromFileWithPath(CodeContext/*!*/ context, string/*!*/ file) {
if (file == null) throw new TypeErrorException("LoadAssemblyFromFileWithPath: arg 1 must be a string.");
Assembly res;
if (!context.LanguageContext.TryLoadAssemblyFromFileWithPath(file, out res)) {
if (!Path.IsPathRooted(file)) {
throw new ValueErrorException("LoadAssemblyFromFileWithPath: path must be rooted");
} else if (!File.Exists(file)) {
throw new ValueErrorException("LoadAssemblyFromFileWithPath: file not found");
} else {
throw new ValueErrorException("LoadAssemblyFromFileWithPath: error loading assembly");
}
}
return res;
}
[Documentation(@"Loads an assembly from the specified filename and returns the assembly
object. Namespaces or types in the assembly can be accessed directly from
the assembly object.")]
public static Assembly/*!*/ LoadAssemblyFromFile(CodeContext/*!*/ context, string/*!*/ file) {
if (file == null) throw new TypeErrorException("Expected string, got NoneType");
if (file.Length == 0) throw new ValueErrorException("assembly name must not be empty string");
ContractUtils.RequiresNotNull(context, "context");
if (file.IndexOf(System.IO.Path.DirectorySeparatorChar) != -1) {
throw new ValueErrorException("filenames must not contain full paths, first add the path to sys.path");
}
return context.LanguageContext.LoadAssemblyFromFile(file);
}
#endif
#if FEATURE_LOADWITHPARTIALNAME
[Documentation(@"Loads an assembly from the specified partial assembly name and returns the
assembly object. Namespaces or types in the assembly can be accessed directly
from the assembly object.")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadWithPartialName")]
public static Assembly/*!*/ LoadAssemblyByPartialName(string/*!*/ name) {
if (name == null) {
throw new TypeErrorException("LoadAssemblyByPartialName: arg 1 must be a string");
}
#pragma warning disable 618, 612 // csc
return Assembly.LoadWithPartialName(name);
#pragma warning restore 618, 612
}
#endif
[Documentation(@"Loads an assembly from the specified assembly name and returns the assembly
object. Namespaces or types in the assembly can be accessed directly from
the assembly object.")]
public static Assembly/*!*/ LoadAssemblyByName(CodeContext/*!*/ context, string/*!*/ name) {
if (name == null) {
throw new TypeErrorException("LoadAssemblyByName: arg 1 must be a string");
}
return context.LanguageContext.DomainManager.Platform.LoadAssembly(name);
}
/// <summary>
/// Use(name) -> module
///
/// Attempts to load the specified module searching all languages in the loaded ScriptRuntime.
/// </summary>
public static object Use(CodeContext/*!*/ context, string/*!*/ name) {
ContractUtils.RequiresNotNull(context, "context");
if (name == null) {
throw new TypeErrorException("Use: arg 1 must be a string");
}
var scope = Importer.TryImportSourceFile(context.LanguageContext, name);
if (scope == null) {
throw new ValueErrorException(String.Format("couldn't find module {0} to use", name));
}
return scope;
}
[Documentation("Converts an array of bytes to a string.")]
public static string GetString(byte[] bytes) {
return GetString(bytes, bytes.Length);
}
[Documentation("Converts maxCount of an array of bytes to a string")]
public static string GetString(byte[] bytes, int maxCount) {
int bytesToCopy = Math.Min(bytes.Length, maxCount);
return Encoding.GetEncoding("iso-8859-1").GetString(bytes, 0, bytesToCopy);
}
[Documentation("Converts a string to an array of bytes")]
public static byte[] GetBytes(string s) {
return GetBytes(s, s.Length);
}
[Documentation("Converts maxCount of a string to an array of bytes")]
public static byte[] GetBytes(string s, int maxCount) {
int charsToCopy = Math.Min(s.Length, maxCount);
byte[] ret = new byte[charsToCopy];
Encoding.GetEncoding("iso-8859-1").GetBytes(s, 0, charsToCopy, ret, 0);
return ret;
}
/// <summary>
/// Use(path, language) -> module
///
/// Attempts to load the specified module belonging to a specific language loaded into the
/// current ScriptRuntime.
/// </summary>
public static object/*!*/ Use(CodeContext/*!*/ context, string/*!*/ path, string/*!*/ language) {
ContractUtils.RequiresNotNull(context, "context");
if (path == null) {
throw new TypeErrorException("Use: arg 1 must be a string");
}
if (language == null) {
throw new TypeErrorException("Use: arg 2 must be a string");
}
var manager = context.LanguageContext.DomainManager;
if (!manager.Platform.FileExists(path)) {
throw new ValueErrorException(String.Format("couldn't load module at path '{0}' in language '{1}'", path, language));
}
var sourceUnit = manager.GetLanguageByName(language).CreateFileUnit(path);
return Importer.ExecuteSourceUnit(context.LanguageContext, sourceUnit);
}
/// <summary>
/// SetCommandDispatcher(commandDispatcher)
///
/// Sets the current command dispatcher for the Python command line.
///
/// The command dispatcher will be called with a delegate to be executed. The command dispatcher
/// should invoke the target delegate in the desired context.
///
/// A common use for this is to enable running all REPL commands on the UI thread while the REPL
/// continues to run on a non-UI thread.
/// </summary>
public static Action<Action> SetCommandDispatcher(CodeContext/*!*/ context, Action<Action> dispatcher) {
ContractUtils.RequiresNotNull(context, "context");
return ((PythonContext)context.LanguageContext).GetSetCommandDispatcher(dispatcher);
}
public static void ImportExtensions(CodeContext/*!*/ context, PythonType type) {
if (type == null) {
throw PythonOps.TypeError("type must not be None");
} else if (!type.IsSystemType) {
throw PythonOps.ValueError("type must be .NET type");
}
lock (context.ModuleContext) {
context.ModuleContext.ExtensionMethods = ExtensionMethodSet.AddType(context.LanguageContext, context.ModuleContext.ExtensionMethods, type);
}
}
public static void ImportExtensions(CodeContext/*!*/ context, [NotNull]NamespaceTracker @namespace) {
lock (context.ModuleContext) {
context.ModuleContext.ExtensionMethods = ExtensionMethodSet.AddNamespace(context.LanguageContext, context.ModuleContext.ExtensionMethods, @namespace);
}
}
#if FEATURE_COM
/// <summary>
/// LoadTypeLibrary(rcw) -> type lib desc
///
/// Gets an ITypeLib object from OLE Automation compatible RCW ,
/// reads definitions of CoClass'es and Enum's from this library
/// and creates an object that allows to instantiate coclasses
/// and get actual values for the enums.
/// </summary>
public static ComTypeLibInfo LoadTypeLibrary(CodeContext/*!*/ context, object rcw) {
return ComTypeLibDesc.CreateFromObject(rcw);
}
/// <summary>
/// LoadTypeLibrary(guid) -> type lib desc
///
/// Reads the latest registered type library for the corresponding GUID,
/// reads definitions of CoClass'es and Enum's from this library
/// and creates a IDynamicMetaObjectProvider that allows to instantiate coclasses
/// and get actual values for the enums.
/// </summary>
public static ComTypeLibInfo LoadTypeLibrary(CodeContext/*!*/ context, Guid typeLibGuid) {
return ComTypeLibDesc.CreateFromGuid(typeLibGuid);
}
/// <summary>
/// AddReferenceToTypeLibrary(rcw) -> None
///
/// Makes the type lib desc available for importing. See also LoadTypeLibrary.
/// </summary>
public static void AddReferenceToTypeLibrary(CodeContext/*!*/ context, object rcw) {
ComTypeLibInfo typeLibInfo;
typeLibInfo = ComTypeLibDesc.CreateFromObject(rcw);
PublishTypeLibDesc(context, typeLibInfo.TypeLibDesc);
}
/// <summary>
/// AddReferenceToTypeLibrary(guid) -> None
///
/// Makes the type lib desc available for importing. See also LoadTypeLibrary.
/// </summary>
public static void AddReferenceToTypeLibrary(CodeContext/*!*/ context, Guid typeLibGuid) {
ComTypeLibInfo typeLibInfo;
typeLibInfo = ComTypeLibDesc.CreateFromGuid(typeLibGuid);
PublishTypeLibDesc(context, typeLibInfo.TypeLibDesc);
}
private static void PublishTypeLibDesc(CodeContext context, ComTypeLibDesc typeLibDesc) {
PythonOps.ScopeSetMember(context, context.LanguageContext.DomainManager.Globals, typeLibDesc.Name, typeLibDesc);
}
#endif
#endregion
#region Private implementation methods
private static void AddReference(CodeContext/*!*/ context, object reference) {
Assembly asmRef = reference as Assembly;
if (asmRef != null) {
AddReference(context, asmRef);
return;
}
if (reference is string strRef) {
AddReference(context, strRef);
return;
}
throw new TypeErrorException(String.Format("Invalid assembly type. Expected string or Assembly, got {0}.", reference));
}
private static void AddReference(CodeContext/*!*/ context, Assembly assembly) {
context.LanguageContext.DomainManager.LoadAssembly(assembly);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] // TODO: fix
private static void AddReference(CodeContext/*!*/ context, string name) {
if (name == null) throw new TypeErrorException("Expected string, got NoneType");
Assembly asm = null;
try {
asm = LoadAssemblyByName(context, name);
} catch { }
// note we don't explicit call to get the file version
// here because the assembly resolve event will do it for us.
#if FEATURE_LOADWITHPARTIALNAME
if (asm == null) {
asm = LoadAssemblyByPartialName(name);
}
#endif
if (asm == null) {
throw new IOException(String.Format("Could not add reference to assembly {0}", name));
}
AddReference(context, asm);
}
private static void AddReferenceToFile(CodeContext/*!*/ context, string file) {
if (file == null) throw new TypeErrorException("Expected string, got NoneType");
#if FEATURE_FILESYSTEM
Assembly asm = LoadAssemblyFromFile(context, file);
#else
Assembly asm = context.LanguageContext.DomainManager.Platform.LoadAssemblyFromPath(file);
#endif
if (asm == null) {
throw new IOException(String.Format("Could not add reference to assembly {0}", file));
}
AddReference(context, asm);
}
#if FEATURE_LOADWITHPARTIALNAME
private static void AddReferenceByPartialName(CodeContext/*!*/ context, string name) {
if (name == null) throw new TypeErrorException("Expected string, got NoneType");
ContractUtils.RequiresNotNull(context, "context");
Assembly asm = LoadAssemblyByPartialName(name);
if (asm == null) {
throw new IOException(String.Format("Could not add reference to assembly {0}", name));
}
AddReference(context, asm);
}
#endif
private static void AddReferenceByName(CodeContext/*!*/ context, string name) {
if (name == null) throw new TypeErrorException("Expected string, got NoneType");
Assembly asm = LoadAssemblyByName(context, name);
if (asm == null) {
throw new IOException(String.Format("Could not add reference to assembly {0}", name));
}
AddReference(context, asm);
}
#endregion
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] // TODO: fix
public sealed class ReferencesList : List<Assembly>, ICodeFormattable {
public new void Add(Assembly other) {
base.Add(other);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists"), SpecialName]
public ClrModule.ReferencesList Add(object other) {
IEnumerator ie = PythonOps.GetEnumerator(other);
while (ie.MoveNext()) {
Assembly cur = ie.Current as Assembly;
if (cur == null) throw PythonOps.TypeError("non-assembly added to references list");
base.Add(cur);
}
return this;
}
public string/*!*/ __repr__(CodeContext/*!*/ context) {
StringBuilder res = new StringBuilder("(");
string comma = "";
foreach (Assembly asm in this) {
res.Append(comma);
res.Append('<');
res.Append(asm.FullName);
res.Append('>');
comma = "," + Environment.NewLine;
}
res.AppendLine(")");
return res.ToString();
}
}
private static PythonType _strongBoxType;
#region Runtime Type Checking support
#if FEATURE_FILESYSTEM
[Documentation(@"Adds a reference to a .NET assembly. One or more assembly names can
be provided which are fully qualified names to the file on disk. The
directory is added to sys.path and AddReferenceToFile is then called. After the
load the assemblies namespaces and top-level types will be available via
import Namespace.")]
public static void AddReferenceToFileAndPath(CodeContext/*!*/ context, params string[] files) {
if (files == null) throw new TypeErrorException("Expected string, got NoneType");
ContractUtils.RequiresNotNull(context, "context");
foreach (string file in files) {
AddReferenceToFileAndPath(context, file);
}
}
private static void AddReferenceToFileAndPath(CodeContext/*!*/ context, string file) {
if (file == null) throw PythonOps.TypeError("Expected string, got NoneType");
// update our path w/ the path of this file...
string path = System.IO.Path.GetDirectoryName(Path.GetFullPath(file));
List list;
PythonContext pc = context.LanguageContext;
if (!pc.TryGetSystemPath(out list)) {
throw PythonOps.TypeError("cannot update path, it is not a list");
}
list.append(path);
Assembly asm = pc.LoadAssemblyFromFile(file);
if (asm == null) throw PythonOps.IOError("file does not exist: {0}", file);
AddReference(context, asm);
}
#endif
/// <summary>
/// Gets the CLR Type object from a given Python type object.
/// </summary>
public static Type GetClrType(Type type) {
return type;
}
/// <summary>
/// Gets the Python type object from a given CLR Type object.
/// </summary>
public static PythonType GetPythonType(Type t) {
return DynamicHelpers.GetPythonTypeFromType(t);
}
/// <summary>
/// OBSOLETE: Gets the Python type object from a given CLR Type object.
///
/// Use clr.GetPythonType instead.
/// </summary>
[Obsolete("Call clr.GetPythonType instead")]
public static PythonType GetDynamicType(Type t) {
return DynamicHelpers.GetPythonTypeFromType(t);
}
public static PythonType Reference {
get {
return StrongBox;
}
}
public static PythonType StrongBox {
get {
if (_strongBoxType == null) {
_strongBoxType = DynamicHelpers.GetPythonTypeFromType(typeof(StrongBox<>));
}
return _strongBoxType;
}
}
/// <summary>
/// accepts(*types) -> ArgChecker
///
/// Decorator that returns a new callable object which will validate the arguments are of the specified types.
/// </summary>
/// <param name="types"></param>
/// <returns></returns>
public static object accepts(params object[] types) {
return new ArgChecker(types);
}
/// <summary>
/// returns(type) -> ReturnChecker
///
/// Returns a new callable object which will validate the return type is of the specified type.
/// </summary>
public static object returns(object type) {
return new ReturnChecker(type);
}
public static object Self() {
return null;
}
#endregion
/// <summary>
/// Decorator for verifying the arguments to a function are of a specified type.
/// </summary>
public class ArgChecker {
private object[] expected;
public ArgChecker(object[] prms) {
expected = prms;
}
#region ICallableWithCodeContext Members
[SpecialName]
public object Call(CodeContext context, object func) {
// expect only to receive the function we'll call here.
return new RuntimeArgChecker(func, expected);
}
#endregion
}
/// <summary>
/// Returned value when using clr.accepts/ArgChecker. Validates the argument types and
/// then calls the original function.
/// </summary>
public class RuntimeArgChecker : PythonTypeSlot {
private object[] _expected;
private object _func;
private object _inst;
public RuntimeArgChecker(object function, object[] expectedArgs) {
_expected = expectedArgs;
_func = function;
}
public RuntimeArgChecker(object instance, object function, object[] expectedArgs)
: this(function, expectedArgs) {
_inst = instance;
}
private void ValidateArgs(object[] args) {
int start = 0;
if (_inst != null) {
start = 1;
}
// no need to validate self... the method should handle it.
for (int i = start; i < args.Length + start; i++) {
PythonType dt = DynamicHelpers.GetPythonType(args[i - start]);
if (!(_expected[i] is PythonType expct)) expct = ((OldClass)_expected[i]).TypeObject;
if (dt != _expected[i] && !dt.IsSubclassOf(expct)) {
throw PythonOps.AssertionError("argument {0} has bad value (got {1}, expected {2})", i, dt, _expected[i]);
}
}
}
#region ICallableWithCodeContext Members
[SpecialName]
public object Call(CodeContext context, params object[] args) {
ValidateArgs(args);
if (_inst != null) {
return PythonOps.CallWithContext(context, _func, ArrayUtils.Insert(_inst, args));
} else {
return PythonOps.CallWithContext(context, _func, args);
}
}
#endregion
internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value) {
value = new RuntimeArgChecker(instance, _func, _expected);
return true;
}
internal override bool GetAlwaysSucceeds {
get {
return true;
}
}
#region IFancyCallable Members
[SpecialName]
public object Call(CodeContext context, [ParamDictionary]IDictionary<object, object> dict, params object[] args) {
ValidateArgs(args);
if (_inst != null) {
return PythonCalls.CallWithKeywordArgs(context, _func, ArrayUtils.Insert(_inst, args), dict);
} else {
return PythonCalls.CallWithKeywordArgs(context, _func, args, dict);
}
}
#endregion
}
/// <summary>
/// Decorator for verifying the return type of functions.
/// </summary>
public class ReturnChecker {
public object retType;
public ReturnChecker(object returnType) {
retType = returnType;
}
#region ICallableWithCodeContext Members
[SpecialName]
public object Call(CodeContext context, object func) {
// expect only to receive the function we'll call here.
return new RuntimeReturnChecker(func, retType);
}
#endregion
}
/// <summary>
/// Returned value when using clr.returns/ReturnChecker. Calls the original function and
/// validates the return type is of a specified type.
/// </summary>
public class RuntimeReturnChecker : PythonTypeSlot {
private object _retType;
private object _func;
private object _inst;
public RuntimeReturnChecker(object function, object expectedReturn) {
_retType = expectedReturn;
_func = function;
}
public RuntimeReturnChecker(object instance, object function, object expectedReturn)
: this(function, expectedReturn) {
_inst = instance;
}
private void ValidateReturn(object ret) {
// we return void...
if (ret == null && _retType == null) return;
PythonType dt = DynamicHelpers.GetPythonType(ret);
if (dt != _retType) {
if (!(_retType is PythonType expct)) expct = ((OldClass)_retType).TypeObject;
if (!dt.IsSubclassOf(expct))
throw PythonOps.AssertionError("bad return value returned (expected {0}, got {1})", _retType, dt);
}
}
#region ICallableWithCodeContext Members
[SpecialName]
public object Call(CodeContext context, params object[] args) {
object ret;
if (_inst != null) {
ret = PythonOps.CallWithContext(context, _func, ArrayUtils.Insert(_inst, args));
} else {
ret = PythonOps.CallWithContext(context, _func, args);
}
ValidateReturn(ret);
return ret;
}
#endregion
#region IDescriptor Members
public object GetAttribute(object instance, object owner) {
return new RuntimeReturnChecker(instance, _func, _retType);
}
#endregion
internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value) {
value = GetAttribute(instance, owner);
return true;
}
internal override bool GetAlwaysSucceeds {
get {
return true;
}
}
#region IFancyCallable Members
[SpecialName]
public object Call(CodeContext context, [ParamDictionary]IDictionary<object, object> dict, params object[] args) {
object ret;
if (_inst != null) {
ret = PythonCalls.CallWithKeywordArgs(context, _func, ArrayUtils.Insert(_inst, args), dict);
} else {
return PythonCalls.CallWithKeywordArgs(context, _func, args, dict);
}
ValidateReturn(ret);
return ret;
}
#endregion
}
/// <summary>
/// returns the result of dir(o) as-if "import clr" has not been performed.
/// </summary>
public static List Dir(object o) {
IList<object> ret = PythonOps.GetAttrNames(DefaultContext.Default, o);
List lret = new List(ret);
lret.sort(DefaultContext.Default);
return lret;
}
/// <summary>
/// Returns the result of dir(o) as-if "import clr" has been performed.
/// </summary>
public static List DirClr(object o) {
IList<object> ret = PythonOps.GetAttrNames(DefaultContext.DefaultCLS, o);
List lret = new List(ret);
lret.sort(DefaultContext.DefaultCLS);
return lret;
}
/// <summary>
/// Attempts to convert the provided object to the specified type. Conversions that
/// will be attempted include standard Python conversions as well as .NET implicit
/// and explicit conversions.
///
/// If the conversion cannot be performed a TypeError will be raised.
/// </summary>
public static object Convert(CodeContext/*!*/ context, object o, Type toType) {
return Converter.Convert(o, toType);
}
#if FEATURE_FILESYSTEM && FEATURE_REFEMIT
/// <summary>
/// Provides a helper for compiling a group of modules into a single assembly. The assembly can later be
/// reloaded using the clr.AddReference API.
/// </summary>
public static void CompileModules(CodeContext/*!*/ context, string/*!*/ assemblyName, [ParamDictionary]IDictionary<string, object> kwArgs, params string/*!*/[]/*!*/ filenames) {
ContractUtils.RequiresNotNull(assemblyName, "assemblyName");
ContractUtils.RequiresNotNullItems(filenames, "filenames");
PythonContext pc = context.LanguageContext;
for (int i = 0; i < filenames.Length; i++) {
filenames[i] = Path.GetFullPath(filenames[i]);
}
Dictionary<string, string> packageMap = BuildPackageMap(filenames);
List<SavableScriptCode> code = new List<SavableScriptCode>();
foreach (string filename in filenames) {
if (!pc.DomainManager.Platform.FileExists(filename)) {
throw PythonOps.IOError($"Couldn't find file for compilation: {filename}");
}
ScriptCode sc;
string modName;
string dname = Path.GetDirectoryName(filename);
string outFilename = "";
if (Path.GetFileName(filename) == "__init__.py") {
// remove __init__.py to get package name
dname = Path.GetDirectoryName(dname);
if (String.IsNullOrEmpty(dname)) {
modName = Path.GetDirectoryName(filename);
} else {
modName = Path.GetFileNameWithoutExtension(Path.GetDirectoryName(filename));
}
outFilename = Path.DirectorySeparatorChar + "__init__.py";
} else {
modName = Path.GetFileNameWithoutExtension(filename);
}
// see if we have a parent package, if so incorporate it into
// our name
if (packageMap.TryGetValue(dname, out string parentPackage)) {
modName = parentPackage + "." + modName;
}
outFilename = modName.Replace('.', Path.DirectorySeparatorChar) + outFilename;
SourceUnit su = pc.CreateSourceUnit(
new FileStreamContentProvider(
context.LanguageContext.DomainManager.Platform,
filename
),
outFilename,
pc.DefaultEncoding,
SourceCodeKind.File
);
sc = context.LanguageContext.GetScriptCode(su, modName, ModuleOptions.Initialize, Compiler.CompilationMode.ToDisk);
code.Add((SavableScriptCode)sc);
}
if (kwArgs != null && kwArgs.TryGetValue("mainModule", out object mainModule)) {
if (mainModule is string strModule) {
if (!pc.DomainManager.Platform.FileExists(strModule)) {
throw PythonOps.IOError("Couldn't find main file for compilation: {0}", strModule);
}
SourceUnit su = pc.CreateFileUnit(strModule, pc.DefaultEncoding, SourceCodeKind.File);
code.Add((SavableScriptCode)context.LanguageContext.GetScriptCode(su, "__main__", ModuleOptions.Initialize, Compiler.CompilationMode.ToDisk));
}
}
SavableScriptCode.SaveToAssembly(assemblyName, kwArgs, code.ToArray());
}
#endif
#if FEATURE_REFEMIT
/// <summary>
/// clr.CompileSubclassTypes(assemblyName, *typeDescription)
///
/// Provides a helper for creating an assembly which contains pre-generated .NET
/// base types for new-style types.
///
/// This assembly can then be AddReferenced or put sys.prefix\DLLs and the cached
/// types will be used instead of generating the types at runtime.
///
/// This function takes the name of the assembly to save to and then an arbitrary
/// number of parameters describing the types to be created. Each of those
/// parameter can either be a plain type or a sequence of base types.
///
/// clr.CompileSubclassTypes(object) -> create a base type for object
/// clr.CompileSubclassTypes(object, str, System.Collections.ArrayList) -> create
/// base types for both object and ArrayList.
///
/// clr.CompileSubclassTypes(object, (object, IComparable)) -> create base types for
/// object and an object which implements IComparable.
///
/// </summary>
public static void CompileSubclassTypes(string/*!*/ assemblyName, params object[] newTypes) {
if (assemblyName == null) {
throw PythonOps.TypeError("CompileTypes expected str for assemblyName, got NoneType");
}
var typesToCreate = new List<PythonTuple>();
foreach (object o in newTypes) {
if (o is PythonType) {
typesToCreate.Add(PythonTuple.MakeTuple(o));
} else {
typesToCreate.Add(PythonTuple.Make(o));
}
}
NewTypeMaker.SaveNewTypes(assemblyName, typesToCreate);
}
#endif
/// <summary>
/// clr.GetSubclassedTypes() -> tuple
///
/// Returns a tuple of information about the types which have been subclassed.
///
/// This tuple can be passed to clr.CompileSubclassTypes to cache these
/// types on disk such as:
///
/// clr.CompileSubclassTypes('assembly', *clr.GetSubclassedTypes())
/// </summary>
public static PythonTuple GetSubclassedTypes() {
List<object> res = new List<object>();
foreach (NewTypeInfo info in NewTypeMaker._newTypes.Keys) {
Type clrBaseType = info.BaseType;
Type tempType = clrBaseType;
while (tempType != null) {
if (tempType.IsGenericType && tempType.GetGenericTypeDefinition() == typeof(Extensible<>)) {
clrBaseType = tempType.GetGenericArguments()[0];
break;
}
tempType = tempType.BaseType;
}
PythonType baseType = DynamicHelpers.GetPythonTypeFromType(clrBaseType);
if (info.InterfaceTypes.Count == 0) {
res.Add(baseType);
} else if (info.InterfaceTypes.Count > 0) {
PythonType[] types = new PythonType[info.InterfaceTypes.Count + 1];
types[0] = baseType;
for (int i = 0; i < info.InterfaceTypes.Count; i++) {
types[i + 1] = DynamicHelpers.GetPythonTypeFromType(info.InterfaceTypes[i]);
}
res.Add(PythonTuple.MakeTuple(types));
}
}
return PythonTuple.MakeTuple(res.ToArray());
}
/// <summary>
/// Provides a StreamContentProvider for a stream of content backed by a file on disk.
/// </summary>
[Serializable]
internal sealed class FileStreamContentProvider : StreamContentProvider {
private readonly string _path;
private readonly PALHolder _pal;
internal string Path {
get { return _path; }
}
#region Construction
internal FileStreamContentProvider(PlatformAdaptationLayer manager, string path) {
ContractUtils.RequiresNotNull(path, "path");
_path = path;
_pal = new PALHolder(manager);
}
#endregion
public override Stream GetStream() {
return _pal.GetStream(Path);
}
[Serializable]
private class PALHolder : MarshalByRefObject {
[NonSerialized]
private readonly PlatformAdaptationLayer _pal;
internal PALHolder(PlatformAdaptationLayer pal) {
_pal = pal;
}
internal Stream GetStream(string path) {
return _pal.OpenInputFileStream(path);
}
}
}
/// <summary>
/// Goes through the list of files identifying the relationship between packages
/// and subpackages. Returns a dictionary with all of the package filenames (minus __init__.py)
/// mapping to their full name. For example given a structure:
///
/// C:\
/// someDir\
/// package\
/// __init__.py
/// a.py
/// b\
/// __init.py
/// c.py
///
/// Returns:
/// {r'C:\somedir\package' : 'package', r'C:\somedir\package\b', 'package.b'}
///
/// This can then be used for calculating the full module name of individual files
/// and packages. For example a's full name is "package.a" and c's full name is
/// "package.b.c".
/// </summary>
private static Dictionary<string/*!*/, string/*!*/>/*!*/ BuildPackageMap(string/*!*/[]/*!*/ filenames) {
// modules which are the children of packages should have the __name__
// package.subpackage.modulename, not just modulename. So first
// we need to get a list of all the modules...
List<string> modules = new List<string>();
foreach (string filename in filenames) {
if (filename.EndsWith("__init__.py")) {
// this is a package
modules.Add(filename);
}
}
// next we need to understand the relationship between the packages so
// if we have package.subpackage1 and package.subpackage2 we know
// both of these are children of the package. So sort the module names,
// shortest name first...
SortModules(modules);
// finally build up the package names for the dirs...
Dictionary<string, string> packageMap = new Dictionary<string, string>();
foreach (string packageName in modules) {
string dirName = Path.GetDirectoryName(packageName); // remove __init__.py
string pkgName = String.Empty;
string fullName = Path.GetFileName(Path.GetDirectoryName(packageName));
if (packageMap.TryGetValue(Path.GetDirectoryName(dirName), out pkgName)) { // remove directory name
fullName = pkgName + "." + fullName;
}
packageMap[Path.GetDirectoryName(packageName)] = fullName;
}
return packageMap;
}
private static void SortModules(List<string> modules) {
modules.Sort((string x, string y) => x.Length - y.Length);
}
/// <summary>
/// Returns a list of profile data. The values are tuples of Profiler.Data objects
///
/// All times are expressed in the same unit of measure as DateTime.Ticks
/// </summary>
public static PythonTuple GetProfilerData(CodeContext/*!*/ context, [DefaultParameterValue(false)]bool includeUnused) {
return new PythonTuple(Profiler.GetProfiler(context.LanguageContext).GetProfile(includeUnused));
}
/// <summary>
/// Resets all profiler counters back to zero
/// </summary>
public static void ClearProfilerData(CodeContext/*!*/ context) {
Profiler.GetProfiler(context.LanguageContext).Reset();
}
/// <summary>
/// Enable or disable profiling for the current ScriptEngine. This will only affect code
/// that is compiled after the setting is changed; previously-compiled code will retain
/// whatever setting was active when the code was originally compiled.
///
/// The easiest way to recompile a module is to reload() it.
/// </summary>
public static void EnableProfiler(CodeContext/*!*/ context, bool enable) {
var pc = context.LanguageContext;
var po = pc.Options as PythonOptions;
po.EnableProfiler = enable;
}
#if FEATURE_SERIALIZATION
/// <summary>
/// Serializes data using the .NET serialization formatter for complex
/// types. Returns a tuple identifying the serialization format and the serialized
/// data which can be fed back into clr.Deserialize.
///
/// Current serialization formats include custom formats for primitive .NET
/// types which aren't already recognized as tuples. None is used to indicate
/// that the Binary .NET formatter is used.
/// </summary>
public static PythonTuple/*!*/ Serialize(object self) {
if (self == null) {
return PythonTuple.MakeTuple(null, String.Empty);
}
string data, format;
switch (CompilerHelpers.GetType(self).GetTypeCode()) {
// for the primitive non-python types just do a simple
// serialization
case TypeCode.Byte:
case TypeCode.Char:
case TypeCode.DBNull:
case TypeCode.Decimal:
case TypeCode.Int16:
case TypeCode.Int64:
case TypeCode.SByte:
case TypeCode.Single:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
data = self.ToString();
format = CompilerHelpers.GetType(self).FullName;
break;
default:
// something more complex, let the binary formatter handle it
BinaryFormatter bf = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
bf.Serialize(stream, self);
data = stream.ToArray().MakeString();
format = null;
break;
}
return PythonTuple.MakeTuple(format, data);
}
/// <summary>
/// Deserializes the result of a Serialize call. This can be used to perform serialization
/// for .NET types which are serializable. This method is the callable object provided
/// from __reduce_ex__ for .serializable .NET types.
///
/// The first parameter indicates the serialization format and is the first tuple element
/// returned from the Serialize call.
///
/// The second parameter is the serialized data.
/// </summary>
public static object Deserialize(string serializationFormat, [NotNull]string/*!*/ data) {
if (serializationFormat != null) {
switch (serializationFormat) {
case "System.Byte": return Byte.Parse(data);
case "System.Char": return Char.Parse(data);
case "System.DBNull": return DBNull.Value;
case "System.Decimal": return Decimal.Parse(data);
case "System.Int16": return Int16.Parse(data);
case "System.Int64": return Int64.Parse(data);
case "System.SByte": return SByte.Parse(data);
case "System.Single": return Single.Parse(data);
case "System.UInt16": return UInt16.Parse(data);
case "System.UInt32": return UInt32.Parse(data);
case "System.UInt64": return UInt64.Parse(data);
default:
throw PythonOps.ValueError("unknown serialization format: {0}", serializationFormat);
}
} else if (String.IsNullOrEmpty(data)) {
return null;
}
MemoryStream stream = new MemoryStream(data.MakeByteArray());
BinaryFormatter bf = new BinaryFormatter();
return bf.Deserialize(stream);
}
#endif
}
}
| |
#region License
//
// The Open Toolkit Library License
//
// Copyright (c) 2006 - 2010 the Open Toolkit library.
//
// 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.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Reflection;
namespace OpenTK
{
#region BlittableValueType<T>
/// <summary>
/// Checks whether the specified type parameter is a blittable value type.
/// </summary>
/// <remarks>
/// A blittable value type is a struct that only references other value types recursively,
/// which allows it to be passed to unmanaged code directly.
/// </remarks>
public static class BlittableValueType<T>
{
#region Fields
static readonly Type Type;
static readonly int stride;
#endregion
#region Constructors
static BlittableValueType()
{
Type = typeof(T);
if (Type.IsValueType && !Type.IsGenericType)
{
// Does this support generic types? On Mono 2.4.3 it does
// On .Net it doesn't.
// http://msdn.microsoft.com/en-us/library/5s4920fa.aspx
stride = Marshal.SizeOf(typeof(T));
}
}
#endregion
#region Public Members
/// <summary>
/// Gets the size of the type in bytes or 0 for non-blittable types.
/// </summary>
/// <remarks>
/// This property returns 0 for non-blittable types.
/// </remarks>
public static int Stride { get { return stride; } }
#region Check
/// <summary>
/// Checks whether the current typename T is blittable.
/// </summary>
/// <returns>True if T is blittable; false otherwise.</returns>
public static bool Check()
{
return Check(Type);
}
/// <summary>
/// Checks whether type is a blittable value type.
/// </summary>
/// <param name="type">A System.Type to check.</param>
/// <returns>True if T is blittable; false otherwise.</returns>
public static bool Check(Type type)
{
if (!CheckStructLayoutAttribute(type))
Debug.Print("Warning: type {0} does not specify a StructLayoutAttribute with Pack=1. The memory layout of the struct may change between platforms.", type.Name);
return CheckType(type);
}
#endregion
#endregion
#region Private Members
// Checks whether the parameter is a primitive type or consists of primitive types recursively.
// Throws a NotSupportedException if it is not.
static bool CheckType(Type type)
{
//Debug.Print("Checking type {0} (size: {1} bytes).", type.Name, Marshal.SizeOf(type));
if (type.IsPrimitive)
return true;
if (!type.IsValueType)
return false;
FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
Debug.Indent();
foreach (FieldInfo field in fields)
{
if (!CheckType(field.FieldType))
return false;
}
Debug.Unindent();
return Stride != 0;
}
// Checks whether the specified struct defines [StructLayout(LayoutKind.Sequential, Pack=1)]
// or [StructLayout(LayoutKind.Explicit)]
static bool CheckStructLayoutAttribute(Type type)
{
StructLayoutAttribute[] attr = (StructLayoutAttribute[])
type.GetCustomAttributes(typeof(StructLayoutAttribute), true);
if ((attr == null) ||
(attr != null && attr.Length > 0 && attr[0].Value != LayoutKind.Explicit && attr[0].Pack != 1))
return false;
return true;
}
#endregion
}
#endregion
#region BlittableValueType
/// <summary>
/// Checks whether the specified type parameter is a blittable value type.
/// </summary>
/// <remarks>
/// A blittable value type is a struct that only references other value types recursively,
/// which allows it to be passed to unmanaged code directly.
/// </remarks>
public static class BlittableValueType
{
#region Check
/// <summary>
/// Checks whether type is a blittable value type.
/// </summary>
/// <param name="type">An instance of the type to check.</param>
/// <returns>True if T is blittable; false otherwise.</returns>
public static bool Check<T>(T type)
{
return BlittableValueType<T>.Check();
}
/// <summary>
/// Checks whether type is a blittable value type.
/// </summary>
/// <param name="type">An instance of the type to check.</param>
/// <returns>True if T is blittable; false otherwise.</returns>
public static bool Check<T>(T[] type)
{
return BlittableValueType<T>.Check();
}
/// <summary>
/// Checks whether type is a blittable value type.
/// </summary>
/// <param name="type">An instance of the type to check.</param>
/// <returns>True if T is blittable; false otherwise.</returns>
public static bool Check<T>(T[,] type)
{
return BlittableValueType<T>.Check();
}
/// <summary>
/// Checks whether type is a blittable value type.
/// </summary>
/// <param name="type">An instance of the type to check.</param>
/// <returns>True if T is blittable; false otherwise.</returns>
public static bool Check<T>(T[, ,] type)
{
return BlittableValueType<T>.Check();
}
/// <summary>
/// Checks whether type is a blittable value type.
/// </summary>
/// <param name="type">An instance of the type to check.</param>
/// <returns>True if T is blittable; false otherwise.</returns>
[CLSCompliant(false)]
public static bool Check<T>(T[][] type)
{
return BlittableValueType<T>.Check();
}
#endregion
#region StrideOf
/// <summary>
/// Returns the size of the specified value type in bytes or 0 if the type is not blittable.
/// </summary>
/// <typeparam name="T">The value type. Must be blittable.</typeparam>
/// <param name="type">An instance of the value type.</param>
/// <returns>An integer, specifying the size of the type in bytes.</returns>
/// <exception cref="System.ArgumentException">Occurs when type is not blittable.</exception>
public static int StrideOf<T>(T type)
{
if (!Check(type))
throw new ArgumentException("type");
return BlittableValueType<T>.Stride;
}
/// <summary>
/// Returns the size of a single array element in bytes or 0 if the element is not blittable.
/// </summary>
/// <typeparam name="T">The value type.</typeparam>
/// <param name="type">An instance of the value type.</param>
/// <returns>An integer, specifying the size of the type in bytes.</returns>
/// <exception cref="System.ArgumentException">Occurs when type is not blittable.</exception>
public static int StrideOf<T>(T[] type)
{
if (!Check(type))
throw new ArgumentException("type");
return BlittableValueType<T>.Stride;
}
/// <summary>
/// Returns the size of a single array element in bytes or 0 if the element is not blittable.
/// </summary>
/// <typeparam name="T">The value type.</typeparam>
/// <param name="type">An instance of the value type.</param>
/// <returns>An integer, specifying the size of the type in bytes.</returns>
/// <exception cref="System.ArgumentException">Occurs when type is not blittable.</exception>
public static int StrideOf<T>(T[,] type)
{
if (!Check(type))
throw new ArgumentException("type");
return BlittableValueType<T>.Stride;
}
/// <summary>
/// Returns the size of a single array element in bytes or 0 if the element is not blittable.
/// </summary>
/// <typeparam name="T">The value type.</typeparam>
/// <param name="type">An instance of the value type.</param>
/// <returns>An integer, specifying the size of the type in bytes.</returns>
/// <exception cref="System.ArgumentException">Occurs when type is not blittable.</exception>
public static int StrideOf<T>(T[, ,] type)
{
if (!Check(type))
throw new ArgumentException("type");
return BlittableValueType<T>.Stride;
}
#endregion
}
#endregion
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace Pathfinding {
using Pathfinding.Util;
/** Linearly interpolating movement script.
* This movement script will follow the path exactly, it uses linear interpolation to move between the waypoints in the path.
* This is desirable for some types of games.
* It also works in 2D.
*
* \see You can see an example of this script in action in the example scene called \a Example15_2D.
*
* \section rec Configuration
* \subsection rec-snapped Recommended setup for movement along connections
*
* This depends on what type of movement you are aiming for.
* If you are aiming for movement where the unit follows the path exactly and move only along the graph connections on a grid/point graph.
* I recommend that you adjust the StartEndModifier on the Seeker component: set the 'Start Point Snapping' field to 'NodeConnection' and the 'End Point Snapping' field to 'SnapToNode'.
* \shadowimage{ailerp_recommended_snapped.png}
* \shadowimage{ailerp_snapped_movement.png}
*
* \subsection rec-smooth Recommended setup for smooth movement
* If you on the other hand want smoother movement I recommend setting 'Start Point Snapping' and 'End Point Snapping' to 'ClosestOnNode' and to add the Simple Smooth Modifier to the GameObject as well.
* Alternatively you can use the \link Pathfinding.FunnelModifier Funnel Modifier\endlink which works better on navmesh/recast graphs or the \link Pathfinding.RaycastModifier RaycastModifier\endlink.
*
* You should not combine the Simple Smooth Modifier or the Funnel Modifier with the NodeConnection snapping mode. This may lead to very odd behavior.
*
* \shadowimage{ailerp_recommended_smooth.png}
* \shadowimage{ailerp_smooth_movement.png}
* You may also want to tweak the #rotationSpeed.
*
* \ingroup movementscripts
*/
[RequireComponent(typeof(Seeker))]
[AddComponentMenu("Pathfinding/AI/AILerp (2D,3D)")]
[HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_a_i_lerp.php")]
public class AILerp : VersionedMonoBehaviour, IAstarAI {
/** Determines how often it will search for new paths.
* If you have fast moving targets or AIs, you might want to set it to a lower value.
* The value is in seconds between path requests.
*/
public float repathRate = 0.5F;
/** \copydoc Pathfinding::IAstarAI::canSearch */
public bool canSearch = true;
/** \copydoc Pathfinding::IAstarAI::canMove */
public bool canMove = true;
/** Speed in world units */
public float speed = 3;
/** If true, the AI will rotate to face the movement direction */
public bool enableRotation = true;
/** If true, rotation will only be done along the Z axis so that the Y axis is the forward direction of the character.
* This is useful for 2D games in which one often want to have the Y axis as the forward direction to get sprites and 2D colliders to work properly.
* \shadowimage{aibase_forward_axis.png}
*/
public bool rotationIn2D = false;
/** How quickly to rotate */
public float rotationSpeed = 10;
/** If true, some interpolation will be done when a new path has been calculated.
* This is used to avoid short distance teleportation.
*/
public bool interpolatePathSwitches = true;
/** How quickly to interpolate to the new path */
public float switchPathInterpolationSpeed = 5;
/** True if the end of the current path has been reached */
public bool reachedEndOfPath { get; private set; }
public Vector3 destination { get; set; }
/** Determines if the character's position should be coupled to the Transform's position.
* If false then all movement calculations will happen as usual, but the object that this component is attached to will not move
* instead only the #position property will change.
*
* \see #canMove which in contrast to this field will disable all movement calculations.
* \see #updateRotation
*/
[System.NonSerialized]
public bool updatePosition = true;
/** Determines if the character's rotation should be coupled to the Transform's rotation.
* If false then all movement calculations will happen as usual, but the object that this component is attached to will not rotate
* instead only the #rotation property will change.
*
* \see #updatePosition
*/
[System.NonSerialized]
public bool updateRotation = true;
/** Target to move towards.
* The AI will try to follow/move towards this target.
* It can be a point on the ground where the player has clicked in an RTS for example, or it can be the player object in a zombie game.
*
* \deprecated In 4.0 this will automatically add a \link Pathfinding.AIDestinationSetter AIDestinationSetter\endlink component and set the target on that component.
* Try instead to use the #destination property which does not require a transform to be created as the target or use
* the AIDestinationSetter component directly.
*/
[System.Obsolete("Use the destination property or the AIDestinationSetter component instead")]
public Transform target {
get {
var setter = GetComponent<AIDestinationSetter>();
return setter != null ? setter.target : null;
}
set {
targetCompatibility = null;
var setter = GetComponent<AIDestinationSetter>();
if (setter == null) setter = gameObject.AddComponent<AIDestinationSetter>();
setter.target = value;
destination = value != null ? value.position : new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity);
}
}
/** \copydoc Pathfinding::IAstarAI::position */
public Vector3 position { get { return updatePosition ? tr.position : simulatedPosition; } }
/** \copydoc Pathfinding::IAstarAI::rotation */
public Quaternion rotation { get { return updateRotation ? tr.rotation : simulatedRotation; } }
#region IAstarAI implementation
/** \copydoc Pathfinding::IAstarAI::Move */
void IAstarAI.Move (Vector3 deltaPosition) {
// This script does not know the concept of being away from the path that it is following
// so this call will be ignored (as is also mentioned in the documentation).
}
/** \copydoc Pathfinding::IAstarAI::maxSpeed */
float IAstarAI.maxSpeed { get { return speed; } set { speed = value; } }
/** \copydoc Pathfinding::IAstarAI::canSearch */
bool IAstarAI.canSearch { get { return canSearch; } set { canSearch = value; } }
/** \copydoc Pathfinding::IAstarAI::canMove */
bool IAstarAI.canMove { get { return canMove; } set { canMove = value; } }
Vector3 IAstarAI.velocity {
get {
return Time.deltaTime > 0.00001f ? (previousPosition1 - previousPosition2) / Time.deltaTime : Vector3.zero;
}
}
Vector3 IAstarAI.desiredVelocity {
get {
// The AILerp script sets the position every frame. It does not take into account physics
// or other things. So the velocity should always be the same as the desired velocity.
return (this as IAstarAI).velocity;
}
}
/** \copydoc Pathfinding::IAstarAI::steeringTarget */
Vector3 IAstarAI.steeringTarget {
get {
// AILerp doesn't use steering at all, so we will just return a point ahead of the agent in the direction it is moving.
return interpolator.valid ? interpolator.position + interpolator.tangent : simulatedPosition;
}
}
#endregion
public float remainingDistance {
get {
return Mathf.Max(interpolator.remainingDistance, 0);
}
set {
interpolator.remainingDistance = Mathf.Max(value, 0);
}
}
public bool hasPath {
get {
return interpolator.valid;
}
}
public bool pathPending {
get {
return !canSearchAgain;
}
}
/** \copydoc Pathfinding::IAstarAI::isStopped */
public bool isStopped { get; set; }
/** \copydoc Pathfinding::IAstarAI::onSearchPath */
public System.Action onSearchPath { get; set; }
/** Cached Seeker component */
protected Seeker seeker;
/** Cached Transform component */
protected Transform tr;
/** Time when the last path request was sent */
protected float lastRepath = -9999;
/** Current path which is followed */
protected ABPath path;
/** Only when the previous path has been returned should a search for a new path be done */
protected bool canSearchAgain = true;
/** When a new path was returned, the AI was moving along this ray.
* Used to smoothly interpolate between the previous movement and the movement along the new path.
* The speed is equal to movement direction.
*/
protected Vector3 previousMovementOrigin;
protected Vector3 previousMovementDirection;
/** Time since the path was replaced by a new path.
* \see #interpolatePathSwitches
*/
protected float pathSwitchInterpolationTime = 0;
protected PathInterpolator interpolator = new PathInterpolator();
/** Holds if the Start function has been run.
* Used to test if coroutines should be started in OnEnable to prevent calculating paths
* in the awake stage (or rather before start on frame 0).
*/
bool startHasRun = false;
Vector3 previousPosition1, previousPosition2, simulatedPosition;
Quaternion simulatedRotation;
/** Required for serialization backward compatibility */
[UnityEngine.Serialization.FormerlySerializedAs("target")][SerializeField][HideInInspector]
Transform targetCompatibility;
protected AILerp () {
// Note that this needs to be set here in the constructor and not in e.g Awake
// because it is possible that other code runs and sets the destination property
// before the Awake method on this script runs.
destination = new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity);
}
/** Initializes reference variables.
* If you override this function you should in most cases call base.Awake () at the start of it.
* */
protected override void Awake () {
base.Awake();
//This is a simple optimization, cache the transform component lookup
tr = transform;
seeker = GetComponent<Seeker>();
// Tell the StartEndModifier to ask for our exact position when post processing the path This
// is important if we are using prediction and requesting a path from some point slightly ahead
// of us since then the start point in the path request may be far from our position when the
// path has been calculated. This is also good because if a long path is requested, it may take
// a few frames for it to be calculated so we could have moved some distance during that time
seeker.startEndModifier.adjustStartPoint = () => simulatedPosition;
}
/** Starts searching for paths.
* If you override this function you should in most cases call base.Start () at the start of it.
* \see #Init
* \see #RepeatTrySearchPath
*/
protected virtual void Start () {
startHasRun = true;
Init();
}
/** Called when the component is enabled */
protected virtual void OnEnable () {
// Make sure we receive callbacks when paths complete
seeker.pathCallback += OnPathComplete;
Init();
}
void Init () {
if (startHasRun) {
// The Teleport call will make sure some variables are properly initialized (like #prevPosition1 and #prevPosition2)
Teleport(position, false);
lastRepath = float.NegativeInfinity;
if (shouldRecalculatePath) SearchPath();
}
}
public void OnDisable () {
// Abort any calculations in progress
if (seeker != null) seeker.CancelCurrentPathRequest();
canSearchAgain = true;
// Release current path so that it can be pooled
if (path != null) path.Release(this);
path = null;
interpolator.SetPath(null);
// Make sure we no longer receive callbacks when paths complete
seeker.pathCallback -= OnPathComplete;
}
public void Teleport (Vector3 position, bool clearPath = true) {
if (clearPath) interpolator.SetPath(null);
simulatedPosition = previousPosition1 = previousPosition2 = position;
if (updatePosition) tr.position = position;
reachedEndOfPath = false;
if (clearPath) SearchPath();
}
/** True if the path should be automatically recalculated as soon as possible */
protected virtual bool shouldRecalculatePath {
get {
return Time.time - lastRepath >= repathRate && canSearchAgain && canSearch && !float.IsPositiveInfinity(destination.x);
}
}
/** Requests a path to the target.
* \deprecated Use #SearchPath instead.
*/
[System.Obsolete("Use SearchPath instead")]
public virtual void ForceSearchPath () {
SearchPath();
}
/** Requests a path to the target.
*/
public virtual void SearchPath () {
if (float.IsPositiveInfinity(destination.x)) return;
if (onSearchPath != null) onSearchPath();
lastRepath = Time.time;
// This is where the path should start to search from
var currentPosition = GetFeetPosition();
// If we are following a path, start searching from the node we will
// reach next this can prevent odd turns right at the start of the path
/*if (interpolator.valid) {
var prevDist = interpolator.distance;
// Move to the end of the current segment
interpolator.MoveToSegment(interpolator.segmentIndex, 1);
currentPosition = interpolator.position;
// Move back to the original position
interpolator.distance = prevDist;
}*/
canSearchAgain = false;
// Alternative way of creating a path request
//ABPath p = ABPath.Construct(currentPosition, targetPoint, null);
//seeker.StartPath(p);
// Create a new path request
// The OnPathComplete method will later be called with the result
seeker.StartPath(currentPosition, destination);
}
/** The end of the path has been reached.
* If you want custom logic for when the AI has reached it's destination
* add it here.
* You can also create a new script which inherits from this one
* and override the function in that script.
*/
public virtual void OnTargetReached () {
}
/** Called when a requested path has finished calculation.
* A path is first requested by #SearchPath, it is then calculated, probably in the same or the next frame.
* Finally it is returned to the seeker which forwards it to this function.
*/
protected virtual void OnPathComplete (Path _p) {
ABPath p = _p as ABPath;
if (p == null) throw new System.Exception("This function only handles ABPaths, do not use special path types");
canSearchAgain = true;
// Increase the reference count on the path.
// This is used for path pooling
p.Claim(this);
// Path couldn't be calculated of some reason.
// More info in p.errorLog (debug string)
if (p.error) {
p.Release(this);
return;
}
if (interpolatePathSwitches) {
ConfigurePathSwitchInterpolation();
}
// Replace the old path
var oldPath = path;
path = p;
reachedEndOfPath = false;
// Just for the rest of the code to work, if there
// is only one waypoint in the path add another one
if (path.vectorPath != null && path.vectorPath.Count == 1) {
path.vectorPath.Insert(0, GetFeetPosition());
}
// Reset some variables
ConfigureNewPath();
// Release the previous path
// This is used for path pooling.
// This is done after the interpolator has been configured in the ConfigureNewPath method
// as this method would otherwise invalidate the interpolator
// since the vectorPath list (which the interpolator uses) will be pooled.
if (oldPath != null) oldPath.Release(this);
if (interpolator.remainingDistance < 0.0001f && !reachedEndOfPath) {
reachedEndOfPath = true;
OnTargetReached();
}
}
/** \copydoc Pathfinding::IAstarAI::SetPath */
public void SetPath (Path path) {
if (path.PipelineState == PathState.Created) {
// Path has not started calculation yet
lastRepath = Time.time;
canSearchAgain = false;
seeker.CancelCurrentPathRequest();
seeker.StartPath(path);
} else if (path.PipelineState == PathState.Returned) {
// Path has already been calculated
// We might be calculating another path at the same time, and we don't want that path to override this one. So cancel it.
if (seeker.GetCurrentPath() != path) seeker.CancelCurrentPathRequest();
else throw new System.ArgumentException("If you calculate the path using seeker.StartPath then this script will pick up the calculated path anyway as it listens for all paths the Seeker finishes calculating. You should not call SetPath in that case.");
OnPathComplete(path);
} else {
// Path calculation has been started, but it is not yet complete. Cannot really handle this.
throw new System.ArgumentException("You must call the SetPath method with a path that either has been completely calculated or one whose path calculation has not been started at all. It looks like the path calculation for the path you tried to use has been started, but is not yet finished.");
}
}
protected virtual void ConfigurePathSwitchInterpolation () {
bool reachedEndOfPreviousPath = interpolator.valid && interpolator.remainingDistance < 0.0001f;
if (interpolator.valid && !reachedEndOfPreviousPath) {
previousMovementOrigin = interpolator.position;
previousMovementDirection = interpolator.tangent.normalized * interpolator.remainingDistance;
pathSwitchInterpolationTime = 0;
} else {
previousMovementOrigin = Vector3.zero;
previousMovementDirection = Vector3.zero;
pathSwitchInterpolationTime = float.PositiveInfinity;
}
}
public virtual Vector3 GetFeetPosition () {
return position;
}
/** Finds the closest point on the current path and configures the #interpolator */
protected virtual void ConfigureNewPath () {
var hadValidPath = interpolator.valid;
var prevTangent = hadValidPath ? interpolator.tangent : Vector3.zero;
interpolator.SetPath(path.vectorPath);
interpolator.MoveToClosestPoint(GetFeetPosition());
if (interpolatePathSwitches && switchPathInterpolationSpeed > 0.01f && hadValidPath) {
var correctionFactor = Mathf.Max(-Vector3.Dot(prevTangent.normalized, interpolator.tangent.normalized), 0);
interpolator.distance -= speed*correctionFactor*(1f/switchPathInterpolationSpeed);
}
}
protected virtual void Update () {
if (shouldRecalculatePath) SearchPath();
if (canMove) {
Vector3 nextPosition;
Quaternion nextRotation;
MovementUpdate(Time.deltaTime, out nextPosition, out nextRotation);
FinalizeMovement(nextPosition, nextRotation);
}
}
/** \copydoc Pathfinding::IAstarAI::MovementUpdate */
public void MovementUpdate (float deltaTime, out Vector3 nextPosition, out Quaternion nextRotation) {
if (updatePosition) simulatedPosition = tr.position;
if (updateRotation) simulatedRotation = tr.rotation;
Vector3 direction;
nextPosition = CalculateNextPosition(out direction, isStopped ? 0f : deltaTime);
if (enableRotation) nextRotation = SimulateRotationTowards(direction, deltaTime);
else nextRotation = simulatedRotation;
}
/** \copydoc Pathfinding::IAstarAI::FinalizeMovement */
public void FinalizeMovement (Vector3 nextPosition, Quaternion nextRotation) {
previousPosition2 = previousPosition1;
previousPosition1 = simulatedPosition = nextPosition;
simulatedRotation = nextRotation;
if (updatePosition) tr.position = nextPosition;
if (updateRotation) tr.rotation = nextRotation;
}
Quaternion SimulateRotationTowards (Vector3 direction, float deltaTime) {
// Rotate unless we are really close to the target
if (direction != Vector3.zero) {
Quaternion targetRotation = Quaternion.LookRotation(direction, rotationIn2D ? Vector3.back : Vector3.up);
// This causes the character to only rotate around the Z axis
if (rotationIn2D) targetRotation *= Quaternion.Euler(90, 0, 0);
return Quaternion.Slerp(simulatedRotation, targetRotation, deltaTime * rotationSpeed);
}
return simulatedRotation;
}
/** Calculate the AI's next position (one frame in the future).
* \param direction The tangent of the segment the AI is currently traversing. Not normalized.
*/
protected virtual Vector3 CalculateNextPosition (out Vector3 direction, float deltaTime) {
if (!interpolator.valid) {
direction = Vector3.zero;
return simulatedPosition;
}
interpolator.distance += deltaTime * speed;
if (interpolator.remainingDistance < 0.0001f && !reachedEndOfPath) {
reachedEndOfPath = true;
OnTargetReached();
}
direction = interpolator.tangent;
pathSwitchInterpolationTime += deltaTime;
var alpha = switchPathInterpolationSpeed * pathSwitchInterpolationTime;
if (interpolatePathSwitches && alpha < 1f) {
// Find the approximate position we would be at if we
// would have continued to follow the previous path
Vector3 positionAlongPreviousPath = previousMovementOrigin + Vector3.ClampMagnitude(previousMovementDirection, speed * pathSwitchInterpolationTime);
// Interpolate between the position on the current path and the position
// we would have had if we would have continued along the previous path.
return Vector3.Lerp(positionAlongPreviousPath, interpolator.position, alpha);
} else {
return interpolator.position;
}
}
protected override int OnUpgradeSerializedData (int version, bool unityThread) {
#pragma warning disable 618
if (unityThread && targetCompatibility != null) target = targetCompatibility;
#pragma warning restore 618
return 2;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.ServiceFabric.Data;
using Newtonsoft.Json;
namespace ServiceFabric.BackupRestore
{
/// <summary>
/// Implementation of <see cref="ICentralBackupStore"/> that stores files on disk.
/// Make sure to use a file share outside the cluster! (E.g. a network share on a file server.)
/// </summary>
public class FileStore : ICentralBackupStore
{
private readonly string _remoteFolderName;
/// <summary>
/// The name of a file that contains ServiceFabric.BackupRestore related metadata about a backup.
/// </summary>
public const string ServiceFabricBackupRestoreMetadataFileName = "backuprestore.metadata";
/// <summary>
/// The name of a file that contains ServiceFabric related metadata about a backup.
/// </summary>
public const string BackupMetadataFileName = "backup.metadata";
/// <summary>
/// The name of a file that contains ServiceFabric related metadata about a actor backup
/// </summary>
public const string ActorBackupMetadataFileName = "restore.dat";
/// <summary>
/// The name of a file that contains ServiceFabric related metadata about an incremental backup.
/// </summary>
public const string IncrementalBackupMetadataFileName = "incremental.metadata";
/// <summary>
/// Creates a new instance.
/// </summary>
/// <param name="remoteFolderName">A shared folder that is not on any of the cluster nodes.
/// (Except maybe for local debugging)</param>
public FileStore(string remoteFolderName)
{
if (string.IsNullOrWhiteSpace(remoteFolderName))
throw new ArgumentException("Value cannot be null or whitespace.", nameof(remoteFolderName));
Directory.CreateDirectory(remoteFolderName);
_remoteFolderName = remoteFolderName;
}
/// <inheritdoc />
public async Task<BackupMetadata> UploadBackupFolderAsync(BackupOption backupOption, Guid servicePartitionId, string sourceDirectory,
CancellationToken cancellationToken)
{
//use folder names containing the service partition and the utc date:
var timeStamp = DateTime.UtcNow;
string destinationFolder = CreateDateTimeFolderName(servicePartitionId, timeStamp);
//upload
await CopyFolderAsync(sourceDirectory, destinationFolder, cancellationToken);
//create metadata to return
var info = new BackupMetadata(servicePartitionId, timeStamp, backupOption);
//store the backup id.
await StoreBackupMetadataAsync(destinationFolder, info);
return info;
}
/// <inheritdoc />
public async Task DownloadBackupFolderAsync(Guid backupId, string destinationDirectory,
CancellationToken cancellationToken)
{
//find the metadada
var infos = await GetBackupMetadataPrivateAsync(backupId);
var info = infos.Single();
//copy the backup to the node
await CopyFolderAsync(Path.Combine(_remoteFolderName, info.RelativeFolder.TrimStart('\\', '/')), destinationDirectory, cancellationToken);
}
/// <inheritdoc />
public async Task<IEnumerable<BackupMetadata>> GetBackupMetadataAsync(Guid? backupId = null, Guid? servicePartitionId = null)
{
//get all metadata
var metadata = await GetBackupMetadataPrivateAsync(backupId, servicePartitionId);
return metadata.Select(m => new BackupMetadata(m.OriginalServicePartitionId, m.TimeStampUtc, m.BackupOption, m.BackupId));
}
/// <inheritdoc />
[Obsolete("Naming issue. Call 'ScheduleBackupRestoreAsync'.")]
public Task ScheduleBackupAsync(Guid servicePartitionId, Guid backupId)
{
return ScheduleBackupRestoreAsync(servicePartitionId, backupId);
}
/// <inheritdoc />
public Task ScheduleBackupRestoreAsync(Guid servicePartitionId, Guid backupId)
{
//remember which backup to restore for which partition
string queueFile = GetQueueFile(servicePartitionId);
File.WriteAllText(queueFile, backupId.ToString("N"));
return Task.FromResult(true);
}
/// <inheritdoc />
public async Task<BackupMetadata> RetrieveScheduledBackupAsync(Guid servicePartitionId)
{
BackupMetadata backup = null;
//retrieve the backup to restore for the provided partition
string queueFile = GetQueueFile(servicePartitionId);
if (!File.Exists(queueFile)) return null;
string content = File.ReadAllText(queueFile);
Guid id;
if (Guid.TryParse(content, out id))
{
backup = (await GetBackupMetadataAsync(id)).Single();
}
File.Delete(queueFile);
return backup;
}
/// <inheritdoc />
public Task StoreBackupMetadataAsync(string destinationFolder, BackupMetadata info, CancellationToken cancellationToken = default(CancellationToken))
{
return Task.Run(() =>
{
string file = Path.Combine(destinationFolder, ServiceFabricBackupRestoreMetadataFileName);
string json = JsonConvert.SerializeObject(info);
File.WriteAllText(file, json);
});
}
/// <summary>
/// Queries all metadata, optionally filtered by <paramref name="backupId"/>.
/// </summary>
/// <param name="backupId"></param>
/// <param name="servicePartitionId"></param>
/// <returns></returns>
internal Task<IEnumerable<FileBackupMetadata>> GetBackupMetadataPrivateAsync(Guid? backupId = null, Guid? servicePartitionId = null)
{
return Task.Run(() =>
{
var query = from d in Directory.GetDirectories(_remoteFolderName, "*", SearchOption.AllDirectories)
let dirInfo = new DirectoryInfo(d)
let dirParentInfo = dirInfo.Parent
let metadata = BackupMetadataFromDirectory(d)
where (File.Exists(Path.Combine(d, BackupMetadataFileName)) //find folders with a SF metadata file
|| File.Exists(Path.Combine(d, ActorBackupMetadataFileName))
|| File.Exists(Path.Combine(d, IncrementalBackupMetadataFileName)))
&& (backupId == null || metadata?.BackupId == backupId.Value) //and optionally with the provided backup id
&& (servicePartitionId == null || metadata?.OriginalServicePartitionId == servicePartitionId.Value) //and optionally with the servicePartitionId
orderby dirInfo.Parent?.Name, dirInfo.Name
select
new FileBackupMetadata(//build a metadata description
d.Replace(_remoteFolderName, string.Empty), metadata.OriginalServicePartitionId, metadata.TimeStampUtc, metadata.BackupOption, metadata.BackupId);
return query;
});
}
/// <summary>
/// Finds the single backup metadata file in the folder, deserializes the content to an instance of <see cref="BackupMetadata"/>.
/// </summary>
/// <param name="directory"></param>
/// <returns></returns>
internal static BackupMetadata BackupMetadataFromDirectory(string directory)
{
string file = Path.Combine(directory, ServiceFabricBackupRestoreMetadataFileName);
if (!File.Exists(file)) return null;
string json = File.ReadAllText(file);
var metadata =JsonConvert.DeserializeObject<BackupMetadata>(json);
return metadata;
}
/// <summary>
/// Creates a folder name based on <paramref name="servicePartitionId"/> and timestamp.
/// </summary>
/// <param name="servicePartitionId"></param>
/// <param name="timeStamp"></param>
/// <returns></returns>
internal string CreateDateTimeFolderName(Guid servicePartitionId, DateTime timeStamp)
{
return Path.Combine(_remoteFolderName, servicePartitionId.ToString("N"), timeStamp.ToString("yyyyMMddhhmmss"));
}
/// <summary>
/// Performs a deep copy from <paramref name="sourceFolder"/> to <paramref name="destinationFolder"/>.
/// </summary>
/// <param name="sourceFolder"></param>
/// <param name="destinationFolder"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private static Task<string> CopyFolderAsync(string sourceFolder, string destinationFolder,
CancellationToken cancellationToken)
{
Directory.CreateDirectory(destinationFolder);
return Task.Run(() =>
{
//copy all subfolders
foreach (string directory in Directory.EnumerateDirectories(sourceFolder))
{
CopyFolderAsync(directory, Path.Combine(destinationFolder, new DirectoryInfo(directory).Name), cancellationToken)
.ConfigureAwait(false)
.GetAwaiter()
.GetResult();
}
//copy all files
foreach (string sourceFileName in Directory.EnumerateFiles(sourceFolder))
{
if (sourceFileName == null) continue;
string destFileName = Path.Combine(destinationFolder, Path.GetFileName(sourceFileName));
File.Copy(sourceFileName, destFileName, true);
}
return destinationFolder;
}, cancellationToken);
}
/// <summary>
/// Creates a marker file that indicates which backup to restore for which partition.
/// </summary>
/// <param name="servicePartitionId"></param>
/// <returns></returns>
private string GetQueueFile(Guid servicePartitionId)
{
string queueFolder = GetQueueFolder();
return Path.Combine(queueFolder, servicePartitionId.ToString("N"));
}
/// <summary>
/// Creates and returns a folder that contains files that indicate which backup to restore for which partition.
/// </summary>
/// <returns></returns>
private string GetQueueFolder()
{
string queueFolder = Path.Combine(_remoteFolderName, "Queue");
Directory.CreateDirectory(queueFolder);
return queueFolder;
}
}
}
| |
namespace Epi.Windows.MakeView.Dialogs
{
partial class StandardReferenceTableSelectionDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(StandardReferenceTableSelectionDialog));
this.btnOk = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.lbxFields = new System.Windows.Forms.ListBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.lblDataSource = new System.Windows.Forms.Label();
this.rdbOther = new System.Windows.Forms.RadioButton();
this.rdbWho = new System.Windows.Forms.RadioButton();
this.rdbPhin = new System.Windows.Forms.RadioButton();
this.txtFileName = new System.Windows.Forms.TextBox();
this.btnBrowse = new System.Windows.Forms.Button();
this.groupBox2.SuspendLayout();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// baseImageList
//
this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream")));
this.baseImageList.Images.SetKeyName(0, "");
this.baseImageList.Images.SetKeyName(1, "");
this.baseImageList.Images.SetKeyName(2, "");
this.baseImageList.Images.SetKeyName(3, "");
this.baseImageList.Images.SetKeyName(4, "");
this.baseImageList.Images.SetKeyName(5, "");
this.baseImageList.Images.SetKeyName(6, "");
this.baseImageList.Images.SetKeyName(7, "");
this.baseImageList.Images.SetKeyName(8, "");
this.baseImageList.Images.SetKeyName(9, "");
this.baseImageList.Images.SetKeyName(10, "");
this.baseImageList.Images.SetKeyName(11, "");
this.baseImageList.Images.SetKeyName(12, "");
this.baseImageList.Images.SetKeyName(13, "");
this.baseImageList.Images.SetKeyName(14, "");
this.baseImageList.Images.SetKeyName(15, "");
this.baseImageList.Images.SetKeyName(16, "");
this.baseImageList.Images.SetKeyName(17, "");
this.baseImageList.Images.SetKeyName(18, "");
this.baseImageList.Images.SetKeyName(19, "");
this.baseImageList.Images.SetKeyName(20, "");
this.baseImageList.Images.SetKeyName(21, "");
this.baseImageList.Images.SetKeyName(22, "");
this.baseImageList.Images.SetKeyName(23, "");
this.baseImageList.Images.SetKeyName(24, "");
this.baseImageList.Images.SetKeyName(25, "");
this.baseImageList.Images.SetKeyName(26, "");
this.baseImageList.Images.SetKeyName(27, "");
this.baseImageList.Images.SetKeyName(28, "");
this.baseImageList.Images.SetKeyName(29, "");
this.baseImageList.Images.SetKeyName(30, "");
this.baseImageList.Images.SetKeyName(31, "");
this.baseImageList.Images.SetKeyName(32, "");
this.baseImageList.Images.SetKeyName(33, "");
this.baseImageList.Images.SetKeyName(34, "");
this.baseImageList.Images.SetKeyName(35, "");
this.baseImageList.Images.SetKeyName(36, "");
this.baseImageList.Images.SetKeyName(37, "");
this.baseImageList.Images.SetKeyName(38, "");
this.baseImageList.Images.SetKeyName(39, "");
this.baseImageList.Images.SetKeyName(40, "");
this.baseImageList.Images.SetKeyName(41, "");
this.baseImageList.Images.SetKeyName(42, "");
this.baseImageList.Images.SetKeyName(43, "");
this.baseImageList.Images.SetKeyName(44, "");
this.baseImageList.Images.SetKeyName(45, "");
this.baseImageList.Images.SetKeyName(46, "");
this.baseImageList.Images.SetKeyName(47, "");
this.baseImageList.Images.SetKeyName(48, "");
this.baseImageList.Images.SetKeyName(49, "");
this.baseImageList.Images.SetKeyName(50, "");
this.baseImageList.Images.SetKeyName(51, "");
this.baseImageList.Images.SetKeyName(52, "");
this.baseImageList.Images.SetKeyName(53, "");
this.baseImageList.Images.SetKeyName(54, "");
this.baseImageList.Images.SetKeyName(55, "");
this.baseImageList.Images.SetKeyName(56, "");
this.baseImageList.Images.SetKeyName(57, "");
this.baseImageList.Images.SetKeyName(58, "");
this.baseImageList.Images.SetKeyName(59, "");
this.baseImageList.Images.SetKeyName(60, "");
this.baseImageList.Images.SetKeyName(61, "");
this.baseImageList.Images.SetKeyName(62, "");
this.baseImageList.Images.SetKeyName(63, "");
this.baseImageList.Images.SetKeyName(64, "");
this.baseImageList.Images.SetKeyName(65, "");
this.baseImageList.Images.SetKeyName(66, "");
this.baseImageList.Images.SetKeyName(67, "");
this.baseImageList.Images.SetKeyName(68, "");
this.baseImageList.Images.SetKeyName(69, "");
this.baseImageList.Images.SetKeyName(70, "");
this.baseImageList.Images.SetKeyName(71, "");
this.baseImageList.Images.SetKeyName(72, "");
this.baseImageList.Images.SetKeyName(73, "");
this.baseImageList.Images.SetKeyName(74, "");
this.baseImageList.Images.SetKeyName(75, "");
this.baseImageList.Images.SetKeyName(76, "");
this.baseImageList.Images.SetKeyName(77, "");
this.baseImageList.Images.SetKeyName(78, "");
this.baseImageList.Images.SetKeyName(79, "");
this.baseImageList.Images.SetKeyName(80, "");
this.baseImageList.Images.SetKeyName(81, "");
this.baseImageList.Images.SetKeyName(82, "");
this.baseImageList.Images.SetKeyName(83, "");
this.baseImageList.Images.SetKeyName(84, "");
this.baseImageList.Images.SetKeyName(85, "");
this.baseImageList.Images.SetKeyName(86, "");
//
// btnOk
//
resources.ApplyResources(this.btnOk, "btnOk");
this.btnOk.Name = "btnOk";
this.btnOk.Click += new System.EventHandler(this.btnOk_Click);
//
// btnCancel
//
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
resources.ApplyResources(this.btnCancel, "btnCancel");
this.btnCancel.Name = "btnCancel";
//
// groupBox2
//
this.groupBox2.Controls.Add(this.lbxFields);
this.groupBox2.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.groupBox2, "groupBox2");
this.groupBox2.Name = "groupBox2";
this.groupBox2.TabStop = false;
//
// lbxFields
//
this.lbxFields.Items.AddRange(new object[] {
resources.GetString("lbxFields.Items"),
resources.GetString("lbxFields.Items1"),
resources.GetString("lbxFields.Items2"),
resources.GetString("lbxFields.Items3"),
resources.GetString("lbxFields.Items4"),
resources.GetString("lbxFields.Items5"),
resources.GetString("lbxFields.Items6"),
resources.GetString("lbxFields.Items7"),
resources.GetString("lbxFields.Items8"),
resources.GetString("lbxFields.Items9"),
resources.GetString("lbxFields.Items10"),
resources.GetString("lbxFields.Items11"),
resources.GetString("lbxFields.Items12"),
resources.GetString("lbxFields.Items13"),
resources.GetString("lbxFields.Items14"),
resources.GetString("lbxFields.Items15"),
resources.GetString("lbxFields.Items16"),
resources.GetString("lbxFields.Items17"),
resources.GetString("lbxFields.Items18"),
resources.GetString("lbxFields.Items19"),
resources.GetString("lbxFields.Items20"),
resources.GetString("lbxFields.Items21"),
resources.GetString("lbxFields.Items22"),
resources.GetString("lbxFields.Items23"),
resources.GetString("lbxFields.Items24"),
resources.GetString("lbxFields.Items25"),
resources.GetString("lbxFields.Items26"),
resources.GetString("lbxFields.Items27"),
resources.GetString("lbxFields.Items28"),
resources.GetString("lbxFields.Items29"),
resources.GetString("lbxFields.Items30"),
resources.GetString("lbxFields.Items31"),
resources.GetString("lbxFields.Items32"),
resources.GetString("lbxFields.Items33"),
resources.GetString("lbxFields.Items34"),
resources.GetString("lbxFields.Items35"),
resources.GetString("lbxFields.Items36"),
resources.GetString("lbxFields.Items37"),
resources.GetString("lbxFields.Items38"),
resources.GetString("lbxFields.Items39"),
resources.GetString("lbxFields.Items40"),
resources.GetString("lbxFields.Items41"),
resources.GetString("lbxFields.Items42"),
resources.GetString("lbxFields.Items43"),
resources.GetString("lbxFields.Items44"),
resources.GetString("lbxFields.Items45"),
resources.GetString("lbxFields.Items46"),
resources.GetString("lbxFields.Items47"),
resources.GetString("lbxFields.Items48"),
resources.GetString("lbxFields.Items49"),
resources.GetString("lbxFields.Items50"),
resources.GetString("lbxFields.Items51"),
resources.GetString("lbxFields.Items52"),
resources.GetString("lbxFields.Items53"),
resources.GetString("lbxFields.Items54"),
resources.GetString("lbxFields.Items55"),
resources.GetString("lbxFields.Items56"),
resources.GetString("lbxFields.Items57"),
resources.GetString("lbxFields.Items58"),
resources.GetString("lbxFields.Items59"),
resources.GetString("lbxFields.Items60"),
resources.GetString("lbxFields.Items61"),
resources.GetString("lbxFields.Items62"),
resources.GetString("lbxFields.Items63"),
resources.GetString("lbxFields.Items64"),
resources.GetString("lbxFields.Items65"),
resources.GetString("lbxFields.Items66"),
resources.GetString("lbxFields.Items67"),
resources.GetString("lbxFields.Items68"),
resources.GetString("lbxFields.Items69"),
resources.GetString("lbxFields.Items70"),
resources.GetString("lbxFields.Items71"),
resources.GetString("lbxFields.Items72"),
resources.GetString("lbxFields.Items73"),
resources.GetString("lbxFields.Items74"),
resources.GetString("lbxFields.Items75"),
resources.GetString("lbxFields.Items76"),
resources.GetString("lbxFields.Items77"),
resources.GetString("lbxFields.Items78"),
resources.GetString("lbxFields.Items79"),
resources.GetString("lbxFields.Items80"),
resources.GetString("lbxFields.Items81"),
resources.GetString("lbxFields.Items82"),
resources.GetString("lbxFields.Items83"),
resources.GetString("lbxFields.Items84"),
resources.GetString("lbxFields.Items85"),
resources.GetString("lbxFields.Items86"),
resources.GetString("lbxFields.Items87"),
resources.GetString("lbxFields.Items88"),
resources.GetString("lbxFields.Items89"),
resources.GetString("lbxFields.Items90"),
resources.GetString("lbxFields.Items91"),
resources.GetString("lbxFields.Items92"),
resources.GetString("lbxFields.Items93"),
resources.GetString("lbxFields.Items94"),
resources.GetString("lbxFields.Items95"),
resources.GetString("lbxFields.Items96"),
resources.GetString("lbxFields.Items97"),
resources.GetString("lbxFields.Items98"),
resources.GetString("lbxFields.Items99"),
resources.GetString("lbxFields.Items100"),
resources.GetString("lbxFields.Items101"),
resources.GetString("lbxFields.Items102"),
resources.GetString("lbxFields.Items103"),
resources.GetString("lbxFields.Items104"),
resources.GetString("lbxFields.Items105"),
resources.GetString("lbxFields.Items106"),
resources.GetString("lbxFields.Items107"),
resources.GetString("lbxFields.Items108"),
resources.GetString("lbxFields.Items109"),
resources.GetString("lbxFields.Items110"),
resources.GetString("lbxFields.Items111"),
resources.GetString("lbxFields.Items112"),
resources.GetString("lbxFields.Items113"),
resources.GetString("lbxFields.Items114"),
resources.GetString("lbxFields.Items115"),
resources.GetString("lbxFields.Items116"),
resources.GetString("lbxFields.Items117"),
resources.GetString("lbxFields.Items118"),
resources.GetString("lbxFields.Items119"),
resources.GetString("lbxFields.Items120"),
resources.GetString("lbxFields.Items121"),
resources.GetString("lbxFields.Items122"),
resources.GetString("lbxFields.Items123"),
resources.GetString("lbxFields.Items124"),
resources.GetString("lbxFields.Items125"),
resources.GetString("lbxFields.Items126"),
resources.GetString("lbxFields.Items127"),
resources.GetString("lbxFields.Items128"),
resources.GetString("lbxFields.Items129"),
resources.GetString("lbxFields.Items130"),
resources.GetString("lbxFields.Items131"),
resources.GetString("lbxFields.Items132"),
resources.GetString("lbxFields.Items133"),
resources.GetString("lbxFields.Items134"),
resources.GetString("lbxFields.Items135")});
resources.ApplyResources(this.lbxFields, "lbxFields");
this.lbxFields.Name = "lbxFields";
this.lbxFields.SelectedIndexChanged += new System.EventHandler(this.listBox1_SelectedIndexChanged);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.lblDataSource);
this.groupBox1.Controls.Add(this.rdbOther);
this.groupBox1.Controls.Add(this.rdbWho);
this.groupBox1.Controls.Add(this.rdbPhin);
this.groupBox1.Controls.Add(this.txtFileName);
this.groupBox1.Controls.Add(this.btnBrowse);
this.groupBox1.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.groupBox1, "groupBox1");
this.groupBox1.Name = "groupBox1";
this.groupBox1.TabStop = false;
//
// lblDataSource
//
resources.ApplyResources(this.lblDataSource, "lblDataSource");
this.lblDataSource.Name = "lblDataSource";
//
// rdbOther
//
resources.ApplyResources(this.rdbOther, "rdbOther");
this.rdbOther.Name = "rdbOther";
this.rdbOther.CheckedChanged += new System.EventHandler(this.rdbOther_CheckedChanged);
//
// rdbWho
//
resources.ApplyResources(this.rdbWho, "rdbWho");
this.rdbWho.Name = "rdbWho";
//
// rdbPhin
//
this.rdbPhin.Checked = true;
resources.ApplyResources(this.rdbPhin, "rdbPhin");
this.rdbPhin.Name = "rdbPhin";
this.rdbPhin.TabStop = true;
//
// txtFileName
//
resources.ApplyResources(this.txtFileName, "txtFileName");
this.txtFileName.Name = "txtFileName";
//
// btnBrowse
//
resources.ApplyResources(this.btnBrowse, "btnBrowse");
this.btnBrowse.Name = "btnBrowse";
//
// StandardReferenceTableSelectionDialog
//
this.AcceptButton = this.btnOk;
resources.ApplyResources(this, "$this");
this.CancelButton = this.btnCancel;
this.Controls.Add(this.btnOk);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "StandardReferenceTableSelectionDialog";
this.ShowInTaskbar = false;
this.groupBox2.ResumeLayout(false);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button btnOk;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Label lblDataSource;
private System.Windows.Forms.RadioButton rdbOther;
private System.Windows.Forms.RadioButton rdbWho;
private System.Windows.Forms.RadioButton rdbPhin;
private System.Windows.Forms.TextBox txtFileName;
private System.Windows.Forms.Button btnBrowse;
private System.Windows.Forms.ListBox lbxFields;
}
}
| |
#define PROTOTYPE
/**
* Repairs missing pb_Object and pb_Entity references. It is based
* on this article by Unity Gems: http://unitygems.com/lateral1/
*/
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Linq;
namespace ProBuilder2.EditorCommon
{
/**
* Extends MonoBehaviour Inspector, automatically fixing missing script
* references (typically caused by ProBuilder upgrade process).
*/
[CustomEditor(typeof(MonoBehaviour))]
public class pb_MissingScriptEditor : Editor
{
#region Members
static bool applyDummyScript = true; ///< If true, any null components that can't be set will have this script applied to their reference, allowing us to later remove them.
static float index = 0; ///< general idea of where we are in terms of processing this scene.
static float total; ///< general idea of how many missing script references are in this scene.
static bool doFix = false; ///< while true, the inspector will attempt to cycle to broken gameobjects until none are found.
static List<GameObject> unfixable = new List<GameObject>(); ///< if a non-pb missing reference is encountered, need to let the iterator know not to bother,
static MonoScript _mono_pb; ///< MonoScript assets
static MonoScript _mono_pe; ///< MonoScript assets
static MonoScript _mono_dummy; ///< MonoScript assets
/**
* Load the pb_Object and pb_Entity classes to MonoScript assets. Saves us from having to fall back on Reflection.
*/
static void LoadMonoScript()
{
GameObject go = new GameObject();
pb_Object pb = go.AddComponent<pb_Object>();
pb_Entity pe = go.AddComponent<pb_Entity>();
pb_DummyScript du = go.AddComponent<pb_DummyScript>();
_mono_pb = MonoScript.FromMonoBehaviour( pb );
_mono_pe = MonoScript.FromMonoBehaviour( pe );
_mono_dummy = MonoScript.FromMonoBehaviour( du );
DestroyImmediate(go);
}
public MonoScript pb_monoscript
{
get
{
if(_mono_pb == null) LoadMonoScript();
return _mono_pb;
}
}
public MonoScript pe_monoscript
{
get
{
if(_mono_pe == null) LoadMonoScript();
return _mono_pe;
}
}
public MonoScript dummy_monoscript
{
get
{
if(_mono_dummy == null) LoadMonoScript();
return _mono_dummy;
}
}
#endregion
[MenuItem("Tools/" + pb_Constant.PRODUCT_NAME + "/Repair/Repair Missing Script References")]
public static void MenuRepairMissingScriptReferences()
{
FixAllScriptReferencesInScene();
}
static void FixAllScriptReferencesInScene()
{
EditorApplication.ExecuteMenuItem("Window/Inspector");
Object[] all = Resources.FindObjectsOfTypeAll(typeof(GameObject)).Where(x => ((GameObject)x).GetComponents<Component>().Any(n => n == null) ).ToArray();
total = all.Length;
unfixable.Clear();
if(total > 1)
{
Undo.RecordObjects(all, "Fix missing script references");
index = 0;
doFix = true;
Next();
}
else
{
if( applyDummyScript )
DeleteDummyScripts();
EditorUtility.DisplayDialog("Success", "No missing ProBuilder script references found.", "Okay");
}
}
/**
* Advance to the next gameobject with missing components. If none are found, display dialog and exit.
*/
static void Next()
{
bool earlyExit = false;
if( EditorUtility.DisplayCancelableProgressBar("Repair ProBuilder Script References", "Fixing " + (int)Mathf.Floor(index+1) + " out of " + total + " objects in scene.", ((float)index/total) ) )
{
earlyExit = true;
doFix = false;
}
if(!earlyExit)
{
// Cycle through FindObjectsOfType on every Next() because using a static list didn't work for some reason.
foreach(GameObject go in Resources.FindObjectsOfTypeAll(typeof(GameObject)))
{
if(go.GetComponents<Component>().Any(x => x == null) && !unfixable.Contains(go))
{
if( (PrefabUtility.GetPrefabType(go) == PrefabType.PrefabInstance ||
PrefabUtility.GetPrefabType(go) == PrefabType.Prefab ) )
{
GameObject pref = (GameObject)PrefabUtility.GetPrefabParent(go);
if(pref && (pref.GetComponent<pb_Object>() || pref.GetComponent<pb_Entity>()))
{
unfixable.Add(go);
continue;
}
}
if(go.hideFlags != HideFlags.None)
{
unfixable.Add(go);
continue;
}
Selection.activeObject = go;
return;
}
}
}
pb_Object[] pbs = (pb_Object[])Resources.FindObjectsOfTypeAll(typeof(pb_Object));
for(int i = 0; i < pbs.Length; i++)
{
EditorUtility.DisplayProgressBar("Checking ProBuilder Meshes", "Refresh " + (i+1) + " out of " + total + " objects in scene.", ((float)i/pbs.Length) );
try
{
pbs[i].ToMesh();
pbs[i].Refresh();
pbs[i].Optimize();
} catch (System.Exception e)
{
Debug.LogWarning("Failed reconstituting " + pbs[i].name + ". Proceeding with upgrade anyways. Usually this means a prefab is already fixed, and just needs to be instantiated to take effect.\n" + e.ToString());
}
}
EditorUtility.ClearProgressBar();
if( applyDummyScript )
DeleteDummyScripts();
EditorUtility.DisplayDialog("Success", "Successfully repaired " + total + " ProBuilder objects.", "Okay");
if(!pb_EditorSceneUtility.SaveCurrentSceneIfUserWantsTo())
Debug.LogWarning("Repaired script references will be lost on exit if this scene is not saved!");
doFix = false;
skipEvent = true;
}
/**
* SerializedProperty names found in pb_Entity.
*/
List<string> PB_OBJECT_SCRIPT_PROPERTIES = new List<string>()
{
"_sharedIndices",
"_vertices",
"_uv",
"_sharedIndicesUV",
"_quads"
};
/**
* SerializedProperty names found in pb_Object.
*/
List<string> PB_ENTITY_SCRIPT_PROPERTIES = new List<string>()
{
"pb",
"userSetDimensions",
"_entityType",
"forceConvex"
};
// Prevents ArgumentException after displaying 'Done' dialog. For some reason the Event loop skips layout phase after DisplayDialog.
private static bool skipEvent = false;
public override void OnInspectorGUI()
{
if(skipEvent && Event.current.type == EventType.Repaint)
{
skipEvent = false;
return;
}
SerializedProperty scriptProperty = this.serializedObject.FindProperty("m_Script");
if(scriptProperty == null || scriptProperty.objectReferenceValue != null)
{
if(doFix)
{
if(Event.current.type == EventType.Repaint)
{
Next();
}
}
else
{
base.OnInspectorGUI();
}
return;
}
int pbObjectMatches = 0, pbEntityMatches = 0;
// Shows a detailed tree view of all the properties in this serializedobject.
// GUILayout.Label( SerializedObjectToString(this.serializedObject) );
SerializedProperty iterator = this.serializedObject.GetIterator();
iterator.Next(true);
while( iterator.Next(true) )
{
if( PB_OBJECT_SCRIPT_PROPERTIES.Contains(iterator.name) )
pbObjectMatches++;
if( PB_ENTITY_SCRIPT_PROPERTIES.Contains(iterator.name) )
pbEntityMatches++;
}
// If we can fix it, show the help box, otherwise just default inspector it up.
if(pbObjectMatches >= 3 || pbEntityMatches >= 3)
{
EditorGUILayout.HelpBox("Missing Script Reference\n\nProBuilder can automatically fix this missing reference. To fix all references in the scene, click \"Fix All in Scene\". To fix just this one, click \"Reconnect\".", MessageType.Warning);
}
else
{
if(doFix)
{
if( applyDummyScript )
{
index += .5f;
scriptProperty.objectReferenceValue = dummy_monoscript;
scriptProperty.serializedObject.ApplyModifiedProperties();
scriptProperty = this.serializedObject.FindProperty("m_Script");
scriptProperty.serializedObject.Update();
}
else
{
unfixable.Add( ((Component)target).gameObject );
}
Next();
GUIUtility.ExitGUI();
return;
}
else
{
base.OnInspectorGUI();
}
return;
}
GUI.backgroundColor = Color.green;
if(!doFix)
{
if(GUILayout.Button("Fix All in Scene"))
{
FixAllScriptReferencesInScene();
return;
}
}
GUI.backgroundColor = Color.cyan;
if((doFix && Event.current.type == EventType.Repaint) || GUILayout.Button("Reconnect"))
{
if(pbObjectMatches >= 3) // only increment for pb_Object otherwise the progress bar will fill 2x faster than it should
{
index++;
}
else
{
// Make sure that pb_Object is fixed first if we're automatically cycling objects.
if(doFix && ((Component)target).gameObject.GetComponent<pb_Object>() == null)
return;
}
if(!doFix)
{
Undo.RegisterCompleteObjectUndo(target, "Fix missing reference.");
}
// Debug.Log("Fix: " + (pbObjectMatches > 2 ? "pb_Object" : "pb_Entity") + " " + ((Component)target).gameObject.name);
scriptProperty.objectReferenceValue = pbObjectMatches >= 3 ? pb_monoscript : pe_monoscript;
scriptProperty.serializedObject.ApplyModifiedProperties();
scriptProperty = this.serializedObject.FindProperty("m_Script");
scriptProperty.serializedObject.Update();
if(doFix)
Next();
GUIUtility.ExitGUI();
}
GUI.backgroundColor = Color.white;
}
/**
* Scan the scene for gameObjects referencing `pb_DummyScript` and delete them.
*/
static void DeleteDummyScripts()
{
pb_DummyScript[] dummies = (pb_DummyScript[])Resources.FindObjectsOfTypeAll(typeof(pb_DummyScript));
dummies = dummies.Where(x => x.hideFlags == HideFlags.None).ToArray();
if(dummies.Length > 0)
{
int ret = EditorUtility.DisplayDialogComplex("Found Unrepairable Objects", "Repair script found " + dummies.Length + " missing components that could not be repaired. Would you like to delete those components now, or attempt to rebuild (ProBuilderize) them?", "Delete", "Cancel", "ProBuilderize");
switch(ret)
{
case 1: // cancel
{}
break;
default:
{
// Delete and ProBuilderize
if(ret == 2)
{
// Only interested in objects that have 2 null components (pb_Object and pb_Entity)
Object[] broken = (Object[])Resources.FindObjectsOfTypeAll(typeof(GameObject))
.Where(x => !x.Equals(null) &&
x is GameObject &&
((GameObject)x).GetComponents<pb_DummyScript>().Length == 2 &&
((GameObject)x).GetComponent<MeshRenderer>() != null &&
((GameObject)x).GetComponent<MeshFilter>() != null &&
((GameObject)x).GetComponent<MeshFilter>().sharedMesh != null
).ToArray();
broken = broken.Distinct().ToArray();
ProBuilder2.Actions.ProBuilderize.DoProBuilderize(System.Array.ConvertAll(broken, x => (GameObject)x).Select(x => x.GetComponent<MeshFilter>()), true);
}
// Always delete components
Undo.RecordObjects(dummies.Select(x=>x.gameObject).ToArray(), "Delete Broken Scripts");
for(int i = 0; i < dummies.Length; i++)
GameObject.DestroyImmediate( dummies[i] );
}
break;
}
}
}
/**
* Returns a formatted string with all properties in serialized object.
*/
static string SerializedObjectToString(SerializedObject serializedObject)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
if(serializedObject == null)
{
sb.Append("NULL");
return sb.ToString();
}
SerializedProperty iterator = serializedObject.GetIterator();
iterator.Next(true);
while( iterator.Next(true) )
{
string tabs = "";
for(int i = 0; i < iterator.depth; i++) tabs += "\t";
sb.AppendLine(tabs + iterator.name + (iterator.propertyType == SerializedPropertyType.ObjectReference && iterator.type.Contains("Component") && iterator.objectReferenceValue == null ? " -> NULL" : "") );
tabs += " - ";
sb.AppendLine(tabs + "Type: (" + iterator.type + " / " + iterator.propertyType + " / " + " / " + iterator.name + ")");
sb.AppendLine(tabs + iterator.propertyPath);
sb.AppendLine(tabs + "Value: " + SerializedPropertyValue(iterator));
}
return sb.ToString();
}
/**
* Return a string from the value of a SerializedProperty.
*/
static string SerializedPropertyValue(SerializedProperty sp)
{
switch(sp.propertyType)
{
case SerializedPropertyType.Integer:
return sp.intValue.ToString();
case SerializedPropertyType.Boolean:
return sp.boolValue.ToString();
case SerializedPropertyType.Float:
return sp.floatValue.ToString();
case SerializedPropertyType.String:
return sp.stringValue.ToString();
case SerializedPropertyType.Color:
return sp.colorValue.ToString();
case SerializedPropertyType.ObjectReference:
return (sp.objectReferenceValue == null ? "null" : sp.objectReferenceValue.name);
case SerializedPropertyType.LayerMask:
return sp.intValue.ToString();
case SerializedPropertyType.Enum:
return sp.enumValueIndex.ToString();
case SerializedPropertyType.Vector2:
return sp.vector2Value.ToString();
case SerializedPropertyType.Vector3:
return sp.vector3Value.ToString();
// Not public api as of 4.3?
// case SerializedPropertyType.Vector4:
// return sp.vector4Value.ToString();
case SerializedPropertyType.Rect:
return sp.rectValue.ToString();
case SerializedPropertyType.ArraySize:
return sp.intValue.ToString();
case SerializedPropertyType.Character:
return "Character";
case SerializedPropertyType.AnimationCurve:
return sp.animationCurveValue.ToString();
case SerializedPropertyType.Bounds:
return sp.boundsValue.ToString();
case SerializedPropertyType.Gradient:
return "Gradient";
default:
return "Unknown type";
}
}
}
}
| |
using System;
using System.Text;
namespace NBitcoin.BouncyCastle.Math.EC.Abc
{
/**
* Class representing a simple version of a big decimal. A
* <code>SimpleBigDecimal</code> is basically a
* {@link java.math.BigInteger BigInteger} with a few digits on the right of
* the decimal point. The number of (binary) digits on the right of the decimal
* point is called the <code>scale</code> of the <code>SimpleBigDecimal</code>.
* Unlike in {@link java.math.BigDecimal BigDecimal}, the scale is not adjusted
* automatically, but must be set manually. All <code>SimpleBigDecimal</code>s
* taking part in the same arithmetic operation must have equal scale. The
* result of a multiplication of two <code>SimpleBigDecimal</code>s returns a
* <code>SimpleBigDecimal</code> with double scale.
*/
internal class SimpleBigDecimal
// : Number
{
// private static final long serialVersionUID = 1L;
private readonly BigInteger bigInt;
private readonly int scale;
/**
* Returns a <code>SimpleBigDecimal</code> representing the same numerical
* value as <code>value</code>.
* @param value The value of the <code>SimpleBigDecimal</code> to be
* created.
* @param scale The scale of the <code>SimpleBigDecimal</code> to be
* created.
* @return The such created <code>SimpleBigDecimal</code>.
*/
public static SimpleBigDecimal GetInstance(BigInteger val, int scale)
{
return new SimpleBigDecimal(val.ShiftLeft(scale), scale);
}
/**
* Constructor for <code>SimpleBigDecimal</code>. The value of the
* constructed <code>SimpleBigDecimal</code> Equals <code>bigInt /
* 2<sup>scale</sup></code>.
* @param bigInt The <code>bigInt</code> value parameter.
* @param scale The scale of the constructed <code>SimpleBigDecimal</code>.
*/
public SimpleBigDecimal(BigInteger bigInt, int scale)
{
if (scale < 0)
throw new ArgumentException("scale may not be negative");
this.bigInt = bigInt;
this.scale = scale;
}
private SimpleBigDecimal(SimpleBigDecimal limBigDec)
{
bigInt = limBigDec.bigInt;
scale = limBigDec.scale;
}
private void CheckScale(SimpleBigDecimal b)
{
if (scale != b.scale)
throw new ArgumentException("Only SimpleBigDecimal of same scale allowed in arithmetic operations");
}
public SimpleBigDecimal AdjustScale(int newScale)
{
if (newScale < 0)
throw new ArgumentException("scale may not be negative");
if (newScale == scale)
return this;
return new SimpleBigDecimal(bigInt.ShiftLeft(newScale - scale), newScale);
}
public SimpleBigDecimal Add(SimpleBigDecimal b)
{
CheckScale(b);
return new SimpleBigDecimal(bigInt.Add(b.bigInt), scale);
}
public SimpleBigDecimal Add(BigInteger b)
{
return new SimpleBigDecimal(bigInt.Add(b.ShiftLeft(scale)), scale);
}
public SimpleBigDecimal Negate()
{
return new SimpleBigDecimal(bigInt.Negate(), scale);
}
public SimpleBigDecimal Subtract(SimpleBigDecimal b)
{
return Add(b.Negate());
}
public SimpleBigDecimal Subtract(BigInteger b)
{
return new SimpleBigDecimal(bigInt.Subtract(b.ShiftLeft(scale)), scale);
}
public SimpleBigDecimal Multiply(SimpleBigDecimal b)
{
CheckScale(b);
return new SimpleBigDecimal(bigInt.Multiply(b.bigInt), scale + scale);
}
public SimpleBigDecimal Multiply(BigInteger b)
{
return new SimpleBigDecimal(bigInt.Multiply(b), scale);
}
public SimpleBigDecimal Divide(SimpleBigDecimal b)
{
CheckScale(b);
BigInteger dividend = bigInt.ShiftLeft(scale);
return new SimpleBigDecimal(dividend.Divide(b.bigInt), scale);
}
public SimpleBigDecimal Divide(BigInteger b)
{
return new SimpleBigDecimal(bigInt.Divide(b), scale);
}
public SimpleBigDecimal ShiftLeft(int n)
{
return new SimpleBigDecimal(bigInt.ShiftLeft(n), scale);
}
public int CompareTo(SimpleBigDecimal val)
{
CheckScale(val);
return bigInt.CompareTo(val.bigInt);
}
public int CompareTo(BigInteger val)
{
return bigInt.CompareTo(val.ShiftLeft(scale));
}
public BigInteger Floor()
{
return bigInt.ShiftRight(scale);
}
public BigInteger Round()
{
SimpleBigDecimal oneHalf = new SimpleBigDecimal(BigInteger.One, 1);
return Add(oneHalf.AdjustScale(scale)).Floor();
}
public int IntValue
{
get { return Floor().IntValue; }
}
public long LongValue
{
get { return Floor().LongValue; }
}
// public double doubleValue()
// {
// return new Double(ToString()).doubleValue();
// }
//
// public float floatValue()
// {
// return new Float(ToString()).floatValue();
// }
public int Scale
{
get { return scale; }
}
public override string ToString()
{
if (scale == 0)
return bigInt.ToString();
BigInteger floorBigInt = Floor();
BigInteger fract = bigInt.Subtract(floorBigInt.ShiftLeft(scale));
if (bigInt.SignValue < 0)
{
fract = BigInteger.One.ShiftLeft(scale).Subtract(fract);
}
if ((floorBigInt.SignValue == -1) && (!(fract.Equals(BigInteger.Zero))))
{
floorBigInt = floorBigInt.Add(BigInteger.One);
}
string leftOfPoint = floorBigInt.ToString();
char[] fractCharArr = new char[scale];
string fractStr = fract.ToString(2);
int fractLen = fractStr.Length;
int zeroes = scale - fractLen;
for (int i = 0; i < zeroes; i++)
{
fractCharArr[i] = '0';
}
for (int j = 0; j < fractLen; j++)
{
fractCharArr[zeroes + j] = fractStr[j];
}
string rightOfPoint = new string(fractCharArr);
StringBuilder sb = new StringBuilder(leftOfPoint);
sb.Append(".");
sb.Append(rightOfPoint);
return sb.ToString();
}
public override bool Equals(
object obj)
{
if (this == obj)
return true;
SimpleBigDecimal other = obj as SimpleBigDecimal;
if (other == null)
return false;
return bigInt.Equals(other.bigInt)
&& scale == other.scale;
}
public override int GetHashCode()
{
return bigInt.GetHashCode() ^ scale;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void AddSByte()
{
var test = new SimpleBinaryOpTest__AddSByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.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 (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.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 (AdvSimd.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 (AdvSimd.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 (AdvSimd.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__AddSByte
{
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(SByte[] inArray1, SByte[] inArray2, SByte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>();
if ((alignment != 16 && alignment != 8) || (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<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<SByte> _fld1;
public Vector128<SByte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__AddSByte testClass)
{
var result = AdvSimd.Add(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddSByte testClass)
{
fixed (Vector128<SByte>* pFld1 = &_fld1)
fixed (Vector128<SByte>* pFld2 = &_fld2)
{
var result = AdvSimd.Add(
AdvSimd.LoadVector128((SByte*)(pFld1)),
AdvSimd.LoadVector128((SByte*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte);
private static SByte[] _data1 = new SByte[Op1ElementCount];
private static SByte[] _data2 = new SByte[Op2ElementCount];
private static Vector128<SByte> _clsVar1;
private static Vector128<SByte> _clsVar2;
private Vector128<SByte> _fld1;
private Vector128<SByte> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__AddSByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
}
public SimpleBinaryOpTest__AddSByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
_dataTable = new DataTable(_data1, _data2, new SByte[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Add(
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<SByte>>(_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 = AdvSimd.Add(
AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((SByte*)(_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(AdvSimd).GetMethod(nameof(AdvSimd.Add), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Add), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Add(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<SByte>* pClsVar1 = &_clsVar1)
fixed (Vector128<SByte>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.Add(
AdvSimd.LoadVector128((SByte*)(pClsVar1)),
AdvSimd.LoadVector128((SByte*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr);
var result = AdvSimd.Add(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr));
var result = AdvSimd.Add(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__AddSByte();
var result = AdvSimd.Add(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__AddSByte();
fixed (Vector128<SByte>* pFld1 = &test._fld1)
fixed (Vector128<SByte>* pFld2 = &test._fld2)
{
var result = AdvSimd.Add(
AdvSimd.LoadVector128((SByte*)(pFld1)),
AdvSimd.LoadVector128((SByte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Add(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<SByte>* pFld1 = &_fld1)
fixed (Vector128<SByte>* pFld2 = &_fld2)
{
var result = AdvSimd.Add(
AdvSimd.LoadVector128((SByte*)(pFld1)),
AdvSimd.LoadVector128((SByte*)(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 = AdvSimd.Add(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 = AdvSimd.Add(
AdvSimd.LoadVector128((SByte*)(&test._fld1)),
AdvSimd.LoadVector128((SByte*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<SByte> op1, Vector128<SByte> op2, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((sbyte)(left[0] + right[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((sbyte)(left[i] + right[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Add)}<SByte>(Vector128<SByte>, Vector128<SByte>): {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.
/*=============================================================================
**
** Class: CollectionBase
**
** Purpose: Provides the abstract base class for a strongly typed collection.
**
=============================================================================*/
using System.Diagnostics.Contracts;
namespace System.Collections
{
// Useful base class for typed read/write collections where items derive from object
public abstract class CollectionBase : IList
{
private ArrayList _list;
protected CollectionBase()
{
_list = new ArrayList();
}
protected CollectionBase(int capacity)
{
_list = new ArrayList(capacity);
}
protected ArrayList InnerList
{
get
{
return _list;
}
}
protected IList List
{
get { return (IList)this; }
}
public int Capacity
{
get
{
return InnerList.Capacity;
}
set
{
InnerList.Capacity = value;
}
}
public int Count
{
get
{
return _list.Count;
}
}
public void Clear()
{
OnClear();
InnerList.Clear();
OnClearComplete();
}
public void RemoveAt(int index)
{
if (index < 0 || index >= Count)
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
Object temp = InnerList[index];
OnValidate(temp);
OnRemove(index, temp);
InnerList.RemoveAt(index);
try
{
OnRemoveComplete(index, temp);
}
catch
{
InnerList.Insert(index, temp);
throw;
}
}
bool IList.IsReadOnly
{
get { return InnerList.IsReadOnly; }
}
bool IList.IsFixedSize
{
get { return InnerList.IsFixedSize; }
}
bool ICollection.IsSynchronized
{
get { return InnerList.IsSynchronized; }
}
Object ICollection.SyncRoot
{
get { return InnerList.SyncRoot; }
}
void ICollection.CopyTo(Array array, int index)
{
InnerList.CopyTo(array, index);
}
Object IList.this[int index]
{
get
{
if (index < 0 || index >= Count)
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
return InnerList[index];
}
set
{
if (index < 0 || index >= Count)
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
OnValidate(value);
Object temp = InnerList[index];
OnSet(index, temp, value);
InnerList[index] = value;
try
{
OnSetComplete(index, temp, value);
}
catch
{
InnerList[index] = temp;
throw;
}
}
}
bool IList.Contains(Object value)
{
return InnerList.Contains(value);
}
int IList.Add(Object value)
{
OnValidate(value);
OnInsert(InnerList.Count, value);
int index = InnerList.Add(value);
try
{
OnInsertComplete(index, value);
}
catch
{
InnerList.RemoveAt(index);
throw;
}
return index;
}
void IList.Remove(Object value)
{
OnValidate(value);
int index = InnerList.IndexOf(value);
if (index < 0) throw new ArgumentException(SR.Arg_RemoveArgNotFound);
OnRemove(index, value);
InnerList.RemoveAt(index);
try
{
OnRemoveComplete(index, value);
}
catch
{
InnerList.Insert(index, value);
throw;
}
}
int IList.IndexOf(Object value)
{
return InnerList.IndexOf(value);
}
void IList.Insert(int index, Object value)
{
if (index < 0 || index > Count)
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
OnValidate(value);
OnInsert(index, value);
InnerList.Insert(index, value);
try
{
OnInsertComplete(index, value);
}
catch
{
InnerList.RemoveAt(index);
throw;
}
}
public IEnumerator GetEnumerator()
{
return InnerList.GetEnumerator();
}
protected virtual void OnSet(int index, Object oldValue, Object newValue)
{
}
protected virtual void OnInsert(int index, Object value)
{
}
protected virtual void OnClear()
{
}
protected virtual void OnRemove(int index, Object value)
{
}
protected virtual void OnValidate(Object value)
{
if (value == null) throw new ArgumentNullException(nameof(value));
Contract.EndContractBlock();
}
protected virtual void OnSetComplete(int index, Object oldValue, Object newValue)
{
}
protected virtual void OnInsertComplete(int index, Object value)
{
}
protected virtual void OnClearComplete()
{
}
protected virtual void OnRemoveComplete(int index, Object value)
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using SIL.Email;
using SIL.Reporting;
using System.Runtime.InteropServices;
using SIL.PlatformUtilities;
namespace SIL.Windows.Forms.Reporting
{
/// <summary>
/// Display exception reporting dialog.
/// NOTE: It is recommended to call one of Palaso.Reporting.ErrorReport.Report(Non)Fatal*
/// methods instead of instantiating this class.
/// </summary>
public class ExceptionReportingDialog : Form
{
#region Local structs
private struct ExceptionReportingData
{
public ExceptionReportingData(string message, string messageBeforeStack,
Exception error, StackTrace stackTrace, Form owningForm, int threadId)
{
Message = message;
MessageBeforeStack = messageBeforeStack;
Error = error;
StackTrace = stackTrace;
OwningForm = owningForm;
ThreadId = threadId;
}
public string Message;
public string MessageBeforeStack;
public Exception Error;
public Form OwningForm;
public StackTrace StackTrace;
public int ThreadId;
}
#endregion
#region Member variables
private Label label3;
private TextBox _details;
private TextBox _pleaseHelpText;
private TextBox m_reproduce;
private bool _isLethal;
private Button _sendAndCloseButton;
private TextBox _notificationText;
private TextBox textBox1;
private ComboBox _methodCombo;
private Button _privacyNoticeButton;
private Label _emailAddress;
private static bool s_doIgnoreReport;
/// <summary>
/// Stack with exception data.
/// </summary>
/// <remarks>When an exception occurs on a background thread ideally it should be handled
/// by the application. However, not all applications are always implemented to do it
/// that way, so we need a safe fall back that doesn't pop up a dialog from a (non-UI)
/// background thread.
///
/// This implementation creates a control on the UI thread
/// (WinFormsExceptionHandler.ControlOnUIThread) in order to be able to check
/// if invoke is required. When an exception occurs on a background thread we push the
/// exception data to an exception data stack and try to invoke the exception dialog on
/// the UI thread. In case that the UI thread already shows an exception dialog we skip
/// the exception (similar to the behavior we already have when we get an exception on
/// the UI thread while displaying the exception dialog). Otherwise we display the
/// exception dialog, appending the messages from the exception data stack.</remarks>
private static Stack<ExceptionReportingData> s_reportDataStack = new Stack<ExceptionReportingData>();
#endregion
protected ExceptionReportingDialog(bool isLethal)
{
_isLethal = isLethal;
}
#region IDisposable override
/// <summary>
/// Check to see if the object has been disposed.
/// All public Properties and Methods should call this
/// before doing anything else.
/// </summary>
public void CheckDisposed()
{
if (IsDisposed)
{
throw new ObjectDisposedException(String.Format("'{0}' in use after being disposed.", GetType().Name));
}
}
/// <summary>
/// Executes in two distinct scenarios.
///
/// 1. If disposing is true, the method has been called directly
/// or indirectly by a user's code via the Dispose method.
/// Both managed and unmanaged resources can be disposed.
///
/// 2. If disposing is false, the method has been called by the
/// runtime from inside the finalizer and you should not reference (access)
/// other managed objects, as they already have been garbage collected.
/// Only unmanaged resources can be disposed.
/// </summary>
/// <param name="disposing"></param>
/// <remarks>
/// If any exceptions are thrown, that is fine.
/// If the method is being done in a finalizer, it will be ignored.
/// If it is thrown by client code calling Dispose,
/// it needs to be handled by fixing the bug.
///
/// If subclasses override this method, they should call the base implementation.
/// </remarks>
protected override void Dispose(bool disposing)
{
//Debug.WriteLineIf(!disposing, "****************** " + GetType().Name + " 'disposing' is false. ******************");
// Must not be run more than once.
if (IsDisposed)
{
return;
}
if (disposing)
{
// Dispose managed resources here.
}
// Dispose unmanaged resources here, whether disposing is true or false.
base.Dispose(disposing);
}
#endregion IDisposable override
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ExceptionReportingDialog));
this.m_reproduce = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this._details = new System.Windows.Forms.TextBox();
this._sendAndCloseButton = new System.Windows.Forms.Button();
this._pleaseHelpText = new System.Windows.Forms.TextBox();
this._notificationText = new System.Windows.Forms.TextBox();
this.textBox1 = new System.Windows.Forms.TextBox();
this._methodCombo = new System.Windows.Forms.ComboBox();
this._privacyNoticeButton = new System.Windows.Forms.Button();
this._emailAddress = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// m_reproduce
//
this.m_reproduce.AcceptsReturn = true;
this.m_reproduce.AcceptsTab = true;
resources.ApplyResources(this.m_reproduce, "m_reproduce");
this.m_reproduce.Name = "m_reproduce";
//
// label3
//
resources.ApplyResources(this.label3, "label3");
this.label3.Name = "label3";
//
// _details
//
resources.ApplyResources(this._details, "_details");
this._details.BackColor = System.Drawing.SystemColors.ControlLightLight;
this._details.Name = "_details";
this._details.ReadOnly = true;
//
// _sendAndCloseButton
//
resources.ApplyResources(this._sendAndCloseButton, "_sendAndCloseButton");
this._sendAndCloseButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this._sendAndCloseButton.Name = "_sendAndCloseButton";
this._sendAndCloseButton.Click += new System.EventHandler(this.btnClose_Click);
//
// _pleaseHelpText
//
resources.ApplyResources(this._pleaseHelpText, "_pleaseHelpText");
this._pleaseHelpText.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
this._pleaseHelpText.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._pleaseHelpText.ForeColor = System.Drawing.Color.Black;
this._pleaseHelpText.Name = "_pleaseHelpText";
this._pleaseHelpText.ReadOnly = true;
//
// _notificationText
//
resources.ApplyResources(this._notificationText, "_notificationText");
this._notificationText.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
this._notificationText.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._notificationText.ForeColor = System.Drawing.Color.Black;
this._notificationText.Name = "_notificationText";
this._notificationText.ReadOnly = true;
//
// textBox1
//
resources.ApplyResources(this.textBox1, "textBox1");
this.textBox1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
this.textBox1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.textBox1.ForeColor = System.Drawing.Color.Black;
this.textBox1.Name = "textBox1";
this.textBox1.ReadOnly = true;
//
// _methodCombo
//
resources.ApplyResources(this._methodCombo, "_methodCombo");
this._methodCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this._methodCombo.FormattingEnabled = true;
this._methodCombo.Name = "_methodCombo";
this._methodCombo.SelectedIndexChanged += new System.EventHandler(this._methodCombo_SelectedIndexChanged);
//
// _privacyNoticeButton
//
resources.ApplyResources(this._privacyNoticeButton, "_privacyNoticeButton");
this._privacyNoticeButton.Image = global::SIL.Windows.Forms.Properties.Resources.spy16x16;
this._privacyNoticeButton.Name = "_privacyNoticeButton";
this._privacyNoticeButton.UseVisualStyleBackColor = true;
this._privacyNoticeButton.Click += new System.EventHandler(this._privacyNoticeButton_Click);
//
// _emailAddress
//
resources.ApplyResources(this._emailAddress, "_emailAddress");
this._emailAddress.ForeColor = System.Drawing.Color.DimGray;
this._emailAddress.Name = "_emailAddress";
//
// ExceptionReportingDialog
//
this.AcceptButton = this._sendAndCloseButton;
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
this.Controls.Add(this._emailAddress);
this.Controls.Add(this._privacyNoticeButton);
this.Controls.Add(this._methodCombo);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.m_reproduce);
this.Controls.Add(this._notificationText);
this.Controls.Add(this._pleaseHelpText);
this.Controls.Add(this._details);
this.Controls.Add(this.label3);
this.Controls.Add(this._sendAndCloseButton);
this.KeyPreview = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "ExceptionReportingDialog";
this.ControlBox = true;
this.ShowIcon = false; // Showing the Control box ("X") also shows a default icon.
this.TopMost = true;
this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.ExceptionReportingDialog_KeyPress);
this.ResumeLayout(false);
this.PerformLayout();
}
private void SetupMethodCombo()
{
_methodCombo.Items.Clear();
_methodCombo.Items.Add(new ReportingMethod("Send using my email program", "&Email", "mapiWithPopup", SendViaEmail));
_methodCombo.Items.Add(new ReportingMethod("Copy to clipboard", "&Copy", "clipboard", PutOnClipboard));
}
class ReportingMethod
{
private readonly string _label;
public readonly string CloseButtonLabel;
public readonly string Id;
public readonly Func<bool> Method;
public ReportingMethod(string label, string closeButtonLabel, string id, Func<bool> method)
{
_label = label;
CloseButtonLabel = closeButtonLabel;
Id = id;
Method = method;
}
public override string ToString()
{
return _label;
}
}
#endregion
/// ------------------------------------------------------------------------------------
/// <summary>
/// show a dialog or output to the error log, as appropriate.
/// </summary>
/// <param name="error">the exception you want to report</param>
/// ------------------------------------------------------------------------------------
internal static void ReportException(Exception error)
{
ReportException(error, null);
}
/// <summary>
///
/// </summary>
/// <param name="error"></param>
/// <param name="parent"></param>
internal static void ReportException(Exception error, Form parent)
{
ReportException(error, null, true);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// show a dialog or output to the error log, as appropriate.
/// </summary>
/// <param name="error">the exception you want to report</param>
/// <param name="parent">the parent form that this error belongs to (i.e. the form
/// show modally on)</param>
/// ------------------------------------------------------------------------------------
/// <param name="isLethal"></param>
internal static void ReportException(Exception error, Form parent, bool isLethal)
{
if (s_doIgnoreReport)
{
lock (s_reportDataStack)
{
s_reportDataStack.Push(new ExceptionReportingData(null, null, error,
null, parent, Thread.CurrentThread.ManagedThreadId));
}
return; // ignore message if we are showing from a previous error
}
using (ExceptionReportingDialog dlg = new ExceptionReportingDialog(isLethal))
{
dlg.Report(error, parent);
}
}
internal static void ReportMessage(string message, StackTrace stack, bool isLethal)
{
if (s_doIgnoreReport)
{
lock (s_reportDataStack)
{
s_reportDataStack.Push(new ExceptionReportingData(message, null, null,
stack, null, Thread.CurrentThread.ManagedThreadId));
}
return; // ignore message if we are showing from a previous error
}
using (ExceptionReportingDialog dlg = new ExceptionReportingDialog(isLethal))
{
dlg.Report(message, string.Empty, stack, null);
}
}
internal static void ReportMessage(string message, Exception error, bool isLethal)
{
if (s_doIgnoreReport)
{
lock (s_reportDataStack)
{
s_reportDataStack.Push(new ExceptionReportingData(message, null, error,
null, null, Thread.CurrentThread.ManagedThreadId));
}
return; // ignore message if we are showing from a previous error
}
using (ExceptionReportingDialog dlg = new ExceptionReportingDialog(isLethal))
{
dlg.Report(message, null, error,null);
}
}
protected void GatherData()
{
_details.Text += Environment.NewLine + "To Reproduce: " + m_reproduce.Text + Environment.NewLine;
}
public void Report(Exception error, Form owningForm)
{
Report(null,null, error, owningForm);
}
public void Report(string message, string messageBeforeStack, Exception error, Form owningForm)
{
lock (s_reportDataStack)
{
s_reportDataStack.Push(new ExceptionReportingData(message, messageBeforeStack, error,
null, owningForm, Thread.CurrentThread.ManagedThreadId));
}
if (WinFormsExceptionHandler.InvokeRequired)
{
// we got called from a background thread.
WinFormsExceptionHandler.ControlOnUIThread.Invoke(
new Action(ReportInternal));
return;
}
ReportInternal();
}
public void Report(string message, string messageBeforeStack, StackTrace stackTrace, Form owningForm)
{
lock (s_reportDataStack)
{
s_reportDataStack.Push(new ExceptionReportingData(message, messageBeforeStack, null,
stackTrace, owningForm, Thread.CurrentThread.ManagedThreadId));
}
if (WinFormsExceptionHandler.InvokeRequired)
{
// we got called from a background thread.
WinFormsExceptionHandler.ControlOnUIThread.Invoke(
new Action(ReportInternal));
return;
}
ReportInternal();
}
private void ReportInternal()
{
// This method will/should always be called on the UI thread
Debug.Assert(!WinFormsExceptionHandler.InvokeRequired);
ExceptionReportingData reportingData;
lock (s_reportDataStack)
{
if (s_reportDataStack.Count <= 0)
return;
reportingData = s_reportDataStack.Pop();
}
ReportExceptionToAnalytics(reportingData);
if (s_doIgnoreReport)
return; // ignore message if we are showing from a previous error
PrepareDialog();
if(!string.IsNullOrEmpty(reportingData.Message))
_notificationText.Text = reportingData.Message;
var bldr = new StringBuilder();
var innerMostException = FormatMessage(bldr, reportingData);
bldr.Append(AddMessagesFromBackgroundThreads());
_details.Text += bldr.ToString();
Debug.WriteLine(_details.Text);
var error = reportingData.Error;
if (error != null)
{
if (innerMostException != null)
{
error = innerMostException;
}
try
{
Logger.WriteEvent("Got exception " + error.GetType().Name);
}
catch (Exception err)
{
//We have more than one report of dieing while logging an exception.
_details.Text += "****Could not write to log (" + err.Message + ")" + Environment.NewLine;
_details.Text += "Was trying to log the exception: " + error.Message + Environment.NewLine;
_details.Text += "Recent events:" + Environment.NewLine;
_details.Text += Logger.MinorEventsLog;
}
}
else
{
try
{
Logger.WriteEvent("Got error message " + reportingData.Message);
}
catch (Exception err)
{
//We have more than one report of dieing while logging an exception.
_details.Text += "****Could not write to log (" + err.Message + ")" + Environment.NewLine;
}
}
ShowReportDialogIfAppropriate(reportingData.OwningForm);
}
private static void ReportExceptionToAnalytics(ExceptionReportingData reportingData)
{
try
{
if (!string.IsNullOrEmpty(reportingData.Message))
UsageReporter.ReportExceptionString(reportingData.Message);
else if (reportingData.Error != null)
UsageReporter.ReportException(reportingData.Error);
}
catch
{
//swallow
}
}
private static string AddMessagesFromBackgroundThreads()
{
var bldr = new StringBuilder();
for (bool messageOnStack = AddNextMessageFromStack(bldr); messageOnStack;)
messageOnStack = AddNextMessageFromStack(bldr);
return bldr.ToString();
}
private static bool AddNextMessageFromStack(StringBuilder bldr)
{
ExceptionReportingData data;
lock (s_reportDataStack)
{
if (s_reportDataStack.Count <= 0)
return false;
data = s_reportDataStack.Pop();
}
ReportExceptionToAnalytics(data);
bldr.AppendLine("---------------------------------");
bldr.AppendFormat("The following exception occurred on a different thread ({0}) at about the same time:",
data.ThreadId);
bldr.AppendLine();
bldr.AppendLine();
FormatMessage(bldr, data);
return true;
}
private static Exception FormatMessage(StringBuilder bldr, ExceptionReportingData data)
{
if (!string.IsNullOrEmpty(data.Message))
{
bldr.Append("Message (not an exception): ");
bldr.AppendLine(data.Message);
bldr.AppendLine();
}
if (!string.IsNullOrEmpty(data.MessageBeforeStack))
{
bldr.AppendLine(data.MessageBeforeStack);
}
if (data.Error != null)
{
Exception innerMostException = null;
bldr.Append(ErrorReport.GetHiearchicalExceptionInfo(data.Error, ref innerMostException));
//if the exception had inner exceptions, show the inner-most exception first, since that is usually the one
//we want the developer to read.
if (innerMostException != null)
{
var oldText = bldr.ToString();
bldr.Clear();
bldr.AppendLine("Inner-most exception:");
bldr.AppendLine(ErrorReport.GetExceptionText(innerMostException));
bldr.AppendLine();
bldr.AppendLine("Full, hierarchical exception contents:");
bldr.Append(oldText);
}
AddErrorReportingPropertiesToDetails(bldr);
return innerMostException;
}
if (data.StackTrace != null)
{
bldr.AppendLine("--Stack--");
bldr.AppendLine(data.StackTrace.ToString());
}
return null;
}
private static void AddErrorReportingPropertiesToDetails(StringBuilder bldr)
{
bldr.AppendLine();
bldr.AppendLine("--Error Reporting Properties--");
foreach (string label in ErrorReport.Properties.Keys)
{
bldr.Append(label);
bldr.Append(": ");
bldr.AppendLine(ErrorReport.Properties[label]);
}
bldr.AppendLine();
bldr.AppendLine("--Log--");
try
{
bldr.Append(Logger.LogText);
}
catch (Exception err)
{
//We have more than one report of dieing while logging an exception.
bldr.AppendLine("****Could not read from log: " + err.Message);
}
}
private void PrepareDialog()
{
CheckDisposed();
Font = SystemFonts.MessageBoxFont;
//
// Required for Windows Form Designer support
//
InitializeComponent();
_emailAddress.Text = ErrorReport.EmailAddress;
SetupMethodCombo();
foreach (ReportingMethod method in _methodCombo.Items)
{
if (ErrorReportSettings.Default.ReportingMethod == method.Id)
{
SelectedMethod = method;
break;
}
}
if (!_isLethal)
{
BackColor = Color.FromArgb(255, 255, 192); //yellow
_notificationText.Text = "Take Courage. It'll work out.";
_notificationText.BackColor = BackColor;
_pleaseHelpText.BackColor = BackColor;
textBox1.BackColor = BackColor;
}
SetupCloseButtonText();
}
private void ShowReportDialogIfAppropriate(Form owningForm)
{
if (ErrorReport.IsOkToInteractWithUser)
{
s_doIgnoreReport = true;
ShowDialog(owningForm);
s_doIgnoreReport = false;
}
else //the test environment already prohibits dialogs but will save the contents of assertions in some log.
{
Debug.Fail(_details.Text);
}
}
/// ------------------------------------------------------------------------------------
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// ------------------------------------------------------------------------------------
private void btnClose_Click(object sender, EventArgs e)
{
ErrorReportSettings.Default.ReportingMethod = ((ReportingMethod) (_methodCombo.SelectedItem)).Id;
ErrorReportSettings.Default.Save();
if (ModifierKeys.Equals(Keys.Shift))
{
return;
}
GatherData();
// Clipboard.SetDataObject(_details.Text, true);
if (SelectedMethod.Method())
{
CloseUp();
}
else
{
PutOnClipboard();
CloseUp();
}
}
private bool PutOnClipboard()
{
if (ErrorReport.EmailAddress != null)
{
_details.Text = String.Format("Please e-mail this to {0} {1}", ErrorReport.EmailAddress, _details.Text);
}
if (!Platform.IsWindows)
{
try
{
// Workaround for Xamarin bug #4959. Eberhard had a mono fix for that bug
// but it doesn't work with FW (or Palaso) -- he couldn't figure out why not.
// This is a dirty hack but at least it works :-)
var clipboardAtom = gdk_atom_intern("CLIPBOARD", true);
var clipboard = gtk_clipboard_get(clipboardAtom);
if (clipboard != IntPtr.Zero)
{
gtk_clipboard_set_text(clipboard, _details.Text, -1);
gtk_clipboard_store(clipboard);
}
}
catch
{
// ignore any errors - most likely because gtk isn't installed?
return false;
}
}
else
Clipboard.SetDataObject(_details.Text, true);
return true;
}
// Workaround for Xamarin bug #4959
[DllImport("libgdk-x11-2.0")]
private static extern IntPtr gdk_atom_intern(string atomName, bool onlyIfExists);
[DllImport("libgtk-x11-2.0")]
private static extern IntPtr gtk_clipboard_get(IntPtr atom);
[DllImport("libgtk-x11-2.0")]
private static extern void gtk_clipboard_store(IntPtr clipboard);
[DllImport("libgtk-x11-2.0")]
private static extern void gtk_clipboard_set_text(IntPtr clipboard, [MarshalAs(UnmanagedType.LPStr)] string text, int len);
private bool SendViaEmail()
{
try
{
var emailProvider = EmailProviderFactory.PreferredEmailProvider();
var emailMessage = emailProvider.CreateMessage();
emailMessage.To.Add(ErrorReport.EmailAddress);
emailMessage.Subject = ErrorReport.EmailSubject;
emailMessage.Body = _details.Text;
if (emailMessage.Send(emailProvider))
{
CloseUp();
return true;
}
}
catch (Exception)
{
//swallow it and go to the alternate method
}
try
{
//EmailMessage msg = new EmailMessage();
// This currently does not work. The main issue seems to be the length of the error report. mailto
// apparently has some limit on the length of the message, and we are exceeding that.
var emailProvider = EmailProviderFactory.PreferredEmailProvider();
var emailMessage = emailProvider.CreateMessage();
emailMessage.To.Add(ErrorReport.EmailAddress);
emailMessage.Subject = ErrorReport.EmailSubject;
if (Environment.OSVersion.Platform == PlatformID.Unix)
{
emailMessage.Body = _details.Text;
}
else
{
PutOnClipboard();
emailMessage.Body = "<Details of the crash have been copied to the clipboard. Please paste them here>";
}
if (emailMessage.Send(emailProvider))
{
CloseUp();
return true;
}
}
catch (Exception error)
{
PutOnClipboard();
ErrorReport.NotifyUserOfProblem(error,
"This program wasn't able to get your email program, if you have one, to send the error message. " +
"The contents of the error message has been placed on your Clipboard.");
return false;
}
return false;
}
private void CloseUp()
{
if (!_isLethal || ModifierKeys.Equals(Keys.Shift))
{
try
{
Logger.WriteEvent("Error Dialog: Continuing...");
}
catch (Exception)
{
//really can't handle an embedded error related to logging
}
Close();
return;
}
try
{
Logger.WriteEvent("Error Dialog: Exiting...");
}
catch (Exception)
{
//really can't handle an embedded error related to logging
}
Process.GetCurrentProcess().Kill();
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Shows the attempt to continue label if the shift key is pressed
/// </summary>
/// <param name="e"></param>
/// ------------------------------------------------------------------------------------
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyCode == Keys.ShiftKey && Visible)
{
_sendAndCloseButton.Text = "Continue";
}
base.OnKeyDown(e);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Hides the attempt to continue label if the shift key is pressed
/// </summary>
/// <param name="e"></param>
/// ------------------------------------------------------------------------------------
protected override void OnKeyUp(KeyEventArgs e)
{
if (e.KeyCode == Keys.ShiftKey && Visible)
{
SetupCloseButtonText();
}
base.OnKeyUp(e);
}
private void OnJustExit_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
CloseUp();
}
private void _methodCombo_SelectedIndexChanged(object sender, EventArgs e)
{
SetupCloseButtonText();
}
private void SetupCloseButtonText()
{
_sendAndCloseButton.Text = SelectedMethod.CloseButtonLabel;
if (!_isLethal)
{
// _dontSendEmailLink.Text = "Don't Send Email";
}
else
{
_sendAndCloseButton.Text += " and Exit";
}
}
private ReportingMethod SelectedMethod
{
get { return ((ReportingMethod) _methodCombo.SelectedItem); }
set { _methodCombo.SelectedItem = value; }
}
public static string PrivacyNotice = @"If you don't care who reads your bug report, you can skip this notice.
When you submit a crash report or other issue, the contents of your email go in our issue tracking system, ""jira"", which is available via the web at https://jira.sil.org/issues. This is the normal way to handle issues in an open-source project.
Our issue-tracking system is not searchable by those without an account. Therefore, someone searching via Google will not find your bug reports.
However, anyone can make an account and then read what you sent us. So if you have something private to say, please send it to one of the developers privately with a note that you don't want the issue in our issue tracking system. If need be, we'll make some kind of sanitized place-holder for your issue so that we don't lose it.
";
private void _privacyNoticeButton_Click(object sender, EventArgs e)
{
MessageBox.Show(PrivacyNotice, "Privacy Notice");
}
private void ExceptionReportingDialog_KeyPress(object sender, KeyPressEventArgs e)
{
if(e.KeyChar== 27)//ESCAPE
{
CloseUp();
}
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System;
using System.Xml;
using System.IO;
using System.Collections;
using System.Collections.Generic;
public class UnitAbilityEditorWindow : EditorWindow {
public delegate void UpdateHandler();
public static event UpdateHandler onUnitAbilityUpdateE;
static private UnitAbilityEditorWindow window;
static string[] abilityTargetAreaLabel=new string[3];
static string[] abilityEffectTypeLabel=new string[4];
static string[] abilityTargetTypeLabel=new string[4];
static string[] effectAttrTypeLabel=new string[4];
static string[] shootModeLabel=new string[4];
static string[] abilityTargetAreaTooltip=new string[3];
static string[] abilityEffectTypeTooltip=new string[4];
static string[] abilityTargetTypeTooltip=new string[4];
static string[] effectAttrTypeTooltip=new string[4];
static string[] shootModeTooltip=new string[4];
static string[] damageList=new string[0];
static string[] armorList=new string[0];
static string[] damageTooltipList=new string[0];
static string[] armorTooltipList=new string[0];
// Add menu named "PerkEditor" to the Window menu
//[MenuItem ("TDTK/PerkEditor")]
public static void Init () {
// Get existing open window or if none, make a new one:
window = (UnitAbilityEditorWindow)EditorWindow.GetWindow(typeof (UnitAbilityEditorWindow));
window.minSize=new Vector2(615, 600);
window.maxSize=new Vector2(615, 801);
Load();
LoadDamageArmor();
InitLabel();
}
static void InitLabel(){
int enumLength = Enum.GetValues(typeof(_TargetArea)).Length;
abilityTargetAreaLabel=new string[enumLength];
for(int i=0; i<enumLength; i++) abilityTargetAreaLabel[i]=((_TargetArea)i).ToString();
abilityTargetAreaTooltip=new string[enumLength];
abilityTargetAreaTooltip[0]="Any tile within range, when AOE is enabled, surrounding tile of the selected tile is included";
abilityTargetAreaTooltip[1]="A a striaight line of tiles extend from the tile occupied by source unit";
abilityTargetAreaTooltip[2]="A conical area extend from the tile occupied by source unit\nNot applicable for SquareTile, Line will be used instead";
enumLength = Enum.GetValues(typeof(_EffectType)).Length;
abilityEffectTypeLabel=new string[enumLength];
for(int i=0; i<enumLength; i++) abilityEffectTypeLabel[i]=((_EffectType)i).ToString();
abilityEffectTypeTooltip=new string[enumLength];
abilityEffectTypeTooltip[0]="for instant effect (doesnt persist through round) that target friendly units";
abilityEffectTypeTooltip[1]="for instant effect (doesnt persist through round) that target hostile units";
abilityEffectTypeTooltip[2]="for buff effect (persist through round) that target friendly units";
abilityEffectTypeTooltip[3]="for debuff effect (persist through round) that target hostile units";
enumLength = Enum.GetValues(typeof(_AbilityTargetType)).Length;
abilityTargetTypeLabel=new string[enumLength];
for(int i=0; i<enumLength; i++) abilityTargetTypeLabel[i]=((_AbilityTargetType)i).ToString();
abilityTargetTypeTooltip=new string[enumLength];
abilityTargetTypeTooltip[0]="Target all unit, both friendly or hostile";
abilityTargetTypeTooltip[1]="Target friendly unit";
abilityTargetTypeTooltip[2]="Target hostile unit";
abilityTargetTypeTooltip[3]="Target tiles only";
//AllUnits, Friendly, Hostile, Tile
//~ abilityTargetTypeTooltip=new string[enumLength];
//~ abilityTargetTypeTooltip[0]="Target effect to self";
//~ abilityTargetTypeTooltip[1]="Target effect to the occupied tile";
//~ abilityTargetTypeTooltip[2]="Target effect to friendly unit";
//~ abilityTargetTypeTooltip[3]="Target effect to hostile unit";
//~ abilityTargetTypeTooltip[4]="Target effect to any tile";
enumLength = Enum.GetValues(typeof(_EffectAttrType)).Length;
effectAttrTypeLabel=new string[enumLength];
effectAttrTypeTooltip=new string[enumLength];
for(int i=0; i<enumLength; i++) effectAttrTypeLabel[i]=((_EffectAttrType)i).ToString();
//~ for(int i=0; i<enumLength; i++) effectAttrTypeTooltip[i]="";
effectAttrTypeTooltip[0]="Reduce target's HP";
effectAttrTypeTooltip[1]="Restore target's HP";
effectAttrTypeTooltip[2]="Reduce target's AP";
effectAttrTypeTooltip[3]="Restore target's AP";
effectAttrTypeTooltip[4]="Increase/decrease target's damage";
effectAttrTypeTooltip[5]="Increase/decrease target's movement range";
effectAttrTypeTooltip[6]="Increase/decrease target's attack range";
effectAttrTypeTooltip[7]="Increase/decrease target's speed";
effectAttrTypeTooltip[8]="Increase/decrease target's hit chance";
effectAttrTypeTooltip[9]="Increase/decrease target's dodge chance";
effectAttrTypeTooltip[10]="Increase/decrease target's critical chance";
effectAttrTypeTooltip[11]="Increase/decrease target's critical immunity";
effectAttrTypeTooltip[12]="Increase/decrease target's attack per turn";
effectAttrTypeTooltip[13]="Increase/decrease target's counter attack limit ";
effectAttrTypeTooltip[14]="Stun target, stop target from doing anything";
effectAttrTypeTooltip[15]="Prevent target from attack\nTakes binary value: 0-no effect. >0-cannot attack";
effectAttrTypeTooltip[16]="Prevent target from moving\nTakes binary value: 0-no effect. >0-cannot move";
effectAttrTypeTooltip[17]="Prevent target from using ability\nTakes binary value: 0-no effect. >0-cannot use ability";
effectAttrTypeTooltip[18]="Faction gain points\nFor data currency used to purchase unit";
effectAttrTypeTooltip[19]="Teleport to a specified tile";
effectAttrTypeTooltip[20]="Spawn a unit";
effectAttrTypeTooltip[21]="Convert the target unit to the faction of the casting unit";
effectAttrTypeTooltip[22]="Spawn a collectible";
//~ enumLength = Enum.GetValues(typeof(_AbilityEffectType)).Length;
//~ effectTypeLabel=new string[enumLength];
//~ effectTypeLabel[0]="HPGain";
//~ effectTypeLabel[1]="HPDamage";
//~ effectTypeLabel[2]="Damage";
//~ effectTypeLabel[3]="Attack";
//~ effectTypeLabel[4]="Defend";
//~ effectTypeLabel[5]="Critical";
//~ effectTypeLabel[6]="CritDef";
//~ effectTypeLabel[7]="Movement";
//~ effectTypeLabel[8]="ExtraAttack";
//~ effectTypeLabel[9]="Stun";
//~ effectTypeTooltip=new string[enumLength];
//~ effectTypeTooltip[0]="HPGain";
//~ effectTypeTooltip[1]="HPDamage";
//~ effectTypeTooltip[2]="modify damage";
//~ effectTypeTooltip[3]="modify attack";
//~ effectTypeTooltip[4]="modify defend";
//~ effectTypeTooltip[5]="modify critical";
//~ effectTypeTooltip[6]="modify critical immunity";
//~ effectTypeTooltip[7]="modify movement";
//~ effectTypeTooltip[8]="modify attack per turn";
//~ effectTypeTooltip[9]="modify stun";
enumLength = Enum.GetValues(typeof(_AbilityShootMode)).Length;
shootModeLabel=new string[enumLength];
shootModeLabel[0]="None";
shootModeLabel[1]="ShootToCenter";
shootModeLabel[2]="ShootToAll";
shootModeTooltip=new string[enumLength];
shootModeTooltip[0]="No ShootObject will be fire at target tile";
shootModeTooltip[1]="A single shootObject will be fired at the center of all target tile(s)";
shootModeTooltip[2]="shootObjects will be fired to all target tile(s)";
}
public static void Load(){
GameObject obj=Resources.Load("PrefabList/UnitAbilityListPrefab", typeof(GameObject)) as GameObject;
if(obj==null) obj=CreatePrefab();
prefab=obj.GetComponent<UnitAbilityListPrefab>();
if(prefab==null) prefab=obj.AddComponent<UnitAbilityListPrefab>();
allUAbList=prefab.unitAbilityList;
foreach(UnitAbility uAB in allUAbList){
UAbIDList.Add(uAB.ID);
}
}
public static GameObject CreatePrefab(){
GameObject obj=new GameObject();
obj.AddComponent<UnitAbilityListPrefab>();
GameObject prefab=PrefabUtility.CreatePrefab("Assets/TBTK/Resources/PrefabList/UnitAbilityListPrefab.prefab", obj, ReplacePrefabOptions.ConnectToPrefab);
DestroyImmediate(obj);
AssetDatabase.Refresh ();
return prefab;
}
private static void LoadDamageArmor(){
GameObject obj=Resources.Load("PrefabList/DamageArmorList", typeof(GameObject)) as GameObject;
if(obj==null) return;
DamageArmorListPrefab prefab=obj.GetComponent<DamageArmorListPrefab>();
if(prefab==null) prefab=obj.AddComponent<DamageArmorListPrefab>();
armorList=new string[prefab.armorList.Count];
armorTooltipList=new string[prefab.armorList.Count];
damageList=new string[prefab.damageList.Count];
damageTooltipList=new string[prefab.damageList.Count];
for(int i=0; i<prefab.armorList.Count; i++){
armorList[i]=(prefab.armorList[i].name);
armorTooltipList[i]=prefab.armorList[i].desp;
}
for(int i=0; i<prefab.damageList.Count; i++){
damageList[i]=prefab.damageList[i].name;
damageTooltipList[i]=prefab.damageList[i].desp;
}
}
private Vector2 mainScrollPos;
private int deleteID=-1;
private int selectedUAbID=-1;
private int swapID=-1;
private Vector2 scrollPos;
private static UnitAbilityListPrefab prefab;
private static List<UnitAbility> allUAbList=new List<UnitAbility>();
private static List<int> UAbIDList=new List<int>();
//~ GUIContent cont;
private GUIContent cont;
private GUIContent[] contList;
void NewUnitAbilityRoutine(UnitAbility UAb){
UAb.ID=GenerateNewID();
UAbIDList.Add(UAb.ID);
UAb.name="UnitAbility "+allUAbList.Count;
allUAbList.Add(UAb);
selectedUAbID=allUAbList.Count-1;
deleteID=-1;
}
void OnGUI () {
if(window==null) Init();
//if(GUI.Button(new Rect(window.position.width-110, 10, 100, 30), "Save")){
// SaveToXML();
//}
int currentAbilityCount=allUAbList.Count;
cont=new GUIContent("New UnitAbility", "Create a new unit ability");
if(GUI.Button(new Rect(5, 10, 100, 30), cont)){
UnitAbility UAb=new UnitAbility();
NewUnitAbilityRoutine(UAb);
if(onUnitAbilityUpdateE!=null) onUnitAbilityUpdateE();
}
cont=new GUIContent("Clone UnitAbility", "Create a new ability by cloning the current selected unit ability");
if(selectedUAbID>=0 && selectedUAbID<allUAbList.Count){
if(GUI.Button(new Rect(115, 10, 100, 30), cont)){
UnitAbility UAb=allUAbList[selectedUAbID].Clone();
NewUnitAbilityRoutine(UAb);
if(onUnitAbilityUpdateE!=null) onUnitAbilityUpdateE();
}
}
//~ Rect visibleRect=;
//~ Rect contentRect=
GUI.Box(new Rect(5, 50, window.position.width-10, 260), "");
scrollPos = GUI.BeginScrollView(new Rect(5, 55, window.position.width-12, 250), scrollPos, new Rect(5, 50, window.position.width-40, 10+((allUAbList.Count-1)/3)*35));
int row=0;
int column=0;
for(int i=0; i<allUAbList.Count; i++){
GUIStyle style=GUI.skin.label;
style.alignment=TextAnchor.MiddleCenter;
if(swapID==i) GUI.color=new Color(.9f, .9f, .0f, 1);
else GUI.color=new Color(.8f, .8f, .8f, 1);
GUI.Box(new Rect(10+column*210, 50+row*30, 25, 25), "");
if(GUI.Button(new Rect(10+column*210, 50+row*30, 25, 25), "")){
//~ deleteID=-1;
//~ if(swapID==i) swapID=-1;
//~ else if(swapID==-1) swapID=i;
//~ else{
//~ SwapUAbInList(swapID, i);
//~ swapID=-1;
//~ }
}
GUI.Label(new Rect(8+column*210, 50+row*30, 25, 25), allUAbList[i].ID.ToString(), style);
GUI.color=Color.white;
style.alignment=TextAnchor.MiddleLeft;
int ID=allUAbList[i].ID;
if(selectedUAbID>=0 && allUAbList[selectedUAbID].chainedAbilityIDList.Contains(ID)) GUI.color=new Color(0, 1f, 1f, 1f);
else if(selectedUAbID==i) GUI.color = Color.green;
style=GUI.skin.button;
style.fontStyle=FontStyle.Bold;
GUI.SetNextControlName ("AbilityButton");
if(GUI.Button(new Rect(10+27+column*210, 50+row*30, 100, 25), allUAbList[i].name, style)){
GUI.FocusControl ("AbilityButton");
selectedUAbID=i;
deleteID=-1;
}
GUI.color = Color.white;
style.fontStyle=FontStyle.Normal;
if(deleteID!=i){
if(GUI.Button(new Rect(10+27+102+column*210, 50+row*30, 25, 25), "X")){
deleteID=i;
}
}
else{
GUI.color = Color.red;
if(GUI.Button(new Rect(10+27+102+column*210, 50+row*30, 55, 25), "Delete")){
UAbIDList.Remove(allUAbList[i].ID);
allUAbList.RemoveAt(i);
if(i<=selectedUAbID) selectedUAbID-=1;
deleteID=-1;
if(onUnitAbilityUpdateE!=null) onUnitAbilityUpdateE();
}
GUI.color = Color.white;
}
column+=1;
if(column==3){
column=0;
row+=1;
}
}
GUI.EndScrollView();
if(selectedUAbID>-1 && selectedUAbID<allUAbList.Count){
UAbConfigurator();
}
if (GUI.changed || currentAbilityCount!=allUAbList.Count){
prefab.unitAbilityList=allUAbList;
EditorUtility.SetDirty(prefab);
if(onUnitAbilityUpdateE!=null) onUnitAbilityUpdateE();
}
}
void UAbConfigurator(){
Rect displayRect=new Rect(5, 315, window.position.width-5, window.position.height-315);
Rect contentRect=new Rect(5, 315, window.position.width-40, 485);
mainScrollPos = GUI.BeginScrollView(displayRect, mainScrollPos, contentRect);
int startY=315;
int startX=5;
GUIStyle style=new GUIStyle();
style.wordWrap=true;
UnitAbility uAB=allUAbList[selectedUAbID];
//~ GUI.Box(new Rect(startX, startY, 80, 100), "");
cont=new GUIContent("Default Icon:", "The icon for the unit ability");
EditorGUI.LabelField(new Rect(startX, startY, 80, 20), cont);
uAB.icon=(Texture)EditorGUI.ObjectField(new Rect(startX+10, startY+17, 60, 60), uAB.icon, typeof(Texture), false);
startX+=100;
cont=new GUIContent("Unavailable:", "The icon for the unit ability when it's unavailable (on cooldown and etc.)");
EditorGUI.LabelField(new Rect(startX, startY, 80, 34), cont);
uAB.iconUnavailable=(Texture)EditorGUI.ObjectField(new Rect(startX+10, startY+17, 60, 60), uAB.iconUnavailable, typeof(Texture), false);
startX+=80;
if(uAB.icon!=null && uAB.icon.name!=uAB.iconName){
uAB.iconName=uAB.icon.name;
GUI.changed=true;
}
if(uAB.iconUnavailable!=null && uAB.iconUnavailable.name!=uAB.iconUnavailableName){
uAB.iconUnavailableName=uAB.iconUnavailable.name;
GUI.changed=true;
}
startX=5;
startY=390;
cont=new GUIContent("Name:", "The name for the unit ability");
EditorGUI.LabelField(new Rect(startX, startY+=20, 80, 20), "Name: ");
uAB.name=EditorGUI.TextField(new Rect(startX+50, startY-1, 120, 17), uAB.name);
startY+=8;
int type=(int)uAB.effectType;
cont=new GUIContent("EffectType:", "Effect type of the ability. Set to Buff/Debuff type will enable duration setting on the effect. It will also enable buff/debuff indicator on the unit-overlay");
contList=new GUIContent[abilityEffectTypeLabel.Length];
for(int i=0; i<contList.Length; i++) contList[i]=new GUIContent(abilityEffectTypeLabel[i], abilityEffectTypeTooltip[i]);
EditorGUI.LabelField(new Rect(startX, startY+=18, 80, 20), cont);
type = EditorGUI.Popup(new Rect(startX+80, startY, 90, 16), type, contList);
uAB.effectType=(_EffectType)type;
type=(int)uAB.targetType;
cont=new GUIContent("TargetType:", "Target type of the ability");
contList=new GUIContent[abilityTargetTypeLabel.Length];
for(int i=0; i<contList.Length; i++) contList[i]=new GUIContent(abilityTargetTypeLabel[i], abilityTargetTypeTooltip[i]);
EditorGUI.LabelField(new Rect(startX, startY+=18, 80, 20), cont);
type = EditorGUI.Popup(new Rect(startX+80, startY, 90, 16), type, contList);
uAB.targetType=(_AbilityTargetType)type;
startY+=8;
//~ if(uAB.targetType!=_AbilityTargetType.Self && uAB.targetType!=_AbilityTargetType.SelfTile){
cont=new GUIContent("RequireTargetSelect:", "Check if a target is required for the ability, else the ability will be casted on the unit tile");
EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont);
uAB.requireTargetSelection=EditorGUI.Toggle(new Rect(startX+155, startY-1, 20, 17), uAB.requireTargetSelection);
if(uAB.requireTargetSelection){
int areaType=(int)uAB.targetArea;
cont=new GUIContent("TargetArea:", "Target area of the ability");
contList=new GUIContent[abilityTargetAreaLabel.Length];
for(int i=0; i<contList.Length; i++) contList[i]=new GUIContent(abilityTargetAreaLabel[i], abilityTargetAreaTooltip[i]);
EditorGUI.LabelField(new Rect(startX, startY+=18, 80, 20), cont);
areaType = EditorGUI.Popup(new Rect(startX+80, startY, 90, 16), areaType, contList);
uAB.targetArea=(_TargetArea)areaType;
cont=new GUIContent("Range:", "Effective range of the ability in term of tile");
EditorGUI.LabelField(new Rect(startX, startY+=18, 80, 20), cont);
uAB.range=EditorGUI.IntField(new Rect(startX+120, startY-1, 50, 16), uAB.range);
uAB.range=Math.Max(1, uAB.range);
}
//cont=new GUIContent("enableAOE:", "");
//EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont);
//uAB.enableAOE=EditorGUI.Toggle(new Rect(startX+155, startY-1, 20, 17), uAB.enableAOE);
//if target hostile and no target selection, ability must have aoe capability otherwise it doesnt do anything
//if(uAB.targetType==_AbilityTargetType.Hostile && !uAB.requireTargetSelection) uAB.enableAOE=true;
//if(uAB.enableAOE){
if(!uAB.requireTargetSelection || uAB.targetArea==_TargetArea.Default){
cont=new GUIContent("aoeRange:", "Effective aoe range of the ability in term of tile");
EditorGUI.LabelField(new Rect(startX, startY+=18, 80, 20), cont);
uAB.aoeRange=EditorGUI.IntField(new Rect(startX+120, startY-1, 50, 16), uAB.aoeRange);
if(uAB.requireTargetSelection) uAB.aoeRange=Math.Max(0, uAB.aoeRange);
else uAB.aoeRange=Math.Max(0, uAB.aoeRange);
}
//~ int aoeType=(int)uAB.aoe;
//~ cont=new GUIContent("AOE Mode:", "Switch between different AOE options");
//~ contList=new GUIContent[aoeTypeLabel.Length];
//~ for(int i=0; i<contList.Length; i++) contList[i]=new GUIContent(aoeTypeLabel[i], aoeTypeTooltip[i]);
//~ EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont);
//~ aoeType = EditorGUI.Popup(new Rect(startX+70, startY, 100, 16), aoeType, contList);
//~ uAB.aoe=(_AOETypeHex)aoeType;
//~ }
//~ cont=new GUIContent("Duration:", "Effective duration of the ability in term of round");
//~ EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont);
//~ uAB.duration=EditorGUI.IntField(new Rect(startX+120, startY-1, 50, 16), uAB.duration);
startY+=8;
uAB.totalCost=uAB.cost;
for(int i=0; i<uAB.chainedAbilityIDList.Count; i++){
for(int n=0; n<allUAbList.Count; n++){
if(allUAbList[n].ID==uAB.chainedAbilityIDList[i]){
uAB.totalCost+=allUAbList[n].cost;
}
}
}
cont=new GUIContent("AP Cost:", "The AP cost to use this unit ability\nvalue in bracket being the total cost required (taking acount of the chained abilities)");
EditorGUI.LabelField(new Rect(startX, startY+=18, 80, 20), cont);
EditorGUI.LabelField(new Rect(startX+90, startY, 50, 20), "("+uAB.totalCost+")");
uAB.cost=EditorGUI.IntField(new Rect(startX+120, startY-1, 50, 16), uAB.cost);
cont=new GUIContent("Cooldown:", "The cooldown (in round) required before the unit ability become available again after each use");
EditorGUI.LabelField(new Rect(startX, startY+=18, 80, 20), cont);
uAB.cdDuration=EditorGUI.IntField(new Rect(startX+120, startY-1, 50, 16), uAB.cdDuration);
cont=new GUIContent("Limit:", "The maximum amount of time the ability can be use in the game (set to -1 for infinite use)");
EditorGUI.LabelField(new Rect(startX, startY+=18, 80, 20), cont);
uAB.useLimit=EditorGUI.IntField(new Rect(startX+120, startY-1, 50, 16), uAB.useLimit);
cont=new GUIContent("enableMovementAfter:", "check to allow unit to move after using the ability (only if unit hasnt moved already)");
EditorGUI.LabelField(new Rect(startX, startY+=18, 140, 20), cont);
uAB.enableMovementAfter=EditorGUI.Toggle(new Rect(startX+155, startY-1, 20, 17), uAB.enableMovementAfter);
cont=new GUIContent("enableAttackAfter:", "check to allow unit to attack after using the ability (only if unit hasnt attacked already)");
EditorGUI.LabelField(new Rect(startX, startY+=18, 140, 20), cont);
uAB.enableAttackAfter=EditorGUI.Toggle(new Rect(startX+155, startY-1, 20, 17), uAB.enableAttackAfter);
startY+=8;
cont=new GUIContent("Can Fail:", "Check if the ability can fail to activate\nwhen enabled, takes value from 0-1");
EditorGUI.LabelField(new Rect(startX, startY+=18, 80, 20), cont);
uAB.canFail=EditorGUI.Toggle(new Rect(startX+100, startY-1, 15, 16), uAB.canFail);
if(uAB.canFail) uAB.failChance=EditorGUI.FloatField(new Rect(startX+120, startY-1, 50, 16), uAB.failChance);
cont=new GUIContent("Can Miss:", "Check if the ability can miss it's target\nwhen enabled, takes value from 0-1");
EditorGUI.LabelField(new Rect(startX, startY+=18, 80, 20), cont);
uAB.canMiss=EditorGUI.Toggle(new Rect(startX+100, startY-1, 15, 16), uAB.canMiss);
if(uAB.canMiss) uAB.missChance=EditorGUI.FloatField(new Rect(startX+120, startY-1, 50, 16), uAB.missChance);
if(uAB.canMiss){
cont=new GUIContent(" - Stack with dodge :", "Check to stack the ability miss chance with target's dodge chance");
EditorGUI.LabelField(new Rect(startX, startY+=16, 156, 20), cont);
uAB.stackMissWithDodge=EditorGUI.Toggle(new Rect(startX+157, startY-1, 50, 16), uAB.stackMissWithDodge);
}
startY=320;
startX=205;
//~ EditorGUI.LabelField(new Rect(startX, startY, 200, 20), "AbilityEffect:");
if(GUI.Button(new Rect(startX, startY, 100, 20), "Add Effect")){
if(uAB.effectAttrs.Count<3){
uAB.effectAttrs.Add(new EffectAttr());
}
}
cont=new GUIContent("Delay:", "The delay in second before the effects take place (only applicable when the ability doesnt use a shoot mechanism)");
EditorGUI.LabelField(new Rect(startX+135, startY, 200, 20), cont);
uAB.effectUseDelay=EditorGUI.FloatField(new Rect(startX+180, startY-1, 50, 16), uAB.effectUseDelay);
startY+=7;
for(int i=0; i<uAB.effectAttrs.Count; i++){
EffectAttrConfigurator(uAB, i, startX, startY);
startX+=135;
}
startY+=155;
startX=205;
cont=new GUIContent("Effect Self:", "The prefab intend as visual effect to spawn on the unit using the ability everytime the ability is used");
EditorGUI.LabelField(new Rect(startX, startY, 200, 20), cont);
uAB.effectUse=(GameObject)EditorGUI.ObjectField(new Rect(startX+80, startY-1, 90, 17), uAB.effectUse, typeof(GameObject), false);
cont=new GUIContent(" - Delay:", "The delay in second before the visual effect is spawned");
EditorGUI.LabelField(new Rect(startX+170, startY, 200, 20), cont);
uAB.effectUseDelay=EditorGUI.FloatField(new Rect(startX+235, startY-1, 50, 16), uAB.effectUseDelay);
cont=new GUIContent("Effect Target:", "The prefab intend as visual effect to spawn on the unit using the ability everytime the ability is used");
EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont);
uAB.effectTarget=(GameObject)EditorGUI.ObjectField(new Rect(startX+80, startY-1, 90, 17), uAB.effectTarget, typeof(GameObject), false);
cont=new GUIContent(" - Delay:", "The delay in second before the target visual effect is spawned");
EditorGUI.LabelField(new Rect(startX+170, startY, 200, 20), cont);
uAB.effectTargetDelay=EditorGUI.FloatField(new Rect(startX+235, startY-1, 50, 16), uAB.effectTargetDelay);
startY+=15;
if(uAB.requireTargetSelection){
int shootMode=(int)uAB.shootMode;
cont=new GUIContent("ShootMode:", "Shoot object setting for the ability if applicable");
contList=new GUIContent[shootModeLabel.Length];
for(int i=0; i<contList.Length; i++) contList[i]=new GUIContent(shootModeLabel[i], shootModeTooltip[i]);
EditorGUI.LabelField(new Rect(startX, startY+=18, 180, 20), cont);
shootMode = EditorGUI.Popup(new Rect(startX+80, startY, 100, 16), shootMode, contList);
uAB.shootMode=(_AbilityShootMode)shootMode;
if(shootMode!=0){
cont=new GUIContent("ShootObject:", "The shootObject prefab to be used");
EditorGUI.LabelField(new Rect(startX, startY+=18, 180, 20), cont);
uAB.shootObject=(GameObject)EditorGUI.ObjectField(new Rect(startX+80, startY-1, 100, 17), uAB.shootObject, typeof(GameObject), false);
}
else startY+=18;
}
else{
cont=new GUIContent("ShootMode: None", "Shoot object setting for the ability if applicable");
EditorGUI.LabelField(new Rect(startX, startY+=18, 180, 20), cont);
startY+=18;
}
//startY+=10;
startX+=210;
startY-=36;
cont=new GUIContent("Sound Use:", "The sound to play when the ability is used");
EditorGUI.LabelField(new Rect(startX, startY+=18, 180, 20), cont);
uAB.soundUse=(AudioClip)EditorGUI.ObjectField(new Rect(startX+80, startY-1, 100, 17), uAB.soundUse, typeof(AudioClip), false);
cont=new GUIContent("Sound Hit:", "The sound to play on the target when the ability hit it's target");
EditorGUI.LabelField(new Rect(startX, startY+=18, 180, 20), cont);
uAB.soundHit=(AudioClip)EditorGUI.ObjectField(new Rect(startX+80, startY-1, 100, 17), uAB.soundHit, typeof(AudioClip), false);
startX-=210;
startY+=10;
cont=new GUIContent("Chained-Ability:", "The ability that will be used along with the current one");
EditorGUI.LabelField(new Rect(startX, startY+=18, 150, 20), cont);
//~ EditorGUI.LabelField(new Rect(startX, startY, 200, 20), cont);
string label="Expand";
if(expandChainedAbilityPanel) label="Minimise";
if(GUI.Button(new Rect(startX+98, startY, 70, 17), label)){
expandChainedAbilityPanel=!expandChainedAbilityPanel;
}
startY+=20;
int count=0;
if(!expandChainedAbilityPanel){
foreach(int abID in uAB.chainedAbilityIDList){
foreach(UnitAbility unitAB in allUAbList){
if(unitAB.ID==abID){
GUI.Box(new Rect(startX+count*60, startY, 50, 50), "");
cont=new GUIContent(unitAB.icon, unitAB.name+" - "+unitAB.desp);
EditorGUI.LabelField(new Rect(startX+count*60+3, startY+4, 44, 44), cont);
count+=1;
}
}
}
startY+=65;
}
else{
Rect abilityBoxRect=new Rect(startX, startY, 390, 130);
Rect abilityBoxcontentRect=new Rect(startX-2, startY-2, 390-20, Mathf.Ceil((allUAbList.Count/6)+1)*60);
GUI.Box(abilityBoxRect, "");
scrollPosAbilBox = GUI.BeginScrollView(abilityBoxRect, scrollPosAbilBox, abilityBoxcontentRect);
float startXX=startX+8;
float startYY=startY+8;
foreach(UnitAbility unitAB in allUAbList){
if(uAB.chainedAbilityIDList.Contains(unitAB.ID)) GUI.color=Color.green;
GUI.Box(new Rect(startXX+count*60, startYY, 50, 50), "");
GUI.color=Color.white;
if(uAB.ID==unitAB.ID){
cont=new GUIContent(unitAB.iconUnavailable, unitAB.name+" - "+unitAB.desp);
GUI.Label(new Rect(startXX+count*60+4, startYY+4, 42, 42), cont);
}
else{
cont=new GUIContent(unitAB.icon, unitAB.name+" - "+unitAB.desp);
if(GUI.Button(new Rect(startXX+count*60+4, startYY+4, 42, 42), cont)){
if(!uAB.chainedAbilityIDList.Contains(unitAB.ID)){
if(uAB.chainedAbilityIDList.Count<6){
uAB.chainedAbilityIDList.Add(unitAB.ID);
}
else Debug.Log("cannot have more than 6 chained-abilities");
}
else uAB.chainedAbilityIDList.Remove(unitAB.ID);
}
}
count+=1;
if(count%6==0){
startXX-=6*60;
startYY+=60;
}
}
GUI.EndScrollView();
startY+=220;
}
startX=5;
//startY=Mathf.Max((int)window.position.height-75, startY);
startY=725;
EditorGUI.LabelField(new Rect(startX, startY, 300, 25), "Description for runtime UI: ");
uAB.desp=EditorGUI.TextArea(new Rect(startX, startY+17, window.position.width-10, 50), uAB.desp);
GUI.EndScrollView();
}
private bool expandChainedAbilityPanel=false;
private Vector2 scrollPosAbilBox;
void EffectAttrConfigurator(UnitAbility uAB, int ID, int startX, int startY){
EffectAttr effectAttr=uAB.effectAttrs[ID];
if(GUI.Button(new Rect(startX, startY+=18, 70, 14), "Remove")){
uAB.effectAttrs.Remove(effectAttr);
return;
}
int type=(int)effectAttr.type;
cont=new GUIContent("Type:", "Type of the effect.");
contList=new GUIContent[effectAttrTypeLabel.Length];
for(int i=0; i<contList.Length; i++) contList[i]=new GUIContent(effectAttrTypeLabel[i], effectAttrTypeTooltip[i]);
EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont);
type = EditorGUI.Popup(new Rect(startX+40, startY, 80, 16), type, contList);
effectAttr.type=(_EffectAttrType)type;
if(effectAttr.type==_EffectAttrType.Teleport){
uAB.targetType=_AbilityTargetType.EmptyTile;
uAB.requireTargetSelection=true;
uAB.targetArea=_TargetArea.Default;
uAB.aoeRange=0;
}
else if(effectAttr.type==_EffectAttrType.SpawnUnit || effectAttr.type==_EffectAttrType.SpawnCollectible){
if(effectAttr.type==_EffectAttrType.SpawnUnit){
cont=new GUIContent("Unit To Spawn:", "The unit prefab to be used spawned");
EditorGUI.LabelField(new Rect(startX, startY+=18, 180, 20), cont);
effectAttr.unit=(UnitTB)EditorGUI.ObjectField(new Rect(startX, startY+=18, 125, 17), effectAttr.unit, typeof(UnitTB), false);
cont=new GUIContent("Duration:", "The effective duration in which the spawned unit will last\nSet to -ve value for the spawn to be permenant" );
EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont);
effectAttr.duration=EditorGUI.IntField(new Rect(startX+70, startY-1, 50, 16), effectAttr.duration);
if(effectAttr.duration==0) effectAttr.duration=-1;
}
else if(effectAttr.type==_EffectAttrType.SpawnCollectible){
cont=new GUIContent("Collectible To Spawn:", "The collectible prefab to be used spawned");
EditorGUI.LabelField(new Rect(startX, startY+=18, 180, 20), cont);
effectAttr.collectible=(CollectibleTB)EditorGUI.ObjectField(new Rect(startX, startY+=18, 125, 17), effectAttr.collectible, typeof(CollectibleTB), false);
}
uAB.targetType=_AbilityTargetType.EmptyTile;
uAB.requireTargetSelection=true;
uAB.targetArea=_TargetArea.Default;
uAB.aoeRange=0;
}
else if(effectAttr.type==_EffectAttrType.ChangeTargetFaction){
cont=new GUIContent("Chance:", "The chance of success. Take value from 0 to 1");
EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont);
effectAttr.value=EditorGUI.FloatField(new Rect(startX+70, startY-1, 50, 16), effectAttr.value);
//~ cont=new GUIContent("Duration:", "The effective duration of the faction change");
//~ EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont);
//~ effectAttr.duration=EditorGUI.IntField(new Rect(startX+70, startY-1, 50, 16), effectAttr.duration);
uAB.targetType=_AbilityTargetType.Hostile;
uAB.requireTargetSelection=true;
uAB.targetArea=_TargetArea.Default;
uAB.aoeRange=0;
}
else if(effectAttr.type==_EffectAttrType.HPDamage){
cont=new GUIContent("UseDefaultValue:", "Check to use the unit default attack damage value");
EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont);
effectAttr.useDefaultDamageValue=EditorGUI.Toggle(new Rect(startX+107, startY-1, 50, 16), effectAttr.useDefaultDamageValue);
if(!effectAttr.useDefaultDamageValue){
cont=new GUIContent("ValueMin:", "Minimum value for the effect");
EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont);
effectAttr.value=EditorGUI.FloatField(new Rect(startX+70, startY-1, 50, 16), effectAttr.value);
cont=new GUIContent("ValueMax:", "Maximum value for the effect");
EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont);
effectAttr.valueAlt=EditorGUI.FloatField(new Rect(startX+70, startY-1, 50, 16), effectAttr.valueAlt);
}
}
else if(effectAttr.type==_EffectAttrType.HPGain || effectAttr.type==_EffectAttrType.APGain || effectAttr.type==_EffectAttrType.APDamage){
cont=new GUIContent("ValueMin:", "Minimum value for the effect");
EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont);
effectAttr.value=EditorGUI.FloatField(new Rect(startX+70, startY-1, 50, 16), effectAttr.value);
effectAttr.value=Mathf.Min(effectAttr.value, effectAttr.valueAlt);
cont=new GUIContent("ValueMax:", "Maximum value for the effect");
EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont);
effectAttr.valueAlt=EditorGUI.FloatField(new Rect(startX+70, startY-1, 50, 16), effectAttr.valueAlt);
effectAttr.valueAlt=Mathf.Max(effectAttr.value, effectAttr.valueAlt);
}
else{
cont=new GUIContent("Value:", "Value for the effect");
EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont);
effectAttr.value=EditorGUI.FloatField(new Rect(startX+70, startY-1, 50, 16), effectAttr.value);
}
//~ if(type==1){
//~ cont=new GUIContent("Range:", "Effective range of the ability in term of tile");
//~ EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), "use Default Damage:");
//~ effect.useDefaultDamageValue=EditorGUI.Toggle(new Rect(startX+120, startY-1, 50, 16), effect.useDefaultDamageValue);
//~ }
//~ if(type!=2 || !effectAttr.useDefaultDamageValue){
//~ cont=new GUIContent("Range:", "Effective range of the ability in term of tile");
//~ EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), "value:");
//~ effectAttr.value=EditorGUI.FloatField(new Rect(startX+70, startY-1, 50, 16), effectAttr.value);
//~ }
if(uAB.effectType==_EffectType.Debuff || uAB.effectType==_EffectType.Buff){
if(effectAttr.type!=_EffectAttrType.SpawnUnit){
cont=new GUIContent("Duration:", "Effective duration of the effect in term of round");
EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont);
effectAttr.duration=EditorGUI.IntField(new Rect(startX+70, startY-1, 50, 16), effectAttr.duration);
}
}
//~ int type=(int)effectAttr.type;
//~ cont=new GUIContent("Type:", "Type of the effect");
//~ contList=new GUIContent[effectAttrTypeLabel.Length];
//~ for(int i=0; i<contList.Length; i++) contList[i]=new GUIContent(effectAttrTypeLabel[i], effectAttrTypeTooltip[i]);
//~ EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont);
//~ type = EditorGUI.Popup(new Rect(startX+40, startY, 80, 16), type, contList);
//~ effectAttr.type=(_EffectAttrType)type;
if(effectAttr.type==_EffectAttrType.HPDamage){
if(damageList.Length>0){
contList=new GUIContent[damageTooltipList.Length];
for(int i=0; i<contList.Length; i++) contList[i]=new GUIContent(damageList[i], damageTooltipList[i]);
cont=new GUIContent("Type:", "Damage type to be inflicted on target");
EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont);
effectAttr.damageType = EditorGUI.Popup(new Rect(startX+40, startY, 80, 16), effectAttr.damageType, contList);
}
else{
cont=new GUIContent("Type:", "No damage type has been created, use DamageArmorTableEditor to create one");
EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont);
if(GUI.Button(new Rect(startX+40, startY, 80, 15), "OpenEditor")){
DamageArmorTableEditor.Init();
}
}
}
}
int GenerateNewID(){
int newID=0;
while(UAbIDList.Contains(newID)) newID+=1;
return newID;
}
static void SwapUAbInList(int ID1, int ID2){
UnitAbility temp=allUAbList[ID1].Clone();
allUAbList[ID1]=allUAbList[ID2].Clone();
allUAbList[ID2]=temp.Clone();
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureReport
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Test Infrastructure for AutoRest
/// </summary>
public partial class AutoRestReportServiceForAzure : ServiceClient<AutoRestReportServiceForAzure>, IAutoRestReportServiceForAzure, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Initializes a new instance of the AutoRestReportServiceForAzure class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestReportServiceForAzure(params DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestReportServiceForAzure class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestReportServiceForAzure(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestReportServiceForAzure class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutoRestReportServiceForAzure(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestReportServiceForAzure class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutoRestReportServiceForAzure(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestReportServiceForAzure class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestReportServiceForAzure(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestReportServiceForAzure class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestReportServiceForAzure(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestReportServiceForAzure class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestReportServiceForAzure(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestReportServiceForAzure class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestReportServiceForAzure(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.BaseUri = new Uri("http://localhost");
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
/// <summary>
/// Get test coverage report
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IDictionary<string, int?>>> GetReportWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetReport", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "report/azure").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IDictionary<string, int?>>();
_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 = SafeJsonConvert.DeserializeObject<IDictionary<string, int?>>(_responseContent, this.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 file="XmlQueryStaticData.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Xml.Xsl.IlGen;
using System.Xml.Xsl.Qil;
namespace System.Xml.Xsl.Runtime {
/// <summary>
/// Contains all static data that is used by the runtime.
/// </summary>
internal class XmlQueryStaticData {
// Name of the field to serialize to
public const string DataFieldName = "staticData";
public const string TypesFieldName = "ebTypes";
// Format version marker to support versioning: (major << 8) | minor
private const int CurrentFormatVersion = (0 << 8) | 0;
private XmlWriterSettings defaultWriterSettings;
private IList<WhitespaceRule> whitespaceRules;
private string[] names;
private StringPair[][] prefixMappingsList;
private Int32Pair[] filters;
private XmlQueryType[] types;
private XmlCollation[] collations;
private string[] globalNames;
private EarlyBoundInfo[] earlyBound;
/// <summary>
/// Constructor.
/// </summary>
public XmlQueryStaticData(XmlWriterSettings defaultWriterSettings, IList<WhitespaceRule> whitespaceRules, StaticDataManager staticData) {
Debug.Assert(defaultWriterSettings != null && staticData != null);
this.defaultWriterSettings = defaultWriterSettings;
this.whitespaceRules = whitespaceRules;
this.names = staticData.Names;
this.prefixMappingsList = staticData.PrefixMappingsList;
this.filters = staticData.NameFilters;
this.types = staticData.XmlTypes;
this.collations = staticData.Collations;
this.globalNames = staticData.GlobalNames;
this.earlyBound = staticData.EarlyBound;
#if DEBUG
// Round-trip check
byte[] data;
Type[] ebTypes;
this.GetObjectData(out data, out ebTypes);
XmlQueryStaticData copy = new XmlQueryStaticData(data, ebTypes);
this.defaultWriterSettings = copy.defaultWriterSettings;
this.whitespaceRules = copy.whitespaceRules;
this.names = copy.names;
this.prefixMappingsList = copy.prefixMappingsList;
this.filters = copy.filters;
this.types = copy.types;
this.collations = copy.collations;
this.globalNames = copy.globalNames;
this.earlyBound = copy.earlyBound;
#endif
}
/// <summary>
/// Deserialize XmlQueryStaticData object from a byte array.
/// </summary>
public XmlQueryStaticData(byte[] data, Type[] ebTypes) {
MemoryStream dataStream = new MemoryStream(data, /*writable:*/false);
XmlQueryDataReader dataReader = new XmlQueryDataReader(dataStream);
int length;
// Read a format version
int formatVersion = dataReader.ReadInt32Encoded();
// Changes in the major part of version are not supported
if ((formatVersion & ~0xff) > CurrentFormatVersion)
throw new NotSupportedException();
// XmlWriterSettings defaultWriterSettings;
defaultWriterSettings = new XmlWriterSettings(dataReader);
// IList<WhitespaceRule> whitespaceRules;
length = dataReader.ReadInt32();
if (length != 0) {
this.whitespaceRules = new WhitespaceRule[length];
for (int idx = 0; idx < length; idx++) {
this.whitespaceRules[idx] = new WhitespaceRule(dataReader);
}
}
// string[] names;
length = dataReader.ReadInt32();
if (length != 0) {
this.names = new string[length];
for (int idx = 0; idx < length; idx++) {
this.names[idx] = dataReader.ReadString();
}
}
// StringPair[][] prefixMappingsList;
length = dataReader.ReadInt32();
if (length != 0) {
this.prefixMappingsList = new StringPair[length][];
for (int idx = 0; idx < length; idx++) {
int length2 = dataReader.ReadInt32();
this.prefixMappingsList[idx] = new StringPair[length2];
for (int idx2 = 0; idx2 < length2; idx2++) {
this.prefixMappingsList[idx][idx2] = new StringPair(dataReader.ReadString(), dataReader.ReadString());
}
}
}
// Int32Pair[] filters;
length = dataReader.ReadInt32();
if (length != 0) {
this.filters = new Int32Pair[length];
for (int idx = 0; idx < length; idx++) {
this.filters[idx] = new Int32Pair(dataReader.ReadInt32Encoded(), dataReader.ReadInt32Encoded());
}
}
// XmlQueryType[] types;
length = dataReader.ReadInt32();
if (length != 0) {
this.types = new XmlQueryType[length];
for (int idx = 0; idx < length; idx++) {
this.types[idx] = XmlQueryTypeFactory.Deserialize(dataReader);
}
}
// XmlCollation[] collations;
length = dataReader.ReadInt32();
if (length != 0) {
this.collations = new XmlCollation[length];
for (int idx = 0; idx < length; idx++) {
this.collations[idx] = new XmlCollation(dataReader);
}
}
// string[] globalNames;
length = dataReader.ReadInt32();
if (length != 0) {
this.globalNames = new string[length];
for (int idx = 0; idx < length; idx++) {
this.globalNames[idx] = dataReader.ReadString();
}
}
// EarlyBoundInfo[] earlyBound;
length = dataReader.ReadInt32();
if (length != 0) {
this.earlyBound = new EarlyBoundInfo[length];
for (int idx = 0; idx < length; idx++) {
this.earlyBound[idx] = new EarlyBoundInfo(dataReader.ReadString(), ebTypes[idx]);
}
}
Debug.Assert(formatVersion != CurrentFormatVersion || dataReader.Read() == -1, "Extra data at the end of the stream");
dataReader.Close();
}
/// <summary>
/// Serialize XmlQueryStaticData object into a byte array.
/// </summary>
public void GetObjectData(out byte[] data, out Type[] ebTypes) {
MemoryStream dataStream = new MemoryStream(4096);
XmlQueryDataWriter dataWriter = new XmlQueryDataWriter(dataStream);
// First put the format version
dataWriter.WriteInt32Encoded(CurrentFormatVersion);
// XmlWriterSettings defaultWriterSettings;
defaultWriterSettings.GetObjectData(dataWriter);
// IList<WhitespaceRule> whitespaceRules;
if (this.whitespaceRules == null) {
dataWriter.Write(0);
}
else {
dataWriter.Write(this.whitespaceRules.Count);
foreach (WhitespaceRule rule in this.whitespaceRules) {
rule.GetObjectData(dataWriter);
}
}
// string[] names;
if (this.names == null) {
dataWriter.Write(0);
}
else {
dataWriter.Write(this.names.Length);
foreach (string name in this.names) {
dataWriter.Write(name);
}
}
// StringPair[][] prefixMappingsList;
if (this.prefixMappingsList == null) {
dataWriter.Write(0);
}
else {
dataWriter.Write(this.prefixMappingsList.Length);
foreach (StringPair[] mappings in this.prefixMappingsList) {
dataWriter.Write(mappings.Length);
foreach (StringPair mapping in mappings) {
dataWriter.Write(mapping.Left);
dataWriter.Write(mapping.Right);
}
}
}
// Int32Pair[] filters;
if (this.filters == null) {
dataWriter.Write(0);
}
else {
dataWriter.Write(this.filters.Length);
foreach (Int32Pair filter in this.filters) {
dataWriter.WriteInt32Encoded(filter.Left);
dataWriter.WriteInt32Encoded(filter.Right);
}
}
// XmlQueryType[] types;
if (this.types == null) {
dataWriter.Write(0);
}
else {
dataWriter.Write(this.types.Length);
foreach (XmlQueryType type in this.types) {
XmlQueryTypeFactory.Serialize(dataWriter, type);
}
}
// XmlCollation[] collations;
if (collations == null) {
dataWriter.Write(0);
}
else {
dataWriter.Write(this.collations.Length);
foreach (XmlCollation collation in this.collations) {
collation.GetObjectData(dataWriter);
}
}
// string[] globalNames;
if (this.globalNames == null) {
dataWriter.Write(0);
}
else {
dataWriter.Write(this.globalNames.Length);
foreach (string name in this.globalNames) {
dataWriter.Write(name);
}
}
// EarlyBoundInfo[] earlyBound;
if (this.earlyBound == null) {
dataWriter.Write(0);
ebTypes = null;
}
else {
dataWriter.Write(this.earlyBound.Length);
ebTypes = new Type[this.earlyBound.Length];
int idx = 0;
foreach (EarlyBoundInfo info in this.earlyBound) {
dataWriter.Write(info.NamespaceUri);
ebTypes[idx++] = info.EarlyBoundType;
}
}
dataWriter.Close();
data = dataStream.ToArray();
}
/// <summary>
/// Return the default writer settings.
/// </summary>
public XmlWriterSettings DefaultWriterSettings {
get { return this.defaultWriterSettings; }
}
/// <summary>
/// Return the rules used for whitespace stripping/preservation.
/// </summary>
public IList<WhitespaceRule> WhitespaceRules {
get { return this.whitespaceRules; }
}
/// <summary>
/// Return array of names used by this query.
/// </summary>
public string[] Names {
get { return this.names; }
}
/// <summary>
/// Return array of prefix mappings used by this query.
/// </summary>
public StringPair[][] PrefixMappingsList {
get { return this.prefixMappingsList; }
}
/// <summary>
/// Return array of name filter specifications used by this query.
/// </summary>
public Int32Pair[] Filters {
get { return this.filters; }
}
/// <summary>
/// Return array of types used by this query.
/// </summary>
public XmlQueryType[] Types {
get { return this.types; }
}
/// <summary>
/// Return array of collations used by this query.
/// </summary>
public XmlCollation[] Collations {
get { return this.collations; }
}
/// <summary>
/// Return names of all global variables and parameters used by this query.
/// </summary>
public string[] GlobalNames {
get { return this.globalNames; }
}
/// <summary>
/// Return array of early bound object information related to this query.
/// </summary>
public EarlyBoundInfo[] EarlyBound {
get { return this.earlyBound; }
}
}
/// <summary>
/// Subclass of BinaryReader used to serialize query static data.
/// </summary>
internal class XmlQueryDataReader : BinaryReader {
public XmlQueryDataReader(Stream input) : base(input) { }
/// <summary>
/// Read in a 32-bit integer in compressed format.
/// </summary>
public int ReadInt32Encoded() {
return Read7BitEncodedInt();
}
/// <summary>
/// Read a string value from the stream. Value can be null.
/// </summary>
public string ReadStringQ() {
return ReadBoolean() ? ReadString() : null;
}
/// <summary>
/// Read a signed byte value from the stream and check if it belongs to the given diapason.
/// </summary>
public sbyte ReadSByte(sbyte minValue, sbyte maxValue) {
sbyte value = ReadSByte();
if (value < minValue)
throw new ArgumentOutOfRangeException("minValue");
if (maxValue < value)
throw new ArgumentOutOfRangeException("maxValue");
return value;
}
}
/// <summary>
/// Subclass of BinaryWriter used to deserialize query static data.
/// </summary>
internal class XmlQueryDataWriter : BinaryWriter {
public XmlQueryDataWriter(Stream output) : base(output) { }
/// <summary>
/// Write a 32-bit integer in a compressed format.
/// </summary>
public void WriteInt32Encoded(int value) {
Write7BitEncodedInt(value);
}
/// <summary>
/// Write a string value to the stream. Value can be null.
/// </summary>
public void WriteStringQ(string value) {
Write(value != null);
if (value != null) {
Write(value);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace AutoMapper
{
/// <summary>
/// Mapping configuration options for non-generic maps
/// </summary>
public interface IMappingExpression
{
/// <summary>
/// Preserve object identity. Useful for circular references.
/// </summary>
/// <returns></returns>
IMappingExpression PreserveReferences();
/// <summary>
/// Customize configuration for individual constructor parameter
/// </summary>
/// <param name="ctorParamName">Constructor parameter name</param>
/// <param name="paramOptions">Options</param>
/// <returns>Itself</returns>
IMappingExpression ForCtorParam(string ctorParamName, Action<ICtorParamConfigurationExpression<object>> paramOptions);
/// <summary>
/// Create a type mapping from the destination to the source type, using the destination members as validation.
/// </summary>
/// <returns>Itself</returns>
IMappingExpression ReverseMap();
/// <summary>
/// Replace the original runtime instance with a new source instance. Useful when ORMs return proxy types with no relationships to runtime types.
/// The returned source object will be mapped instead of what was supplied in the original source object.
/// </summary>
/// <param name="substituteFunc">Substitution function</param>
/// <returns>New source object to map.</returns>
IMappingExpression Substitute(Func<object, object> substituteFunc);
/// <summary>
/// Construct the destination object using the service locator
/// </summary>
/// <returns>Itself</returns>
IMappingExpression ConstructUsingServiceLocator();
/// <summary>
/// For self-referential types, limit recurse depth.
/// Enables PreserveReferences.
/// </summary>
/// <param name="depth">Number of levels to limit to</param>
/// <returns>Itself</returns>
IMappingExpression MaxDepth(int depth);
/// <summary>
/// Supply a custom instantiation expression for the destination type for LINQ projection
/// </summary>
/// <param name="ctor">Callback to create the destination type given the source object</param>
/// <returns>Itself</returns>
IMappingExpression ConstructProjectionUsing(LambdaExpression ctor);
/// <summary>
/// Supply a custom instantiation function for the destination type, based on the entire resolution context
/// </summary>
/// <param name="ctor">Callback to create the destination type given the source object and current resolution context</param>
/// <returns>Itself</returns>
IMappingExpression ConstructUsing(Func<object, ResolutionContext, object> ctor);
/// <summary>
/// Supply a custom instantiation function for the destination type
/// </summary>
/// <param name="ctor">Callback to create the destination type given the source object</param>
/// <returns>Itself</returns>
IMappingExpression ConstructUsing(Func<object, object> ctor);
/// <summary>
/// Skip member mapping and use a custom expression during LINQ projection
/// </summary>
/// <param name="projectionExpression">Projection expression</param>
void ProjectUsing(Expression<Func<object, object>> projectionExpression);
/// <summary>
/// Customize configuration for all members
/// </summary>
/// <param name="memberOptions">Callback for member options</param>
void ForAllMembers(Action<IMemberConfigurationExpression> memberOptions);
/// <summary>
/// Customize configuration for members not previously configured
/// </summary>
/// <param name="memberOptions">Callback for member options</param>
void ForAllOtherMembers(Action<IMemberConfigurationExpression> memberOptions);
/// <summary>
/// Customize configuration for an individual source member
/// </summary>
/// <param name="sourceMemberName">Source member name</param>
/// <param name="memberOptions">Callback for member configuration options</param>
/// <returns>Itself</returns>
IMappingExpression ForSourceMember(string sourceMemberName, Action<ISourceMemberConfigurationExpression> memberOptions);
/// <summary>
/// Skip normal member mapping and convert using a <see cref="ITypeConverter{TSource,TDestination}"/> instantiated during mapping
/// </summary>
/// <typeparam name="TTypeConverter">Type converter type</typeparam>
void ConvertUsing<TTypeConverter>();
/// <summary>
/// Skip normal member mapping and convert using a <see cref="ITypeConverter{TSource,TDestination}"/> instantiated during mapping
/// Use this method if you need to specify the converter type at runtime
/// </summary>
/// <param name="typeConverterType">Type converter type</param>
void ConvertUsing(Type typeConverterType);
/// <summary>
/// Override the destination type mapping for looking up configuration and instantiation
/// </summary>
/// <param name="typeOverride"></param>
void As(Type typeOverride);
/// <summary>
/// Customize individual members
/// </summary>
/// <param name="name">Name of the member</param>
/// <param name="memberOptions">Callback for configuring member</param>
/// <returns>Itself</returns>
IMappingExpression ForMember(string name, Action<IMemberConfigurationExpression> memberOptions);
/// <summary>
/// Include this configuration in derived types' maps
/// </summary>
/// <param name="derivedSourceType">Derived source type</param>
/// <param name="derivedDestinationType">Derived destination type</param>
/// <returns>Itself</returns>
IMappingExpression Include(Type derivedSourceType, Type derivedDestinationType);
/// <summary>
/// Ignores all destination properties that have either a private or protected setter, forcing the mapper to respect encapsulation (note: order matters, so place this before explicit configuration of any properties with an inaccessible setter)
/// </summary>
/// <returns>Itself</returns>
IMappingExpression IgnoreAllPropertiesWithAnInaccessibleSetter();
/// <summary>
/// When using ReverseMap, ignores all source properties that have either a private or protected setter, keeping the reverse mapping consistent with the forward mapping (note: destination properties with an inaccessible setter may still be mapped unless IgnoreAllPropertiesWithAnInaccessibleSetter is also used)
/// </summary>
/// <returns>Itself</returns>
IMappingExpression IgnoreAllSourcePropertiesWithAnInaccessibleSetter();
/// <summary>
/// Include the base type map's configuration in this map
/// </summary>
/// <param name="sourceBase">Base source type</param>
/// <param name="destinationBase">Base destination type</param>
/// <returns></returns>
IMappingExpression IncludeBase(Type sourceBase, Type destinationBase);
/// <summary>
/// Execute a custom function to the source and/or destination types before member mapping
/// </summary>
/// <param name="beforeFunction">Callback for the source/destination types</param>
/// <returns>Itself</returns>
IMappingExpression BeforeMap(Action<object, object> beforeFunction);
/// <summary>
/// Execute a custom mapping action before member mapping
/// </summary>
/// <typeparam name="TMappingAction">Mapping action type instantiated during mapping</typeparam>
/// <returns>Itself</returns>
IMappingExpression BeforeMap<TMappingAction>()
where TMappingAction : IMappingAction<object, object>;
/// <summary>
/// Execute a custom function to the source and/or destination types after member mapping
/// </summary>
/// <param name="afterFunction">Callback for the source/destination types</param>
/// <returns>Itself</returns>
IMappingExpression AfterMap(Action<object, object> afterFunction);
/// <summary>
/// Execute a custom mapping action after member mapping
/// </summary>
/// <typeparam name="TMappingAction">Mapping action type instantiated during mapping</typeparam>
/// <returns>Itself</returns>
IMappingExpression AfterMap<TMappingAction>()
where TMappingAction : IMappingAction<object, object>;
IList<ValueTransformerConfiguration> ValueTransformers { get; }
/// <summary>
/// Specify which member list to validate
/// </summary>
/// <param name="memberList">Member list to validate</param>
/// <returns>Itself</returns>
IMappingExpression ValidateMemberList(MemberList memberList);
}
/// <summary>
/// Mapping configuration options
/// </summary>
/// <typeparam name="TSource">Source type</typeparam>
/// <typeparam name="TDestination">Destination type</typeparam>
public interface IMappingExpression<TSource, TDestination>
{
/// <summary>
/// Customize configuration for a path inside the destination object.
/// </summary>
/// <param name="destinationMember">Expression to the destination subobject</param>
/// <param name="memberOptions">Callback for member options</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> ForPath<TMember>(Expression<Func<TDestination, TMember>> destinationMember,
Action<IPathConfigurationExpression<TSource, TDestination, TMember>> memberOptions);
/// <summary>
/// Preserve object identity. Useful for circular references.
/// </summary>
/// <returns></returns>
IMappingExpression<TSource, TDestination> PreserveReferences();
/// <summary>
/// Customize configuration for members not previously configured
/// </summary>
/// <param name="memberOptions">Callback for member options</param>
void ForAllOtherMembers(Action<IMemberConfigurationExpression<TSource, TDestination, object>> memberOptions);
/// <summary>
/// Customize configuration for individual member
/// </summary>
/// <param name="destinationMember">Expression to the top-level destination member. This must be a member on the <typeparamref name="TDestination"/>TDestination</param> type
/// <param name="memberOptions">Callback for member options</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> ForMember<TMember>(Expression<Func<TDestination, TMember>> destinationMember,
Action<IMemberConfigurationExpression<TSource, TDestination, TMember>> memberOptions);
/// <summary>
/// Customize configuration for individual member. Used when the name isn't known at compile-time
/// </summary>
/// <param name="name">Destination member name</param>
/// <param name="memberOptions">Callback for member options</param>
/// <returns></returns>
IMappingExpression<TSource, TDestination> ForMember(string name,
Action<IMemberConfigurationExpression<TSource, TDestination, object>> memberOptions);
/// <summary>
/// Customize configuration for all members
/// </summary>
/// <param name="memberOptions">Callback for member options</param>
void ForAllMembers(Action<IMemberConfigurationExpression<TSource, TDestination, object>> memberOptions);
/// <summary>
/// Ignores all <typeparamref name="TDestination"/> properties that have either a private or protected setter, forcing the mapper to respect encapsulation (note: order matters, so place this before explicit configuration of any properties with an inaccessible setter)
/// </summary>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> IgnoreAllPropertiesWithAnInaccessibleSetter();
/// <summary>
/// When using ReverseMap, ignores all <typeparamref name="TSource"/> properties that have either a private or protected setter, keeping the reverse mapping consistent with the forward mapping (note: <typeparamref name="TDestination"/> properties with an inaccessible setter may still be mapped unless IgnoreAllPropertiesWithAnInaccessibleSetter is also used)
/// </summary>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> IgnoreAllSourcePropertiesWithAnInaccessibleSetter();
/// <summary>
/// Include this configuration in derived types' maps
/// </summary>
/// <typeparam name="TOtherSource">Derived source type</typeparam>
/// <typeparam name="TOtherDestination">Derived destination type</typeparam>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> Include<TOtherSource, TOtherDestination>()
where TOtherSource : TSource
where TOtherDestination : TDestination;
/// <summary>
/// Include the base type map's configuration in this map
/// </summary>
/// <typeparam name="TSourceBase">Base source type</typeparam>
/// <typeparam name="TDestinationBase">Base destination type</typeparam>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> IncludeBase<TSourceBase, TDestinationBase>();
/// <summary>
/// Include this configuration in derived types' maps
/// </summary>
/// <param name="derivedSourceType">Derived source type</param>
/// <param name="derivedDestinationType">Derived destination type</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> Include(Type derivedSourceType, Type derivedDestinationType);
/// <summary>
/// Skip member mapping and use a custom expression during LINQ projection
/// </summary>
/// <param name="projectionExpression">Projection expression</param>
void ProjectUsing(Expression<Func<TSource, TDestination>> projectionExpression);
/// <summary>
/// Skip member mapping and use a custom function to convert to the destination type
/// </summary>
/// <param name="mappingFunction">Callback to convert from source type to destination type</param>
void ConvertUsing(Func<TSource, TDestination> mappingFunction);
/// <summary>
/// Skip member mapping and use a custom function to convert to the destination type
/// </summary>
/// <param name="mappingFunction">Callback to convert from source type to destination type, including destination object</param>
void ConvertUsing(Func<TSource, TDestination, TDestination> mappingFunction);
/// <summary>
/// Skip member mapping and use a custom function to convert to the destination type
/// </summary>
/// <param name="mappingFunction">Callback to convert from source type to destination type, with source, destination and context</param>
void ConvertUsing(Func<TSource, TDestination, ResolutionContext, TDestination> mappingFunction);
/// <summary>
/// Skip member mapping and use a custom type converter instance to convert to the destination type
/// </summary>
/// <param name="converter">Type converter instance</param>
void ConvertUsing(ITypeConverter<TSource, TDestination> converter);
/// <summary>
/// Skip member mapping and use a custom type converter instance to convert to the destination type
/// </summary>
/// <typeparam name="TTypeConverter">Type converter type</typeparam>
void ConvertUsing<TTypeConverter>() where TTypeConverter : ITypeConverter<TSource, TDestination>;
/// <summary>
/// Execute a custom function to the source and/or destination types before member mapping
/// </summary>
/// <param name="beforeFunction">Callback for the source/destination types</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> BeforeMap(Action<TSource, TDestination> beforeFunction);
/// <summary>
/// Execute a custom function to the source and/or destination types before member mapping
/// </summary>
/// <param name="beforeFunction">Callback for the source/destination types</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> BeforeMap(Action<TSource, TDestination, ResolutionContext> beforeFunction);
/// <summary>
/// Execute a custom mapping action before member mapping
/// </summary>
/// <typeparam name="TMappingAction">Mapping action type instantiated during mapping</typeparam>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> BeforeMap<TMappingAction>()
where TMappingAction : IMappingAction<TSource, TDestination>;
/// <summary>
/// Execute a custom function to the source and/or destination types after member mapping
/// </summary>
/// <param name="afterFunction">Callback for the source/destination types</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> AfterMap(Action<TSource, TDestination> afterFunction);
/// <summary>
/// Execute a custom function to the source and/or destination types after member mapping
/// </summary>
/// <param name="afterFunction">Callback for the source/destination types</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> AfterMap(Action<TSource, TDestination, ResolutionContext> afterFunction);
/// <summary>
/// Execute a custom mapping action after member mapping
/// </summary>
/// <typeparam name="TMappingAction">Mapping action type instantiated during mapping</typeparam>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> AfterMap<TMappingAction>()
where TMappingAction : IMappingAction<TSource, TDestination>;
/// <summary>
/// Supply a custom instantiation function for the destination type
/// </summary>
/// <param name="ctor">Callback to create the destination type given the source object</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> ConstructUsing(Func<TSource, TDestination> ctor);
/// <summary>
/// Supply a custom instantiation expression for the destination type for LINQ projection
/// </summary>
/// <param name="ctor">Callback to create the destination type given the source object</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> ConstructProjectionUsing(Expression<Func<TSource, TDestination>> ctor);
/// <summary>
/// Supply a custom instantiation function for the destination type, based on the entire resolution context
/// </summary>
/// <param name="ctor">Callback to create the destination type given the current resolution context</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> ConstructUsing(Func<TSource, ResolutionContext, TDestination> ctor);
/// <summary>
/// Override the destination type mapping for looking up configuration and instantiation
/// </summary>
/// <typeparam name="T">Destination type to use</typeparam>
void As<T>() where T : TDestination;
/// <summary>
/// For self-referential types, limit recurse depth.
/// Enables PreserveReferences.
/// </summary>
/// <param name="depth">Number of levels to limit to</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> MaxDepth(int depth);
/// <summary>
/// Construct the destination object using the service locator
/// </summary>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> ConstructUsingServiceLocator();
/// <summary>
/// Create a type mapping from the destination to the source type, using the <typeparamref name="TDestination"/> members as validation
/// </summary>
/// <returns>Itself</returns>
IMappingExpression<TDestination, TSource> ReverseMap();
/// <summary>
/// Customize configuration for an individual source member
/// </summary>
/// <param name="sourceMember">Expression to source member. Must be a member of the <typeparamref name="TSource"/> type</param>
/// <param name="memberOptions">Callback for member configuration options</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> ForSourceMember(Expression<Func<TSource, object>> sourceMember,
Action<ISourceMemberConfigurationExpression> memberOptions);
/// <summary>
/// Customize configuration for an individual source member. Member name not known until runtime
/// </summary>
/// <param name="sourceMemberName">Expression to source member. Must be a member of the <typeparamref name="TSource"/> type</param>
/// <param name="memberOptions">Callback for member configuration options</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> ForSourceMember(string sourceMemberName,
Action<ISourceMemberConfigurationExpression> memberOptions);
/// <summary>
/// Replace the original runtime instance with a new source instance. Useful when ORMs return proxy types with no relationships to runtime types.
/// The returned source object will be mapped instead of what was supplied in the original source object.
/// </summary>
/// <param name="substituteFunc">Substitution function</param>
/// <returns>New source object to map.</returns>
IMappingExpression<TSource, TDestination> Substitute<TSubstitute>(Func<TSource, TSubstitute> substituteFunc);
/// <summary>
/// Customize configuration for individual constructor parameter
/// </summary>
/// <param name="ctorParamName">Constructor parameter name</param>
/// <param name="paramOptions">Options</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> ForCtorParam(string ctorParamName, Action<ICtorParamConfigurationExpression<TSource>> paramOptions);
/// <summary>
/// Disable constructor validation. During mapping this map is used against an existing destination object and never constructed itself.
/// </summary>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> DisableCtorValidation();
IList<ValueTransformerConfiguration> ValueTransformers { get; }
/// <summary>
/// Apply a transformation function after any resolved destination member value with the given type
/// </summary>
/// <typeparam name="TValue">Value type to match and transform</typeparam>
/// <param name="transformer">Transformation expression</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> AddTransform<TValue>(Expression<Func<TValue, TValue>> transformer);
/// <summary>
/// Specify which member list to validate
/// </summary>
/// <param name="memberList">Member list to validate</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> ValidateMemberList(MemberList memberList);
}
}
| |
//=================================================================================================
// Copyright 2017 Dirk Lemstra <https://graphicsmagick.codeplex.com/>
//
// Licensed under the ImageMagick License (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.imagemagick.org/script/license.php
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing permissions and
// limitations under the License.
//=================================================================================================
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.Text;
using System.Windows.Media.Imaging;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using Fasterflect;
namespace GraphicsMagick
{
public sealed class MagickImageCollection: IList<MagickImage>, ICollection<MagickImage>, IEnumerable<MagickImage>, IEnumerable, IDisposable
{
internal object _Instance;
internal MagickImageCollection(object instance)
{
_Instance = instance;
}
public static object GetInstance(MagickImageCollection obj)
{
if (ReferenceEquals(obj, null))
return null;
return obj._Instance;
}
public static object GetInstance(object obj)
{
if (ReferenceEquals(obj, null))
return null;
MagickImageCollection casted = obj as MagickImageCollection;
if (ReferenceEquals(casted, null))
return obj;
return casted._Instance;
}
public MagickImageCollection(Stream stream, MagickReadSettings readSettings)
: this(AssemblyHelper.CreateInstance(Types.MagickImageCollection, new Type[] {typeof(Stream), Types.MagickReadSettings}, stream, GraphicsMagick.MagickReadSettings.GetInstance(readSettings)))
{
}
public MagickImageCollection(Stream stream)
: this(AssemblyHelper.CreateInstance(Types.MagickImageCollection, new Type[] {typeof(Stream)}, stream))
{
}
public MagickImageCollection(String fileName, MagickReadSettings readSettings)
: this(AssemblyHelper.CreateInstance(Types.MagickImageCollection, new Type[] {typeof(String), Types.MagickReadSettings}, fileName, GraphicsMagick.MagickReadSettings.GetInstance(readSettings)))
{
}
public MagickImageCollection(String fileName)
: this(AssemblyHelper.CreateInstance(Types.MagickImageCollection, new Type[] {typeof(String)}, fileName))
{
}
public MagickImageCollection(IEnumerable<MagickImage> images)
: this(AssemblyHelper.CreateInstance(Types.MagickImageCollection, new Type[] {Types.IEnumerableMagickImage}, MagickImage.CastIEnumerable(images)))
{
}
public MagickImageCollection(Byte[] data, MagickReadSettings readSettings)
: this(AssemblyHelper.CreateInstance(Types.MagickImageCollection, new Type[] {typeof(Byte[]), Types.MagickReadSettings}, data, GraphicsMagick.MagickReadSettings.GetInstance(readSettings)))
{
}
public MagickImageCollection(Byte[] data)
: this(AssemblyHelper.CreateInstance(Types.MagickImageCollection, new Type[] {typeof(Byte[])}, data))
{
}
public MagickImageCollection()
: this(AssemblyHelper.CreateInstance(Types.MagickImageCollection))
{
}
private Delegate _WarningDelegate;
private EventHandler<WarningEventArgs> _Warning;
private object HandleWarningEvent(object[] args)
{
if (_Warning != null)
_Warning(this, new WarningEventArgs(args[1]));
return null;
}
public event EventHandler<WarningEventArgs> Warning
{
add
{
if (_Warning == null)
{
EventInfo eventInfo = Types.MagickImageCollection.GetEvent("Warning", BindingFlags.Public | BindingFlags.Instance);
if (_WarningDelegate == null)
_WarningDelegate = eventInfo.EventHandlerType.BuildDynamicHandler(HandleWarningEvent);
eventInfo.GetAddMethod(true).Invoke(_Instance, new object[] { _WarningDelegate });
}
_Warning += value;
}
remove
{
_Warning -= value;
if (_Warning == null)
{
EventInfo eventInfo = Types.MagickImageCollection.GetEvent("Warning", BindingFlags.Public | BindingFlags.Instance);
eventInfo.GetRemoveMethod(true).Invoke(_Instance, new object[] { _WarningDelegate });
}
}
}
public static explicit operator Byte[](MagickImageCollection collection)
{
object result = Types.MagickImageCollection.CallMethod("op_Explicit", new Type[] {Types.MagickImageCollection}, GraphicsMagick.MagickImageCollection.GetInstance(collection));
return (Byte[])result;
}
public Int32 Count
{
get
{
object result;
try
{
result = _Instance.GetPropertyValue("Count");
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
return (Int32)result;
}
}
public Boolean IsReadOnly
{
get
{
object result;
try
{
result = _Instance.GetPropertyValue("IsReadOnly");
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
return (Boolean)result;
}
}
public MagickImage this[Int32 index]
{
get
{
object result;
try
{
result = _Instance.GetIndexer(new Type[] {typeof(Int32)}, index);
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
return (result == null ? null : new MagickImage(result));
}
set
{
try
{
_Instance.SetIndexer(new Type[] {typeof(Int32), Types.MagickImage}, index, GraphicsMagick.MagickImage.GetInstance(value));
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
}
public void Add(String fileName)
{
try
{
_Instance.CallMethod("Add", new Type[] {typeof(String)}, fileName);
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
public void Add(MagickImage item)
{
try
{
_Instance.CallMethod("Add", new Type[] {Types.MagickImage}, GraphicsMagick.MagickImage.GetInstance(item));
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
public void AddRange(Stream stream, MagickReadSettings readSettings)
{
try
{
_Instance.CallMethod("AddRange", new Type[] {typeof(Stream), Types.MagickReadSettings}, stream, GraphicsMagick.MagickReadSettings.GetInstance(readSettings));
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
public void AddRange(Stream stream)
{
try
{
_Instance.CallMethod("AddRange", new Type[] {typeof(Stream)}, stream);
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
public void AddRange(String fileName, MagickReadSettings readSettings)
{
try
{
_Instance.CallMethod("AddRange", new Type[] {typeof(String), Types.MagickReadSettings}, fileName, GraphicsMagick.MagickReadSettings.GetInstance(readSettings));
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
public void AddRange(String fileName)
{
try
{
_Instance.CallMethod("AddRange", new Type[] {typeof(String)}, fileName);
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
public void AddRange(MagickImageCollection images)
{
try
{
_Instance.CallMethod("AddRange", new Type[] {Types.MagickImageCollection}, GraphicsMagick.MagickImageCollection.GetInstance(images));
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
public void AddRange(IEnumerable<MagickImage> images)
{
try
{
_Instance.CallMethod("AddRange", new Type[] {Types.IEnumerableMagickImage}, MagickImage.CastIEnumerable(images));
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
public void AddRange(Byte[] data, MagickReadSettings readSettings)
{
try
{
_Instance.CallMethod("AddRange", new Type[] {typeof(Byte[]), Types.MagickReadSettings}, data, GraphicsMagick.MagickReadSettings.GetInstance(readSettings));
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
public void AddRange(Byte[] data)
{
try
{
_Instance.CallMethod("AddRange", new Type[] {typeof(Byte[])}, data);
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
public MagickImage AppendHorizontally()
{
object result;
try
{
result = _Instance.CallMethod("AppendHorizontally");
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
return (result == null ? null : new MagickImage(result));
}
public MagickImage AppendVertically()
{
object result;
try
{
result = _Instance.CallMethod("AppendVertically");
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
return (result == null ? null : new MagickImage(result));
}
public void Clear()
{
try
{
_Instance.CallMethod("Clear");
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
public void Coalesce()
{
try
{
_Instance.CallMethod("Coalesce");
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
public Boolean Contains(MagickImage item)
{
object result;
try
{
result = _Instance.CallMethod("Contains", new Type[] {Types.MagickImage}, GraphicsMagick.MagickImage.GetInstance(item));
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
return (Boolean)result;
}
public void CopyTo(MagickImage[] destination, Int32 arrayIndex)
{
object[] casted_destination = MagickImage.CastArray(destination);
try
{
_Instance.CallMethod("CopyTo", new Type[] {Types.MagickImage.MakeArrayType(), typeof(Int32)}, casted_destination, arrayIndex);
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
MagickImage.UpdateArray(destination, casted_destination);
}
public void Deconstruct()
{
try
{
_Instance.CallMethod("Deconstruct");
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
public void Dispose()
{
try
{
_Instance.CallMethod("Dispose");
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
public MagickImage Flatten()
{
object result;
try
{
result = _Instance.CallMethod("Flatten");
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
return (result == null ? null : new MagickImage(result));
}
public IEnumerator<MagickImage> GetEnumerator()
{
object result;
try
{
result = _Instance.CallMethod("GetEnumerator");
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
return new EnumeratorWrapper<MagickImage>(result).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public Int32 IndexOf(MagickImage item)
{
object result;
try
{
result = _Instance.CallMethod("IndexOf", new Type[] {Types.MagickImage}, GraphicsMagick.MagickImage.GetInstance(item));
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
return (Int32)result;
}
public void Insert(Int32 index, String fileName)
{
try
{
_Instance.CallMethod("Insert", new Type[] {typeof(Int32), typeof(String)}, index, fileName);
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
public void Insert(Int32 index, MagickImage item)
{
try
{
_Instance.CallMethod("Insert", new Type[] {typeof(Int32), Types.MagickImage}, index, GraphicsMagick.MagickImage.GetInstance(item));
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
public void Map(QuantizeSettings settings)
{
try
{
_Instance.CallMethod("Map", new Type[] {Types.QuantizeSettings}, GraphicsMagick.QuantizeSettings.GetInstance(settings));
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
public void Map()
{
try
{
_Instance.CallMethod("Map");
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
public MagickImageCollection Morph(Int32 frames)
{
object result;
try
{
result = _Instance.CallMethod("Morph", new Type[] {typeof(Int32)}, frames);
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
return (result == null ? null : new MagickImageCollection(result));
}
public MagickImage Mosaic()
{
object result;
try
{
result = _Instance.CallMethod("Mosaic");
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
return (result == null ? null : new MagickImage(result));
}
public MagickErrorInfo Quantize(QuantizeSettings settings)
{
object result;
try
{
result = _Instance.CallMethod("Quantize", new Type[] {Types.QuantizeSettings}, GraphicsMagick.QuantizeSettings.GetInstance(settings));
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
return (result == null ? null : new MagickErrorInfo(result));
}
public void Read(Stream stream, MagickReadSettings readSettings)
{
try
{
_Instance.CallMethod("Read", new Type[] {typeof(Stream), Types.MagickReadSettings}, stream, GraphicsMagick.MagickReadSettings.GetInstance(readSettings));
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
public void Read(Stream stream)
{
try
{
_Instance.CallMethod("Read", new Type[] {typeof(Stream)}, stream);
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
public void Read(String fileName, MagickReadSettings readSettings)
{
try
{
_Instance.CallMethod("Read", new Type[] {typeof(String), Types.MagickReadSettings}, fileName, GraphicsMagick.MagickReadSettings.GetInstance(readSettings));
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
public void Read(String fileName)
{
try
{
_Instance.CallMethod("Read", new Type[] {typeof(String)}, fileName);
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
public void Read(FileInfo file, MagickReadSettings readSettings)
{
try
{
_Instance.CallMethod("Read", new Type[] {typeof(FileInfo), Types.MagickReadSettings}, file, GraphicsMagick.MagickReadSettings.GetInstance(readSettings));
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
public void Read(FileInfo file)
{
try
{
_Instance.CallMethod("Read", new Type[] {typeof(FileInfo)}, file);
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
public void Read(Byte[] data, MagickReadSettings readSettings)
{
try
{
_Instance.CallMethod("Read", new Type[] {typeof(Byte[]), Types.MagickReadSettings}, data, GraphicsMagick.MagickReadSettings.GetInstance(readSettings));
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
public void Read(Byte[] data)
{
try
{
_Instance.CallMethod("Read", new Type[] {typeof(Byte[])}, data);
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
public Boolean Remove(MagickImage item)
{
object result;
try
{
result = _Instance.CallMethod("Remove", new Type[] {Types.MagickImage}, GraphicsMagick.MagickImage.GetInstance(item));
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
return (Boolean)result;
}
public void RemoveAt(Int32 index)
{
try
{
_Instance.CallMethod("RemoveAt", new Type[] {typeof(Int32)}, index);
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
public void RePage()
{
try
{
_Instance.CallMethod("RePage");
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
public void Reverse()
{
try
{
_Instance.CallMethod("Reverse");
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
public Bitmap ToBitmap(ImageFormat imageFormat)
{
object result;
try
{
result = _Instance.CallMethod("ToBitmap", new Type[] {typeof(ImageFormat)}, imageFormat);
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
return (Bitmap)result;
}
public Bitmap ToBitmap()
{
object result;
try
{
result = _Instance.CallMethod("ToBitmap");
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
return (Bitmap)result;
}
public Byte[] ToByteArray(MagickFormat format)
{
object result;
try
{
result = _Instance.CallMethod("ToByteArray", new Type[] {Types.MagickFormat}, format);
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
return (Byte[])result;
}
public Byte[] ToByteArray()
{
object result;
try
{
result = _Instance.CallMethod("ToByteArray");
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
return (Byte[])result;
}
public void Write(String fileName)
{
try
{
_Instance.CallMethod("Write", new Type[] {typeof(String)}, fileName);
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
public void Write(Stream stream, MagickFormat format)
{
try
{
_Instance.CallMethod("Write", new Type[] {typeof(Stream), Types.MagickFormat}, stream, format);
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
public void Write(Stream stream)
{
try
{
_Instance.CallMethod("Write", new Type[] {typeof(Stream)}, stream);
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
public void Write(FileInfo file)
{
try
{
_Instance.CallMethod("Write", new Type[] {typeof(FileInfo)}, file);
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
}
}
| |
namespace ContosoUniversity.Migrations
{
using ContosoUniversity.Models;
using ContosoUniversity.DAL;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<SchoolContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(SchoolContext context)
{
var students = new List<Student>
{
new Student { FirstMidName = "Carson", LastName = "Alexander",
EnrollmentDate = DateTime.Parse("2010-09-01"), Email = "tepidUntruths15@mail.com" },
new Student { FirstMidName = "Meredith", LastName = "Alonso",
EnrollmentDate = DateTime.Parse("2012-09-01"), Email = "tyrannicalHulkHunters53@mail.com" },
new Student { FirstMidName = "Arturo", LastName = "Anand",
EnrollmentDate = DateTime.Parse("2013-09-01"), Email = "unbaptisedFundamentalist8@gmail.com" },
new Student { FirstMidName = "Gytis", LastName = "Barzdukas",
EnrollmentDate = DateTime.Parse("2012-09-01"), Email = "vibrantWhipsawnNippleworts78@hotmail.com" },
new Student { FirstMidName = "Yan", LastName = "Li",
EnrollmentDate = DateTime.Parse("2012-09-01"), Email = "uncircumcisedFabledAppealingness17@comcast.net" },
new Student { FirstMidName = "Peggy", LastName = "Justice",
EnrollmentDate = DateTime.Parse("2011-09-01"), Email = "heartsomeLaxative45@mail.com" },
new Student { FirstMidName = "Laura", LastName = "Norman",
EnrollmentDate = DateTime.Parse("2013-09-01"), Email = "inapprehensiveBambi8@yahoo.com" },
new Student { FirstMidName = "Nino", LastName = "Olivetto",
EnrollmentDate = DateTime.Parse("2005-08-11"), Email = "biblicalPopularisers95@hotmail.com" }
};
students.ForEach(s => context.Students.AddOrUpdate(p => p.LastName, s));
context.SaveChanges();
var instructors = new List<Instructor>
{
new Instructor { FirstMidName = "Kim", LastName = "Abercrombie",
HireDate = DateTime.Parse("1995-03-11") },
new Instructor { FirstMidName = "Fadi", LastName = "Fakhouri",
HireDate = DateTime.Parse("2002-07-06") },
new Instructor { FirstMidName = "Roger", LastName = "Harui",
HireDate = DateTime.Parse("1998-07-01") },
new Instructor { FirstMidName = "Candace", LastName = "Kapoor",
HireDate = DateTime.Parse("2001-01-15") },
new Instructor { FirstMidName = "Roger", LastName = "Zheng",
HireDate = DateTime.Parse("2004-02-12") }
};
instructors.ForEach(s => context.Instructors.AddOrUpdate(p => p.LastName, s));
context.SaveChanges();
var departments = new List<Department>
{
new Department { Name = "English", Budget = 350000,
StartDate = DateTime.Parse("2007-09-01"),
InstructorID = instructors.Single( i => i.LastName == "Abercrombie").ID },
new Department { Name = "Mathematics", Budget = 100000,
StartDate = DateTime.Parse("2007-09-01"),
InstructorID = instructors.Single( i => i.LastName == "Fakhouri").ID },
new Department { Name = "Engineering", Budget = 350000,
StartDate = DateTime.Parse("2007-09-01"),
InstructorID = instructors.Single( i => i.LastName == "Harui").ID },
new Department { Name = "Economics", Budget = 100000,
StartDate = DateTime.Parse("2007-09-01"),
InstructorID = instructors.Single( i => i.LastName == "Kapoor").ID }
};
departments.ForEach(s => context.Departments.AddOrUpdate(p => p.Name, s));
context.SaveChanges();
var courses = new List<Course>
{
new Course {CourseID = 1050, Title = "Chemistry", Credits = 3,
DepartmentID = departments.Single( s => s.Name == "Engineering").DepartmentID,
Instructors = new List<Instructor>()
},
new Course {CourseID = 4022, Title = "Microeconomics", Credits = 3,
DepartmentID = departments.Single( s => s.Name == "Economics").DepartmentID,
Instructors = new List<Instructor>()
},
new Course {CourseID = 4041, Title = "Macroeconomics", Credits = 3,
DepartmentID = departments.Single( s => s.Name == "Economics").DepartmentID,
Instructors = new List<Instructor>()
},
new Course {CourseID = 1045, Title = "Calculus", Credits = 4,
DepartmentID = departments.Single( s => s.Name == "Mathematics").DepartmentID,
Instructors = new List<Instructor>()
},
new Course {CourseID = 3141, Title = "Trigonometry", Credits = 4,
DepartmentID = departments.Single( s => s.Name == "Mathematics").DepartmentID,
Instructors = new List<Instructor>()
},
new Course {CourseID = 2021, Title = "Composition", Credits = 3,
DepartmentID = departments.Single( s => s.Name == "English").DepartmentID,
Instructors = new List<Instructor>()
},
new Course {CourseID = 2042, Title = "Literature", Credits = 4,
DepartmentID = departments.Single( s => s.Name == "English").DepartmentID,
Instructors = new List<Instructor>()
},
};
courses.ForEach(s => context.Courses.AddOrUpdate(p => p.CourseID, s));
context.SaveChanges();
var officeAssignments = new List<OfficeAssignment>
{
new OfficeAssignment {
InstructorID = instructors.Single( i => i.LastName == "Fakhouri").ID,
Location = "Smith 17" },
new OfficeAssignment {
InstructorID = instructors.Single( i => i.LastName == "Harui").ID,
Location = "Gowan 27" },
new OfficeAssignment {
InstructorID = instructors.Single( i => i.LastName == "Kapoor").ID,
Location = "Thompson 304" },
};
officeAssignments.ForEach(s => context.OfficeAssignments.AddOrUpdate(p => p.InstructorID, s));
context.SaveChanges();
AddOrUpdateInstructor(context, "Chemistry", "Kapoor");
AddOrUpdateInstructor(context, "Chemistry", "Harui");
AddOrUpdateInstructor(context, "Microeconomics", "Zheng");
AddOrUpdateInstructor(context, "Macroeconomics", "Zheng");
AddOrUpdateInstructor(context, "Calculus", "Fakhouri");
AddOrUpdateInstructor(context, "Trigonometry", "Harui");
AddOrUpdateInstructor(context, "Composition", "Abercrombie");
AddOrUpdateInstructor(context, "Literature", "Abercrombie");
context.SaveChanges();
var enrollments = new List<Enrollment>
{
new Enrollment {
StudentID = students.Single(s => s.LastName == "Alexander").ID,
CourseID = courses.Single(c => c.Title == "Chemistry" ).CourseID,
Grade = Grade.A
},
new Enrollment {
StudentID = students.Single(s => s.LastName == "Alexander").ID,
CourseID = courses.Single(c => c.Title == "Microeconomics" ).CourseID,
Grade = Grade.C
},
new Enrollment {
StudentID = students.Single(s => s.LastName == "Alexander").ID,
CourseID = courses.Single(c => c.Title == "Macroeconomics" ).CourseID,
Grade = Grade.B
},
new Enrollment {
StudentID = students.Single(s => s.LastName == "Alonso").ID,
CourseID = courses.Single(c => c.Title == "Calculus" ).CourseID,
Grade = Grade.B
},
new Enrollment {
StudentID = students.Single(s => s.LastName == "Alonso").ID,
CourseID = courses.Single(c => c.Title == "Trigonometry" ).CourseID,
Grade = Grade.B
},
new Enrollment {
StudentID = students.Single(s => s.LastName == "Alonso").ID,
CourseID = courses.Single(c => c.Title == "Composition" ).CourseID,
Grade = Grade.B
},
new Enrollment {
StudentID = students.Single(s => s.LastName == "Anand").ID,
CourseID = courses.Single(c => c.Title == "Chemistry" ).CourseID
},
new Enrollment {
StudentID = students.Single(s => s.LastName == "Anand").ID,
CourseID = courses.Single(c => c.Title == "Microeconomics").CourseID,
Grade = Grade.B
},
new Enrollment {
StudentID = students.Single(s => s.LastName == "Barzdukas").ID,
CourseID = courses.Single(c => c.Title == "Chemistry").CourseID,
Grade = Grade.B
},
new Enrollment {
StudentID = students.Single(s => s.LastName == "Li").ID,
CourseID = courses.Single(c => c.Title == "Composition").CourseID,
Grade = Grade.B
},
new Enrollment {
StudentID = students.Single(s => s.LastName == "Justice").ID,
CourseID = courses.Single(c => c.Title == "Literature").CourseID,
Grade = Grade.B
}
};
foreach (Enrollment e in enrollments)
{
var enrollmentInDataBase = context.Enrollments.Where(
s =>
s.Student.ID == e.StudentID &&
s.Course.CourseID == e.CourseID).SingleOrDefault();
if (enrollmentInDataBase == null)
{
context.Enrollments.Add(e);
}
}
context.SaveChanges();
}
void AddOrUpdateInstructor(SchoolContext context, string courseTitle, string instructorName)
{
var crs = context.Courses.SingleOrDefault(c => c.Title == courseTitle);
var inst = crs.Instructors.SingleOrDefault(i => i.LastName == instructorName);
if (inst == null)
crs.Instructors.Add(context.Instructors.Single(i => i.LastName == instructorName));
}
}
}
| |
/*
* MindTouch Dream - a distributed REST framework
* Copyright (C) 2006-2011 MindTouch, Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit wiki.developer.mindtouch.com;
* please review the licensing section.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Web;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using MindTouch.IO;
using MindTouch.Tasking;
using MindTouch.Web;
using MindTouch.Xml;
namespace MindTouch.Dream.Http {
using Yield = IEnumerator<IYield>;
/// <summary>
/// Provides an <see cref="IHttpHandler"/> implementation to load Dream inside of IIS.
/// </summary>
public class HttpHandler : IHttpHandler, IPlugEndpoint {
// NOTE (steveb): we only allow one environment to exist at once (see bug 5520)
//--- Class Fields ---
private static readonly log4net.ILog _log = LogUtils.CreateLog();
private static readonly object SyncRoot = new object();
private static IDreamEnvironment _env;
private static XUri _uri;
private static int _minSimilarity;
//--- Constructors ---
/// <summary>
/// Create new handler instance
/// </summary>
public HttpHandler() {
if(_env == null) {
lock(SyncRoot) {
if(_env == null) {
_log.InfoMethodCall("Startup");
try {
_log.InfoMethodCall("ctor: initializing HttpHandler");
NameValueCollection settings = System.Configuration.ConfigurationManager.AppSettings;
// determine storage locations
string basePath = HttpContext.Current.ApplicationInstance.Server.MapPath("~");
string storagePath = settings["storage-dir"] ?? settings["service-dir"];
if(string.IsNullOrEmpty(storagePath)) {
storagePath = Path.Combine(basePath, "storage");
} else if(!Path.IsPathRooted(storagePath)) {
storagePath = Path.Combine(basePath, storagePath);
}
// read configuration
string apikey = settings["apikey"];
_uri = new XUri(settings["public-uri"] ?? settings["root-uri"] ?? "http://localhost/@api");
_minSimilarity = _uri.MaxSimilarity;
// start dreamhost
XDoc config = new XDoc("config")
.Elem("guid", settings["guid"])
.Elem("uri.public", _uri.ToString())
.Elem("storage-dir", storagePath)
.Elem("host-path", settings["host-path"])
.Elem("connect-limit", settings["connect-limit"])
.Elem("apikey", apikey);
IDreamEnvironment env = new DreamHostService();
env.Initialize(config);
// load assemblies in 'services' folder
string servicesFolder = settings["service-dir"] ?? Path.Combine("bin", "services");
if(!Path.IsPathRooted(servicesFolder)) {
servicesFolder = Path.Combine(basePath, servicesFolder);
}
_log.DebugFormat("examining services directory '{0}'", servicesFolder);
if(Directory.Exists(servicesFolder)) {
Plug host = env.Self.With("apikey", apikey);
foreach(string file in Directory.GetFiles(servicesFolder, "*.dll")) {
string assembly = Path.GetFileNameWithoutExtension(file);
_log.DebugFormat("attempting to load '{0}'", assembly);
// register assembly blueprints
DreamMessage response = host.At("load").With("name", assembly).Post(new Result<DreamMessage>(TimeSpan.MaxValue)).Wait();
if(!response.IsSuccessful) {
_log.WarnFormat("DreamHost: ERROR: assembly '{0}' failed to load", file);
}
}
} else {
_log.WarnFormat("DreamHost: WARN: no services directory '{0}'", servicesFolder);
}
// execute script
string scriptFilename = settings["script"];
if(!string.IsNullOrEmpty(scriptFilename)) {
string filename = scriptFilename;
if(!Path.IsPathRooted(filename)) {
filename = Path.Combine(basePath, filename);
}
// execute xml script file
XDoc script = XDocFactory.LoadFrom(filename, MimeType.XML);
Plug host = env.Self.With("apikey", apikey);
host.At("execute").Post(script);
}
// register plug factory for this uri
Plug.AddEndpoint(this);
// set _env variable so other constructors don't initialize it anymore
_env = env;
} catch(Exception e) {
_log.ErrorExceptionMethodCall(e, "ctor");
throw;
}
}
}
}
}
//--- Properties ---
bool IHttpHandler.IsReusable { get { return true; } }
//--- Methods ---
void IHttpHandler.ProcessRequest(HttpContext httpContext) {
var key = new object();
DreamMessage request = null;
try {
string verb = httpContext.Request.HttpMethod;
XUri requestUri = HttpUtil.FromHttpContext(httpContext);
_env.AddActivityDescription(key, string.Format("Incoming: {0} {1}", verb, requestUri.ToString()));
_log.DebugMethodCall("ProcessRequest", verb, requestUri);
// create request message
request = new DreamMessage(DreamStatus.Ok, new DreamHeaders(httpContext.Request.Headers), MimeType.New(httpContext.Request.ContentType), httpContext.Request.ContentLength, httpContext.Request.InputStream);
DreamUtil.PrepareIncomingMessage(request, httpContext.Request.ContentEncoding, string.Format("{0}://{1}{2}", httpContext.Request.Url.Scheme, httpContext.Request.Url.Authority, httpContext.Request.ApplicationPath), httpContext.Request.UserHostAddress, httpContext.Request.UserAgent);
// process message
Result<DreamMessage> response = _env.SubmitRequestAsync(verb, requestUri, httpContext.User, request, new Result<DreamMessage>(TimeSpan.MaxValue)).Block();
request.Close();
DreamMessage item = response.HasException ? DreamMessage.InternalError(response.Exception) : response.Value;
// set status
if(_log.IsDebugEnabled) {
_log.DebugMethodCall("ProcessRequest[Status]", item.Status, String.Format("{0}{1}", httpContext.Request.Url.GetLeftPart(UriPartial.Authority), httpContext.Request.RawUrl).Replace("/index.aspx", "/"));
}
httpContext.Response.StatusCode = (int)item.Status;
// remove internal headers
item.Headers.DreamTransport = null;
item.Headers.DreamPublicUri = null;
// create stream for response (this will force the creation of the 'Content-Length' header as well)
Stream stream = item.ToStream();
// copy headers
foreach(KeyValuePair<string, string> pair in item.Headers) {
_log.TraceMethodCall("ProcessRequest[Header]", pair.Key, pair.Value);
httpContext.Response.AppendHeader(pair.Key, pair.Value);
}
// add set-cookie headers to response
if(item.HasCookies) {
foreach(DreamCookie cookie in item.Cookies) {
httpContext.Response.AppendHeader(DreamHeaders.SET_COOKIE, cookie.ToSetCookieHeader());
}
}
// send message stream
long size = item.ContentLength;
if(((size == -1) || (size > 0)) && (stream != Stream.Null)) {
stream.CopyTo(httpContext.Response.OutputStream, size, new Result<long>(TimeSpan.MaxValue)).Wait();
}
item.Close();
} catch(Exception ex) {
_log.ErrorExceptionMethodCall(ex, "CommonRequestHandler");
if(request != null) {
request.Close();
}
if(httpContext != null) {
httpContext.Response.Close();
}
} finally {
_env.RemoveActivityDescription(key);
}
}
//--- Interface Methods ---
int IPlugEndpoint.GetScoreWithNormalizedUri(XUri uri, out XUri normalized) {
normalized = uri;
int similarity = uri.Similarity(_uri);
return (similarity >= _minSimilarity) ? similarity : 0;
}
Yield IPlugEndpoint.Invoke(Plug plug, string verb, XUri uri, DreamMessage request, Result<DreamMessage> response) {
Result<DreamMessage> res;
yield return res = _env.SubmitRequestAsync(verb, uri, null, request, new Result<DreamMessage>(response.Timeout));
response.Return(res);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using Microsoft.Build.BackEnd;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using Microsoft.Build.Utilities;
using Xunit;
namespace Microsoft.Build.UnitTests.BackEnd
{
/// <summary>
/// Unit Tests for TaskHostConfiguration packet.
/// </summary>
public class TaskHostConfiguration_Tests
{
/// <summary>
/// Override for ContinueOnError
/// </summary>
private bool _continueOnErrorDefault = true;
/// <summary>
/// Test that an exception is thrown when the task name is null.
/// </summary>
[Fact]
public void ConstructorWithNullName()
{
Assert.Throws<InternalErrorException>(() =>
{
TaskHostConfiguration config = new TaskHostConfiguration(
1,
Directory.GetCurrentDirectory(),
null,
Thread.CurrentThread.CurrentCulture,
Thread.CurrentThread.CurrentUICulture,
#if FEATURE_APPDOMAIN
null,
#endif
1,
1,
@"c:\my project\myproj.proj",
_continueOnErrorDefault,
null,
@"c:\my tasks\mytask.dll",
null,
null);
}
);
}
/// <summary>
/// Test that an exception is thrown when the task name is empty.
/// </summary>
[Fact]
public void ConstructorWithEmptyName()
{
Assert.Throws<InternalErrorException>(() =>
{
TaskHostConfiguration config = new TaskHostConfiguration(
1,
Directory.GetCurrentDirectory(),
null,
Thread.CurrentThread.CurrentCulture,
Thread.CurrentThread.CurrentUICulture,
#if FEATURE_APPDOMAIN
null,
#endif
1,
1,
@"c:\my project\myproj.proj",
_continueOnErrorDefault,
String.Empty,
@"c:\my tasks\mytask.dll",
null,
null);
}
);
}
/// <summary>
/// Test that an exception is thrown when the path to the task assembly is null
/// </summary>
[Fact]
public void ConstructorWithNullLocation()
{
Assert.Throws<InternalErrorException>(() =>
{
TaskHostConfiguration config = new TaskHostConfiguration(
1,
Directory.GetCurrentDirectory(),
null,
Thread.CurrentThread.CurrentCulture,
Thread.CurrentThread.CurrentUICulture,
#if FEATURE_APPDOMAIN
null,
#endif
1,
1,
@"c:\my project\myproj.proj",
_continueOnErrorDefault,
"TaskName",
null,
null,
null);
}
);
}
#if !FEATURE_ASSEMBLYLOADCONTEXT
/// <summary>
/// Test that an exception is thrown when the path to the task assembly is empty
/// </summary>
[Fact]
public void ConstructorWithEmptyLocation()
{
Assert.Throws<InternalErrorException>(() =>
{
TaskHostConfiguration config = new TaskHostConfiguration(
1,
Directory.GetCurrentDirectory(),
null,
Thread.CurrentThread.CurrentCulture,
Thread.CurrentThread.CurrentUICulture,
#if FEATURE_APPDOMAIN
null,
#endif
1,
1,
@"c:\my project\myproj.proj",
_continueOnErrorDefault,
"TaskName",
String.Empty,
null,
null);
}
);
}
#endif
/// <summary>
/// Test the valid constructors.
/// </summary>
[Fact]
public void TestValidConstructors()
{
TaskHostConfiguration config = new TaskHostConfiguration(
1,
Directory.GetCurrentDirectory(),
null,
Thread.CurrentThread.CurrentCulture,
Thread.CurrentThread.CurrentUICulture,
#if FEATURE_APPDOMAIN
null,
#endif
1,
1,
@"c:\my project\myproj.proj",
_continueOnErrorDefault,
"TaskName",
@"c:\MyTasks\MyTask.dll",
null,
null);
TaskHostConfiguration config2 = new TaskHostConfiguration(
1,
Directory.GetCurrentDirectory(),
null,
Thread.CurrentThread.CurrentCulture,
Thread.CurrentThread.CurrentUICulture,
#if FEATURE_APPDOMAIN
null,
#endif
1,
1,
@"c:\my project\myproj.proj",
_continueOnErrorDefault,
"TaskName",
@"c:\MyTasks\MyTask.dll",
null,
null);
IDictionary<string, object> parameters = new Dictionary<string, object>();
TaskHostConfiguration config3 = new TaskHostConfiguration(
1,
Directory.GetCurrentDirectory(),
null,
Thread.CurrentThread.CurrentCulture,
Thread.CurrentThread.CurrentUICulture,
#if FEATURE_APPDOMAIN
null,
#endif
1,
1,
@"c:\my project\myproj.proj",
_continueOnErrorDefault,
"TaskName",
@"c:\MyTasks\MyTask.dll",
parameters,
null);
IDictionary<string, object> parameters2 = new Dictionary<string, object>();
parameters2.Add("Text", "Hello!");
parameters2.Add("MyBoolValue", true);
parameters2.Add("MyITaskItem", new TaskItem("ABC"));
parameters2.Add("ItemArray", new ITaskItem[] { new TaskItem("DEF"), new TaskItem("GHI"), new TaskItem("JKL") });
TaskHostConfiguration config4 = new TaskHostConfiguration(
1,
Directory.GetCurrentDirectory(),
null,
Thread.CurrentThread.CurrentCulture,
Thread.CurrentThread.CurrentUICulture,
#if FEATURE_APPDOMAIN
null,
#endif
1,
1,
@"c:\my project\myproj.proj",
_continueOnErrorDefault,
"TaskName",
@"c:\MyTasks\MyTask.dll",
parameters2,
null);
}
/// <summary>
/// Test serialization / deserialization when the parameter dictionary is null.
/// </summary>
[Fact]
public void TestTranslationWithNullDictionary()
{
var expectedGlobalProperties = new Dictionary<string, string>
{
["Property1"] = "Value1",
["Property2"] = "Value2"
};
TaskHostConfiguration config = new TaskHostConfiguration(
1,
Directory.GetCurrentDirectory(),
null,
Thread.CurrentThread.CurrentCulture,
Thread.CurrentThread.CurrentUICulture,
#if FEATURE_APPDOMAIN
null,
#endif
1,
1,
@"c:\my project\myproj.proj",
_continueOnErrorDefault,
"TaskName",
@"c:\MyTasks\MyTask.dll",
null,
expectedGlobalProperties);
((ITranslatable)config).Translate(TranslationHelpers.GetWriteTranslator());
INodePacket packet = TaskHostConfiguration.FactoryForDeserialization(TranslationHelpers.GetReadTranslator());
TaskHostConfiguration deserializedConfig = packet as TaskHostConfiguration;
Assert.Equal(config.TaskName, deserializedConfig.TaskName);
#if !FEATURE_ASSEMBLYLOADCONTEXT
Assert.Equal(config.TaskLocation, deserializedConfig.TaskLocation);
#endif
Assert.Null(deserializedConfig.TaskParameters);
Assert.Equal(expectedGlobalProperties, deserializedConfig.GlobalProperties);
}
/// <summary>
/// Test serialization / deserialization when the parameter dictionary is empty.
/// </summary>
[Fact]
public void TestTranslationWithEmptyDictionary()
{
TaskHostConfiguration config = new TaskHostConfiguration(
1,
Directory.GetCurrentDirectory(),
null,
Thread.CurrentThread.CurrentCulture,
Thread.CurrentThread.CurrentUICulture,
#if FEATURE_APPDOMAIN
null,
#endif
1,
1,
@"c:\my project\myproj.proj",
_continueOnErrorDefault,
"TaskName",
@"c:\MyTasks\MyTask.dll",
new Dictionary<string, object>(),
new Dictionary<string, string>());
((ITranslatable)config).Translate(TranslationHelpers.GetWriteTranslator());
INodePacket packet = TaskHostConfiguration.FactoryForDeserialization(TranslationHelpers.GetReadTranslator());
TaskHostConfiguration deserializedConfig = packet as TaskHostConfiguration;
Assert.Equal(config.TaskName, deserializedConfig.TaskName);
#if !FEATURE_ASSEMBLYLOADCONTEXT
Assert.Equal(config.TaskLocation, deserializedConfig.TaskLocation);
#endif
Assert.NotNull(deserializedConfig.TaskParameters);
Assert.Equal(config.TaskParameters.Count, deserializedConfig.TaskParameters.Count);
Assert.NotNull(deserializedConfig.GlobalProperties);
Assert.Equal(config.GlobalProperties.Count, deserializedConfig.GlobalProperties.Count);
}
/// <summary>
/// Test serialization / deserialization when the parameter dictionary contains just value types.
/// </summary>
[Fact]
public void TestTranslationWithValueTypesInDictionary()
{
IDictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("Text", "Foo");
parameters.Add("BoolValue", false);
TaskHostConfiguration config = new TaskHostConfiguration(
1,
Directory.GetCurrentDirectory(),
null,
Thread.CurrentThread.CurrentCulture,
Thread.CurrentThread.CurrentUICulture,
#if FEATURE_APPDOMAIN
null,
#endif
1,
1,
@"c:\my project\myproj.proj",
_continueOnErrorDefault,
"TaskName",
@"c:\MyTasks\MyTask.dll",
parameters,
null);
((ITranslatable)config).Translate(TranslationHelpers.GetWriteTranslator());
INodePacket packet = TaskHostConfiguration.FactoryForDeserialization(TranslationHelpers.GetReadTranslator());
TaskHostConfiguration deserializedConfig = packet as TaskHostConfiguration;
Assert.Equal(config.TaskName, deserializedConfig.TaskName);
#if !FEATURE_ASSEMBLYLOADCONTEXT
Assert.Equal(config.TaskLocation, deserializedConfig.TaskLocation);
#endif
Assert.NotNull(deserializedConfig.TaskParameters);
Assert.Equal(config.TaskParameters.Count, deserializedConfig.TaskParameters.Count);
Assert.Equal(config.TaskParameters["Text"].WrappedParameter, deserializedConfig.TaskParameters["Text"].WrappedParameter);
Assert.Equal(config.TaskParameters["BoolValue"].WrappedParameter, deserializedConfig.TaskParameters["BoolValue"].WrappedParameter);
}
/// <summary>
/// Test serialization / deserialization when the parameter dictionary contains an ITaskItem.
/// </summary>
[Fact]
public void TestTranslationWithITaskItemInDictionary()
{
IDictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("TaskItemValue", new TaskItem("Foo"));
TaskHostConfiguration config = new TaskHostConfiguration(
1,
Directory.GetCurrentDirectory(),
null,
Thread.CurrentThread.CurrentCulture,
Thread.CurrentThread.CurrentUICulture,
#if FEATURE_APPDOMAIN
null,
#endif
1,
1,
@"c:\my project\myproj.proj",
_continueOnErrorDefault,
"TaskName",
@"c:\MyTasks\MyTask.dll",
parameters,
null);
((ITranslatable)config).Translate(TranslationHelpers.GetWriteTranslator());
INodePacket packet = TaskHostConfiguration.FactoryForDeserialization(TranslationHelpers.GetReadTranslator());
TaskHostConfiguration deserializedConfig = packet as TaskHostConfiguration;
Assert.Equal(config.TaskName, deserializedConfig.TaskName);
#if !FEATURE_ASSEMBLYLOADCONTEXT
Assert.Equal(config.TaskLocation, deserializedConfig.TaskLocation);
#endif
Assert.NotNull(deserializedConfig.TaskParameters);
Assert.Equal(config.TaskParameters.Count, deserializedConfig.TaskParameters.Count);
TaskHostPacketHelpers.AreEqual((ITaskItem)config.TaskParameters["TaskItemValue"].WrappedParameter, (ITaskItem)deserializedConfig.TaskParameters["TaskItemValue"].WrappedParameter);
}
/// <summary>
/// Test serialization / deserialization when the parameter dictionary contains an ITaskItem array.
/// </summary>
[Fact]
public void TestTranslationWithITaskItemArrayInDictionary()
{
IDictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("TaskItemArrayValue", new ITaskItem[] { new TaskItem("Foo"), new TaskItem("Baz") });
TaskHostConfiguration config = new TaskHostConfiguration(
1,
Directory.GetCurrentDirectory(),
null,
Thread.CurrentThread.CurrentCulture,
Thread.CurrentThread.CurrentUICulture,
#if FEATURE_APPDOMAIN
null,
#endif
1,
1,
@"c:\my project\myproj.proj",
_continueOnErrorDefault,
"TaskName",
@"c:\MyTasks\MyTask.dll",
parameters,
null);
((ITranslatable)config).Translate(TranslationHelpers.GetWriteTranslator());
INodePacket packet = TaskHostConfiguration.FactoryForDeserialization(TranslationHelpers.GetReadTranslator());
TaskHostConfiguration deserializedConfig = packet as TaskHostConfiguration;
Assert.Equal(config.TaskName, deserializedConfig.TaskName);
#if !FEATURE_ASSEMBLYLOADCONTEXT
Assert.Equal(config.TaskLocation, deserializedConfig.TaskLocation);
#endif
Assert.NotNull(deserializedConfig.TaskParameters);
Assert.Equal(config.TaskParameters.Count, deserializedConfig.TaskParameters.Count);
ITaskItem[] itemArray = (ITaskItem[])config.TaskParameters["TaskItemArrayValue"].WrappedParameter;
ITaskItem[] deserializedItemArray = (ITaskItem[])deserializedConfig.TaskParameters["TaskItemArrayValue"].WrappedParameter;
TaskHostPacketHelpers.AreEqual(itemArray, deserializedItemArray);
}
/// <summary>
/// Helper methods for testing the task host-related packets.
/// </summary>
internal static class TaskHostPacketHelpers
{
/// <summary>
/// Asserts the equality (or lack thereof) of two arrays of ITaskItems.
/// </summary>
internal static void AreEqual(ITaskItem[] x, ITaskItem[] y)
{
if (x == null && y == null)
{
return;
}
if (x == null || y == null)
{
Assert.True(false, "The two item lists are not equal -- one of them is null");
}
if (x.Length != y.Length)
{
Assert.True(false, "The two item lists have different lengths, so they cannot be equal");
}
for (int i = 0; i < x.Length; i++)
{
AreEqual(x[i], y[i]);
}
}
/// <summary>
/// Asserts the equality (or lack thereof) of two ITaskItems.
/// </summary>
internal static void AreEqual(ITaskItem x, ITaskItem y)
{
if (x == null && y == null)
{
return;
}
if (x == null || y == null)
{
Assert.True(false, "The two items are not equal -- one of them is null");
}
Assert.Equal(x.ItemSpec, y.ItemSpec);
IDictionary metadataFromX = x.CloneCustomMetadata();
IDictionary metadataFromY = y.CloneCustomMetadata();
Assert.Equal(metadataFromX.Count, metadataFromY.Count);
foreach (object metadataName in metadataFromX.Keys)
{
if (!metadataFromY.Contains(metadataName))
{
Assert.True(false, string.Format("Only one item contains the '{0}' metadata", metadataName));
}
else
{
Assert.Equal(metadataFromX[metadataName], metadataFromY[metadataName]);
}
}
}
}
}
}
| |
// Copyright 2003-2021 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
using System.Collections;
using System.ComponentModel;
using System.Drawing.Printing;
using Autodesk.Revit.DB;
using RevitLookup.Core;
using RevitLookup.Core.Collectors;
using Exception = System.Exception;
using Form = System.Windows.Forms.Form;
namespace RevitLookup.Views;
/// <summary>
/// Summary description for Object form.
/// </summary>
public class ObjectsView : Form, IHaveCollector
{
private readonly CollectorObj _snoopCollector = new();
private ToolStripMenuItem _copyToolStripMenuItem;
private object _curObj;
private int _currentPrintItem;
private ContextMenuStrip _listViewContextMenuStrip;
private ColumnHeader _lvColLabel;
private ColumnHeader _lvColValue;
private int[] _maxWidths;
private MenuItem _mnuItemBrowseReflection;
private MenuItem _mnuItemCopy;
private PrintDialog _printDialog;
private PrintDocument _printDocument;
private PrintPreviewDialog _printPreviewDialog;
private TableLayoutPanel _tableLayoutPanel1;
private ToolStrip _toolStrip1;
private ToolStripButton _toolStripButton1;
private ToolStripButton _toolStripButton2;
private ToolStripButton _toolStripButton3;
private ToolStripButton _toolStripButtonRefreshListView;
private ToolStripButton _toolStripButtonSnoopActiveView;
private ToolStripButton _toolStripButtonSnoopApplication;
private ToolStripButton _toolStripButtonSnoopCurrentSelection;
private ToolStripButton _toolStripButtonSnoopDb;
private ToolStripButton _toolStripButtonSnoopDependentElements;
private ToolStripButton _toolStripButtonSnoopLinkedElement;
private ToolStripButton _toolStripButtonSnoopPickEdge;
private ToolStripButton _toolStripButtonSnoopPickFace;
private ToolStrip _toolStripListView;
private ToolStrip _toolStripSelectors;
private ArrayList _treeTypeNodes = new();
private ArrayList _types = new();
protected Button BnOk;
protected ContextMenu CntxMenuObjId;
private IContainer components;
protected ListView LvData;
protected TreeView TvObjs;
public ObjectsView()
{
InitializeComponent();
}
public ObjectsView(object obj)
{
InitializeComponent();
CommonInit(new[] {SnoopableWrapper.Create(obj)});
}
public ObjectsView(ArrayList objs)
{
InitializeComponent();
CommonInit(objs.Cast<object>().Select(SnoopableWrapper.Create));
}
public ObjectsView(IEnumerable<SnoopableWrapper> objects)
{
InitializeComponent();
CommonInit(objects);
}
public Document Document
{
set => _snoopCollector.Document = value;
}
public async void SnoopAndShow(Selector selector)
{
await SelectElements(selector);
ModelessWindowFactory.Show(this);
}
private void CommonInit(IEnumerable<SnoopableWrapper> objs)
{
TvObjs.Nodes.Clear();
LvData.Items.Clear();
_curObj = null;
_treeTypeNodes = new ArrayList();
_types = new ArrayList();
TvObjs.BeginUpdate();
AddObjectsToTree(objs);
// if the tree isn't well populated, expand it and select the first item
// so its not a pain for the user when there is only one relevant item in the tree
if (TvObjs.Nodes.Count == 1)
{
TvObjs.Nodes[0].Expand();
TvObjs.SelectedNode = TvObjs.Nodes[0].Nodes.Count == 0
? TvObjs.Nodes[0]
: TvObjs.Nodes[0].Nodes[0];
}
TvObjs.EndUpdate();
TvObjs.Focus();
// Add Load to update ListView Width
Core.Utils.AddOnLoadForm(this);
}
private void CommonInit(object obj)
{
switch (obj)
{
case null:
return;
case IList<Element> lista:
CommonInit(lista.Select(SnoopableWrapper.Create));
break;
default:
CommonInit(new[] {SnoopableWrapper.Create(obj)});
break;
}
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing) components?.Dispose();
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ObjectsView));
this.TvObjs = new System.Windows.Forms.TreeView();
this.CntxMenuObjId = new System.Windows.Forms.ContextMenu();
this._mnuItemCopy = new System.Windows.Forms.MenuItem();
this._mnuItemBrowseReflection = new System.Windows.Forms.MenuItem();
this.BnOk = new System.Windows.Forms.Button();
this.LvData = new System.Windows.Forms.ListView();
this._lvColLabel = new System.Windows.Forms.ColumnHeader();
this._lvColValue = new System.Windows.Forms.ColumnHeader();
this._listViewContextMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components);
this._copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this._printDialog = new System.Windows.Forms.PrintDialog();
this._printDocument = new System.Drawing.Printing.PrintDocument();
this._printPreviewDialog = new System.Windows.Forms.PrintPreviewDialog();
this._tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this._toolStrip1 = new System.Windows.Forms.ToolStrip();
this._toolStripButton1 = new System.Windows.Forms.ToolStripButton();
this._toolStripButton2 = new System.Windows.Forms.ToolStripButton();
this._toolStripButton3 = new System.Windows.Forms.ToolStripButton();
this._toolStripListView = new System.Windows.Forms.ToolStrip();
this._toolStripButtonRefreshListView = new System.Windows.Forms.ToolStripButton();
this._toolStripSelectors = new System.Windows.Forms.ToolStrip();
this._toolStripButtonSnoopDb = new System.Windows.Forms.ToolStripButton();
this._toolStripButtonSnoopCurrentSelection = new System.Windows.Forms.ToolStripButton();
this._toolStripButtonSnoopPickFace = new System.Windows.Forms.ToolStripButton();
this._toolStripButtonSnoopPickEdge = new System.Windows.Forms.ToolStripButton();
this._toolStripButtonSnoopLinkedElement = new System.Windows.Forms.ToolStripButton();
this._toolStripButtonSnoopDependentElements = new System.Windows.Forms.ToolStripButton();
this._toolStripButtonSnoopActiveView = new System.Windows.Forms.ToolStripButton();
this._toolStripButtonSnoopApplication = new System.Windows.Forms.ToolStripButton();
this._listViewContextMenuStrip.SuspendLayout();
this._tableLayoutPanel1.SuspendLayout();
this._toolStrip1.SuspendLayout();
this._toolStripListView.SuspendLayout();
this._toolStripSelectors.SuspendLayout();
this.SuspendLayout();
//
// TvObjs
//
this.TvObjs.Anchor =
((System.Windows.Forms.AnchorStyles) (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left)));
this.TvObjs.ContextMenu = this.CntxMenuObjId;
this.TvObjs.HideSelection = false;
this.TvObjs.Location = new System.Drawing.Point(12, 32);
this.TvObjs.Name = "TvObjs";
this.TvObjs.Size = new System.Drawing.Size(248, 430);
this.TvObjs.TabIndex = 0;
this.TvObjs.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.TreeNodeSelected);
//
// CntxMenuObjId
//
this.CntxMenuObjId.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {this._mnuItemCopy, this._mnuItemBrowseReflection});
//
// _mnuItemCopy
//
this._mnuItemCopy.Index = 0;
this._mnuItemCopy.Text = "Copy";
this._mnuItemCopy.Click += new System.EventHandler(this.ContextMenuClick_Copy);
//
// _mnuItemBrowseReflection
//
this._mnuItemBrowseReflection.Index = 1;
this._mnuItemBrowseReflection.Text = "Browse Using Reflection...";
this._mnuItemBrowseReflection.Click += new System.EventHandler(this.ContextMenuClick_BrowseReflection);
//
// BnOk
//
this.BnOk.Anchor =
((System.Windows.Forms.AnchorStyles) (((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right)));
this.BnOk.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.BnOk.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.BnOk.Location = new System.Drawing.Point(284, 464);
this.BnOk.Name = "BnOk";
this.BnOk.Size = new System.Drawing.Size(504, 23);
this.BnOk.TabIndex = 4;
this.BnOk.Text = "OK";
this.BnOk.Click += new System.EventHandler(this.ButtonOK_Click);
//
// LvData
//
this.LvData.Anchor =
((System.Windows.Forms.AnchorStyles) ((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) |
System.Windows.Forms.AnchorStyles.Right)));
this.LvData.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {this._lvColLabel, this._lvColValue});
this.LvData.ContextMenuStrip = this._listViewContextMenuStrip;
this.LvData.FullRowSelect = true;
this.LvData.GridLines = true;
this.LvData.HideSelection = false;
this.LvData.Location = new System.Drawing.Point(284, 32);
this.LvData.Name = "LvData";
this.LvData.ShowItemToolTips = true;
this.LvData.Size = new System.Drawing.Size(504, 430);
this.LvData.TabIndex = 3;
this.LvData.UseCompatibleStateImageBehavior = false;
this.LvData.View = System.Windows.Forms.View.Details;
this.LvData.Click += new System.EventHandler(this.DataItemSelected);
this.LvData.DoubleClick += new System.EventHandler(this.DataItemSelected);
//
// _lvColLabel
//
this._lvColLabel.Text = "Field";
this._lvColLabel.Width = 200;
//
// _lvColValue
//
this._lvColValue.Text = "Value";
this._lvColValue.Width = 800;
//
// _listViewContextMenuStrip
//
this._listViewContextMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {this._copyToolStripMenuItem});
this._listViewContextMenuStrip.Name = "_listViewContextMenuStrip";
this._listViewContextMenuStrip.Size = new System.Drawing.Size(103, 26);
//
// _copyToolStripMenuItem
//
this._copyToolStripMenuItem.Image = global::RevitLookup.Properties.Resources.Copy;
this._copyToolStripMenuItem.Name = "_copyToolStripMenuItem";
this._copyToolStripMenuItem.Size = new System.Drawing.Size(102, 22);
this._copyToolStripMenuItem.Text = "Copy";
this._copyToolStripMenuItem.Click += new System.EventHandler(this.CopyToolStripMenuItem_Click);
//
// _printDialog
//
this._printDialog.Document = this._printDocument;
this._printDialog.UseEXDialog = true;
//
// _printDocument
//
this._printDocument.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.PrintDocument_PrintPage);
//
// _printPreviewDialog
//
this._printPreviewDialog.AutoScrollMargin = new System.Drawing.Size(0, 0);
this._printPreviewDialog.AutoScrollMinSize = new System.Drawing.Size(0, 0);
this._printPreviewDialog.ClientSize = new System.Drawing.Size(400, 300);
this._printPreviewDialog.Document = this._printDocument;
this._printPreviewDialog.Enabled = true;
this._printPreviewDialog.Icon = ((System.Drawing.Icon) (resources.GetObject("_printPreviewDialog.Icon")));
this._printPreviewDialog.Name = "_printPreviewDialog";
this._printPreviewDialog.Visible = false;
//
// _tableLayoutPanel1
//
this._tableLayoutPanel1.AutoSize = true;
this._tableLayoutPanel1.ColumnCount = 3;
this._tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 40F));
this._tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 40F));
this._tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20F));
this._tableLayoutPanel1.Controls.Add(this._toolStrip1, 0, 0);
this._tableLayoutPanel1.Controls.Add(this._toolStripListView, 2, 0);
this._tableLayoutPanel1.Controls.Add(this._toolStripSelectors, 1, 0);
this._tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Top;
this._tableLayoutPanel1.Location = new System.Drawing.Point(0, 0);
this._tableLayoutPanel1.Name = "_tableLayoutPanel1";
this._tableLayoutPanel1.RowCount = 1;
this._tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
this._tableLayoutPanel1.Size = new System.Drawing.Size(800, 26);
this._tableLayoutPanel1.TabIndex = 5;
//
// _toolStrip1
//
this._toolStrip1.AutoSize = false;
this._toolStrip1.ImageScalingSize = new System.Drawing.Size(20, 20);
this._toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {this._toolStripButton1, this._toolStripButton2, this._toolStripButton3});
this._toolStrip1.Location = new System.Drawing.Point(0, 0);
this._toolStrip1.Name = "_toolStrip1";
this._toolStrip1.Size = new System.Drawing.Size(320, 26);
this._toolStrip1.TabIndex = 5;
//
// _toolStripButton1
//
this._toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this._toolStripButton1.Image = global::RevitLookup.Properties.Resources.Print;
this._toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta;
this._toolStripButton1.Name = "_toolStripButton1";
this._toolStripButton1.Size = new System.Drawing.Size(24, 23);
this._toolStripButton1.Text = "Print";
this._toolStripButton1.Click += new System.EventHandler(this.PrintMenuItem_Click);
//
// _toolStripButton2
//
this._toolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this._toolStripButton2.Image = global::RevitLookup.Properties.Resources.Preview;
this._toolStripButton2.ImageTransparentColor = System.Drawing.Color.Magenta;
this._toolStripButton2.Name = "_toolStripButton2";
this._toolStripButton2.Size = new System.Drawing.Size(24, 23);
this._toolStripButton2.Text = "Print Preview";
this._toolStripButton2.Click += new System.EventHandler(this.PrintPreviewMenuItem_Click);
//
// _toolStripButton3
//
this._toolStripButton3.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this._toolStripButton3.Image = global::RevitLookup.Properties.Resources.Copy;
this._toolStripButton3.ImageTransparentColor = System.Drawing.Color.Magenta;
this._toolStripButton3.Name = "_toolStripButton3";
this._toolStripButton3.Size = new System.Drawing.Size(24, 23);
this._toolStripButton3.Text = "Copy To Clipboard";
this._toolStripButton3.Click += new System.EventHandler(this.ContextMenuClick_Copy);
//
// _toolStripListView
//
this._toolStripListView.AutoSize = false;
this._toolStripListView.ImageScalingSize = new System.Drawing.Size(20, 20);
this._toolStripListView.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {this._toolStripButtonRefreshListView});
this._toolStripListView.Location = new System.Drawing.Point(640, 0);
this._toolStripListView.Name = "_toolStripListView";
this._toolStripListView.Size = new System.Drawing.Size(160, 26);
this._toolStripListView.TabIndex = 7;
this._toolStripListView.Text = "toolStrip3";
//
// _toolStripButtonRefreshListView
//
this._toolStripButtonRefreshListView.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this._toolStripButtonRefreshListView.Image = ((System.Drawing.Image) (resources.GetObject("_toolStripButtonRefreshListView.Image")));
this._toolStripButtonRefreshListView.ImageTransparentColor = System.Drawing.Color.Magenta;
this._toolStripButtonRefreshListView.Name = "_toolStripButtonRefreshListView";
this._toolStripButtonRefreshListView.Size = new System.Drawing.Size(24, 23);
this._toolStripButtonRefreshListView.Text = "toolStripButton4";
this._toolStripButtonRefreshListView.ToolTipText = "Refresh selected element data in the list view";
this._toolStripButtonRefreshListView.Click += new System.EventHandler(this.ToolStripButton_RefreshListView_Click);
this._toolStripButtonRefreshListView.MouseEnter += new System.EventHandler(this.ToolStrip_MouseEnter);
//
// _toolStripSelectors
//
this._toolStripSelectors.AutoSize = false;
this._toolStripSelectors.ImageScalingSize = new System.Drawing.Size(20, 20);
this._toolStripSelectors.Items.AddRange(new System.Windows.Forms.ToolStripItem[]
{
this._toolStripButtonSnoopDb, this._toolStripButtonSnoopCurrentSelection, this._toolStripButtonSnoopPickFace, this._toolStripButtonSnoopPickEdge,
this._toolStripButtonSnoopLinkedElement, this._toolStripButtonSnoopDependentElements, this._toolStripButtonSnoopActiveView, this._toolStripButtonSnoopApplication
});
this._toolStripSelectors.Location = new System.Drawing.Point(320, 0);
this._toolStripSelectors.Name = "_toolStripSelectors";
this._toolStripSelectors.Size = new System.Drawing.Size(320, 26);
this._toolStripSelectors.TabIndex = 8;
this._toolStripSelectors.Text = "toolStrip2";
//
// _toolStripButtonSnoopDb
//
this._toolStripButtonSnoopDb.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this._toolStripButtonSnoopDb.Image = ((System.Drawing.Image) (resources.GetObject("_toolStripButtonSnoopDb.Image")));
this._toolStripButtonSnoopDb.ImageTransparentColor = System.Drawing.Color.Magenta;
this._toolStripButtonSnoopDb.Name = "_toolStripButtonSnoopDb";
this._toolStripButtonSnoopDb.Tag = nameof(Selector.SnoopDb);
this._toolStripButtonSnoopDb.Size = new System.Drawing.Size(24, 23);
this._toolStripButtonSnoopDb.Text = "Snoop DB";
this._toolStripButtonSnoopDb.Click += new System.EventHandler(this.ToolStripButton_Snoop_Click);
this._toolStripButtonSnoopDb.MouseEnter += new System.EventHandler(this.ToolStrip_MouseEnter);
//
// _toolStripButtonSnoopCurrentSelection
//
this._toolStripButtonSnoopCurrentSelection.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this._toolStripButtonSnoopCurrentSelection.Image = ((System.Drawing.Image) (resources.GetObject("_toolStripButtonSnoopCurrentSelection.Image")));
this._toolStripButtonSnoopCurrentSelection.ImageTransparentColor = System.Drawing.Color.Magenta;
this._toolStripButtonSnoopCurrentSelection.Name = "_toolStripButtonSnoopCurrentSelection";
this._toolStripButtonSnoopCurrentSelection.Tag = nameof(Selector.SnoopCurrentSelection);
this._toolStripButtonSnoopCurrentSelection.Size = new System.Drawing.Size(24, 23);
this._toolStripButtonSnoopCurrentSelection.Text = "Snoop current selection";
this._toolStripButtonSnoopCurrentSelection.ToolTipText = "Snoop current selection";
this._toolStripButtonSnoopCurrentSelection.Click += new System.EventHandler(this.ToolStripButton_Snoop_Click);
this._toolStripButtonSnoopCurrentSelection.MouseEnter += new System.EventHandler(this.ToolStrip_MouseEnter);
//
// _toolStripButtonSnoopPickFace
//
this._toolStripButtonSnoopPickFace.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this._toolStripButtonSnoopPickFace.Image = ((System.Drawing.Image) (resources.GetObject("_toolStripButtonSnoopPickFace.Image")));
this._toolStripButtonSnoopPickFace.ImageTransparentColor = System.Drawing.Color.Magenta;
this._toolStripButtonSnoopPickFace.Name = "_toolStripButtonSnoopPickFace";
this._toolStripButtonSnoopPickFace.Tag = nameof(Selector.SnoopPickFace);
this._toolStripButtonSnoopPickFace.Size = new System.Drawing.Size(24, 23);
this._toolStripButtonSnoopPickFace.Text = "Snoop pick face";
this._toolStripButtonSnoopPickFace.Click += new System.EventHandler(this.ToolStripButton_Snoop_Click);
this._toolStripButtonSnoopPickFace.MouseEnter += new System.EventHandler(this.ToolStrip_MouseEnter);
//
// _toolStripButtonSnoopPickEdge
//
this._toolStripButtonSnoopPickEdge.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this._toolStripButtonSnoopPickEdge.Image = ((System.Drawing.Image) (resources.GetObject("_toolStripButtonSnoopPickEdge.Image")));
this._toolStripButtonSnoopPickEdge.ImageTransparentColor = System.Drawing.Color.Magenta;
this._toolStripButtonSnoopPickEdge.Name = "_toolStripButtonSnoopPickEdge";
this._toolStripButtonSnoopPickEdge.Tag = nameof(Selector.SnoopPickEdge);
this._toolStripButtonSnoopPickEdge.Size = new System.Drawing.Size(24, 23);
this._toolStripButtonSnoopPickEdge.Text = "Snoop pick edge";
this._toolStripButtonSnoopPickEdge.Click += new System.EventHandler(this.ToolStripButton_Snoop_Click);
this._toolStripButtonSnoopPickEdge.MouseEnter += new System.EventHandler(this.ToolStrip_MouseEnter);
//
// _toolStripButtonSnoopLinkedElement
//
this._toolStripButtonSnoopLinkedElement.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this._toolStripButtonSnoopLinkedElement.Image = ((System.Drawing.Image) (resources.GetObject("_toolStripButtonSnoopLinkedElement.Image")));
this._toolStripButtonSnoopLinkedElement.ImageTransparentColor = System.Drawing.Color.Magenta;
this._toolStripButtonSnoopLinkedElement.Name = "_toolStripButtonSnoopLinkedElement";
this._toolStripButtonSnoopLinkedElement.Tag = nameof(Selector.SnoopLinkedElement);
this._toolStripButtonSnoopLinkedElement.Size = new System.Drawing.Size(24, 23);
this._toolStripButtonSnoopLinkedElement.Text = "Snoop linked element";
this._toolStripButtonSnoopLinkedElement.Click += new System.EventHandler(this.ToolStripButton_Snoop_Click);
this._toolStripButtonSnoopLinkedElement.MouseEnter += new System.EventHandler(this.ToolStrip_MouseEnter);
//
// _toolStripButtonSnoopDependentElements
//
this._toolStripButtonSnoopDependentElements.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this._toolStripButtonSnoopDependentElements.Image = ((System.Drawing.Image) (resources.GetObject("_toolStripButtonSnoopDependentElements.Image")));
this._toolStripButtonSnoopDependentElements.ImageTransparentColor = System.Drawing.Color.Magenta;
this._toolStripButtonSnoopDependentElements.Name = "_toolStripButtonSnoopDependentElements";
this._toolStripButtonSnoopDependentElements.Tag = nameof(Selector.SnoopDependentElements);
this._toolStripButtonSnoopDependentElements.Size = new System.Drawing.Size(24, 23);
this._toolStripButtonSnoopDependentElements.Text = "Snoop dependent elements";
this._toolStripButtonSnoopDependentElements.Click += new System.EventHandler(this.ToolStripButton_Snoop_Click);
this._toolStripButtonSnoopDependentElements.MouseEnter += new System.EventHandler(this.ToolStrip_MouseEnter);
//
// _toolStripButtonSnoopActiveView
//
this._toolStripButtonSnoopActiveView.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this._toolStripButtonSnoopActiveView.Image = ((System.Drawing.Image) (resources.GetObject("_toolStripButtonSnoopActiveView.Image")));
this._toolStripButtonSnoopActiveView.ImageTransparentColor = System.Drawing.Color.Magenta;
this._toolStripButtonSnoopActiveView.Name = "_toolStripButtonSnoopActiveView";
this._toolStripButtonSnoopActiveView.Tag = nameof(Selector.SnoopActiveView);
this._toolStripButtonSnoopActiveView.Size = new System.Drawing.Size(24, 23);
this._toolStripButtonSnoopActiveView.Text = "Snoop active view";
this._toolStripButtonSnoopActiveView.Click += new System.EventHandler(this.ToolStripButton_Snoop_Click);
this._toolStripButtonSnoopActiveView.MouseEnter += new System.EventHandler(this.ToolStrip_MouseEnter);
//
// _toolStripButtonSnoopApplication
//
this._toolStripButtonSnoopApplication.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this._toolStripButtonSnoopApplication.Image = ((System.Drawing.Image) (resources.GetObject("_toolStripButtonSnoopApplication.Image")));
this._toolStripButtonSnoopApplication.ImageTransparentColor = System.Drawing.Color.Magenta;
this._toolStripButtonSnoopApplication.Name = "_toolStripButtonSnoopApplication";
this._toolStripButtonSnoopApplication.Tag = nameof(Selector.SnoopApplication);
this._toolStripButtonSnoopApplication.Size = new System.Drawing.Size(24, 23);
this._toolStripButtonSnoopApplication.Text = "Snoop application";
this._toolStripButtonSnoopApplication.Click += new System.EventHandler(this.ToolStripButton_Snoop_Click);
this._toolStripButtonSnoopApplication.MouseEnter += new System.EventHandler(this.ToolStrip_MouseEnter);
//
// ObjectsView
//
this.CancelButton = this.BnOk;
this.ClientSize = new System.Drawing.Size(800, 492);
this.Controls.Add(this._tableLayoutPanel1);
this.Controls.Add(this.LvData);
this.Controls.Add(this.TvObjs);
this.Controls.Add(this.BnOk);
this.Icon = ((System.Drawing.Icon) (resources.GetObject("$this.Icon")));
this.MinimumSize = new System.Drawing.Size(650, 200);
this.Name = "ObjectsView";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Snoop Objects";
this._listViewContextMenuStrip.ResumeLayout(false);
this._tableLayoutPanel1.ResumeLayout(false);
this._toolStrip1.ResumeLayout(false);
this._toolStrip1.PerformLayout();
this._toolStripListView.ResumeLayout(false);
this._toolStripListView.PerformLayout();
this._toolStripSelectors.ResumeLayout(false);
this._toolStripSelectors.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private void AddObjectsToTree(IEnumerable<SnoopableWrapper> snoopableObjects)
{
TvObjs.Sorted = true;
// initialize the tree control
foreach (var snoopableObject in snoopableObjects)
{
// hook this up to the correct spot in the tree based on the object's type
var parentNode = GetExistingNodeForType(snoopableObject.GetUnderlyingType());
if (parentNode is null)
{
parentNode = new TreeNode(snoopableObject.GetUnderlyingType().Name);
TvObjs.Nodes.Add(parentNode);
// record that we've seen this one
_treeTypeNodes.Add(parentNode);
_types.Add(snoopableObject.GetUnderlyingType());
}
// add the new node for this element
var tmpNode = new TreeNode(snoopableObject.Title) {Tag = snoopableObject.Object};
parentNode.Nodes.Add(tmpNode);
}
}
/// <summary>
/// If we've already seen this type before, return the existing TreeNode object
/// </summary>
/// <param name="objType">System.Type we're looking to find</param>
/// <returns>The existing TreeNode or NULL</returns>
private TreeNode GetExistingNodeForType(Type objType)
{
var len = _types.Count;
for (var i = 0; i < len; i++)
if ((Type) _types[i] == objType)
return (TreeNode) _treeTypeNodes[i];
return null;
}
private async Task CollectAndDisplayData()
{
try
{
await _snoopCollector.Collect(_curObj);
Core.Utils.Display(LvData, _snoopCollector);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private async Task SelectElements(Selector selector)
{
await ExternalExecutor.ExecuteInRevitContextAsync(x =>
{
_tableLayoutPanel1.Enabled = false;
TvObjs.Enabled = false;
LvData.Enabled = false;
BnOk.Enabled = false;
var (item1, document) = Selectors.Snoop(x, selector);
_tableLayoutPanel1.Enabled = true;
TvObjs.Enabled = true;
LvData.Enabled = true;
BnOk.Enabled = true;
Document = document;
CommonInit(item1);
});
}
#region Events
private async void TreeNodeSelected(object sender, TreeViewEventArgs e)
{
_curObj = e.Node.Tag;
await CollectAndDisplayData();
}
private void DataItemSelected(object sender, EventArgs e)
{
Core.Utils.DataItemSelected(LvData, new ModelessWindowFactory(this, _snoopCollector.Document));
}
private void ContextMenuClick_Copy(object sender, EventArgs e)
{
if (TvObjs.SelectedNode is not null) Core.Utils.CopyToClipboard(LvData);
}
private void ContextMenuClick_BrowseReflection(object sender, EventArgs e)
{
Core.Utils.BrowseReflection(_curObj);
}
private void CopyToolStripMenuItem_Click(object sender, EventArgs e)
{
if (LvData.SelectedItems.Count > 0)
Core.Utils.CopyToClipboard(LvData.SelectedItems[0], false);
else
Clipboard.Clear();
}
private void PrintMenuItem_Click(object sender, EventArgs e)
{
Core.Utils.UpdatePrintSettings(_printDocument, TvObjs, LvData, ref _maxWidths);
Core.Utils.PrintMenuItemClick(_printDialog, TvObjs);
}
private void PrintPreviewMenuItem_Click(object sender, EventArgs e)
{
Core.Utils.UpdatePrintSettings(_printDocument, TvObjs, LvData, ref _maxWidths);
Core.Utils.PrintPreviewMenuItemClick(_printPreviewDialog, TvObjs);
}
private void PrintDocument_PrintPage(object sender, PrintPageEventArgs e)
{
_currentPrintItem = Core.Utils.Print(TvObjs.SelectedNode.Text, LvData, e, _maxWidths[0], _maxWidths[1], _currentPrintItem);
}
private async void ToolStripButton_RefreshListView_Click(object sender, EventArgs e)
{
await CollectAndDisplayData();
}
private void ToolStrip_MouseEnter(object sender, EventArgs e)
{
if (ActiveForm != this) Activate();
}
private void ButtonOK_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
Dispose();
}
private async void ToolStripButton_Snoop_Click(object sender, EventArgs e)
{
var btn = (ToolStripButton) sender;
var selector = (Selector) Enum.Parse(typeof(Selector), btn.Tag as string ?? string.Empty);
await SelectElements(selector);
}
#endregion
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Sugar.Mime
{
/// <summary>
/// Common mime types
/// </summary>
public static class MimeTypes
{
#region Application
/// <summary>
/// Gets the unknown mime type.
/// </summary>
public static ApplicationMime Unknown
{
get
{
return new ApplicationMime
{
ApplicationMimeType = ApplicationMimeType.Unknown,
Extensions = new List<string> {""}
};
}
}
/// <summary>
/// Gets the octet stream mime type.
/// </summary>
public static ApplicationMime OctetStream
{
get
{
return new ApplicationMime
{
ApplicationMimeType = ApplicationMimeType.OctetStream,
Extensions = new List<string> {"bin"}
};
}
}
/// <summary>
/// Gets the Microsoft Word mime type.
/// </summary>
public static ApplicationMime MicrosoftWord
{
get
{
return new ApplicationMime
{
ApplicationMimeType = ApplicationMimeType.MicrosoftWord,
Extensions = new List<string> {"doc"}
};
}
}
/// <summary>
/// Gets the Microsoft Word Open XML mime type.
/// </summary>
public static ApplicationMime MicrosoftWordOpenXml
{
get
{
return new ApplicationMime
{
ApplicationMimeType = ApplicationMimeType.MicrosoftWordOpenXml,
Extensions = new List<string> {"docx"}
};
}
}
/// <summary>
/// Gets the Microsoft Power Point mime type.
/// </summary>
public static ApplicationMime MicrosoftPowerPoint
{
get
{
return new ApplicationMime
{
ApplicationMimeType = ApplicationMimeType.MicrosoftPowerPoint,
Extensions = new List<string> {"ppt"}
};
}
}
/// <summary>
/// Gets the Microsoft Power Point Open XML mime type.
/// </summary>
public static ApplicationMime MicrosoftPowerPointOpenXml
{
get
{
return new ApplicationMime
{
ApplicationMimeType = ApplicationMimeType.MicrosoftPowerPointOpenXml,
Extensions = new List<string> {"pptx"}
};
}
}
/// <summary>
/// Gets the Microsoft Excel mime type.
/// </summary>
public static ApplicationMime MicrosoftExcel
{
get
{
return new ApplicationMime
{
ApplicationMimeType = ApplicationMimeType.MicrosoftExcel,
Extensions = new List<string> {"xls"}
};
}
}
/// <summary>
/// Gets the Microsoft Excel Open XML mime type.
/// </summary>
public static ApplicationMime MicrosoftExcelOpenXml
{
get
{
return new ApplicationMime
{
ApplicationMimeType = ApplicationMimeType.MicrosoftExcelOpenXml,
Extensions = new List<string> {"xlsx"}
};
}
}
/// <summary>
/// Gets the Microsoft Visio mime type.
/// </summary>
public static ApplicationMime MicrosoftVisio
{
get
{
return new ApplicationMime
{
ApplicationMimeType = ApplicationMimeType.MicrosoftVisio,
Extensions = new List<string> { "vsd" }
};
}
}
/// <summary>
/// Gets the gzip mime type.
/// </summary>
public static ApplicationMime GZip
{
get
{
return new ApplicationMime
{
ApplicationMimeType = ApplicationMimeType.GZip,
Extensions = new List<string> {"gzip"}
};
}
}
/// <summary>
/// Gets the zip mime type.
/// </summary>
public static ApplicationMime Zip
{
get
{
return new ApplicationMime
{
ApplicationMimeType = ApplicationMimeType.Zip,
Extensions = new List<string> {"zip"}
};
}
}
/// <summary>
/// Gets the PDF mime type.
/// </summary>
public static ApplicationMime Pdf
{
get
{
return new ApplicationMime
{
ApplicationMimeType = ApplicationMimeType.Pdf,
Extensions = new List<string> {"pdf"}
};
}
}
/// <summary>
/// Gets the JSON mime type.
/// </summary>
public static ApplicationMime Json
{
get
{
return new ApplicationMime
{
ApplicationMimeType = ApplicationMimeType.Json,
Extensions = new List<string> {"json"}
};
}
}
#endregion
#region Audio
/// <summary>
/// Gets the basic audio mime type.
/// </summary>
public static AudioMime BasicAudio
{
get
{
return new AudioMime
{
AudioMimeType = AudioMimeType.Basic,
Extensions = new List<string> {"au", "snd"}
};
}
}
/// <summary>
/// Gets the midi audio mime type.
/// </summary>
public static AudioMime MidiAudio
{
get
{
return new AudioMime
{
AudioMimeType = AudioMimeType.Midi,
Extensions = new List<string> {"mid", "midi"}
};
}
}
/// <summary>
/// Gets the MPEG audio mime type.
/// </summary>
public static AudioMime MpegAudio
{
get
{
return new AudioMime
{
AudioMimeType = AudioMimeType.Mpeg,
Extensions = new List<string> {"mp2", "mp3", "mpa", "mpg", "mpga"}
};
}
}
/// <summary>
/// Gets the MPEG4 audio mime type.
/// </summary>
public static AudioMime Mpeg4Audio
{
get
{
return new AudioMime
{
AudioMimeType = AudioMimeType.Mpeg4,
Extensions = new List<string> {"mp4", "mp4a"}
};
}
}
/// <summary>
/// Gets the Ogg Vorbis audio mime type.
/// </summary>
public static AudioMime OggVorbisAudio
{
get
{
return new AudioMime
{
AudioMimeType = AudioMimeType.OggVorbis,
Extensions = new List<string> {"ogg"}
};
}
}
/// <summary>
/// Gets the Real Audio mime type.
/// </summary>
public static AudioMime RealAudio
{
get
{
return new AudioMime
{
AudioMimeType = AudioMimeType.RealAudio,
Extensions = new List<string> {"ra", "ram"}
};
}
}
/// <summary>
/// Gets the wav audio mime type.
/// </summary>
public static AudioMime WavAudio
{
get
{
return new AudioMime
{
AudioMimeType = AudioMimeType.Wav,
Extensions = new List<string> {"wav"}
};
}
}
/// <summary>
/// Gets the Windows Media audio mime type.
/// </summary>
public static AudioMime WindowsMediaAudio
{
get
{
return new AudioMime
{
AudioMimeType = AudioMimeType.WindowsMedia,
Extensions = new List<string> {"wma"}
};
}
}
#endregion
#region Image
/// <summary>
/// Gets the bitmap mime type.
/// </summary>
public static ImageMime Bitmap
{
get
{
return new ImageMime
{
ImageMimeType = ImageMimeType.Bitmap,
Extensions = new List<string> {"bmp"}
};
}
}
/// <summary>
/// Gets the icon mime type.
/// </summary>
public static ImageMime Icon
{
get
{
return new ImageMime
{
ImageMimeType = ImageMimeType.Icon,
Extensions = new List<string> {"ico"}
};
}
}
/// <summary>
/// Gets the JPEG mime type.
/// </summary>
public static ImageMime Jpeg
{
get
{
return new ImageMime
{
ImageMimeType = ImageMimeType.Jpeg,
Extensions = new List<string> {"jpg", "jpeg"}
};
}
}
/// <summary>
/// Gets the PNG mime type.
/// </summary>
public static ImageMime Png
{
get
{
return new ImageMime
{
ImageMimeType = ImageMimeType.Png,
Extensions = new List<string> {"png"}
};
}
}
/// <summary>
/// Gets the SVG mime type.
/// </summary>
public static ImageMime Svg
{
get
{
return new ImageMime
{
ImageMimeType = ImageMimeType.Svg,
Extensions = new List<string> {"svg"}
};
}
}
/// <summary>
/// Gets the TIFF mime type.
/// </summary>
public static ImageMime Tiff
{
get
{
return new ImageMime
{
ImageMimeType = ImageMimeType.Tiff,
Extensions = new List<string> {"tiff", "tif"}
};
}
}
public static ImageMime Gif
{
get
{
return new ImageMime
{
ImageMimeType = ImageMimeType.Gif,
Extensions = new List<string> { "gif" }
};
}
}
#endregion
#region Text
/// <summary>
/// Gets the Css mime type.
/// </summary>
public static TextMime Css
{
get
{
return new TextMime
{
TextMimeType = TextMimeType.CascadingStyleSheet,
Extensions = new List<string> {"css"}
};
}
}
/// <summary>
/// Gets the CSV mime type.
/// </summary>
public static TextMime Csv
{
get
{
return new TextMime
{
TextMimeType = TextMimeType.CommaSeperatedValues,
Extensions = new List<string> {"csv"}
};
}
}
/// <summary>
/// Gets the HTML mime type.
/// </summary>
public static TextMime Html
{
get
{
return new TextMime
{
TextMimeType = TextMimeType.Html,
Extensions = new List<string> {"htm", "html", "htmls"}
};
}
}
/// <summary>
/// Gets the plain text mime type.
/// </summary>
public static TextMime PlainText
{
get
{
return new TextMime
{
TextMimeType = TextMimeType.Plain,
Extensions = new List<string> {"txt", "text", "log"}
};
}
}
/// <summary>
/// Gets the XML mime type.
/// </summary>
public static TextMime Xml
{
get
{
return new TextMime
{
TextMimeType = TextMimeType.Xml,
Extensions = new List<string> {"xml"}
};
}
}
/// <summary>
/// Gets the RTF mime type.
/// </summary>
public static TextMime Rtf
{
get
{
return new TextMime
{
TextMimeType = TextMimeType.Rtf,
Extensions = new List<string> { "rtf" }
};
}
}
#endregion
#region Video
/// <summary>
/// Gets the AVI video mime type.
/// </summary>
public static VideoMime AviVideo
{
get
{
return new VideoMime
{
VideoMimeType = VideoMimeType.Avi,
Extensions = new List<string> {"avi"}
};
}
}
/// <summary>
/// Gets the flash video mime type.
/// </summary>
public static VideoMime FlashVideo
{
get
{
return new VideoMime
{
VideoMimeType = VideoMimeType.Flash,
Extensions = new List<string> {"flv"}
};
}
}
/// <summary>
/// Gets the MPEG video mime type.
/// </summary>
public static VideoMime MpegVideo
{
get
{
return new VideoMime
{
VideoMimeType = VideoMimeType.Mpeg,
Extensions = new List<string> {"mpg", "mpeg"}
};
}
}
/// <summary>
/// Gets the MPEG4 video mime type.
/// </summary>
public static VideoMime Mpeg4Video
{
get
{
return new VideoMime
{
VideoMimeType = VideoMimeType.Mpeg4,
Extensions = new List<string> {"mp4", "mp4a"}
};
}
}
/// <summary>
/// Gets the Quicktime video mime type.
/// </summary>
public static VideoMime QuicktimeVideo
{
get
{
return new VideoMime
{
VideoMimeType = VideoMimeType.Quicktime,
Extensions = new List<string> {"qt", "mov"}
};
}
}
/// <summary>
/// Gets the Windows Media video mime type.
/// </summary>
public static VideoMime WindowsMediaVideo
{
get
{
return new VideoMime
{
VideoMimeType = VideoMimeType.WindowsMedia,
Extensions = new List<string> {"wmv"}
};
}
}
#endregion
#region Messagae
public static MessageMime Mht
{
get
{
return new MessageMime
{
MessageMimeType = MessageMimeType.Mht,
Extensions = new List<string> { "mht" }
};
}
}
#endregion
/// <summary>
/// Generates common mime types
/// </summary>
/// <returns></returns>
public static IEnumerable<BaseMime> Generate()
{
var types = typeof (MimeTypes).GetProperties(BindingFlags.Public | BindingFlags.Static);
return types
.Select(type => type.GetGetMethod().Invoke(null, null))
.OfType<BaseMime>();
}
}
}
| |
// ------------------------------------------------------------------------------
// 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.
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 DriveRequest.
/// </summary>
public partial class DriveRequest : BaseRequest, IDriveRequest
{
/// <summary>
/// Constructs a new DriveRequest.
/// </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 DriveRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified Drive using POST.
/// </summary>
/// <param name="driveToCreate">The Drive to create.</param>
/// <returns>The created Drive.</returns>
public System.Threading.Tasks.Task<Drive> CreateAsync(Drive driveToCreate)
{
return this.CreateAsync(driveToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified Drive using POST.
/// </summary>
/// <param name="driveToCreate">The Drive to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created Drive.</returns>
public async System.Threading.Tasks.Task<Drive> CreateAsync(Drive driveToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<Drive>(driveToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified Drive.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified Drive.
/// </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<Drive>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified Drive.
/// </summary>
/// <returns>The Drive.</returns>
public System.Threading.Tasks.Task<Drive> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified Drive.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The Drive.</returns>
public async System.Threading.Tasks.Task<Drive> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<Drive>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified Drive using PATCH.
/// </summary>
/// <param name="driveToUpdate">The Drive to update.</param>
/// <returns>The updated Drive.</returns>
public System.Threading.Tasks.Task<Drive> UpdateAsync(Drive driveToUpdate)
{
return this.UpdateAsync(driveToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified Drive using PATCH.
/// </summary>
/// <param name="driveToUpdate">The Drive to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated Drive.</returns>
public async System.Threading.Tasks.Task<Drive> UpdateAsync(Drive driveToUpdate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<Drive>(driveToUpdate, 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 IDriveRequest 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 IDriveRequest Expand(Expression<Func<Drive, 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 IDriveRequest 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 IDriveRequest Select(Expression<Func<Drive, 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="driveToInitialize">The <see cref="Drive"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(Drive driveToInitialize)
{
if (driveToInitialize != null && driveToInitialize.AdditionalData != null)
{
if (driveToInitialize.Items != null && driveToInitialize.Items.CurrentPage != null)
{
driveToInitialize.Items.AdditionalData = driveToInitialize.AdditionalData;
object nextPageLink;
driveToInitialize.AdditionalData.TryGetValue("items@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
driveToInitialize.Items.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
}
if (driveToInitialize.Special != null && driveToInitialize.Special.CurrentPage != null)
{
driveToInitialize.Special.AdditionalData = driveToInitialize.AdditionalData;
object nextPageLink;
driveToInitialize.AdditionalData.TryGetValue("special@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
driveToInitialize.Special.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
}
}
}
}
}
| |
// ---------------------------------------------------------------------------------------------
#region // Copyright (c) 2013, SIL International. All Rights Reserved.
// <copyright from='2013' to='2013' company='SIL International'>
// Copyright (c) 2013, SIL International. All Rights Reserved.
//
// Distributable under the terms of either the Common Public License or the
// GNU Lesser General Public License, as specified in the LICENSING.txt file.
// </copyright>
#endregion
// ---------------------------------------------------------------------------------------------
namespace PalasoUIWindowsForms.TestApp
{
/// ----------------------------------------------------------------------------------------
/// <summary>
///
/// </summary>
/// ----------------------------------------------------------------------------------------
partial class TestAppForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
Palaso.UI.WindowsForms.SuperToolTip.SuperToolTipInfoWrapper superToolTipInfoWrapper1 = new Palaso.UI.WindowsForms.SuperToolTip.SuperToolTipInfoWrapper();
Palaso.UI.WindowsForms.SuperToolTip.SuperToolTipInfo superToolTipInfo1 = new Palaso.UI.WindowsForms.SuperToolTip.SuperToolTipInfo();
this.btnFolderBrowserControl = new System.Windows.Forms.Button();
this.btnLookupISOCodeDialog = new System.Windows.Forms.Button();
this.btnWritingSystemSetupDialog = new System.Windows.Forms.Button();
this.btnArtOfReading = new System.Windows.Forms.Button();
this.btnSilAboutBox = new System.Windows.Forms.Button();
this.btnShowReleaseNotes = new System.Windows.Forms.Button();
this.superToolTip1 = new Palaso.UI.WindowsForms.SuperToolTip.SuperToolTip(this.components);
this.label1 = new System.Windows.Forms.Label();
this.btnMetaDataEditor = new System.Windows.Forms.Button();
this._silAboutBoxGecko = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// btnFolderBrowserControl
//
this.btnFolderBrowserControl.Location = new System.Drawing.Point(12, 12);
this.btnFolderBrowserControl.Name = "btnFolderBrowserControl";
this.btnFolderBrowserControl.Size = new System.Drawing.Size(157, 23);
this.btnFolderBrowserControl.TabIndex = 0;
this.btnFolderBrowserControl.Text = "FolderBrowserControl";
this.btnFolderBrowserControl.UseVisualStyleBackColor = true;
this.btnFolderBrowserControl.Click += new System.EventHandler(this.OnFolderBrowserControlClicked);
//
// btnLookupISOCodeDialog
//
this.btnLookupISOCodeDialog.Location = new System.Drawing.Point(12, 41);
this.btnLookupISOCodeDialog.Name = "btnLookupISOCodeDialog";
this.btnLookupISOCodeDialog.Size = new System.Drawing.Size(157, 23);
this.btnLookupISOCodeDialog.TabIndex = 0;
this.btnLookupISOCodeDialog.Text = "LookupISOCodeDialog";
this.btnLookupISOCodeDialog.UseVisualStyleBackColor = true;
this.btnLookupISOCodeDialog.Click += new System.EventHandler(this.OnLookupISOCodeDialogClicked);
//
// btnWritingSystemSetupDialog
//
this.btnWritingSystemSetupDialog.Location = new System.Drawing.Point(12, 70);
this.btnWritingSystemSetupDialog.Name = "btnWritingSystemSetupDialog";
this.btnWritingSystemSetupDialog.Size = new System.Drawing.Size(157, 23);
this.btnWritingSystemSetupDialog.TabIndex = 0;
this.btnWritingSystemSetupDialog.Text = "WritingSystemSetupDialog";
this.btnWritingSystemSetupDialog.UseVisualStyleBackColor = true;
this.btnWritingSystemSetupDialog.Click += new System.EventHandler(this.OnWritingSystemSetupDialogClicked);
//
// btnArtOfReading
//
this.btnArtOfReading.Location = new System.Drawing.Point(12, 99);
this.btnArtOfReading.Name = "btnArtOfReading";
this.btnArtOfReading.Size = new System.Drawing.Size(157, 23);
this.btnArtOfReading.TabIndex = 0;
this.btnArtOfReading.Text = "ArtOfReading";
this.btnArtOfReading.UseVisualStyleBackColor = true;
this.btnArtOfReading.Click += new System.EventHandler(this.OnArtOfReadingClicked);
//
// btnSilAboutBox
//
this.btnSilAboutBox.Location = new System.Drawing.Point(12, 128);
this.btnSilAboutBox.Name = "btnSilAboutBox";
this.btnSilAboutBox.Size = new System.Drawing.Size(157, 23);
this.btnSilAboutBox.TabIndex = 0;
this.btnSilAboutBox.Text = "SIL AboutBox";
this.btnSilAboutBox.UseVisualStyleBackColor = true;
this.btnSilAboutBox.Click += new System.EventHandler(this.OnSilAboutBoxClicked);
//
// btnShowReleaseNotes
//
this.btnShowReleaseNotes.Location = new System.Drawing.Point(12, 185);
this.btnShowReleaseNotes.Name = "btnShowReleaseNotes";
this.btnShowReleaseNotes.Size = new System.Drawing.Size(157, 23);
this.btnShowReleaseNotes.TabIndex = 0;
this.btnShowReleaseNotes.Text = "Show Release Notes";
this.btnShowReleaseNotes.UseVisualStyleBackColor = true;
this.btnShowReleaseNotes.Click += new System.EventHandler(this.OnShowReleaseNotesClicked);
//
// superToolTip1
//
this.superToolTip1.FadingInterval = 10;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 246);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(149, 13);
superToolTipInfo1.BackgroundGradientBegin = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(0)))));
superToolTipInfo1.BackgroundGradientEnd = System.Drawing.Color.Blue;
superToolTipInfo1.BackgroundGradientMiddle = System.Drawing.Color.FromArgb(((int)(((byte)(242)))), ((int)(((byte)(246)))), ((int)(((byte)(251)))));
superToolTipInfo1.BodyText = "This is the body text";
superToolTipInfo1.FooterForeColor = System.Drawing.Color.Lime;
superToolTipInfo1.FooterText = "And this is the footer";
superToolTipInfo1.HeaderForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(0)))), ((int)(((byte)(0)))));
superToolTipInfo1.HeaderText = "The header can serve as a title";
superToolTipInfo1.OffsetForWhereToDisplay = new System.Drawing.Point(0, 0);
superToolTipInfo1.ShowFooter = true;
superToolTipInfo1.ShowFooterSeparator = true;
superToolTipInfoWrapper1.SuperToolTipInfo = superToolTipInfo1;
superToolTipInfoWrapper1.UseSuperToolTip = true;
this.superToolTip1.SetSuperStuff(this.label1, superToolTipInfoWrapper1);
this.label1.TabIndex = 1;
this.label1.Text = "Hover over me to see a tooltip";
//
// btnMetaDataEditor
//
this.btnMetaDataEditor.Location = new System.Drawing.Point(12, 214);
this.btnMetaDataEditor.Name = "btnMetaDataEditor";
this.btnMetaDataEditor.Size = new System.Drawing.Size(157, 23);
this.btnMetaDataEditor.TabIndex = 0;
this.btnMetaDataEditor.Text = "Meta Data Editor";
this.btnMetaDataEditor.UseVisualStyleBackColor = true;
this.btnMetaDataEditor.Click += new System.EventHandler(this.OnShowMetaDataEditorClicked);
//
// _silAboutBoxGecko
//
this._silAboutBoxGecko.Location = new System.Drawing.Point(12, 157);
this._silAboutBoxGecko.Name = "_silAboutBoxGecko";
this._silAboutBoxGecko.Size = new System.Drawing.Size(157, 23);
this._silAboutBoxGecko.TabIndex = 2;
this._silAboutBoxGecko.Text = "SIL AboutBox (Gecko)";
this._silAboutBoxGecko.UseVisualStyleBackColor = true;
this._silAboutBoxGecko.Click += new System.EventHandler(this.OnSilAboutBoxGeckoClicked);
//
// TestAppForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(187, 268);
this.Controls.Add(this._silAboutBoxGecko);
this.Controls.Add(this.label1);
this.Controls.Add(this.btnMetaDataEditor);
this.Controls.Add(this.btnShowReleaseNotes);
this.Controls.Add(this.btnSilAboutBox);
this.Controls.Add(this.btnArtOfReading);
this.Controls.Add(this.btnWritingSystemSetupDialog);
this.Controls.Add(this.btnLookupISOCodeDialog);
this.Controls.Add(this.btnFolderBrowserControl);
this.Name = "TestAppForm";
this.Text = "PalasoUIWindowsForms.TestApp";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnFolderBrowserControl;
private System.Windows.Forms.Button btnLookupISOCodeDialog;
private System.Windows.Forms.Button btnWritingSystemSetupDialog;
private System.Windows.Forms.Button btnArtOfReading;
private System.Windows.Forms.Button btnSilAboutBox;
private System.Windows.Forms.Button btnShowReleaseNotes;
private Palaso.UI.WindowsForms.SuperToolTip.SuperToolTip superToolTip1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button btnMetaDataEditor;
private System.Windows.Forms.Button _silAboutBoxGecko;
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
// ERROR: Not supported in C#: OptionDeclaration
namespace _4PosBackOffice.NET
{
internal partial class frmRPfilter : System.Windows.Forms.Form
{
string gFilter;
string gFilterSQL;
string gReport;
private void loadLanguage()
{
//frmRPfilter = No Code [Select the filter for your Report]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then frmRPfilter.Caption = rsLang("LanguageLayoutLnk_Description"): frmRPfilter.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//lblHeading = No Code [Using the "Stock Item Selector"...]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then lblHeading.Caption = rsLang("LanguageLayoutLnk_Description"): lblHeading.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1006;
//Filter|Checked
if (modRecordSet.rsLang.RecordCount){cmdNamespace.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdNamespace.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1085;
//Print|Checked
if (modRecordSet.rsLang.RecordCount){cmdPrint.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdPrint.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004;
//Exit|Checked
if (modRecordSet.rsLang.RecordCount){cmdExit.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdExit.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'";
//UPGRADE_ISSUE: Form property frmRPfilter.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
if (modRecordSet.rsHelp.RecordCount)
this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value;
}
public void loadItem(ref string Report)
{
getNamespace();
switch (Strings.LCase(Report)) {
case "recipe":
gReport = Report;
this.Text = "Bill Of Material Listing";
gFilter = "stockitem";
System.Windows.Forms.Application.DoEvents();
getNamespace();
loadLanguage();
ShowDialog();
break;
case "stockitemgrouping":
gReport = Report;
this.Text = "Stock Item Grouping Details";
gFilter = "stockitem";
System.Windows.Forms.Application.DoEvents();
getNamespace();
loadLanguage();
ShowDialog();
break;
case "stockitemorderlevels":
gReport = Report;
this.Text = "Stock Item Re-order Levels";
gFilter = "stockitem";
System.Windows.Forms.Application.DoEvents();
getNamespace();
loadLanguage();
ShowDialog();
break;
}
}
private void cmdExit_Click(System.Object eventSender, System.EventArgs eventArgs)
{
this.Close();
}
private void cmdNamespace_Click(System.Object eventSender, System.EventArgs eventArgs)
{
My.MyProject.Forms.frmFilter.loadFilter(ref gFilter);
getNamespace();
}
private void cmdPrint_Click(System.Object eventSender, System.EventArgs eventArgs)
{
switch (Strings.LCase(gReport)) {
case "recipe":
modApplication.report_BOM(ref gFilterSQL);
break;
case "stockitemgrouping":
stockitemGroup();
break;
case "stockitemorderlevels":
stockitemOrderLevels();
break;
}
}
private void frmRPfilter_Load(System.Object eventSender, System.EventArgs eventArgs)
{
getNamespace();
}
private void frmRPfilter_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
switch (KeyAscii) {
case System.Windows.Forms.Keys.Escape:
this.Close();
KeyAscii = 0;
break;
}
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void getNamespace()
{
if (string.IsNullOrEmpty(gFilter)) {
this.lblHeading.Text = "";
} else {
My.MyProject.Forms.frmFilter.buildCriteria(ref gFilter);
this.lblHeading.Text = My.MyProject.Forms.frmFilter.gHeading;
}
gFilterSQL = My.MyProject.Forms.frmFilter.gCriteria;
}
private void stockitemGroup()
{
CrystalDecisions.CrystalReports.Engine.ReportDocument Report = default(CrystalDecisions.CrystalReports.Engine.ReportDocument);
ADODB.Recordset rs = default(ADODB.Recordset);
string sql = null;
Report.Load("cryStockItemGrouping.rpt");
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
rs = modRecordSet.getRS(ref "SELECT * FROM Company");
Report.SetParameterValue("txtCompanyName", rs.Fields("Company_Name"));
Report.SetParameterValue("txtTitle", this.Text);
Report.SetParameterValue("txtFilter", this.lblHeading.Text);
rs.Close();
sql = "SELECT StockItem.StockItemID, StockItem.StockItem_Name, StockItem.StockItem_ReceiptName, StockItem.StockItem_Quantity, StockItem.StockItem_ListCost , Deposit.Deposit_Name, StockGroup.StockGroup_Name, Shrink.Shrink_Name, Supplier.Supplier_Name, PricingGroup.PricingGroup_Name FROM (((Deposit INNER JOIN (StockItem INNER JOIN Supplier ON StockItem.StockItem_SupplierID = Supplier.SupplierID) ON Deposit.DepositID = StockItem.StockItem_DepositID) INNER JOIN PricingGroup ON StockItem.StockItem_PricingGroupID = PricingGroup.PricingGroupID) INNER JOIN StockGroup ON StockItem.StockItem_StockGroupID = StockGroup.StockGroupID) INNER JOIN Shrink ON StockItem.StockItem_ShrinkID = Shrink.ShrinkID ";
sql = sql + gFilterSQL + " ORDER BY StockItem.StockItem_Name;";
rs = modRecordSet.getRS(ref sql);
CrystalDecisions.CrystalReports.Engine.ReportDocument ReportNone = default(CrystalDecisions.CrystalReports.Engine.ReportDocument);
ReportNone.Load("cryNoRecords.rpt");
if (rs.BOF | rs.EOF) {
ReportNone.SetParameterValue("txtCompanyName", Report.ParameterFields("txtCompanyName").ToString);
ReportNone.SetParameterValue("txtTitle", Report.ParameterFields("txtTitle").ToString);
My.MyProject.Forms.frmReportShow.Text = ReportNone.ParameterFields("txtTitle").ToString;
My.MyProject.Forms.frmReportShow.CRViewer1.ReportSource = ReportNone;
My.MyProject.Forms.frmReportShow.mReport = ReportNone;
My.MyProject.Forms.frmReportShow.sMode = "0";
My.MyProject.Forms.frmReportShow.CRViewer1.Refresh();
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
My.MyProject.Forms.frmReportShow.ShowDialog();
return;
}
//Report.Database.SetDataSource(rs, 3)
Report.Database.Tables(1).SetDataSource(rs);
//Report.VerifyOnEveryPrint = True
My.MyProject.Forms.frmReportShow.Text = Report.ParameterFields("txtTitle").ToString;
My.MyProject.Forms.frmReportShow.CRViewer1.ReportSource = Report;
My.MyProject.Forms.frmReportShow.mReport = Report;
My.MyProject.Forms.frmReportShow.sMode = "0";
My.MyProject.Forms.frmReportShow.CRViewer1.Refresh();
//UPGRADE_WARNING: Screen property Screen.MousePointer has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6BA9B8D2-2A32-4B6E-8D36-44949974A5B4"'
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
My.MyProject.Forms.frmReportShow.ShowDialog();
}
private void stockitemOrderLevels()
{
CrystalDecisions.CrystalReports.Engine.ReportDocument Report = default(CrystalDecisions.CrystalReports.Engine.ReportDocument);
ADODB.Recordset rs = default(ADODB.Recordset);
string sql = null;
Report.Load("cryStockItemORderLevels.rpt");
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
rs = modRecordSet.getRS(ref "SELECT * FROM Company");
Report.SetParameterValue("txtCompanyName", rs.Fields("Company_Name"));
Report.SetParameterValue("txtTitle", this.Text);
Report.SetParameterValue("txtFilter", this.lblHeading.Text);
rs.Close();
sql = "SELECT StockItem.StockItemID, StockItem.StockItem_Name, StockItem.StockItem_Quantity, StockItem.StockItem_MinimumStock, [StockItem_MinimumStock]/[StockItem_Quantity] AS minimumCase, StockItem.StockItem_OrderQuantity, StockItem.StockItem_OrderRounding, StockItem.StockItem_OrderDynamic, [StockItem_Quantity]=[StockItem_OrderQuantity] AS brokenPack FROM StockItem ";
sql = sql + gFilterSQL + " ORDER BY StockItem.StockItem_Name;";
rs = modRecordSet.getRS(ref sql);
CrystalDecisions.CrystalReports.Engine.ReportDocument ReportNone = default(CrystalDecisions.CrystalReports.Engine.ReportDocument);
ReportNone.Load("cryNoRecords.rpt");
if (rs.BOF | rs.EOF) {
ReportNone.SetParameterValue("txtCompanyName", Report.ParameterFields("txtCompanyName").ToString);
ReportNone.SetParameterValue("txtTitle", Report.ParameterFields("txtTitle").ToString);
My.MyProject.Forms.frmReportShow.Text = ReportNone.ParameterFields("txtTitle").ToString;
My.MyProject.Forms.frmReportShow.CRViewer1.ReportSource = ReportNone;
My.MyProject.Forms.frmReportShow.CRViewer1.Refresh();
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
My.MyProject.Forms.frmReportShow.ShowDialog();
return;
}
//Report.Database.SetDataSource(rs, 3)
Report.Database.Tables(1).SetDataSource(rs);
//Report.VerifyOnEveryPrint = True
My.MyProject.Forms.frmReportShow.Text = Report.ParameterFields("txtTitle").ToString;
My.MyProject.Forms.frmReportShow.CRViewer1.ReportSource = Report;
My.MyProject.Forms.frmReportShow.CRViewer1.Refresh();
//UPGRADE_WARNING: Screen property Screen.MousePointer has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6BA9B8D2-2A32-4B6E-8D36-44949974A5B4"'
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
My.MyProject.Forms.frmReportShow.ShowDialog();
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="TimeoutsSpec.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Akka.Streams.Dsl;
using Akka.Streams.TestKit;
using Akka.Streams.TestKit.Tests;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
using TestPublisher = Akka.Streams.TestKit.TestPublisher;
namespace Akka.Streams.Tests.Implementation
{
public class TimeoutsSpec : AkkaSpec
{
private ActorMaterializer Materializer { get; }
public TimeoutsSpec(ITestOutputHelper helper = null) : base(helper)
{
Materializer = ActorMaterializer.Create(Sys);
}
[Fact]
public void InitialTimeout_must_pass_through_elements_unmodified()
{
this.AssertAllStagesStopped(() =>
{
var t = Source.From(Enumerable.Range(1, 100))
.InitialTimeout(TimeSpan.FromSeconds(2)).Grouped(200)
.RunWith(Sink.First<IEnumerable<int>>(), Materializer);
t.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
t.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 100));
}, Materializer);
}
[Fact]
public void InitialTimeout_must_pass_through_error_unmodified()
{
this.AssertAllStagesStopped(() =>
{
var task = Source.From(Enumerable.Range(1, 100))
.Concat(Source.Failed<int>(new TestException("test")))
.InitialTimeout(TimeSpan.FromSeconds(2)).Grouped(200)
.RunWith(Sink.First<IEnumerable<int>>(), Materializer);
task.Invoking(t => t.Wait(TimeSpan.FromSeconds(3)))
.ShouldThrow<TestException>().WithMessage("test");
}, Materializer);
}
[Fact]
public void InitialTimeout_must_fail_if_no_initial_element_passes_until_timeout()
{
this.AssertAllStagesStopped(() =>
{
var downstreamProbe = this.CreateProbe<int>();
Source.Maybe<int>()
.InitialTimeout(TimeSpan.FromSeconds(1))
.RunWith(Sink.FromSubscriber(downstreamProbe), Materializer);
downstreamProbe.ExpectSubscription();
downstreamProbe.ExpectNoMsg(TimeSpan.FromMilliseconds(500));
var ex = downstreamProbe.ExpectError();
ex.Message.Should().Be($"The first element has not yet passed through in {TimeSpan.FromSeconds(1)}.");
}, Materializer);
}
[Fact]
public void CompletionTimeout_must_pass_through_elemnts_unmodified()
{
this.AssertAllStagesStopped(() =>
{
var t = Source.From(Enumerable.Range(1, 100))
.CompletionTimeout(TimeSpan.FromSeconds(2)).Grouped(200)
.RunWith(Sink.First<IEnumerable<int>>(), Materializer);
t.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
t.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 100));
}, Materializer);
}
[Fact]
public void CompletionTimeout_must_pass_through_error_unmodified()
{
this.AssertAllStagesStopped(() =>
{
var task = Source.From(Enumerable.Range(1, 100))
.Concat(Source.Failed<int>(new TestException("test")))
.CompletionTimeout(TimeSpan.FromSeconds(2)).Grouped(200)
.RunWith(Sink.First<IEnumerable<int>>(), Materializer);
task.Invoking(t => t.Wait(TimeSpan.FromSeconds(3)))
.ShouldThrow<TestException>().WithMessage("test");
}, Materializer);
}
[Fact]
public void CompletionTimeout_must_fail_if_not_completed_until_timeout()
{
this.AssertAllStagesStopped(() =>
{
var upstreamProbe = TestPublisher.CreateProbe<int>(this);
var downstreamProbe = this.CreateProbe<int>();
Source.FromPublisher<int>(upstreamProbe)
.CompletionTimeout(TimeSpan.FromSeconds(2))
.RunWith(Sink.FromSubscriber(downstreamProbe), Materializer);
upstreamProbe.SendNext(1);
downstreamProbe.RequestNext(1);
downstreamProbe.ExpectNoMsg(TimeSpan.FromMilliseconds(500)); // No timeout yet
upstreamProbe.SendNext(2);
downstreamProbe.RequestNext(2);
downstreamProbe.ExpectNoMsg(TimeSpan.FromMilliseconds(500)); // No timeout yet
var ex = downstreamProbe.ExpectError();
ex.Message.Should().Be($"The stream has not been completed in {TimeSpan.FromSeconds(2)}.");
}, Materializer);
}
[Fact]
public void IdleTimeout_must_pass_through_elements_unmodified()
{
this.AssertAllStagesStopped(() =>
{
var t = Source.From(Enumerable.Range(1, 100))
.IdleTimeout(TimeSpan.FromSeconds(2)).Grouped(200)
.RunWith(Sink.First<IEnumerable<int>>(), Materializer);
t.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
t.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 100));
}, Materializer);
}
[Fact]
public void IdleTimeout_must_pass_through_error_unmodified()
{
this.AssertAllStagesStopped(() =>
{
var task = Source.From(Enumerable.Range(1, 100))
.Concat(Source.Failed<int>(new TestException("test")))
.IdleTimeout(TimeSpan.FromSeconds(2)).Grouped(200)
.RunWith(Sink.First<IEnumerable<int>>(), Materializer);
task.Invoking(t => t.Wait(TimeSpan.FromSeconds(3)))
.ShouldThrow<TestException>().WithMessage("test");
}, Materializer);
}
[Fact]
public void IdleTimeout_must_fail_if_time_between_elements_is_too_large()
{
this.AssertAllStagesStopped(() =>
{
var upstreamProbe = TestPublisher.CreateProbe<int>(this);
var downstreamProbe = this.CreateProbe<int>();
Source.FromPublisher<int>(upstreamProbe)
.IdleTimeout(TimeSpan.FromSeconds(1))
.RunWith(Sink.FromSubscriber(downstreamProbe), Materializer);
// Two seconds in overall, but won't timeout until time between elements is large enough
// (i.e. this works differently from completionTimeout)
for (var i = 1; i <= 4; i++)
{
upstreamProbe.SendNext(1);
downstreamProbe.RequestNext(1);
downstreamProbe.ExpectNoMsg(TimeSpan.FromMilliseconds(500)); // No timeout yet
}
var ex = downstreamProbe.ExpectError();
ex.Message.Should().Be($"No elements passed in the last {TimeSpan.FromSeconds(1)}.");
}, Materializer);
}
[Fact]
public void IdleTimeoutBidi_must_not_signal_error_in_simple_loopback_case_and_pass_through_elements_unmodified()
{
this.AssertAllStagesStopped(() =>
{
var timeoutIdentity = BidiFlow.BidirectionalIdleTimeout<int, int>(TimeSpan.FromSeconds(2)).Join(Flow.Create<int>());
var t = Source.From(Enumerable.Range(1, 100))
.Via(timeoutIdentity).Grouped(200)
.RunWith(Sink.First<IEnumerable<int>>(), Materializer);
t.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
t.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 100));
}, Materializer);
}
[Fact]
public void IdleTimeoutBidi_must_not_signal_error_if_traffic_is_one_way()
{
this.AssertAllStagesStopped(() =>
{
var upstreamWriter = TestPublisher.CreateProbe<int>(this);
var downstreamWriter = TestPublisher.CreateProbe<string>(this);
var upstream = Flow.FromSinkAndSource(Sink.Ignore<string>(),
Source.FromPublisher<int>(upstreamWriter), Keep.Left);
var downstream = Flow.FromSinkAndSource(Sink.Ignore<int>(),
Source.FromPublisher<string>(downstreamWriter), Keep.Left);
var assembly = upstream.JoinMaterialized(
BidiFlow.BidirectionalIdleTimeout<int, string>(TimeSpan.FromSeconds(2)),
Keep.Left).JoinMaterialized(downstream, Keep.Both);
var r = assembly.Run(Materializer);
var upFinished = r.Item1;
var downFinished = r.Item2;
upstreamWriter.SendNext(1);
Thread.Sleep(1000);
upstreamWriter.SendNext(1);
Thread.Sleep(1000);
upstreamWriter.SendNext(1);
Thread.Sleep(1000);
upstreamWriter.SendComplete();
downstreamWriter.SendComplete();
upFinished.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
downFinished.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
}, Materializer);
}
[Fact]
public void IdleTimeoutBidi_must_be_able_to_signal_timeout_once_no_traffic_on_either_sides()
{
this.AssertAllStagesStopped(() =>
{
var upWrite = TestPublisher.CreateProbe<string>(this);
var upRead = TestSubscriber.CreateProbe<int>(this);
var downWrite = TestPublisher.CreateProbe<int>(this);
var downRead = TestSubscriber.CreateProbe<string>(this);
RunnableGraph.FromGraph(GraphDsl.Create(b =>
{
var timeoutStage = b.Add(BidiFlow.BidirectionalIdleTimeout<string, int>(TimeSpan.FromSeconds(2)));
b.From(Source.FromPublisher<string>(upWrite)).To(timeoutStage.Inlet1);
b.From(timeoutStage.Outlet1).To(Sink.FromSubscriber(downRead));
b.From(timeoutStage.Outlet2).To(Sink.FromSubscriber(upRead));
b.From(Source.FromPublisher<int>(downWrite)).To(timeoutStage.Inlet2);
return ClosedShape.Instance;
})).Run(Materializer);
// Request enough for the whole test
upRead.Request(100);
downRead.Request(100);
upWrite.SendNext("DATA1");
downRead.ExpectNext("DATA1");
Thread.Sleep(1500);
downWrite.SendNext(1);
upRead.ExpectNext(1);
Thread.Sleep(1500);
upWrite.SendNext("DATA2");
downRead.ExpectNext("DATA2");
Thread.Sleep(1000);
downWrite.SendNext(2);
upRead.ExpectNext(2);
upRead.ExpectNoMsg(TimeSpan.FromMilliseconds(500));
var error1 = upRead.ExpectError();
var error2 = downRead.ExpectError();
error1.Should().BeOfType<TimeoutException>();
error1.Message.Should().Be($"No elements passed in the last {TimeSpan.FromSeconds(2)}.");
error2.ShouldBeEquivalentTo(error1);
upWrite.ExpectCancellation();
downWrite.ExpectCancellation();
}, Materializer);
}
[Fact]
public void IdleTimeoutBidi_must_signal_error_to_all_outputs()
{
this.AssertAllStagesStopped(() =>
{
var upWrite = TestPublisher.CreateProbe<string>(this);
var upRead = TestSubscriber.CreateProbe<int>(this);
var downWrite = TestPublisher.CreateProbe<int>(this);
var downRead = TestSubscriber.CreateProbe<string>(this);
RunnableGraph.FromGraph(GraphDsl.Create(b =>
{
var timeoutStage = b.Add(BidiFlow.BidirectionalIdleTimeout<string, int>(TimeSpan.FromSeconds(2)));
b.From(Source.FromPublisher<string>(upWrite)).To(timeoutStage.Inlet1);
b.From(timeoutStage.Outlet1).To(Sink.FromSubscriber(downRead));
b.From(timeoutStage.Outlet2).To(Sink.FromSubscriber(upRead));
b.From(Source.FromPublisher<int>(downWrite)).To(timeoutStage.Inlet2);
return ClosedShape.Instance;
})).Run(Materializer);
var te = new TestException("test");
upWrite.SendError(te);
upRead.ExpectSubscriptionAndError().ShouldBeEquivalentTo(te);
downRead.ExpectSubscriptionAndError().ShouldBeEquivalentTo(te);
downWrite.ExpectCancellation();
}, Materializer);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using BetMania.Services.Areas.HelpPage.Models;
namespace BetMania.Services.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 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 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)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(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}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
//! \file ArcPCF.cs
//! \date Fri Sep 30 10:37:28 2016
//! \brief Primel the Adventure System resource archive.
//
// Copyright (C) 2016-2017 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using GameRes.Utility;
namespace GameRes.Formats.Primel
{
internal class PcfEntry : PackedEntry
{
public uint Flags;
public byte[] Key;
}
internal class PcfArchive : ArcFile
{
public readonly PrimelScheme Scheme;
public PcfArchive (ArcView arc, ArchiveFormat impl, ICollection<Entry> dir, PrimelScheme scheme)
: base (arc, impl, dir)
{
Scheme = scheme;
}
}
[Export(typeof(ArchiveFormat))]
public class PcfOpener : ArchiveFormat
{
public override string Tag { get { return "PCF"; } }
public override string Description { get { return "Primel ADV System resource archive"; } }
public override uint Signature { get { return 0x6B636150; } } // 'Pack'
public override bool IsHierarchic { get { return true; } }
public override bool CanWrite { get { return false; } }
public override ArcFile TryOpen (ArcView file)
{
if (!file.View.AsciiEqual (4, "Code"))
return null;
int count = file.View.ReadInt32 (8);
if (!IsSaneCount (count))
return null;
var reader = new PcfIndexReader (file, count);
var dir = reader.Read();
if (null == dir)
return null;
return new PcfArchive (file, this, dir, reader.Scheme);
}
public override Stream OpenEntry (ArcFile arc, Entry entry)
{
var parc = arc as PcfArchive;
var pent = entry as PcfEntry;
if (null == pent || null == parc)
return base.OpenEntry (arc, entry);
Stream input = arc.File.CreateStream (entry.Offset, entry.Size);
try
{
input = parc.Scheme.TransformStream (input, pent.Key, pent.Flags);
if (pent.IsPacked)
input = new LimitStream (input, pent.UnpackedSize);
return input;
}
catch
{
input.Dispose();
throw;
}
}
}
internal sealed class PcfIndexReader
{
ArcView m_file;
int m_count;
long m_base_offset;
List<Entry> m_dir;
public PrimelScheme Scheme { get; set; }
public PcfIndexReader (ArcView file, int count)
{
m_file = file;
m_count = count;
m_dir = new List<Entry> (m_count);
}
static readonly PrimelScheme[] KnownSchemes = {
new PrimelScheme(), new PrimelSchemeV2()
};
public List<Entry> Read ()
{
long data_size = m_file.View.ReadInt64 (0x10);
long index_offset = m_file.View.ReadInt64 (0x28);
if (data_size >= m_file.MaxOffset || index_offset >= m_file.MaxOffset)
return null;
uint index_size = m_file.View.ReadUInt32 (0x30);
uint flags = m_file.View.ReadUInt32 (0x38);
var key = m_file.View.ReadBytes (0x58, 8);
m_base_offset = m_file.MaxOffset - data_size;
foreach (var scheme in KnownSchemes)
{
m_dir.Clear();
try
{
using (var stream = m_file.CreateStream (m_base_offset + index_offset, index_size))
using (var index = scheme.TransformStream (stream, key, flags))
{
if (ReadIndex (index))
{
this.Scheme = scheme;
return m_dir;
}
}
}
catch { /* invalid scheme, retry */ }
}
return null;
}
byte[] m_buffer = new byte[0x80];
bool ReadIndex (Stream index)
{
for (int i = 0; i < m_count; ++i)
{
if (m_buffer.Length != index.Read (m_buffer, 0, m_buffer.Length))
break;
var name = Binary.GetCString (m_buffer, 0, 0x50);
var entry = FormatCatalog.Instance.Create<PcfEntry> (name);
entry.Offset = LittleEndian.ToInt64 (m_buffer, 0x50) + m_base_offset;
entry.UnpackedSize = LittleEndian.ToUInt32 (m_buffer, 0x58);
entry.Size = LittleEndian.ToUInt32 (m_buffer, 0x60);
if (!entry.CheckPlacement (m_file.MaxOffset))
return false;
entry.Flags = LittleEndian.ToUInt32 (m_buffer, 0x68);
entry.Key = new ArraySegment<byte> (m_buffer, 0x78, 8).ToArray();
entry.IsPacked = entry.UnpackedSize != entry.Size;
m_dir.Add (entry);
}
return m_dir.Count > 0;
}
}
internal class PrimelScheme
{
public Stream TransformStream (Stream input, byte[] key, uint flags)
{
var key1 = GenerateKey (key);
var iv = GenerateKey (key1);
ICryptoTransform decryptor;
switch (flags & 0xF0000)
{
case 0x10000:
decryptor = new Primel1Encyption (key1, iv);
break;
case 0x20000:
decryptor = new Primel2Encyption (key1, iv);
break;
case 0x30000:
decryptor = new Primel3Encyption (key1, iv);
break;
case 0x80000: // RC6
decryptor = new GameRes.Cryptography.RC6 (key1, iv);
break;
case 0xA0000: // AES
using (var aes = Rijndael.Create())
{
aes.Mode = CipherMode.CFB;
aes.Padding = PaddingMode.Zeros;
decryptor = aes.CreateDecryptor (key1, iv);
}
break;
default: // not encrypted
return input;
}
input = new InputCryptoStream (input, decryptor);
try
{
if (0 != (flags & 0xFF))
{
input = new RangePackedStream (input);
}
switch (flags & 0xF00)
{
case 0x400:
input = new RlePackedStream (input);
input = new MtfPackedStream (input);
break;
case 0x700:
input = new LzssPackedStream (input);
break;
}
return input;
}
catch
{
input.Dispose();
throw;
}
}
byte[] GenerateKey (byte[] seed)
{
var hash = ComputeHash (seed);
var key = new byte[0x10];
for (int i = 0; i < hash.Length; ++i)
{
key[i & 0xF] ^= hash[i];
}
return key;
}
protected virtual byte[] ComputeHash (byte[] seed)
{
var sha = new Primel.SHA256();
return sha.ComputeHash (seed);
}
}
internal class PrimelSchemeV2 : PrimelScheme
{
protected override byte[] ComputeHash (byte[] seed)
{
using (var sha = System.Security.Cryptography.SHA256.Create())
return sha.ComputeHash (seed);
}
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ElasticLoadBalancing.Model
{
/// <summary>
/// Container for the parameters to the CreateLoadBalancer operation.
/// <para> Creates a new LoadBalancer. </para> <para> After the call has completed successfully, a new LoadBalancer is created; however, it will
/// not be usable until at least one instance has been registered. When the LoadBalancer creation is completed, the client can check whether or
/// not it is usable by using the DescribeInstanceHealth action. The LoadBalancer is usable as soon as any registered instance is
/// <i>InService</i> .
/// </para> <para><b>NOTE:</b> Currently, the client's quota of LoadBalancers is limited to ten per Region. </para> <para><b>NOTE:</b>
/// LoadBalancer DNS names vary depending on the Region they're created in. For LoadBalancers created in the United States, the DNS name ends
/// with: us-east-1.elb.amazonaws.com (for the US Standard Region) us-west-1.elb.amazonaws.com (for the Northern California Region) For
/// LoadBalancers created in the EU (Ireland) Region, the DNS name ends with: eu-west-1.elb.amazonaws.com </para> <para>For information on using
/// CreateLoadBalancer to create a new LoadBalancer in Amazon EC2, go to Using Query API section in the <i>Creating a Load Balancer With SSL
/// Cipher Settings and Back-end Authentication</i> topic of the <i>Elastic Load Balancing Developer Guide</i> .</para> <para>For information on
/// using CreateLoadBalancer to create a new LoadBalancer in Amazon VPC, go to Using Query API section in the <i>Creating a Basic Load Balancer
/// in Amazon VPC</i> topic of the <i>Elastic Load Balancing Developer Guide</i> .</para>
/// </summary>
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.CreateLoadBalancer"/>
public class CreateLoadBalancerRequest : AmazonWebServiceRequest
{
private string loadBalancerName;
private List<Listener> listeners = new List<Listener>();
private List<string> availabilityZones = new List<string>();
private List<string> subnets = new List<string>();
private List<string> securityGroups = new List<string>();
private string scheme;
/// <summary>
/// Default constructor for a new CreateLoadBalancerRequest object. Callers should use the
/// properties or fluent setter (With...) methods to initialize this object after creating it.
/// </summary>
public CreateLoadBalancerRequest() {}
/// <summary>
/// Constructs a new CreateLoadBalancerRequest object.
/// Callers should use the properties or fluent setter (With...) methods to
/// initialize any additional object members.
/// </summary>
///
/// <param name="loadBalancerName"> The name associated with the LoadBalancer. The name must be unique within your set of LoadBalancers.
/// </param>
public CreateLoadBalancerRequest(string loadBalancerName)
{
this.loadBalancerName = loadBalancerName;
}
/// <summary>
/// Constructs a new CreateLoadBalancerRequest object.
/// Callers should use the properties or fluent setter (With...) methods to
/// initialize any additional object members.
/// </summary>
///
/// <param name="loadBalancerName"> The name associated with the LoadBalancer. The name must be unique within your set of LoadBalancers.
/// </param>
/// <param name="listeners"> A list of the following tuples: LoadBalancerPort, InstancePort, and Protocol. </param>
/// <param name="availabilityZones"> A list of Availability Zones. At least one Availability Zone must be specified. Specified Availability
/// Zones must be in the same EC2 Region as the LoadBalancer. Traffic will be equally distributed across all zones. This list can be modified
/// after the creation of the LoadBalancer by calling <a>EnableAvailabilityZonesFroLoadBalancer</a>. </param>
public CreateLoadBalancerRequest(string loadBalancerName, List<Listener> listeners, List<string> availabilityZones)
{
this.loadBalancerName = loadBalancerName;
this.listeners = listeners;
this.availabilityZones = availabilityZones;
}
/// <summary>
/// The name associated with the LoadBalancer. The name must be unique within your set of LoadBalancers.
///
/// </summary>
public string LoadBalancerName
{
get { return this.loadBalancerName; }
set { this.loadBalancerName = value; }
}
/// <summary>
/// Sets the LoadBalancerName property
/// </summary>
/// <param name="loadBalancerName">The value to set for the LoadBalancerName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateLoadBalancerRequest WithLoadBalancerName(string loadBalancerName)
{
this.loadBalancerName = loadBalancerName;
return this;
}
// Check to see if LoadBalancerName property is set
internal bool IsSetLoadBalancerName()
{
return this.loadBalancerName != null;
}
/// <summary>
/// A list of the following tuples: LoadBalancerPort, InstancePort, and Protocol.
///
/// </summary>
public List<Listener> Listeners
{
get { return this.listeners; }
set { this.listeners = value; }
}
/// <summary>
/// Adds elements to the Listeners collection
/// </summary>
/// <param name="listeners">The values to add to the Listeners collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateLoadBalancerRequest WithListeners(params Listener[] listeners)
{
foreach (Listener element in listeners)
{
this.listeners.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the Listeners collection
/// </summary>
/// <param name="listeners">The values to add to the Listeners collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateLoadBalancerRequest WithListeners(IEnumerable<Listener> listeners)
{
foreach (Listener element in listeners)
{
this.listeners.Add(element);
}
return this;
}
// Check to see if Listeners property is set
internal bool IsSetListeners()
{
return this.listeners.Count > 0;
}
/// <summary>
/// A list of Availability Zones. At least one Availability Zone must be specified. Specified Availability Zones must be in the same EC2 Region
/// as the LoadBalancer. Traffic will be equally distributed across all zones. This list can be modified after the creation of the LoadBalancer
/// by calling <a>EnableAvailabilityZonesFroLoadBalancer</a>.
///
/// </summary>
public List<string> AvailabilityZones
{
get { return this.availabilityZones; }
set { this.availabilityZones = value; }
}
/// <summary>
/// Adds elements to the AvailabilityZones collection
/// </summary>
/// <param name="availabilityZones">The values to add to the AvailabilityZones collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateLoadBalancerRequest WithAvailabilityZones(params string[] availabilityZones)
{
foreach (string element in availabilityZones)
{
this.availabilityZones.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the AvailabilityZones collection
/// </summary>
/// <param name="availabilityZones">The values to add to the AvailabilityZones collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateLoadBalancerRequest WithAvailabilityZones(IEnumerable<string> availabilityZones)
{
foreach (string element in availabilityZones)
{
this.availabilityZones.Add(element);
}
return this;
}
// Check to see if AvailabilityZones property is set
internal bool IsSetAvailabilityZones()
{
return this.availabilityZones.Count > 0;
}
/// <summary>
/// A list of subnet IDs in your VPC to attach to your LoadBalancer.
///
/// </summary>
public List<string> Subnets
{
get { return this.subnets; }
set { this.subnets = value; }
}
/// <summary>
/// Adds elements to the Subnets collection
/// </summary>
/// <param name="subnets">The values to add to the Subnets collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateLoadBalancerRequest WithSubnets(params string[] subnets)
{
foreach (string element in subnets)
{
this.subnets.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the Subnets collection
/// </summary>
/// <param name="subnets">The values to add to the Subnets collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateLoadBalancerRequest WithSubnets(IEnumerable<string> subnets)
{
foreach (string element in subnets)
{
this.subnets.Add(element);
}
return this;
}
// Check to see if Subnets property is set
internal bool IsSetSubnets()
{
return this.subnets.Count > 0;
}
/// <summary>
/// The security groups assigned to your LoadBalancer within your VPC.
///
/// </summary>
public List<string> SecurityGroups
{
get { return this.securityGroups; }
set { this.securityGroups = value; }
}
/// <summary>
/// Adds elements to the SecurityGroups collection
/// </summary>
/// <param name="securityGroups">The values to add to the SecurityGroups collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateLoadBalancerRequest WithSecurityGroups(params string[] securityGroups)
{
foreach (string element in securityGroups)
{
this.securityGroups.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the SecurityGroups collection
/// </summary>
/// <param name="securityGroups">The values to add to the SecurityGroups collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateLoadBalancerRequest WithSecurityGroups(IEnumerable<string> securityGroups)
{
foreach (string element in securityGroups)
{
this.securityGroups.Add(element);
}
return this;
}
// Check to see if SecurityGroups property is set
internal bool IsSetSecurityGroups()
{
return this.securityGroups.Count > 0;
}
/// <summary>
/// The type of a LoadBalancer. By default, Elastic Load Balancing creates an Internet-facing LoadBalancer with a publicly resolvable DNS name,
/// which resolves to public IP addresses. Specify the value <c>internal</c> for this option to create an internal LoadBalancer with a DNS name
/// that resolves to private IP addresses. This option is only available for LoadBalancers attached to an Amazon VPC.
///
/// </summary>
public string Scheme
{
get { return this.scheme; }
set { this.scheme = value; }
}
/// <summary>
/// Sets the Scheme property
/// </summary>
/// <param name="scheme">The value to set for the Scheme property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateLoadBalancerRequest WithScheme(string scheme)
{
this.scheme = scheme;
return this;
}
// Check to see if Scheme property is set
internal bool IsSetScheme()
{
return this.scheme != null;
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.txt file at the root of this distribution.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using Microsoft.VisualStudio.Shell;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
namespace Microsoft.VisualStudio.Project.Automation
{
/// <summary>
/// This can navigate a collection object only (partial implementation of ProjectItems interface)
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[ComVisible(true), CLSCompliant(false)]
public class OANavigableProjectItems : EnvDTE.ProjectItems
{
#region fields
private OAProject project;
private IList<EnvDTE.ProjectItem> items;
private HierarchyNode nodeWithItems;
#endregion
#region properties
/// <summary>
/// Defines an internal list of project items
/// </summary>
internal IList<EnvDTE.ProjectItem> Items
{
get
{
return this.items;
}
}
/// <summary>
/// Defines a relationship to the associated project.
/// </summary>
internal OAProject Project
{
get
{
return this.project;
}
}
/// <summary>
/// Defines the node that contains the items
/// </summary>
internal HierarchyNode NodeWithItems
{
get
{
return this.nodeWithItems;
}
}
#endregion
#region ctor
/// <summary>
/// Constructor.
/// </summary>
/// <param name="project">The associated project.</param>
/// <param name="nodeWithItems">The node that defines the items.</param>
internal OANavigableProjectItems(OAProject project, HierarchyNode nodeWithItems)
{
this.project = project;
this.nodeWithItems = nodeWithItems;
this.items = this.GetListOfProjectItems();
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="project">The associated project.</param>
/// <param name="items">A list of items that will make up the items defined by this object.</param>
/// <param name="nodeWithItems">The node that defines the items.</param>
public OANavigableProjectItems(OAProject project, IList<EnvDTE.ProjectItem> items, HierarchyNode nodeWithItems)
{
this.items = items;
this.project = project;
this.nodeWithItems = nodeWithItems;
}
#endregion
#region EnvDTE.ProjectItems
/// <summary>
/// Gets a value indicating the number of objects in the collection.
/// </summary>
public virtual int Count
{
get
{
int count = 0;
ThreadHelper.JoinableTaskFactory.Run(async delegate
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
count = items.Count;
});
return count;
}
}
/// <summary>
/// Gets the immediate parent object of a ProjectItems collection.
/// </summary>
public virtual object Parent
{
get
{
return this.nodeWithItems.GetAutomationObject();
}
}
/// <summary>
/// Gets an enumeration indicating the type of object.
/// </summary>
public virtual string Kind
{
get
{
// TODO: Add OAProjectItems.Kind getter implementation
return null;
}
}
/// <summary>
/// Gets the top-level extensibility object.
/// </summary>
public virtual EnvDTE.DTE DTE
{
get
{
return ThreadHelper.JoinableTaskFactory.Run(async delegate
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
return (EnvDTE.DTE)this.project.DTE;
});
}
}
/// <summary>
/// Gets the project hosting the project item or items.
/// </summary>
public virtual EnvDTE.Project ContainingProject
{
get
{
return this.project;
}
}
/// <summary>
/// Adds one or more ProjectItem objects from a directory to the ProjectItems collection.
/// </summary>
/// <param name="directory">The directory from which to add the project item.</param>
/// <returns>A ProjectItem object.</returns>
public virtual EnvDTE.ProjectItem AddFromDirectory(string directory)
{
throw new NotImplementedException();
}
/// <summary>
/// Creates a new project item from an existing item template file and adds it to the project.
/// </summary>
/// <param name="fileName">The full path and file name of the template project file.</param>
/// <param name="name">The file name to use for the new project item.</param>
/// <returns>A ProjectItem object. </returns>
public virtual EnvDTE.ProjectItem AddFromTemplate(string fileName, string name)
{
throw new NotImplementedException();
}
/// <summary>
/// Creates a new folder in Solution Explorer.
/// </summary>
/// <param name="name">The name of the folder node in Solution Explorer.</param>
/// <param name="kind">The type of folder to add. The available values are based on vsProjectItemsKindConstants and vsProjectItemKindConstants</param>
/// <returns>A ProjectItem object.</returns>
public virtual EnvDTE.ProjectItem AddFolder(string name, string kind)
{
throw new NotImplementedException();
}
/// <summary>
/// Copies a source file and adds it to the project.
/// </summary>
/// <param name="filePath">The path and file name of the project item to be added.</param>
/// <returns>A ProjectItem object. </returns>
public virtual EnvDTE.ProjectItem AddFromFileCopy(string filePath)
{
throw new NotImplementedException();
}
/// <summary>
/// Adds a project item from a file that is installed in a project directory structure.
/// </summary>
/// <param name="fileName">The file name of the item to add as a project item. </param>
/// <returns>A ProjectItem object. </returns>
public virtual EnvDTE.ProjectItem AddFromFile(string fileName)
{
throw new NotImplementedException();
}
/// <summary>
/// Adds a project item which is a link to a file outside the project directory structure.
/// </summary>
/// <param name="fileName">The file to be linked to the project.</param>
/// <returns>A ProjectItem object.</returns>
public virtual EnvDTE.ProjectItem AddFileLink(string fileName)
{
throw new NotImplementedException();
}
/// <summary>
/// Get Project Item from index
/// </summary>
/// <param name="index">Either index by number (1-based) or by name can be used to get the item</param>
/// <returns>Project Item. null is return if invalid index is specified</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
public virtual EnvDTE.ProjectItem Item(object index)
{
return ThreadHelper.JoinableTaskFactory.Run(async delegate
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
if(index is int)
{
int realIndex = (int)index - 1;
if(realIndex >= 0 && realIndex < this.items.Count)
{
return (EnvDTE.ProjectItem)items[realIndex];
}
return null;
}
else if(index is string)
{
string name = (string)index;
foreach(EnvDTE.ProjectItem item in items)
{
if(String.Compare(item.Name, name, StringComparison.OrdinalIgnoreCase) == 0)
{
return item;
}
}
}
return null;
});
}
/// <summary>
/// Returns an enumeration for items in a collection.
/// </summary>
/// <returns>An IEnumerator for this object.</returns>
public virtual IEnumerator GetEnumerator()
{
if(this.items == null)
{
yield return null;
}
int count = items.Count;
for(int i = 0; i < count; i++)
{
yield return items[i];
}
}
#endregion
#region virtual methods
/// <summary>
/// Retrives a list of items associated with the current node.
/// </summary>
/// <returns>A List of project items</returns>
protected IList<EnvDTE.ProjectItem> GetListOfProjectItems()
{
return ThreadHelper.JoinableTaskFactory.Run(async delegate
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
List<EnvDTE.ProjectItem> list = new List<EnvDTE.ProjectItem>();
for (HierarchyNode child = this.NodeWithItems.FirstChild; child != null; child = child.NextSibling)
{
EnvDTE.ProjectItem item = child.GetAutomationObject() as EnvDTE.ProjectItem;
if (null != item)
{
list.Add(item);
}
}
return list;
});
}
#endregion
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmPackSizeList
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmPackSizeList() : base()
{
FormClosed += frmPackSizeList_FormClosed;
KeyPress += frmPackSizeList_KeyPress;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
private System.Windows.Forms.Button withEventsField_cmdNew;
public System.Windows.Forms.Button cmdNew {
get { return withEventsField_cmdNew; }
set {
if (withEventsField_cmdNew != null) {
withEventsField_cmdNew.Click -= cmdNew_Click;
}
withEventsField_cmdNew = value;
if (withEventsField_cmdNew != null) {
withEventsField_cmdNew.Click += cmdNew_Click;
}
}
}
private myDataGridView withEventsField_DataList1;
public myDataGridView DataList1 {
get { return withEventsField_DataList1; }
set {
if (withEventsField_DataList1 != null) {
withEventsField_DataList1.DoubleClick -= DataList1_DblClick;
withEventsField_DataList1.KeyPress -= DataList1_KeyPress;
}
withEventsField_DataList1 = value;
if (withEventsField_DataList1 != null) {
withEventsField_DataList1.DoubleClick += DataList1_DblClick;
withEventsField_DataList1.KeyPress += DataList1_KeyPress;
}
}
}
private System.Windows.Forms.TextBox withEventsField_txtSearch;
public System.Windows.Forms.TextBox txtSearch {
get { return withEventsField_txtSearch; }
set {
if (withEventsField_txtSearch != null) {
withEventsField_txtSearch.Enter -= txtSearch_Enter;
withEventsField_txtSearch.KeyDown -= txtSearch_KeyDown;
withEventsField_txtSearch.KeyPress -= txtSearch_KeyPress;
}
withEventsField_txtSearch = value;
if (withEventsField_txtSearch != null) {
withEventsField_txtSearch.Enter += txtSearch_Enter;
withEventsField_txtSearch.KeyDown += txtSearch_KeyDown;
withEventsField_txtSearch.KeyPress += txtSearch_KeyPress;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdExit;
public System.Windows.Forms.Button cmdExit {
get { return withEventsField_cmdExit; }
set {
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click -= cmdExit_Click;
}
withEventsField_cmdExit = value;
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click += cmdExit_Click;
}
}
}
public System.Windows.Forms.Label lbl;
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmPackSizeList));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this.cmdNew = new System.Windows.Forms.Button();
this.DataList1 = new myDataGridView();
this.txtSearch = new System.Windows.Forms.TextBox();
this.cmdExit = new System.Windows.Forms.Button();
this.lbl = new System.Windows.Forms.Label();
this.SuspendLayout();
this.ToolTip1.Active = true;
//CType(Me.DataList1, System.ComponentModel.ISupportInitialize).BeginInit()
this.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Text = "Select a Pack Size";
this.ClientSize = new System.Drawing.Size(259, 433);
this.Location = new System.Drawing.Point(3, 22);
this.ControlBox = false;
this.KeyPreview = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Enabled = true;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.HelpButton = false;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.Name = "frmPackSizeList";
this.cmdNew.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdNew.Text = "&New";
this.cmdNew.Size = new System.Drawing.Size(97, 52);
this.cmdNew.Location = new System.Drawing.Point(6, 375);
this.cmdNew.TabIndex = 4;
this.cmdNew.TabStop = false;
this.cmdNew.BackColor = System.Drawing.SystemColors.Control;
this.cmdNew.CausesValidation = true;
this.cmdNew.Enabled = true;
this.cmdNew.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdNew.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdNew.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdNew.Name = "cmdNew";
//'DataList1.OcxState = CType(resources.GetObject("'DataList1.OcxState"), System.Windows.Forms.AxHost.State)
this.DataList1.Size = new System.Drawing.Size(244, 342);
this.DataList1.Location = new System.Drawing.Point(6, 27);
this.DataList1.TabIndex = 2;
this.DataList1.Name = "DataList1";
this.txtSearch.AutoSize = false;
this.txtSearch.Size = new System.Drawing.Size(199, 19);
this.txtSearch.Location = new System.Drawing.Point(51, 3);
this.txtSearch.TabIndex = 1;
this.txtSearch.AcceptsReturn = true;
this.txtSearch.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
this.txtSearch.BackColor = System.Drawing.SystemColors.Window;
this.txtSearch.CausesValidation = true;
this.txtSearch.Enabled = true;
this.txtSearch.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtSearch.HideSelection = true;
this.txtSearch.ReadOnly = false;
this.txtSearch.MaxLength = 0;
this.txtSearch.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtSearch.Multiline = false;
this.txtSearch.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtSearch.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.txtSearch.TabStop = true;
this.txtSearch.Visible = true;
this.txtSearch.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.txtSearch.Name = "txtSearch";
this.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdExit.Text = "E&xit";
this.cmdExit.Size = new System.Drawing.Size(97, 52);
this.cmdExit.Location = new System.Drawing.Point(153, 375);
this.cmdExit.TabIndex = 3;
this.cmdExit.TabStop = false;
this.cmdExit.BackColor = System.Drawing.SystemColors.Control;
this.cmdExit.CausesValidation = true;
this.cmdExit.Enabled = true;
this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdExit.Name = "cmdExit";
this.lbl.TextAlign = System.Drawing.ContentAlignment.TopRight;
this.lbl.Text = "&Search :";
this.lbl.Size = new System.Drawing.Size(40, 13);
this.lbl.Location = new System.Drawing.Point(8, 6);
this.lbl.TabIndex = 0;
this.lbl.BackColor = System.Drawing.Color.Transparent;
this.lbl.Enabled = true;
this.lbl.ForeColor = System.Drawing.SystemColors.ControlText;
this.lbl.Cursor = System.Windows.Forms.Cursors.Default;
this.lbl.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lbl.UseMnemonic = true;
this.lbl.Visible = true;
this.lbl.AutoSize = true;
this.lbl.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lbl.Name = "lbl";
this.Controls.Add(cmdNew);
this.Controls.Add(DataList1);
this.Controls.Add(txtSearch);
this.Controls.Add(cmdExit);
this.Controls.Add(lbl);
((System.ComponentModel.ISupportInitialize)this.DataList1).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
//
// App.cs
//
// Author:
// Ruben Vermeersch <ruben@savanne.be>
// Stephane Delcroix <stephane@delcroix.org>
//
// Copyright (C) 2009-2010 Novell, Inc.
// Copyright (C) 2010 Ruben Vermeersch
// Copyright (C) 2009-2010 Stephane Delcroix
//
// 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.IO;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Unique;
using Mono.Unix;
using Hyena;
using FSpot.Core;
using FSpot.Database;
namespace FSpot
{
public class App : Unique.App
{
static object sync_handle = new object ();
#region public API
static App app;
public static App Instance {
get {
lock (sync_handle) {
if (app == null)
app = new App ();
}
return app;
}
}
Thread constructing_organizer = null;
public MainWindow Organizer {
get {
lock (sync_handle) {
if (organizer == null) {
if (constructing_organizer == Thread.CurrentThread) {
throw new Exception ("Recursively tried to acquire App.Organizer!");
}
constructing_organizer = Thread.CurrentThread;
organizer = new MainWindow (Database);
Register (organizer.Window);
}
}
return organizer;
}
}
public Db Database {
get {
lock (sync_handle) {
if (db == null) {
if (!File.Exists (Global.BaseDirectory))
Directory.CreateDirectory (Global.BaseDirectory);
db = new Db ();
try {
db.Init (Path.Combine (Global.BaseDirectory, "photos.db"), true);
} catch (Exception e) {
new FSpot.UI.Dialog.RepairDbDialog (e, db.Repair (), null);
db.Init (Path.Combine (Global.BaseDirectory, "photos.db"), true);
}
}
}
return db;
}
}
public void Import (string path)
{
if (IsRunning) {
var md = new MessageData ();
md.Text = path;
SendMessage (Command.Import, md);
return;
}
HandleImport (path);
}
public void Organize ()
{
if (IsRunning) {
SendMessage (Command.Organize, null);
return;
}
HandleOrganize ();
}
public void Shutdown ()
{
if (IsRunning) {
SendMessage (Command.Shutdown, null);
return;
}
HandleShutdown ();
}
public void Slideshow (string tagname)
{
if (IsRunning) {
var md = new MessageData ();
md.Text = tagname ?? String.Empty;
SendMessage (Command.Slideshow, md);
return;
}
HandleSlideshow (tagname);
}
public void View (SafeUri uri)
{
View (new[] {uri});
}
public void View (IEnumerable<SafeUri> uris)
{
var uri_s = from uri in uris select uri.ToString ();
View (uri_s);
}
public void View (string uri)
{
View (new[] {uri});
}
public void View (IEnumerable<string> uris)
{
if (IsRunning) {
var md = new MessageData ();
md.Uris = uris.ToArray ();
SendMessage (Command.View, md);
return;
}
HandleView (uris.ToArray());
}
#endregion
#region private ctor and stuffs
enum Command {
Invalid = 0,
Import,
View,
Organize,
Shutdown,
Version,
Slideshow,
}
List<Gtk.Window> toplevels;
MainWindow organizer;
Db db;
App (): base ("org.gnome.FSpot.Core", null,
"Import", Command.Import,
"View", Command.View,
"Organize", Command.Organize,
"Shutdown", Command.Shutdown,
"Slideshow", Command.Slideshow)
{
toplevels = new List<Gtk.Window> ();
if (IsRunning) {
Log.Information ("Found active FSpot process");
} else {
MessageReceived += HandleMessageReceived;
}
}
void SendMessage (Command command, MessageData md)
{
SendMessage ((Unique.Command)command, md);
}
#endregion
#region Command Handlers
void HandleMessageReceived (object sender, MessageReceivedArgs e)
{
switch ((Command)e.Command) {
case Command.Import:
HandleImport (e.MessageData.Text);
e.RetVal = Response.Ok;
break;
case Command.Organize:
HandleOrganize ();
e.RetVal = Response.Ok;
break;
case Command.Shutdown:
HandleShutdown ();
e.RetVal = Response.Ok;
break;
case Command.Slideshow:
HandleSlideshow (e.MessageData.Text);
e.RetVal = Response.Ok;
break;
case Command.View:
HandleView (e.MessageData.Uris);
e.RetVal = Response.Ok;
break;
case Command.Invalid:
default:
Log.Debug ("Wrong command received");
break;
}
}
void HandleImport (string path)
{
// Some users get wonky URIs here, trying to work around below.
// https://bugzilla.gnome.org/show_bug.cgi?id=629248
if (path != null && path.StartsWith ("gphoto2:usb:")) {
path = String.Format ("gphoto2://[{0}]", path.Substring (8));
}
Hyena.Log.DebugFormat ("Importing from {0}", path);
Organizer.Window.Present ();
Organizer.ImportFile (path == null ? null : new SafeUri(path));
}
void HandleOrganize ()
{
if (Database.Empty)
HandleImport (null);
else
Organizer.Window.Present ();
}
void HandleShutdown ()
{
try {
App.Instance.Organizer.Close ();
} catch {
System.Environment.Exit (0);
}
}
//FIXME move all this in a standalone class
void HandleSlideshow (string tagname)
{
Tag tag;
FSpot.Widgets.SlideShow slideshow = null;
if (!String.IsNullOrEmpty (tagname))
tag = Database.Tags.GetTagByName (tagname);
else
tag = Database.Tags.GetTagById (Preferences.Get<int> (Preferences.SCREENSAVER_TAG));
IPhoto[] photos;
if (tag != null)
photos = Database.Photos.Query (new Tag[] {tag});
else if (Preferences.Get<int> (Preferences.SCREENSAVER_TAG) == 0)
photos = Database.Photos.Query (new Tag [] {});
else
photos = new IPhoto [0];
// Minimum delay 1 second; default is 4s
var delay = Math.Max (1.0, Preferences.Get<double> (Preferences.SCREENSAVER_DELAY));
var window = new XScreenSaverSlide ();
window.ModifyFg (Gtk.StateType.Normal, new Gdk.Color (127, 127, 127));
window.ModifyBg (Gtk.StateType.Normal, new Gdk.Color (0, 0, 0));
if (photos.Length > 0) {
Array.Sort (photos, new IPhotoComparer.RandomSort ());
slideshow = new FSpot.Widgets.SlideShow (new BrowsablePointer (new PhotoList (photos), 0), (uint)(delay * 1000), true);
window.Add (slideshow);
} else {
Gtk.HBox outer = new Gtk.HBox ();
Gtk.HBox hbox = new Gtk.HBox ();
Gtk.VBox vbox = new Gtk.VBox ();
outer.PackStart (new Gtk.Label (String.Empty));
outer.PackStart (vbox, false, false, 0);
vbox.PackStart (new Gtk.Label (String.Empty));
vbox.PackStart (hbox, false, false, 0);
hbox.PackStart (new Gtk.Image (Gtk.Stock.DialogWarning, Gtk.IconSize.Dialog),
false, false, 0);
outer.PackStart (new Gtk.Label (String.Empty));
string msg;
string long_msg;
if (tag != null) {
msg = String.Format (Catalog.GetString ("No photos matching {0} found"), tag.Name);
long_msg = String.Format (Catalog.GetString ("The tag \"{0}\" is not applied to any photos. Try adding\n" +
"the tag to some photos or selecting a different tag in the\n" +
"F-Spot preference dialog."), tag.Name);
} else {
msg = Catalog.GetString ("Search returned no results");
long_msg = Catalog.GetString ("The tag F-Spot is looking for does not exist. Try\n" +
"selecting a different tag in the F-Spot preference\n" +
"dialog.");
}
Gtk.Label label = new Gtk.Label (msg);
hbox.PackStart (label, false, false, 0);
Gtk.Label long_label = new Gtk.Label (long_msg);
long_label.Markup = String.Format ("<small>{0}</small>", long_msg);
vbox.PackStart (long_label, false, false, 0);
vbox.PackStart (new Gtk.Label (String.Empty));
window.Add (outer);
label.ModifyFg (Gtk.StateType.Normal, new Gdk.Color (127, 127, 127));
label.ModifyBg (Gtk.StateType.Normal, new Gdk.Color (0, 0, 0));
long_label.ModifyFg (Gtk.StateType.Normal, new Gdk.Color (127, 127, 127));
long_label.ModifyBg (Gtk.StateType.Normal, new Gdk.Color (0, 0, 0));
}
window.ShowAll ();
Register (window);
GLib.Idle.Add (delegate {
if (slideshow != null)
slideshow.Start ();
return false;
});
}
void HandleView (string[] uris)
{
List<SafeUri> ul = new List<SafeUri> ();
foreach (var u in uris)
ul.Add (new SafeUri (u, true));
try {
Register (new FSpot.SingleView (ul.ToArray ()).Window);
} catch (System.Exception e) {
Log.Exception (e);
Log.Debug ("no real valid path to view from");
}
}
#endregion
#region Track toplevel windows
void Register (Gtk.Window window)
{
toplevels.Add (window);
window.Destroyed += HandleDestroyed;
}
void HandleDestroyed (object sender, EventArgs e)
{
toplevels.Remove (sender as Gtk.Window);
if (toplevels.Count == 0) {
Log.Information ("Exiting...");
Banshee.Kernel.Scheduler.Dispose ();
Database.Dispose ();
ImageLoaderThread.CleanAll ();
Gtk.Application.Quit ();
System.Environment.Exit (0);
}
if (organizer != null && organizer.Window == sender)
organizer = null;
}
#endregion
}
}
| |
using AllReady.Services.Sms;
using Microsoft.Extensions.Options;
using Moq;
using Shouldly;
using System;
using System.Threading.Tasks;
using AllReady.Configuration;
using Twilio.Clients;
using Twilio.Rest.Lookups.V1;
using Xunit;
namespace AllReady.UnitTest.Services.Sms
{
public class TwilioPhoneNumberLookupServiceTests
{
private string TwilioResponseJson = "{\"carrier\": {\"error_code\": null,\"mobile_country_code\": \"310\",\"mobile_network_code\": \"456\",\"name\": \"verizon\",\"type\": \"mobile\"},\"country_code\": \"US\",\"national_format\": \"(510) 867-5309\",\"phone_number\": \"+15108675309\",\"add_ons\": {\"status\": \"successful\",\"message\": null,\"code\": null,\"results\": {}},\"url\": \"https://lookups.twilio.com/v1/PhoneNumbers/phone_number\"}";
private string TwilioResponseJsonNoCarrier = "{\"country_code\": \"US\",\"national_format\": \"(510) 867-5309\",\"phone_number\": \"+15108675309\",\"add_ons\": {\"status\": \"successful\",\"message\": null,\"code\": null,\"results\": {}},\"url\": \"https://lookups.twilio.com/v1/PhoneNumbers/phone_number\"}";
private string TwilioResponseJsonLandline = "{\"carrier\": {\"error_code\": null,\"mobile_country_code\": \"310\",\"mobile_network_code\": \"456\",\"name\": \"verizon\",\"type\": \"landline\"},\"country_code\": \"US\",\"national_format\": \"(510) 867-5309\",\"phone_number\": \"+15108675309\",\"add_ons\": {\"status\": \"successful\",\"message\": null,\"code\": null,\"results\": {}},\"url\": \"https://lookups.twilio.com/v1/PhoneNumbers/phone_number\"}";
private string TwilioResponseJsonVoip = "{\"carrier\": {\"error_code\": null,\"mobile_country_code\": \"310\",\"mobile_network_code\": \"456\",\"name\": \"verizon\",\"type\": \"voip\"},\"country_code\": \"US\",\"national_format\": \"(510) 867-5309\",\"phone_number\": \"+15108675309\",\"add_ons\": {\"status\": \"successful\",\"message\": null,\"code\": null,\"results\": {}},\"url\": \"https://lookups.twilio.com/v1/PhoneNumbers/phone_number\"}";
[Fact]
public async Task LookupNumber_CallsTwilioWrapper()
{
var options = new Mock<IOptions<TwilioSettings>>();
options.Setup(x => x.Value).Returns(new TwilioSettings { Sid = "123",Token = "ABC", PhoneNo = "1234567890" });
var twilioWrapper = new Mock<ITwilioWrapper>();
var sut = new TwilioPhoneNumberLookupService(options.Object, twilioWrapper.Object);
await sut.LookupNumber("123456789", "us");
twilioWrapper.Verify(x => x.FetchPhoneNumberResource(It.IsAny<FetchPhoneNumberOptions>(), It.IsAny<ITwilioRestClient>()), Times.Once);
}
[Fact]
public async Task LookupNumber_CallsTwilioWrapper_WithCorrectPhoneNumber()
{
FetchPhoneNumberOptions fetchOptions = null;
var options = new Mock<IOptions<TwilioSettings>>();
options.Setup(x => x.Value).Returns(new TwilioSettings { Sid = "123", Token = "ABC", PhoneNo = "1234567890" });
var twilioWrapper = new Mock<ITwilioWrapper>();
twilioWrapper.Setup(x => x.FetchPhoneNumberResource(It.IsAny<FetchPhoneNumberOptions>(), It.IsAny<ITwilioRestClient>()))
.Callback<FetchPhoneNumberOptions, ITwilioRestClient>((x, y) => fetchOptions = x);
var sut = new TwilioPhoneNumberLookupService(options.Object, twilioWrapper.Object);
await sut.LookupNumber("123456789", "us");
fetchOptions.PathPhoneNumber.ToString().ShouldBe(new Twilio.Types.PhoneNumber("123456789").ToString());
}
[Fact]
public async Task LookupNumber_CallsTwilioWrapper_WithCorrectType()
{
FetchPhoneNumberOptions fetchOptions = null;
var options = new Mock<IOptions<TwilioSettings>>();
options.Setup(x => x.Value).Returns(new TwilioSettings { Sid = "123", Token = "ABC", PhoneNo = "1234567890" });
var twilioWrapper = new Mock<ITwilioWrapper>();
twilioWrapper.Setup(x => x.FetchPhoneNumberResource(It.IsAny<FetchPhoneNumberOptions>(), It.IsAny<ITwilioRestClient>()))
.Callback<FetchPhoneNumberOptions, ITwilioRestClient>((x, y) => fetchOptions = x);
var sut = new TwilioPhoneNumberLookupService(options.Object, twilioWrapper.Object);
await sut.LookupNumber("123456789", "us");
fetchOptions.Type[0].ShouldBe("carrier");
}
[Fact]
public async Task LookupNumber_CallsTwilioWrapper_WithCorrectCountryCode()
{
FetchPhoneNumberOptions fetchOptions = null;
var options = new Mock<IOptions<TwilioSettings>>();
options.Setup(x => x.Value).Returns(new TwilioSettings { Sid = "123", Token = "ABC", PhoneNo = "1234567890" });
var twilioWrapper = new Mock<ITwilioWrapper>();
twilioWrapper.Setup(x => x.FetchPhoneNumberResource(It.IsAny<FetchPhoneNumberOptions>(), It.IsAny<ITwilioRestClient>()))
.Callback<FetchPhoneNumberOptions, ITwilioRestClient>((x, y) => fetchOptions = x);
var sut = new TwilioPhoneNumberLookupService(options.Object, twilioWrapper.Object);
await sut.LookupNumber("123456789", "us");
fetchOptions.CountryCode.ShouldBe("us");
}
[Fact]
public async Task LookupNumber_ReturnsFailedLokupResult_IfTheTwilioCallFails()
{
var options = new Mock<IOptions<TwilioSettings>>();
options.Setup(x => x.Value).Returns(new TwilioSettings { Sid = "123", Token = "ABC", PhoneNo = "1234567890" });
var twilioWrapper = new Mock<ITwilioWrapper>();
twilioWrapper.Setup(x => x.FetchPhoneNumberResource(It.IsAny<FetchPhoneNumberOptions>(), It.IsAny<ITwilioRestClient>()))
.Throws<Exception>();
var sut = new TwilioPhoneNumberLookupService(options.Object, twilioWrapper.Object);
var result = await sut.LookupNumber("123456789", "us");
result.LookupFailed.ShouldBeTrue();
}
[Fact]
public async Task LookupNumber_ReturnsFailedLokupResult_IfTheTwilioCallReturnsNullPhoneNumberResource()
{
var options = new Mock<IOptions<TwilioSettings>>();
options.Setup(x => x.Value).Returns(new TwilioSettings { Sid = "123", Token = "ABC", PhoneNo = "1234567890" });
var twilioWrapper = new Mock<ITwilioWrapper>();
twilioWrapper.Setup(x => x.FetchPhoneNumberResource(It.IsAny<FetchPhoneNumberOptions>(), It.IsAny<ITwilioRestClient>()))
.ReturnsAsync((PhoneNumberResource)null);
var sut = new TwilioPhoneNumberLookupService(options.Object, twilioWrapper.Object);
var result = await sut.LookupNumber("123456789", "us");
result.LookupFailed.ShouldBeTrue();
}
[Fact]
public async Task LookupNumber_ReturnsCorrectPhoneNumberInResult()
{
var options = new Mock<IOptions<TwilioSettings>>();
options.Setup(x => x.Value).Returns(new TwilioSettings { Sid = "123", Token = "ABC", PhoneNo = "1234567890" });
var twilioWrapper = new Mock<ITwilioWrapper>();
twilioWrapper.Setup(x => x.FetchPhoneNumberResource(It.IsAny<FetchPhoneNumberOptions>(), It.IsAny<ITwilioRestClient>()))
.ReturnsAsync(PhoneNumberResource.FromJson(TwilioResponseJson));
var sut = new TwilioPhoneNumberLookupService(options.Object, twilioWrapper.Object);
var result = await sut.LookupNumber("123456789", "us");
result.PhoneNumberE164.ToString().ShouldBe(new Twilio.Types.PhoneNumber("+15108675309").ToString());
}
[Fact]
public async Task LookupNumber_ReturnsUnknownType_WhenNoCarrierInfo()
{
var options = new Mock<IOptions<TwilioSettings>>();
options.Setup(x => x.Value).Returns(new TwilioSettings { Sid = "123", Token = "ABC", PhoneNo = "1234567890" });
var twilioWrapper = new Mock<ITwilioWrapper>();
twilioWrapper.Setup(x => x.FetchPhoneNumberResource(It.IsAny<FetchPhoneNumberOptions>(), It.IsAny<ITwilioRestClient>()))
.ReturnsAsync(PhoneNumberResource.FromJson(TwilioResponseJsonNoCarrier));
var sut = new TwilioPhoneNumberLookupService(options.Object, twilioWrapper.Object);
var result = await sut.LookupNumber("123456789", "us");
result.Type.ShouldBe(PhoneNumberType.Unknown);
}
[Fact]
public async Task LookupNumber_ReturnsMobileType_WhenResponseIncludesMobileCarrier()
{
var options = new Mock<IOptions<TwilioSettings>>();
options.Setup(x => x.Value).Returns(new TwilioSettings { Sid = "123", Token = "ABC", PhoneNo = "1234567890" });
var twilioWrapper = new Mock<ITwilioWrapper>();
twilioWrapper.Setup(x => x.FetchPhoneNumberResource(It.IsAny<FetchPhoneNumberOptions>(), It.IsAny<ITwilioRestClient>()))
.ReturnsAsync(PhoneNumberResource.FromJson(TwilioResponseJson));
var sut = new TwilioPhoneNumberLookupService(options.Object, twilioWrapper.Object);
var result = await sut.LookupNumber("123456789", "us");
result.Type.ShouldBe(PhoneNumberType.Mobile);
}
[Fact]
public async Task LookupNumber_ReturnsLandlineType_WhenResponseIncludesLandlineCarrier()
{
var options = new Mock<IOptions<TwilioSettings>>();
options.Setup(x => x.Value).Returns(new TwilioSettings { Sid = "123", Token = "ABC", PhoneNo = "1234567890" });
var twilioWrapper = new Mock<ITwilioWrapper>();
twilioWrapper.Setup(x => x.FetchPhoneNumberResource(It.IsAny<FetchPhoneNumberOptions>(), It.IsAny<ITwilioRestClient>()))
.ReturnsAsync(PhoneNumberResource.FromJson(TwilioResponseJsonLandline));
var sut = new TwilioPhoneNumberLookupService(options.Object, twilioWrapper.Object);
var result = await sut.LookupNumber("123456789", "us");
result.Type.ShouldBe(PhoneNumberType.Landline);
}
[Fact]
public async Task LookupNumber_ReturnsVoipType_WhenResponseIncludesVoipCarrier()
{
var options = new Mock<IOptions<TwilioSettings>>();
options.Setup(x => x.Value).Returns(new TwilioSettings { Sid = "123", Token = "ABC", PhoneNo = "1234567890" });
var twilioWrapper = new Mock<ITwilioWrapper>();
twilioWrapper.Setup(x => x.FetchPhoneNumberResource(It.IsAny<FetchPhoneNumberOptions>(), It.IsAny<ITwilioRestClient>()))
.ReturnsAsync(PhoneNumberResource.FromJson(TwilioResponseJsonVoip));
var sut = new TwilioPhoneNumberLookupService(options.Object, twilioWrapper.Object);
var result = await sut.LookupNumber("123456789", "us");
result.Type.ShouldBe(PhoneNumberType.Voip);
}
}
}
| |
/*
* Exchange Web Services Managed API
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
namespace Microsoft.Exchange.WebServices.Data
{
using System.Diagnostics.CodeAnalysis;
/// <summary>
/// Represents the schem for contacts.
/// </summary>
[Schema]
public class ContactSchema : ItemSchema
{
/// <summary>
/// FieldURIs for contacts.
/// </summary>
private static class FieldUris
{
public const string FileAs = "contacts:FileAs";
public const string FileAsMapping = "contacts:FileAsMapping";
public const string DisplayName = "contacts:DisplayName";
public const string GivenName = "contacts:GivenName";
public const string Initials = "contacts:Initials";
public const string MiddleName = "contacts:MiddleName";
public const string NickName = "contacts:Nickname";
public const string CompleteName = "contacts:CompleteName";
public const string CompanyName = "contacts:CompanyName";
public const string EmailAddress = "contacts:EmailAddress";
public const string EmailAddresses = "contacts:EmailAddresses";
public const string PhysicalAddresses = "contacts:PhysicalAddresses";
public const string PhoneNumber = "contacts:PhoneNumber";
public const string PhoneNumbers = "contacts:PhoneNumbers";
public const string AssistantName = "contacts:AssistantName";
public const string Birthday = "contacts:Birthday";
public const string BusinessHomePage = "contacts:BusinessHomePage";
public const string Children = "contacts:Children";
public const string Companies = "contacts:Companies";
public const string ContactSource = "contacts:ContactSource";
public const string Department = "contacts:Department";
public const string Generation = "contacts:Generation";
public const string ImAddress = "contacts:ImAddress";
public const string ImAddresses = "contacts:ImAddresses";
public const string JobTitle = "contacts:JobTitle";
public const string Manager = "contacts:Manager";
public const string Mileage = "contacts:Mileage";
public const string OfficeLocation = "contacts:OfficeLocation";
public const string PhysicalAddressCity = "contacts:PhysicalAddress:City";
public const string PhysicalAddressCountryOrRegion = "contacts:PhysicalAddress:CountryOrRegion";
public const string PhysicalAddressState = "contacts:PhysicalAddress:State";
public const string PhysicalAddressStreet = "contacts:PhysicalAddress:Street";
public const string PhysicalAddressPostalCode = "contacts:PhysicalAddress:PostalCode";
public const string PostalAddressIndex = "contacts:PostalAddressIndex";
public const string Profession = "contacts:Profession";
public const string SpouseName = "contacts:SpouseName";
public const string Surname = "contacts:Surname";
public const string WeddingAnniversary = "contacts:WeddingAnniversary";
public const string HasPicture = "contacts:HasPicture";
public const string PhoneticFullName = "contacts:PhoneticFullName";
public const string PhoneticFirstName = "contacts:PhoneticFirstName";
public const string PhoneticLastName = "contacts:PhoneticLastName";
public const string Alias = "contacts:Alias";
public const string Notes = "contacts:Notes";
public const string Photo = "contacts:Photo";
public const string UserSMIMECertificate = "contacts:UserSMIMECertificate";
public const string MSExchangeCertificate = "contacts:MSExchangeCertificate";
public const string DirectoryId = "contacts:DirectoryId";
public const string ManagerMailbox = "contacts:ManagerMailbox";
public const string DirectReports = "contacts:DirectReports";
}
/// <summary>
/// Defines the FileAs property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition FileAs =
new StringPropertyDefinition(
XmlElementNames.FileAs,
FieldUris.FileAs,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the FileAsMapping property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition FileAsMapping =
new GenericPropertyDefinition<FileAsMapping>(
XmlElementNames.FileAsMapping,
FieldUris.FileAsMapping,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the DisplayName property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition DisplayName =
new StringPropertyDefinition(
XmlElementNames.DisplayName,
FieldUris.DisplayName,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the GivenName property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition GivenName =
new StringPropertyDefinition(
XmlElementNames.GivenName,
FieldUris.GivenName,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the Initials property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition Initials =
new StringPropertyDefinition(
XmlElementNames.Initials,
FieldUris.Initials,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the MiddleName property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition MiddleName =
new StringPropertyDefinition(
XmlElementNames.MiddleName,
FieldUris.MiddleName,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the NickName property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition NickName =
new StringPropertyDefinition(
XmlElementNames.NickName,
FieldUris.NickName,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the CompleteName property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition CompleteName =
new ComplexPropertyDefinition<CompleteName>(
XmlElementNames.CompleteName,
FieldUris.CompleteName,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1,
delegate() { return new CompleteName(); });
/// <summary>
/// Defines the CompanyName property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition CompanyName =
new StringPropertyDefinition(
XmlElementNames.CompanyName,
FieldUris.CompanyName,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the EmailAddresses property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition EmailAddresses =
new ComplexPropertyDefinition<EmailAddressDictionary>(
XmlElementNames.EmailAddresses,
FieldUris.EmailAddresses,
PropertyDefinitionFlags.AutoInstantiateOnRead | PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate,
ExchangeVersion.Exchange2007_SP1,
delegate() { return new EmailAddressDictionary(); });
/// <summary>
/// Defines the PhysicalAddresses property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition PhysicalAddresses =
new ComplexPropertyDefinition<PhysicalAddressDictionary>(
XmlElementNames.PhysicalAddresses,
FieldUris.PhysicalAddresses,
PropertyDefinitionFlags.AutoInstantiateOnRead | PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate,
ExchangeVersion.Exchange2007_SP1,
delegate() { return new PhysicalAddressDictionary(); });
/// <summary>
/// Defines the PhoneNumbers property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition PhoneNumbers =
new ComplexPropertyDefinition<PhoneNumberDictionary>(
XmlElementNames.PhoneNumbers,
FieldUris.PhoneNumbers,
PropertyDefinitionFlags.AutoInstantiateOnRead | PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate,
ExchangeVersion.Exchange2007_SP1,
delegate() { return new PhoneNumberDictionary(); });
/// <summary>
/// Defines the AssistantName property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition AssistantName =
new StringPropertyDefinition(
XmlElementNames.AssistantName,
FieldUris.AssistantName,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the Birthday property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition Birthday =
new DateTimePropertyDefinition(
XmlElementNames.Birthday,
FieldUris.Birthday,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the BusinessHomePage property.
/// </summary>
/// <remarks>
/// Defined as anyURI in the EWS schema. String is fine here.
/// </remarks>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition BusinessHomePage =
new StringPropertyDefinition(
XmlElementNames.BusinessHomePage,
FieldUris.BusinessHomePage,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the Children property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition Children =
new ComplexPropertyDefinition<StringList>(
XmlElementNames.Children,
FieldUris.Children,
PropertyDefinitionFlags.AutoInstantiateOnRead | PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1,
delegate() { return new StringList(); });
/// <summary>
/// Defines the Companies property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition Companies =
new ComplexPropertyDefinition<StringList>(
XmlElementNames.Companies,
FieldUris.Companies,
PropertyDefinitionFlags.AutoInstantiateOnRead | PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1,
delegate() { return new StringList(); });
/// <summary>
/// Defines the ContactSource property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition ContactSource =
new GenericPropertyDefinition<ContactSource>(
XmlElementNames.ContactSource,
FieldUris.ContactSource,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the Department property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition Department =
new StringPropertyDefinition(
XmlElementNames.Department,
FieldUris.Department,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the Generation property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition Generation =
new StringPropertyDefinition(
XmlElementNames.Generation,
FieldUris.Generation,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the ImAddresses property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition ImAddresses =
new ComplexPropertyDefinition<ImAddressDictionary>(
XmlElementNames.ImAddresses,
FieldUris.ImAddresses,
PropertyDefinitionFlags.AutoInstantiateOnRead | PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate,
ExchangeVersion.Exchange2007_SP1,
delegate() { return new ImAddressDictionary(); });
/// <summary>
/// Defines the JobTitle property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition JobTitle =
new StringPropertyDefinition(
XmlElementNames.JobTitle,
FieldUris.JobTitle,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the Manager property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition Manager =
new StringPropertyDefinition(
XmlElementNames.Manager,
FieldUris.Manager,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the Mileage property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition Mileage =
new StringPropertyDefinition(
XmlElementNames.Mileage,
FieldUris.Mileage,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the OfficeLocation property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition OfficeLocation =
new StringPropertyDefinition(
XmlElementNames.OfficeLocation,
FieldUris.OfficeLocation,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the PostalAddressIndex property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition PostalAddressIndex =
new GenericPropertyDefinition<PhysicalAddressIndex>(
XmlElementNames.PostalAddressIndex,
FieldUris.PostalAddressIndex,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the Profession property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition Profession =
new StringPropertyDefinition(
XmlElementNames.Profession,
FieldUris.Profession,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the SpouseName property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition SpouseName =
new StringPropertyDefinition(
XmlElementNames.SpouseName,
FieldUris.SpouseName,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the Surname property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition Surname =
new StringPropertyDefinition(
XmlElementNames.Surname,
FieldUris.Surname,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the WeddingAnniversary property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition WeddingAnniversary =
new DateTimePropertyDefinition(
XmlElementNames.WeddingAnniversary,
FieldUris.WeddingAnniversary,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the HasPicture property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition HasPicture =
new BoolPropertyDefinition(
XmlElementNames.HasPicture,
FieldUris.HasPicture,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010);
#region Directory Only Properties
/// <summary>
/// Defines the PhoneticFullName property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition PhoneticFullName =
new StringPropertyDefinition(
XmlElementNames.PhoneticFullName,
FieldUris.PhoneticFullName,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1);
/// <summary>
/// Defines the PhoneticFirstName property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition PhoneticFirstName =
new StringPropertyDefinition(
XmlElementNames.PhoneticFirstName,
FieldUris.PhoneticFirstName,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1);
/// <summary>
/// Defines the PhoneticLastName property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition PhoneticLastName =
new StringPropertyDefinition(
XmlElementNames.PhoneticLastName,
FieldUris.PhoneticLastName,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1);
/// <summary>
/// Defines the Alias property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition Alias =
new StringPropertyDefinition(
XmlElementNames.Alias,
FieldUris.Alias,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1);
/// <summary>
/// Defines the Notes property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition Notes =
new StringPropertyDefinition(
XmlElementNames.Notes,
FieldUris.Notes,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1);
/// <summary>
/// Defines the Photo property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition Photo =
new ByteArrayPropertyDefinition(
XmlElementNames.Photo,
FieldUris.Photo,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1);
/// <summary>
/// Defines the UserSMIMECertificate property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition UserSMIMECertificate =
new ComplexPropertyDefinition<ByteArrayArray>(
XmlElementNames.UserSMIMECertificate,
FieldUris.UserSMIMECertificate,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1,
delegate() { return new ByteArrayArray(); });
/// <summary>
/// Defines the MSExchangeCertificate property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition MSExchangeCertificate =
new ComplexPropertyDefinition<ByteArrayArray>(
XmlElementNames.MSExchangeCertificate,
FieldUris.MSExchangeCertificate,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1,
delegate() { return new ByteArrayArray(); });
/// <summary>
/// Defines the DirectoryId property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition DirectoryId =
new StringPropertyDefinition(
XmlElementNames.DirectoryId,
FieldUris.DirectoryId,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1);
/// <summary>
/// Defines the ManagerMailbox property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition ManagerMailbox =
new ContainedPropertyDefinition<EmailAddress>(
XmlElementNames.ManagerMailbox,
FieldUris.ManagerMailbox,
XmlElementNames.Mailbox,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1,
delegate() { return new EmailAddress(); });
/// <summary>
/// Defines the DirectReports property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition DirectReports =
new ComplexPropertyDefinition<EmailAddressCollection>(
XmlElementNames.DirectReports,
FieldUris.DirectReports,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1,
delegate() { return new EmailAddressCollection(); });
#endregion
#region Email addresses indexed properties
/// <summary>
/// Defines the EmailAddress1 property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition EmailAddress1 =
new IndexedPropertyDefinition(FieldUris.EmailAddress, "EmailAddress1");
/// <summary>
/// Defines the EmailAddress2 property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition EmailAddress2 =
new IndexedPropertyDefinition(FieldUris.EmailAddress, "EmailAddress2");
/// <summary>
/// Defines the EmailAddress3 property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition EmailAddress3 =
new IndexedPropertyDefinition(FieldUris.EmailAddress, "EmailAddress3");
#endregion
#region IM addresses indexed properties
/// <summary>
/// Defines the ImAddress1 property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition ImAddress1 =
new IndexedPropertyDefinition(FieldUris.ImAddress, "ImAddress1");
/// <summary>
/// Defines the ImAddress2 property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition ImAddress2 =
new IndexedPropertyDefinition(FieldUris.ImAddress, "ImAddress2");
/// <summary>
/// Defines the ImAddress3 property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition ImAddress3 =
new IndexedPropertyDefinition(FieldUris.ImAddress, "ImAddress3");
#endregion
#region Phone numbers indexed properties
/// <summary>
/// Defines the AssistentPhone property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition AssistantPhone =
new IndexedPropertyDefinition(FieldUris.PhoneNumber, "AssistantPhone");
/// <summary>
/// Defines the BusinessFax property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition BusinessFax =
new IndexedPropertyDefinition(FieldUris.PhoneNumber, "BusinessFax");
/// <summary>
/// Defines the BusinessPhone property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition BusinessPhone =
new IndexedPropertyDefinition(FieldUris.PhoneNumber, "BusinessPhone");
/// <summary>
/// Defines the BusinessPhone2 property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition BusinessPhone2 =
new IndexedPropertyDefinition(FieldUris.PhoneNumber, "BusinessPhone2");
/// <summary>
/// Defines the Callback property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition Callback =
new IndexedPropertyDefinition(FieldUris.PhoneNumber, "Callback");
/// <summary>
/// Defines the CarPhone property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition CarPhone =
new IndexedPropertyDefinition(FieldUris.PhoneNumber, "CarPhone");
/// <summary>
/// Defines the CompanyMainPhone property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition CompanyMainPhone =
new IndexedPropertyDefinition(FieldUris.PhoneNumber, "CompanyMainPhone");
/// <summary>
/// Defines the HomeFax property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition HomeFax =
new IndexedPropertyDefinition(FieldUris.PhoneNumber, "HomeFax");
/// <summary>
/// Defines the HomePhone property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition HomePhone =
new IndexedPropertyDefinition(FieldUris.PhoneNumber, "HomePhone");
/// <summary>
/// Defines the HomePhone2 property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition HomePhone2 =
new IndexedPropertyDefinition(FieldUris.PhoneNumber, "HomePhone2");
/// <summary>
/// Defines the Isdn property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition Isdn =
new IndexedPropertyDefinition(FieldUris.PhoneNumber, "Isdn");
/// <summary>
/// Defines the MobilePhone property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition MobilePhone =
new IndexedPropertyDefinition(FieldUris.PhoneNumber, "MobilePhone");
/// <summary>
/// Defines the OtherFax property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition OtherFax =
new IndexedPropertyDefinition(FieldUris.PhoneNumber, "OtherFax");
/// <summary>
/// Defines the OtherTelephone property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition OtherTelephone =
new IndexedPropertyDefinition(FieldUris.PhoneNumber, "OtherTelephone");
/// <summary>
/// Defines the Pager property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition Pager =
new IndexedPropertyDefinition(FieldUris.PhoneNumber, "Pager");
/// <summary>
/// Defines the PrimaryPhone property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition PrimaryPhone =
new IndexedPropertyDefinition(FieldUris.PhoneNumber, "PrimaryPhone");
/// <summary>
/// Defines the RadioPhone property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition RadioPhone =
new IndexedPropertyDefinition(FieldUris.PhoneNumber, "RadioPhone");
/// <summary>
/// Defines the Telex property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition Telex =
new IndexedPropertyDefinition(FieldUris.PhoneNumber, "Telex");
/// <summary>
/// Defines the TtyTddPhone property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition TtyTddPhone =
new IndexedPropertyDefinition(FieldUris.PhoneNumber, "TtyTddPhone");
#endregion
#region Business address indexed properties
/// <summary>
/// Defines the BusinessAddressStreet property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition BusinessAddressStreet =
new IndexedPropertyDefinition(FieldUris.PhysicalAddressStreet, "Business");
/// <summary>
/// Defines the BusinessAddressCity property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition BusinessAddressCity =
new IndexedPropertyDefinition(FieldUris.PhysicalAddressCity, "Business");
/// <summary>
/// Defines the BusinessAddressState property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition BusinessAddressState =
new IndexedPropertyDefinition(FieldUris.PhysicalAddressState, "Business");
/// <summary>
/// Defines the BusinessAddressCountryOrRegion property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition BusinessAddressCountryOrRegion =
new IndexedPropertyDefinition(FieldUris.PhysicalAddressCountryOrRegion, "Business");
/// <summary>
/// Defines the BusinessAddressPostalCode property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition BusinessAddressPostalCode =
new IndexedPropertyDefinition(FieldUris.PhysicalAddressPostalCode, "Business");
#endregion
#region Home address indexed properties
/// <summary>
/// Defines the HomeAddressStreet property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition HomeAddressStreet =
new IndexedPropertyDefinition(FieldUris.PhysicalAddressStreet, "Home");
/// <summary>
/// Defines the HomeAddressCity property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition HomeAddressCity =
new IndexedPropertyDefinition(FieldUris.PhysicalAddressCity, "Home");
/// <summary>
/// Defines the HomeAddressState property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition HomeAddressState =
new IndexedPropertyDefinition(FieldUris.PhysicalAddressState, "Home");
/// <summary>
/// Defines the HomeAddressCountryOrRegion property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition HomeAddressCountryOrRegion =
new IndexedPropertyDefinition(FieldUris.PhysicalAddressCountryOrRegion, "Home");
/// <summary>
/// Defines the HomeAddressPostalCode property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition HomeAddressPostalCode =
new IndexedPropertyDefinition(FieldUris.PhysicalAddressPostalCode, "Home");
#endregion
#region Other address indexed properties
/// <summary>
/// Defines the OtherAddressStreet property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition OtherAddressStreet =
new IndexedPropertyDefinition(FieldUris.PhysicalAddressStreet, "Other");
/// <summary>
/// Defines the OtherAddressCity property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition OtherAddressCity =
new IndexedPropertyDefinition(FieldUris.PhysicalAddressCity, "Other");
/// <summary>
/// Defines the OtherAddressState property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition OtherAddressState =
new IndexedPropertyDefinition(FieldUris.PhysicalAddressState, "Other");
/// <summary>
/// Defines the OtherAddressCountryOrRegion property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition OtherAddressCountryOrRegion =
new IndexedPropertyDefinition(FieldUris.PhysicalAddressCountryOrRegion, "Other");
/// <summary>
/// Defines the OtherAddressPostalCode property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly IndexedPropertyDefinition OtherAddressPostalCode =
new IndexedPropertyDefinition(FieldUris.PhysicalAddressPostalCode, "Other");
#endregion
// This must be declared after the property definitions
internal static new readonly ContactSchema Instance = new ContactSchema();
/// <summary>
/// Registers properties.
/// </summary>
/// <remarks>
/// IMPORTANT NOTE: PROPERTIES MUST BE REGISTERED IN SCHEMA ORDER (i.e. the same order as they are defined in types.xsd)
/// </remarks>
internal override void RegisterProperties()
{
base.RegisterProperties();
this.RegisterProperty(FileAs);
this.RegisterProperty(FileAsMapping);
this.RegisterProperty(DisplayName);
this.RegisterProperty(GivenName);
this.RegisterProperty(Initials);
this.RegisterProperty(MiddleName);
this.RegisterProperty(NickName);
this.RegisterProperty(CompleteName);
this.RegisterProperty(CompanyName);
this.RegisterProperty(EmailAddresses);
this.RegisterProperty(PhysicalAddresses);
this.RegisterProperty(PhoneNumbers);
this.RegisterProperty(AssistantName);
this.RegisterProperty(Birthday);
this.RegisterProperty(BusinessHomePage);
this.RegisterProperty(Children);
this.RegisterProperty(Companies);
this.RegisterProperty(ContactSource);
this.RegisterProperty(Department);
this.RegisterProperty(Generation);
this.RegisterProperty(ImAddresses);
this.RegisterProperty(JobTitle);
this.RegisterProperty(Manager);
this.RegisterProperty(Mileage);
this.RegisterProperty(OfficeLocation);
this.RegisterProperty(PostalAddressIndex);
this.RegisterProperty(Profession);
this.RegisterProperty(SpouseName);
this.RegisterProperty(Surname);
this.RegisterProperty(WeddingAnniversary);
this.RegisterProperty(HasPicture);
this.RegisterProperty(PhoneticFullName);
this.RegisterProperty(PhoneticFirstName);
this.RegisterProperty(PhoneticLastName);
this.RegisterProperty(Alias);
this.RegisterProperty(Notes);
this.RegisterProperty(Photo);
this.RegisterProperty(UserSMIMECertificate);
this.RegisterProperty(MSExchangeCertificate);
this.RegisterProperty(DirectoryId);
this.RegisterProperty(ManagerMailbox);
this.RegisterProperty(DirectReports);
this.RegisterIndexedProperty(EmailAddress1);
this.RegisterIndexedProperty(EmailAddress2);
this.RegisterIndexedProperty(EmailAddress3);
this.RegisterIndexedProperty(ImAddress1);
this.RegisterIndexedProperty(ImAddress2);
this.RegisterIndexedProperty(ImAddress3);
this.RegisterIndexedProperty(AssistantPhone);
this.RegisterIndexedProperty(BusinessFax);
this.RegisterIndexedProperty(BusinessPhone);
this.RegisterIndexedProperty(BusinessPhone2);
this.RegisterIndexedProperty(Callback);
this.RegisterIndexedProperty(CarPhone);
this.RegisterIndexedProperty(CompanyMainPhone);
this.RegisterIndexedProperty(HomeFax);
this.RegisterIndexedProperty(HomePhone);
this.RegisterIndexedProperty(HomePhone2);
this.RegisterIndexedProperty(Isdn);
this.RegisterIndexedProperty(MobilePhone);
this.RegisterIndexedProperty(OtherFax);
this.RegisterIndexedProperty(OtherTelephone);
this.RegisterIndexedProperty(Pager);
this.RegisterIndexedProperty(PrimaryPhone);
this.RegisterIndexedProperty(RadioPhone);
this.RegisterIndexedProperty(Telex);
this.RegisterIndexedProperty(TtyTddPhone);
this.RegisterIndexedProperty(BusinessAddressStreet);
this.RegisterIndexedProperty(BusinessAddressCity);
this.RegisterIndexedProperty(BusinessAddressState);
this.RegisterIndexedProperty(BusinessAddressCountryOrRegion);
this.RegisterIndexedProperty(BusinessAddressPostalCode);
this.RegisterIndexedProperty(HomeAddressStreet);
this.RegisterIndexedProperty(HomeAddressCity);
this.RegisterIndexedProperty(HomeAddressState);
this.RegisterIndexedProperty(HomeAddressCountryOrRegion);
this.RegisterIndexedProperty(HomeAddressPostalCode);
this.RegisterIndexedProperty(OtherAddressStreet);
this.RegisterIndexedProperty(OtherAddressCity);
this.RegisterIndexedProperty(OtherAddressState);
this.RegisterIndexedProperty(OtherAddressCountryOrRegion);
this.RegisterIndexedProperty(OtherAddressPostalCode);
}
internal ContactSchema()
: base()
{
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using NLog.Config;
using NLog.Filters;
namespace NLog.UnitTests.Layouts
{
using NLog.LayoutRenderers;
using NLog.LayoutRenderers.Wrappers;
using NLog.Layouts;
using NLog.Targets;
using System;
using Xunit;
using static Config.TargetConfigurationTests;
public class SimpleLayoutParserTests : NLogTestBase
{
[Fact]
public void SimpleTest()
{
SimpleLayout l = "${message}";
Assert.Single(l.Renderers);
Assert.IsType<MessageLayoutRenderer>(l.Renderers[0]);
}
[Fact]
public void UnclosedTest()
{
new SimpleLayout("${message");
}
[Fact]
public void UnknownLayoutRenderer()
{
Assert.Throws<NLogConfigurationException>(() => new SimpleLayout("'${{unknown-type}}'"));
}
[Fact]
public void UnknownLayoutRendererProperty()
{
Assert.Throws<NLogConfigurationException>(() => new SimpleLayout("${message:unknown_item=${unknown-value}}"));
}
[Fact]
public void UnknownConditionLayoutRenderer()
{
Assert.Throws<NLogConfigurationException>(() => new SimpleLayout("${when:when=Levl==LogLevel.Info:inner=Unknown}"));
}
[Fact]
public void UnknownLayoutRendererPropertyValue()
{
Assert.Throws<NLogConfigurationException>(() => new SimpleLayout("'${message:withexception=${unknown-value}}'"));
}
[Fact]
public void SingleParamTest()
{
SimpleLayout l = "${event-property:item=AAA}";
Assert.Single(l.Renderers);
var eventPropertyLayout = l.Renderers[0] as EventPropertiesLayoutRenderer;
Assert.NotNull(eventPropertyLayout);
Assert.Equal("AAA", eventPropertyLayout.Item);
}
[Fact]
public void ValueWithColonTest()
{
SimpleLayout l = "${event-property:item=AAA\\:}";
Assert.Single(l.Renderers);
var eventPropertyLayout = l.Renderers[0] as EventPropertiesLayoutRenderer;
Assert.NotNull(eventPropertyLayout);
Assert.Equal("AAA:", eventPropertyLayout.Item);
}
[Fact]
public void ValueWithBracketTest()
{
SimpleLayout l = "${event-property:item=AAA\\}\\:}";
Assert.Equal("${event-property:item=AAA\\}\\:}", l.Text);
Assert.Single(l.Renderers);
var eventPropertyLayout = l.Renderers[0] as EventPropertiesLayoutRenderer;
Assert.NotNull(eventPropertyLayout);
Assert.Equal("AAA}:", eventPropertyLayout.Item);
}
[Fact]
public void DefaultValueTest()
{
SimpleLayout l = "${event-property:BBB}";
Assert.Single(l.Renderers);
var eventPropertyLayout = l.Renderers[0] as EventPropertiesLayoutRenderer;
Assert.NotNull(eventPropertyLayout);
Assert.Equal("BBB", eventPropertyLayout.Item);
}
[Fact]
public void DefaultValueWithBracketTest()
{
SimpleLayout l = "${event-property:AAA\\}\\:}";
Assert.Equal("${event-property:AAA\\}\\:}", l.Text);
Assert.Single(l.Renderers);
var eventPropertyLayout = l.Renderers[0] as EventPropertiesLayoutRenderer;
Assert.NotNull(eventPropertyLayout);
Assert.Equal("AAA}:", eventPropertyLayout.Item);
}
[Fact]
public void DefaultValueWithOtherParametersTest()
{
SimpleLayout l = "${exception:message,type:separator=x}";
Assert.Single(l.Renderers);
ExceptionLayoutRenderer elr = l.Renderers[0] as ExceptionLayoutRenderer;
Assert.NotNull(elr);
Assert.Equal("message,type", elr.Format);
Assert.Equal("x", elr.Separator);
}
[Fact]
public void EmptyValueTest()
{
SimpleLayout l = "${event-property:item=}";
Assert.Single(l.Renderers);
var eventPropertyLayout = l.Renderers[0] as EventPropertiesLayoutRenderer;
Assert.NotNull(eventPropertyLayout);
Assert.Equal("", eventPropertyLayout.Item);
}
[Fact]
public void NestedLayoutTest()
{
SimpleLayout l = "${rot13:inner=${scopenested:topFrames=3:separator=x}}";
Assert.Single(l.Renderers);
var lr = l.Renderers[0] as Rot13LayoutRendererWrapper;
Assert.NotNull(lr);
var nestedLayout = lr.Inner as SimpleLayout;
Assert.NotNull(nestedLayout);
Assert.Equal("${scopenested:topFrames=3:separator=x}", nestedLayout.Text);
Assert.Single(nestedLayout.Renderers);
var nestedLayoutRenderer = nestedLayout.Renderers[0] as ScopeContextNestedStatesLayoutRenderer;
Assert.NotNull(nestedLayoutRenderer);
Assert.Equal(3, nestedLayoutRenderer.TopFrames);
Assert.Equal("x", nestedLayoutRenderer.Separator.ToString());
}
[Fact]
public void DoubleNestedLayoutTest()
{
SimpleLayout l = "${rot13:inner=${rot13:inner=${scopenested:topFrames=3:separator=x}}}";
Assert.Single(l.Renderers);
var lr = l.Renderers[0] as Rot13LayoutRendererWrapper;
Assert.NotNull(lr);
var nestedLayout0 = lr.Inner as SimpleLayout;
Assert.NotNull(nestedLayout0);
Assert.Equal("${rot13:inner=${scopenested:topFrames=3:separator=x}}", nestedLayout0.Text);
var innerRot13 = nestedLayout0.Renderers[0] as Rot13LayoutRendererWrapper;
var nestedLayout = innerRot13.Inner as SimpleLayout;
Assert.NotNull(nestedLayout);
Assert.Equal("${scopenested:topFrames=3:separator=x}", nestedLayout.Text);
Assert.Single(nestedLayout.Renderers);
var nestedLayoutRenderer = nestedLayout.Renderers[0] as ScopeContextNestedStatesLayoutRenderer;
Assert.NotNull(nestedLayoutRenderer);
Assert.Equal(3, nestedLayoutRenderer.TopFrames);
Assert.Equal("x", nestedLayoutRenderer.Separator.ToString());
}
[Fact]
public void DoubleNestedLayoutWithDefaultLayoutParametersTest()
{
SimpleLayout l = "${rot13:${rot13:${scopenested:topFrames=3:separator=x}}}";
Assert.Single(l.Renderers);
var lr = l.Renderers[0] as Rot13LayoutRendererWrapper;
Assert.NotNull(lr);
var nestedLayout0 = lr.Inner as SimpleLayout;
Assert.NotNull(nestedLayout0);
Assert.Equal("${rot13:${scopenested:topFrames=3:separator=x}}", nestedLayout0.Text);
var innerRot13 = nestedLayout0.Renderers[0] as Rot13LayoutRendererWrapper;
var nestedLayout = innerRot13.Inner as SimpleLayout;
Assert.NotNull(nestedLayout);
Assert.Equal("${scopenested:topFrames=3:separator=x}", nestedLayout.Text);
Assert.Single(nestedLayout.Renderers);
var nestedLayoutRenderer = nestedLayout.Renderers[0] as ScopeContextNestedStatesLayoutRenderer;
Assert.NotNull(nestedLayoutRenderer);
Assert.Equal(3, nestedLayoutRenderer.TopFrames);
Assert.Equal("x", nestedLayoutRenderer.Separator.ToString());
}
[Fact]
public void AmbientPropertyTest()
{
SimpleLayout l = "${message:padding=10}";
Assert.Single(l.Renderers);
var pad = l.Renderers[0] as PaddingLayoutRendererWrapper;
Assert.NotNull(pad);
var message = ((SimpleLayout)pad.Inner).Renderers[0] as MessageLayoutRenderer;
Assert.NotNull(message);
}
[Fact]
public void MissingLayoutRendererTest()
{
LogManager.ThrowConfigExceptions = true;
Assert.Throws<NLogConfigurationException>(() =>
{
SimpleLayout l = "${rot13:${foobar}}";
});
}
[Fact]
public void DoubleAmbientPropertyTest()
{
SimpleLayout l = "${message:uppercase=true:padding=10}";
Assert.Single(l.Renderers);
var upperCase = l.Renderers[0] as UppercaseLayoutRendererWrapper;
Assert.NotNull(upperCase);
var pad = ((SimpleLayout)upperCase.Inner).Renderers[0] as PaddingLayoutRendererWrapper;
Assert.NotNull(pad);
var message = ((SimpleLayout)pad.Inner).Renderers[0] as MessageLayoutRenderer;
Assert.NotNull(message);
}
[Fact]
public void ReverseDoubleAmbientPropertyTest()
{
SimpleLayout l = "${message:padding=10:uppercase=true}";
Assert.Single(l.Renderers);
var pad = ((SimpleLayout)l).Renderers[0] as PaddingLayoutRendererWrapper;
Assert.NotNull(pad);
var upperCase = ((SimpleLayout)pad.Inner).Renderers[0] as UppercaseLayoutRendererWrapper;
Assert.NotNull(upperCase);
var message = ((SimpleLayout)upperCase.Inner).Renderers[0] as MessageLayoutRenderer;
Assert.NotNull(message);
}
[Fact]
public void EscapeTest()
{
AssertEscapeRoundTrips(string.Empty);
AssertEscapeRoundTrips("hello ${${}} world!");
AssertEscapeRoundTrips("hello $");
AssertEscapeRoundTrips("hello ${");
AssertEscapeRoundTrips("hello $${{");
AssertEscapeRoundTrips("hello ${message}");
AssertEscapeRoundTrips("hello ${${level}}");
AssertEscapeRoundTrips("hello ${${level}${message}}");
}
[Fact]
public void EvaluateTest()
{
var logEventInfo = LogEventInfo.CreateNullEvent();
logEventInfo.Level = LogLevel.Warn;
Assert.Equal("Warn", SimpleLayout.Evaluate("${level}", logEventInfo));
}
[Fact]
public void EvaluateTest2()
{
Assert.Equal("Off", SimpleLayout.Evaluate("${level}"));
Assert.Equal(string.Empty, SimpleLayout.Evaluate("${message}"));
Assert.Equal(string.Empty, SimpleLayout.Evaluate("${logger}"));
}
private static void AssertEscapeRoundTrips(string originalString)
{
string escapedString = SimpleLayout.Escape(originalString);
SimpleLayout l = escapedString;
string renderedString = l.Render(LogEventInfo.CreateNullEvent());
Assert.Equal(originalString, renderedString);
}
[Fact]
public void LayoutParserEscapeCodesForRegExTestV1()
{
ScopeContext.Clear();
var configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true'>
<variable name=""searchExp""
value=""(?<!\\d[ -]*)(?\u003a(?<digits>\\d)[ -]*)\u007b8,16\u007d(?=(\\d[ -]*)\u007b3\u007d(\\d)(?![ -]\\d))""
/>
<variable name=""message1"" value=""${replace:inner=${message}:searchFor=${searchExp}:replaceWith=\u003a\u003a:regex=true:ignorecase=true}"" />
<targets>
<target name=""d1"" type=""Debug"" layout=""${message1}"" />
</targets>
<rules>
<logger name=""*"" minlevel=""Trace"" writeTo=""d1"" />
</rules>
</nlog>");
var d1 = configuration.FindTargetByName("d1") as DebugTarget;
Assert.NotNull(d1);
var layout = d1.Layout as SimpleLayout;
Assert.NotNull(layout);
var c = layout.Renderers.Count;
Assert.Equal(1, c);
var l1 = layout.Renderers[0] as ReplaceLayoutRendererWrapper;
Assert.NotNull(l1);
Assert.True(l1.Regex);
Assert.True(l1.IgnoreCase);
Assert.Equal(@"::", l1.ReplaceWith);
Assert.Equal(@"(?<!\d[ -]*)(?:(?<digits>\d)[ -]*){8,16}(?=(\d[ -]*){3}(\d)(?![ -]\d))", l1.SearchFor);
}
[Fact]
public void LayoutParserEscapeCodesForRegExTestV2()
{
ScopeContext.Clear();
var configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true'>
<variable name=""searchExp""
value=""(?<!\\d[ -]*)(?\:(?<digits>\\d)[ -]*)\{8,16\}(?=(\\d[ -]*)\{3\}(\\d)(?![ -]\\d))""
/>
<variable name=""message1"" value=""${replace:inner=${message}:searchFor=${searchExp}:replaceWith=\u003a\u003a:regex=true:ignorecase=true}"" />
<targets>
<target name=""d1"" type=""Debug"" layout=""${message1}"" />
</targets>
<rules>
<logger name=""*"" minlevel=""Trace"" writeTo=""d1"" />
</rules>
</nlog>");
var d1 = configuration.FindTargetByName("d1") as DebugTarget;
Assert.NotNull(d1);
var layout = d1.Layout as SimpleLayout;
Assert.NotNull(layout);
var c = layout.Renderers.Count;
Assert.Equal(1, c);
var l1 = layout.Renderers[0] as ReplaceLayoutRendererWrapper;
Assert.NotNull(l1);
Assert.True(l1.Regex);
Assert.True(l1.IgnoreCase);
Assert.Equal(@"::", l1.ReplaceWith);
Assert.Equal(@"(?<!\d[ -]*)(?:(?<digits>\d)[ -]*){8,16}(?=(\d[ -]*){3}(\d)(?![ -]\d))", l1.SearchFor);
}
[Fact]
public void InnerLayoutWithColonTest_with_workaround()
{
SimpleLayout l = @"${when:when=1 == 1:Inner=Test${literal:text=\:} Hello}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("Test: Hello", l.Render(le));
}
[Fact]
public void InnerLayoutWithColonTest()
{
SimpleLayout l = @"${when:when=1 == 1:Inner=Test\: Hello}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("Test: Hello", l.Render(le));
}
[Fact]
public void InnerLayoutWithSlashSingleTest()
{
SimpleLayout l = @"${when:when=1 == 1:Inner=Test\Hello}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("Test\\Hello", l.Render(le));
}
[Fact]
public void InnerLayoutWithSlashTest()
{
SimpleLayout l = @"${when:when=1 == 1:Inner=Test\Hello}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("Test\\Hello", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest()
{
SimpleLayout l = @"${when:when=1 == 1:Inner=Test{Hello\}}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("Test{Hello}", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest2()
{
SimpleLayout l = @"${when:when=1 == 1:Inner=Test{Hello\\}}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal(@"Test{Hello\}", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest_reverse()
{
SimpleLayout l = @"${when:Inner=Test{Hello\}:when=1 == 1}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("Test{Hello}", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest_no_escape()
{
SimpleLayout l = @"${when:when=1 == 1:Inner=Test{Hello}}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("Test{Hello}", l.Render(le));
}
[Fact]
public void InnerLayoutWithHashTest()
{
SimpleLayout l = @"${when:when=1 == 1:inner=Log_{#\}.log}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("Log_{#}.log", l.Render(le));
}
[Fact]
public void InnerLayoutWithHashTest_need_escape()
{
SimpleLayout l = @"${when:when=1 == 1:inner=L\}.log}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("L}.log", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest_needEscape()
{
SimpleLayout l = @"${when:when=1 == 1:inner=\}{.log}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("}{.log", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest_needEscape2()
{
SimpleLayout l = @"${when:when=1 == 1:inner={\}\}{.log}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("{}}{.log", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest_needEscape3()
{
SimpleLayout l = @"${when:when=1 == 1:inner={\}\}\}.log}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("{}}}.log", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest_needEscape4()
{
SimpleLayout l = @"${when:when=1 == 1:inner={\}\}\}.log}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("{}}}.log", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest_needEscape5()
{
SimpleLayout l = @"${when:when=1 == 1:inner=\}{a\}.log}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("}{a}.log", l.Render(le));
}
[Fact]
public void InnerLayoutWithHashTest_and_layoutrender()
{
SimpleLayout l = @"${when:when=1 == 1:inner=${counter}/Log_{#\}.log}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("1/Log_{#}.log", l.Render(le));
}
[Fact]
public void InvalidLayoutWillParsePartly()
{
using (new NoThrowNLogExceptions())
{
SimpleLayout l = @"aaa ${iDontExist} bbb";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("aaa bbb", l.Render(le));
}
}
[Fact]
public void InvalidLayoutWillThrowIfExceptionThrowingIsOn()
{
LogManager.ThrowConfigExceptions = true;
Assert.Throws<NLogConfigurationException>(() =>
{
SimpleLayout l = @"aaa ${iDontExist} bbb";
});
}
[Fact]
public void InvalidLayoutWithExistingRenderer_WillThrowIfExceptionThrowingIsOn()
{
ConfigurationItemFactory.Default.LayoutRenderers.RegisterDefinition("layoutrenderer-with-list", typeof(LayoutRendererWithListParam));
LogManager.ThrowConfigExceptions = true;
Assert.Throws<NLogConfigurationException>(() =>
{
SimpleLayout l = @"${layoutrenderer-with-list:}";
});
}
[Fact]
public void UnknownPropertyInLayout_WillThrowIfExceptionThrowingIsOn()
{
ConfigurationItemFactory.Default.LayoutRenderers.RegisterDefinition("layoutrenderer-with-list", typeof(LayoutRendererWithListParam));
LogManager.ThrowConfigExceptions = true;
Assert.Throws<NLogConfigurationException>(() =>
{
SimpleLayout l = @"${layoutrenderer-with-list:iDontExist=1}";
});
}
/// <summary>
///
/// Test layout with Generic List type. - is the separator
///
///
/// </summary>
/// <remarks>
/// comma escape is backtick (cannot use backslash due to layout parse)
/// </remarks>
/// <param name="input"></param>
/// <param name="propname"></param>
/// <param name="expected"></param>
[Theory]
[InlineData("2,3,4", "numbers", "2-3-4")]
[InlineData("a,b,c", "Strings", "a-b-c")]
[InlineData("a,b,c", "Objects", "a-b-c")]
[InlineData("a,,b,c", "Strings", "a--b-c")]
[InlineData("a`b,c", "Strings", "a`b-c")]
[InlineData("a\'b,c", "Strings", "a'b-c")]
[InlineData("'a,b',c", "Strings", "a,b-c")]
[InlineData("2.0,3.0,4.0", "doubles", "2-3-4")]
[InlineData("2.1,3.2,4.3", "doubles", "2.1-3.2-4.3")]
[InlineData("Ignore,Neutral,Ignore", "enums", "Ignore-Neutral-Ignore")]
[InlineData("ASCII,ISO-8859-1, UTF-8", "encodings", "us-ascii-iso-8859-1-utf-8")]
[InlineData("ASCII,ISO-8859-1,UTF-8", "encodings", "us-ascii-iso-8859-1-utf-8")]
[InlineData("Value1,Value3,Value2", "FlagEnums", "Value1-Value3-Value2")]
[InlineData("2,3,4", "IEnumerableNumber", "2-3-4")]
[InlineData("2,3,4", "IListNumber", "2-3-4")]
[InlineData("2,3,4", "HashsetNumber", "2-3-4")]
#if !NET35
[InlineData("2,3,4", "ISetNumber", "2-3-4")]
#endif
[InlineData("a,b,c", "IEnumerableString", "a-b-c")]
[InlineData("a,b,c", "IListString", "a-b-c")]
[InlineData("a,b,c", "HashSetString", "a-b-c")]
#if !NET35
[InlineData("a,b,c", "ISetString", "a-b-c")]
#endif
public void LayoutWithListParamTest(string input, string propname, string expected)
{
ConfigurationItemFactory.Default.LayoutRenderers.RegisterDefinition("layoutrenderer-with-list", typeof(LayoutRendererWithListParam));
SimpleLayout l = $@"${{layoutrenderer-with-list:{propname}={input}}}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
var actual = l.Render(le);
Assert.Equal(expected, actual);
}
[Theory]
[InlineData("2,,3,4", "numbers")]
[InlineData("a,bc", "numbers")]
[InlineData("value1,value10", "FlagEnums")]
public void LayoutWithListParamTest_incorrect(string input, string propname)
{
//note flags enum already supported
//can;t convert empty to int
ConfigurationItemFactory.Default.LayoutRenderers.RegisterDefinition("layoutrenderer-with-list", typeof(LayoutRendererWithListParam));
Assert.Throws<NLogConfigurationException>(() =>
{
SimpleLayout l = $@"${{layoutrenderer-with-list:{propname}={input}}}";
});
}
[Theory]
[InlineData(@" ${literal:text={0\} {1\}}")]
[InlineData(@" ${cached:${literal:text={0\} {1\}}}")]
[InlineData(@" ${cached:${cached:${literal:text={0\} {1\}}}}")]
[InlineData(@" ${cached:${cached:${cached:${literal:text={0\} {1\}}}}}")]
[InlineData(@"${cached:${cached:${cached:${cached:${literal:text={0\} {1\}}}}}}")]
public void Render_EscapedBrackets_ShouldRenderAllBrackets(string input)
{
SimpleLayout simple = input.Trim();
var result = simple.Render(LogEventInfo.CreateNullEvent());
Assert.Equal("{0} {1}", result);
}
[Fact]
void FuncLayoutRendererRegisterTest1()
{
LayoutRenderer.Register("the-answer", (info) => "42");
Layout l = "${the-answer}";
var result = l.Render(LogEventInfo.CreateNullEvent());
Assert.Equal("42", result);
}
[Fact]
void FuncLayoutRendererFluentMethod_ThreadAgnostic_Test()
{
// Arrange
var layout = Layout.FromMethod(l => "42", LayoutRenderOptions.ThreadAgnostic);
// Act
var result = layout.Render(LogEventInfo.CreateNullEvent());
// Assert
Assert.Equal("42", result);
Assert.True(layout.ThreadAgnostic);
}
[Fact]
void FuncLayoutRendererFluentMethod_Test()
{
// Arrange
var layout = Layout.FromMethod(l => "42", LayoutRenderOptions.None);
// Act
var result = layout.Render(LogEventInfo.CreateNullEvent());
// Assert
Assert.Equal("42", result);
Assert.False(layout.ThreadAgnostic);
}
[Fact]
void FuncLayoutRendererFluentMethod_NullThrows_Test()
{
// Arrange
Assert.Throws<ArgumentNullException>(() => Layout.FromMethod(null));
}
[Fact]
void FuncLayoutRendererRegisterTest1WithXML()
{
LayoutRenderer.Register("the-answer", (info) => 42);
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true'>
<targets>
<target name='debug' type='Debug' layout= 'TheAnswer=${the-answer:Format=D3}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
var logger = LogManager.GetCurrentClassLogger();
logger.Debug("test1");
AssertDebugLastMessage("debug", "TheAnswer=042");
}
[Fact]
void FuncLayoutRendererRegisterTest2()
{
LayoutRenderer.Register("message-length", (info) => info.Message.Length);
Layout l = "${message-length}";
var result = l.Render(LogEventInfo.Create(LogLevel.Error, "logger-adhoc", "1234567890"));
Assert.Equal("10", result);
}
[Fact]
void SimpleLayout_FromString_ThrowConfigExceptions()
{
Assert.Throws<NLogConfigurationException>(() => Layout.FromString("${evil}", true));
}
[Fact]
void SimpleLayout_FromString_NoThrowConfigExceptions()
{
Assert.NotNull(Layout.FromString("${evil}", false));
}
[Theory]
[InlineData("", true)]
[InlineData(null, true)]
[InlineData("'a'", true)]
[InlineData("${gdc:a}", false)]
[InlineData("${threadname}", false)]
public void FromString_isFixedText(string input, bool expected)
{
// Act
var layout = (SimpleLayout)Layout.FromString(input);
layout.Initialize(null);
// Assert
Assert.Equal(expected, layout.IsFixedText);
}
[Theory]
[InlineData("", true)]
[InlineData(null, true)]
[InlineData("'a'", true)]
[InlineData("${gdc:a}", true)]
[InlineData("${threadname}", false)]
public void FromString_isThreadAgnostic(string input, bool expected)
{
// Act
var layout = (SimpleLayout)Layout.FromString(input);
layout.Initialize(null);
// Assert
Assert.Equal(expected, layout.ThreadAgnostic);
}
[Theory]
[InlineData("", "")]
[InlineData(null, "")]
[InlineData("'a'", "'a'")]
[InlineData("${gdc:a}", "")]
public void Render(string input, string expected)
{
var layout = (SimpleLayout)Layout.FromString(input);
// Act
var result = layout.Render(LogEventInfo.CreateNullEvent());
// Assert
Assert.Equal(expected, result);
}
[Fact]
public void Parse_AppDomainFixedOutput_ConvertToLiteral()
{
// Arrange
var input = "${newline}";
// Act
var layout = (SimpleLayout)Layout.FromString(input);
// Assert
var single = Assert.Single(layout.Renderers);
Assert.IsType<LiteralLayoutRenderer>(single);
}
[Fact]
public void Parse_MultipleAppDomainFixedOutput_ConvertSingleToLiteral()
{
// Arrange
var input = "${newline}${machinename}";
// Act
var layout = (SimpleLayout)Layout.FromString(input);
// Assert
var single = Assert.Single(layout.Renderers);
Assert.IsType<LiteralLayoutRenderer>(single);
}
[Fact]
public void Parse_AppDomainFixedOutputWithRawValue_ConvertSingleToLiteralAndKeepRawValue()
{
// Arrange
var input = "${processid}";
// Act
var layout = (SimpleLayout)Layout.FromString(input);
// Assert
Assert.True(layout.IsFixedText);
var single = Assert.Single(layout.Renderers);
Assert.IsType<LiteralWithRawValueLayoutRenderer>(single);
var succeeded = layout.TryGetRawValue(LogEventInfo.CreateNullEvent(), out var rawValue);
var rawValueInt = Assert.IsType<int>(rawValue);
Assert.True(succeeded);
Assert.True(rawValueInt > 0);
}
/// <summary>
/// Combined literals should not support rawValue
/// </summary>
[Theory]
[InlineData("${newline}${processid}")]
[InlineData("${processid}${processid}")]
[InlineData("${processid}${processname}")]
[InlineData("${processname}${processid}")]
[InlineData("${processname}-${processid}")]
public void Parse_Multiple_ConvertSingleToLiteralWithoutRaw(string input)
{
// Act
var layout = (SimpleLayout)Layout.FromString(input);
// Assert
var single = Assert.Single(layout.Renderers);
Assert.IsType<LiteralLayoutRenderer>(single);
}
private class LayoutRendererWithListParam : LayoutRenderer
{
public List<double> Doubles { get; set; }
public List<FilterResult> Enums { get; set; }
public List<MyFlagsEnum> FlagEnums { get; set; }
public List<int> Numbers { get; set; }
public List<string> Strings { get; set; }
public List<object> Objects { get; set; }
public List<Encoding> Encodings { get; set; }
public IEnumerable<string> IEnumerableString { get; set; }
public IEnumerable<int> IEnumerableNumber { get; set; }
public IList<string> IListString { get; set; }
public IList<int> IListNumber { get; set; }
#if !NET35
public ISet<string> ISetString { get; set; }
public ISet<int> ISetNumber { get; set; }
#endif
public HashSet<int> HashSetNumber { get; set; }
public HashSet<string> HashSetString { get; set; }
/// <summary>
/// Renders the specified environmental information and appends it to the specified <see cref="StringBuilder" />.
/// </summary>
/// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
/// <param name="logEvent">Logging event.</param>
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
Append(builder, Strings);
AppendFormattable(builder, Numbers);
AppendFormattable(builder, Enums);
AppendFormattable(builder, FlagEnums);
AppendFormattable(builder, Doubles);
Append(builder, Encodings?.Select(e => e.BodyName).ToList());
Append(builder, Objects);
Append(builder, IEnumerableString);
AppendFormattable(builder, IEnumerableNumber);
Append(builder, IListString);
AppendFormattable(builder, IListNumber);
#if !NET35
Append(builder, ISetString);
AppendFormattable(builder, ISetNumber);
#endif
Append(builder, HashSetString);
AppendFormattable(builder, HashSetNumber);
}
private void Append<T>(StringBuilder builder, IEnumerable<T> items)
{
if (items != null) builder.Append(string.Join("-", items.ToArray()));
}
private void AppendFormattable<T>(StringBuilder builder, IEnumerable<T> items)
where T : IFormattable
{
if (items != null) builder.Append(string.Join("-", items.Select(it => it.ToString(null, CultureInfo.InvariantCulture)).ToArray()));
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using OpenMetaverse;
using OpenSim.Region.Framework.Interfaces;
using Nini.Config;
using Aurora.Framework;
using System.Timers;
using Timer = System.Timers.Timer;
namespace OpenSim.Region.Framework.Scenes
{
/// <summary>
/// Manager for adding, closing, reseting, and restarting scenes.
/// </summary>
public class SceneManager : ISceneManager, IApplicationPlugin
{
#region Declares
#region Events
public event NewScene OnAddedScene;
public event NewScene OnCloseScene;
#endregion
private ISimulationBase m_OpenSimBase;
private int RegionsFinishedStarting = 0;
public int AllRegions { get; set; }
protected ISimulationDataStore m_simulationDataService;
public ISimulationDataStore SimulationDataService
{
get { return m_simulationDataService; }
set { m_simulationDataService = value; }
}
private IConfigSource m_config = null;
public IConfigSource ConfigSource
{
get { return m_config; }
}
private readonly List<IScene> m_localScenes = new List<IScene> ();
public List<IScene> GetAllScenes() { return new List<IScene>(m_localScenes); }
public IScene GetCurrentOrFirstScene()
{
if (MainConsole.Instance.ConsoleScene == null)
{
if (m_localScenes.Count > 0)
{
return m_localScenes[0];
}
return null;
}
return MainConsole.Instance.ConsoleScene;
}
#endregion
#region IApplicationPlugin members
public void PreStartup(ISimulationBase simBase)
{
m_OpenSimBase = simBase;
IConfig handlerConfig = simBase.ConfigSource.Configs["ApplicationPlugins"];
if (handlerConfig.GetString("SceneManager", "") != Name)
return;
m_config = simBase.ConfigSource;
//Register us!
m_OpenSimBase.ApplicationRegistry.RegisterModuleInterface<ISceneManager>(this);
}
public void Initialize(ISimulationBase simBase)
{
IConfig handlerConfig = simBase.ConfigSource.Configs["ApplicationPlugins"];
if (handlerConfig.GetString("SceneManager", "") != Name)
return;
string name = "FileBasedDatabase";
// Try reading the [SimulationDataStore] section
IConfig simConfig = simBase.ConfigSource.Configs["SimulationDataStore"];
if (simConfig != null)
{
name = simConfig.GetString("DatabaseLoaderName", "FileBasedDatabase");
}
IConfig gridConfig = m_config.Configs["Configuration"];
m_RegisterRegionPassword = Util.Md5Hash(gridConfig.GetString("RegisterRegionPassword", m_RegisterRegionPassword));
ISimulationDataStore[] stores = AuroraModuleLoader.PickupModules<ISimulationDataStore> ().ToArray ();
List<string> storeNames = new List<string>();
foreach (ISimulationDataStore store in stores)
{
if (store.Name.ToLower() == name.ToLower())
{
m_simulationDataService = store;
break;
}
storeNames.Add(store.Name);
}
if (m_simulationDataService == null)
{
MainConsole.Instance.ErrorFormat("[SceneManager]: FAILED TO LOAD THE SIMULATION SERVICE AT '{0}', ONLY OPTIONS ARE {1}, QUITING...", name, string.Join(", ", storeNames.ToArray()));
Console.Read ();//Wait till they see
Environment.Exit(0);
}
m_simulationDataService.Initialise();
AddConsoleCommands();
//Load the startup modules for the region
m_startupPlugins = AuroraModuleLoader.PickupModules<ISharedRegionStartupModule>();
m_OpenSimBase.EventManager.RegisterEventHandler("RegionInfoChanged", RegionInfoChanged);
}
public void ReloadConfiguration(IConfigSource config)
{
//Update this
m_config = config;
if (m_localScenes == null)
return;
foreach (IScene scene in m_localScenes)
{
scene.Config = config;
scene.PhysicsScene.PostInitialise(config);
}
}
public void PostInitialise()
{
}
public void Start()
{
}
public void PostStart()
{
}
public string Name
{
get { return "SceneManager"; }
}
public void Dispose()
{
}
public void Close()
{
if (m_localScenes == null)
return;
IScene[] scenes = new IScene[m_localScenes.Count];
m_localScenes.CopyTo(scenes, 0);
// collect known shared modules in sharedModules
foreach (IScene t in scenes)
{
// close scene/region
CloseRegion (t, ShutdownType.Immediate, 0);
}
}
#endregion
#region Startup complete
public void HandleStartupComplete(IScene scene, List<string> data)
{
MainConsole.Instance.Info("[SceneManager]: Startup Complete in region " + scene.RegionInfo.RegionName);
RegionsFinishedStarting++;
if (RegionsFinishedStarting >= AllRegions)
FinishStartUp();
}
private void FinishStartUp()
{
//Tell modules about it
StartupCompleteModules();
m_OpenSimBase.RunStartupCommands();
TimeSpan timeTaken = DateTime.Now - m_OpenSimBase.StartupTime;
MainConsole.Instance.InfoFormat ("[SceneManager]: All regions are started. This took {0}m {1}.{2}s", timeTaken.Minutes, timeTaken.Seconds, timeTaken.Milliseconds);
AuroraModuleLoader.ClearCache ();
// In 99.9% of cases it is a bad idea to manually force garbage collection. However,
// this is a rare case where we know we have just went through a long cycle of heap
// allocations, and there is no more work to be done until someone logs in
GC.Collect ();
}
#endregion
#region ForEach functions
public void ForEachCurrentScene(Action<IScene> func)
{
if (MainConsole.Instance.ConsoleScene == null)
{
m_localScenes.ForEach(func);
}
else
{
func (MainConsole.Instance.ConsoleScene);
}
}
public void ForEachScene(Action<IScene> action)
{
m_localScenes.ForEach(action);
}
#endregion
#region TrySetScene functions
/// <summary>
/// Checks to see whether a region with the given name exists, and then sets the MainConsole.Instance.ConsoleScene ref
/// </summary>
/// <param name="regionName"></param>
/// <returns></returns>
private bool TrySetConsoleScene(string regionName)
{
if ((String.Compare(regionName, "root") == 0))
{
MainConsole.Instance.ConsoleScene = null;
return true;
}
#if (!ISWIN)
foreach (IScene scene in m_localScenes)
{
if (String.Compare(scene.RegionInfo.RegionName, regionName, true) == 0)
{
MainConsole.Instance.ConsoleScene = scene;
return true;
}
}
#else
foreach (IScene scene in m_localScenes.Where(scene => String.Compare(scene.RegionInfo.RegionName, regionName, true) == 0))
{
MainConsole.Instance.ConsoleScene = scene;
return true;
}
#endif
return false;
}
/// <summary>
/// Changes the console scene to a new region, also can pass 'root' down to set it to no console scene
/// </summary>
/// <param name="newRegionName"></param>
/// <returns></returns>
public bool ChangeConsoleRegion(string newRegionName)
{
if (!TrySetConsoleScene(newRegionName))
{
MainConsole.Instance.Info (String.Format ("Couldn't select region {0}", newRegionName));
return false;
}
string regionName = (MainConsole.Instance.ConsoleScene == null ?
"root" : MainConsole.Instance.ConsoleScene.RegionInfo.RegionName);
if (MainConsole.Instance != null)
MainConsole.Instance.DefaultPrompt = String.Format ("Region ({0}) ", regionName);
return true;
}
#endregion
#region TryGet functions
/// <summary>
/// Gets a region by its region name
/// </summary>
/// <param name="regionName"></param>
/// <param name="scene"></param>
/// <returns></returns>
public bool TryGetScene (string regionName, out IScene scene)
{
foreach (IScene mscene in m_localScenes)
{
if (String.Compare(mscene.RegionInfo.RegionName, regionName, true) == 0)
{
scene = mscene;
return true;
}
}
scene = null;
return false;
}
/// <summary>
/// Gets a region by its region UUID
/// </summary>
/// <param name="regionID"></param>
/// <param name="scene"></param>
/// <returns></returns>
public bool TryGetScene(UUID regionID, out IScene scene)
{
foreach (IScene mscene in m_localScenes)
{
if (mscene.RegionInfo.RegionID == regionID)
{
scene = mscene;
return true;
}
}
scene = null;
return false;
}
/// <summary>
/// Gets a region at the given location
/// </summary>
/// <param name="locX">In meters</param>
/// <param name="locY">In meters</param>
/// <param name="scene"></param>
/// <returns></returns>
public bool TryGetScene(int locX, int locY, out IScene scene)
{
foreach (IScene mscene in m_localScenes)
{
if (mscene.RegionInfo.RegionLocX == locX &&
mscene.RegionInfo.RegionLocY == locY)
{
scene = mscene;
return true;
}
}
scene = null;
return false;
}
/// <summary>
/// Gets a region at the given location
/// </summary>
/// <param name="RegionHandle"></param>
/// <param name="scene"></param>
/// <returns></returns>
public bool TryGetScene(ulong RegionHandle, out IScene scene)
{
int X, Y;
Util.UlongToInts (RegionHandle, out X, out Y);
return TryGetScene (X, Y, out scene);
}
#endregion
#region Add a region
public IScene StartNewRegion (RegionInfo regionInfo)
{
MainConsole.Instance.InfoFormat("[SceneManager]: Starting region \"{0}\" at @ {1},{2}", regionInfo.RegionName,
regionInfo.RegionLocX / 256, regionInfo.RegionLocY / 256);
ISceneLoader sceneLoader = m_OpenSimBase.ApplicationRegistry.RequestModuleInterface<ISceneLoader> ();
if (sceneLoader == null)
throw new Exception ("No Scene Loader Interface!");
//Get the new scene from the interface
IScene scene = sceneLoader.CreateScene (regionInfo);
#if (!ISWIN)
foreach (IScene loadedScene in m_localScenes)
{
if (loadedScene.RegionInfo.RegionName == regionInfo.RegionName && loadedScene.RegionInfo.RegionHandle == regionInfo.RegionHandle)
{
throw new Exception("Duplicate region!");
}
}
#else
if (m_localScenes.Any(loadedScene => loadedScene.RegionInfo.RegionName == regionInfo.RegionName &&
loadedScene.RegionInfo.RegionHandle == regionInfo.RegionHandle))
{
throw new Exception("Duplicate region!");
}
#endif
StartNewRegion (scene);
return scene;
}
/// <summary>
/// Execute the region creation process. This includes setting up scene infrastructure.
/// </summary>
/// <param name="scene"></param>
/// <returns></returns>
public void StartNewRegion(IScene scene)
{
//Do this here so that we don't have issues later when startup complete messages start coming in
m_localScenes.Add (scene);
StartModules (scene);
//Start the heartbeats
scene.StartHeartbeat();
//Tell the scene that the startup is complete
// Note: this event is added in the scene constructor
scene.FinishedStartup("Startup", new List<string>());
}
/// <summary>
/// Gets a new copy of the simulation data store, keep one per region
/// </summary>
/// <returns></returns>
public ISimulationDataStore GetNewSimulationDataStore()
{
return m_simulationDataService.Copy();
}
#endregion
#region Reset a region
public void ResetRegion (IScene scene)
{
if (scene == null)
{
MainConsole.Instance.Warn("You must use this command on a region. Use 'change region' to change to the region you would like to change");
return;
}
IBackupModule backup = scene.RequestModuleInterface<IBackupModule> ();
if(backup != null)
backup.DeleteAllSceneObjects();//Remove all the objects from the region
ITerrainModule module = scene.RequestModuleInterface<ITerrainModule> ();
if (module != null)
module.ResetTerrain();//Then remove the terrain
//Then reset the textures
scene.RegionInfo.RegionSettings.TerrainTexture1 = RegionSettings.DEFAULT_TERRAIN_TEXTURE_1;
scene.RegionInfo.RegionSettings.TerrainTexture2 = RegionSettings.DEFAULT_TERRAIN_TEXTURE_2;
scene.RegionInfo.RegionSettings.TerrainTexture3 = RegionSettings.DEFAULT_TERRAIN_TEXTURE_3;
scene.RegionInfo.RegionSettings.TerrainTexture4 = RegionSettings.DEFAULT_TERRAIN_TEXTURE_4;
scene.RegionInfo.RegionSettings.Save ();
MainConsole.Instance.Warn ("Region " + scene.RegionInfo.RegionName + " was reset");
}
#endregion
#region Restart a region
public void RestartRegion (IScene scene)
{
CloseRegion (scene, ShutdownType.Immediate, 0);
StartNewRegion (scene.RegionInfo);
}
#endregion
#region Shutdown regions
/// <summary>
/// Shuts down and permanently removes all info associated with the region
/// </summary>
/// <param name="scene"></param>
/// <param name="cleanup"></param>
public void RemoveRegion (IScene scene, bool cleanup)
{
IBackupModule backup = scene.RequestModuleInterface<IBackupModule>();
if (backup != null)
backup.DeleteAllSceneObjects();
scene.RegionInfo.HasBeenDeleted = true;
CloseRegion (scene, ShutdownType.Immediate, 0);
if (!cleanup)
return;
IRegionLoader[] loaders = m_OpenSimBase.ApplicationRegistry.RequestModuleInterfaces<IRegionLoader>();
foreach (IRegionLoader loader in loaders)
{
loader.DeleteRegion(scene.RegionInfo);
}
}
/// <summary>
/// Shuts down a region and removes it from all running modules
/// </summary>
/// <param name="scene"></param>
/// <param name="type"></param>
/// <param name="seconds"></param>
/// <returns></returns>
public void CloseRegion (IScene scene, ShutdownType type, int seconds)
{
if (type == ShutdownType.Immediate)
{
InnerCloseRegion (scene);
}
else
{
Timer t = new Timer (seconds * 1000);//Millisecond conversion
#if (!ISWIN)
t.Elapsed +=
delegate(object sender, ElapsedEventArgs e)
{
CloseRegion(scene, ShutdownType.Immediate, 0);
};
#else
t.Elapsed += (sender, e) => CloseRegion(scene, ShutdownType.Immediate, 0);
#endif
t.AutoReset = false;
t.Start ();
}
}
private void InnerCloseRegion (IScene scene)
{
//Make sure that if we are set on the console, that we are removed from it
if ((MainConsole.Instance.ConsoleScene != null) &&
(MainConsole.Instance.ConsoleScene.RegionInfo.RegionID == scene.RegionInfo.RegionID))
ChangeConsoleRegion ("root");
m_localScenes.Remove (scene);
scene.Close ();
CloseModules (scene);
}
#endregion
#region Update region info
public object RegionInfoChanged(string funcName, object param)
{
UpdateRegionInfo((RegionInfo)((object[])param)[0], (RegionInfo)((object[])param)[1]);
return null;
}
public void UpdateRegionInfo (RegionInfo oldRegion, RegionInfo region)
{
foreach(IScene scene in m_localScenes)
{
if(scene.RegionInfo.RegionID == region.RegionID)
{
bool needsGridUpdate =
scene.RegionInfo.RegionName != region.RegionName ||
scene.RegionInfo.RegionLocX != region.RegionLocX ||
scene.RegionInfo.RegionLocY != region.RegionLocY ||
scene.RegionInfo.RegionLocZ != region.RegionLocZ ||
scene.RegionInfo.AccessLevel != region.AccessLevel ||
scene.RegionInfo.RegionType != region.RegionType// ||
//scene.RegionInfo.RegionSizeX != region.RegionSizeX //Don't allow for size updates on the fly, that needs a restart
//scene.RegionInfo.RegionSizeY != region.RegionSizeY
//scene.RegionInfo.RegionSizeZ != region.RegionSizeZ
;
bool needsRegistration =
scene.RegionInfo.RegionName != region.RegionName ||
scene.RegionInfo.RegionLocX != region.RegionLocX ||
scene.RegionInfo.RegionLocY != region.RegionLocY;
region.RegionSettings = scene.RegionInfo.RegionSettings;
region.EstateSettings = scene.RegionInfo.EstateSettings;
region.GridSecureSessionID = scene.RegionInfo.GridSecureSessionID;
scene.RegionInfo = region;
if(needsRegistration)
scene.RequestModuleInterface<IGridRegisterModule>().RegisterRegionWithGrid(scene, false, false, m_RegisterRegionPassword);
else if(needsGridUpdate)
scene.RequestModuleInterface<IGridRegisterModule>().UpdateGridRegion(scene);
//Tell clients about the changes
IEstateModule es = scene.RequestModuleInterface<IEstateModule>();
if(es != null)
es.sendRegionHandshakeToAll();
}
}
}
#endregion
#region ISharedRegionStartupModule plugins
protected List<ISharedRegionStartupModule> m_startupPlugins = new List<ISharedRegionStartupModule> ();
private string m_RegisterRegionPassword = "";
protected void StartModules(IScene scene)
{
//Run all the initialization
//First, Initialize the SharedRegionStartupModule
foreach (ISharedRegionStartupModule module in m_startupPlugins)
{
module.Initialise(scene, m_config, m_OpenSimBase);
}
//Then do the ISharedRegionModule and INonSharedRegionModules
MainConsole.Instance.Debug ("[Modules]: Loading region modules");
IRegionModulesController controller;
if (m_OpenSimBase.ApplicationRegistry.TryRequestModuleInterface (out controller))
{
controller.AddRegionToModules (scene);
}
else
MainConsole.Instance.Error ("[Modules]: The new RegionModulesController is missing...");
//Then finish the rest of the SharedRegionStartupModules
foreach (ISharedRegionStartupModule module in m_startupPlugins)
{
module.PostInitialise(scene, m_config, m_OpenSimBase);
}
foreach (ISharedRegionStartupModule module in m_startupPlugins)
{
module.FinishStartup(scene, m_config, m_OpenSimBase);
}
foreach (ISharedRegionStartupModule module in m_startupPlugins)
{
module.PostFinishStartup(scene, m_config, m_OpenSimBase);
}
if (OnAddedScene != null)
OnAddedScene (scene);
}
protected void StartupCompleteModules()
{
foreach (ISharedRegionStartupModule module in m_startupPlugins)
{
try
{
module.StartupComplete();
}
catch (Exception ex) { MainConsole.Instance.Warn("[SceneManager]: Exception running StartupComplete, " + ex); }
}
}
protected void CloseModules(IScene scene)
{
IRegionModulesController controller;
if (m_OpenSimBase.ApplicationRegistry.TryRequestModuleInterface(out controller))
controller.RemoveRegionFromModules(scene);
foreach (ISharedRegionStartupModule module in m_startupPlugins)
{
module.Close(scene);
}
if (OnCloseScene != null)
OnCloseScene(scene);
}
public void DeleteRegion(UUID regionID)
{
IScene scene;
if (TryGetScene(regionID, out scene))
DeleteSceneFromModules(scene);
}
protected void DeleteSceneFromModules(IScene scene)
{
foreach (ISharedRegionStartupModule module in m_startupPlugins)
{
module.DeleteRegion(scene);
}
}
#endregion
#region Console Commands
private void AddConsoleCommands()
{
if (MainConsole.Instance == null)
return;
MainConsole.Instance.Commands.AddCommand ("show users", "show users [full]", "Shows users in the given region (if full is added, child agents are shown as well)", HandleShowUsers);
MainConsole.Instance.Commands.AddCommand ("show regions", "show regions", "Show information about all regions in this instance", HandleShowRegions);
MainConsole.Instance.Commands.AddCommand ("show maturity", "show maturity", "Show all region's maturity levels", HandleShowMaturity);
MainConsole.Instance.Commands.AddCommand ("force update", "force update", "Force the update of all objects on clients", HandleForceUpdate);
MainConsole.Instance.Commands.AddCommand("debug packet", "debug packet [level]", "Turn on packet debugging", Debug);
MainConsole.Instance.Commands.AddCommand("debug scene", "debug scene [scripting] [collisions] [physics]", "Turn on scene debugging", Debug);
MainConsole.Instance.Commands.AddCommand("change region", "change region [region name]", "Change current console region", ChangeSelectedRegion);
MainConsole.Instance.Commands.AddCommand("load xml2", "load xml2", "Load a region's data from XML2 format", LoadXml2);
MainConsole.Instance.Commands.AddCommand("save xml2", "save xml2", "Save a region's data in XML2 format", SaveXml2);
MainConsole.Instance.Commands.AddCommand("load oar", "load oar [oar name] [--merge] [--skip-assets] [--OffsetX=#] [--OffsetY=#] [--OffsetZ=#] [--FlipX] [--FlipY] [--UseParcelOwnership] [--CheckOwnership]",
"Load a region's data from OAR archive. \n" +
"--merge will merge the oar with the existing scene (including parcels). \n" +
"--skip-assets will load the oar but ignore the assets it contains. \n" +
"--OffsetX will change where the X location of the oar is loaded, and the same for Y and Z. \n" +
"--FlipX flips the region on the X axis. \n" +
"--FlipY flips the region on the Y axis. \n" +
"--UseParcelOwnership changes who the default owner of objects whose owner cannot be found from the Estate Owner to the parcel owner on which the object is found. \n" +
"--CheckOwnership asks for each UUID that is not found on the grid what user it should be changed to (useful for changing UUIDs from other grids, but very long with many users). ", LoadOar);
MainConsole.Instance.Commands.AddCommand("save oar", "save oar [<OAR path>] [--perm=<permissions>] ", "Save a region's data to an OAR archive" + Environment.NewLine
+ "<OAR path> The OAR path must be a filesystem path."
+ " If this is not given then the oar is saved to region.oar in the current directory." + Environment.NewLine
+ "--perm stops objects with insufficient permissions from being saved to the OAR." + Environment.NewLine
+ " <permissions> can contain one or more of these characters: \"C\" = Copy, \"T\" = Transfer" + Environment.NewLine, SaveOar);
MainConsole.Instance.Commands.AddCommand("kick user", "kick user [first] [last] [message]", "Kick a user off the simulator", KickUserCommand);
MainConsole.Instance.Commands.AddCommand("reset region", "reset region", "Reset region to the default terrain, wipe all prims, etc.", RunCommand);
MainConsole.Instance.Commands.AddCommand("restart-instance", "restart-instance", "Restarts the instance (as if you closed and re-opened Aurora)", RunCommand);
MainConsole.Instance.Commands.AddCommand("command-script", "command-script [script]", "Run a command script from file", RunCommand);
MainConsole.Instance.Commands.AddCommand("remove-region", "remove-region [name]", "Remove a region from this simulator", RunCommand);
MainConsole.Instance.Commands.AddCommand("delete-region", "delete-region [name]", "Delete a region from disk", RunCommand);
MainConsole.Instance.Commands.AddCommand ("modules list", "modules list", "Lists all simulator modules", HandleModulesList);
MainConsole.Instance.Commands.AddCommand ("modules unload", "modules unload [module]", "Unload the given simulator module", HandleModulesUnload);
}
/// <summary>
/// Kicks users off the region
/// </summary>
/// <param name="cmdparams">name of avatar to kick</param>
private void KickUserCommand(string[] cmdparams)
{
string alert = null;
IList agents = new List<IScenePresence>(GetCurrentOrFirstScene().GetScenePresences());
if (cmdparams.Length < 4)
{
if (cmdparams.Length < 3)
return;
UUID avID = UUID.Zero;
if (cmdparams[2] == "all")
{
foreach (IScenePresence presence in agents)
{
RegionInfo regionInfo = presence.Scene.RegionInfo;
MainConsole.Instance.Info (String.Format ("Kicking user: {0,-16}{1,-37} in region: {2,-16}", presence.Name, presence.UUID, regionInfo.RegionName));
// kick client...
presence.ControllingClient.Kick(alert ?? "\nThe Aurora manager kicked you out.\n");
// ...and close on our side
IEntityTransferModule transferModule = presence.Scene.RequestModuleInterface<IEntityTransferModule> ();
if(transferModule != null)
transferModule.IncomingCloseAgent (presence.Scene, presence.UUID);
}
}
else if(UUID.TryParse(cmdparams[2], out avID))
{
foreach (IScenePresence presence in agents)
{
if (presence.UUID == avID)
{
RegionInfo regionInfo = presence.Scene.RegionInfo;
MainConsole.Instance.Info (String.Format ("Kicking user: {0,-16}{1,-37} in region: {2,-16}", presence.Name, presence.UUID, regionInfo.RegionName));
// kick client...
presence.ControllingClient.Kick(alert ?? "\nThe Aurora manager kicked you out.\n");
// ...and close on our side
IEntityTransferModule transferModule = presence.Scene.RequestModuleInterface<IEntityTransferModule> ();
if (transferModule != null)
transferModule.IncomingCloseAgent (presence.Scene, presence.UUID);
}
}
}
}
if (cmdparams.Length > 4)
alert = String.Format("\n{0}\n", String.Join(" ", cmdparams, 4, cmdparams.Length - 4));
foreach (IScenePresence presence in agents)
{
RegionInfo regionInfo = presence.Scene.RegionInfo;
string param = Util.CombineParams (cmdparams, 2);
if (presence.Name.ToLower().Contains (param.ToLower ()) ||
(presence.Firstname.ToLower ().Contains (cmdparams[2].ToLower ()) && presence.Lastname.ToLower ().Contains (cmdparams[3].ToLower ())))
{
MainConsole.Instance.Info (String.Format ("Kicking user: {0,-16}{1,-37} in region: {2,-16}", presence.Name, presence.UUID, regionInfo.RegionName));
// kick client...
presence.ControllingClient.Kick(alert ?? "\nThe Aurora manager kicked you out.\n");
// ...and close on our side
IEntityTransferModule transferModule = presence.Scene.RequestModuleInterface<IEntityTransferModule> ();
if (transferModule != null)
transferModule.IncomingCloseAgent (presence.Scene, presence.UUID);
}
}
MainConsole.Instance.Info ("");
}
/// <summary>
/// Force resending of all updates to all clients in active region(s)
/// </summary>
/// <param name="args"></param>
private void HandleForceUpdate(string[] args)
{
MainConsole.Instance.Info ("Updating all clients");
#if (!ISWIN)
ForEachCurrentScene(delegate(IScene scene)
{
ISceneEntity[] EntityList = scene.Entities.GetEntities ();
foreach (ISceneEntity ent in EntityList)
{
if (ent is SceneObjectGroup)
{
((SceneObjectGroup)ent).ScheduleGroupUpdate (PrimUpdateFlags.ForcedFullUpdate);
}
}
List<IScenePresence> presences = scene.Entities.GetPresences ();
foreach(IScenePresence presence in presences)
{
if(!presence.IsChildAgent)
scene.ForEachClient(delegate(IClientAPI client)
{
client.SendAvatarDataImmediate(presence);
});
}
});
#else
ForEachCurrentScene(scene =>
{
ISceneEntity[] EntityList = scene.Entities.GetEntities();
foreach (SceneObjectGroup ent in EntityList.OfType<SceneObjectGroup>())
{
(ent).ScheduleGroupUpdate(
PrimUpdateFlags.ForcedFullUpdate);
}
List<IScenePresence> presences = scene.Entities.GetPresences();
foreach (IScenePresence presence in presences.Where(presence => !presence.IsChildAgent))
{
IScenePresence presence1 = presence;
scene.ForEachClient(
client => client.SendAvatarDataImmediate(presence1));
}
});
#endif
}
/// <summary>
/// Load, Unload, and list Region modules in use
/// </summary>
/// <param name="cmd"></param>
private void HandleModulesUnload(string[] cmd)
{
List<string> args = new List<string> (cmd);
args.RemoveAt (0);
string[] cmdparams = args.ToArray ();
IRegionModulesController controller = m_OpenSimBase.ApplicationRegistry.RequestModuleInterface<IRegionModulesController> ();
if (cmdparams.Length > 1)
{
foreach (IRegionModuleBase irm in controller.AllModules)
{
if (irm.Name.ToLower () == cmdparams[1].ToLower ())
{
MainConsole.Instance.Info (String.Format ("Unloading module: {0}", irm.Name));
foreach (IScene scene in m_localScenes)
irm.RemoveRegion (scene);
irm.Close ();
}
}
}
}
/// <summary>
/// Load, Unload, and list Region modules in use
/// </summary>
/// <param name="cmd"></param>
private void HandleModulesList (string[] cmd)
{
List<string> args = new List<string> (cmd);
args.RemoveAt (0);
IRegionModulesController controller = m_OpenSimBase.ApplicationRegistry.RequestModuleInterface<IRegionModulesController> ();
foreach (IRegionModuleBase irm in controller.AllModules)
{
if (irm is ISharedRegionModule)
MainConsole.Instance.Info (String.Format ("Shared region module: {0}", irm.Name));
else if (irm is INonSharedRegionModule)
MainConsole.Instance.Info (String.Format ("Nonshared region module: {0}", irm.Name));
else
MainConsole.Instance.Info (String.Format ("Unknown type " + irm.GetType () + " region module: {0}", irm.Name));
}
}
/// <summary>
/// Serialize region data to XML2Format
/// </summary>
/// <param name="cmdparams"></param>
protected void SaveXml2(string[] cmdparams)
{
if (cmdparams.Length > 2)
{
IRegionSerialiserModule serialiser = GetCurrentOrFirstScene().RequestModuleInterface<IRegionSerialiserModule>();
if (serialiser != null)
serialiser.SavePrimsToXml2(GetCurrentOrFirstScene(), cmdparams[2]);
}
else
{
MainConsole.Instance.Warn("Wrong number of parameters!");
}
}
/// <summary>
/// Runs commands issued by the server console from the operator
/// </summary>
/// <param name="cmdparams">Additional arguments passed to the command</param>
private void RunCommand (string[] cmdparams)
{
List<string> args = new List<string>(cmdparams);
if (args.Count < 1)
return;
string command = args[0];
args.RemoveAt(0);
cmdparams = args.ToArray();
switch (command)
{
case "reset":
if (cmdparams.Length > 0)
if (cmdparams[0] == "region")
{
if (MainConsole.Instance.Prompt ("Are you sure you want to reset the region?", "yes") != "yes")
return;
ResetRegion (MainConsole.Instance.ConsoleScene);
}
break;
case "command-script":
if (cmdparams.Length > 0)
{
m_OpenSimBase.RunCommandScript(cmdparams[0]);
}
break;
case "remove-region":
string regRemoveName = Util.CombineParams(cmdparams, 0);
IScene removeScene;
if (TryGetScene(regRemoveName, out removeScene))
RemoveRegion(removeScene, false);
else
MainConsole.Instance.Info ("no region with that name");
break;
case "delete-region":
string regDeleteName = Util.CombineParams(cmdparams, 0);
IScene killScene;
if (TryGetScene(regDeleteName, out killScene))
RemoveRegion(killScene, true);
else
MainConsole.Instance.Info ("no region with that name");
break;
case "restart-instance":
//This kills the instance and restarts it
MainConsole.Instance.EndConsoleProcessing();
break;
}
}
/// <summary>
/// Change the currently selected region. The selected region is that operated upon by single region commands.
/// </summary>
/// <param name="cmdparams"></param>
protected void ChangeSelectedRegion(string[] cmdparams)
{
if (cmdparams.Length > 2)
{
string newRegionName = Util.CombineParams(cmdparams, 2);
ChangeConsoleRegion(newRegionName);
}
else
{
MainConsole.Instance.Info ("Usage: change region <region name>");
}
}
/// <summary>
/// Turn on some debugging values for OpenSim.
/// </summary>
/// <param name="args"></param>
protected void Debug(string[] args)
{
if (args.Length == 1)
return;
switch (args[1])
{
case "packet":
if (args.Length > 2)
{
int newDebug;
if (int.TryParse(args[2], out newDebug))
{
SetDebugPacketLevelOnCurrentScene(newDebug);
}
else
{
MainConsole.Instance.Info ("packet debug should be 0..255");
}
MainConsole.Instance.Info (String.Format ("New packet debug: {0}", newDebug));
}
break;
default:
MainConsole.Instance.Info ("Unknown debug");
break;
}
}
/// <summary>
/// Set the debug packet level on the current scene. This level governs which packets are printed out to the
/// console.
/// </summary>
/// <param name="newDebug"></param>
private void SetDebugPacketLevelOnCurrentScene(int newDebug)
{
#if (!ISWIN)
ForEachCurrentScene(
delegate(IScene scene)
{
scene.ForEachScenePresence (delegate (IScenePresence scenePresence)
{
if (!scenePresence.IsChildAgent)
{
MainConsole.Instance.DebugFormat("Packet debug for {0} set to {1}",
scenePresence.Name,
newDebug);
scenePresence.ControllingClient.SetDebugPacketLevel(newDebug);
}
});
}
);
#else
ForEachCurrentScene(
scene => scene.ForEachScenePresence(scenePresence =>
{
if (scenePresence.IsChildAgent) return;
MainConsole.Instance.DebugFormat(
"Packet debug for {0} set to {1}",
scenePresence.Name,
newDebug);
scenePresence.ControllingClient.SetDebugPacketLevel(
newDebug);
})
);
#endif
}
private void HandleShowUsers (string[] cmd)
{
List<string> args = new List<string> (cmd);
args.RemoveAt (0);
string[] showParams = args.ToArray ();
List<IScenePresence> agents = new List<IScenePresence>();
if(showParams.Length > 1 && showParams[1] == "full")
{
if(MainConsole.Instance.ConsoleScene == null)
{
foreach(IScene scene in m_localScenes)
{
agents.AddRange(scene.GetScenePresences());
}
}
else
agents = GetCurrentOrFirstScene().GetScenePresences();
}
else
{
if(MainConsole.Instance.ConsoleScene == null)
{
foreach(IScene scene in m_localScenes)
{
agents.AddRange(scene.GetScenePresences());
}
}
else
agents = GetCurrentOrFirstScene().GetScenePresences();
#if (!ISWIN)
agents.RemoveAll(delegate(IScenePresence sp)
{
return sp.IsChildAgent;
});
#else
agents.RemoveAll(sp => sp.IsChildAgent);
#endif
}
MainConsole.Instance.Info (String.Format ("\nAgents connected: {0}\n", agents.Count));
MainConsole.Instance.Info (String.Format ("{0,-16}{1,-16}{2,-37}{3,-11}{4,-16}{5,-30}", "Firstname", "Lastname", "Agent ID", "Root/Child", "Region", "Position"));
foreach (IScenePresence presence in agents)
{
RegionInfo regionInfo = presence.Scene.RegionInfo;
string regionName = regionInfo == null ? "Unresolvable" : regionInfo.RegionName;
MainConsole.Instance.Info (String.Format ("{0,-16}{1,-37}{2,-11}{3,-16}{4,-30}", presence.Name, presence.UUID, presence.IsChildAgent ? "Child" : "Root", regionName, presence.AbsolutePosition.ToString ()));
}
MainConsole.Instance.Info (String.Empty);
MainConsole.Instance.Info (String.Empty);
}
private void HandleShowRegions (string[] cmd)
{
#if (!ISWIN)
ForEachScene (delegate (IScene scene)
{
MainConsole.Instance.Info (scene.ToString ());
});
#else
ForEachScene(scene => MainConsole.Instance.Info(scene.ToString()));
#endif
}
private void HandleShowMaturity (string[] cmd)
{
ForEachCurrentScene (delegate (IScene scene)
{
string rating = "";
if (scene.RegionInfo.RegionSettings.Maturity == 1)
{
rating = "Mature";
}
else if (scene.RegionInfo.RegionSettings.Maturity == 2)
{
rating = "Adult";
}
else
{
rating = "PG";
}
MainConsole.Instance.Info (String.Format ("Region Name: {0}, Region Rating {1}", scene.RegionInfo.RegionName, rating));
});
}
/// <summary>
/// Load region data from Xml2Format
/// </summary>
/// <param name="cmdparams"></param>
protected void LoadXml2(string[] cmdparams)
{
if (cmdparams.Length > 2)
{
try
{
IRegionSerialiserModule serialiser = GetCurrentOrFirstScene().RequestModuleInterface<IRegionSerialiserModule>();
if (serialiser != null)
serialiser.LoadPrimsFromXml2(GetCurrentOrFirstScene(), cmdparams[2]);
}
catch (FileNotFoundException)
{
MainConsole.Instance.Info ("Specified xml not found. Usage: load xml2 <filename>");
}
}
else
{
MainConsole.Instance.Warn("Not enough parameters!");
}
}
/// <summary>
/// Load a whole region from an opensimulator archive.
/// </summary>
/// <param name="cmdparams"></param>
protected void LoadOar(string[] cmdparams)
{
try
{
IRegionArchiverModule archiver = GetCurrentOrFirstScene().RequestModuleInterface<IRegionArchiverModule>();
if (archiver != null)
archiver.HandleLoadOarConsoleCommand(cmdparams);
}
catch (Exception e)
{
MainConsole.Instance.Error (e.ToString ());
}
}
/// <summary>
/// Save a region to a file, including all the assets needed to restore it.
/// </summary>
/// <param name="cmdparams"></param>
protected void SaveOar(string[] cmdparams)
{
IRegionArchiverModule archiver = GetCurrentOrFirstScene().RequestModuleInterface<IRegionArchiverModule>();
if (archiver != null)
archiver.HandleSaveOarConsoleCommand(cmdparams);
}
#endregion
}
}
| |
using System;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Web;
using Newtonsoft.Json.Linq;
namespace RedditSharp
{
public sealed class WebAgent : IWebAgent
{
/// <summary>
/// Additional values to append to the default RedditSharp user agent.
/// </summary>
public static string UserAgent { get; set; }
/// <summary>
/// It is strongly advised that you leave this enabled. Reddit bans excessive
/// requests with extreme predjudice.
/// </summary>
public static bool EnableRateLimit { get; set; }
public static string Protocol { get; set; }
/// <summary>
/// It is strongly advised that you leave this set to Burst or Pace. Reddit bans excessive
/// requests with extreme predjudice.
/// </summary>
public static RateLimitMode RateLimit { get; set; }
/// <summary>
/// The method by which the WebAgent will limit request rate
/// </summary>
public enum RateLimitMode
{
/// <summary>
/// Limits requests to one every two seconds
/// </summary>
Pace,
/// <summary>
/// Restricts requests to thirty per minute
/// </summary>
Burst,
/// <summary>
/// Does not restrict request rate. ***NOT RECOMMENDED***
/// </summary>
None
}
/// <summary>
/// The root domain RedditSharp uses to address Reddit.
/// www.reddit.com by default
/// </summary>
public static string RootDomain { get; set; }
/// <summary>
/// Used to make calls against Reddit's API using OAuth23
/// </summary>
public string AccessToken { get; set; }
public CookieContainer Cookies { get; set; }
public string AuthCookie { get; set; }
private static DateTime _lastRequest;
private static DateTime _burstStart;
private static int _requestsThisBurst;
public JToken CreateAndExecuteRequest(string url)
{
Uri uri;
if (!Uri.TryCreate(url, UriKind.Absolute, out uri))
{
if (!Uri.TryCreate(String.Format("{0}://{1}{2}", Protocol, RootDomain, url), UriKind.Absolute, out uri))
throw new Exception("Could not parse Uri");
}
var request = CreateGet(uri);
try { return ExecuteRequest(request); }
catch (Exception)
{
var tempProtocol = Protocol;
var tempRootDomain = RootDomain;
Protocol = "http";
RootDomain = "www.reddit.com";
var retval = CreateAndExecuteRequest(url);
Protocol = tempProtocol;
RootDomain = tempRootDomain;
return retval;
}
}
/// <summary>
/// Executes the web request and handles errors in the response
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public JToken ExecuteRequest(HttpWebRequest request)
{
EnforceRateLimit();
var response = request.GetResponse();
var result = GetResponseString(response.GetResponseStream());
var json = JToken.Parse(result);
try
{
if (json["json"] != null)
{
json = json["json"]; //get json object if there is a root node
}
if (json["error"] != null)
{
switch (json["error"].ToString())
{
case "404":
throw new Exception("File Not Found");
case "403":
throw new Exception("Restricted");
case "invalid_grant":
//Refresh authtoken
//AccessToken = authProvider.GetRefreshToken();
//ExecuteRequest(request);
break;
}
}
}
catch
{
}
return json;
}
private static void EnforceRateLimit()
{
switch (RateLimit)
{
case RateLimitMode.Pace:
while ((DateTime.UtcNow - _lastRequest).TotalSeconds < 2)// Rate limiting
Thread.Sleep(250);
_lastRequest = DateTime.UtcNow;
break;
case RateLimitMode.Burst:
if (_requestsThisBurst == 0)//this is first request
_burstStart = DateTime.UtcNow;
if (_requestsThisBurst >= 30) //limit has been reached
{
while ((DateTime.UtcNow - _burstStart).TotalSeconds < 60)
Thread.Sleep(250);
_burstStart = DateTime.UtcNow;
}
_requestsThisBurst++;
break;
}
}
public HttpWebRequest CreateRequest(string url, string method)
{
EnforceRateLimit();
bool prependDomain;
// IsWellFormedUriString returns true on Mono for some reason when using a string like "/api/me"
if (Type.GetType("Mono.Runtime") != null)
prependDomain = !url.StartsWith("http://") && !url.StartsWith("https://");
else
prependDomain = !Uri.IsWellFormedUriString(url, UriKind.Absolute);
HttpWebRequest request;
if (prependDomain)
request = (HttpWebRequest)WebRequest.Create(String.Format("{0}://{1}{2}", Protocol, RootDomain, url));
else
request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = Cookies;
if (Type.GetType("Mono.Runtime") != null)
{
var cookieHeader = Cookies.GetCookieHeader(new Uri("http://reddit.com"));
request.Headers.Set("Cookie", cookieHeader);
}
if (RootDomain == "oauth.reddit.com")// use OAuth
{
request.Headers.Set("Authorization", "bearer " + AccessToken);//Must be included in OAuth calls
}
request.Method = method;
request.UserAgent = UserAgent + " - with RedditSharp by /u/sircmpwn";
return request;
}
private HttpWebRequest CreateRequest(Uri uri, string method)
{
EnforceRateLimit();
var request = (HttpWebRequest)WebRequest.Create(uri);
request.CookieContainer = Cookies;
if (Type.GetType("Mono.Runtime") != null)
{
var cookieHeader = Cookies.GetCookieHeader(new Uri("http://reddit.com"));
request.Headers.Set("Cookie", cookieHeader);
}
if (RootDomain == "oauth.reddit.com")// use OAuth
{
request.Headers.Set("Authorization", "bearer " + AccessToken);//Must be included in OAuth calls
}
request.Method = method;
request.UserAgent = UserAgent + " - with RedditSharp by /u/sircmpwn";
return request;
}
public HttpWebRequest CreateGet(string url)
{
return CreateRequest(url, "GET");
}
private HttpWebRequest CreateGet(Uri url)
{
return CreateRequest(url, "GET");
}
public HttpWebRequest CreatePost(string url)
{
var request = CreateRequest(url, "POST");
request.ContentType = "application/x-www-form-urlencoded";
return request;
}
public string GetResponseString(Stream stream)
{
var data = new StreamReader(stream).ReadToEnd();
stream.Close();
return data;
}
public void WritePostBody(Stream stream, object data, params string[] additionalFields)
{
var type = data.GetType();
var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
string value = "";
foreach (var property in properties)
{
var attr = property.GetCustomAttributes(typeof(RedditAPINameAttribute), false).FirstOrDefault() as RedditAPINameAttribute;
string name = attr == null ? property.Name : attr.Name;
var entry = Convert.ToString(property.GetValue(data, null));
value += name + "=" + HttpUtility.UrlEncode(entry).Replace(";", "%3B").Replace("&", "%26") + "&";
}
for (int i = 0; i < additionalFields.Length; i += 2)
{
var entry = Convert.ToString(additionalFields[i + 1]) ?? string.Empty;
value += additionalFields[i] + "=" + HttpUtility.UrlEncode(entry).Replace(";", "%3B").Replace("&", "%26") + "&";
}
value = value.Remove(value.Length - 1); // Remove trailing &
var raw = Encoding.UTF8.GetBytes(value);
stream.Write(raw, 0, raw.Length);
stream.Close();
}
}
}
| |
//
// (c) sof, 2002-2003
//
using System;
namespace HsWrapGen
{
/// <summary>
///
/// </summary>
public class HsOutput
{
private System.Type m_type;
private System.Reflection.MemberInfo[] m_members;
private System.Collections.Specialized.StringCollection m_names;
private System.Collections.Specialized.StringCollection m_imports;
private System.String m_modname;
public HsOutput(System.Type ty,System.Reflection.MemberInfo[] mems) {
m_type = ty;
m_members = mems;
m_names = new System.Collections.Specialized.StringCollection();
m_imports = new System.Collections.Specialized.StringCollection();
m_modname = "Dotnet." + m_type.FullName;
}
protected void OutputHeader(System.IO.StreamWriter st) {
String supTy = (m_type.IsInterface ? "System.Object" : m_type.BaseType.FullName);
String supTyCls = (m_type.IsInterface ? "Object" : m_type.BaseType.Name);
st.WriteLine("module Dotnet.{0} where", m_type.FullName);
st.WriteLine("");
st.WriteLine("import Dotnet");
AddImport("Dotnet."+supTy);
foreach (String s in m_imports) {
st.WriteLine("import qualified {0}", s);
}
st.WriteLine("");
// ToDo: provide the option of stashing this away in a separate
// module.
st.WriteLine("data {0}_ a", m_type.Name);
st.WriteLine("type {0} a = Dotnet.{1}.{2} ({0}_ a)",
m_type.Name,
supTy,
supTyCls);
st.WriteLine("");
}
private String ToHaskellName(String x) {
System.String candName, candNameOrig;
System.Int32 uniq = 1;
if (System.Char.IsUpper(x[0])) {
candName =
String.Concat(System.Char.ToLower(x[0]),
x.Substring(1));
} else {
candName = x;
}
candNameOrig = candName;
while (m_names.Contains(candName)) {
candName = String.Concat(candNameOrig,"_",uniq.ToString());
uniq++;
}
m_names.Add(candName);
return candName;
}
private String ToHaskellConName(String x) {
System.String candName, candNameOrig;
System.Int32 uniq = 1;
if (System.Char.IsLower(x[0])) {
candName =
String.Concat(System.Char.ToUpper(x[0]),
x.Substring(1));
} else {
candName = x;
}
candNameOrig = candName;
while (m_names.Contains(candName)) {
candName = String.Concat(candNameOrig,"_",uniq.ToString());
uniq++;
}
m_names.Add(candName);
return candName;
}
private void AddImport(System.String nm) {
if (!m_imports.Contains(nm) && String.Compare(nm, m_modname) != 0) {
m_imports.Add(nm);
}
}
protected void OutputHaskellType(System.Text.StringBuilder sb,
System.Type ty,
System.Int32 idx) {
/* Curiously, &-versions of prim types are showing up (cf. System.Uri.HexUnescape).
* Just ignore them.
*/
if (ty.FullName == "System.Boolean" || ty.FullName == "System.Boolean&" ) {
sb.Append("Bool"); return;
}
if (ty.FullName == "System.String") {
sb.Append("String"); return;
}
if (ty.FullName == "System.Char" || ty.FullName == "System.Char&") {
sb.Append("Char"); return;
}
if (ty.FullName == "System.Double" || ty.FullName == "System.Double&") {
sb.Append("Double"); return;
}
if (ty.FullName == "System.Single" || ty.FullName == "System.Single&") {
sb.Append("Double"); return;
}
if (ty.FullName == "System.SByte" || ty.FullName == "System.SByte&") {
AddImport("Data.Int");
sb.Append("Data.Int.Int8"); return;
}
if (ty.FullName == "System.Int16" || ty.FullName == "System.Int16&") {
AddImport("Data.Int");
sb.Append("Data.Int.Int16"); return;
}
if (ty.FullName == "System.Int32" || ty.FullName == "System.Int32&") {
sb.Append("Int"); return;
}
if (ty.FullName == "System.Int64" || ty.FullName == "System.Int64&") {
AddImport("Data.Int");
sb.Append("Data.Int.Int64"); return;
}
if (ty.FullName == "System.Byte" || ty.FullName == "System.Byte&") {
AddImport("Data.Word");
sb.Append("Data.Word.Word8"); return;
}
if (ty.FullName == "System.UInt16" || ty.FullName == "System.UInt16&") {
AddImport("Data.Word");
sb.Append("Data.Word.Word16"); return;
}
if (ty.FullName == "System.UInt32" || ty.FullName == "System.UInt32&") {
AddImport("Data.Word");
sb.Append("Data.Word.Word32"); return;
}
if (ty.FullName == "System.UInt64" || ty.FullName == "System.UInt64&") {
AddImport("Data.Word");
sb.Append("Data.Word.Word64"); return;
}
if (ty.FullName == "System.Void") {
sb.Append("()"); return;
}
if (ty.FullName == "System.Object") {
AddImport("Dotnet.System.Object");
sb.AppendFormat("Dotnet.System.Object.Object a{0}",idx); return;
}
if (ty.IsArray) {
AddImport("Dotnet.System.Array");
sb.Append("Dotnet.System.Array.Array (");
OutputHaskellType(sb, ty.GetElementType(), idx);
sb.Append(")");
} else {
AddImport("Dotnet." + ty.FullName);
sb.AppendFormat("Dotnet.{0}.{1} a{2}", ty.FullName, ty.Name, idx);
}
}
protected void OutputMethodSig(System.Text.StringBuilder sb,
System.Reflection.MemberInfo mi) {
System.Reflection.MethodInfo m = (System.Reflection.MethodInfo)mi;
System.Reflection.ParameterInfo[] ps = m.GetParameters();
int i;
for (i=0; i < ps.Length; i++) {
OutputHaskellType(sb,ps[i].ParameterType,i);
sb.Append(" -> ");
}
if (m.IsStatic) {
sb.Append("IO (");
} else {
sb.AppendFormat("{0} obj -> IO (", mi.DeclaringType.Name);
}
OutputHaskellType(sb,m.ReturnType,i);
sb.AppendFormat("){0}",System.Environment.NewLine);
}
protected void OutputCtorSig(System.Text.StringBuilder sb,
System.Reflection.ConstructorInfo ci) {
System.Reflection.ParameterInfo[] ps = ci.GetParameters();
int i;
for (i=0; i < ps.Length; i++) {
OutputHaskellType(sb,ps[i].ParameterType,i);
sb.Append(" -> ");
}
sb.AppendFormat("IO ({0} ())", ci.DeclaringType.Name);
sb.Append(System.Environment.NewLine);
}
protected void OutputFieldSig(System.Text.StringBuilder sb,
System.Reflection.FieldInfo fi,
bool isSetter) {
/* Note: indexed values are provided via properties */
if (isSetter) {
OutputHaskellType(sb,fi.FieldType,0);
if (!fi.IsStatic) {
sb.AppendFormat(" -> {0} obj", fi.DeclaringType.Name);
}
sb.AppendFormat(" -> IO (){0}",System.Environment.NewLine);
} else {
if (fi.IsStatic) {
sb.Append("IO (");
} else {
sb.AppendFormat("{0} obj -> IO (", fi.DeclaringType.Name);
}
OutputHaskellType(sb,fi.FieldType,0);
sb.AppendFormat("){0}",System.Environment.NewLine);
}
}
protected void OutputArgs(System.Text.StringBuilder sb,
System.Reflection.MemberInfo mi,
System.Boolean isTupled) {
System.Reflection.MethodInfo m = (System.Reflection.MethodInfo)mi;
Int32 i = 0;
System.Reflection.ParameterInfo[] ps = m.GetParameters();
if (isTupled && ps.Length != 1) sb.Append("(");
for (i=0; i < ps.Length; i++) {
sb.AppendFormat("arg{0}",i);
if (isTupled && (i+1) < ps.Length) {
sb.Append(",");
} else {
if (!isTupled) sb.Append(" ");
}
}
if (isTupled && ps.Length != 1) sb.Append(")");
}
protected void OutputMember(System.Text.StringBuilder sb,
System.Reflection.MemberInfo mi) {
switch (mi.MemberType) {
case System.Reflection.MemberTypes.Method:
System.String methName = ToHaskellName(mi.Name);
System.Reflection.MethodInfo m = (System.Reflection.MethodInfo)mi;
sb.Append("foreign import dotnet"); sb.Append(System.Environment.NewLine);
// the 'method' bit is really optional.
sb.AppendFormat(" \"{0}method {1}.{2}\"", (m.IsStatic ? "static " : ""), mi.DeclaringType, mi.Name);
sb.Append(System.Environment.NewLine);
sb.AppendFormat(" {0} :: ", methName);
OutputMethodSig(sb,mi);
// the mind boggles, System.Environment ?
sb.Append(System.Environment.NewLine);
/* old habit ;) */
break;
case System.Reflection.MemberTypes.Constructor:
OutputCtor(sb,(System.Reflection.ConstructorInfo)mi);
break;
case System.Reflection.MemberTypes.Field:
System.String fieldName = mi.Name;
System.Reflection.FieldInfo f = (System.Reflection.FieldInfo)mi;
System.String staticPrefix = (f.IsStatic ? "static " : "");
sb.Append("foreign import dotnet");
sb.Append(System.Environment.NewLine);
sb.AppendFormat(" \"{0}field {1}.{2}\"", staticPrefix, mi.DeclaringType, mi.Name);
sb.Append(System.Environment.NewLine);
sb.AppendFormat(" get_{0} :: ", fieldName);
OutputFieldSig(sb,f,false);
sb.Append(System.Environment.NewLine);
if (!f.IsInitOnly) {
sb.Append("foreign import dotnet");
sb.Append(System.Environment.NewLine);
sb.AppendFormat(" \"{0}field {1}.{2}\"", staticPrefix, mi.DeclaringType, mi.Name);
sb.Append(System.Environment.NewLine);
sb.AppendFormat(" set_{0} :: ", fieldName);
OutputFieldSig(sb,f,true);
sb.Append(System.Environment.NewLine);
}
break;
default:
break;
}
}
protected void OutputCtor(System.Text.StringBuilder sb,
System.Reflection.ConstructorInfo ci) {
System.String ctorName = ToHaskellName("new"+ci.DeclaringType.Name);
sb.Append("foreign import dotnet");
sb.Append(System.Environment.NewLine);
sb.AppendFormat(" \"ctor {0}\"", ci.DeclaringType);
sb.AppendFormat("{0}",System.Environment.NewLine);
sb.AppendFormat(" {0} :: ", ctorName);
OutputCtorSig(sb,ci);
sb.Append(System.Environment.NewLine);
}
protected void OutputField(System.Text.StringBuilder sb,
System.Reflection.MemberInfo mi) {
switch (mi.MemberType) {
case System.Reflection.MemberTypes.Field:
System.String fieldName = ToHaskellConName(mi.Name);
sb.Append(fieldName);
break;
default:
break;
}
}
public void OutputToFile(String fn) {
System.IO.FileStream fs = new System.IO.FileStream(fn,System.IO.FileMode.Create);
System.IO.StreamWriter st = new System.IO.StreamWriter(fs,System.Text.Encoding.ASCII);
System.Text.StringBuilder sb = new System.Text.StringBuilder();
if (!m_type.IsInterface && m_type.BaseType.FullName == "System.Enum") {
/* enumerations are mapped onto Haskell data types. */
System.String sep = " = ";
sb.AppendFormat("data {0}Ty", m_type.Name);
sb.Append(System.Environment.NewLine);
foreach (System.Reflection.MemberInfo mem in m_members) {
if (mem.Name != "value__") {
sb.Append(sep);
OutputField(sb,mem);
sb.Append(System.Environment.NewLine);
sep = " | ";
}
}
sb.AppendFormat(" deriving ( Enum, Show, Read ){0}",System.Environment.NewLine);
// Emit functions for converting betw alg type and object type.
AddImport("IOExts");
AddImport("Dotnet.System.Type");
AddImport("Dotnet.System.Enum");
sb.AppendFormat("to{0} :: {0}Ty -> {0} (){1}", m_type.Name, System.Environment.NewLine);
sb.AppendFormat("to{0} tag = IOExts.unsafePerformIO (Dotnet.System.Enum.parse (IOExts.unsafePerformIO (Dotnet.System.Type.getType \"{1}\")) (show tag)){2}", m_type.Name, m_type.AssemblyQualifiedName,System.Environment.NewLine);
sb.Append(System.Environment.NewLine);
sb.AppendFormat("from{0} :: {0} () -> {0}Ty{1}", m_type.Name, System.Environment.NewLine);
sb.AppendFormat("from{0} obj = IOExts.unsafePerformIO (toString obj >>= return.read)", m_type.Name);
sb.Append(System.Environment.NewLine);
} else {
foreach (System.Reflection.MemberInfo mem in m_members) {
OutputMember(sb,mem);
}
foreach (System.Reflection.ConstructorInfo ci in m_type.GetConstructors()) {
OutputCtor(sb,ci);
}
}
OutputHeader(st);
st.WriteLine(sb.ToString());
st.Flush();
st.Close();
fs.Close();
}
}
}
| |
/*
Copyright 2021 Jeffrey Sharp
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
using System.Management.Automation;
namespace PSql;
using static AzureAuthenticationMode;
/// <summary>
/// Information necessary to connect to an Azure SQL Database or compatible database.
/// </summary>
public class AzureSqlContext : SqlContext
{
private string? _serverResourceGroupName;
private string? _serverResourceName;
private string? _serverResolvedName;
private AzureAuthenticationMode _authenticationMode;
/// <summary>
/// Initializes a new <see cref="AzureSqlContext"/> instance with
/// default property values.
/// </summary>
public AzureSqlContext()
{
// Encryption is required for connections to Azure SQL Database
base.EncryptionMode = EncryptionMode.Full;
}
/// <summary>
/// Initializes a new <see cref="AzureSqlContext"/> instance by property
/// values from the specified instance.
/// </summary>
/// <param name="other">
/// The instance from which to copy property values.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="other"/> is <see langword="null"/>.
/// </exception>
public AzureSqlContext(AzureSqlContext other)
: base(other)
{
_serverResourceGroupName = other. ServerResourceGroupName;
_serverResourceName = other. ServerResourceName;
_serverResolvedName = other._serverResolvedName;
_authenticationMode = other. AuthenticationMode;
}
/// <inheritdoc/>
public sealed override bool IsAzure => true;
/// <summary>
/// Gets or sets the name of the Azure resource group containing the
/// virtual database server. The default is <see langword="null"/>.
/// </summary>
public string? ServerResourceGroupName
{
get => _serverResourceGroupName;
set
{
Set(out _serverResourceGroupName, value);
_serverResolvedName = null;
}
}
/// <summary>
/// Gets or sets the Azure resource name of the virtual database server.
/// The default is <see langword="null"/>.
/// </summary>
public string? ServerResourceName
{
get => _serverResourceName;
set
{
Set(out _serverResourceName, value);
_serverResolvedName = null;
}
}
/// <summary>
/// Gets or sets the method used to authenticate with the database server.
/// The default is <see cref="AzureAuthenticationMode.Default"/>.
/// </summary>
public AzureAuthenticationMode AuthenticationMode
{
get => _authenticationMode;
set => Set(out _authenticationMode, value);
}
/// <inheritdoc/>
public sealed override EncryptionMode EncryptionMode
{
get => base.EncryptionMode;
set { } // Property is immutable for AzureSqlContext
}
/// <summary>
/// Gets a new context that is a copy of the current instance, but with
/// the specified server resource group name, server resource name, and
/// database name. If the current instance is frozen, the copy is
/// frozen also.
/// </summary>
/// <param name="serverResourceGroupName">
/// The value to set on the copy for the name of the Azure resource
/// group containing the virtual database server.
/// </param>
/// <param name="serverResourceName">
/// The value to set on the copy for the Azure resource name of the
/// virtual database server.
/// </param>
/// <param name="databaseName">
/// The value to set on the copy for the name of the database.
/// </param>
public AzureSqlContext
this[
string? serverResourceGroupName,
string? serverResourceName,
string? databaseName
]
=> CloneAndModify(this, clone =>
{
clone.ServerResourceGroupName = serverResourceGroupName;
clone.ServerResourceName = serverResourceName;
clone.DatabaseName = databaseName;
});
/// <inheritdoc cref="SqlContext.Clone()" />
public new AzureSqlContext Clone()
=> (AzureSqlContext) CloneCore();
/// <inheritdoc/>
protected override SqlContext CloneCore()
=> new AzureSqlContext(this);
private protected sealed override string GetDefaultServerName()
{
// Resolve ServerName using Az module
if (_serverResolvedName is string existing)
return existing;
if (string.IsNullOrEmpty(ServerResourceGroupName) ||
string.IsNullOrEmpty(ServerResourceName))
{
throw new InvalidOperationException(
"Cannot determine the server DNS name. " +
"Set ServerName to the DNS name of a database server, or " +
"set ServerResourceGroupName and ServerResourceName to " +
"the resource group name and resource name, respectively, " +
"of an Azure SQL Database virtual server."
);
}
var value = ScriptBlock
.Create("param ($x) Get-AzSqlServer @x -ErrorAction Stop")
.Invoke(new Dictionary<string, object?>
{
["ResourceGroupName"] = ServerResourceGroupName,
["ServerName"] = ServerResourceName,
})
.FirstOrDefault()
?.Properties["FullyQualifiedDomainName"]
?.Value as string;
if (string.IsNullOrEmpty(value))
{
throw new InvalidOperationException(
"Failed to determine the server DNS name. " +
"The Get-AzSqlServer command completed without error, " +
"but did not yield an object with a FullyQualifiedDomainName " +
"property set to a non-null, non-empty string."
);
}
return _serverResolvedName = value;
}
private protected override void
ConfigureServerName(SqlConnectionStringBuilder builder)
{
// Ignore ServerPort and InstanceName.
builder.AppendServerName(GetEffectiveServerName());
}
private protected override void
ConfigureDatabaseName(SqlConnectionStringBuilder builder, string? databaseName)
{
if (string.IsNullOrEmpty(databaseName))
databaseName = MasterDatabaseName;
builder.AppendDatabaseName(databaseName);
}
private protected override void
ConfigureAuthentication(SqlConnectionStringBuilder builder, bool omitCredential)
{
var mode = AuthenticationMode;
// Mode
switch (mode)
{
case Default when Credential.IsNullOrEmpty():
mode = AadIntegrated;
goto default;
case Default:
mode = SqlPassword;
goto case SqlPassword;
case SqlPassword:
// No need to specify the mode in connection string in this case
break;
default:
RequireSupport(builder.Version, mode);
builder.AppendAuthenticationMode(mode);
break;
}
// Credential
switch (mode)
{
// Required
case SqlPassword:
case AadPassword:
case AadServicePrincipal:
RequireCredential(mode);
if (!omitCredential || ExposeCredentialInConnectionString)
builder.AppendCredential(Credential!.GetNetworkCredential());
if (ExposeCredentialInConnectionString)
builder.AppendPersistSecurityInfo(true);
break;
// Optional, password ignored
case AadManagedIdentity:
case AadDefault:
if (!Credential.IsNullOrEmpty())
builder.AppendUserName(Credential.UserName);
break;
}
}
private protected override void
ConfigureEncryption(SqlConnectionStringBuilder builder)
{
// Encryption is required for connections to Azure SQL Database
builder.AppendEncrypt(true);
// Always verify server identity
// builder.AppendTrustServerCertificate(false); is the default
}
private void RequireSupport(SqlClientVersion version, AzureAuthenticationMode mode)
{
if (version.SupportsAuthenticationMode(mode))
return;
var message = string.Format(
"The specified SqlClient version '{0}' " +
"does not support authentication mode '{1}'.",
version, mode
);
throw new NotSupportedException(message);
}
private void RequireCredential(AzureAuthenticationMode mode)
{
if (!Credential.IsNullOrEmpty())
return;
var message = string.Format(
"A credential is required when connecting to " +
"Azure SQL Database using authentication mode '{0}'.",
mode
);
throw new NotSupportedException(message);
}
}
| |
// Copyright 2018 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.UI;
using Esri.ArcGISRuntime.UI.Controls;
using System;
using System.Collections.Generic;
using System.Drawing;
using Windows.UI.Popups;
using Microsoft.UI.Xaml;
namespace ArcGISRuntime.WinUI.Samples.BufferList
{
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Buffer list",
category: "Geometry",
description: "Generate multiple individual buffers or a single unioned buffer around multiple points.",
instructions: "Click/tap on the map to add points. Click the \"Create Buffer(s)\" button to draw buffer(s) around the points (the size of the buffer is determined by the value entered by the user). Check the check box if you want the result to union (combine) the buffers. Click the \"Clear\" button to start over. The red dashed envelope shows the area where you can expect reasonable results for planar buffer operations with the North Central Texas State Plane spatial reference.",
tags: new[] { "analysis", "buffer", "geometry", "planar" })]
public partial class BufferList
{
// A polygon that defines the valid area of the spatial reference used.
private Polygon _spatialReferenceArea;
// A Random object to create RGB color values.
private Random _random = new Random();
public BufferList()
{
InitializeComponent();
// Create the map and graphics overlays.
Initialize();
}
private void Initialize()
{
// Create a spatial reference that's suitable for creating planar buffers in north central Texas (State Plane).
SpatialReference statePlaneNorthCentralTexas = new SpatialReference(32038);
// Define a polygon that represents the valid area of use for the spatial reference.
// This information is available at https://developers.arcgis.com/net/latest/wpf/guide/pdf/projected_coordinate_systems_rt100_3_0.pdf
List<MapPoint> spatialReferenceExtentCoords = new List<MapPoint>
{
new MapPoint(-103.070, 31.720, SpatialReferences.Wgs84),
new MapPoint(-103.070, 34.580, SpatialReferences.Wgs84),
new MapPoint(-94.000, 34.580, SpatialReferences.Wgs84),
new MapPoint(-94.00, 31.720, SpatialReferences.Wgs84)
};
_spatialReferenceArea = new Polygon(spatialReferenceExtentCoords);
_spatialReferenceArea = GeometryEngine.Project(_spatialReferenceArea, statePlaneNorthCentralTexas) as Polygon;
// Create a map that uses the North Central Texas state plane spatial reference.
Map bufferMap = new Map(statePlaneNorthCentralTexas);
// Add some base layers (counties, cities, and highways).
Uri usaLayerSource = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/USA/MapServer");
ArcGISMapImageLayer usaLayer = new ArcGISMapImageLayer(usaLayerSource);
bufferMap.Basemap.BaseLayers.Add(usaLayer);
// Use a new EnvelopeBuilder to expand the spatial reference extent 120%.
EnvelopeBuilder envBuilder = new EnvelopeBuilder(_spatialReferenceArea.Extent);
envBuilder.Expand(1.2);
// Set the map's initial extent to the expanded envelope.
Envelope startingEnvelope = envBuilder.ToGeometry();
bufferMap.InitialViewpoint = new Viewpoint(startingEnvelope);
// Assign the map to the MapView.
MyMapView.Map = bufferMap;
// Create a graphics overlay to show the buffer polygon graphics.
GraphicsOverlay bufferGraphicsOverlay = new GraphicsOverlay
{
// Give the overlay an ID so it can be found later.
Id = "buffers"
};
// Create a graphic to show the spatial reference's valid extent (envelope) with a dashed red line.
SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Dash, Color.Red, 5);
Graphic spatialReferenceExtentGraphic = new Graphic(_spatialReferenceArea, lineSymbol);
// Add the graphic to a new overlay.
GraphicsOverlay spatialReferenceGraphicsOverlay = new GraphicsOverlay();
spatialReferenceGraphicsOverlay.Graphics.Add(spatialReferenceExtentGraphic);
// Add the graphics overlays to the MapView.
MyMapView.GraphicsOverlays.Add(bufferGraphicsOverlay);
MyMapView.GraphicsOverlays.Add(spatialReferenceGraphicsOverlay);
// Wire up the MapView's GeoViewTapped event handler.
MyMapView.GeoViewTapped += MyMapView_GeoViewTapped;
}
private async void MyMapView_GeoViewTapped(object sender, GeoViewInputEventArgs e)
{
try
{
// Get the input map point (in the map's coordinate system, State Plane for North Central Texas).
MapPoint tapMapPoint = e.Location;
// Check if the point coordinates are within the spatial reference envelope.
bool withinValidExent = GeometryEngine.Contains(_spatialReferenceArea, tapMapPoint);
// If the input point is not within the valid extent for the spatial reference, warn the user and return.
if (!withinValidExent)
{
var dialog = new MessageDialog2("Location is not valid to buffer using the defined spatial reference.", "Out of bounds");
await dialog.ShowAsync();
return;
}
// Get the buffer radius (in miles) from the text box.
double bufferDistanceMiles = Convert.ToDouble(BufferDistanceMilesTextBox.Text);
// Use a helper method to get the buffer distance in feet (unit that's used by the spatial reference).
double bufferDistanceFeet = LinearUnits.Miles.ConvertTo(LinearUnits.Feet, bufferDistanceMiles);
// Create a simple marker symbol (red circle) to display where the user tapped/clicked on the map.
SimpleMarkerSymbol tapSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, Color.Red, 10);
// Create a new graphic to show the tap location.
Graphic tapGraphic = new Graphic(tapMapPoint, tapSymbol)
{
// Specify a z-index value on the point graphic to make sure it draws on top of the buffer polygons.
ZIndex = 2
};
// Store the specified buffer distance as an attribute with the graphic.
tapGraphic.Attributes["distance"] = bufferDistanceFeet;
// Add the tap point graphic to the buffer graphics overlay.
MyMapView.GraphicsOverlays["buffers"].Graphics.Add(tapGraphic);
}
catch (Exception ex)
{
// Display an error message.
await new MessageDialog2(ex.Message, "Error creating buffer point").ShowAsync();
}
}
private async void BufferButton_Click(object sender, RoutedEventArgs e)
{
try
{
// Call a function to delete any existing buffer polygons so they can be recreated.
ClearBufferPolygons();
// Check if the user wants to create a single unioned buffer or independent buffers around each map point.
bool areBuffersUnioned = UnionCheckBox.IsChecked == true;
// Iterate all point graphics and create a list of map points and buffer distances for each.
List<MapPoint> bufferMapPoints = new List<MapPoint>();
List<double> bufferDistances = new List<double>();
foreach (Graphic bufferGraphic in MyMapView.GraphicsOverlays["buffers"].Graphics)
{
// Only use point graphics.
if (bufferGraphic.Geometry.GeometryType == GeometryType.Point)
{
// Get the geometry (map point) from the graphic.
MapPoint bufferLocation = bufferGraphic.Geometry as MapPoint;
// Read the "distance" attribute to get the buffer distance entered when the point was tapped.
double bufferDistanceFeet = (double)bufferGraphic.Attributes["distance"];
// Add the point and the corresponding distance to the lists.
bufferMapPoints.Add(bufferLocation);
bufferDistances.Add(bufferDistanceFeet);
}
}
// Call GeometryEngine.Buffer with a list of map points and a list of buffered distances.
IEnumerable<Geometry> bufferPolygons = GeometryEngine.Buffer(bufferMapPoints, bufferDistances, areBuffersUnioned);
// Create the outline for the buffered polygons.
SimpleLineSymbol bufferPolygonOutlineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.DarkBlue, 3);
// Loop through all the geometries in the buffer results. There will be one buffered polygon if
// the result geometries were unioned. Otherwise, there will be one buffer per input geometry.
foreach (Geometry poly in bufferPolygons)
{
// Create a random color to use for buffer polygon fill.
Color bufferPolygonColor = GetRandomColor();
// Create simple fill symbol for the buffered polygon using the fill color and outline.
SimpleFillSymbol bufferPolygonFillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, bufferPolygonColor, bufferPolygonOutlineSymbol);
// Create a new graphic for the buffered polygon using the fill symbol.
Graphic bufferPolygonGraphic = new Graphic(poly, bufferPolygonFillSymbol)
{
// Specify a z-index of 0 to ensure the polygons draw below the tap points.
ZIndex = 0
};
// Add the buffered polygon graphic to the graphics overlay.
MyMapView.GraphicsOverlays[0].Graphics.Add(bufferPolygonGraphic);
}
}
catch (Exception ex)
{
// Display an error message if there is a problem generating the buffers.
await new MessageDialog2(ex.Message, "Unable to create buffer polygons").ShowAsync();
}
}
private Color GetRandomColor()
{
// Get a byte array with three random values.
var colorBytes = new byte[3];
_random.NextBytes(colorBytes);
// Use the random bytes to define red, green, and blue values for a new color.
return Color.FromArgb(155, colorBytes[0], colorBytes[1], colorBytes[2]);
}
private void ClearButton_Click(object sender, RoutedEventArgs e)
{
// Clear all graphics (tap points and buffer polygons).
MyMapView.GraphicsOverlays["buffers"].Graphics.Clear();
}
private void ClearBufferPolygons()
{
// Get the collection of graphics in the graphics overlay (points and buffer polygons).
GraphicCollection bufferGraphics = MyMapView.GraphicsOverlays["buffers"].Graphics;
// Loop (backwards) through all graphics.
for (int i = bufferGraphics.Count - 1; i >= 0; i--)
{
// If the graphic is a polygon, remove it from the overlay.
Graphic thisGraphic = bufferGraphics[i];
if (thisGraphic.Geometry.GeometryType == GeometryType.Polygon)
{
bufferGraphics.RemoveAt(i);
}
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
extern alias WORKSPACES;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Serialization.Formatters;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.CodeAnalysis.Scripting;
using Microsoft.CodeAnalysis.Scripting.Hosting;
using Roslyn.Utilities;
using RuntimeMetadataReferenceResolver = WORKSPACES::Microsoft.CodeAnalysis.Scripting.Hosting.RuntimeMetadataReferenceResolver;
using GacFileResolver = WORKSPACES::Microsoft.CodeAnalysis.Scripting.Hosting.GacFileResolver;
namespace Microsoft.CodeAnalysis.Interactive
{
internal partial class InteractiveHost
{
/// <summary>
/// A remote singleton server-activated object that lives in the interactive host process and controls it.
/// </summary>
internal sealed class Service : MarshalByRefObject, IDisposable
{
private static readonly ManualResetEventSlim s_clientExited = new ManualResetEventSlim(false);
private static TaskScheduler s_UIThreadScheduler;
private readonly InteractiveAssemblyLoader _assemblyLoader;
private readonly MetadataShadowCopyProvider _metadataFileProvider;
private ReplServiceProvider _replServiceProvider;
private readonly InteractiveHostObject _hostObject;
private ObjectFormattingOptions _formattingOptions;
// Session is not thread-safe by itself, and the compilation
// and execution of scripts are asynchronous operations.
// However since the operations are executed serially, it
// is sufficient to lock when creating the async tasks.
private readonly object _lastTaskGuard = new object();
private Task<EvaluationState> _lastTask;
private struct EvaluationState
{
internal ImmutableArray<string> SourceSearchPaths;
internal ImmutableArray<string> ReferenceSearchPaths;
internal string WorkingDirectory;
internal readonly ScriptState<object> ScriptStateOpt;
internal readonly ScriptOptions ScriptOptions;
internal EvaluationState(
ScriptState<object> scriptState,
ScriptOptions scriptOptions,
ImmutableArray<string> sourceSearchPaths,
ImmutableArray<string> referenceSearchPaths,
string workingDirectory)
{
ScriptStateOpt = scriptState;
ScriptOptions = scriptOptions;
SourceSearchPaths = sourceSearchPaths;
ReferenceSearchPaths = referenceSearchPaths;
WorkingDirectory = workingDirectory;
}
internal EvaluationState WithScriptState(ScriptState<object> state)
{
return new EvaluationState(
state,
ScriptOptions,
SourceSearchPaths,
ReferenceSearchPaths,
WorkingDirectory);
}
internal EvaluationState WithOptions(ScriptOptions options)
{
return new EvaluationState(
ScriptStateOpt,
options,
SourceSearchPaths,
ReferenceSearchPaths,
WorkingDirectory);
}
}
private static readonly ImmutableArray<string> s_systemNoShadowCopyDirectories = ImmutableArray.Create(
FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.Windows)),
FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)),
FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)),
FileUtilities.NormalizeDirectoryPath(RuntimeEnvironment.GetRuntimeDirectory()));
#region Setup
public Service()
{
// TODO (tomat): we should share the copied files with the host
_metadataFileProvider = new MetadataShadowCopyProvider(
Path.Combine(Path.GetTempPath(), "InteractiveHostShadow"),
noShadowCopyDirectories: s_systemNoShadowCopyDirectories);
_assemblyLoader = new InteractiveAssemblyLoader(_metadataFileProvider);
_formattingOptions = new ObjectFormattingOptions(
memberFormat: MemberDisplayFormat.Inline,
quoteStrings: true,
useHexadecimalNumbers: false,
maxOutputLength: 200,
memberIndentation: " ");
_hostObject = new InteractiveHostObject();
var initialState = new EvaluationState(
scriptState: null,
scriptOptions: ScriptOptions.Default,
sourceSearchPaths: ImmutableArray<string>.Empty,
referenceSearchPaths: ImmutableArray<string>.Empty,
workingDirectory: Directory.GetCurrentDirectory());
_lastTask = Task.FromResult(initialState);
Console.OutputEncoding = Encoding.UTF8;
// We want to be sure to delete the shadow-copied files when the process goes away. Frankly
// there's nothing we can do if the process is forcefully quit or goes down in a completely
// uncontrolled manner (like a stack overflow). When the process goes down in a controlled
// manned, we should generally expect this event to be called.
AppDomain.CurrentDomain.ProcessExit += HandleProcessExit;
}
private void HandleProcessExit(object sender, EventArgs e)
{
Dispose();
AppDomain.CurrentDomain.ProcessExit -= HandleProcessExit;
}
public void Dispose()
{
_metadataFileProvider.Dispose();
}
public override object InitializeLifetimeService()
{
return null;
}
public void Initialize(Type replServiceProviderType)
{
Contract.ThrowIfNull(replServiceProviderType);
_replServiceProvider = (ReplServiceProvider)Activator.CreateInstance(replServiceProviderType);
}
private MetadataReferenceResolver CreateMetadataReferenceResolver(ImmutableArray<string> searchPaths, string baseDirectory)
{
var userProfilePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
var packagesDirectory = string.IsNullOrEmpty(userProfilePath) ?
null :
Path.Combine(userProfilePath, Path.Combine(".nuget", "packages"));
return new RuntimeMetadataReferenceResolver(
new RelativePathResolver(searchPaths, baseDirectory),
string.IsNullOrEmpty(packagesDirectory) ? null : new NuGetPackageResolverImpl(packagesDirectory),
new GacFileResolver(
architectures: GacFileResolver.Default.Architectures, // TODO (tomat)
preferredCulture: CultureInfo.CurrentCulture), // TODO (tomat)
(path, properties) => _metadataFileProvider.GetReference(path, properties));
}
private SourceReferenceResolver CreateSourceReferenceResolver(ImmutableArray<string> searchPaths, string baseDirectory)
{
return new SourceFileResolver(searchPaths, baseDirectory);
}
private static bool AttachToClientProcess(int clientProcessId)
{
Process clientProcess;
try
{
clientProcess = Process.GetProcessById(clientProcessId);
}
catch (ArgumentException)
{
return false;
}
clientProcess.EnableRaisingEvents = true;
clientProcess.Exited += new EventHandler((_, __) =>
{
s_clientExited.Set();
});
return clientProcess.IsAlive();
}
// for testing purposes
public void EmulateClientExit()
{
s_clientExited.Set();
}
internal static void RunServer(string[] args)
{
if (args.Length != 3)
{
throw new ArgumentException("Expecting arguments: <server port> <semaphore name> <client process id>");
}
RunServer(args[0], args[1], int.Parse(args[2], CultureInfo.InvariantCulture));
}
/// <summary>
/// Implements remote server.
/// </summary>
private static void RunServer(string serverPort, string semaphoreName, int clientProcessId)
{
if (!AttachToClientProcess(clientProcessId))
{
return;
}
// Disables Windows Error Reporting for the process, so that the process fails fast.
// Unfortunately, this doesn't work on Windows Server 2008 (OS v6.0), Vista (OS v6.0) and XP (OS v5.1)
// Note that GetErrorMode is not available on XP at all.
if (Environment.OSVersion.Version >= new Version(6, 1, 0, 0))
{
SetErrorMode(GetErrorMode() | ErrorMode.SEM_FAILCRITICALERRORS | ErrorMode.SEM_NOOPENFILEERRORBOX | ErrorMode.SEM_NOGPFAULTERRORBOX);
}
IpcServerChannel serverChannel = null;
IpcClientChannel clientChannel = null;
try
{
using (var semaphore = Semaphore.OpenExisting(semaphoreName))
{
// DEBUG: semaphore.WaitOne();
var serverProvider = new BinaryServerFormatterSinkProvider();
serverProvider.TypeFilterLevel = TypeFilterLevel.Full;
var clientProvider = new BinaryClientFormatterSinkProvider();
clientChannel = new IpcClientChannel(GenerateUniqueChannelLocalName(), clientProvider);
ChannelServices.RegisterChannel(clientChannel, ensureSecurity: false);
serverChannel = new IpcServerChannel(GenerateUniqueChannelLocalName(), serverPort, serverProvider);
ChannelServices.RegisterChannel(serverChannel, ensureSecurity: false);
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(Service),
ServiceName,
WellKnownObjectMode.Singleton);
using (var resetEvent = new ManualResetEventSlim(false))
{
var uiThread = new Thread(() =>
{
var c = new Control();
c.CreateControl();
s_UIThreadScheduler = TaskScheduler.FromCurrentSynchronizationContext();
resetEvent.Set();
Application.Run();
});
uiThread.SetApartmentState(ApartmentState.STA);
uiThread.IsBackground = true;
uiThread.Start();
resetEvent.Wait();
}
// the client can instantiate interactive host now:
semaphore.Release();
}
s_clientExited.Wait();
}
finally
{
if (serverChannel != null)
{
ChannelServices.UnregisterChannel(serverChannel);
}
if (clientChannel != null)
{
ChannelServices.UnregisterChannel(clientChannel);
}
}
// force exit even if there are foreground threads running:
Environment.Exit(0);
}
internal static string ServiceName
{
get { return typeof(Service).Name; }
}
private static string GenerateUniqueChannelLocalName()
{
return typeof(Service).FullName + Guid.NewGuid();
}
#endregion
#region Remote Async Entry Points
// Used by ResetInteractive - consider improving (we should remember the parameters for auto-reset, e.g.)
[OneWay]
public void SetPathsAsync(
RemoteAsyncOperation<RemoteExecutionResult> operation,
string[] referenceSearchPaths,
string[] sourceSearchPaths,
string baseDirectory)
{
Debug.Assert(operation != null);
Debug.Assert(referenceSearchPaths != null);
Debug.Assert(sourceSearchPaths != null);
Debug.Assert(baseDirectory != null);
lock (_lastTaskGuard)
{
_lastTask = SetPathsAsync(_lastTask, operation, referenceSearchPaths, sourceSearchPaths, baseDirectory);
}
}
private async Task<EvaluationState> SetPathsAsync(
Task<EvaluationState> lastTask,
RemoteAsyncOperation<RemoteExecutionResult> operation,
string[] referenceSearchPaths,
string[] sourceSearchPaths,
string baseDirectory)
{
var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false);
try
{
Directory.SetCurrentDirectory(baseDirectory);
_hostObject.ReferencePaths.Clear();
_hostObject.ReferencePaths.AddRange(referenceSearchPaths);
_hostObject.SourcePaths.Clear();
_hostObject.SourcePaths.AddRange(sourceSearchPaths);
}
finally
{
state = CompleteExecution(state, operation, success: true);
}
return state;
}
/// <summary>
/// Reads given initialization file (.rsp) and loads and executes all assembly references and files, respectively specified in it.
/// Execution is performed on the UI thread.
/// </summary>
[OneWay]
public void InitializeContextAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string initializationFile, bool isRestarting)
{
Debug.Assert(operation != null);
lock (_lastTaskGuard)
{
_lastTask = InitializeContextAsync(_lastTask, operation, initializationFile, isRestarting);
}
}
/// <summary>
/// Adds an assembly reference to the current session.
/// </summary>
[OneWay]
public void AddReferenceAsync(RemoteAsyncOperation<bool> operation, string reference)
{
Debug.Assert(operation != null);
Debug.Assert(reference != null);
lock (_lastTaskGuard)
{
_lastTask = AddReferenceAsync(_lastTask, operation, reference);
}
}
private async Task<EvaluationState> AddReferenceAsync(Task<EvaluationState> lastTask, RemoteAsyncOperation<bool> operation, string reference)
{
var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false);
bool success = false;
try
{
var resolvedReferences = state.ScriptOptions.MetadataResolver.ResolveReference(reference, baseFilePath: null, properties: MetadataReferenceProperties.Assembly);
if (!resolvedReferences.IsDefaultOrEmpty)
{
state = state.WithOptions(state.ScriptOptions.AddReferences(resolvedReferences));
success = true;
}
else
{
Console.Error.WriteLine(string.Format(FeaturesResources.CannotResolveReference, reference));
}
}
catch (Exception e)
{
ReportUnhandledException(e);
}
finally
{
operation.Completed(success);
}
return state;
}
/// <summary>
/// Executes given script snippet on the UI thread in the context of the current session.
/// </summary>
[OneWay]
public void ExecuteAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string text)
{
Debug.Assert(operation != null);
Debug.Assert(text != null);
lock (_lastTaskGuard)
{
_lastTask = ExecuteAsync(_lastTask, operation, text);
}
}
private async Task<EvaluationState> ExecuteAsync(Task<EvaluationState> lastTask, RemoteAsyncOperation<RemoteExecutionResult> operation, string text)
{
var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false);
bool success = false;
try
{
Script<object> script = TryCompile(state.ScriptStateOpt?.Script, text, null, state.ScriptOptions);
if (script != null)
{
// successful if compiled
success = true;
var newScriptState = await ExecuteOnUIThread(script, state.ScriptStateOpt).ConfigureAwait(false);
if (newScriptState != null)
{
DisplaySubmissionResult(newScriptState);
state = state.WithScriptState(newScriptState);
}
}
}
catch (Exception e)
{
ReportUnhandledException(e);
}
finally
{
state = CompleteExecution(state, operation, success);
}
return state;
}
private void DisplaySubmissionResult(ScriptState<object> state)
{
bool hasValue;
var resultType = state.Script.GetCompilation().GetSubmissionResultType(out hasValue);
if (hasValue)
{
if (resultType != null && resultType.SpecialType == SpecialType.System_Void)
{
Console.Out.WriteLine(_replServiceProvider.ObjectFormatter.VoidDisplayString);
}
else
{
Console.Out.WriteLine(_replServiceProvider.ObjectFormatter.FormatObject(state.ReturnValue, _formattingOptions));
}
}
}
/// <summary>
/// Executes given script file on the UI thread in the context of the current session.
/// </summary>
[OneWay]
public void ExecuteFileAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string path)
{
Debug.Assert(operation != null);
Debug.Assert(path != null);
lock (_lastTaskGuard)
{
_lastTask = ExecuteFileAsync(operation, _lastTask, path);
}
}
private EvaluationState CompleteExecution(EvaluationState state, RemoteAsyncOperation<RemoteExecutionResult> operation, bool success)
{
// send any updates to the host object and current directory back to the client:
var currentSourcePaths = _hostObject.SourcePaths.List.ToArray();
var currentReferencePaths = _hostObject.ReferencePaths.List.ToArray();
var currentWorkingDirectory = Directory.GetCurrentDirectory();
var changedSourcePaths = currentSourcePaths.SequenceEqual(state.SourceSearchPaths) ? null : currentSourcePaths;
var changedReferencePaths = currentSourcePaths.SequenceEqual(state.ReferenceSearchPaths) ? null : currentReferencePaths;
var changedWorkingDirectory = currentWorkingDirectory == state.WorkingDirectory ? null : currentWorkingDirectory;
operation.Completed(new RemoteExecutionResult(success, changedSourcePaths, changedReferencePaths, changedWorkingDirectory));
// no changes in resolvers:
if (changedReferencePaths == null && changedSourcePaths == null && changedWorkingDirectory == null)
{
return state;
}
var newSourcePaths = ImmutableArray.CreateRange(currentSourcePaths);
var newReferencePaths = ImmutableArray.CreateRange(currentReferencePaths);
var newWorkingDirectory = currentWorkingDirectory;
ScriptOptions newOptions = state.ScriptOptions;
if (changedReferencePaths != null || changedWorkingDirectory != null)
{
newOptions = newOptions.WithCustomMetadataResolution(CreateMetadataReferenceResolver(newReferencePaths, newWorkingDirectory));
}
if (changedSourcePaths != null || changedWorkingDirectory != null)
{
newOptions = newOptions.WithCustomSourceResolution(CreateSourceReferenceResolver(newSourcePaths, newWorkingDirectory));
}
return new EvaluationState(
state.ScriptStateOpt,
newOptions,
newSourcePaths,
newReferencePaths,
workingDirectory: newWorkingDirectory);
}
private static async Task<EvaluationState> ReportUnhandledExceptionIfAny(Task<EvaluationState> lastTask)
{
try
{
return await lastTask.ConfigureAwait(false);
}
catch (Exception e)
{
ReportUnhandledException(e);
return lastTask.Result;
}
}
private static void ReportUnhandledException(Exception e)
{
Console.Error.WriteLine("Unexpected error:");
Console.Error.WriteLine(e);
Debug.Fail("Unexpected error");
Debug.WriteLine(e);
}
#endregion
#region Operations
// TODO (tomat): testing only
public void SetTestObjectFormattingOptions()
{
_formattingOptions = new ObjectFormattingOptions(
memberFormat: MemberDisplayFormat.Inline,
quoteStrings: true,
useHexadecimalNumbers: false,
maxOutputLength: int.MaxValue,
memberIndentation: " ");
}
/// <summary>
/// Loads references, set options and execute files specified in the initialization file.
/// Also prints logo unless <paramref name="isRestarting"/> is true.
/// </summary>
private async Task<EvaluationState> InitializeContextAsync(
Task<EvaluationState> lastTask,
RemoteAsyncOperation<RemoteExecutionResult> operation,
string initializationFileOpt,
bool isRestarting)
{
Debug.Assert(initializationFileOpt == null || PathUtilities.IsAbsolute(initializationFileOpt));
var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false);
try
{
// TODO (tomat): this is also done in CommonInteractiveEngine, perhaps we can pass the parsed command lines to here?
if (!isRestarting)
{
Console.Out.WriteLine(_replServiceProvider.Logo);
}
if (File.Exists(initializationFileOpt))
{
Console.Out.WriteLine(string.Format(FeaturesResources.LoadingContextFrom, Path.GetFileName(initializationFileOpt)));
var parser = _replServiceProvider.CommandLineParser;
// The base directory for relative paths is the directory that contains the .rsp file.
// Note that .rsp files included by this .rsp file will share the base directory (Dev10 behavior of csc/vbc).
var rspDirectory = Path.GetDirectoryName(initializationFileOpt);
var args = parser.Parse(new[] { "@" + initializationFileOpt }, rspDirectory, RuntimeEnvironment.GetRuntimeDirectory(), null /* TODO: pass a valid value*/);
foreach (var error in args.Errors)
{
var writer = (error.Severity == DiagnosticSeverity.Error) ? Console.Error : Console.Out;
writer.WriteLine(error.GetMessage(CultureInfo.CurrentCulture));
}
if (args.Errors.Length == 0)
{
// TODO (tomat): other arguments
// TODO (tomat): parse options
var metadataResolver = CreateMetadataReferenceResolver(args.ReferencePaths, rspDirectory);
_hostObject.ReferencePaths.Clear();
_hostObject.ReferencePaths.AddRange(args.ReferencePaths);
_hostObject.SourcePaths.Clear();
var metadataReferences = new List<PortableExecutableReference>();
foreach (CommandLineReference cmdLineReference in args.MetadataReferences)
{
// interactive command line parser doesn't accept modules or linked assemblies
Debug.Assert(cmdLineReference.Properties.Kind == MetadataImageKind.Assembly && !cmdLineReference.Properties.EmbedInteropTypes);
var resolvedReferences = metadataResolver.ResolveReference(cmdLineReference.Reference, baseFilePath: null, properties: MetadataReferenceProperties.Assembly);
if (!resolvedReferences.IsDefaultOrEmpty)
{
metadataReferences.AddRange(resolvedReferences);
}
}
// only search for scripts next to the .rsp file:
var sourceSearchPaths = ImmutableArray<string>.Empty;
var rspState = new EvaluationState(
state.ScriptStateOpt,
state.ScriptOptions.AddReferences(metadataReferences),
sourceSearchPaths,
args.ReferencePaths,
rspDirectory);
foreach (CommandLineSourceFile file in args.SourceFiles)
{
// execute all files as scripts (matches csi/vbi semantics)
string fullPath = ResolveRelativePath(file.Path, rspDirectory, sourceSearchPaths, displayPath: true);
if (fullPath != null)
{
var newScriptState = await ExecuteFileAsync(rspState, fullPath).ConfigureAwait(false);
if (newScriptState != null)
{
rspState = rspState.WithScriptState(newScriptState);
}
}
}
state = new EvaluationState(
rspState.ScriptStateOpt,
rspState.ScriptOptions,
ImmutableArray<string>.Empty,
args.ReferencePaths,
state.WorkingDirectory);
}
}
if (!isRestarting)
{
Console.Out.WriteLine(FeaturesResources.TypeHelpForMoreInformation);
}
}
catch (Exception e)
{
ReportUnhandledException(e);
}
finally
{
state = CompleteExecution(state, operation, success: true);
}
return state;
}
private string ResolveRelativePath(string path, string baseDirectory, ImmutableArray<string> searchPaths, bool displayPath)
{
List<string> attempts = new List<string>();
Func<string, bool> fileExists = file =>
{
attempts.Add(file);
return File.Exists(file);
};
string fullPath = FileUtilities.ResolveRelativePath(path, null, baseDirectory, searchPaths, fileExists);
if (fullPath == null)
{
if (displayPath)
{
Console.Error.WriteLine(FeaturesResources.SpecifiedFileNotFoundFormat, path);
}
else
{
Console.Error.WriteLine(FeaturesResources.SpecifiedFileNotFound);
}
if (attempts.Count > 0)
{
DisplaySearchPaths(Console.Error, attempts);
}
}
return fullPath;
}
private void LoadReference(PortableExecutableReference resolvedReference, bool suppressWarnings)
{
AssemblyLoadResult result;
try
{
result = _assemblyLoader.LoadFromPath(resolvedReference.FilePath);
}
catch (FileNotFoundException e)
{
Console.Error.WriteLine(e.Message);
return;
}
catch (ArgumentException e)
{
Console.Error.WriteLine((e.InnerException ?? e).Message);
return;
}
catch (TargetInvocationException e)
{
// The user might have hooked AssemblyResolve event, which might have thrown an exception.
// Display stack trace in this case.
Console.Error.WriteLine(e.InnerException.ToString());
return;
}
if (!result.IsSuccessful && !suppressWarnings)
{
Console.Out.WriteLine(string.Format(CultureInfo.CurrentCulture, FeaturesResources.RequestedAssemblyAlreadyLoaded, result.OriginalPath));
}
}
private Script<object> TryCompile(Script previousScript, string code, string path, ScriptOptions options)
{
Script script;
var scriptOptions = options.WithPath(path).WithIsInteractive(path == null);
if (previousScript != null)
{
script = previousScript.ContinueWith(code, scriptOptions);
}
else
{
script = _replServiceProvider.CreateScript<object>(code, scriptOptions, _hostObject.GetType(), _assemblyLoader);
}
// force build so exception is thrown now if errors are found.
try
{
script.Build();
}
catch (CompilationErrorException e)
{
DisplayInteractiveErrors(e.Diagnostics, Console.Error);
return null;
}
// TODO: Do we want to do this?
// Pros: immediate feedback for assemblies that can't be loaded.
// Cons: maybe we won't need them
//foreach (PortableExecutableReference reference in script.GetCompilation().DirectiveReferences)
//{
// LoadReference(reference, suppressWarnings: false);
//}
return (Script<object>)script;
}
private async Task<EvaluationState> ExecuteFileAsync(
RemoteAsyncOperation<RemoteExecutionResult> operation,
Task<EvaluationState> lastTask,
string path)
{
var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false);
var success = false;
try
{
var fullPath = ResolveRelativePath(path, state.WorkingDirectory, state.SourceSearchPaths, displayPath: false);
var newScriptState = await ExecuteFileAsync(state, fullPath).ConfigureAwait(false);
if (newScriptState != null)
{
success = true;
state = state.WithScriptState(newScriptState);
}
}
finally
{
state = CompleteExecution(state, operation, success);
}
return state;
}
/// <summary>
/// Executes specified script file as a submission.
/// </summary>
/// <returns>True if the code has been executed. False if the code doesn't compile.</returns>
/// <remarks>
/// All errors are written to the error output stream.
/// Uses source search paths to resolve unrooted paths.
/// </remarks>
private async Task<ScriptState<object>> ExecuteFileAsync(EvaluationState state, string fullPath)
{
string content = null;
if (fullPath != null)
{
Debug.Assert(PathUtilities.IsAbsolute(fullPath));
try
{
content = File.ReadAllText(fullPath);
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
}
}
ScriptState<object> newScriptState = null;
if (content != null)
{
Script<object> script = TryCompile(state.ScriptStateOpt?.Script, content, fullPath, state.ScriptOptions);
if (script != null)
{
newScriptState = await ExecuteOnUIThread(script, state.ScriptStateOpt).ConfigureAwait(false);
}
}
return newScriptState;
}
private static void DisplaySearchPaths(TextWriter writer, List<string> attemptedFilePaths)
{
var directories = attemptedFilePaths.Select(path => Path.GetDirectoryName(path)).ToArray();
var uniqueDirectories = new HashSet<string>(directories);
writer.WriteLine(uniqueDirectories.Count == 1 ?
FeaturesResources.SearchedInDirectory :
FeaturesResources.SearchedInDirectories);
foreach (string directory in directories)
{
if (uniqueDirectories.Remove(directory))
{
writer.Write(" ");
writer.WriteLine(directory);
}
}
}
private async Task<ScriptState<object>> ExecuteOnUIThread(Script<object> script, ScriptState<object> stateOpt)
{
return await Task.Factory.StartNew(async () =>
{
try
{
var task = (stateOpt == null) ?
script.RunAsync(_hostObject, CancellationToken.None) :
script.ContinueAsync(stateOpt, CancellationToken.None);
return await task.ConfigureAwait(false);
}
catch (Exception e)
{
// TODO (tomat): format exception
Console.Error.WriteLine(e);
return null;
}
},
CancellationToken.None,
TaskCreationOptions.None,
s_UIThreadScheduler).Unwrap().ConfigureAwait(false);
}
private void DisplayInteractiveErrors(ImmutableArray<Diagnostic> diagnostics, TextWriter output)
{
var displayedDiagnostics = new List<Diagnostic>();
const int MaxErrorCount = 5;
for (int i = 0, n = Math.Min(diagnostics.Length, MaxErrorCount); i < n; i++)
{
displayedDiagnostics.Add(diagnostics[i]);
}
displayedDiagnostics.Sort((d1, d2) => d1.Location.SourceSpan.Start - d2.Location.SourceSpan.Start);
var formatter = _replServiceProvider.DiagnosticFormatter;
foreach (var diagnostic in displayedDiagnostics)
{
output.WriteLine(formatter.Format(diagnostic, output.FormatProvider as CultureInfo));
}
if (diagnostics.Length > MaxErrorCount)
{
int notShown = diagnostics.Length - MaxErrorCount;
output.WriteLine(string.Format(output.FormatProvider, FeaturesResources.PlusAdditional, notShown, (notShown == 1) ? "error" : "errors"));
}
}
#endregion
#region Win32 API
[DllImport("kernel32", PreserveSig = true)]
internal static extern ErrorMode SetErrorMode(ErrorMode mode);
[DllImport("kernel32", PreserveSig = true)]
internal static extern ErrorMode GetErrorMode();
[Flags]
internal enum ErrorMode : int
{
/// <summary>
/// Use the system default, which is to display all error dialog boxes.
/// </summary>
SEM_FAILCRITICALERRORS = 0x0001,
/// <summary>
/// The system does not display the critical-error-handler message box. Instead, the system sends the error to the calling process.
/// Best practice is that all applications call the process-wide SetErrorMode function with a parameter of SEM_FAILCRITICALERRORS at startup.
/// This is to prevent error mode dialogs from hanging the application.
/// </summary>
SEM_NOGPFAULTERRORBOX = 0x0002,
/// <summary>
/// The system automatically fixes memory alignment faults and makes them invisible to the application.
/// It does this for the calling process and any descendant processes. This feature is only supported by
/// certain processor architectures. For more information, see the Remarks section.
/// After this value is set for a process, subsequent attempts to clear the value are ignored.
/// </summary>
SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
/// <summary>
/// The system does not display a message box when it fails to find a file. Instead, the error is returned to the calling process.
/// </summary>
SEM_NOOPENFILEERRORBOX = 0x8000,
}
#endregion
#region Testing
// TODO(tomat): remove when the compiler supports events
// For testing purposes only!
public void HookMaliciousAssemblyResolve()
{
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler((_, __) =>
{
int i = 0;
while (true)
{
if (i < 10)
{
i = i + 1;
}
else if (i == 10)
{
Console.Error.WriteLine("in the loop");
i = i + 1;
}
}
});
}
public void RemoteConsoleWrite(byte[] data, bool isError)
{
using (var stream = isError ? Console.OpenStandardError() : Console.OpenStandardOutput())
{
stream.Write(data, 0, data.Length);
stream.Flush();
}
}
public bool IsShadowCopy(string path)
{
return _metadataFileProvider.IsShadowCopy(path);
}
#endregion
}
}
}
| |
/***************************************************************************
* SafeUri.cs
*
* Copyright (C) 2006 Novell, Inc.
* Written by Aaron Bockover <aaron@abock.org>
****************************************************************************/
/* 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.Runtime.InteropServices;
namespace Hyena
{
public class SafeUri
{
private enum LocalPathCheck {
NotPerformed,
Yes,
No
}
private static int MAX_SCHEME_LENGTH = 8;
private string uri;
private string local_path;
private string scheme;
private LocalPathCheck local_path_check = LocalPathCheck.NotPerformed;
public SafeUri (string uri)
{
if (String.IsNullOrEmpty (uri)) {
throw new ArgumentNullException ("uri");
}
int scheme_delimit_index = uri.IndexOf ("://", StringComparison.InvariantCulture);
if (scheme_delimit_index > 0 && scheme_delimit_index <= MAX_SCHEME_LENGTH) {
this.uri = uri;
} else {
this.uri = FilenameToUri (uri);
}
}
public SafeUri (string uriOrFilename, bool isUri)
{
if (String.IsNullOrEmpty (uriOrFilename)) {
throw new ArgumentNullException ("uriOrFilename");
}
if (isUri) {
this.uri = uriOrFilename;
} else {
this.uri = FilenameToUri (uriOrFilename);
}
}
public SafeUri (Uri uri)
{
if (uri == null) {
throw new ArgumentNullException ("uri");
}
this.uri = uri.AbsoluteUri;
}
public static string FilenameToUri (string localPath)
{
// TODO: replace with managed conversion to avoid marshalling
IntPtr path_ptr = GLib.Marshaller.StringToPtrGStrdup (localPath);
IntPtr uri_ptr = PlatformDetection.IsWindows
? g_filename_to_uri_utf8 (path_ptr, IntPtr.Zero, IntPtr.Zero)
: g_filename_to_uri (path_ptr, IntPtr.Zero, IntPtr.Zero);
GLib.Marshaller.Free (path_ptr);
if (uri_ptr == IntPtr.Zero) {
throw new ApplicationException ("Filename path must be absolute");
}
string uri = GLib.Marshaller.Utf8PtrToString (uri_ptr);
GLib.Marshaller.Free (uri_ptr);
return uri;
}
public static string UriToFilename (string uri)
{
// TODO: replace with managed conversion to avoid marshalling
IntPtr uri_ptr = GLib.Marshaller.StringToPtrGStrdup (uri);
IntPtr path_ptr = PlatformDetection.IsWindows
? g_filename_from_uri_utf8 (uri_ptr, IntPtr.Zero, IntPtr.Zero)
: g_filename_from_uri (uri_ptr, IntPtr.Zero, IntPtr.Zero);
GLib.Marshaller.Free (uri_ptr);
if (path_ptr == IntPtr.Zero) {
throw new ApplicationException ("URI could not be converted to local file location");
}
string path = GLib.Marshaller.Utf8PtrToString (path_ptr);
GLib.Marshaller.Free (path_ptr);
return path;
}
public static string UriToFilename (SafeUri uri)
{
return UriToFilename (uri.AbsoluteUri);
}
public override string ToString ()
{
return AbsoluteUri;
}
public static implicit operator string (SafeUri s)
{
return s.ToString ();
}
public override bool Equals (object o)
{
SafeUri s = o as SafeUri;
if (s != null) {
return s.AbsoluteUri == AbsoluteUri;
}
return false;
}
public override int GetHashCode ()
{
return AbsoluteUri.GetHashCode ();
}
public string AbsoluteUri {
get { return uri; }
}
public bool IsLocalPath {
get {
if (local_path_check == LocalPathCheck.NotPerformed) {
if (IsFile) {
local_path_check = LocalPathCheck.Yes;
return true;
} else {
local_path_check = LocalPathCheck.No;
return false;
}
}
return local_path_check == LocalPathCheck.Yes;
}
}
public string AbsolutePath {
get {
if (local_path == null && IsLocalPath) {
local_path = UriToFilename (uri);
}
return local_path;
}
}
public string LocalPath {
get { return AbsolutePath; }
}
public string Scheme {
get {
if (scheme == null) {
scheme = uri.Substring (0, uri.IndexOf ("://", StringComparison.InvariantCulture));
}
return scheme;
}
}
public bool IsFile {
get { return Scheme == System.Uri.UriSchemeFile; }
}
const string GLIB_DLL = "libglib-2.0-0.dll";
[DllImport (GLIB_DLL, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr g_filename_to_uri_utf8 (IntPtr filename, IntPtr hostname, IntPtr error);
[DllImport (GLIB_DLL, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr g_filename_from_uri_utf8 (IntPtr uri, IntPtr hostname, IntPtr error);
[DllImport (GLIB_DLL, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr g_filename_to_uri (IntPtr filename, IntPtr hostname, IntPtr error);
[DllImport (GLIB_DLL, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr g_filename_from_uri (IntPtr uri, IntPtr hostname, IntPtr error);
}
}
| |
// Copyright 2011 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using Microsoft.Data.Edm.Annotations;
using Microsoft.Data.Edm.Internal;
using Microsoft.Data.Edm.Library;
using Microsoft.Data.Edm.Validation;
using Microsoft.Data.Edm.Validation.Internal;
using Microsoft.Data.Edm.Values;
namespace Microsoft.Data.Edm.Csdl
{
/// <summary>
/// Represents whether a vocabulary annotation should be serialized within the element it applies to or in a seperate section of the CSDL.
/// </summary>
public enum EdmVocabularyAnnotationSerializationLocation
{
/// <summary>
/// The annotation should be serialized within the element being annotated.
/// </summary>
Inline,
/// <summary>
/// The annotation should be serialized in a seperate section.
/// </summary>
OutOfLine
}
/// <summary>
/// Contains extension methods for <see cref="IEdmModel"/> interfaces that are useful to serialization.
/// </summary>
public static class SerializationExtensionMethods
{
#region Private Constants
private const char AssociationNameEscapeChar = '_';
private const string AssociationNameEscapeString = "_";
private const string AssociationNameEscapeStringEscaped = "__";
#endregion
#region EdmxVersion
/// <summary>
/// Gets the value for the EDMX version of the <paramref name="model"/>.
/// </summary>
/// <param name="model">Model the version has been set for.</param>
/// <returns>The version.</returns>
public static Version GetEdmxVersion(this IEdmModel model)
{
EdmUtil.CheckArgumentNull(model, "model");
return model.GetAnnotationValue<Version>(model, EdmConstants.InternalUri, CsdlConstants.EdmxVersionAnnotation);
}
/// <summary>
/// Sets a value of EDMX version attribute of the <paramref name="model"/>.
/// </summary>
/// <param name="model">The model the version should be set for.</param>
/// <param name="version">The version.</param>
public static void SetEdmxVersion(this IEdmModel model, Version version)
{
EdmUtil.CheckArgumentNull(model, "model");
model.SetAnnotationValue(model, EdmConstants.InternalUri, CsdlConstants.EdmxVersionAnnotation, version);
}
#endregion
#region NamespacePrefixMappings
/// <summary>
/// Sets an annotation on the IEdmModel to notify the serializer of preferred prefix mappings for xml namespaces.
/// </summary>
/// <param name="model">Reference to the calling object.</param>
/// <param name="mappings">XmlNamespaceManage containing mappings between namespace prefixes and xml namespaces.</param>
public static void SetNamespacePrefixMappings(this IEdmModel model, IEnumerable<KeyValuePair<string, string>> mappings)
{
EdmUtil.CheckArgumentNull(model, "model");
model.SetAnnotationValue(model, EdmConstants.InternalUri, CsdlConstants.NamespacePrefixAnnotation, mappings);
}
/// <summary>
/// Gets the preferred prefix mappings for xml namespaces from an IEdmModel
/// </summary>
/// <param name="model">Reference to the calling object.</param>
/// <returns>Namespace prefixes that exist on the model.</returns>
public static IEnumerable<KeyValuePair<string, string>> GetNamespacePrefixMappings(this IEdmModel model)
{
EdmUtil.CheckArgumentNull(model, "model");
return model.GetAnnotationValue<IEnumerable<KeyValuePair<string, string>>>(model, EdmConstants.InternalUri, CsdlConstants.NamespacePrefixAnnotation);
}
#endregion
#region DataServicesVersion
/// <summary>
/// Sets a value for the DataServiceVersion attribute in an EDMX artifact.
/// </summary>
/// <param name="model">The model the attribute should be set for.</param>
/// <param name="version">The value of the attribute.</param>
public static void SetDataServiceVersion(this IEdmModel model, Version version)
{
EdmUtil.CheckArgumentNull(model, "model");
model.SetAnnotationValue(model, EdmConstants.InternalUri, EdmConstants.DataServiceVersion, version);
}
/// <summary>
/// Gets the value for the DataServiceVersion attribute used during EDMX serialization.
/// </summary>
/// <param name="model">Model the attribute has been set for.</param>
/// <returns>Value of the attribute.</returns>
public static Version GetDataServiceVersion(this IEdmModel model)
{
EdmUtil.CheckArgumentNull(model, "model");
return model.GetAnnotationValue<Version>(model, EdmConstants.InternalUri, EdmConstants.DataServiceVersion);
}
#endregion
#region MaxDataServicesVersion
/// <summary>
/// Sets a value for the MaxDataServiceVersion attribute in an EDMX artifact.
/// </summary>
/// <param name="model">The model the attribute should be set for.</param>
/// <param name="version">The value of the attribute.</param>
public static void SetMaxDataServiceVersion(this IEdmModel model, Version version)
{
EdmUtil.CheckArgumentNull(model, "model");
model.SetAnnotationValue(model, EdmConstants.InternalUri, EdmConstants.MaxDataServiceVersion, version);
}
/// <summary>
/// Gets the value for the MaxDataServiceVersion attribute used during EDMX serialization.
/// </summary>
/// <param name="model">Model the attribute has been set for</param>
/// <returns>Value of the attribute.</returns>
public static Version GetMaxDataServiceVersion(this IEdmModel model)
{
EdmUtil.CheckArgumentNull(model, "model");
return model.GetAnnotationValue<Version>(model, EdmConstants.InternalUri, EdmConstants.MaxDataServiceVersion);
}
#endregion
#region SerializationLocation
/// <summary>
/// Sets the location an annotation should be serialized in.
/// </summary>
/// <param name="annotation">The annotation the location is being specified for.</param>
/// <param name="model">Model containing the annotation.</param>
/// <param name="location">The location the annotation should appear.</param>
public static void SetSerializationLocation(this IEdmVocabularyAnnotation annotation, IEdmModel model, EdmVocabularyAnnotationSerializationLocation? location)
{
EdmUtil.CheckArgumentNull(annotation, "annotation");
EdmUtil.CheckArgumentNull(model, "model");
model.SetAnnotationValue(annotation, EdmConstants.InternalUri, CsdlConstants.AnnotationSerializationLocationAnnotation, (object)location);
}
/// <summary>
/// Gets the location an annotation should be serialized in.
/// </summary>
/// <param name="annotation">Reference to the calling annotation.</param>
/// <param name="model">Model containing the annotation.</param>
/// <returns>The location the annotation should be serialized at.</returns>
public static EdmVocabularyAnnotationSerializationLocation? GetSerializationLocation(this IEdmVocabularyAnnotation annotation, IEdmModel model)
{
EdmUtil.CheckArgumentNull(annotation, "annotation");
EdmUtil.CheckArgumentNull(model, "model");
return model.GetAnnotationValue(annotation, EdmConstants.InternalUri, CsdlConstants.AnnotationSerializationLocationAnnotation) as EdmVocabularyAnnotationSerializationLocation?;
}
#endregion
#region SchemaNamespace
/// <summary>
/// Sets the schema an annotation should appear in.
/// </summary>
/// <param name="annotation">The annotation the schema should be set for.</param>
/// <param name="model">Model containing the annotation.</param>
/// <param name="schemaNamespace">The schema the annotation belongs in.</param>
public static void SetSchemaNamespace(this IEdmVocabularyAnnotation annotation, IEdmModel model, string schemaNamespace)
{
EdmUtil.CheckArgumentNull(annotation, "annotation");
EdmUtil.CheckArgumentNull(model, "model");
model.SetAnnotationValue(annotation, EdmConstants.InternalUri, CsdlConstants.SchemaNamespaceAnnotation, schemaNamespace);
}
/// <summary>
/// Gets the schema an annotation should be serialized in.
/// </summary>
/// <param name="annotation">Reference to the calling annotation.</param>
/// <param name="model">Model containing the annotation.</param>
/// <returns>Name of the schema the annotation belongs to.</returns>
public static string GetSchemaNamespace(this IEdmVocabularyAnnotation annotation, IEdmModel model)
{
EdmUtil.CheckArgumentNull(annotation, "annotation");
EdmUtil.CheckArgumentNull(model, "model");
return model.GetAnnotationValue<string>(annotation, EdmConstants.InternalUri, CsdlConstants.SchemaNamespaceAnnotation);
}
#endregion
#region Model
/// <summary>
/// Sets the name used for the association serialized for a navigation property.
/// </summary>
/// <param name="model">Model containing the navigation property.</param>
/// <param name="property">The navigation property.</param>
/// <param name="associationName">The association name.</param>
public static void SetAssociationName(this IEdmModel model, IEdmNavigationProperty property, string associationName)
{
EdmUtil.CheckArgumentNull(model, "model");
EdmUtil.CheckArgumentNull(property, "property");
EdmUtil.CheckArgumentNull(associationName, "associationName");
model.SetAnnotationValue(property, EdmConstants.InternalUri, CsdlConstants.AssociationNameAnnotation, associationName);
}
/// <summary>
/// Gets the name used for the association serialized for a navigation property.
/// </summary>
/// <param name="model">Model containing the navigation property.</param>
/// <param name="property">The navigation property.</param>
/// <returns>The association name.</returns>
public static string GetAssociationName(this IEdmModel model, IEdmNavigationProperty property)
{
EdmUtil.CheckArgumentNull(model, "model");
EdmUtil.CheckArgumentNull(property, "property");
property.PopulateCaches();
string associationName = model.GetAnnotationValue<string>(property, EdmConstants.InternalUri, CsdlConstants.AssociationNameAnnotation);
if (associationName == null)
{
IEdmNavigationProperty fromPrincipal = property.GetPrimary();
IEdmNavigationProperty toPrincipal = fromPrincipal.Partner;
associationName =
GetQualifiedAndEscapedPropertyName(toPrincipal) +
AssociationNameEscapeChar +
GetQualifiedAndEscapedPropertyName(fromPrincipal);
}
return associationName;
}
/// <summary>
/// Sets the namespace used for the association serialized for a navigation property.
/// </summary>
/// <param name="model">Model containing the navigation property.</param>
/// <param name="property">The navigation property.</param>
/// <param name="associationNamespace">The association namespace.</param>
public static void SetAssociationNamespace(this IEdmModel model, IEdmNavigationProperty property, string associationNamespace)
{
EdmUtil.CheckArgumentNull(model, "model");
EdmUtil.CheckArgumentNull(property, "property");
EdmUtil.CheckArgumentNull(associationNamespace, "associationNamespace");
model.SetAnnotationValue(property, EdmConstants.InternalUri, CsdlConstants.AssociationNamespaceAnnotation, associationNamespace);
}
/// <summary>
/// Gets the namespace used for the association serialized for a navigation property.
/// </summary>
/// <param name="model">Model containing the navigation property.</param>
/// <param name="property">The navigation property.</param>
/// <returns>The association namespace.</returns>
public static string GetAssociationNamespace(this IEdmModel model, IEdmNavigationProperty property)
{
EdmUtil.CheckArgumentNull(model, "model");
EdmUtil.CheckArgumentNull(property, "property");
property.PopulateCaches();
string associationNamespace = model.GetAnnotationValue<string>(property, EdmConstants.InternalUri, CsdlConstants.AssociationNamespaceAnnotation);
if (associationNamespace == null)
{
associationNamespace = property.GetPrimary().DeclaringEntityType().Namespace;
}
return associationNamespace;
}
/// <summary>
/// Gets the fully-qualified name used for the association serialized for a navigation property.
/// </summary>
/// <param name="model">Model containing the navigation property.</param>
/// <param name="property">The navigation property.</param>
/// <returns>The fully-qualified association name.</returns>
public static string GetAssociationFullName(this IEdmModel model, IEdmNavigationProperty property)
{
EdmUtil.CheckArgumentNull(model, "model");
EdmUtil.CheckArgumentNull(property, "property");
property.PopulateCaches();
return model.GetAssociationNamespace(property) + "." + model.GetAssociationName(property);
}
/// <summary>
/// Sets the annotations for the association serialized for a navigation property.
/// </summary>
/// <param name="model">Model containing the navigation property.</param>
/// <param name="property">The navigation property.</param>
/// <param name="annotations">The association annotations.</param>
/// <param name="end1Annotations">The annotations for association end 1.</param>
/// <param name="end2Annotations">The annotations for association end 2.</param>
/// <param name="constraintAnnotations">The annotations for the referential constraint.</param>
public static void SetAssociationAnnotations(this IEdmModel model, IEdmNavigationProperty property, IEnumerable<IEdmDirectValueAnnotation> annotations, IEnumerable<IEdmDirectValueAnnotation> end1Annotations, IEnumerable<IEdmDirectValueAnnotation> end2Annotations, IEnumerable<IEdmDirectValueAnnotation> constraintAnnotations)
{
EdmUtil.CheckArgumentNull(model, "model");
EdmUtil.CheckArgumentNull(property, "property");
if ((annotations != null && annotations.FirstOrDefault() != null) || (end1Annotations != null && end1Annotations.FirstOrDefault() != null) || (end2Annotations != null && end2Annotations.FirstOrDefault() != null) || (constraintAnnotations != null && constraintAnnotations.FirstOrDefault() != null))
{
model.SetAnnotationValue(property, EdmConstants.InternalUri, CsdlConstants.AssociationAnnotationsAnnotation, new AssociationAnnotations { Annotations = annotations, End1Annotations = end1Annotations, End2Annotations = end2Annotations, ConstraintAnnotations = constraintAnnotations });
}
}
/// <summary>
/// Gets the annotations associated with the association serialized for a navigation property.
/// </summary>
/// <param name="model">Model containing the navigation property.</param>
/// <param name="property">The navigation property.</param>
/// <param name="annotations">The association annotations.</param>
/// <param name="end1Annotations">The annotations for association end 1.</param>
/// <param name="end2Annotations">The annotations for association end 2.</param>
/// <param name="constraintAnnotations">The annotations for the referential constraint.</param>
public static void GetAssociationAnnotations(this IEdmModel model, IEdmNavigationProperty property, out IEnumerable<IEdmDirectValueAnnotation> annotations, out IEnumerable<IEdmDirectValueAnnotation> end1Annotations, out IEnumerable<IEdmDirectValueAnnotation> end2Annotations, out IEnumerable<IEdmDirectValueAnnotation> constraintAnnotations)
{
EdmUtil.CheckArgumentNull(model, "model");
EdmUtil.CheckArgumentNull(property, "property");
property.PopulateCaches();
AssociationAnnotations associationAnnotations = model.GetAnnotationValue<AssociationAnnotations>(property, EdmConstants.InternalUri, CsdlConstants.AssociationAnnotationsAnnotation);
if (associationAnnotations != null)
{
annotations = associationAnnotations.Annotations ?? Enumerable.Empty<IEdmDirectValueAnnotation>();
end1Annotations = associationAnnotations.End1Annotations ?? Enumerable.Empty<IEdmDirectValueAnnotation>();
end2Annotations = associationAnnotations.End2Annotations ?? Enumerable.Empty<IEdmDirectValueAnnotation>();
constraintAnnotations = associationAnnotations.ConstraintAnnotations ?? Enumerable.Empty<IEdmDirectValueAnnotation>();
}
else
{
IEnumerable<IEdmDirectValueAnnotation> empty = Enumerable.Empty<IEdmDirectValueAnnotation>();
annotations = empty;
end1Annotations = empty;
end2Annotations = empty;
constraintAnnotations = empty;
}
}
/// <summary>
/// Sets the name used for the association end serialized for a navigation property.
/// </summary>
/// <param name="model">Model containing the navigation property.</param>
/// <param name="property">The navigation property.</param>
/// <param name="association">The association end name.</param>
public static void SetAssociationEndName(this IEdmModel model, IEdmNavigationProperty property, string association)
{
EdmUtil.CheckArgumentNull(model, "model");
EdmUtil.CheckArgumentNull(property, "property");
model.SetAnnotationValue(property, EdmConstants.InternalUri, CsdlConstants.AssociationEndNameAnnotation, association);
}
/// <summary>
/// Gets the name used for the association end serialized for a navigation property.
/// </summary>
/// <param name="model">Model containing the navigation property.</param>
/// <param name="property">The navigation property.</param>
/// <returns>The association end name.</returns>
public static string GetAssociationEndName(this IEdmModel model, IEdmNavigationProperty property)
{
EdmUtil.CheckArgumentNull(model, "model");
EdmUtil.CheckArgumentNull(property, "property");
property.PopulateCaches();
return model.GetAnnotationValue<string>(property, EdmConstants.InternalUri, CsdlConstants.AssociationEndNameAnnotation) ?? property.Partner.Name;
}
/// <summary>
/// Sets the name used for the association set serialized for a navigation property of an entity set.
/// </summary>
/// <param name="model">Model containing the entity set.</param>
/// <param name="entitySet">The entity set</param>
/// <param name="property">The navigation property.</param>
/// <param name="associationSet">The association set name.</param>
public static void SetAssociationSetName(this IEdmModel model, IEdmEntitySet entitySet, IEdmNavigationProperty property, string associationSet)
{
EdmUtil.CheckArgumentNull(model, "model");
EdmUtil.CheckArgumentNull(entitySet, "entitySet");
EdmUtil.CheckArgumentNull(property, "property");
Dictionary<string, string> navigationPropertyMappings = model.GetAnnotationValue<Dictionary<string, string>>(entitySet, EdmConstants.InternalUri, CsdlConstants.AssociationSetNameAnnotation);
if (navigationPropertyMappings == null)
{
navigationPropertyMappings = new Dictionary<string, string>();
model.SetAnnotationValue(entitySet, EdmConstants.InternalUri, CsdlConstants.AssociationSetNameAnnotation, navigationPropertyMappings);
}
navigationPropertyMappings[property.Name] = associationSet;
}
/// <summary>
/// Gets the name used for the association set serialized for a navigation property of an entity set.
/// </summary>
/// <param name="model">Model containing the entity set.</param>
/// <param name="entitySet">The entity set.</param>
/// <param name="property">The navigation property.</param>
/// <returns>The association set name.</returns>
public static string GetAssociationSetName(this IEdmModel model, IEdmEntitySet entitySet, IEdmNavigationProperty property)
{
EdmUtil.CheckArgumentNull(model, "model");
EdmUtil.CheckArgumentNull(entitySet, "entitySet");
EdmUtil.CheckArgumentNull(property, "property");
string associationSetName;
Dictionary<string, string> navigationPropertyMappings = model.GetAnnotationValue<Dictionary<string, string>>(entitySet, EdmConstants.InternalUri, CsdlConstants.AssociationSetNameAnnotation);
if (navigationPropertyMappings == null || !navigationPropertyMappings.TryGetValue(property.Name, out associationSetName))
{
associationSetName = model.GetAssociationName(property) + "Set";
}
return associationSetName;
}
/// <summary>
/// Sets the annotations for the association set serialized for a navigation target of an entity set.
/// </summary>
/// <param name="model">Model containing the entity set.</param>
/// <param name="entitySet">The entity set.</param>
/// <param name="property">The navigation property.</param>
/// <param name="annotations">The association set annotations.</param>
/// <param name="end1Annotations">The annotations for association set end 1.</param>
/// <param name="end2Annotations">The annotations for association set end 2.</param>
public static void SetAssociationSetAnnotations(this IEdmModel model, IEdmEntitySet entitySet, IEdmNavigationProperty property, IEnumerable<IEdmDirectValueAnnotation> annotations, IEnumerable<IEdmDirectValueAnnotation> end1Annotations, IEnumerable<IEdmDirectValueAnnotation> end2Annotations)
{
EdmUtil.CheckArgumentNull(model, "model");
EdmUtil.CheckArgumentNull(entitySet, "property");
EdmUtil.CheckArgumentNull(property, "property");
if ((annotations != null && annotations.FirstOrDefault() != null) || (end1Annotations != null && end1Annotations.FirstOrDefault() != null) || (end2Annotations != null && end2Annotations.FirstOrDefault() != null))
{
Dictionary<string, AssociationSetAnnotations> navigationPropertyMappings = model.GetAnnotationValue<Dictionary<string, AssociationSetAnnotations>>(entitySet, EdmConstants.InternalUri, CsdlConstants.AssociationSetAnnotationsAnnotation);
if (navigationPropertyMappings == null)
{
navigationPropertyMappings = new Dictionary<string, AssociationSetAnnotations>();
model.SetAnnotationValue(entitySet, EdmConstants.InternalUri, CsdlConstants.AssociationSetAnnotationsAnnotation, navigationPropertyMappings);
}
navigationPropertyMappings[property.Name] = new AssociationSetAnnotations { Annotations = annotations, End1Annotations = end1Annotations, End2Annotations = end2Annotations };
}
}
/// <summary>
/// Gets the annotations associated with the association serialized for a navigation target of an entity set.
/// </summary>
/// <param name="model">Model containing the entity set.</param>
/// <param name="entitySet">The entity set.</param>
/// <param name="property">The navigation property.</param>
/// <param name="annotations">The association set annotations.</param>
/// <param name="end1Annotations">The annotations for association set end 1.</param>
/// <param name="end2Annotations">The annotations for association set end 2.</param>
public static void GetAssociationSetAnnotations(this IEdmModel model, IEdmEntitySet entitySet, IEdmNavigationProperty property, out IEnumerable<IEdmDirectValueAnnotation> annotations, out IEnumerable<IEdmDirectValueAnnotation> end1Annotations, out IEnumerable<IEdmDirectValueAnnotation> end2Annotations)
{
EdmUtil.CheckArgumentNull(model, "model");
EdmUtil.CheckArgumentNull(entitySet, "entitySet");
EdmUtil.CheckArgumentNull(property, "property");
AssociationSetAnnotations associationSetAnnotations;
Dictionary<string, AssociationSetAnnotations> navigationPropertyMappings = model.GetAnnotationValue<Dictionary<string, AssociationSetAnnotations>>(entitySet, EdmConstants.InternalUri, CsdlConstants.AssociationSetAnnotationsAnnotation);
if (navigationPropertyMappings != null && navigationPropertyMappings.TryGetValue(property.Name, out associationSetAnnotations))
{
annotations = associationSetAnnotations.Annotations ?? Enumerable.Empty<IEdmDirectValueAnnotation>();
end1Annotations = associationSetAnnotations.End1Annotations ?? Enumerable.Empty<IEdmDirectValueAnnotation>();
end2Annotations = associationSetAnnotations.End2Annotations ?? Enumerable.Empty<IEdmDirectValueAnnotation>();
}
else
{
IEnumerable<IEdmDirectValueAnnotation> empty = Enumerable.Empty<IEdmDirectValueAnnotation>();
annotations = empty;
end1Annotations = empty;
end2Annotations = empty;
}
}
#endregion
#region NavigationProperty
/// <summary>
/// Gets the primary end of a pair of partnered navigation properties, selecting the principal end if there is one and making a stable, arbitrary choice otherwise.
/// </summary>
/// <param name="property">The navigation property.</param>
/// <returns>The primary end between the navigation property and its partner.</returns>
public static IEdmNavigationProperty GetPrimary(this IEdmNavigationProperty property)
{
if (property.IsPrincipal)
{
return property;
}
IEdmNavigationProperty partner = property.Partner;
if (partner.IsPrincipal)
{
return partner;
}
// There is no meaningful basis for determining which of the two partners is principal, so break the tie with an arbitrary, stable comparision.
int nameComparison = string.Compare(property.Name, partner.Name, StringComparison.Ordinal);
if (nameComparison == 0)
{
nameComparison = string.Compare(property.DeclaringEntityType().FullName(), partner.DeclaringEntityType().FullName(), StringComparison.Ordinal);
}
return nameComparison > 0 ? property : partner;
}
#endregion
#region IsValueExplicit
/// <summary>
/// Sets an annotation indicating whether the value of an enum member should be explicitly serialized.
/// </summary>
/// <param name="member">Member to set the annotation on.</param>
/// <param name="model">Model containing the member.</param>
/// <param name="isExplicit">If the value of the enum member should be explicitly serialized</param>
public static void SetIsValueExplicit(this IEdmEnumMember member, IEdmModel model, bool? isExplicit)
{
EdmUtil.CheckArgumentNull(member, "member");
EdmUtil.CheckArgumentNull(model, "model");
model.SetAnnotationValue(member, EdmConstants.InternalUri, CsdlConstants.IsEnumMemberValueExplicitAnnotation, (object)isExplicit);
}
/// <summary>
/// Gets an annotation indicating whether the value of an enum member should be explicitly serialized.
/// </summary>
/// <param name="member">The member the annotation is on.</param>
/// <param name="model">Model containing the member.</param>
/// <returns>Whether the member should have its value serialized.</returns>
public static bool? IsValueExplicit(this IEdmEnumMember member, IEdmModel model)
{
EdmUtil.CheckArgumentNull(member, "member");
EdmUtil.CheckArgumentNull(model, "model");
return model.GetAnnotationValue(member, EdmConstants.InternalUri, CsdlConstants.IsEnumMemberValueExplicitAnnotation) as bool?;
}
#endregion
#region IsSerializedAsElement
/// <summary>
/// Sets an annotation indicating if the value should be serialized as an element.
/// </summary>
/// <param name="value">Value to set the annotation on.</param>
/// <param name="model">Model containing the value.</param>
/// <param name="isSerializedAsElement">Value indicating if the value should be serialized as an element.</param>
public static void SetIsSerializedAsElement(this IEdmValue value, IEdmModel model, bool isSerializedAsElement)
{
EdmUtil.CheckArgumentNull(value, "value");
EdmUtil.CheckArgumentNull(model, "model");
if (isSerializedAsElement)
{
EdmError error;
if (!ValidationHelper.ValidateValueCanBeWrittenAsXmlElementAnnotation(value, null, null, out error))
{
throw new InvalidOperationException(error.ToString());
}
}
model.SetAnnotationValue(value, EdmConstants.InternalUri, CsdlConstants.IsSerializedAsElementAnnotation, (object)isSerializedAsElement);
}
/// <summary>
/// Gets an annotation indicating if the value should be serialized as an element.
/// </summary>
/// <param name="value">Value the annotation is on.</param>
/// <param name="model">Model containing the value.</param>
/// <returns>Value indicating if the string should be serialized as an element.</returns>
public static bool IsSerializedAsElement(this IEdmValue value, IEdmModel model)
{
EdmUtil.CheckArgumentNull(value, "value");
EdmUtil.CheckArgumentNull(model, "model");
return (model.GetAnnotationValue(value, EdmConstants.InternalUri, CsdlConstants.IsSerializedAsElementAnnotation) as bool?) ?? false;
}
#endregion
#region NamespaceAliases
/// <summary>
/// Sets the serialization alias for a given namespace
/// </summary>
/// <param name="model">Model that will be serialized.</param>
/// <param name="namespaceName">The namespace to set the alias for.</param>
/// <param name="alias">The alias for that namespace.</param>
public static void SetNamespaceAlias(this IEdmModel model, string namespaceName, string alias)
{
VersioningDictionary<string, string> mappings = model.GetAnnotationValue<VersioningDictionary<string, string>>(model, EdmConstants.InternalUri, CsdlConstants.NamespaceAliasAnnotation);
if (mappings == null)
{
mappings = VersioningDictionary<string, string>.Create(string.CompareOrdinal);
}
if (alias == null)
{
mappings = mappings.Remove(namespaceName);
}
else
{
mappings = mappings.Set(namespaceName, alias);
}
model.SetAnnotationValue(model, EdmConstants.InternalUri, CsdlConstants.NamespaceAliasAnnotation, mappings);
}
/// <summary>
/// Gets the serialization alias for a given namespace.
/// </summary>
/// <param name="model">Model that will be serialized.</param>
/// <param name="namespaceName">Namespace the alias is needed for.</param>
/// <returns>The alias of the given namespace, or null if one does not exist.</returns>
public static string GetNamespaceAlias(this IEdmModel model, string namespaceName)
{
VersioningDictionary<string, string> mappings = model.GetAnnotationValue<VersioningDictionary<string, string>>(model, EdmConstants.InternalUri, CsdlConstants.NamespaceAliasAnnotation);
return mappings.Get(namespaceName);
}
// This internal method exists so we can get a consistent view of the mappings through the entire serialization process.
// Otherwise, changes to the dictionary durring serialization would result in an invalid or inconsistent output.
internal static VersioningDictionary<string, string> GetNamespaceAliases(this IEdmModel model)
{
EdmUtil.CheckArgumentNull(model, "model");
return model.GetAnnotationValue<VersioningDictionary<string, string>>(model, EdmConstants.InternalUri, CsdlConstants.NamespaceAliasAnnotation);
}
#endregion
internal static bool IsInline(this IEdmVocabularyAnnotation annotation, IEdmModel model)
{
return annotation.GetSerializationLocation(model) == EdmVocabularyAnnotationSerializationLocation.Inline || annotation.TargetString() == null;
}
internal static string TargetString(this IEdmVocabularyAnnotation annotation)
{
return EdmUtil.FullyQualifiedName(annotation.Target);
}
private static void PopulateCaches(this IEdmNavigationProperty property)
{
// Force computation that can apply annotations to the navigation property.
IEdmNavigationProperty partner = property.Partner;
bool isPrincipal = property.IsPrincipal;
IEnumerable<IEdmStructuralProperty> dependentProperties = property.DependentProperties;
}
private static string GetQualifiedAndEscapedPropertyName(IEdmNavigationProperty property)
{
return
EscapeName(property.DeclaringEntityType().Namespace).Replace('.', AssociationNameEscapeChar) +
AssociationNameEscapeChar +
EscapeName(property.DeclaringEntityType().Name) +
AssociationNameEscapeChar +
EscapeName(property.Name);
}
private static string EscapeName(string name)
{
return name.Replace(AssociationNameEscapeString, AssociationNameEscapeStringEscaped);
}
private class AssociationAnnotations
{
public IEnumerable<IEdmDirectValueAnnotation> Annotations { get; set; }
public IEnumerable<IEdmDirectValueAnnotation> End1Annotations { get; set; }
public IEnumerable<IEdmDirectValueAnnotation> End2Annotations { get; set; }
public IEnumerable<IEdmDirectValueAnnotation> ConstraintAnnotations { get; set; }
}
private class AssociationSetAnnotations
{
public IEnumerable<IEdmDirectValueAnnotation> Annotations { get; set; }
public IEnumerable<IEdmDirectValueAnnotation> End1Annotations { get; set; }
public IEnumerable<IEdmDirectValueAnnotation> End2Annotations { get; set; }
}
}
}
| |
// Copyright (c) 2006-2007 Frank Laub
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
using OpenSSL.Core;
namespace OpenSSL.Crypto
{
#region Cipher
/// <summary>
/// Wraps the EVP_CIPHER object.
/// </summary>
public class Cipher : Base
{
private EVP_CIPHER raw;
internal Cipher(IntPtr ptr, bool owner) : base(ptr, owner)
{
this.raw = (EVP_CIPHER)Marshal.PtrToStructure(this.ptr, typeof(EVP_CIPHER));
}
/// <summary>
/// Prints the LongName of this cipher.
/// </summary>
/// <param name="bio"></param>
public override void Print(BIO bio)
{
bio.Write(this.LongName);
}
/// <summary>
/// Not implemented, these objects should never be disposed
/// </summary>
protected override void OnDispose() {
throw new NotImplementedException();
}
/// <summary>
/// Returns EVP_get_cipherbyname()
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static Cipher CreateByName(string name)
{
byte[] buf = Encoding.ASCII.GetBytes(name);
IntPtr ptr = Native.EVP_get_cipherbyname(buf);
if(ptr == IntPtr.Zero)
return null;
return new Cipher(ptr, false);
}
/// <summary>
/// Calls OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH)
/// </summary>
public static string[] AllNamesSorted
{
get { return new NameCollector(Native.OBJ_NAME_TYPE_CIPHER_METH, true).Result.ToArray(); }
}
/// <summary>
/// Calls OBJ_NAME_do_all(OBJ_NAME_TYPE_CIPHER_METH)
/// </summary>
public static string[] AllNames
{
get { return new NameCollector(Native.OBJ_NAME_TYPE_CIPHER_METH, false).Result.ToArray(); }
}
#region EVP_CIPHER
[StructLayout(LayoutKind.Sequential)]
struct EVP_CIPHER
{
public int nid;
public int block_size;
public int key_len;
public int iv_len;
public uint flags;
public IntPtr init;
public IntPtr do_cipher;
public IntPtr cleanup;
public int ctx_size;
public IntPtr set_asn1_parameters;
public IntPtr get_asn1_parameters;
public IntPtr ctrl;
public IntPtr app_data;
}
#endregion
#region Ciphers
/// <summary>
/// EVP_enc_null()
/// </summary>
public static Cipher Null = new Cipher(Native.EVP_enc_null(), false);
/// <summary>
/// EVP_des_ecb()
/// </summary>
public static Cipher DES_ECB = new Cipher(Native.EVP_des_ecb(), false);
/// <summary>
/// EVP_des_ede()
/// </summary>
public static Cipher DES_EDE = new Cipher(Native.EVP_des_ede(), false);
/// <summary>
/// EVP_des_ede3()
/// </summary>
public static Cipher DES_EDE3 = new Cipher(Native.EVP_des_ede3(), false);
/// <summary>
/// EVP_des_ede_ecb()
/// </summary>
public static Cipher DES_EDE_ECB = new Cipher(Native.EVP_des_ede_ecb(), false);
/// <summary>
/// EVP_des_ede3_ecb()
/// </summary>
public static Cipher DES_EDE3_ECB = new Cipher(Native.EVP_des_ede3_ecb(), false);
/// <summary>
/// EVP_des_cfb64()
/// </summary>
public static Cipher DES_CFB64 = new Cipher(Native.EVP_des_cfb64(), false);
/// <summary>
/// EVP_des_cfb1()
/// </summary>
public static Cipher DES_CFB1 = new Cipher(Native.EVP_des_cfb1(), false);
/// <summary>
/// EVP_des_cfb8()
/// </summary>
public static Cipher DES_CFB8 = new Cipher(Native.EVP_des_cfb8(), false);
/// <summary>
/// EVP_des_ede_cfb64()
/// </summary>
public static Cipher DES_EDE_CFB64 = new Cipher(Native.EVP_des_ede_cfb64(), false);
/// <summary>
/// EVP_des_ede3_cfb64()
/// </summary>
public static Cipher DES_EDE3_CFB64 = new Cipher(Native.EVP_des_ede3_cfb64(), false);
/// <summary>
/// EVP_des_ede3_cfb1()
/// </summary>
public static Cipher DES_EDE3_CFB1 = new Cipher(Native.EVP_des_ede3_cfb1(), false);
/// <summary>
/// EVP_des_ede3_cfb8()
/// </summary>
public static Cipher DES_EDE3_CFB8 = new Cipher(Native.EVP_des_ede3_cfb8(), false);
/// <summary>
/// EVP_des_ofb()
/// </summary>
public static Cipher DES_OFB = new Cipher(Native.EVP_des_ofb(), false);
/// <summary>
/// EVP_ded_ede_ofb()
/// </summary>
public static Cipher DES_EDE_OFB = new Cipher(Native.EVP_des_ede_ofb(), false);
/// <summary>
/// EVP_des_ede3_ofb()
/// </summary>
public static Cipher DES_EDE3_OFB = new Cipher(Native.EVP_des_ede3_ofb(), false);
/// <summary>
/// EVP_des_cbc()
/// </summary>
public static Cipher DES_CBC = new Cipher(Native.EVP_des_cbc(), false);
/// <summary>
/// EVP_des_ede_cbc()
/// </summary>
public static Cipher DES_EDE_CBC = new Cipher(Native.EVP_des_ede_cbc(), false);
/// <summary>
/// EVP_des_ede3_cbc()
/// </summary>
public static Cipher DES_EDE3_CBC = new Cipher(Native.EVP_des_ede3_cbc(), false);
/// <summary>
/// EVP_desx_cbc()
/// </summary>
public static Cipher DESX_CBC = new Cipher(Native.EVP_desx_cbc(), false);
/// <summary>
/// EVP_rc4()
/// </summary>
public static Cipher RC4 = new Cipher(Native.EVP_rc4(), false);
/// <summary>
/// EVP_rc4_40()
/// </summary>
public static Cipher RC4_40 = new Cipher(Native.EVP_rc4_40(), false);
/// <summary>
/// EVP_idea_ecb()
/// </summary>
public static Cipher Idea_ECB = new Cipher(Native.EVP_idea_ecb(), false);
/// <summary>
/// EVP_idea_cfb64()
/// </summary>
public static Cipher Idea_CFB64 = new Cipher(Native.EVP_idea_cfb64(), false);
/// <summary>
/// EVP_idea_ofb()
/// </summary>
public static Cipher Idea_OFB = new Cipher(Native.EVP_idea_ofb(), false);
/// <summary>
/// EVP_idea_cbc()
/// </summary>
public static Cipher Idea_CBC = new Cipher(Native.EVP_idea_cbc(), false);
/// <summary>
/// EVP_rc2_ecb()
/// </summary>
public static Cipher RC2_ECB = new Cipher(Native.EVP_rc2_ecb(), false);
/// <summary>
/// EVP_rc2_cbc()
/// </summary>
public static Cipher RC2_CBC = new Cipher(Native.EVP_rc2_cbc(), false);
/// <summary>
/// EVP_rc2_40_cbc()
/// </summary>
public static Cipher RC2_40_CBC = new Cipher(Native.EVP_rc2_40_cbc(), false);
/// <summary>
/// EVP_rc2_64_cbc()
/// </summary>
public static Cipher RC2_64_CBC = new Cipher(Native.EVP_rc2_64_cbc(), false);
/// <summary>
/// EVP_rc2_cfb64()
/// </summary>
public static Cipher RC2_CFB64 = new Cipher(Native.EVP_rc2_cfb64(), false);
/// <summary>
/// EVP_rc2_ofb()
/// </summary>
public static Cipher RC2_OFB = new Cipher(Native.EVP_rc2_ofb(), false);
/// <summary>
/// EVP_bf_ecb()
/// </summary>
public static Cipher Blowfish_ECB = new Cipher(Native.EVP_bf_ecb(), false);
/// <summary>
/// EVP_bf_cbc()
/// </summary>
public static Cipher Blowfish_CBC = new Cipher(Native.EVP_bf_cbc(), false);
/// <summary>
/// EVP_bf_cfb64()
/// </summary>
public static Cipher Blowfish_CFB64 = new Cipher(Native.EVP_bf_cfb64(), false);
/// <summary>
/// EVP_bf_ofb()
/// </summary>
public static Cipher Blowfish_OFB = new Cipher(Native.EVP_bf_ofb(), false);
/// <summary>
/// EVP_cast5_ecb()
/// </summary>
public static Cipher Cast5_ECB = new Cipher(Native.EVP_cast5_ecb(), false);
/// <summary>
/// EVP_cast5_cbc()
/// </summary>
public static Cipher Cast5_CBC = new Cipher(Native.EVP_cast5_cbc(), false);
/// <summary>
/// EVP_cast5_cfb64()
/// </summary>
public static Cipher Cast5_OFB64 = new Cipher(Native.EVP_cast5_cfb64(), false);
/// <summary>
/// EVP_cast5_ofb()
/// </summary>
public static Cipher Cast5_OFB = new Cipher(Native.EVP_cast5_ofb(), false);
#if OPENSSL_RC5_SUPPORT
public static Cipher RC5_32_12_16_CBC = new Cipher(Native.EVP_rc5_32_12_16_cbc(), false);
public static Cipher RC5_32_12_16_ECB = new Cipher(Native.EVP_rc5_32_12_16_ecb(), false);
public static Cipher RC5_32_12_16_CFB64 = new Cipher(Native.EVP_rc5_32_12_16_cfb64(), false);
public static Cipher RC5_32_12_16_OFB = new Cipher(Native.EVP_rc5_32_12_16_ofb(), false);
#endif
/// <summary>
/// EVP_aes_128_ecb()
/// </summary>
public static Cipher AES_128_ECB = new Cipher(Native.EVP_aes_128_ecb(), false);
/// <summary>
/// EVP_aes_128_cbc()
/// </summary>
public static Cipher AES_128_CBC = new Cipher(Native.EVP_aes_128_cbc(), false);
/// <summary>
/// EVP_aes_128_cfb1()
/// </summary>
public static Cipher AES_128_CFB1 = new Cipher(Native.EVP_aes_128_cfb1(), false);
/// <summary>
/// EVP_aes_128_cfb8()
/// </summary>
public static Cipher AES_128_CFB8 = new Cipher(Native.EVP_aes_128_cfb8(), false);
/// <summary>
/// EVP_aes_128_cfb128()
/// </summary>
public static Cipher AES_128_CFB128 = new Cipher(Native.EVP_aes_128_cfb128(), false);
/// <summary>
/// EVP_aes_128_ofb()
/// </summary>
public static Cipher AES_128_OFB = new Cipher(Native.EVP_aes_128_ofb(), false);
/// <summary>
/// EVP_aes_192_ecb()
/// </summary>
public static Cipher AES_192_ECB = new Cipher(Native.EVP_aes_192_ecb(), false);
/// <summary>
/// EVP_aes_192_cbc()
/// </summary>
public static Cipher AES_192_CBC = new Cipher(Native.EVP_aes_192_cbc(), false);
/// <summary>
/// EVP_aes_192_cfb1()
/// </summary>
public static Cipher AES_192_CFB1 = new Cipher(Native.EVP_aes_192_cfb1(), false);
/// <summary>
/// EVP_aes_192_cfb8()
/// </summary>
public static Cipher AES_192_CFB8 = new Cipher(Native.EVP_aes_192_cfb8(), false);
/// <summary>
/// EVP_aes_192_cfb128()
/// </summary>
public static Cipher AES_192_CFB128 = new Cipher(Native.EVP_aes_192_cfb128(), false);
/// <summary>
/// EVP_aes_192_ofb()
/// </summary>
public static Cipher AES_192_OFB = new Cipher(Native.EVP_aes_192_ofb(), false);
/// <summary>
/// EVP_aes_256_ecb()
/// </summary>
public static Cipher AES_256_ECB = new Cipher(Native.EVP_aes_256_ecb(), false);
/// <summary>
/// EVP_aes_256_cbc()
/// </summary>
public static Cipher AES_256_CBC = new Cipher(Native.EVP_aes_256_cbc(), false);
/// <summary>
/// EVP_aes_256_cfb1()
/// </summary>
public static Cipher AES_256_CFB1 = new Cipher(Native.EVP_aes_256_cfb1(), false);
/// <summary>
/// EVP_aes_256_cfb8()
/// </summary>
public static Cipher AES_256_CFB8 = new Cipher(Native.EVP_aes_256_cfb8(), false);
/// <summary>
/// EVP_aes_256_cfb128()
/// </summary>
public static Cipher AES_256_CFB128 = new Cipher(Native.EVP_aes_256_cfb128(), false);
/// <summary>
/// EVP_aes_256_ofb()
/// </summary>
public static Cipher AES_256_OFB = new Cipher(Native.EVP_aes_256_ofb(), false);
#endregion
#region Properties
/// <summary>
/// Returns the key_len field
/// </summary>
public int KeyLength
{
get { return this.raw.key_len; }
}
/// <summary>
/// Returns the iv_len field
/// </summary>
public int IVLength
{
get { return this.raw.iv_len; }
}
/// <summary>
/// Returns the block_size field
/// </summary>
public int BlockSize
{
get { return this.raw.block_size; }
}
/// <summary>
/// Returns the flags field
/// </summary>
public uint Flags
{
get { return this.raw.flags; }
}
/// <summary>
/// Returns the long name for the nid field using OBJ_nid2ln()
/// </summary>
public string LongName
{
get { return Native.OBJ_nid2ln(this.raw.nid); }
}
/// <summary>
/// Returns the name for the nid field using OBJ_nid2sn()
/// </summary>
public string Name
{
get { return Native.OBJ_nid2sn(this.raw.nid); }
}
/// <summary>
/// Returns EVP_CIPHER_type()
/// </summary>
public int Type
{
get { return Native.EVP_CIPHER_type(this.ptr); }
}
/// <summary>
/// Returns the long name for the type using OBJ_nid2ln()
/// </summary>
public string TypeName
{
get { return Native.OBJ_nid2ln(this.Type); }
}
#endregion
}
#endregion
/// <summary>
/// Simple struct to encapsulate common parameters for crypto functions
/// </summary>
public struct Envelope
{
/// <summary>
/// The key for a crypto operation
/// </summary>
public ArraySegment<byte>[] Keys;
/// <summary>
/// The IV (Initialization Vector)
/// </summary>
public byte[] IV;
/// <summary>
/// The payload (contains plaintext or ciphertext)
/// </summary>
public byte[] Data;
}
/// <summary>
/// Wraps the EVP_CIPHER_CTX object.
/// </summary>
public class CipherContext : Base, IDisposable
{
#region EVP_CIPHER_CTX
[StructLayout(LayoutKind.Sequential)]
public struct EVP_CIPHER_CTX
{
public IntPtr cipher;
public IntPtr engine; /* functional reference if 'cipher' is ENGINE-provided */
public int encrypt; /* encrypt or decrypt */
public int buf_len; /* number we have left */
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Native.EVP_MAX_IV_LENGTH)]
public byte[] oiv; /* original iv */
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Native.EVP_MAX_IV_LENGTH)]
public byte[] iv; /* working iv */
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Native.EVP_MAX_BLOCK_LENGTH)]
public byte[] buf;/* saved partial block */
public int num; /* used by cfb/ofb mode */
public IntPtr app_data; /* application stuff */
public int key_len; /* May change for variable length cipher */
public uint flags; /* Various flags */
public IntPtr cipher_data; /* per EVP data */
public int final_used;
public int block_mask;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Native.EVP_MAX_BLOCK_LENGTH)]
public byte[] final;/* possible final block */
}
#endregion
private Cipher cipher;
/// <summary>
/// Calls OPENSSL_malloc() and initializes the buffer using EVP_CIPHER_CTX_init()
/// </summary>
/// <param name="cipher"></param>
public CipherContext(Cipher cipher)
: base(Native.OPENSSL_malloc(Marshal.SizeOf(typeof(EVP_CIPHER_CTX))), true)
{
Native.EVP_CIPHER_CTX_init(this.ptr);
this.cipher = cipher;
}
/// <summary>
/// Returns the cipher's LongName
/// </summary>
/// <param name="bio"></param>
public override void Print(BIO bio)
{
bio.Write("CipherContext: " + this.cipher.LongName);
}
#region Methods
/// <summary>
/// Calls EVP_OpenInit() and EVP_OpenFinal()
/// </summary>
/// <param name="input"></param>
/// <param name="iv"></param>
/// <param name="pkey"></param>
/// <returns></returns>
public byte[] Open(byte[] input, byte[] iv, CryptoKey pkey)
{
Native.ExpectSuccess(Native.EVP_OpenInit(
this.ptr, this.cipher.Handle, input, input.Length, iv, pkey.Handle));
int len;
Native.ExpectSuccess(Native.EVP_OpenFinal(this.ptr, null, out len));
byte[] output = new byte[len];
Native.ExpectSuccess(Native.EVP_OpenFinal(this.ptr, output, out len));
return output;
}
/// <summary>
/// Calls EVP_SealInit() and EVP_SealFinal()
/// </summary>
/// <param name="pkeys"></param>
/// <param name="needsIV"></param>
/// <returns></returns>
public Envelope Seal(CryptoKey[] pkeys, bool needsIV)
{
Envelope ret = new Envelope();
byte[][] bufs = new byte[pkeys.Length][];
int[] lens = new int[pkeys.Length];
IntPtr[] pubkeys = new IntPtr[pkeys.Length];
ret.Keys = new ArraySegment<byte>[pkeys.Length];
for (int i = 0; i < pkeys.Length; ++i)
{
bufs[i] = new byte[pkeys[i].Size];
lens[i] = pkeys[i].Size;
pubkeys[i] = pkeys[i].Handle;
}
if(needsIV)
ret.IV = new byte[this.cipher.IVLength];
int len;
Native.ExpectSuccess(Native.EVP_SealInit(
this.ptr, this.cipher.Handle, bufs, lens, ret.IV, pubkeys, pubkeys.Length));
for (int i = 0; i < pkeys.Length; ++i)
{
ret.Keys[i] = new ArraySegment<byte>(bufs[i], 0, lens[i]);
}
Native.ExpectSuccess(Native.EVP_SealFinal(this.ptr, null, out len));
ret.Data = new byte[len];
Native.ExpectSuccess(Native.EVP_SealFinal(this.ptr, ret.Data, out len));
return ret;
}
/// <summary>
/// Encrypts or decrypts the specified payload.
/// </summary>
/// <param name="input"></param>
/// <param name="key"></param>
/// <param name="iv"></param>
/// <param name="doEncrypt"></param>
/// <returns></returns>
public byte[] Crypt(byte[] input, byte[] key, byte[] iv, bool doEncrypt)
{
return this.Crypt(input, key, iv, doEncrypt, -1);
}
private byte[] SetupKey(byte[] key)
{
byte[] real_key;
bool isStreamCipher = (this.cipher.Flags & Native.EVP_CIPH_MODE) == Native.EVP_CIPH_STREAM_CIPHER;
if (isStreamCipher)
{
real_key = new byte[this.Cipher.KeyLength];
if (key == null)
real_key.Initialize();
else
Buffer.BlockCopy(key, 0, real_key, 0, Math.Min(key.Length, real_key.Length));
}
else
{
if (key == null)
{
real_key = new byte[this.Cipher.KeyLength];
real_key.Initialize();
}
else
{
if (this.Cipher.KeyLength != key.Length)
{
real_key = new byte[this.Cipher.KeyLength];
real_key.Initialize();
Buffer.BlockCopy(key, 0, real_key, 0, Math.Min(key.Length, real_key.Length));
}
else
{
real_key = key;
}
}
// FIXME: what was this for??
// total += this.cipher.BlockSize;
}
return real_key;
}
private byte[] SetupIV(byte[] iv)
{
if (this.cipher.IVLength > iv.Length)
{
byte[] ret = new byte[this.cipher.IVLength];
ret.Initialize();
Buffer.BlockCopy(iv, 0, ret, 0, iv.Length);
return ret;
}
return iv;
}
/// <summary>
/// Calls EVP_CipherInit_ex(), EVP_CipherUpdate(), and EVP_CipherFinal_ex()
/// </summary>
/// <param name="input"></param>
/// <param name="key"></param>
/// <param name="iv"></param>
/// <param name="doEncrypt"></param>
/// <param name="padding"></param>
/// <returns></returns>
public byte[] Crypt(byte[] input, byte[] key, byte[] iv, bool doEncrypt, int padding)
{
int enc = doEncrypt ? 1 : 0;
int total = Math.Max(input.Length, this.cipher.BlockSize);
byte[] real_key = SetupKey(key);
byte[] real_iv = SetupIV(iv);
byte[] buf = new byte[total];
MemoryStream memory = new MemoryStream(total);
Native.ExpectSuccess(Native.EVP_CipherInit_ex(
this.ptr, this.cipher.Handle, IntPtr.Zero, null, null, enc));
Native.ExpectSuccess(Native.EVP_CIPHER_CTX_set_key_length(this.ptr, real_key.Length));
if (padding >= 0)
Native.ExpectSuccess(Native.EVP_CIPHER_CTX_set_padding(this.ptr, padding));
bool isStreamCipher = (this.cipher.Flags & Native.EVP_CIPH_MODE) == Native.EVP_CIPH_STREAM_CIPHER;
if (isStreamCipher)
{
for (int i = 0; i < Math.Min(real_key.Length, iv.Length); i++)
{
real_key[i] ^= iv[i];
}
Native.ExpectSuccess(Native.EVP_CipherInit_ex(
this.ptr, this.cipher.Handle, IntPtr.Zero, real_key, null, enc));
}
else
{
Native.ExpectSuccess(Native.EVP_CipherInit_ex(
this.ptr, this.cipher.Handle, IntPtr.Zero, real_key, real_iv, enc));
}
int len = buf.Length;
Native.ExpectSuccess(Native.EVP_CipherUpdate(
this.ptr, buf, out len, input, input.Length));
memory.Write(buf, 0, len);
len = buf.Length;
Native.EVP_CipherFinal_ex(this.ptr, buf, ref len);
memory.Write(buf, 0, len);
return memory.ToArray();
}
/// <summary>
/// Encrypts the specified plaintext
/// </summary>
/// <param name="input"></param>
/// <param name="key"></param>
/// <param name="iv"></param>
/// <returns></returns>
public byte[] Encrypt(byte[] input, byte[] key, byte[] iv)
{
return this.Crypt(input, key, iv, true);
}
/// <summary>
/// Decrypts the specified ciphertext
/// </summary>
/// <param name="input"></param>
/// <param name="key"></param>
/// <param name="iv"></param>
/// <returns></returns>
public byte[] Decrypt(byte[] input, byte[] key, byte[] iv)
{
return this.Crypt(input, key, iv, false);
}
/// <summary>
/// Encrypts the specified plaintext
/// </summary>
/// <param name="input"></param>
/// <param name="key"></param>
/// <param name="iv"></param>
/// <param name="padding"></param>
/// <returns></returns>
public byte[] Encrypt(byte[] input, byte[] key, byte[] iv, int padding)
{
return this.Crypt(input, key, iv, true, padding);
}
/// <summary>
/// Decrypts the specified ciphertext
/// </summary>
/// <param name="input"></param>
/// <param name="key"></param>
/// <param name="iv"></param>
/// <param name="padding"></param>
/// <returns></returns>
public byte[] Decrypt(byte[] input, byte[] key, byte[] iv, int padding)
{
return this.Crypt(input, key, iv, false, padding);
}
/// <summary>
/// Calls EVP_BytesToKey
/// </summary>
/// <param name="md"></param>
/// <param name="salt"></param>
/// <param name="data"></param>
/// <param name="count"></param>
/// <param name="iv"></param>
/// <returns></returns>
public byte[] BytesToKey(MessageDigest md, byte[] salt, byte[] data, int count, out byte[] iv)
{
byte[] key = new byte[this.cipher.KeyLength];
iv = new byte[this.cipher.IVLength];
Native.ExpectSuccess(Native.EVP_BytesToKey(
this.cipher.Handle,
md.Handle,
salt,
data,
data.Length,
count,
key,
iv));
return key;
}
#endregion
#region Properties
/// <summary>
/// Returns the EVP_CIPHER for this context.
/// </summary>
public Cipher Cipher
{
get { return this.cipher; }
}
private EVP_CIPHER_CTX Raw
{
get { return (EVP_CIPHER_CTX)Marshal.PtrToStructure(this.ptr, typeof(EVP_CIPHER_CTX)); }
set { Marshal.StructureToPtr(value, this.ptr, false); }
}
#endregion
#region IDisposable Members
/// <summary>
/// Calls EVP_CIPHER_CTX_clean() and then OPENSSL_free()
/// </summary>
protected override void OnDispose() {
Native.EVP_CIPHER_CTX_cleanup(this.ptr);
Native.OPENSSL_free(this.ptr);
}
#endregion
}
}
| |
using System;
using System.Data;
using System.Data.OleDb;
using System.Text.RegularExpressions;
using BLToolkit.Mapping;
namespace BLToolkit.Data.DataProvider
{
#if FW3
using Sql.SqlProvider;
#endif
public sealed class AccessDataProvider : OleDbDataProvider
{
private static Regex _paramsExp;
// Based on idea from http://qapi.blogspot.com/2006/12/deriveparameters-oledbprovider-ii.html
//
public override bool DeriveParameters(IDbCommand command)
{
if (command == null)
throw new ArgumentNullException("command");
if (command.CommandType != CommandType.StoredProcedure)
throw new InvalidOperationException("command.CommandType must be CommandType.StoredProcedure");
OleDbConnection conn = command.Connection as OleDbConnection;
if (conn == null || conn.State != ConnectionState.Open)
throw new InvalidOperationException("Invalid connection state.");
command.Parameters.Clear();
DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Procedures, new object[]{null, null, command.CommandText});
if (dt.Rows.Count == 0)
{
// Jet does convert parameretless procedures to views.
//
dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Views, new object[]{null, null, command.CommandText});
if (dt.Rows.Count == 0)
throw new DataException(string.Format("Stored procedure '{0}' not found", command.CommandText));
// Do nothing. There is no parameters.
//
}
else
{
DataColumn col = dt.Columns["PROCEDURE_DEFINITION"];
if (col == null)
{
// Not really possible
//
return false;
}
if (_paramsExp == null)
_paramsExp = new Regex(@"PARAMETERS ((\[(?<name>[^\]]+)\]|(?<name>[^\s]+))\s(?<type>[^,;\s]+(\s\([^\)]+\))?)[,;]\s)*", RegexOptions.Compiled | RegexOptions.ExplicitCapture);
Match match = _paramsExp.Match((string)dt.Rows[0][col.Ordinal]);
CaptureCollection names = match.Groups["name"].Captures;
CaptureCollection types = match.Groups["type"].Captures;
if (names.Count != types.Count)
{
// Not really possible
//
return false;
}
char[] separators = new char[]{' ', '(', ',', ')'};
for (int i = 0; i < names.Count; ++i)
{
string paramName = names[i].Value;
string[] rawType = types[i].Value.Split(separators, StringSplitOptions.RemoveEmptyEntries);
OleDbParameter p = new OleDbParameter(paramName, GetOleDbType(rawType[0]));
if (rawType.Length > 2)
{
p.Precision = Common.Convert.ToByte(rawType[1]);
p.Scale = Common.Convert.ToByte(rawType[2]);
}
else if (rawType.Length > 1)
{
p.Size = Common.Convert.ToInt32(rawType[1]);
}
command.Parameters.Add(p);
}
}
return true;
}
private static OleDbType GetOleDbType(string jetType)
{
switch (jetType.ToLower())
{
case "byte":
case "tinyint":
case "integer1":
return OleDbType.TinyInt;
case "short":
case "smallint":
case "integer2":
return OleDbType.SmallInt;
case "int":
case "integer":
case "long":
case "integer4":
case "counter":
case "identity":
case "autoincrement":
return OleDbType.Integer;
case "single":
case "real":
case "float4":
case "ieeesingle":
return OleDbType.Single;
case "double":
case "number":
case "double precision":
case "float":
case "float8":
case "ieeedouble":
return OleDbType.Double;
case "currency":
case "money":
return OleDbType.Currency;
case "dec":
case "decimal":
case "numeric":
return OleDbType.Decimal;
case "bit":
case "yesno":
case "logical":
case "logical1":
return OleDbType.Boolean;
case "datetime":
case "date":
case "time":
return OleDbType.Date;
case "alphanumeric":
case "char":
case "character":
case "character varying":
case "national char":
case "national char varying":
case "national character":
case "national character varying":
case "nchar":
case "string":
case "text":
case "varchar":
return OleDbType.VarWChar;
case "longchar":
case "longtext":
case "memo":
case "note":
case "ntext":
return OleDbType.LongVarWChar;
case "binary":
case "varbinary":
case "binary varying":
case "bit varying":
return OleDbType.VarBinary;
case "longbinary":
case "image":
case "general":
case "oleobject":
return OleDbType.LongVarBinary;
case "guid":
case "uniqueidentifier":
return OleDbType.Guid;
default:
// Each release of Jet brings many new aliases to existing types.
// This list may be outdated, please send a report to us.
//
throw new NotSupportedException("Unknown DB type '" + jetType + "'");
}
}
public override void AttachParameter(IDbCommand command, IDbDataParameter parameter)
{
// Do some magic to workaround 'Data type mismatch in criteria expression' error
// in JET for some european locales.
//
if (parameter.Value is DateTime)
{
// OleDbType.DBTimeStamp is locale aware, OleDbType.Date is locale neutral.
//
((OleDbParameter)parameter).OleDbType = OleDbType.Date;
}
else if (parameter.Value is decimal)
{
// OleDbType.Decimal is locale aware, OleDbType.Currency is locale neutral.
//
((OleDbParameter)parameter).OleDbType = OleDbType.Currency;
}
base.AttachParameter(command, parameter);
}
public new const string NameString = DataProvider.ProviderName.Access;
public override string Name
{
get { return NameString; }
}
public override int MaxBatchSize
{
get { return 0; }
}
#if FW3
public override ISqlProvider CreateSqlProvider()
{
return new AccessSqlProvider(this);
}
#endif
#region DataReaderEx
public override IDataReader GetDataReader(MappingSchema schema, IDataReader dataReader)
{
return dataReader is OleDbDataReader?
new DataReaderEx((OleDbDataReader)dataReader):
base.GetDataReader(schema, dataReader);
}
class DataReaderEx : DataReaderBase<OleDbDataReader>, IDataReader
{
public DataReaderEx(OleDbDataReader rd): base(rd)
{
}
public new object GetValue(int i)
{
object value = DataReader.GetValue(i);
if (value is DateTime)
{
DateTime dt = (DateTime)value;
if (dt.Year == 1899 && dt.Month == 12 && dt.Day == 30)
return new DateTime(1, 1, 1, dt.Hour, dt.Minute, dt.Second, dt.Millisecond);
}
return value;
}
public new DateTime GetDateTime(int i)
{
DateTime dt = DataReader.GetDateTime(i);
if (dt.Year == 1899 && dt.Month == 12 && dt.Day == 30)
return new DateTime(1, 1, 1, dt.Hour, dt.Minute, dt.Second, dt.Millisecond);
return dt;
}
}
#endregion
}
}
| |
/*
'===============================================================================
' Generated From - CSharp_dOOdads_BusinessEntity.vbgen
'
' ** IMPORTANT **
' How to Generate your stored procedures:
'
' SQL = SQL_StoredProcs.vbgen
' ACCESS = Access_StoredProcs.vbgen
' ORACLE = Oracle_StoredProcs.vbgen
' FIREBIRD = FirebirdStoredProcs.vbgen
' POSTGRESQL = PostgreSQL_StoredProcs.vbgen
'
' The supporting base class SqlClientEntity is in the Architecture directory in "dOOdads".
'
' This object is 'abstract' which means you need to inherit from it to be able
' to instantiate it. This is very easilly done. You can override properties and
' methods in your derived class, this allows you to regenerate this class at any
' time and not worry about overwriting custom code.
'
' NEVER EDIT THIS FILE.
'
' public class YourObject : _YourObject
' {
'
' }
'
'===============================================================================
*/
// Generated by MyGeneration Version # (1.3.0.3)
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Collections.Specialized;
using MyGeneration.dOOdads;
namespace nTier.Entity
{
public abstract class _Territories : SqlClientEntity
{
public _Territories()
{
this.QuerySource = "Territories";
this.MappingName = "Territories";
}
//=================================================================
// public Overrides void AddNew()
//=================================================================
//
//=================================================================
public override void AddNew()
{
base.AddNew();
}
public override void FlushData()
{
this._whereClause = null;
this._aggregateClause = null;
base.FlushData();
}
//=================================================================
// public Function LoadAll() As Boolean
//=================================================================
// Loads all of the records in the database, and sets the currentRow to the first row
//=================================================================
public bool LoadAll()
{
ListDictionary parameters = null;
return base.LoadFromSql("[" + this.SchemaStoredProcedure + "proc_TerritoriesLoadAll]", parameters);
}
//=================================================================
// public Overridable Function LoadByPrimaryKey() As Boolean
//=================================================================
// Loads a single row of via the primary key
//=================================================================
public virtual bool LoadByPrimaryKey(string TerritoryID)
{
ListDictionary parameters = new ListDictionary();
parameters.Add(Parameters.TerritoryID, TerritoryID);
return base.LoadFromSql("[" + this.SchemaStoredProcedure + "proc_TerritoriesLoadByPrimaryKey]", parameters);
}
#region Parameters
protected class Parameters
{
public static SqlParameter TerritoryID
{
get
{
return new SqlParameter("@TerritoryID", SqlDbType.NVarChar, 20);
}
}
public static SqlParameter TerritoryDescription
{
get
{
return new SqlParameter("@TerritoryDescription", SqlDbType.NChar, 50);
}
}
public static SqlParameter RegionID
{
get
{
return new SqlParameter("@RegionID", SqlDbType.Int, 0);
}
}
}
#endregion
#region ColumnNames
public class ColumnNames
{
public const string TerritoryID = "TerritoryID";
public const string TerritoryDescription = "TerritoryDescription";
public const string RegionID = "RegionID";
static public string ToPropertyName(string columnName)
{
if(ht == null)
{
ht = new Hashtable();
ht[TerritoryID] = _Territories.PropertyNames.TerritoryID;
ht[TerritoryDescription] = _Territories.PropertyNames.TerritoryDescription;
ht[RegionID] = _Territories.PropertyNames.RegionID;
}
return (string)ht[columnName];
}
static private Hashtable ht = null;
}
#endregion
#region PropertyNames
public class PropertyNames
{
public const string TerritoryID = "TerritoryID";
public const string TerritoryDescription = "TerritoryDescription";
public const string RegionID = "RegionID";
static public string ToColumnName(string propertyName)
{
if(ht == null)
{
ht = new Hashtable();
ht[TerritoryID] = _Territories.ColumnNames.TerritoryID;
ht[TerritoryDescription] = _Territories.ColumnNames.TerritoryDescription;
ht[RegionID] = _Territories.ColumnNames.RegionID;
}
return (string)ht[propertyName];
}
static private Hashtable ht = null;
}
#endregion
#region StringPropertyNames
public class StringPropertyNames
{
public const string TerritoryID = "s_TerritoryID";
public const string TerritoryDescription = "s_TerritoryDescription";
public const string RegionID = "s_RegionID";
}
#endregion
#region Properties
public virtual string TerritoryID
{
get
{
return base.Getstring(ColumnNames.TerritoryID);
}
set
{
base.Setstring(ColumnNames.TerritoryID, value);
}
}
public virtual string TerritoryDescription
{
get
{
return base.Getstring(ColumnNames.TerritoryDescription);
}
set
{
base.Setstring(ColumnNames.TerritoryDescription, value);
}
}
public virtual int? RegionID
{
get
{
return base.Getint(ColumnNames.RegionID);
}
set
{
base.Setint(ColumnNames.RegionID, value);
}
}
#endregion
#region String Properties
public virtual string s_TerritoryID
{
get
{
return this.IsColumnNull(ColumnNames.TerritoryID) ? string.Empty : base.GetstringAsString(ColumnNames.TerritoryID);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.TerritoryID);
else
this.TerritoryID = base.SetstringAsString(ColumnNames.TerritoryID, value);
}
}
public virtual string s_TerritoryDescription
{
get
{
return this.IsColumnNull(ColumnNames.TerritoryDescription) ? string.Empty : base.GetstringAsString(ColumnNames.TerritoryDescription);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.TerritoryDescription);
else
this.TerritoryDescription = base.SetstringAsString(ColumnNames.TerritoryDescription, value);
}
}
public virtual string s_RegionID
{
get
{
return this.IsColumnNull(ColumnNames.RegionID) ? string.Empty : base.GetintAsString(ColumnNames.RegionID);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.RegionID);
else
this.RegionID = base.SetintAsString(ColumnNames.RegionID, value);
}
}
#endregion
#region Where Clause
public class WhereClause
{
public WhereClause(BusinessEntity entity)
{
this._entity = entity;
}
public TearOffWhereParameter TearOff
{
get
{
if(_tearOff == null)
{
_tearOff = new TearOffWhereParameter(this);
}
return _tearOff;
}
}
#region WhereParameter TearOff's
public class TearOffWhereParameter
{
public TearOffWhereParameter(WhereClause clause)
{
this._clause = clause;
}
public WhereParameter TerritoryID
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.TerritoryID, Parameters.TerritoryID);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter TerritoryDescription
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.TerritoryDescription, Parameters.TerritoryDescription);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter RegionID
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.RegionID, Parameters.RegionID);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
private WhereClause _clause;
}
#endregion
public WhereParameter TerritoryID
{
get
{
if(_TerritoryID_W == null)
{
_TerritoryID_W = TearOff.TerritoryID;
}
return _TerritoryID_W;
}
}
public WhereParameter TerritoryDescription
{
get
{
if(_TerritoryDescription_W == null)
{
_TerritoryDescription_W = TearOff.TerritoryDescription;
}
return _TerritoryDescription_W;
}
}
public WhereParameter RegionID
{
get
{
if(_RegionID_W == null)
{
_RegionID_W = TearOff.RegionID;
}
return _RegionID_W;
}
}
private WhereParameter _TerritoryID_W = null;
private WhereParameter _TerritoryDescription_W = null;
private WhereParameter _RegionID_W = null;
public void WhereClauseReset()
{
_TerritoryID_W = null;
_TerritoryDescription_W = null;
_RegionID_W = null;
this._entity.Query.FlushWhereParameters();
}
private BusinessEntity _entity;
private TearOffWhereParameter _tearOff;
}
public WhereClause Where
{
get
{
if(_whereClause == null)
{
_whereClause = new WhereClause(this);
}
return _whereClause;
}
}
private WhereClause _whereClause = null;
#endregion
#region Aggregate Clause
public class AggregateClause
{
public AggregateClause(BusinessEntity entity)
{
this._entity = entity;
}
public TearOffAggregateParameter TearOff
{
get
{
if(_tearOff == null)
{
_tearOff = new TearOffAggregateParameter(this);
}
return _tearOff;
}
}
#region AggregateParameter TearOff's
public class TearOffAggregateParameter
{
public TearOffAggregateParameter(AggregateClause clause)
{
this._clause = clause;
}
public AggregateParameter TerritoryID
{
get
{
AggregateParameter aggregate = new AggregateParameter(ColumnNames.TerritoryID, Parameters.TerritoryID);
this._clause._entity.Query.AddAggregateParameter(aggregate);
return aggregate;
}
}
public AggregateParameter TerritoryDescription
{
get
{
AggregateParameter aggregate = new AggregateParameter(ColumnNames.TerritoryDescription, Parameters.TerritoryDescription);
this._clause._entity.Query.AddAggregateParameter(aggregate);
return aggregate;
}
}
public AggregateParameter RegionID
{
get
{
AggregateParameter aggregate = new AggregateParameter(ColumnNames.RegionID, Parameters.RegionID);
this._clause._entity.Query.AddAggregateParameter(aggregate);
return aggregate;
}
}
private AggregateClause _clause;
}
#endregion
public AggregateParameter TerritoryID
{
get
{
if(_TerritoryID_W == null)
{
_TerritoryID_W = TearOff.TerritoryID;
}
return _TerritoryID_W;
}
}
public AggregateParameter TerritoryDescription
{
get
{
if(_TerritoryDescription_W == null)
{
_TerritoryDescription_W = TearOff.TerritoryDescription;
}
return _TerritoryDescription_W;
}
}
public AggregateParameter RegionID
{
get
{
if(_RegionID_W == null)
{
_RegionID_W = TearOff.RegionID;
}
return _RegionID_W;
}
}
private AggregateParameter _TerritoryID_W = null;
private AggregateParameter _TerritoryDescription_W = null;
private AggregateParameter _RegionID_W = null;
public void AggregateClauseReset()
{
_TerritoryID_W = null;
_TerritoryDescription_W = null;
_RegionID_W = null;
this._entity.Query.FlushAggregateParameters();
}
private BusinessEntity _entity;
private TearOffAggregateParameter _tearOff;
}
public AggregateClause Aggregate
{
get
{
if(_aggregateClause == null)
{
_aggregateClause = new AggregateClause(this);
}
return _aggregateClause;
}
}
private AggregateClause _aggregateClause = null;
#endregion
protected override IDbCommand GetInsertCommand()
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "[" + this.SchemaStoredProcedure + "proc_TerritoriesInsert]";
CreateParameters(cmd);
return cmd;
}
protected override IDbCommand GetUpdateCommand()
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "[" + this.SchemaStoredProcedure + "proc_TerritoriesUpdate]";
CreateParameters(cmd);
return cmd;
}
protected override IDbCommand GetDeleteCommand()
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "[" + this.SchemaStoredProcedure + "proc_TerritoriesDelete]";
SqlParameter p;
p = cmd.Parameters.Add(Parameters.TerritoryID);
p.SourceColumn = ColumnNames.TerritoryID;
p.SourceVersion = DataRowVersion.Current;
return cmd;
}
private IDbCommand CreateParameters(SqlCommand cmd)
{
SqlParameter p;
p = cmd.Parameters.Add(Parameters.TerritoryID);
p.SourceColumn = ColumnNames.TerritoryID;
p.SourceVersion = DataRowVersion.Current;
p = cmd.Parameters.Add(Parameters.TerritoryDescription);
p.SourceColumn = ColumnNames.TerritoryDescription;
p.SourceVersion = DataRowVersion.Current;
p = cmd.Parameters.Add(Parameters.RegionID);
p.SourceColumn = ColumnNames.RegionID;
p.SourceVersion = DataRowVersion.Current;
return cmd;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Relisten.Api.Models;
using Dapper;
using Relisten.Vendor;
using Relisten.Data;
using System.Text.RegularExpressions;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
using System.Globalization;
using Relisten.Vendor.Phishin;
using Hangfire.Server;
using Hangfire.Console;
using System.Transactions;
using System.Net.Http.Headers;
using Microsoft.Extensions.Configuration;
namespace Relisten.Import
{
public class PhishinImporter : ImporterBase
{
public const string DataSourceName = "phish.in";
protected SourceService _sourceService { get; set; }
protected SourceSetService _sourceSetService { get; set; }
protected SourceReviewService _sourceReviewService { get; set; }
protected SourceTrackService _sourceTrackService { get; set; }
protected VenueService _venueService { get; set; }
protected TourService _tourService { get; set; }
protected EraService _eraService { get; set; }
protected SetlistSongService _setlistSongService { get; set; }
protected SetlistShowService _setlistShowService { get; set; }
protected ILogger<PhishinImporter> _log { get; set; }
public IConfiguration _configuration { get; }
readonly LinkService linkService;
public PhishinImporter(
DbService db,
VenueService venueService,
TourService tourService,
SourceService sourceService,
SourceSetService sourceSetService,
SourceReviewService sourceReviewService,
SourceTrackService sourceTrackService,
SetlistSongService setlistSongService,
LinkService linkService,
SetlistShowService setlistShowService,
EraService eraService,
ILogger<PhishinImporter> log,
IConfiguration configuration
) : base(db)
{
this.linkService = linkService;
this._setlistSongService = setlistSongService;
this._setlistShowService = setlistShowService;
this._sourceService = sourceService;
this._venueService = venueService;
this._tourService = tourService;
this._log = log;
_configuration = configuration;
_sourceReviewService = sourceReviewService;
_sourceTrackService = sourceTrackService;
_sourceSetService = sourceSetService;
_eraService = eraService;
_configuration = configuration;
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", configuration["PHISHIN_KEY"]);
}
public override string ImporterName => "phish.in";
public override ImportableData ImportableDataForArtist(Artist artist)
{
return ImportableData.Sources
| ImportableData.Venues
| ImportableData.Tours
| ImportableData.Eras
| ImportableData.SetlistShowsAndSongs
;
}
public override async Task<ImportStats> ImportDataForArtist(Artist artist, ArtistUpstreamSource src, PerformContext ctx)
{
await PreloadData(artist);
var stats = new ImportStats();
ctx?.WriteLine("Processing Eras");
stats += await ProcessEras(artist, ctx);
ctx?.WriteLine("Processing Tours");
stats += await ProcessTours(artist, ctx);
ctx?.WriteLine("Processing Songs");
stats += await ProcessSongs(artist, ctx);
ctx?.WriteLine("Processing Venues");
stats += await ProcessVenues(artist, ctx);
ctx?.WriteLine("Processing Shows");
stats += await ProcessShows(artist, src, ctx);
ctx?.WriteLine("Rebuilding");
await RebuildShows(artist);
await RebuildYears(artist);
return stats;
//return await ProcessIdentifiers(artist, await this.http.GetAsync(SearchUrlForArtist(artist)));
}
public override Task<ImportStats> ImportSpecificShowDataForArtist(Artist artist, ArtistUpstreamSource src, string showIdentifier, PerformContext ctx)
{
return Task.FromResult(new ImportStats());
}
private IDictionary<string, Source> existingSources = new Dictionary<string, Source>();
private IDictionary<string, Era> existingEras = new Dictionary<string, Era>();
private IDictionary<string, VenueWithShowCount> existingVenues = new Dictionary<string, VenueWithShowCount>();
private IDictionary<string, Tour> existingTours = new Dictionary<string, Tour>();
private IDictionary<string, SetlistShow> existingSetlistShows = new Dictionary<string, SetlistShow>();
private IDictionary<string, SetlistSong> existingSetlistSongs = new Dictionary<string, SetlistSong>();
private IDictionary<string, Era> yearToEraMapping = new Dictionary<string, Era>();
async Task PreloadData(Artist artist)
{
existingSources = (await _sourceService.AllForArtist(artist)).
GroupBy(venue => venue.upstream_identifier).
ToDictionary(grp => grp.Key, grp => grp.First());
existingEras = (await _eraService.AllForArtist(artist)).
GroupBy(era => era.name).
ToDictionary(grp => grp.Key, grp => grp.First());
existingVenues = (await _venueService.AllIncludingUnusedForArtist(artist)).
GroupBy(venue => venue.upstream_identifier).
ToDictionary(grp => grp.Key, grp => grp.First());
existingTours = (await _tourService.AllForArtist(artist)).
GroupBy(tour => tour.upstream_identifier).
ToDictionary(grp => grp.Key, grp => grp.First());
existingSetlistShows = (await _setlistShowService.AllForArtist(artist)).
GroupBy(show => show.upstream_identifier).
ToDictionary(grp => grp.Key, grp => grp.First());
existingSetlistSongs = (await _setlistSongService.AllForArtist(artist)).
GroupBy(song => song.upstream_identifier).
ToDictionary(grp => grp.Key, grp => grp.First());
}
private string PhishinApiUrl(string api, string sort_attr = null, int per_page = 99999, int? page = null)
{
return $"http://phish.in/api/v1/{api}.json?per_page={per_page}{(sort_attr != null ? "&sort_attr=" + sort_attr : "")}{(page != null ? "&page=" + page.Value : "")}";
}
private async Task<PhishinRootObject<T>> PhishinApiRequest<T>(string apiRoute, PerformContext ctx, string sort_attr = null, int per_page = 99999, int? page = null)
{
var url = PhishinApiUrl(apiRoute, sort_attr, per_page, page);
ctx?.WriteLine($"Requesting {url}");
var resp = await http.GetAsync(url);
return JsonConvert.DeserializeObject<PhishinRootObject<T>>(await resp.Content.ReadAsStringAsync());
}
public async Task<ImportStats> ProcessTours(Artist artist, PerformContext ctx)
{
var stats = new ImportStats();
foreach (var tour in (await PhishinApiRequest<IEnumerable<PhishinSmallTour>>("tours", ctx)).data)
{
var dbTour = existingTours.GetValue(tour.id.ToString());
if (dbTour == null)
{
dbTour = await _tourService.Save(new Tour
{
updated_at = tour.updated_at,
artist_id = artist.id,
start_date = DateTime.Parse(tour.starts_on),
end_date = DateTime.Parse(tour.ends_on),
name = tour.name,
slug = Slugify(tour.name),
upstream_identifier = tour.id.ToString()
});
existingTours[dbTour.upstream_identifier] = dbTour;
stats.Created++;
}
else if(tour.updated_at > dbTour.updated_at)
{
dbTour.start_date = DateTime.Parse(tour.starts_on);
dbTour.end_date = DateTime.Parse(tour.ends_on);
dbTour.name = tour.name;
dbTour = await _tourService.Save(dbTour);
existingTours[dbTour.upstream_identifier] = dbTour;
stats.Updated++;
}
}
return stats;
}
public async Task<ImportStats> ProcessEras(Artist artist, PerformContext ctx)
{
var stats = new ImportStats();
var order = 0;
foreach (var era in (await PhishinApiRequest<IDictionary<string, IList<string>>>("eras", ctx)).data)
{
var dbEra = existingEras.GetValue(era.Key);
if (dbEra == null)
{
dbEra = await _eraService.Save(new Era()
{
artist_id = artist.id,
name = era.Key,
order = order,
updated_at = DateTime.Now
});
existingEras[dbEra.name] = dbEra;
stats.Created++;
}
foreach (var year in era.Value)
{
yearToEraMapping[year] = dbEra;
}
order++;
}
return stats;
}
public async Task<ImportStats> ProcessSongs(Artist artist, PerformContext ctx)
{
var stats = new ImportStats();
var songsToSave = new List<SetlistSong>();
foreach (var song in (await PhishinApiRequest<IEnumerable<PhishinSmallSong>>("songs", ctx)).data)
{
var dbSong = existingSetlistSongs.GetValue(song.id.ToString());
// skip aliases for now
if (dbSong == null && song.alias_for.HasValue == false)
{
songsToSave.Add(new SetlistSong()
{
updated_at = song.updated_at,
artist_id = artist.id,
name = song.title,
slug = song.slug,
upstream_identifier = song.id.ToString()
});
}
}
var newSongs = await _setlistSongService.InsertAll(artist, songsToSave);
foreach (var s in newSongs)
{
existingSetlistSongs[s.upstream_identifier] = s;
}
stats.Created += newSongs.Count();
return stats;
}
public async Task<ImportStats> ProcessVenues(Artist artist, PerformContext ctx)
{
var stats = new ImportStats();
foreach (var venue in (await PhishinApiRequest<IEnumerable<PhishinSmallVenue>>("venues", ctx)).data)
{
var dbVenue = existingVenues.GetValue(venue.id.ToString());
if (dbVenue == null)
{
var sc = new VenueWithShowCount()
{
updated_at = venue.updated_at,
artist_id = artist.id,
name = venue.name,
location = venue.location,
slug = Slugify(venue.name),
latitude = venue.latitude,
longitude = venue.longitude,
past_names = venue.past_names,
upstream_identifier = venue.id.ToString()
};
var createdDb = await _venueService.Save(sc);
sc.id = createdDb.id;
existingVenues[sc.upstream_identifier] = sc;
stats.Created++;
dbVenue = sc;
}
else if(venue.updated_at > dbVenue.updated_at)
{
dbVenue.name = venue.name;
dbVenue.location = venue.location;
dbVenue.longitude = venue.longitude;
dbVenue.latitude = venue.latitude;
dbVenue.past_names = venue.past_names;
dbVenue.updated_at = venue.updated_at;
await _venueService.Save(dbVenue);
existingVenues[dbVenue.upstream_identifier] = dbVenue;
stats.Updated++;
}
}
return stats;
}
private int SetIndexForIdentifier(string ident)
{
if (ident == "S") { return 0; }
else if (ident == "1") { return 1; }
else if (ident == "2") { return 2; }
else if (ident == "3") { return 3; }
else if (ident == "4") { return 4; }
else if (ident == "E") { return 5; }
else if (ident == "E2") { return 6; }
else if (ident == "E3") { return 7; }
else { return 8; }
}
private async Task ProcessSetlistShow(ImportStats stats, PhishinShow show, Artist artist, ArtistUpstreamSource src, Source dbSource, IDictionary<string, SourceSet> sets)
{
var dbShow = existingSetlistShows.GetValue(show.date);
var addSongs = false;
if (dbShow == null)
{
dbShow = await _setlistShowService.Save(new SetlistShow()
{
artist_id = artist.id,
upstream_identifier = show.date,
date = DateTime.Parse(show.date),
venue_id = existingVenues[show.venue.id.ToString()].id,
tour_id = existingTours[show.tour_id.ToString()].id,
era_id = yearToEraMapping.GetValue(show.date.Substring(0, 4), yearToEraMapping["1983-1987"]).id,
updated_at = dbSource.updated_at
});
stats.Created++;
addSongs = true;
}
else if (show.updated_at > dbShow.updated_at)
{
dbShow.date = DateTime.Parse(show.date);
dbShow.venue_id = existingVenues[show.venue.id.ToString()].id;
dbShow.tour_id = existingTours[show.tour_id.ToString()].id;
dbShow.era_id = yearToEraMapping.GetValue(show.date.Substring(0, 4), yearToEraMapping["1983-1987"]).id;
dbShow.updated_at = dbSource.updated_at;
dbShow = await _setlistShowService.Save(dbShow);
stats.Updated++;
addSongs = true;
}
if (addSongs)
{
var dbSongs = show.tracks.
SelectMany(phishinTrack => phishinTrack.song_ids.Select(song_id => existingSetlistSongs.GetValue(song_id.ToString()))).
Where(t => t != null).
GroupBy(t => t.upstream_identifier).
Select(g => g.First()).
ToList()
;
stats += await _setlistShowService.UpdateSongPlays(dbShow, dbSongs);
}
}
private async Task<Source> ProcessShow(ImportStats stats, Artist artist, PhishinShow fullShow, ArtistUpstreamSource src, Source dbSource, PerformContext ctx)
{
dbSource.has_jamcharts = fullShow.tags.Count(t => t.name == "Jamcharts") > 0;
dbSource = await _sourceService.Save(dbSource);
var sets = new Dictionary<string, SourceSet>();
foreach (var track in fullShow.tracks)
{
var set = sets.GetValue(track.set);
if (set == null)
{
set = new SourceSet()
{
source_id = dbSource.id,
index = SetIndexForIdentifier(track.set),
name = track.set_name,
is_encore = track.set[0] == 'E',
updated_at = dbSource.updated_at
};
// this needs to be set after loading from the db
set.tracks = new List<SourceTrack>();
sets[track.set] = set;
}
}
var setMaps = (await _sourceSetService.UpdateAll(dbSource, sets.Values))
.GroupBy(s => s.index)
.ToDictionary(kvp => kvp.Key, kvp => kvp.Single());
foreach (var kvp in setMaps)
{
kvp.Value.tracks = new List<SourceTrack>();
}
foreach (var track in fullShow.tracks)
{
var set = setMaps[SetIndexForIdentifier(track.set)];
set.tracks.Add(new SourceTrack()
{
source_set_id = set.id,
source_id = dbSource.id,
title = track.title,
duration = track.duration / 1000,
track_position = track.position,
slug = SlugifyTrack(track.title),
mp3_url = track.mp3.Replace("http:", "https:"),
updated_at = dbSource.updated_at,
artist_id = artist.id
});
}
stats.Created += (await _sourceTrackService.InsertAll(dbSource, setMaps.SelectMany(kvp => kvp.Value.tracks))).Count();
await ProcessSetlistShow(stats, fullShow, artist, src, dbSource, sets);
ResetTrackSlugCounts();
return dbSource;
}
public async Task<ImportStats> ProcessShows(Artist artist, ArtistUpstreamSource src, PerformContext ctx)
{
var stats = new ImportStats();
var pages = 80;
var prog = ctx?.WriteProgressBar();
var pageSize = 20;
for (var currentPage = 1; currentPage <= pages; currentPage++)
{
var apiShows = await PhishinApiRequest<IEnumerable<PhishinShow>>("shows", ctx, "date", per_page: pageSize, page: currentPage);
pages = apiShows.total_pages;
var shows = apiShows.data.ToList();
foreach(var (idx, show) in shows.Select((s, i) => (i, s)))
{
try
{
await processShow(show);
}
catch (Exception e)
{
ctx?.WriteLine($"Error processing show (but continuing): {show.date} (id: {show.id})");
ctx?.LogException(e);
}
prog?.SetValue(100.0 * ((currentPage - 1) * pageSize + idx + 1) / apiShows.total_entries);
}
}
async Task processShow(PhishinShow show)
{
using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
var dbSource = existingSources.GetValue(show.id.ToString());
if (dbSource == null)
{
dbSource = await ProcessShow(stats, artist, show, src, new Source()
{
updated_at = show.updated_at,
artist_id = artist.id,
venue_id = existingVenues[show.venue.id.ToString()].id,
display_date = show.date,
upstream_identifier = show.id.ToString(),
is_soundboard = show.sbd,
is_remaster = show.remastered,
description = "",
taper_notes = show.taper_notes
}, ctx);
existingSources[dbSource.upstream_identifier] = dbSource;
stats.Created++;
stats.Created += (await linkService.AddLinksForSource(dbSource, new[] {
new Link
{
source_id = dbSource.id,
for_ratings = false,
for_source = true,
for_reviews = false,
upstream_source_id = src.upstream_source_id,
url = $"http://phish.in/{dbSource.display_date}",
label = "View on phish.in"
}
})).Count();
}
else if (show.updated_at > dbSource.updated_at)
{
dbSource.updated_at = show.updated_at;
dbSource.venue_id = existingVenues[show.venue.id.ToString()].id;
dbSource.display_date = show.date;
dbSource.upstream_identifier = show.id.ToString();
dbSource.is_soundboard = show.sbd;
dbSource.is_remaster = show.remastered;
dbSource.description = "";
dbSource.taper_notes = show.taper_notes;
dbSource = await ProcessShow(stats, artist, show, src, dbSource, ctx);
existingSources[dbSource.upstream_identifier] = dbSource;
stats.Updated++;
}
scope.Complete();
}
}
return stats;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.explicit01.explicit01
{
// <Area>Declaration of Optional Params</Area>
// <Title> Explicit User defined conversions</Title>
// <Description>User-defined conversions with defaults</Description>
// <Expects status=success></Expects>
// <Code>
//<Expects Status=warning>\(10,39\).*CS1066</Expects>
public class Derived
{
public static explicit operator int (Derived d = null)
{
if (d != null)
return 0;
return 1;
}
}
public class TestFunction
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic tf = new Derived();
int result = (int)tf;
return result;
}
}
//</code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.explicit02.explicit02
{
// <Area>Declaration of Optional Params</Area>
// <Title> Explicit User defined conversions</Title>
// <Description>User-defined conversions with defaults</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success></Expects>
// <Code>
//<Expects Status=warning>\(12,41\).*CS1066</Expects>
public class Derived
{
public static explicit operator int (Derived d = default(Derived))
{
if (d == null)
return 0;
return 1;
}
}
public class TestFunction
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = null;
dynamic tf = p;
try
{
int result = (int)tf;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.ValueCantBeNull, e.Message, "int");
if (ret)
return 0;
}
return 1;
}
}
//</code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.explicit04.explicit04
{
// <Area>Declaration of Optional Params</Area>
// <Title> Explicit User defined conversions</Title>
// <Description>User-defined conversions with defaults</Description>
// <Expects status=success></Expects>
// <Code>
//<Expects Status=warning>\(11,39\).*CS1066</Expects>
public class Derived
{
private const Derived x = null;
public static explicit operator int (Derived d = x)
{
if (d != null)
return 0;
return 1;
}
}
public class TestFunction
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic tf = new Derived();
int result = (int)tf;
return result;
}
}
//</code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.explicit05.explicit05
{
// <Area>Declaration of Optional Params</Area>
// <Title> Explicit User defined conversions</Title>
// <Description>User-defined conversions with defaults</Description>
// <Expects status=success></Expects>
// <Code>
//<Expects Status=warning>\(11,39\).*CS1066</Expects>
public class Derived
{
private const Derived x = null;
public static explicit operator int (Derived d = true ? x : x)
{
if (d != null)
return 0;
return 1;
}
}
public class TestFunction
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic tf = new Derived();
int result = (int)tf;
return result;
}
}
//</code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.implicit01.implicit01
{
// <Area>Declaration of Optional Params</Area>
// <Title> Explicit User defined conversions</Title>
// <Description>User-defined conversions with defaults</Description>
// <Expects status=success></Expects>
// <Code>
//<Expects Status=warning>\(10,39\).*CS1066</Expects>
public class Derived
{
public static implicit operator int (Derived d = null)
{
if (d != null)
return 0;
return 1;
}
}
public class TestFunction
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic tf = new Derived();
int result = tf;
return result;
}
}
//</code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.implicit02.implicit02
{
// <Area>Declaration of Optional Params</Area>
// <Title> Explicit User defined conversions</Title>
// <Description>User-defined conversions with defaults</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success></Expects>
// <Code>
//<Expects Status=warning>\(11,39\).*CS1066</Expects>
public class Derived
{
public static implicit operator int (Derived d = default(Derived))
{
if (d == null)
return 0;
return 1;
}
}
public class TestFunction
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = null;
dynamic tf = p;
try
{
int result = tf;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.ValueCantBeNull, e.Message, "int");
if (ret)
return 0;
}
return 1;
}
}
//</code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.implicit04.implicit04
{
// <Area>Declaration of Optional Params</Area>
// <Title> Explicit User defined conversions</Title>
// <Description>User-defined conversions with defaults</Description>
// <Expects status=success></Expects>
// <Code>
//<Expects Status=warning>\(11,39\).*CS1066</Expects>
public class Derived
{
private const Derived x = null;
public static implicit operator int (Derived d = x)
{
if (d != null)
return 0;
return 1;
}
}
public class TestFunction
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic tf = new Derived();
int result = tf;
return result;
}
}
//</code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.implicit05.implicit05
{
// <Area>Declaration of Optional Params</Area>
// <Title> Explicit User defined conversions</Title>
// <Description>User-defined conversions with defaults</Description>
// <Expects status=success></Expects>
// <Code>
//<Expects Status=warning>\(11,39\).*CS1066</Expects>
public class Derived
{
private const Derived x = null;
public static implicit operator int (Derived d = true ? x : x)
{
if (d != null)
return 0;
return 1;
}
}
public class TestFunction
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic tf = new Derived();
int result = tf;
return result;
}
}
//</code>
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.DocumentationCommentFormatting;
using Microsoft.CodeAnalysis.Editor.SignatureHelp;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CSharp.SignatureHelp
{
[ExportSignatureHelpProvider("AttributeSignatureHelpProvider", LanguageNames.CSharp)]
internal partial class AttributeSignatureHelpProvider : AbstractCSharpSignatureHelpProvider
{
public override bool IsTriggerCharacter(char ch)
{
return ch == '(' || ch == ',';
}
public override bool IsRetriggerCharacter(char ch)
{
return ch == ')';
}
private bool TryGetAttributeExpression(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out AttributeSyntax attribute)
{
if (!CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsArgumentListToken, cancellationToken, out attribute))
{
return false;
}
return attribute.ArgumentList != null;
}
private bool IsTriggerToken(SyntaxToken token)
{
return !token.IsKind(SyntaxKind.None) &&
token.ValueText.Length == 1 &&
IsTriggerCharacter(token.ValueText[0]) &&
token.Parent is AttributeArgumentListSyntax &&
token.Parent.Parent is AttributeSyntax;
}
private static bool IsArgumentListToken(AttributeSyntax expression, SyntaxToken token)
{
return expression.ArgumentList != null &&
expression.ArgumentList.Span.Contains(token.SpanStart) &&
token != expression.ArgumentList.CloseParenToken;
}
protected override async Task<SignatureHelpItems> GetItemsWorkerAsync(Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
AttributeSyntax attribute;
if (!TryGetAttributeExpression(root, position, document.GetLanguageService<ISyntaxFactsService>(), triggerInfo.TriggerReason, cancellationToken, out attribute))
{
return null;
}
var semanticModel = await document.GetSemanticModelForNodeAsync(attribute, cancellationToken).ConfigureAwait(false);
var attributeType = semanticModel.GetTypeInfo(attribute, cancellationToken).Type as INamedTypeSymbol;
if (attributeType == null)
{
return null;
}
var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken);
if (within == null)
{
return null;
}
var symbolDisplayService = document.Project.LanguageServices.GetService<ISymbolDisplayService>();
var accessibleConstructors = attributeType.InstanceConstructors
.Where(c => c.IsAccessibleWithin(within))
.FilterToVisibleAndBrowsableSymbols(document.ShouldHideAdvancedMembers(), semanticModel.Compilation)
.Sort(symbolDisplayService, semanticModel, attribute.SpanStart);
if (!accessibleConstructors.Any())
{
return null;
}
var anonymousTypeDisplayService = document.Project.LanguageServices.GetService<IAnonymousTypeDisplayService>();
var documentationCommentFormatter = document.Project.LanguageServices.GetService<IDocumentationCommentFormattingService>();
var textSpan = SignatureHelpUtilities.GetSignatureHelpSpan(attribute.ArgumentList);
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
return CreateSignatureHelpItems(accessibleConstructors.Select(c =>
Convert(c, within, attribute, semanticModel, symbolDisplayService, anonymousTypeDisplayService, documentationCommentFormatter, cancellationToken)),
textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken));
}
public override SignatureHelpState GetCurrentArgumentState(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, TextSpan currentSpan, CancellationToken cancellationToken)
{
AttributeSyntax expression;
if (TryGetAttributeExpression(root, position, syntaxFacts, SignatureHelpTriggerReason.InvokeSignatureHelpCommand, cancellationToken, out expression) &&
currentSpan.Start == SignatureHelpUtilities.GetSignatureHelpSpan(expression.ArgumentList).Start)
{
return SignatureHelpUtilities.GetSignatureHelpState(expression.ArgumentList, position);
}
return null;
}
private SignatureHelpItem Convert(
IMethodSymbol constructor,
ISymbol within,
AttributeSyntax attribute,
SemanticModel semanticModel,
ISymbolDisplayService symbolDisplayService,
IAnonymousTypeDisplayService anonymousTypeDisplayService,
IDocumentationCommentFormattingService documentationCommentFormatter,
CancellationToken cancellationToken)
{
var position = attribute.SpanStart;
var namedParameters = constructor.ContainingType.GetAttributeNamedParameters(semanticModel.Compilation, within)
.OrderBy(s => s.Name)
.ToList();
var isVariadic =
constructor.Parameters.Length > 0 && constructor.Parameters.Last().IsParams && namedParameters.Count == 0;
var item = CreateItem(
constructor, semanticModel, position,
symbolDisplayService, anonymousTypeDisplayService,
isVariadic,
constructor.GetDocumentationPartsFactory(semanticModel, position, documentationCommentFormatter),
GetPreambleParts(constructor, semanticModel, position),
GetSeparatorParts(),
GetPostambleParts(constructor),
GetParameters(constructor, semanticModel, position, namedParameters, documentationCommentFormatter, cancellationToken));
return item;
}
private IEnumerable<SignatureHelpParameter> GetParameters(
IMethodSymbol constructor,
SemanticModel semanticModel,
int position,
IList<ISymbol> namedParameters,
IDocumentationCommentFormattingService documentationCommentFormatter,
CancellationToken cancellationToken)
{
foreach (var parameter in constructor.Parameters)
{
yield return Convert(parameter, semanticModel, position, documentationCommentFormatter, cancellationToken);
}
for (int i = 0; i < namedParameters.Count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
var namedParameter = namedParameters[i];
var type = namedParameter is IFieldSymbol ? ((IFieldSymbol)namedParameter).Type : ((IPropertySymbol)namedParameter).Type;
var displayParts = new List<SymbolDisplayPart>();
displayParts.Add(new SymbolDisplayPart(
namedParameter is IFieldSymbol ? SymbolDisplayPartKind.FieldName : SymbolDisplayPartKind.PropertyName,
namedParameter, namedParameter.Name.ToIdentifierToken().ToString()));
displayParts.Add(Space());
displayParts.Add(Punctuation(SyntaxKind.EqualsToken));
displayParts.Add(Space());
displayParts.AddRange(type.ToMinimalDisplayParts(semanticModel, position));
yield return new SignatureHelpParameter(
namedParameter.Name,
isOptional: true,
documentationFactory: namedParameter.GetDocumentationPartsFactory(semanticModel, position, documentationCommentFormatter),
displayParts: displayParts,
prefixDisplayParts: GetParameterPrefixDisplayParts(i));
}
}
private static List<SymbolDisplayPart> GetParameterPrefixDisplayParts(int i)
{
if (i == 0)
{
return new List<SymbolDisplayPart>
{
new SymbolDisplayPart(SymbolDisplayPartKind.Text, null, CSharpEditorResources.Properties),
Punctuation(SyntaxKind.ColonToken),
Space()
};
}
return null;
}
private IEnumerable<SymbolDisplayPart> GetPreambleParts(
IMethodSymbol method,
SemanticModel semanticModel,
int position)
{
var result = new List<SymbolDisplayPart>();
result.AddRange(method.ContainingType.ToMinimalDisplayParts(semanticModel, position));
result.Add(Punctuation(SyntaxKind.OpenParenToken));
return result;
}
private IEnumerable<SymbolDisplayPart> GetPostambleParts(IMethodSymbol method)
{
yield return Punctuation(SyntaxKind.CloseParenToken);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureSpecials
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// SubscriptionInCredentialsOperations operations.
/// </summary>
internal partial class SubscriptionInCredentialsOperations : IServiceOperations<AutoRestAzureSpecialParametersTestClient>, ISubscriptionInCredentialsOperations
{
/// <summary>
/// Initializes a new instance of the SubscriptionInCredentialsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal SubscriptionInCredentialsOperations(AutoRestAzureSpecialParametersTestClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestAzureSpecialParametersTestClient
/// </summary>
public AutoRestAzureSpecialParametersTestClient Client { get; private set; }
/// <summary>
/// POST method with subscriptionId modeled in credentials. Set the
/// credential subscriptionId to '1234-5678-9012-3456' to succeed
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PostMethodGlobalValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PostMethodGlobalValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/subscriptionId/method/string/none/path/global/1234-5678-9012-3456/{subscriptionId}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// POST method with subscriptionId modeled in credentials. Set the
/// credential subscriptionId to null, and client-side validation should
/// prevent you from making this call
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PostMethodGlobalNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PostMethodGlobalNull", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/subscriptionId/method/string/none/path/global/null/{subscriptionId}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// POST method with subscriptionId modeled in credentials. Set the
/// credential subscriptionId to '1234-5678-9012-3456' to succeed
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PostMethodGlobalNotProvidedValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PostMethodGlobalNotProvidedValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/subscriptionId/method/string/none/path/globalNotProvided/1234-5678-9012-3456/{subscriptionId}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// POST method with subscriptionId modeled in credentials. Set the
/// credential subscriptionId to '1234-5678-9012-3456' to succeed
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PostPathGlobalValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PostPathGlobalValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/subscriptionId/path/string/none/path/global/1234-5678-9012-3456/{subscriptionId}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// POST method with subscriptionId modeled in credentials. Set the
/// credential subscriptionId to '1234-5678-9012-3456' to succeed
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PostSwaggerGlobalValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PostSwaggerGlobalValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/subscriptionId/swagger/string/none/path/global/1234-5678-9012-3456/{subscriptionId}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
/*
Copyright (c) 2005, Marc Clifton
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name Marc Clifton nor the names of its contributors may be
used to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
using System.Xml;
using Clifton.ExtensionMethods;
using Clifton.Tools.Strings;
namespace Clifton.MycroParser
{
public delegate void InstantiateClassDlgt(object sender, ClassEventArgs cea);
public delegate void AssignPropertyDlgt(object sender, PropertyEventArgs pea);
public delegate void UnknownPropertyDlgt(object sender, UnknownPropertyEventArgs pea);
public delegate void CustomAssignPropertyDlgt(object sender, CustomPropertyEventArgs pea);
public delegate void AssignEventDlgt(object sender, EventEventArgs eea);
public delegate void SupportInitializeDlgt(object sender, SupportInitializeEventArgs siea);
public delegate void AddToCollectionDlgt(object sender, CollectionEventArgs cea);
public delegate void UseReferenceDlgt(object sender, UseReferenceEventArgs urea);
public delegate void AssignReferenceDlgt(object sender, AssignReferenceEventArgs area);
public delegate void CommentDlgt(object sender, CommentEventArgs cea);
public interface IMycroParserInstantiatedObject
{
Dictionary<string, object> ObjectCollection { get; set; }
}
public class HandledEventArgs : EventArgs
{
protected bool handled;
public bool Handled
{
get { return handled; }
set { handled = value; }
}
}
public class ClassEventArgs : HandledEventArgs
{
protected Type t;
protected XmlNode node;
protected object result;
public Type Type
{
get { return t; }
}
public XmlNode Node
{
get { return node; }
}
public object Result
{
get { return result; }
set { result = value; }
}
public ClassEventArgs(Type t, XmlNode node)
{
this.t = t;
this.node = node;
result = null;
handled = false;
}
}
public class PropertyEventArgs : HandledEventArgs
{
protected PropertyInfo pi;
protected object src;
protected object val;
protected string valStr;
public PropertyInfo PropertyInfo
{
get { return pi; }
}
public object Source
{
get { return src; }
}
public object Value
{
get { return val; }
}
public string AsString
{
get { return valStr; }
}
public PropertyEventArgs(PropertyInfo pi, object src, object val, string valStr)
{
this.pi = pi;
this.src = src;
this.val = val;
this.valStr = valStr;
handled = false;
}
}
public class CustomPropertyEventArgs : HandledEventArgs
{
protected PropertyInfo pi;
protected object src;
protected object val;
public PropertyInfo PropertyInfo
{
get { return pi; }
}
public object Source
{
get { return src; }
}
public object Value
{
get { return val; }
}
public CustomPropertyEventArgs(PropertyInfo pi, object src, object val)
{
this.pi = pi;
this.src = src;
this.val = val;
}
}
public class UnknownPropertyEventArgs : HandledEventArgs
{
protected string propertyName;
protected object src;
protected string propertyValue;
public string PropertyName
{
get { return propertyName; }
}
public object Source
{
get { return src; }
}
public string PropertyValue
{
get { return propertyValue; }
}
public UnknownPropertyEventArgs(string pname, object src, string pvalue)
{
this.propertyName = pname;
this.src = src;
this.propertyValue = pvalue;
}
}
public class EventEventArgs : HandledEventArgs
{
protected EventInfo ei;
protected object ret;
protected object sink;
protected string srcName;
protected string methodName;
public EventInfo EventInfo
{
get { return ei; }
}
public object Return
{
get { return ret; }
}
public object Sink
{
get { return sink; }
}
public string SourceName
{
get { return srcName; }
}
public string MethodName
{
get { return methodName; }
}
public EventEventArgs(EventInfo ei, object ret, object sink, string srcName, string methodName)
{
this.ei = ei;
this.ret = ret;
this.sink = sink;
this.srcName = srcName;
this.methodName = methodName;
}
}
public class SupportInitializeEventArgs : HandledEventArgs
{
protected Type t;
protected object obj;
public object Object
{
get { return obj; }
}
public Type Type
{
get { return t; }
}
public SupportInitializeEventArgs(Type t, object obj)
{
this.t = t;
this.obj = obj;
}
}
public class CollectionEventArgs : HandledEventArgs
{
protected PropertyInfo pi;
protected Type instanceType;
protected Type parentType;
public PropertyInfo PropertyInfo
{
get { return pi; }
}
public Type InstanceType
{
get { return instanceType; }
}
public Type ParentType
{
get { return parentType; }
}
public CollectionEventArgs(PropertyInfo pi, Type instanceType, Type parentType)
{
this.pi = pi;
this.instanceType = instanceType;
this.parentType = parentType;
}
}
public class UseReferenceEventArgs : HandledEventArgs
{
protected Type t;
protected string refName;
protected object ret;
public Type Type
{
get { return t; }
}
public string RefName
{
get { return refName; }
}
public object Return
{
get { return ret; }
set { ret = value; }
}
public UseReferenceEventArgs(Type t, string refName)
{
this.t = t;
this.refName = refName;
ret = null;
}
}
public class AssignReferenceEventArgs : HandledEventArgs
{
protected PropertyInfo pi;
protected string refName;
protected object obj;
public PropertyInfo PropertyInfo
{
get { return pi; }
}
public string RefName
{
get { return refName; }
}
public object Object
{
get { return obj; }
}
public AssignReferenceEventArgs(PropertyInfo pi, string refName, object obj)
{
this.pi = pi;
this.refName = refName;
this.obj = obj;
}
}
public class CommentEventArgs
{
protected string comment;
public string Comment
{
get { return comment; }
}
public CommentEventArgs(string comment)
{
this.comment = comment;
}
}
// public interface IMycroXaml
// {
// void Initialize(object parent);
// object ReturnedObject
// {
// get;
// }
// }
public class MycroParser
{
protected List<Tuple<Type, object>> objectsToEndInit;
protected Dictionary<string, object> nsMap;
protected Dictionary<string, object> objectCollection;
protected object eventSink;
protected XmlNode baseNode;
public event InstantiateClassDlgt InstantiateClass;
public event AssignPropertyDlgt AssignProperty;
public event UnknownPropertyDlgt UnknownProperty;
public event CustomAssignPropertyDlgt CustomAssignProperty;
public event AssignEventDlgt AssignEvent;
public event SupportInitializeDlgt BeginInitCheck;
public event SupportInitializeDlgt EndInitCheck;
public event EventHandler EndChildProcessing;
public event AddToCollectionDlgt AddToCollection;
public event UseReferenceDlgt UseReference;
public event AssignReferenceDlgt AssignReference;
public event CommentDlgt Comment;
public Dictionary<string, object> NamespaceMap
{
get { return nsMap; }
}
public Dictionary<string, object> ObjectCollection
{
get { return objectCollection; }
}
public MycroParser()
{
objectCollection = new Dictionary<string, object>();
objectsToEndInit = new List<Tuple<Type, object>>();
}
public static T InstantiateFromFile<T>(string filename, Action<MycroParser> AddInstances)
{
MycroParser mp = new MycroParser();
AddInstances.IfNotNull(t => t(mp));
XmlDocument doc = new XmlDocument();
doc.Load(filename);
mp.Load(doc, "Form", null);
T obj = (T)mp.Process();
// Pass object collection to the instantiated class if it implements IMycroParserInstantiatedObject.
if (obj is IMycroParserInstantiatedObject)
{
((IMycroParserInstantiatedObject)obj).ObjectCollection = mp.ObjectCollection;
}
return obj;
}
public void Load(XmlDocument doc, string objectName, object eventSink)
{
this.eventSink = eventSink;
XmlNode node;
if (objectName != null)
{
node = doc.SelectSingleNode("//MycroXaml[@Name='" + objectName + "']");
Trace.Assert(node != null, "Couldn't find MycroXaml element " + objectName);
Trace.Assert(node.ChildNodes.Count <= 1, "Only one child of the root is allowed.");
// The last valid node instantiated is returned.
// The xml root should only have one child.
ProcessNamespaces(node);
if (node.ChildNodes.Count == 1)
{
baseNode = node.ChildNodes[0];
}
}
else
{
node = doc.DocumentElement;
baseNode = node;
ProcessNamespaces(node);
}
}
public object Process()
{
object ret = null;
if (baseNode != null)
{
Type t;
ret = ProcessNode(baseNode, null, out t);
}
DoEndInit();
return ret;
}
public bool HasInstance(string name)
{
return objectCollection.ContainsKey(name);
}
public object GetInstance(string name)
{
Trace.Assert(objectCollection.ContainsKey(name), "The object collection does not have an entry for " + name);
return objectCollection[name];
}
public void AddInstance(string name, object obj)
{
// We don't care if we overwrite an existing object.
objectCollection[name] = obj;
}
protected void DoEndInit()
{
foreach (var endInit in objectsToEndInit)
{
OnEndInitCheck(endInit.Item1, endInit.Item2);
}
}
protected void ProcessNamespaces(XmlNode node)
{
nsMap = new Dictionary<string, object>();
foreach (XmlAttribute attr in node.Attributes)
{
if (attr.Prefix == "xmlns")
{
nsMap[attr.LocalName] = attr.Value;
}
}
}
protected virtual object OnInstantiateClass(Type t, XmlNode node)
{
object ret = null;
ClassEventArgs args = new ClassEventArgs(t, node);
if (InstantiateClass != null)
{
InstantiateClass(this, args);
ret = args.Result;
}
if (!args.Handled)
{
ret = Activator.CreateInstance(t);
}
return ret;
}
protected virtual void OnAssignProperty(PropertyInfo pi, object ret, object val, string origVal)
{
PropertyEventArgs args = new PropertyEventArgs(pi, ret, val, origVal);
if (AssignProperty != null)
{
AssignProperty(this, args);
}
if (!args.Handled)
{
pi.SetValue(ret, val, null);
}
}
protected virtual bool OnCustomAssignProperty(PropertyInfo pi, object ret, object val)
{
CustomPropertyEventArgs args = new CustomPropertyEventArgs(pi, ret, val);
if (CustomAssignProperty != null)
{
CustomAssignProperty(this, args);
}
return args.Handled;
}
protected virtual bool OnUnknownProperty(string pname, object ret, string pvalue)
{
UnknownPropertyEventArgs args = new UnknownPropertyEventArgs(pname, ret, pvalue);
if (UnknownProperty != null)
{
UnknownProperty(this, args);
}
return args.Handled;
}
protected virtual void OnAssignEvent(EventInfo ei, object ret, object sink, string srcName, string methodName)
{
EventEventArgs args = new EventEventArgs(ei, ret, sink, srcName, methodName);
if (AssignEvent != null)
{
AssignEvent(this, args);
}
if (!args.Handled)
{
Delegate dlgt = null;
try
{
MethodInfo mi = sink.GetType().GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
dlgt = Delegate.CreateDelegate(ei.EventHandlerType, sink, mi.Name);
}
catch (Exception e)
{
Trace.Fail("Couldn't create a delegate for the event " + srcName + "." + methodName + ":\r\n" + e.Message);
}
try
{
ei.AddEventHandler(ret, dlgt);
}
catch (Exception e)
{
Trace.Fail("Binding to event " + ei.Name + " failed: " + e.Message);
}
}
}
protected virtual void OnBeginInitCheck(Type t, object obj)
{
SupportInitializeEventArgs args = new SupportInitializeEventArgs(t, obj);
if (BeginInitCheck != null)
{
BeginInitCheck(this, args);
}
if (!args.Handled)
{
// support the ISupportInitialize interface
if (obj is ISupportInitialize)
{
((ISupportInitialize)obj).BeginInit();
}
}
}
protected virtual void OnEndInitCheck(Type t, object obj)
{
SupportInitializeEventArgs args = new SupportInitializeEventArgs(t, obj);
if (EndInitCheck != null)
{
EndInitCheck(this, args);
}
if (!args.Handled)
{
// support the ISupportInitialize interface
if (obj is ISupportInitialize)
{
((ISupportInitialize)obj).EndInit();
}
}
}
protected virtual void OnEndChildProcessing()
{
if (EndChildProcessing != null)
{
EndChildProcessing(this, EventArgs.Empty);
}
}
protected virtual object OnUseReference(Type t, string refVar)
{
object ret = null;
UseReferenceEventArgs args = new UseReferenceEventArgs(t, refVar);
if (UseReference != null)
{
UseReference(this, args);
}
if (!args.Handled)
{
if (HasInstance(refVar))
{
ret = GetInstance(refVar);
}
}
else
{
ret = args.Return;
}
return ret;
}
protected virtual void OnAssignReference(PropertyInfo pi, string refName, object obj)
{
AssignReferenceEventArgs args = new AssignReferenceEventArgs(pi, refName, obj);
if (AssignReference != null)
{
AssignReference(this, args);
}
if (!args.Handled)
{
object val = GetInstance(refName);
try
{
pi.SetValue(obj, val, null);
}
catch (Exception e)
{
if (!OnCustomAssignProperty(pi, obj, val))
{
Trace.Fail("Couldn't set property " + pi.Name + " to an instance of " + refName + ":\r\n" + e.Message);
}
}
}
}
/// <summary>
///
/// </summary>
/// <param name="pi">The PropertyInfo of the collection property.</param>
/// <param name="propObject">The instance of the collection.</param>
/// <param name="obj">The instance to add to the collection.</param>
/// <param name="t">The instance type (being added to the collection).</param>
/// <param name="parentType">The parent type.</param>
/// <param name="parent">The parent instance.</param>
protected virtual void OnAddToCollection(PropertyInfo pi, object propObject, object obj, Type t, Type parentType, object parent)
{
CollectionEventArgs args = new CollectionEventArgs(pi, t, parentType);
if (AddToCollection != null)
{
AddToCollection(this, args);
}
if (!args.Handled)
{
// A null return is valid in cases where a class implementing the IMicroXaml interface
// might want to take care of managing the instance it creates itself. See DataBinding
if (obj != null)
{
// support for ICollection and IList objects.
// If the object is a collection or list, then even if it's writeable, treat as a list.
if ( (!pi.CanWrite) || (propObject is ICollection) || (propObject is IList) )
{
if (propObject is ICollection)
{
MethodInfo mi = propObject.GetType().GetMethod("Add", new Type[] { obj.GetType() });
if (mi != null)
{
try
{
mi.Invoke(propObject, new object[] { obj });
}
catch (Exception e)
{
Trace.Fail("Adding to collection failed:\r\n" + e.Message);
}
}
else if (propObject is IList)
{
try
{
((IList)propObject).Add(obj);
}
catch (Exception e)
{
Trace.Fail("List/Collection add failed:\r\n" + e.Message);
}
}
}
else
{
Trace.Fail("Unsupported read-only property: " + pi.Name);
}
}
else
{
// direct assignment if not a collection
try
{
pi.SetValue(parent, obj, null);
}
catch (Exception e)
{
Trace.Fail("Property setter for " + pi.Name + " failed:\r\n" + e.Message);
}
}
}
}
}
protected virtual void OnComment(string text)
{
if (Comment != null)
{
CommentEventArgs args = new CommentEventArgs(text);
Comment(this, args);
}
}
protected object ProcessNode(XmlNode node, object parent, out Type t)
{
t = null;
object ret = null;
// Special case for String objects
if (node.LocalName == "String")
{
return node.InnerText;
}
bool useRef = false;
int attributeCount = 0;
string ns = node.Prefix;
string cname = node.LocalName;
Trace.Assert(nsMap.ContainsKey(ns), "Namespace '" + ns + "' has not been declared.");
string asyName = (string)nsMap[ns];
string qname = StringHelpers.LeftOf(asyName, ',') + "." + cname + ", " + StringHelpers.RightOf(asyName, ',');
t = Type.GetType(qname, false);
Trace.Assert(t != null, "Type " + qname + " could not be determined.");
// Do ref:Name check here and call OnReferenceInstance if appropriate.
if (node.Attributes != null)
{
attributeCount = node.Attributes.Count;
if (attributeCount > 0)
{
// We're making a blatant assumption that the ref:Name is going to be
// the first attribute in the node.
if (node.Attributes[0].Name == "ref:Name")
{
string refVar = node.Attributes[0].Value;
ret = OnUseReference(t, refVar);
useRef = true;
}
}
}
if (!useRef)
{
// instantiate the class
try
{
ret = OnInstantiateClass(t, node);
AddToInstanceCollection(node, ret); // Allows for reference of the node by any child nodes.
}
catch (Exception e)
{
while (e.InnerException != null)
{
e = e.InnerException;
}
Trace.Fail("Type " + qname + " could not be instantiated:\r\n" + e.Message);
}
}
// Optimization, to remove SuspendLayout followed by ResumeLayout when no
// properties are being set (the ref only has a Name attribute).
// If the referenced object has additional properties that have been set (attributeCount > 1, as the first attribute is the ref:),
// then we call EndInit again because the object might need to do initialization with the attribute values that have now been assigned.
// Unfortunately, we leave it up to the object to determine how to handle potential multiple inits!
if (!useRef)
{
OnBeginInitCheck(t, ret);
}
// If the instance implements the IMicroXaml interface, then it may need
// access to the parser.
// if (ret is IMycroXaml)
// {
// ((IMycroXaml)ret).Initialize(parent);
// }
// implements the class-property-class model
ProcessChildProperties(node, ret, t);
OnEndChildProcessing();
string refName = ProcessAttributes(node, ret, t);
// Optimization, to remove SuspendLayout followed by ResumeLayout when no
// properties are being set (the ref only has a Name attribute).
// If the referenced object has additional properties that have been set (attributeCount > 1, as the first attribute is the ref:),
// then we call EndInit again because the object might need to do initialization with the attribute values that have now been assigned.
// Unfortunately, we leave it up to the object to determine how to handle potential multiple inits!
if (!useRef)
{
objectsToEndInit.Add(new Tuple<Type, object>(t, ret));
}
// If the instance implements the IMicroXaml interface, then it has the option
// to return an object that replaces the instance created by the parser.
// if (ret is IMycroXaml)
// {
// ret=((IMycroXaml)ret).ReturnedObject;
//
// if ( (ret != null) && (refName != String.Empty) )
// {
// AddInstance(refName, ret);
// }
// }
return ret;
}
protected void ProcessChildProperties(XmlNode node, object parent, Type parentType)
{
Type t;
object obj;
// children of a class must always be properties
foreach (XmlNode child in node.ChildNodes)
{
if (child is XmlComment)
{
OnComment(child.Value);
}
else
if (child is XmlElement)
{
string pname = child.LocalName;
PropertyInfo pi = parentType.GetProperty(pname); //, BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.NonPublic);
if ((pi == null)) // || (node.Prefix != child.Prefix))
{
// Special case--we're going to assume that the child is a class instance
// not associated with the parent object
ProcessNode(child, null, out t);
continue;
}
// a property can only have one child node unless it's a collection
foreach (XmlNode grandChild in child.ChildNodes)
{
if (grandChild is XmlComment)
{
OnComment(grandChild.Value);
}
else
if (grandChild is XmlElement)
{
object propObject = null;
if (parent != null)
{
propObject = pi.GetValue(parent, null);
if (propObject == null)
{
// The grandChild type is a property of the child, which is itself a property/instance of the parent.
// Instantiate the child and assign it to the parent, then process the grandchild as a collection property.
// TODO: This could be iterated more levels!
obj = ProcessNode(child, null, out t);
pi.SetValue(parent, obj, null);
continue;
}
}
obj = ProcessNode(grandChild, propObject, out t);
OnAddToCollection(pi, propObject, obj, t, parentType, parent);
}
}
}
}
}
protected void AddToInstanceCollection(XmlNode node, object ret)
{
foreach (XmlAttribute attr in node.Attributes)
{
string pname = attr.Name;
string pvalue = attr.Value;
// auto-add to our object collection
if ((pname == "Name") || (pname == "def:Name"))
{
AddInstance(pvalue, ret);
}
}
}
protected string ProcessAttributes(XmlNode node, object ret, Type t)
{
string refName = String.Empty;
// process attributes
foreach (XmlAttribute attr in node.Attributes)
{
string pname = attr.Name;
string pvalue = attr.Value;
// it's either a property or an event. Allow assignment to protected / private properties.
PropertyInfo pi = t.GetProperty(pname, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
EventInfo ei = t.GetEvent(pname);
if (pi != null)
{
// it's a property!
if (pvalue.StartsWith("{") && pvalue.EndsWith("}"))
{
// And the value is a reference to an instance!
// Get the referenced object. Late binding is not supported!
OnAssignReference(pi, StringHelpers.Between(pvalue, '{', '}'), ret);
}
else
{
// it's string, so use a type converter.
if (pi.PropertyType.FullName == "System.Object")
{
OnAssignProperty(pi, ret, pvalue, pvalue);
}
else
{
TypeConverter tc = TypeDescriptor.GetConverter(pi.PropertyType);
if (tc.CanConvertFrom(typeof(string)))
{
object val = tc.ConvertFrom(pvalue);
try
{
OnAssignProperty(pi, ret, val, pvalue);
}
catch (Exception e)
{
Trace.Fail("Property setter for " + pname + " failed:\r\n" + e.Message);
}
}
else
{
if (!OnCustomAssignProperty(pi, ret, pvalue))
{
Trace.Fail("Property setter for " + pname + " cannot be converted to property type " + pi.PropertyType.FullName + ".");
}
}
}
}
// auto-add to our object collection
if ((pname == "Name") || (pname == "def:Name"))
{
refName = pvalue;
// AddInstance(pvalue, ret);
}
}
else if (ei != null)
{
// it's an event!
string src = pvalue;
string methodName = String.Empty;
object sink = eventSink;
if ((StringHelpers.BeginsWith(src, '{')) && (StringHelpers.EndsWith(src, '}')))
{
src = StringHelpers.Between(src, '{', '}');
}
if (src.IndexOf('.') != -1)
{
string[] handler = src.Split('.');
src = handler[0];
methodName = handler[1];
sink = GetInstance(src);
}
else
{
methodName = src;
}
OnAssignEvent(ei, ret, sink, src, methodName);
}
else
{
// auto-add to our object collection
if ((pname == "Name") || (pname == "def:Name"))
{
refName = pvalue;
// AddInstance(pvalue, ret);
}
else if (pname == "ref:Name")
{
// Do nothing.
}
else
{
if (!OnUnknownProperty(pname, ret, pvalue))
{
// who knows what it is???
Trace.Fail("Failed acquiring property information for '" + pname + "' with value '"+pvalue+"'");
}
}
}
}
return refName;
}
}
}
| |
new SimGroup(TPG_LayerGroup_Saved) {
canSave = "1";
canSaveDynamicFields = "1";
new ScriptObject() {
internalName = "Layer_191";
canSave = "1";
canSaveDynamicFields = "1";
activeCtrl = "59141";
coverage = "99";
fieldsValidated = "1";
heightMax = "50";
heightMin = "0";
Inactive = "1";
isValidated = "1";
matIndex = "8";
matInternalName = "gvSandGrain01";
matObject = "3332";
pill = "59139";
slopeMax = "90";
slopeMin = "0";
};
new ScriptObject() {
internalName = "Layer_192";
canSave = "1";
canSaveDynamicFields = "1";
activeCtrl = "59169";
coverage = "33";
fieldsValidated = "1";
heightMax = "50";
heightMin = "0";
Inactive = "1";
isValidated = "1";
matIndex = "3";
matInternalName = "gvDirt01_Rocky";
matObject = "3331";
pill = "59167";
slopeMax = "90";
slopeMin = "0";
};
new ScriptObject() {
internalName = "Layer_193";
canSave = "1";
canSaveDynamicFields = "1";
activeCtrl = "59203";
coverage = "33";
fieldsValidated = "1";
heightMax = "54";
heightMin = "47";
Inactive = "1";
isValidated = "1";
matIndex = "4";
matInternalName = "gvGrassMeadow02_Dirty";
matObject = "3307";
pill = "59201";
slopeMax = "90";
slopeMin = "0";
};
new ScriptObject() {
internalName = "Layer_194";
canSave = "1";
canSaveDynamicFields = "1";
activeCtrl = "59231";
coverage = "33";
fieldsValidated = "1";
heightMax = "52";
heightMin = "48";
Inactive = "1";
isValidated = "1";
matIndex = "3";
matInternalName = "gvDirt01_Rocky";
matObject = "3331";
pill = "59229";
slopeMax = "90";
slopeMin = "0";
};
new ScriptObject() {
internalName = "Layer_195";
canSave = "1";
canSaveDynamicFields = "1";
activeCtrl = "59385";
coverage = "33";
fieldsValidated = "1";
heightMax = "55";
heightMin = "50";
Inactive = "1";
isValidated = "1";
matIndex = "2";
matInternalName = "gvGrassMeadow01_Dirt";
matObject = "3305";
pill = "59383";
slopeMax = "90";
slopeMin = "0";
};
new ScriptObject() {
internalName = "Layer_196";
canSave = "1";
canSaveDynamicFields = "1";
activeCtrl = "59413";
coverage = "80";
fieldsValidated = "1";
heightMax = "66";
heightMin = "50";
Inactive = "1";
isValidated = "1";
matIndex = "1";
matInternalName = "gvGrassMeadow01";
matObject = "3304";
pill = "59411";
slopeMax = "90";
slopeMin = "0";
};
new ScriptObject() {
internalName = "Layer_197";
canSave = "1";
canSaveDynamicFields = "1";
activeCtrl = "59473";
coverage = "99";
fieldsValidated = "1";
heightMax = "193.16";
heightMin = "0";
Inactive = "1";
isValidated = "1";
matIndex = "6";
matInternalName = "gvCliff02_v";
matObject = "3325";
pill = "59471";
slopeMax = "90";
slopeMin = "34";
};
new ScriptObject() {
internalName = "Layer_198";
canSave = "1";
canSaveDynamicFields = "1";
activeCtrl = "59514";
coverage = "50";
fieldsValidated = "1";
heightMax = "1000";
heightMin = "0";
Inactive = "1";
isValidated = "1";
matIndex = "5";
matInternalName = "gvCliff02";
matObject = "3321";
pill = "59512";
slopeMax = "42";
slopeMin = "35";
};
new ScriptObject() {
internalName = "Layer_199";
canSave = "1";
canSaveDynamicFields = "1";
activeCtrl = "59542";
coverage = "99";
fieldsValidated = "1";
heightMax = "1000";
heightMin = "0";
Inactive = "1";
isValidated = "1";
matIndex = "7";
matInternalName = "gvCliff01";
matObject = "3324";
pill = "59540";
slopeMax = "38";
slopeMin = "27";
};
new ScriptObject() {
internalName = "Layer_200";
canSave = "1";
canSaveDynamicFields = "1";
activeCtrl = "59579";
coverage = "22";
fieldsValidated = "1";
heightMax = "1000";
heightMin = "0";
Inactive = "1";
isValidated = "1";
matIndex = "3";
matInternalName = "gvDirt01_Rocky";
matObject = "3331";
pill = "59577";
slopeMax = "44";
slopeMin = "27";
};
new ScriptObject() {
internalName = "Layer_201";
canSave = "1";
canSaveDynamicFields = "1";
activeCtrl = "59649";
coverage = "44";
fieldsValidated = "1";
heightMax = "1000";
heightMin = "0";
Inactive = "0";
isValidated = "0";
matIndex = "3";
matInternalName = "gvDirt01_Rocky";
matObject = "3331";
pill = "59647";
slopeMax = "27";
slopeMin = "22";
};
};
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// File: LengthConverter.cs
//
// Description: Contains the LengthConverter: TypeConverter for the Length class.
//
// History:
// 06/27/2003 : wwilaria - Initial implementation
//
//---------------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Windows;
using System.Windows.Markup;
using System.Security;
using MS.Internal;
using MS.Utility;
namespace System.Windows
{
/// <summary>
/// LengthConverter - Converter class for converting instances of other types to and from double representing length.
/// </summary>
public class LengthConverter: TypeConverter
{
//-------------------------------------------------------------------
//
// Public Methods
//
//-------------------------------------------------------------------
#region Public Methods
/// <summary>
/// CanConvertFrom - Returns whether or not this class can convert from a given type.
/// </summary>
/// <returns>
/// bool - True if thie converter can convert from the provided type, false if not.
/// </returns>
/// <param name="typeDescriptorContext"> The ITypeDescriptorContext for this call. </param>
/// <param name="sourceType"> The Type being queried for support. </param>
public override bool CanConvertFrom(ITypeDescriptorContext typeDescriptorContext, Type sourceType)
{
// We can only handle strings, integral and floating types
TypeCode tc = Type.GetTypeCode(sourceType);
switch (tc)
{
case TypeCode.String:
case TypeCode.Decimal:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return true;
default:
return false;
}
}
/// <summary>
/// CanConvertTo - Returns whether or not this class can convert to a given type.
/// </summary>
/// <returns>
/// bool - True if this converter can convert to the provided type, false if not.
/// </returns>
/// <param name="typeDescriptorContext"> The ITypeDescriptorContext for this call. </param>
/// <param name="destinationType"> The Type being queried for support. </param>
public override bool CanConvertTo(ITypeDescriptorContext typeDescriptorContext, Type destinationType)
{
// We can convert to an InstanceDescriptor or to a string.
if (destinationType == typeof(InstanceDescriptor) ||
destinationType == typeof(string))
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// ConvertFrom - Attempt to convert to a length from the given object
/// </summary>
/// <returns>
/// The double representing the size in 1/96th of an inch.
/// </returns>
/// <exception cref="ArgumentNullException">
/// An ArgumentNullException is thrown if the example object is null.
/// </exception>
/// <exception cref="ArgumentException">
/// An ArgumentException is thrown if the example object is not null and is not a valid type
/// which can be converted to a double.
/// </exception>
/// <param name="typeDescriptorContext"> The ITypeDescriptorContext for this call. </param>
/// <param name="cultureInfo"> The CultureInfo which is respected when converting. </param>
/// <param name="source"> The object to convert to a double. </param>
public override object ConvertFrom(ITypeDescriptorContext typeDescriptorContext,
CultureInfo cultureInfo,
object source)
{
if (source != null)
{
if (source is string) { return FromString((string)source, cultureInfo); }
else { return (double)(Convert.ToDouble(source, cultureInfo)); }
}
throw GetConvertFromException(source);
}
/// <summary>
/// ConvertTo - Attempt to convert a double to the given type
/// </summary>
/// <returns>
/// The object which was constructed.
/// </returns>
/// <exception cref="ArgumentNullException">
/// An ArgumentNullException is thrown if the example object is null.
/// </exception>
/// <exception cref="ArgumentException">
/// An ArgumentException is thrown if the object is not null,
/// or if the destinationType isn't one of the valid destination types.
/// </exception>
/// <param name="typeDescriptorContext"> The ITypeDescriptorContext for this call. </param>
/// <param name="cultureInfo"> The CultureInfo which is respected when converting. </param>
/// <param name="value"> The double to convert. </param>
/// <param name="destinationType">The type to which to convert the double. </param>
///<SecurityNote>
/// Critical: calls InstanceDescriptor ctor which LinkDemands
/// PublicOK: can only make an InstanceDescriptor for double, not an arbitrary class
///</SecurityNote>
[SecurityCritical]
public override object ConvertTo(ITypeDescriptorContext typeDescriptorContext,
CultureInfo cultureInfo,
object value,
Type destinationType)
{
if (destinationType == null)
{
throw new ArgumentNullException("destinationType");
}
if ( value != null
&& value is double )
{
double l = (double)value;
if (destinationType == typeof(string))
{
if(DoubleUtil.IsNaN(l))
return "Auto";
else
return Convert.ToString(l, cultureInfo);
}
else if (destinationType == typeof(InstanceDescriptor))
{
ConstructorInfo ci = typeof(double).GetConstructor(new Type[] { typeof(double) });
return new InstanceDescriptor(ci, new object[] { l });
}
}
throw GetConvertToException(value, destinationType);
}
#endregion
//-------------------------------------------------------------------
//
// Internal Methods
//
//-------------------------------------------------------------------
#region Internal Methods
// Parse a Length from a string given the CultureInfo.
// Formats:
//"[value][unit]"
// [value] is a double
// [unit] is a string specifying the unit, like 'in' or 'px', or nothing (means pixels)
// NOTE - This code is called from FontSizeConverter, so changes will affect both.
static internal double FromString(string s, CultureInfo cultureInfo)
{
string valueString = s.Trim();
string goodString = valueString.ToLowerInvariant();
int strLen = goodString.Length;
int strLenUnit = 0;
double unitFactor = 1.0;
//Auto is represented and Double.NaN
//properties that do not want Auto and NaN to be in their ligit values,
//should disallow NaN in validation callbacks (same goes for negative values)
if (goodString == "auto") return Double.NaN;
for (int i = 0; i < PixelUnitStrings.Length; i++)
{
// NOTE: This is NOT a culture specific comparison.
// This is by design: we want the same unit string table to work across all cultures.
if (goodString.EndsWith(PixelUnitStrings[i], StringComparison.Ordinal))
{
strLenUnit = PixelUnitStrings[i].Length;
unitFactor = PixelUnitFactors[i];
break;
}
}
// important to substring original non-lowered string
// this allows case sensitive ToDouble below handle "NaN" and "Infinity" correctly.
// this addresses windows bug 1177408
valueString = valueString.Substring(0, strLen - strLenUnit);
// FormatException errors thrown by Convert.ToDouble are pretty uninformative.
// Throw a more meaningful error in this case that tells that we were attempting
// to create a Length instance from a string. This addresses windows bug 968884
try
{
double result = Convert.ToDouble(valueString, cultureInfo) * unitFactor;
return result;
}
catch (FormatException)
{
throw new FormatException(SR.Get(SRID.LengthFormatError, valueString));
}
}
// This array contains strings for unit types
// These are effectively "TypeConverter only" units.
// They are all expressable in terms of the Pixel unit type and a conversion factor.
static private string[] PixelUnitStrings = { "px", "in", "cm", "pt" };
static private double[] PixelUnitFactors =
{
1.0, // Pixel itself
96.0, // Pixels per Inch
96.0 / 2.54, // Pixels per Centimeter
96.0 / 72.0, // Pixels per Point
};
static internal string ToString(double l, CultureInfo cultureInfo)
{
if(DoubleUtil.IsNaN(l)) return "Auto";
return Convert.ToString(l, cultureInfo);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using Sandbox.Common.ObjectBuilders;
using Sandbox.ModAPI;
using VRageMath;
using VRage.ModAPI;
using VRage.ObjectBuilders;
using VRage.Game.Components;
using Sandbox.Definitions;
using ParallelTasks;
using System.Text.RegularExpressions;
using System.Globalization;
using VRage.Game;
using VRage.Game.ModAPI;
using Sandbox.ModAPI.Interfaces.Terminal;
using VRage.Utils;
namespace Hologram
{
[MyEntityComponentDescriptor(typeof(MyObjectBuilder_TextPanel), true)]
class Holo : MyGameLogicComponent
{
private MyObjectBuilder_EntityBase objectBuilder;
private HashSet<IMyEntity> deletecache = new HashSet<IMyEntity>();
private IMyTextPanel panel;
private string privateradarid = "";
private string publicradarid = "";
private bool valid = false;
private bool readyPing = false;
private Task task;
private double m_scale = 0.05;
private double m_adj_u = 0d;
private double m_adj_d = 0d;
private double m_adj_l = 0d;
private double m_adj_r = 0d;
private double m_adj_f = 0d;
private double m_adj_b = 0d;
private bool initDirty = true;
private bool updateHook = false;
//private Dictionary<RadarResult.SweepLocation, IMyEntity> projections = new Dictionary<RadarResult.SweepLocation, IMyEntity>();
private Dictionary<Vector3I, ResultType> color = new Dictionary<Vector3I, ResultType>();
HoloSetting PrivateAdjust = new HoloSetting();
HoloSetting PublicAdjust = new HoloSetting();
HoloSetting ActiveAdjust = new HoloSetting();
IMyGridTerminalSystem system;
//RadarResult.SweepLocation currentLocation = 0;
private double Scale
{
get { return m_scale * ActiveAdjust.S; }
set
{
if (m_scale > 0.001) m_scale = value;
}
}
private int lastid = 65555;
private long lastEntity = 0;
private string lastTitle = "";
private int sweepcount = 0;
public override MyObjectBuilder_EntityBase GetObjectBuilder(bool copy = false)
{
return copy ? (MyObjectBuilder_EntityBase)objectBuilder.Clone() : objectBuilder;
}
public override void Init(MyObjectBuilder_EntityBase objectBuilder)
{
this.objectBuilder = objectBuilder;
Entity.NeedsUpdate |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME;
}
public override void UpdateOnceBeforeFrame()
{
try
{
panel = (IMyTextPanel)Entity;
initBlockSettings();
if (panel.BlockDefinition.SubtypeName.EndsWith("_DS_HOLO") || valid)
{
valid = true;
Entity.NeedsUpdate |= MyEntityUpdateEnum.EACH_10TH_FRAME;//update the block.
CreateTerminalControls<IMyTextPanel>();
updateHook = true;
CoreHolo.UpdateHook += Update;//constrain its position
}
}
catch (Exception ex)
{
Log.DebugWrite(DebugLevel.Error, ex);
}
}
protected static List<Type> m_ControlsInited = new List<Type>();
protected static IMyTerminalControlSeparator Seperator;
//protected static IMyTerminalControlCheckbox YawCheck, PitchCheck, RollCheck, InvertCheck, InvertRollCheck;
protected static IMyTerminalControlSlider RangeControl;
//protected static IMyTerminalControlButton SaveButton;
protected void CreateTerminalControls<T>()
{
if (m_ControlsInited.Contains(typeof(T))) return;
m_ControlsInited.Add(typeof(T));
//if (Seperator == null)
//{
// Seperator = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSeparator, IMyTerminalBlock>(string.Empty);
// Seperator.Visible = (b) => b.IsHoloTable();
//}
//MyAPIGateway.TerminalControls.AddControl<T>(Seperator);
//if (RangeControl == null)
//{
// RangeControl = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSlider, IMyTerminalBlock>("Draygo.ControlSurface.Trim");
// RangeControl.Visible = (b) => b.IsHoloTable();
// RangeControl.Enabled = (b) => b.IsHoloTable() && b.IsWorking;
// RangeControl.Getter = (b) => b.GameLogic.GetAs<Holo>().Control.Trim;
// RangeControl.Writer = (b, v) => v.Append(string.Format("{0:N1} {1}", b.GameLogic.GetAs<Holo>().Control.Trim, MyStringId.GetOrCompute("Degrees")));
// RangeControl.Setter = (b, v) => b.GameLogic.GetAs<Holo>().Control.TrimSet(v);
// RangeControl.Title = MyStringId.GetOrCompute("Range");
// RangeControl.Tooltip = MyStringId.GetOrCompute("Range in KM");
// RangeControl.SupportsMultipleBlocks = true;
// RangeControl.SetLimits(0.0f, 50.0f);
//}
//MyAPIGateway.TerminalControls.AddControl<T>(RangeControl);
//if (PitchCheck == null)
//{
// PitchCheck = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlCheckbox, IMyTerminalBlock>("Draygo.ControlSurface.Pitch");
// PitchCheck.Visible = (b) => b.IsControlSurface();
// PitchCheck.Enabled = (b) => b.IsControlSurface() && b.IsWorking;
// PitchCheck.Getter = (b) => b.GameLogic.GetAs<Holo>().Control.EnablePitch;
// PitchCheck.Setter = (b, v) => b.GameLogic.GetAs<Holo>().Control.EnablePitch = v;
// PitchCheck.Title = MyStringId.GetOrCompute("Pitch");
// PitchCheck.Tooltip = MyStringId.GetOrCompute("Enable Pitch Control");
// PitchCheck.SupportsMultipleBlocks = true;
//}
//MyAPIGateway.TerminalControls.AddControl<T>(PitchCheck);
//var TrimProperty = MyAPIGateway.TerminalControls.CreateProperty<float, T>("Range");
//if (TrimProperty != null)
//{
// TrimProperty.Enabled = (b) => b.IsHoloTable() && b.IsWorking;
// TrimProperty.Getter = (b) => b.GameLogic.GetAs<Holo>().Control.Trim;
// TrimProperty.Setter = (b, v) => b.GameLogic.GetAs<Holo>().Control.TrimSet(v);
// MyAPIGateway.TerminalControls.AddControl<T>(TrimProperty);
//}
}
internal static void RedrawControls()
{
if (RangeControl != null) RangeControl.UpdateVisual();
}
private void initBlockSettings()
{
try
{
MyCubeBlockDefinition blockDefinition = null;
if (MyDefinitionManager.Static.TryGetCubeBlockDefinition(panel.BlockDefinition, out blockDefinition))
{
var descriptionStr = blockDefinition.DescriptionString;
initDirty = false;
Regex reg = new Regex("holo{(.*?)}");
Regex regcom = new Regex(";");
Regex regeq = new Regex("=");
if (descriptionStr == null || descriptionStr.Length == 0) return;
var res = reg.Split(descriptionStr);
if (res.Length > 1)
{
var search = regcom.Split(res[1]);
if (search == null) return;
foreach (string parts in search)
{
var dataeq = regeq.Split(parts);
if (dataeq.Length == 0) continue;
switch (dataeq[0].ToLower())
{
case "holo":
if (dataeq[1].ToLowerInvariant() == "y") valid = true;
if (dataeq[1].ToLowerInvariant() == "yes") valid = true;
if (dataeq[1].ToLowerInvariant() == "t") valid = true;
if (dataeq[1].ToLowerInvariant() == "tru") valid = true;
if (dataeq[1].ToLowerInvariant() == "true") valid = true;
break;
case "u":
case "up":
case "offsetup":
m_adj_u = Convert.ToDouble(dataeq[1], new CultureInfo("en-US"));
break;
case "d":
case "down":
case "offsetdown":
m_adj_d = Convert.ToDouble(dataeq[1], new CultureInfo("en-US"));
break;
case "l":
case "left":
case "offsetleft":
m_adj_l = Convert.ToDouble(dataeq[1], new CultureInfo("en-US"));
break;
case "r":
case "right":
case "offsetright":
m_adj_r = Convert.ToDouble(dataeq[1], new CultureInfo("en-US"));
break;
case "f":
case "forward":
case "offsetforward":
m_adj_f = Convert.ToDouble(dataeq[1], new CultureInfo("en-US"));
break;
case "b":
case "backward":
case "offsetback":
case "offsetbackward":
m_adj_b = Convert.ToDouble(dataeq[1], new CultureInfo("en-US"));
break;
case "scale":
Scale = Convert.ToDouble(dataeq[1], new CultureInfo("en-US")) * 0.05d;
break;
}
}
}
}
}
catch (Exception ex)
{
initDirty = false;
Scale = 0.05;
m_adj_r = 0;
m_adj_l = 0;
m_adj_d = 0;
m_adj_u = 0;
m_adj_f = 0;
m_adj_b = 0;
Log.DebugWrite(DebugLevel.Error, "ERROR in definition, could not init check definition description for correct format. " + ex.ToString());
}
}
public void Update()
{
if (Entity == null || Entity.Closed || Entity.MarkedForClose)
{
if (updateHook)
{
updateHook = false;
if (CoreHolo.UpdateHook != null) CoreHolo.UpdateHook -= Update;
return;
}
}
if (!valid) return;
if (initDirty) initBlockSettings();
if (CoreHolo.instance == null) return;
if (CoreHolo.instance.isDedicated)
{
//Entity.NeedsUpdate &= ~MyEntityUpdateEnum.EACH_FRAME;
if (updateHook)
{
updateHook = false;
if (CoreHolo.UpdateHook != null) CoreHolo.UpdateHook -= Update;
return;
}
return;
}
if (panel.IsWorking) moveProjection();
}
private void getRadarValues()
{
var privatetitle = panel.CustomData;
var publictitle = panel.GetPublicTitle();
try
{
HoloSetting PlayerAdjust;
privateradarid = parseSettingsString(privatetitle, out PlayerAdjust);
PrivateAdjust = PlayerAdjust;
publicradarid = parseSettingsString(publictitle, out PlayerAdjust);
PublicAdjust = PlayerAdjust;
}
catch
{
//do nothing.
}
}
private string parseSettingsString(string title, out HoloSetting Adjust)
{
//Log.DebugWrite(DebugLevel.Info, "parseSettingsString");
HoloSetting adj = new HoloSetting();
Regex reg = new Regex("(.*?)\\[(.*?)\\]");
Regex regcom = new Regex(";");
Regex regeq = new Regex("=");
string foundtitle = "";
Adjust = adj;
if (title == null || title.Length == 0) return foundtitle;
var res = reg.Split(title);
//Log.DebugWrite(DebugLevel.Info, res.Length);
if (res.Length > 2)
{
foreach (var word in res)
{
Log.DebugWrite(DebugLevel.Info, word);
}
foundtitle = res[1];
//Log.DebugWrite(DebugLevel.Info, "settings:" + res[2]);
var search = regcom.Split(res[2]);
if (search == null) return foundtitle.ToLowerInvariant().Trim();
foreach (string parts in search)
{
var dataeq = regeq.Split(parts);
if (dataeq.Length == 0) continue;
try
{
switch (dataeq[0].ToLower())
{
case "u":
case "up":
case "offsetup":
Adjust.U = Convert.ToDouble(dataeq[1], new CultureInfo("en-US"));
break;
case "d":
case "down":
case "offsetdown":
Adjust.D = Convert.ToDouble(dataeq[1], new CultureInfo("en-US"));
break;
case "l":
case "left":
case "offsetleft":
Adjust.L = Convert.ToDouble(dataeq[1], new CultureInfo("en-US"));
break;
case "r":
case "right":
case "offsetright":
Adjust.R = Convert.ToDouble(dataeq[1], new CultureInfo("en-US"));
break;
case "f":
case "forward":
case "offsetforward":
Adjust.F = Convert.ToDouble(dataeq[1], new CultureInfo("en-US"));
break;
case "b":
case "backward":
case "offsetbackward":
Adjust.B = Convert.ToDouble(dataeq[1], new CultureInfo("en-US"));
break;
case "s":
case "scale":
Adjust.S = Convert.ToDouble(dataeq[1], new CultureInfo("en-US"));
break;
}
}
catch
{
//catching stupid.
}
}
}
else
if (res.Length >= 1) foundtitle = res[0];
return foundtitle.ToLowerInvariant().Trim();
}
public override void UpdateBeforeSimulation10()
{
if (Entity == null) return;
if (panel == null) return;
if (CoreHolo.instance == null) return;
if (!valid) return;
if (CoreHolo.instance.isDedicated)
{
//cleanProjections();
return;
}
if (!panel.IsWorking)
{
//cleanProjections();
return;
}
if (!CoreHolo.ClosetoPlayer(Entity.WorldMatrix.Translation, 30))
{
//cleanProjections();
return;
}
long ent = 0;
//refresh
system = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid((IMyCubeGrid)panel.CubeGrid);
List<IMyTerminalBlock> blocks = new List<IMyTerminalBlock>();
system.GetBlocksOfType<IMySensorBlock>(blocks, null);
getRadarValues();
foreach (var block in blocks)
{
var sens = (IMySensorBlock)block;
if (sens.OwnerId == panel.OwnerId)
{
if (sens.CustomName.ToLowerInvariant().Trim() == privateradarid)
{
ent = sens.EntityId;
ActiveAdjust = PrivateAdjust;
break;
}
if (sens.CustomName.ToLowerInvariant().Trim() == publicradarid)
{
//allow public title to get the entity id as well.
ActiveAdjust = PublicAdjust;
ent = sens.EntityId;
}
}
}
Log.DebugWrite(DebugLevel.Verbose, "Entityid " + ent.ToString());
if (ent != 0)
{
var data = CoreHolo.GetRadar(ent);
//MyAPIGateway.Utilities.ShowMessage("Radar?", (data?.RadarData == null).ToString());
if (data != null && data.RadarData != null)
{
color = data.RadarData.ColorData;
//MyAPIGateway.Utilities.ShowMessage("Count", color.Count.ToString());
}
else
cleanDraws();
}
else
cleanDraws();
}
private Vector3D adjustvector(Vector3D vec, MatrixD worldMatrix)
{
if (m_adj_f + ActiveAdjust.F != 0) vec = vec + Vector3D.Multiply(worldMatrix.Forward, m_adj_f + ActiveAdjust.F);
if (m_adj_b + ActiveAdjust.B != 0) vec = vec + -Vector3D.Multiply(worldMatrix.Forward, m_adj_b + ActiveAdjust.B);
if (m_adj_u + ActiveAdjust.U != 0) vec = vec + Vector3D.Multiply(worldMatrix.Up, m_adj_u + ActiveAdjust.U);
if (m_adj_d + ActiveAdjust.D != 0) vec = vec + -Vector3D.Multiply(worldMatrix.Up, m_adj_d + ActiveAdjust.D);
if (m_adj_l + ActiveAdjust.L != 0) vec = vec + Vector3D.Multiply(worldMatrix.Left, m_adj_l + ActiveAdjust.L);
if (m_adj_r + ActiveAdjust.R != 0) vec = vec + -Vector3D.Multiply(worldMatrix.Left, m_adj_r + ActiveAdjust.R);
return vec;
}
private void moveProjection()
{
Log.DebugWrite(DebugLevel.Verbose, "MP getting scales: {0}" + Scale.ToString());
//if (scale == 0.5d) initBlockSettings();//try again!?
advDraw();
}
private void cleanDraws()
{
color.Clear();
}
private void advDraw()
{
if (MyAPIGateway.Session == null) return;
if (MyAPIGateway.Session.Player == null) return;
MatrixD mat = MatrixD.CreateWorld(adjustvector(panel.WorldMatrix.Translation, panel.WorldMatrix), new Vector3(0, 0, 1), new Vector3(0, 1, 0));
Vector3D trans = mat.Translation;
BoundingBoxD bb = new BoundingBoxD(new Vector3D(0), new Vector3D(Scale / 2));
bb = new BoundingBoxD(-bb.Center, bb.Center);
SortedSet<PointStruct> set = new SortedSet<PointStruct>(new PointComparer());
Vector3D playerpos = MyAPIGateway.Session.Player.GetPosition();
foreach (KeyValuePair<Vector3I, ResultType> kvp in color)
{
PointStruct point;
point.Value = trans + ((Vector3D)kvp.Key * (Scale / 2));
point.Key = Vector3D.Distance(point.Value, playerpos);
point.Color = RadarResult.getColor(kvp.Value);
set.Add(point);
}
//MyAPIGateway.Utilities.ShowMessage("Draw Call", color.Count.ToString());
foreach (var value in set.Reverse())
{
mat.Translation = value.Value;
Color _color = value.Color;
MySimpleObjectDraw.DrawTransparentBox(ref mat, ref bb, ref _color, MySimpleObjectRasterizer.Solid, 0, 0, null, null, false, -1);
}
}
public override void Close()
{
//cleanProjections();
if (updateHook)
{
updateHook = false;
if (CoreHolo.UpdateHook != null) CoreHolo.UpdateHook -= Update;
}
}
}
struct PointStruct
{
internal const double increment = 0.001d;
internal Color Color;
internal double Key;
internal Vector3D Value;
}
class PointComparer : Comparer<PointStruct>
{
public override int Compare(PointStruct x, PointStruct y)
{
int retVal = 0;
retVal = Comparer<double>.Default.Compare(x.Key, y.Key);
while (retVal == 0)
{
y.Key += PointStruct.increment;
retVal = Comparer<double>.Default.Compare(x.Key, y.Key);
}
return retVal;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Net.Http
{
public partial class ByteArrayContent : System.Net.Http.HttpContent
{
public ByteArrayContent(byte[] content) { }
public ByteArrayContent(byte[] content, int offset, int count) { }
protected override System.Threading.Tasks.Task<System.IO.Stream> CreateContentReadStreamAsync() { throw null; }
protected override System.Threading.Tasks.Task SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext context) { throw null; }
protected internal override bool TryComputeLength(out long length) { length = default(long); throw null; }
}
public enum ClientCertificateOption
{
Automatic = 1,
Manual = 0,
}
public abstract partial class DelegatingHandler : System.Net.Http.HttpMessageHandler
{
protected DelegatingHandler() { }
protected DelegatingHandler(System.Net.Http.HttpMessageHandler innerHandler) { }
public System.Net.Http.HttpMessageHandler InnerHandler { get { throw null; } set { } }
protected override void Dispose(bool disposing) { }
protected internal override System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { throw null; }
}
public partial class FormUrlEncodedContent : System.Net.Http.ByteArrayContent
{
public FormUrlEncodedContent(System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, string>> nameValueCollection) : base (default(byte[])) { }
}
public partial class HttpClient : System.Net.Http.HttpMessageInvoker
{
public HttpClient() : base (default(System.Net.Http.HttpMessageHandler)) { }
public HttpClient(System.Net.Http.HttpMessageHandler handler) : base (default(System.Net.Http.HttpMessageHandler)) { }
public HttpClient(System.Net.Http.HttpMessageHandler handler, bool disposeHandler) : base (default(System.Net.Http.HttpMessageHandler)) { }
public System.Uri BaseAddress { get { throw null; } set { } }
public System.Net.Http.Headers.HttpRequestHeaders DefaultRequestHeaders { get { throw null; } }
public long MaxResponseContentBufferSize { get { throw null; } set { } }
public System.TimeSpan Timeout { get { throw null; } set { } }
public void CancelPendingRequests() { }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> DeleteAsync(string requestUri) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> DeleteAsync(string requestUri, System.Threading.CancellationToken cancellationToken) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> DeleteAsync(System.Uri requestUri) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> DeleteAsync(System.Uri requestUri, System.Threading.CancellationToken cancellationToken) { throw null; }
protected override void Dispose(bool disposing) { }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(string requestUri) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(string requestUri, System.Net.Http.HttpCompletionOption completionOption) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(string requestUri, System.Net.Http.HttpCompletionOption completionOption, System.Threading.CancellationToken cancellationToken) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(string requestUri, System.Threading.CancellationToken cancellationToken) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(System.Uri requestUri) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(System.Uri requestUri, System.Net.Http.HttpCompletionOption completionOption) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(System.Uri requestUri, System.Net.Http.HttpCompletionOption completionOption, System.Threading.CancellationToken cancellationToken) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(System.Uri requestUri, System.Threading.CancellationToken cancellationToken) { throw null; }
public System.Threading.Tasks.Task<byte[]> GetByteArrayAsync(string requestUri) { throw null; }
public System.Threading.Tasks.Task<byte[]> GetByteArrayAsync(System.Uri requestUri) { throw null; }
public System.Threading.Tasks.Task<System.IO.Stream> GetStreamAsync(string requestUri) { throw null; }
public System.Threading.Tasks.Task<System.IO.Stream> GetStreamAsync(System.Uri requestUri) { throw null; }
public System.Threading.Tasks.Task<string> GetStringAsync(string requestUri) { throw null; }
public System.Threading.Tasks.Task<string> GetStringAsync(System.Uri requestUri) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PostAsync(string requestUri, System.Net.Http.HttpContent content) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PostAsync(string requestUri, System.Net.Http.HttpContent content, System.Threading.CancellationToken cancellationToken) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PostAsync(System.Uri requestUri, System.Net.Http.HttpContent content) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PostAsync(System.Uri requestUri, System.Net.Http.HttpContent content, System.Threading.CancellationToken cancellationToken) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PutAsync(string requestUri, System.Net.Http.HttpContent content) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PutAsync(string requestUri, System.Net.Http.HttpContent content, System.Threading.CancellationToken cancellationToken) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PutAsync(System.Uri requestUri, System.Net.Http.HttpContent content) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PutAsync(System.Uri requestUri, System.Net.Http.HttpContent content, System.Threading.CancellationToken cancellationToken) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Net.Http.HttpCompletionOption completionOption) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Net.Http.HttpCompletionOption completionOption, System.Threading.CancellationToken cancellationToken) { throw null; }
public override System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { throw null; }
}
public partial class HttpClientHandler : System.Net.Http.HttpMessageHandler
{
public HttpClientHandler() { }
public bool AllowAutoRedirect { get { throw null; } set { } }
public System.Net.DecompressionMethods AutomaticDecompression { get { throw null; } set { } }
public System.Net.Http.ClientCertificateOption ClientCertificateOptions { get { throw null; } set { } }
public System.Net.CookieContainer CookieContainer { get { throw null; } set { } }
public System.Net.ICredentials Credentials { get { throw null; } set { } }
public int MaxAutomaticRedirections { get { throw null; } set { } }
public long MaxRequestContentBufferSize { get { throw null; } set { } }
public bool PreAuthenticate { get { throw null; } set { } }
public System.Net.IWebProxy Proxy { get { throw null; } set { } }
public virtual bool SupportsAutomaticDecompression { get { throw null; } }
public virtual bool SupportsProxy { get { throw null; } }
public virtual bool SupportsRedirectConfiguration { get { throw null; } }
public bool UseCookies { get { throw null; } set { } }
public bool UseDefaultCredentials { get { throw null; } set { } }
public bool UseProxy { get { throw null; } set { } }
protected override void Dispose(bool disposing) { }
protected internal override System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { throw null; }
}
public enum HttpCompletionOption
{
ResponseContentRead = 0,
ResponseHeadersRead = 1,
}
public abstract partial class HttpContent : System.IDisposable
{
protected HttpContent() { }
public System.Net.Http.Headers.HttpContentHeaders Headers { get { throw null; } }
public System.Threading.Tasks.Task CopyToAsync(System.IO.Stream stream) { throw null; }
public System.Threading.Tasks.Task CopyToAsync(System.IO.Stream stream, System.Net.TransportContext context) { throw null; }
protected virtual System.Threading.Tasks.Task<System.IO.Stream> CreateContentReadStreamAsync() { throw null; }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public System.Threading.Tasks.Task LoadIntoBufferAsync() { throw null; }
public System.Threading.Tasks.Task LoadIntoBufferAsync(long maxBufferSize) { throw null; }
public System.Threading.Tasks.Task<byte[]> ReadAsByteArrayAsync() { throw null; }
public System.Threading.Tasks.Task<System.IO.Stream> ReadAsStreamAsync() { throw null; }
public System.Threading.Tasks.Task<string> ReadAsStringAsync() { throw null; }
protected abstract System.Threading.Tasks.Task SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext context);
protected internal abstract bool TryComputeLength(out long length);
}
public abstract partial class HttpMessageHandler : System.IDisposable
{
protected HttpMessageHandler() { }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
protected internal abstract System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken);
}
public partial class HttpMessageInvoker : System.IDisposable
{
public HttpMessageInvoker(System.Net.Http.HttpMessageHandler handler) { }
public HttpMessageInvoker(System.Net.Http.HttpMessageHandler handler, bool disposeHandler) { }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public virtual System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { throw null; }
}
public partial class HttpMethod : System.IEquatable<System.Net.Http.HttpMethod>
{
public HttpMethod(string method) { }
public static System.Net.Http.HttpMethod Delete { get { throw null; } }
public static System.Net.Http.HttpMethod Get { get { throw null; } }
public static System.Net.Http.HttpMethod Head { get { throw null; } }
public string Method { get { throw null; } }
public static System.Net.Http.HttpMethod Options { get { throw null; } }
public static System.Net.Http.HttpMethod Post { get { throw null; } }
public static System.Net.Http.HttpMethod Put { get { throw null; } }
public static System.Net.Http.HttpMethod Trace { get { throw null; } }
public bool Equals(System.Net.Http.HttpMethod other) { throw null; }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(System.Net.Http.HttpMethod left, System.Net.Http.HttpMethod right) { throw null; }
public static bool operator !=(System.Net.Http.HttpMethod left, System.Net.Http.HttpMethod right) { throw null; }
public override string ToString() { throw null; }
}
public partial class HttpRequestException : System.Exception
{
public HttpRequestException() { }
public HttpRequestException(string message) { }
public HttpRequestException(string message, System.Exception inner) { }
}
public partial class HttpRequestMessage : System.IDisposable
{
public HttpRequestMessage() { }
public HttpRequestMessage(System.Net.Http.HttpMethod method, string requestUri) { }
public HttpRequestMessage(System.Net.Http.HttpMethod method, System.Uri requestUri) { }
public System.Net.Http.HttpContent Content { get { throw null; } set { } }
public System.Net.Http.Headers.HttpRequestHeaders Headers { get { throw null; } }
public System.Net.Http.HttpMethod Method { get { throw null; } set { } }
public System.Collections.Generic.IDictionary<string, object> Properties { get { throw null; } }
public System.Uri RequestUri { get { throw null; } set { } }
public System.Version Version { get { throw null; } set { } }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public override string ToString() { throw null; }
}
public partial class HttpResponseMessage : System.IDisposable
{
public HttpResponseMessage() { }
public HttpResponseMessage(System.Net.HttpStatusCode statusCode) { }
public System.Net.Http.HttpContent Content { get { throw null; } set { } }
public System.Net.Http.Headers.HttpResponseHeaders Headers { get { throw null; } }
public bool IsSuccessStatusCode { get { throw null; } }
public string ReasonPhrase { get { throw null; } set { } }
public System.Net.Http.HttpRequestMessage RequestMessage { get { throw null; } set { } }
public System.Net.HttpStatusCode StatusCode { get { throw null; } set { } }
public System.Version Version { get { throw null; } set { } }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public System.Net.Http.HttpResponseMessage EnsureSuccessStatusCode() { throw null; }
public override string ToString() { throw null; }
}
public abstract partial class MessageProcessingHandler : System.Net.Http.DelegatingHandler
{
protected MessageProcessingHandler() { }
protected MessageProcessingHandler(System.Net.Http.HttpMessageHandler innerHandler) { }
protected abstract System.Net.Http.HttpRequestMessage ProcessRequest(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken);
protected abstract System.Net.Http.HttpResponseMessage ProcessResponse(System.Net.Http.HttpResponseMessage response, System.Threading.CancellationToken cancellationToken);
protected internal sealed override System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { throw null; }
}
public partial class MultipartContent : System.Net.Http.HttpContent, System.Collections.Generic.IEnumerable<System.Net.Http.HttpContent>, System.Collections.IEnumerable
{
public MultipartContent() { }
public MultipartContent(string subtype) { }
public MultipartContent(string subtype, string boundary) { }
public virtual void Add(System.Net.Http.HttpContent content) { }
protected override void Dispose(bool disposing) { }
public System.Collections.Generic.IEnumerator<System.Net.Http.HttpContent> GetEnumerator() { throw null; }
protected override System.Threading.Tasks.Task SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext context) { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
protected internal override bool TryComputeLength(out long length) { length = default(long); throw null; }
}
public partial class MultipartFormDataContent : System.Net.Http.MultipartContent
{
public MultipartFormDataContent() { }
public MultipartFormDataContent(string boundary) { }
public override void Add(System.Net.Http.HttpContent content) { }
public void Add(System.Net.Http.HttpContent content, string name) { }
public void Add(System.Net.Http.HttpContent content, string name, string fileName) { }
}
public partial class StreamContent : System.Net.Http.HttpContent
{
public StreamContent(System.IO.Stream content) { }
public StreamContent(System.IO.Stream content, int bufferSize) { }
protected override System.Threading.Tasks.Task<System.IO.Stream> CreateContentReadStreamAsync() { throw null; }
protected override void Dispose(bool disposing) { }
protected override System.Threading.Tasks.Task SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext context) { throw null; }
protected internal override bool TryComputeLength(out long length) { length = default(long); throw null; }
}
public partial class StringContent : System.Net.Http.ByteArrayContent
{
public StringContent(string content) : base (default(byte[])) { }
public StringContent(string content, System.Text.Encoding encoding) : base (default(byte[])) { }
public StringContent(string content, System.Text.Encoding encoding, string mediaType) : base (default(byte[])) { }
}
}
namespace System.Net.Http.Headers
{
public partial class AuthenticationHeaderValue : System.ICloneable
{
public AuthenticationHeaderValue(string scheme) { }
public AuthenticationHeaderValue(string scheme, string parameter) { }
public string Parameter { get { throw null; } }
public string Scheme { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Net.Http.Headers.AuthenticationHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.AuthenticationHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.AuthenticationHeaderValue); throw null; }
}
public partial class CacheControlHeaderValue : System.ICloneable
{
public CacheControlHeaderValue() { }
public System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue> Extensions { get { throw null; } }
public System.Nullable<System.TimeSpan> MaxAge { get { throw null; } set { } }
public bool MaxStale { get { throw null; } set { } }
public System.Nullable<System.TimeSpan> MaxStaleLimit { get { throw null; } set { } }
public System.Nullable<System.TimeSpan> MinFresh { get { throw null; } set { } }
public bool MustRevalidate { get { throw null; } set { } }
public bool NoCache { get { throw null; } set { } }
public System.Collections.Generic.ICollection<string> NoCacheHeaders { get { throw null; } }
public bool NoStore { get { throw null; } set { } }
public bool NoTransform { get { throw null; } set { } }
public bool OnlyIfCached { get { throw null; } set { } }
public bool Private { get { throw null; } set { } }
public System.Collections.Generic.ICollection<string> PrivateHeaders { get { throw null; } }
public bool ProxyRevalidate { get { throw null; } set { } }
public bool Public { get { throw null; } set { } }
public System.Nullable<System.TimeSpan> SharedMaxAge { get { throw null; } set { } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Net.Http.Headers.CacheControlHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.CacheControlHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.CacheControlHeaderValue); throw null; }
}
public partial class ContentDispositionHeaderValue : System.ICloneable
{
protected ContentDispositionHeaderValue(System.Net.Http.Headers.ContentDispositionHeaderValue source) { }
public ContentDispositionHeaderValue(string dispositionType) { }
public System.Nullable<System.DateTimeOffset> CreationDate { get { throw null; } set { } }
public string DispositionType { get { throw null; } set { } }
public string FileName { get { throw null; } set { } }
public string FileNameStar { get { throw null; } set { } }
public System.Nullable<System.DateTimeOffset> ModificationDate { get { throw null; } set { } }
public string Name { get { throw null; } set { } }
public System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue> Parameters { get { throw null; } }
public System.Nullable<System.DateTimeOffset> ReadDate { get { throw null; } set { } }
public System.Nullable<long> Size { get { throw null; } set { } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Net.Http.Headers.ContentDispositionHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.ContentDispositionHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.ContentDispositionHeaderValue); throw null; }
}
public partial class ContentRangeHeaderValue : System.ICloneable
{
public ContentRangeHeaderValue(long length) { }
public ContentRangeHeaderValue(long from, long to) { }
public ContentRangeHeaderValue(long from, long to, long length) { }
public System.Nullable<long> From { get { throw null; } }
public bool HasLength { get { throw null; } }
public bool HasRange { get { throw null; } }
public System.Nullable<long> Length { get { throw null; } }
public System.Nullable<long> To { get { throw null; } }
public string Unit { get { throw null; } set { } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Net.Http.Headers.ContentRangeHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.ContentRangeHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.ContentRangeHeaderValue); throw null; }
}
public partial class EntityTagHeaderValue : System.ICloneable
{
public EntityTagHeaderValue(string tag) { }
public EntityTagHeaderValue(string tag, bool isWeak) { }
public static System.Net.Http.Headers.EntityTagHeaderValue Any { get { throw null; } }
public bool IsWeak { get { throw null; } }
public string Tag { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Net.Http.Headers.EntityTagHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.EntityTagHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.EntityTagHeaderValue); throw null; }
}
public sealed partial class HttpContentHeaders : System.Net.Http.Headers.HttpHeaders
{
internal HttpContentHeaders() { }
public System.Collections.Generic.ICollection<string> Allow { get { throw null; } }
public System.Net.Http.Headers.ContentDispositionHeaderValue ContentDisposition { get { throw null; } set { } }
public System.Collections.Generic.ICollection<string> ContentEncoding { get { throw null; } }
public System.Collections.Generic.ICollection<string> ContentLanguage { get { throw null; } }
public System.Nullable<long> ContentLength { get { throw null; } set { } }
public System.Uri ContentLocation { get { throw null; } set { } }
public byte[] ContentMD5 { get { throw null; } set { } }
public System.Net.Http.Headers.ContentRangeHeaderValue ContentRange { get { throw null; } set { } }
public System.Net.Http.Headers.MediaTypeHeaderValue ContentType { get { throw null; } set { } }
public System.Nullable<System.DateTimeOffset> Expires { get { throw null; } set { } }
public System.Nullable<System.DateTimeOffset> LastModified { get { throw null; } set { } }
}
public abstract partial class HttpHeaders : System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Collections.Generic.IEnumerable<string>>>, System.Collections.IEnumerable
{
protected HttpHeaders() { }
public void Add(string name, System.Collections.Generic.IEnumerable<string> values) { }
public void Add(string name, string value) { }
public void Clear() { }
public bool Contains(string name) { throw null; }
public System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<string, System.Collections.Generic.IEnumerable<string>>> GetEnumerator() { throw null; }
public System.Collections.Generic.IEnumerable<string> GetValues(string name) { throw null; }
public bool Remove(string name) { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public override string ToString() { throw null; }
public bool TryAddWithoutValidation(string name, System.Collections.Generic.IEnumerable<string> values) { throw null; }
public bool TryAddWithoutValidation(string name, string value) { throw null; }
public bool TryGetValues(string name, out System.Collections.Generic.IEnumerable<string> values) { values = default(System.Collections.Generic.IEnumerable<string>); throw null; }
}
public sealed partial class HttpHeaderValueCollection<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.IEnumerable where T : class
{
internal HttpHeaderValueCollection() { }
public int Count { get { throw null; } }
public bool IsReadOnly { get { throw null; } }
public void Add(T item) { }
public void Clear() { }
public bool Contains(T item) { throw null; }
public void CopyTo(T[] array, int arrayIndex) { }
public System.Collections.Generic.IEnumerator<T> GetEnumerator() { throw null; }
public void ParseAdd(string input) { }
public bool Remove(T item) { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public override string ToString() { throw null; }
public bool TryParseAdd(string input) { throw null; }
}
public sealed partial class HttpRequestHeaders : System.Net.Http.Headers.HttpHeaders
{
internal HttpRequestHeaders() { }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.MediaTypeWithQualityHeaderValue> Accept { get { throw null; } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.StringWithQualityHeaderValue> AcceptCharset { get { throw null; } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.StringWithQualityHeaderValue> AcceptEncoding { get { throw null; } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.StringWithQualityHeaderValue> AcceptLanguage { get { throw null; } }
public System.Net.Http.Headers.AuthenticationHeaderValue Authorization { get { throw null; } set { } }
public System.Net.Http.Headers.CacheControlHeaderValue CacheControl { get { throw null; } set { } }
public System.Net.Http.Headers.HttpHeaderValueCollection<string> Connection { get { throw null; } }
public System.Nullable<bool> ConnectionClose { get { throw null; } set { } }
public System.Nullable<System.DateTimeOffset> Date { get { throw null; } set { } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.NameValueWithParametersHeaderValue> Expect { get { throw null; } }
public System.Nullable<bool> ExpectContinue { get { throw null; } set { } }
public string From { get { throw null; } set { } }
public string Host { get { throw null; } set { } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.EntityTagHeaderValue> IfMatch { get { throw null; } }
public System.Nullable<System.DateTimeOffset> IfModifiedSince { get { throw null; } set { } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.EntityTagHeaderValue> IfNoneMatch { get { throw null; } }
public System.Net.Http.Headers.RangeConditionHeaderValue IfRange { get { throw null; } set { } }
public System.Nullable<System.DateTimeOffset> IfUnmodifiedSince { get { throw null; } set { } }
public System.Nullable<int> MaxForwards { get { throw null; } set { } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.NameValueHeaderValue> Pragma { get { throw null; } }
public System.Net.Http.Headers.AuthenticationHeaderValue ProxyAuthorization { get { throw null; } set { } }
public System.Net.Http.Headers.RangeHeaderValue Range { get { throw null; } set { } }
public System.Uri Referrer { get { throw null; } set { } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.TransferCodingWithQualityHeaderValue> TE { get { throw null; } }
public System.Net.Http.Headers.HttpHeaderValueCollection<string> Trailer { get { throw null; } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.TransferCodingHeaderValue> TransferEncoding { get { throw null; } }
public System.Nullable<bool> TransferEncodingChunked { get { throw null; } set { } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ProductHeaderValue> Upgrade { get { throw null; } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ProductInfoHeaderValue> UserAgent { get { throw null; } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ViaHeaderValue> Via { get { throw null; } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.WarningHeaderValue> Warning { get { throw null; } }
}
public sealed partial class HttpResponseHeaders : System.Net.Http.Headers.HttpHeaders
{
internal HttpResponseHeaders() { }
public System.Net.Http.Headers.HttpHeaderValueCollection<string> AcceptRanges { get { throw null; } }
public System.Nullable<System.TimeSpan> Age { get { throw null; } set { } }
public System.Net.Http.Headers.CacheControlHeaderValue CacheControl { get { throw null; } set { } }
public System.Net.Http.Headers.HttpHeaderValueCollection<string> Connection { get { throw null; } }
public System.Nullable<bool> ConnectionClose { get { throw null; } set { } }
public System.Nullable<System.DateTimeOffset> Date { get { throw null; } set { } }
public System.Net.Http.Headers.EntityTagHeaderValue ETag { get { throw null; } set { } }
public System.Uri Location { get { throw null; } set { } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.NameValueHeaderValue> Pragma { get { throw null; } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.AuthenticationHeaderValue> ProxyAuthenticate { get { throw null; } }
public System.Net.Http.Headers.RetryConditionHeaderValue RetryAfter { get { throw null; } set { } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ProductInfoHeaderValue> Server { get { throw null; } }
public System.Net.Http.Headers.HttpHeaderValueCollection<string> Trailer { get { throw null; } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.TransferCodingHeaderValue> TransferEncoding { get { throw null; } }
public System.Nullable<bool> TransferEncodingChunked { get { throw null; } set { } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ProductHeaderValue> Upgrade { get { throw null; } }
public System.Net.Http.Headers.HttpHeaderValueCollection<string> Vary { get { throw null; } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ViaHeaderValue> Via { get { throw null; } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.WarningHeaderValue> Warning { get { throw null; } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.AuthenticationHeaderValue> WwwAuthenticate { get { throw null; } }
}
public partial class MediaTypeHeaderValue : System.ICloneable
{
protected MediaTypeHeaderValue(System.Net.Http.Headers.MediaTypeHeaderValue source) { }
public MediaTypeHeaderValue(string mediaType) { }
public string CharSet { get { throw null; } set { } }
public string MediaType { get { throw null; } set { } }
public System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue> Parameters { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Net.Http.Headers.MediaTypeHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.MediaTypeHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.MediaTypeHeaderValue); throw null; }
}
public sealed partial class MediaTypeWithQualityHeaderValue : System.Net.Http.Headers.MediaTypeHeaderValue, System.ICloneable
{
public MediaTypeWithQualityHeaderValue(string mediaType) : base (default(System.Net.Http.Headers.MediaTypeHeaderValue)) { }
public MediaTypeWithQualityHeaderValue(string mediaType, double quality) : base (default(System.Net.Http.Headers.MediaTypeHeaderValue)) { }
public System.Nullable<double> Quality { get { throw null; } set { } }
public static new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.MediaTypeWithQualityHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue); throw null; }
}
public partial class NameValueHeaderValue : System.ICloneable
{
protected NameValueHeaderValue(System.Net.Http.Headers.NameValueHeaderValue source) { }
public NameValueHeaderValue(string name) { }
public NameValueHeaderValue(string name, string value) { }
public string Name { get { throw null; } }
public string Value { get { throw null; } set { } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Net.Http.Headers.NameValueHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.NameValueHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.NameValueHeaderValue); throw null; }
}
public partial class NameValueWithParametersHeaderValue : System.Net.Http.Headers.NameValueHeaderValue, System.ICloneable
{
protected NameValueWithParametersHeaderValue(System.Net.Http.Headers.NameValueWithParametersHeaderValue source) : base (default(string)) { }
public NameValueWithParametersHeaderValue(string name) : base (default(string)) { }
public NameValueWithParametersHeaderValue(string name, string value) : base (default(string)) { }
public System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue> Parameters { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static new System.Net.Http.Headers.NameValueWithParametersHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.NameValueWithParametersHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.NameValueWithParametersHeaderValue); throw null; }
}
public partial class ProductHeaderValue : System.ICloneable
{
public ProductHeaderValue(string name) { }
public ProductHeaderValue(string name, string version) { }
public string Name { get { throw null; } }
public string Version { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Net.Http.Headers.ProductHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.ProductHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.ProductHeaderValue); throw null; }
}
public partial class ProductInfoHeaderValue : System.ICloneable
{
public ProductInfoHeaderValue(System.Net.Http.Headers.ProductHeaderValue product) { }
public ProductInfoHeaderValue(string comment) { }
public ProductInfoHeaderValue(string productName, string productVersion) { }
public string Comment { get { throw null; } }
public System.Net.Http.Headers.ProductHeaderValue Product { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Net.Http.Headers.ProductInfoHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.ProductInfoHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.ProductInfoHeaderValue); throw null; }
}
public partial class RangeConditionHeaderValue : System.ICloneable
{
public RangeConditionHeaderValue(System.DateTimeOffset date) { }
public RangeConditionHeaderValue(System.Net.Http.Headers.EntityTagHeaderValue entityTag) { }
public RangeConditionHeaderValue(string entityTag) { }
public System.Nullable<System.DateTimeOffset> Date { get { throw null; } }
public System.Net.Http.Headers.EntityTagHeaderValue EntityTag { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Net.Http.Headers.RangeConditionHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.RangeConditionHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.RangeConditionHeaderValue); throw null; }
}
public partial class RangeHeaderValue : System.ICloneable
{
public RangeHeaderValue() { }
public RangeHeaderValue(System.Nullable<long> from, System.Nullable<long> to) { }
public System.Collections.Generic.ICollection<System.Net.Http.Headers.RangeItemHeaderValue> Ranges { get { throw null; } }
public string Unit { get { throw null; } set { } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Net.Http.Headers.RangeHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.RangeHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.RangeHeaderValue); throw null; }
}
public partial class RangeItemHeaderValue : System.ICloneable
{
public RangeItemHeaderValue(System.Nullable<long> from, System.Nullable<long> to) { }
public System.Nullable<long> From { get { throw null; } }
public System.Nullable<long> To { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
}
public partial class RetryConditionHeaderValue : System.ICloneable
{
public RetryConditionHeaderValue(System.DateTimeOffset date) { }
public RetryConditionHeaderValue(System.TimeSpan delta) { }
public System.Nullable<System.DateTimeOffset> Date { get { throw null; } }
public System.Nullable<System.TimeSpan> Delta { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Net.Http.Headers.RetryConditionHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.RetryConditionHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.RetryConditionHeaderValue); throw null; }
}
public partial class StringWithQualityHeaderValue : System.ICloneable
{
public StringWithQualityHeaderValue(string value) { }
public StringWithQualityHeaderValue(string value, double quality) { }
public System.Nullable<double> Quality { get { throw null; } }
public string Value { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Net.Http.Headers.StringWithQualityHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.StringWithQualityHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.StringWithQualityHeaderValue); throw null; }
}
public partial class TransferCodingHeaderValue : System.ICloneable
{
protected TransferCodingHeaderValue(System.Net.Http.Headers.TransferCodingHeaderValue source) { }
public TransferCodingHeaderValue(string value) { }
public System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue> Parameters { get { throw null; } }
public string Value { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Net.Http.Headers.TransferCodingHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.TransferCodingHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.TransferCodingHeaderValue); throw null; }
}
public sealed partial class TransferCodingWithQualityHeaderValue : System.Net.Http.Headers.TransferCodingHeaderValue, System.ICloneable
{
public TransferCodingWithQualityHeaderValue(string value) : base (default(System.Net.Http.Headers.TransferCodingHeaderValue)) { }
public TransferCodingWithQualityHeaderValue(string value, double quality) : base (default(System.Net.Http.Headers.TransferCodingHeaderValue)) { }
public System.Nullable<double> Quality { get { throw null; } set { } }
public static new System.Net.Http.Headers.TransferCodingWithQualityHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.TransferCodingWithQualityHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.TransferCodingWithQualityHeaderValue); throw null; }
}
public partial class ViaHeaderValue : System.ICloneable
{
public ViaHeaderValue(string protocolVersion, string receivedBy) { }
public ViaHeaderValue(string protocolVersion, string receivedBy, string protocolName) { }
public ViaHeaderValue(string protocolVersion, string receivedBy, string protocolName, string comment) { }
public string Comment { get { throw null; } }
public string ProtocolName { get { throw null; } }
public string ProtocolVersion { get { throw null; } }
public string ReceivedBy { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Net.Http.Headers.ViaHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.ViaHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.ViaHeaderValue); throw null; }
}
public partial class WarningHeaderValue : System.ICloneable
{
public WarningHeaderValue(int code, string agent, string text) { }
public WarningHeaderValue(int code, string agent, string text, System.DateTimeOffset date) { }
public string Agent { get { throw null; } }
public int Code { get { throw null; } }
public System.Nullable<System.DateTimeOffset> Date { get { throw null; } }
public string Text { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Net.Http.Headers.WarningHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.WarningHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.WarningHeaderValue); throw null; }
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// A Managed wrapper for Event Tracing for Windows
// Based on TraceEvent.cs found in nt\base\wmi\trace.net
// Provides an internal Avalon API to replace Microsoft.Windows.EventTracing.dll
#if !SILVERLIGHTXAML
using System;
using MS.Win32;
using MS.Internal;
using System.Runtime.InteropServices;
using System.Security;
using System.Globalization; //for CultureInfo
using System.Diagnostics;
using MS.Internal.WindowsBase;
#pragma warning disable 1634, 1691 //disable warnings about unknown pragma
#if SYSTEM_XAML
using System.Xaml;
namespace MS.Internal.Xaml
#else
namespace MS.Utility
#endif
{
[StructLayout(LayoutKind.Explicit, Size = 16)]
internal struct EventData
{
[FieldOffset(0)]
internal unsafe ulong Ptr;
[FieldOffset(8)]
internal uint Size;
[FieldOffset(12)]
internal uint Reserved;
}
internal abstract class TraceProvider
{
protected bool _enabled = false;
protected EventTrace.Level _level = EventTrace.Level.LogAlways;
protected EventTrace.Keyword _keywords = (EventTrace.Keyword)0; /* aka Flags */
protected EventTrace.Keyword _matchAllKeyword = (EventTrace.Keyword)0; /*Vista only*/
protected SecurityCriticalDataForSet<ulong> _registrationHandle;
private const int s_basicTypeAllocationBufferSize = sizeof(decimal);
private const int s_traceEventMaximumSize = 65482; // maximum buffer size is 64k - header size
private const int s_etwMaxNumberArguments = 32;
private const int s_etwAPIMaxStringCount = 8; // Arbitrary limit on the number of strings you can emit. This is just to limit allocations so raise it if necessary.
private const int ErrorEventTooBig = 2;
internal TraceProvider()
{
_registrationHandle = new SecurityCriticalDataForSet<ulong>(0);
}
internal abstract void Register(Guid providerGuid);
internal unsafe abstract uint EventWrite(EventTrace.Event eventID, EventTrace.Keyword keywords, EventTrace.Level level, int argc, EventData* argv);
internal uint TraceEvent(EventTrace.Event eventID, EventTrace.Keyword keywords, EventTrace.Level level)
{
// Optimization for 0-1 arguments
return TraceEvent(eventID, keywords, level, (object)null);
}
#region Properties and Structs
//
// Properties
//
internal EventTrace.Keyword Keywords
{
get
{
return _keywords;
}
}
internal EventTrace.Keyword MatchAllKeywords
{
get
{
return _matchAllKeyword;
}
}
internal EventTrace.Level Level
{
get
{
return _level;
}
}
#endregion
internal bool IsEnabled(EventTrace.Keyword keyword, EventTrace.Level level)
{
return _enabled &&
(level <= _level) &&
(keyword & _keywords) != 0 &&
(keyword & _matchAllKeyword) == _matchAllKeyword;
}
// Optimization for 0-1 arguments
internal unsafe uint TraceEvent(EventTrace.Event eventID, EventTrace.Keyword keywords, EventTrace.Level level, object eventData)
{
// It is the responsibility of the caller to check that flags/keywords are enabled before calling this method
Debug.Assert(IsEnabled(keywords, level));
uint status = 0;
int argCount = 0;
EventData userData;
userData.Size = 0;
string dataString = null;
byte* dataBuffer = stackalloc byte[s_basicTypeAllocationBufferSize];
if (eventData != null)
{
dataString = EncodeObject(ref eventData, &userData, dataBuffer);
argCount = 1;
}
if (userData.Size > s_traceEventMaximumSize)
{
return ErrorEventTooBig;
}
if (dataString != null)
{
fixed(char* pdata = dataString)
{
userData.Ptr = (ulong)pdata;
status = EventWrite(eventID, keywords, level, argCount, &userData);
}
}
else
{
status = EventWrite(eventID, keywords, level, argCount, &userData);
}
return status;
}
internal unsafe uint TraceEvent(EventTrace.Event eventID, EventTrace.Keyword keywords, EventTrace.Level level, params object[] eventPayload)
{
// It is the responsibility of the caller to check that flags/keywords are enabled before calling this method
Debug.Assert(IsEnabled(keywords, level));
int argCount = eventPayload.Length;
Debug.Assert(argCount <= s_etwMaxNumberArguments);
uint totalEventSize = 0;
int stringIndex = 0;
int[] stringPosition = new int[s_etwAPIMaxStringCount];
string [] dataString = new string[s_etwAPIMaxStringCount];
EventData* userData = stackalloc EventData[argCount];
EventData* userDataPtr = userData;
byte* dataBuffer = stackalloc byte[s_basicTypeAllocationBufferSize * argCount];
byte* currentBuffer = dataBuffer;
for (int index = 0; index < argCount; index++)
{
if (eventPayload[index] != null)
{
string isString = EncodeObject(ref eventPayload[index], userDataPtr, currentBuffer);
currentBuffer += s_basicTypeAllocationBufferSize;
totalEventSize = userDataPtr->Size;
userDataPtr++;
if (isString != null)
{
Debug.Assert(stringIndex < s_etwAPIMaxStringCount); // need to increase string count or emit fewer strings
dataString[stringIndex] = isString;
stringPosition[stringIndex] = index;
stringIndex++;
}
}
}
if (totalEventSize > s_traceEventMaximumSize)
{
return ErrorEventTooBig;
}
fixed(char* s0 = dataString[0], s1 = dataString[1], s2 = dataString[2], s3 = dataString[3],
s4 = dataString[4], s5 = dataString[5], s6 = dataString[6], s7 = dataString[7])
{
userDataPtr = userData;
if (dataString[0] != null)
{
userDataPtr[stringPosition[0]].Ptr = (ulong)s0;
}
if (dataString[1] != null)
{
userDataPtr[stringPosition[1]].Ptr = (ulong)s1;
}
if (dataString[2] != null)
{
userDataPtr[stringPosition[2]].Ptr = (ulong)s2;
}
if (dataString[3] != null)
{
userDataPtr[stringPosition[3]].Ptr = (ulong)s3;
}
if (dataString[4] != null)
{
userDataPtr[stringPosition[4]].Ptr = (ulong)s4;
}
if (dataString[5] != null)
{
userDataPtr[stringPosition[5]].Ptr = (ulong)s5;
}
if (dataString[6] != null)
{
userDataPtr[stringPosition[6]].Ptr = (ulong)s6;
}
if (dataString[7] != null)
{
userDataPtr[stringPosition[7]].Ptr = (ulong)s7;
}
return EventWrite(eventID, keywords, level, argCount, userData);
}
}
// <SecurityKernel Critical="True" Ring="0">
// <UsesUnsafeCode Name="Local intptrPtr of type: IntPtr*" />
// <UsesUnsafeCode Name="Local intptrPtr of type: Int32*" />
// <UsesUnsafeCode Name="Local longptr of type: Int64*" />
// <UsesUnsafeCode Name="Local uintptr of type: UInt32*" />
// <UsesUnsafeCode Name="Local ulongptr of type: UInt64*" />
// <UsesUnsafeCode Name="Local charptr of type: Char*" />
// <UsesUnsafeCode Name="Local byteptr of type: Byte*" />
// <UsesUnsafeCode Name="Local shortptr of type: Int16*" />
// <UsesUnsafeCode Name="Local sbyteptr of type: SByte*" />
// <UsesUnsafeCode Name="Local ushortptr of type: UInt16*" />
// <UsesUnsafeCode Name="Local floatptr of type: Single*" />
// <UsesUnsafeCode Name="Local doubleptr of type: Double*" />
// <UsesUnsafeCode Name="Local boolptr of type: Boolean*" />
// <UsesUnsafeCode Name="Local guidptr of type: Guid*" />
// <UsesUnsafeCode Name="Local decimalptr of type: Decimal*" />
// <UsesUnsafeCode Name="Local booleanptr of type: Boolean*" />
// <UsesUnsafeCode Name="Parameter dataDescriptor of type: EventData*" />
// <UsesUnsafeCode Name="Parameter dataBuffer of type: Byte*" />
// </SecurityKernel>
private static unsafe string EncodeObject(ref object data, EventData* dataDescriptor, byte* dataBuffer)
/*++
Routine Description:
This routine is used by WriteEvent to unbox the object type and
to fill the passed in ETW data descriptor.
Arguments:
data - argument to be decoded
dataDescriptor - pointer to the descriptor to be filled
dataBuffer - storage buffer for storing user data, needed because cant get the address of the object
Return Value:
null if the object is a basic type other than string. String otherwise
--*/
{
dataDescriptor->Reserved = 0;
string sRet = data as string;
if (sRet != null)
{
dataDescriptor->Size = (uint)((sRet.Length + 1) * 2);
return sRet;
}
// If the data is an enum we'll convert it to it's underlying type
Type dataType = data.GetType();
if (dataType.IsEnum)
{
data = Convert.ChangeType(data, Enum.GetUnderlyingType(dataType), CultureInfo.InvariantCulture);
}
if (data is IntPtr)
{
dataDescriptor->Size = (uint)sizeof(IntPtr);
IntPtr* intptrPtr = (IntPtr*)dataBuffer;
*intptrPtr = (IntPtr)data;
dataDescriptor->Ptr = (ulong)intptrPtr;
}
else if (data is int)
{
dataDescriptor->Size = (uint)sizeof(int);
int* intptrPtr = (int*)dataBuffer;
*intptrPtr = (int)data;
dataDescriptor->Ptr = (ulong)intptrPtr;
}
else if (data is long)
{
dataDescriptor->Size = (uint)sizeof(long);
long* longptr = (long*)dataBuffer;
*longptr = (long)data;
dataDescriptor->Ptr = (ulong)longptr;
}
else if (data is uint)
{
dataDescriptor->Size = (uint)sizeof(uint);
uint* uintptr = (uint*)dataBuffer;
*uintptr = (uint)data;
dataDescriptor->Ptr = (ulong)uintptr;
}
else if (data is UInt64)
{
dataDescriptor->Size = (uint)sizeof(ulong);
ulong* ulongptr = (ulong*)dataBuffer;
*ulongptr = (ulong)data;
dataDescriptor->Ptr = (ulong)ulongptr;
}
else if (data is char)
{
dataDescriptor->Size = (uint)sizeof(char);
char* charptr = (char*)dataBuffer;
*charptr = (char)data;
dataDescriptor->Ptr = (ulong)charptr;
}
else if (data is byte)
{
dataDescriptor->Size = (uint)sizeof(byte);
byte* byteptr = (byte*)dataBuffer;
*byteptr = (byte)data;
dataDescriptor->Ptr = (ulong)byteptr;
}
else if (data is short)
{
dataDescriptor->Size = (uint)sizeof(short);
short* shortptr = (short*)dataBuffer;
*shortptr = (short)data;
dataDescriptor->Ptr = (ulong)shortptr;
}
else if (data is sbyte)
{
dataDescriptor->Size = (uint)sizeof(sbyte);
sbyte* sbyteptr = (sbyte*)dataBuffer;
*sbyteptr = (sbyte)data;
dataDescriptor->Ptr = (ulong)sbyteptr;
}
else if (data is ushort)
{
dataDescriptor->Size = (uint)sizeof(ushort);
ushort* ushortptr = (ushort*)dataBuffer;
*ushortptr = (ushort)data;
dataDescriptor->Ptr = (ulong)ushortptr;
}
else if (data is float)
{
dataDescriptor->Size = (uint)sizeof(float);
float* floatptr = (float*)dataBuffer;
*floatptr = (float)data;
dataDescriptor->Ptr = (ulong)floatptr;
}
else if (data is double)
{
dataDescriptor->Size = (uint)sizeof(double);
double* doubleptr = (double*)dataBuffer;
*doubleptr = (double)data;
dataDescriptor->Ptr = (ulong)doubleptr;
}
else if (data is bool)
{
dataDescriptor->Size = (uint)sizeof(bool);
bool* boolptr = (bool*)dataBuffer;
*boolptr = (bool)data;
dataDescriptor->Ptr = (ulong)boolptr;
}
else if (data is Guid)
{
dataDescriptor->Size = (uint)sizeof(Guid);
Guid* guidptr = (Guid*)dataBuffer;
*guidptr = (Guid)data;
dataDescriptor->Ptr = (ulong)guidptr;
}
else if (data is decimal)
{
dataDescriptor->Size = (uint)sizeof(decimal);
decimal* decimalptr = (decimal*)dataBuffer;
*decimalptr = (decimal)data;
dataDescriptor->Ptr = (ulong)decimalptr;
}
else if (data is Boolean)
{
dataDescriptor->Size = (uint)sizeof(Boolean);
Boolean* booleanptr = (Boolean*)dataBuffer;
*booleanptr = (Boolean)data;
dataDescriptor->Ptr = (ulong)booleanptr;
}
else
{
//To our eyes, everything else is a just a string
sRet = data.ToString();
dataDescriptor->Size = (uint)((sRet.Length + 1) * 2);
return sRet;
}
return null;
}
}
// XP
internal sealed class ClassicTraceProvider : TraceProvider
{
private ulong _traceHandle = 0;
private static ClassicEtw.ControlCallback _etwProc; // Trace Callback function
internal ClassicTraceProvider()
{
}
//
// Registers the providerGuid with an inbuilt callback
//
internal override unsafe void Register(Guid providerGuid)
{
ulong registrationHandle;
ClassicEtw.TRACE_GUID_REGISTRATION guidReg;
Guid dummyGuid = new Guid(0xb4955bf0,
0x3af1,
0x4740,
0xb4,0x75,
0x99,0x05,0x5d,0x3f,0xe9,0xaa);
_etwProc = new ClassicEtw.ControlCallback(EtwEnableCallback);
// This dummyGuid is there for ETW backward compat issues and is the same for all downlevel trace providers
guidReg.Guid = &dummyGuid;
guidReg.RegHandle = null;
ClassicEtw.RegisterTraceGuidsW(_etwProc, IntPtr.Zero, ref providerGuid, 1, ref guidReg, null, null, out registrationHandle);
_registrationHandle.Value = registrationHandle;
}
//
// This callback function is called by ETW to enable or disable this provider
//
private unsafe uint EtwEnableCallback(ClassicEtw.WMIDPREQUESTCODE requestCode, IntPtr context, IntPtr bufferSize, ClassicEtw.WNODE_HEADER* buffer)
{
try
{
switch (requestCode)
{
case ClassicEtw.WMIDPREQUESTCODE.EnableEvents:
_traceHandle = buffer->HistoricalContext;
_keywords = (EventTrace.Keyword)ClassicEtw.GetTraceEnableFlags((ulong)buffer->HistoricalContext);
_level = (EventTrace.Level)ClassicEtw.GetTraceEnableLevel((ulong)buffer->HistoricalContext);
_enabled = true;
break;
case ClassicEtw.WMIDPREQUESTCODE.DisableEvents:
_enabled = false;
_traceHandle = 0;
_level = EventTrace.Level.LogAlways;
_keywords = 0;
break;
default:
_enabled = false;
_traceHandle = 0;
break;
}
return 0;
}
catch(Exception e)
{
if (CriticalExceptions.IsCriticalException(e))
{
throw;
}
else
{
return 0;
}
}
}
~ClassicTraceProvider()
{
#pragma warning suppress 6031 //presharp suppression
ClassicEtw.UnregisterTraceGuids(_registrationHandle.Value);
}
// pack the argv data and emit the event using TraceEvent
internal unsafe override uint EventWrite(EventTrace.Event eventID, EventTrace.Keyword keywords, EventTrace.Level level, int argc, EventData* argv)
{
ClassicEtw.EVENT_HEADER header;
header.Header.ClientContext = 0;
header.Header.Flags = ClassicEtw.WNODE_FLAG_TRACED_GUID | ClassicEtw.WNODE_FLAG_USE_MOF_PTR;
header.Header.Guid = EventTrace.GetGuidForEvent(eventID);
header.Header.Level = (byte)level;
header.Header.Type = (byte)EventTrace.GetOpcodeForEvent(eventID);
header.Header.Version = (ushort)EventTrace.GetVersionForEvent(eventID);
// Extra copy on XP to move argv to the end of the EVENT_HEADER
EventData* eventData = &header.Data;
if (argc > ClassicEtw.MAX_MOF_FIELDS)
{
// Data will be lost on XP
argc = ClassicEtw.MAX_MOF_FIELDS;
}
header.Header.Size = (ushort) (argc * sizeof(EventData) + 48);
for (int x = 0; x < argc; x++)
{
eventData[x].Ptr = argv[x].Ptr;
eventData[x].Size = argv[x].Size;
}
return ClassicEtw.TraceEvent(_traceHandle, &header);
}
}
// Vista and above
internal class ManifestTraceProvider : TraceProvider
{
private static ManifestEtw.EtwEnableCallback _etwEnabledCallback;
internal ManifestTraceProvider()
{
}
internal unsafe override void Register(Guid providerGuid)
{
_etwEnabledCallback =new ManifestEtw.EtwEnableCallback(EtwEnableCallback);
ulong registrationHandle = 0;
ManifestEtw.EventRegister(ref providerGuid, _etwEnabledCallback, null, ref registrationHandle);
_registrationHandle.Value = registrationHandle;
}
private unsafe void EtwEnableCallback(ref Guid sourceId, int isEnabled, byte level, long matchAnyKeywords, long matchAllKeywords, ManifestEtw.EVENT_FILTER_DESCRIPTOR* filterData, void* callbackContext)
{
_enabled = isEnabled > 0;
_level = (EventTrace.Level)level;
_keywords = (EventTrace.Keyword) matchAnyKeywords;
_matchAllKeyword = (EventTrace.Keyword) matchAllKeywords;
// parse data from EVENT_FILTER_DESCRIPTOR - see CLR EventProvider::GetDataFromController
}
~ManifestTraceProvider()
{
if(_registrationHandle.Value != 0)
{
try
{
ManifestEtw.EventUnregister(_registrationHandle.Value);
}
finally
{
_registrationHandle.Value = 0;
}
}
}
internal unsafe override uint EventWrite(EventTrace.Event eventID, EventTrace.Keyword keywords, EventTrace.Level level, int argc, EventData* argv)
{
ManifestEtw.EventDescriptor eventDescriptor;
eventDescriptor.Id = (ushort) eventID;
eventDescriptor.Version = EventTrace.GetVersionForEvent(eventID);
eventDescriptor.Channel = 0x10; // Since Channel isn't supported on XP we only use a single default channel.
eventDescriptor.Level = (byte)level;
eventDescriptor.Opcode = EventTrace.GetOpcodeForEvent(eventID);
eventDescriptor.Task = EventTrace.GetTaskForEvent(eventID);
eventDescriptor.Keywords = (long)keywords;
if (argc == 0)
{
argv = null;
}
return ManifestEtw.EventWrite(_registrationHandle.Value, ref eventDescriptor, (uint)argc, argv);
}
}
}
#endif
| |
#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.Collections.Generic;
using System.IO;
using System.Text;
using System.Globalization;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
using Newtonsoft.Json.Serialization;
namespace Newtonsoft.Json.Utilities
{
internal static class StringUtils
{
public const string CarriageReturnLineFeed = "\r\n";
public const string Empty = "";
public const char CarriageReturn = '\r';
public const char LineFeed = '\n';
public const char Tab = '\t';
public static string FormatWith(this string format, IFormatProvider provider, object arg0)
{
return format.FormatWith(provider, new[] { arg0 });
}
public static string FormatWith(this string format, IFormatProvider provider, object arg0, object arg1)
{
return format.FormatWith(provider, new[] { arg0, arg1 });
}
public static string FormatWith(this string format, IFormatProvider provider, object arg0, object arg1, object arg2)
{
return format.FormatWith(provider, new[] { arg0, arg1, arg2 });
}
public static string FormatWith(this string format, IFormatProvider provider, params object[] args)
{
ValidationUtils.ArgumentNotNull(format, "format");
return string.Format(provider, format, args);
}
/// <summary>
/// Determines whether the string is all white space. Empty string will return false.
/// </summary>
/// <param name="s">The string to test whether it is all white space.</param>
/// <returns>
/// <c>true</c> if the string is all white space; otherwise, <c>false</c>.
/// </returns>
public static bool IsWhiteSpace(string s)
{
if (s == null)
throw new ArgumentNullException("s");
if (s.Length == 0)
return false;
for (int i = 0; i < s.Length; i++)
{
if (!char.IsWhiteSpace(s[i]))
return false;
}
return true;
}
/// <summary>
/// Nulls an empty string.
/// </summary>
/// <param name="s">The string.</param>
/// <returns>Null if the string was null, otherwise the string unchanged.</returns>
public static string NullEmptyString(string s)
{
return (string.IsNullOrEmpty(s)) ? null : s;
}
public static StringWriter CreateStringWriter(int capacity)
{
StringBuilder sb = new StringBuilder(capacity);
StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
return sw;
}
public static int? GetLength(string value)
{
if (value == null)
return null;
else
return value.Length;
}
public static void ToCharAsUnicode(char c, char[] buffer)
{
buffer[0] = '\\';
buffer[1] = 'u';
buffer[2] = MathUtils.IntToHex((c >> 12) & '\x000f');
buffer[3] = MathUtils.IntToHex((c >> 8) & '\x000f');
buffer[4] = MathUtils.IntToHex((c >> 4) & '\x000f');
buffer[5] = MathUtils.IntToHex(c & '\x000f');
}
public static TSource ForgivingCaseSensitiveFind<TSource>(this IEnumerable<TSource> source, Func<TSource, string> valueSelector, string testValue)
{
if (source == null)
throw new ArgumentNullException("source");
if (valueSelector == null)
throw new ArgumentNullException("valueSelector");
var caseInsensitiveResults = source.Where(s => string.Equals(valueSelector(s), testValue, StringComparison.OrdinalIgnoreCase));
if (caseInsensitiveResults.Count() <= 1)
{
return caseInsensitiveResults.SingleOrDefault();
}
else
{
// multiple results returned. now filter using case sensitivity
var caseSensitiveResults = source.Where(s => string.Equals(valueSelector(s), testValue, StringComparison.Ordinal));
return caseSensitiveResults.SingleOrDefault();
}
}
public static string ToCamelCase(string s)
{
if (string.IsNullOrEmpty(s))
return s;
if (!char.IsUpper(s[0]))
return s;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.Length; i++)
{
bool hasNext = (i + 1 < s.Length);
if ((i == 0 || !hasNext) || char.IsUpper(s[i + 1]))
{
char lowerCase;
#if !(NETFX_CORE || PORTABLE)
lowerCase = char.ToLower(s[i], CultureInfo.InvariantCulture);
#else
lowerCase = char.ToLower(s[i]);
#endif
sb.Append(lowerCase);
}
else
{
sb.Append(s.Substring(i));
break;
}
}
return sb.ToString();
}
public static bool IsHighSurrogate(char c)
{
#if !(SILVERLIGHT || PORTABLE40 || PORTABLE)
return char.IsHighSurrogate(c);
#else
return (c >= 55296 && c <= 56319);
#endif
}
public static bool IsLowSurrogate(char c)
{
#if !(SILVERLIGHT || PORTABLE40 || PORTABLE)
return char.IsLowSurrogate(c);
#else
return (c >= 56320 && c <= 57343);
#endif
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.XPath;
using System.Linq;
using MCEBuddy.Globals;
using MCEBuddy.Util;
namespace MCEBuddy.MetaData
{
public static class TVDB
{
private const string MCEBUDDY_THETVDB_API_KEY = "24BC47A0DF94324E";
private static string[] THETVDB_SUPPORTED_LANGUAGES = { "en", "da", "fi", "nl", "de", "it","es", "fr","pl","hu","el","tr","ru","he","ja","pt","zh","cs","sl","hr","ko","sv","no"};
public static bool DownloadSeriesDetails(VideoTags videoTags, bool prioritizeMatchDate, bool dontOverwriteTitle, Log jobLog)
{
XPathDocument Xp;
XPathNavigator Nav;
XPathExpression Exp;
XPathNodeIterator Itr;
// There are no TheTVDB mirrors, so skip that step
// ******************
// Get the series ID
// ******************
try
{
if (!String.IsNullOrWhiteSpace(videoTags.imdbId)) // If we have a specific IMDB movieId specified, look up the movie details on TVDB
{
Xp = new XPathDocument("http://www.thetvdb.com/api/GetSeriesByRemoteID.php?imdbid=" + videoTags.imdbId);
}
else if (!String.IsNullOrWhiteSpace(videoTags.tvdbId)) // If we have a specific TVDB seriesId specified, look up the series details
{
// First match by Episode name and then by Original broadcast date (by default prioritize match date is false)
if (!MatchSeriesInformation(videoTags, videoTags.tvdbId, prioritizeMatchDate, dontOverwriteTitle, jobLog))
return MatchSeriesInformation(videoTags, videoTags.tvdbId, !prioritizeMatchDate, dontOverwriteTitle, jobLog);
else
return true;
}
else // Generic search by name
{
Xp = new XPathDocument("http://www.thetvdb.com/api/GetSeries.php?seriesname=" + videoTags.Title);
}
Nav = Xp.CreateNavigator();
Exp = Nav.Compile("//Data/Series");
Itr = Nav.Select(Exp);
}
catch (Exception e)
{
jobLog.WriteEntry("Unable to connect to TVDB\r\nError -> " + e.ToString(), Log.LogEntryType.Warning);
return false;
}
while (Itr.MoveNext()) // loop through all series returned trying to find a match
{
string seriesID = XML.GetXMLTagValue("seriesid", Itr.Current.OuterXml);
string seriesTitle = XML.GetXMLTagValue("SeriesName", Itr.Current.OuterXml);
string[] aliasNames = XML.GetXMLTagValue("AliasNames", Itr.Current.OuterXml).Split('|'); // sometimes the alias matches
// Compare the series title with the title of the recording
if ((String.Compare(seriesTitle.Trim(), videoTags.Title.Trim(), CultureInfo.InvariantCulture, (CompareOptions.IgnoreSymbols | CompareOptions.IgnoreCase)) != 0) &&
(!aliasNames.Any(s => (String.Compare(s.Trim(), videoTags.Title.Trim(), CultureInfo.InvariantCulture, (CompareOptions.IgnoreSymbols | CompareOptions.IgnoreCase)) == 0))))
continue; // Name mismatch
if (String.IsNullOrWhiteSpace(seriesID))
continue; // can't do anything without seriesID
// First match by Episode name and then by Original broadcast date (by default prioritize match date is false)
if (!MatchSeriesInformation(videoTags, seriesID, prioritizeMatchDate, dontOverwriteTitle, jobLog))
{
if (MatchSeriesInformation(videoTags, seriesID, !prioritizeMatchDate, dontOverwriteTitle, jobLog))
return true;
// Else we continue looping through the returned series looking for a match if nothing matches
}
else
return true;
}
jobLog.WriteEntry("No match found on TVDB", Log.LogEntryType.Debug);
return false; // no match found
}
/// <summary>
/// Match and download the series information
/// </summary>
/// <param name="videoTags">Video tags</param>
/// <param name="seriesID">TVDB Series ID</param>
/// <param name="matchByAirDate">True to match by original broadcast date, false to match by episode name</param>
/// <param name="dontOverwriteTitle">True if the title has been manually corrected and not to be overwritten</param>
/// <returns></returns>
private static bool MatchSeriesInformation(VideoTags videoTags, string seriesID, bool matchByAirDate, bool dontOverwriteTitle, Log jobLog)
{
if (matchByAirDate) // User requested priority
// Match by original broadcast date
return MatchByBroadcastTime(videoTags, seriesID, dontOverwriteTitle, jobLog);
else
// Match by Episode name
return MatchByEpisodeName(videoTags, seriesID, jobLog);
}
/// <summary>
/// Match the series information by Original Broadcast date
/// </summary>
private static bool MatchByBroadcastTime(VideoTags videoTags, string seriesID, bool dontOverwriteTitle, Log jobLog)
{
// If we have no original broadcasttime
if (videoTags.OriginalBroadcastDateTime <= Globals.GlobalDefs.NO_BROADCAST_TIME)
{
jobLog.WriteEntry("No original broadcast date time", Log.LogEntryType.Debug);
return false;
}
// **************************************
// Get the series and episode information
// **************************************
string lang = Localise.TwoLetterISO();
if (!((IList<string>)THETVDB_SUPPORTED_LANGUAGES).Contains(lang))
lang = "en";
string queryUrl = "http://www.thetvdb.com/api/" + MCEBUDDY_THETVDB_API_KEY + "/series/" + seriesID + "/all/" + lang + ".xml";
XPathDocument XpS;
XPathNavigator NavS;
XPathExpression ExpS;
XPathNodeIterator ItrS;
string overview = "";
string seriesName = "";
string bannerUrl = "";
string imdbID = "";
string firstAiredStr = "";
DateTime firstAired = GlobalDefs.NO_BROADCAST_TIME;
int seasonNo = 0;
int episodeNo = 0;
string episodeName = "";
string episodeOverview = "";
string network = "";
DateTime premiereDate = GlobalDefs.NO_BROADCAST_TIME;
List<string> genres = new List<string>();
try
{
// Get the Series information
XpS = new XPathDocument(queryUrl);
NavS = XpS.CreateNavigator();
ExpS = NavS.Compile("//Data/Series"); // Series information
ItrS = NavS.Select(ExpS);
ItrS.MoveNext();
seriesName = XML.GetXMLTagValue("SeriesName", ItrS.Current.OuterXml);
overview = XML.GetXMLTagValue("Overview", ItrS.Current.OuterXml);
if (String.IsNullOrWhiteSpace(bannerUrl = XML.GetXMLTagValue("poster", ItrS.Current.OuterXml))) // We get the poster first
if (String.IsNullOrWhiteSpace(bannerUrl = XML.GetXMLTagValue("fanart", ItrS.Current.OuterXml))) // We get the fanart next
bannerUrl = XML.GetXMLTagValue("banner", ItrS.Current.OuterXml); // We get the banner last
imdbID = XML.GetXMLTagValue("IMDB_ID", ItrS.Current.OuterXml);
network = XML.GetXMLTagValue("Network", ItrS.Current.OuterXml);
DateTime.TryParse(XML.GetXMLTagValue("FirstAired", ItrS.Current.OuterXml), out premiereDate);
string genreValue = XML.GetXMLTagValue("Genre", ItrS.Current.OuterXml);
if (!String.IsNullOrWhiteSpace(genreValue))
foreach (string genre in genreValue.Split('|'))
if (!String.IsNullOrWhiteSpace(genre)) genres.Add(genre);
// Get the Episode information
XpS = new XPathDocument(queryUrl);
NavS = XpS.CreateNavigator();
ExpS = NavS.Compile("//Data/Episode");
ItrS = NavS.Select(ExpS);
}
catch (Exception e)
{
jobLog.WriteEntry("Unable to navigate TVDB\r\nError -> " + e.ToString(), Log.LogEntryType.Warning);
return false;
}
while (ItrS.MoveNext())
{
firstAiredStr = XML.GetXMLTagValue("FirstAired", ItrS.Current.OuterXml);
if (DateTime.TryParse(firstAiredStr, null, DateTimeStyles.AssumeLocal, out firstAired))
{
if (firstAired <= GlobalDefs.NO_BROADCAST_TIME)
continue;
// The information is stored on the server using the network timezone
// So we assume that the show being converted was recorded locally and is converted locally so the timezones match
// Sometimes the timezones get mixed up so we check local time or universal time for a match
if ((firstAired.Date == videoTags.OriginalBroadcastDateTime.ToLocalTime().Date) || // TVDB only reports the date not the time
(firstAired.Date == videoTags.OriginalBroadcastDateTime.ToUniversalTime().Date))
{
episodeName = XML.GetXMLTagValue("EpisodeName", ItrS.Current.OuterXml);
if (String.IsNullOrWhiteSpace(episodeName))
{
jobLog.WriteEntry("Empty episode name", Log.LogEntryType.Debug);
return false; // WRONG series, if there is no name we're in the incorrect series (probably wrong country)
}
int.TryParse(XML.GetXMLTagValue("SeasonNumber", ItrS.Current.OuterXml), out seasonNo);
int.TryParse(XML.GetXMLTagValue("EpisodeNumber", ItrS.Current.OuterXml), out episodeNo);
episodeOverview = XML.GetXMLTagValue("Overview", ItrS.Current.OuterXml);
// ********************
// Get the banner file
// ********************
VideoMetaData.DownloadBannerFile(videoTags, "http://www.thetvdb.com/banners/" + bannerUrl); // Get bannerfile
if ((episodeNo != 0) && (videoTags.Episode == 0)) videoTags.Episode = episodeNo;
if ((seasonNo != 0) && (videoTags.Season == 0)) videoTags.Season = seasonNo;
if (!String.IsNullOrWhiteSpace(seriesName) && !dontOverwriteTitle) videoTags.Title = seriesName; // Overwrite Series name since we matching by broadcast time and the name didn't match earlier so likely an issue with the name
if (!String.IsNullOrWhiteSpace(episodeName)) videoTags.SubTitle = episodeName; // Overwrite episode name, it didn't match earlier in match by episode name, so it's probably wrong on the metadata
if (!String.IsNullOrWhiteSpace(episodeOverview)) videoTags.Description = episodeOverview; // Overwrite
else if (!String.IsNullOrWhiteSpace(overview)) videoTags.Description = overview; // Overwrite
if (!String.IsNullOrWhiteSpace(seriesID) && String.IsNullOrWhiteSpace(videoTags.tvdbId)) videoTags.tvdbId = seriesID;
if (!String.IsNullOrWhiteSpace(imdbID) && String.IsNullOrWhiteSpace(videoTags.imdbId)) videoTags.imdbId = imdbID;
if (!String.IsNullOrWhiteSpace(network) && String.IsNullOrWhiteSpace(videoTags.Network)) videoTags.Network = network;
if (premiereDate > GlobalDefs.NO_BROADCAST_TIME)
if ((videoTags.SeriesPremiereDate <= GlobalDefs.NO_BROADCAST_TIME) || (videoTags.SeriesPremiereDate.Date > premiereDate.Date)) // Sometimes the metadata from the video recordings are incorrect and report the recorded date (which is more recent than the release date) then use TVDB dates, TVDB Dates are more reliable than video metadata usually
videoTags.SeriesPremiereDate = premiereDate; // TVDB stores time in network (local) timezone
if (genres.Count > 0)
{
if (videoTags.Genres != null)
{
if (videoTags.Genres.Length == 0)
videoTags.Genres = genres.ToArray();
}
else
videoTags.Genres = genres.ToArray();
}
return true; // Found a match got all the data, we're done here
}
}
}
jobLog.WriteEntry("No match found on TVDB for language " + lang, Log.LogEntryType.Warning);
return false;
}
/// <summary>
/// Match the series information by Episode name
/// </summary>
private static bool MatchByEpisodeName(VideoTags videoTags, string seriesID, Log jobLog)
{
if (String.IsNullOrWhiteSpace(videoTags.SubTitle))
{
jobLog.WriteEntry("No episode name to match", Log.LogEntryType.Debug);
return false; //Nothing to match here
}
// **************************************
// Get the series and episode information
// **************************************
foreach (string lang in THETVDB_SUPPORTED_LANGUAGES) // Cycle through all languages looking for a match since people in different countries/locales could be viewing shows recorded in different languages
{
jobLog.WriteEntry("Looking for Episode name match on TVDB using language " + lang, Log.LogEntryType.Debug);
string queryUrl = "http://www.thetvdb.com/api/" + MCEBUDDY_THETVDB_API_KEY + "/series/" + seriesID + "/all/" + lang + ".xml";
XPathDocument XpS;
XPathNavigator NavS;
XPathExpression ExpS;
XPathNodeIterator ItrS;
string overview = "";
string bannerUrl = "";
string imdbID = "";
List<String> genres = new List<string>();;
int seasonNo = 0;
int episodeNo = 0;
string episodeName = "";
string episodeOverview = "";
string network = "";
DateTime premiereDate = GlobalDefs.NO_BROADCAST_TIME;
string firstAiredStr = "";
DateTime firstAired = GlobalDefs.NO_BROADCAST_TIME;
try
{
// Get the Series information
XpS = new XPathDocument(queryUrl);
NavS = XpS.CreateNavigator();
ExpS = NavS.Compile("//Data/Series"); // Series information
ItrS = NavS.Select(ExpS);
ItrS.MoveNext();
overview = XML.GetXMLTagValue("Overview", ItrS.Current.OuterXml);
if (String.IsNullOrWhiteSpace(bannerUrl = XML.GetXMLTagValue("poster", ItrS.Current.OuterXml))) // We get the poster first
if (String.IsNullOrWhiteSpace(bannerUrl = XML.GetXMLTagValue("fanart", ItrS.Current.OuterXml))) // We get the fanart next
bannerUrl = XML.GetXMLTagValue("banner", ItrS.Current.OuterXml); // We get the banner last
imdbID = XML.GetXMLTagValue("IMDB_ID", ItrS.Current.OuterXml);
network = XML.GetXMLTagValue("Network", ItrS.Current.OuterXml);
DateTime.TryParse(XML.GetXMLTagValue("FirstAired", ItrS.Current.OuterXml), out premiereDate);
string genreValue = XML.GetXMLTagValue("Genre", ItrS.Current.OuterXml);
if (!String.IsNullOrWhiteSpace(genreValue))
foreach (string genre in genreValue.Split('|'))
if (!String.IsNullOrWhiteSpace(genre)) genres.Add(genre);
// Get the episode information
XpS = new XPathDocument(queryUrl);
NavS = XpS.CreateNavigator();
ExpS = NavS.Compile("//Data/Episode"); // Episode information
ItrS = NavS.Select(ExpS);
}
catch (Exception e)
{
jobLog.WriteEntry("Unable to nagivate TMDB for language " + lang + "\r\nError -> " + e.ToString(), Log.LogEntryType.Warning);
return false;
}
while (ItrS.MoveNext())
{
episodeName = XML.GetXMLTagValue("EpisodeName", ItrS.Current.OuterXml);
if (!String.IsNullOrWhiteSpace(episodeName))
{
if (String.Compare(videoTags.SubTitle.Trim(), episodeName.Trim(), CultureInfo.InvariantCulture, (CompareOptions.IgnoreSymbols | CompareOptions.IgnoreCase)) == 0) // Compare the episode names (case / special characters / whitespace can change very often)
{
int.TryParse(XML.GetXMLTagValue("SeasonNumber", ItrS.Current.OuterXml), out seasonNo);
int.TryParse(XML.GetXMLTagValue("EpisodeNumber", ItrS.Current.OuterXml), out episodeNo);
episodeOverview = XML.GetXMLTagValue("Overview", ItrS.Current.OuterXml);
// ********************
// Get the banner file
// ********************
VideoMetaData.DownloadBannerFile(videoTags, "http://www.thetvdb.com/banners/" + bannerUrl); // Get bannerfile
if ((episodeNo != 0) && (videoTags.Episode == 0)) videoTags.Episode = episodeNo;
if ((seasonNo != 0) && (videoTags.Season == 0)) videoTags.Season = seasonNo;
if (!String.IsNullOrWhiteSpace(episodeOverview) && String.IsNullOrWhiteSpace(videoTags.Description)) videoTags.Description = episodeOverview;
else if (!String.IsNullOrWhiteSpace(overview) && (String.IsNullOrWhiteSpace(videoTags.Description))) videoTags.Description = overview;
if (!String.IsNullOrWhiteSpace(seriesID) && String.IsNullOrWhiteSpace(videoTags.tvdbId)) videoTags.tvdbId = seriesID;
if (!String.IsNullOrWhiteSpace(imdbID) && String.IsNullOrWhiteSpace(videoTags.imdbId)) videoTags.imdbId = imdbID;
if (!String.IsNullOrWhiteSpace(network) && String.IsNullOrWhiteSpace(videoTags.Network)) videoTags.Network = network;
if (premiereDate > GlobalDefs.NO_BROADCAST_TIME)
if ((videoTags.SeriesPremiereDate <= GlobalDefs.NO_BROADCAST_TIME) || (videoTags.SeriesPremiereDate.Date > premiereDate.Date)) // Sometimes the metadata from the video recordings are incorrect and report the recorded date (which is more recent than the release date) then use TVDB dates, TVDB Dates are more reliable than video metadata usually
videoTags.SeriesPremiereDate = premiereDate; // TVDB stores time in network (local) timezone
if (genres.Count > 0)
{
if (videoTags.Genres != null)
{
if (videoTags.Genres.Length == 0)
videoTags.Genres = genres.ToArray();
}
else
videoTags.Genres = genres.ToArray();
}
firstAiredStr = XML.GetXMLTagValue("FirstAired", ItrS.Current.OuterXml);
if (DateTime.TryParse(firstAiredStr, null, DateTimeStyles.AssumeLocal, out firstAired))
{
if (firstAired > GlobalDefs.NO_BROADCAST_TIME)
if ((videoTags.OriginalBroadcastDateTime <= GlobalDefs.NO_BROADCAST_TIME) || (videoTags.OriginalBroadcastDateTime.Date > firstAired.Date)) // Sometimes the metadata from the video recordings are incorrect and report the recorded date (which is more recent than the release date) then use TVDB dates, TVDB Dates are more reliable than video metadata usually
videoTags.OriginalBroadcastDateTime = firstAired; // TVDB stores time in network (local) timezone
}
return true; // Found a match got all the data, we're done here
}
}
}
}
jobLog.WriteEntry("No match found on TVDB for Episode Name", Log.LogEntryType.Debug);
return false;
}
}
}
| |
using Android.App;
using Android.Views;
using Com.Layer.Sdk.Changes;
using Com.Layer.Sdk.Listeners;
using Android.Widget;
using Android.Support.V7.Widget;
using Com.Layer.Sdk.Messaging;
using Android.OS;
using Android.Net;
using Android.Views.InputMethods;
using Com.Layer.Atlas.Util;
using Android.Content;
using System.Collections.Generic;
using Com.Layer.Sdk;
using Com.Layer.Sdk.Policy;
using Com.Layer.Atlas.Provider;
using Com.Layer.Atlas;
namespace Com.Layer.Messenger
{
[Activity(WindowSoftInputMode = SoftInput.AdjustResize)]
public class ConversationSettingsActivity : BaseActivity, ILayerPolicyListener, ILayerChangeEventListener
{
private EditText mConversationName;
private Switch mShowNotifications;
private RecyclerView mParticipantRecyclerView;
private Button mLeaveButton;
private Button mAddParticipantsButton;
private Conversation mConversation;
private ParticipantAdapter mParticipantAdapter;
public ConversationSettingsActivity()
: base(Resource.Layout.activity_conversation_settings, Resource.Menu.menu_conversation_details, Resource.String.title_conversation_details, true)
{
}
protected override void OnCreate(Bundle savedInstanceState) {
base.OnCreate(savedInstanceState);
mConversationName = FindViewById<EditText>(Resource.Id.conversation_name);
mShowNotifications = FindViewById<Switch>(Resource.Id.show_notifications_switch);
mParticipantRecyclerView = FindViewById<RecyclerView>(Resource.Id.participants);
mLeaveButton = FindViewById<Button>(Resource.Id.leave_button);
mAddParticipantsButton = FindViewById<Button>(Resource.Id.add_participant_button);
// Get Conversation from Intent extras
Uri conversationId = Intent.GetParcelableExtra(PushNotificationReceiver.LAYER_CONVERSATION_KEY) as Uri;
mConversation = GetLayerClient().GetConversation(conversationId);
if (mConversation == null && !IsFinishing) Finish();
mParticipantAdapter = new ParticipantAdapter(this);
mParticipantRecyclerView.SetAdapter(mParticipantAdapter);
LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.Vertical, false);
mParticipantRecyclerView.SetLayoutManager(manager);
mConversationName.EditorAction += (sender, args) =>
{
if (args.ActionId == ImeAction.Done || (args.Event != null && args.Event.Action == KeyEventActions.Down && args.Event.KeyCode == Keycode.Enter)) {
string title = ((EditText) sender).Text.ToString().Trim();
AtlasUtil.SetConversationMetadataTitle(mConversation, title);
Toast.MakeText(this, Resource.String.toast_group_name_updated, ToastLength.Short).Show();
args.Handled = true;
}
args.Handled = false;
};
mShowNotifications.CheckedChange += (sender, args) =>
{
PushNotificationReceiver.GetNotifications(this).SetEnabled(mConversation.Id, args.IsChecked);
};
mLeaveButton.Click += (sender, args) =>
{
SetEnabled(false);
mConversation.RemoveParticipants(GetLayerClient().AuthenticatedUserId);
Refresh();
Intent intent = new Intent(this, typeof(ConversationsListActivity));
intent.SetFlags(ActivityFlags.ClearTop);
SetEnabled(true);
StartActivity(intent);
};
mAddParticipantsButton.Click += (sender, args) =>
{
// TODO
Toast.MakeText(this, "Coming soon", ToastLength.Long).Show();
};
}
public void SetEnabled(bool enabled) {
mShowNotifications.Enabled = enabled;
mLeaveButton.Enabled = enabled;
}
private void Refresh() {
if (!GetLayerClient().IsAuthenticated) return;
mConversationName.Text = AtlasUtil.GetConversationMetadataTitle(mConversation);
mShowNotifications.Checked = PushNotificationReceiver.GetNotifications(this).IsEnabled(mConversation.Id);
ISet<string> participantsMinusMe = new HashSet<string>(mConversation.Participants);
participantsMinusMe.Remove(GetLayerClient().AuthenticatedUserId);
if (participantsMinusMe.Count == 0) {
// I've been removed
mConversationName.Enabled = false;
mLeaveButton.Visibility = ViewStates.Gone;
} else if (participantsMinusMe.Count == 1) {
// 1-on-1
mConversationName.Enabled = false;
mLeaveButton.Visibility = ViewStates.Gone;
} else {
// Group
mConversationName.Enabled = true;
mLeaveButton.Visibility = ViewStates.Visible;
}
mParticipantAdapter.Refresh();
}
protected override void OnResume() {
base.OnResume();
GetLayerClient().RegisterPolicyListener(this).RegisterEventListener(this);
SetEnabled(true);
Refresh();
}
protected override void OnPause() {
GetLayerClient().UnregisterPolicyListener(this).UnregisterEventListener(this);
base.OnPause();
}
public void OnPolicyListUpdate(LayerClient layerClient, IList<LayerPolicy> list, IList<LayerPolicy> list1) {
Refresh();
}
public void OnChangeEvent(LayerChangeEvent layerChangeEvent) {
Refresh();
}
private class ViewHolder : RecyclerView.ViewHolder
{
internal AtlasAvatar mAvatar;
internal TextView mTitle;
internal ImageView mBlocked;
internal IParticipant mParticipant;
internal LayerPolicy mBlockPolicy;
public ViewHolder(ViewGroup parent)
: base(LayoutInflater.From(parent.Context).Inflate(Resource.Layout.participant_item, parent, false))
{
mAvatar = ItemView.FindViewById<AtlasAvatar>(Resource.Id.avatar);
mTitle = ItemView.FindViewById<TextView>(Resource.Id.title);
mBlocked = ItemView.FindViewById<ImageView>(Resource.Id.blocked);
}
}
private class ParticipantAdapter : RecyclerView.Adapter
{
private readonly ConversationSettingsActivity _activity;
List<IParticipant> mParticipants = new List<IParticipant>();
internal ParticipantAdapter(ConversationSettingsActivity activity)
{
_activity = activity;
}
public void Refresh() {
// Get new sorted list of Participants
IParticipantProvider provider = App.GetParticipantProvider();
mParticipants.Clear();
foreach (string participantId in _activity.mConversation.Participants) {
if (participantId.Equals(_activity.GetLayerClient().AuthenticatedUserId)) continue;
IParticipant participant = provider.GetParticipant(participantId);
if (participant == null) continue;
mParticipants.Add(participant);
}
mParticipants.Sort();
// Adjust participant container height
int height = (int) System.Math.Round((double) mParticipants.Count * _activity.Resources.GetDimensionPixelSize(Resource.Dimension.atlas_secondary_item_height));
LinearLayout.LayoutParams params_ = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, height);
_activity.mParticipantRecyclerView.LayoutParameters = params_;
// Notify changes
NotifyDataSetChanged();
}
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
ViewHolder viewHolder = new ViewHolder(parent);
viewHolder.mAvatar.Init(App.GetParticipantProvider(), App.GetPicasso());
viewHolder.ItemView.Tag = viewHolder;
// Click to display remove / block dialog
viewHolder.ItemView.Click += (sender, args) =>
{
ViewHolder holder = (sender as View).Tag as ViewHolder;
AlertDialog.Builder builder = new AlertDialog.Builder((sender as View).Context)
.SetMessage(holder.mTitle.Text.ToString());
if (_activity.mConversation.Participants.Count > 2) {
builder.SetNeutralButton(Resource.String.alert_button_remove, (sender_, args_) =>
{
_activity.mConversation.RemoveParticipants(holder.mParticipant.Id);
});
}
builder.SetPositiveButton(holder.mBlockPolicy != null ? Resource.String.alert_button_unblock : Resource.String.alert_button_block,
(sender_, args_) =>
{
IParticipant participant = holder.mParticipant;
if (holder.mBlockPolicy == null) {
// Block
holder.mBlockPolicy = new LayerPolicy.Builder(LayerPolicy.PolicyType.Block).SentByUserId(participant.Id).Build();
_activity.GetLayerClient().AddPolicy(holder.mBlockPolicy);
holder.mBlocked.Visibility = ViewStates.Visible;
} else {
_activity.GetLayerClient().RemovePolicy(holder.mBlockPolicy);
holder.mBlockPolicy = null;
holder.mBlocked.Visibility = ViewStates.Invisible;
}
})
.SetNegativeButton(Resource.String.alert_button_cancel, (sender_, args_) =>
{
((IDialogInterface) sender_).Dismiss();
})
.Show();
};
return viewHolder;
}
public override void OnBindViewHolder(RecyclerView.ViewHolder viewHolderObj, int position) {
IParticipant participant = mParticipants[position];
var viewHolder = viewHolderObj as ViewHolder;
viewHolder.mTitle.Text = participant.Name;
viewHolder.mAvatar.SetParticipants(participant.Id);
viewHolder.mParticipant = participant;
LayerPolicy block = null;
foreach (LayerPolicy policy in _activity.GetLayerClient().Policies) {
if (policy.GetPolicyType() != LayerPolicy.PolicyType.Block) continue;
if (!policy.SentByUserID.Equals(participant.Id)) continue;
block = policy;
break;
}
viewHolder.mBlockPolicy = block;
viewHolder.mBlocked.Visibility = block == null ? ViewStates.Invisible : ViewStates.Visible;
}
public override int ItemCount {
get { return mParticipants.Count; }
}
}
}
}
| |
namespace android.graphics.drawable
{
[global::MonoJavaBridge.JavaClass()]
public partial class LayerDrawable : android.graphics.drawable.Drawable, android.graphics.drawable.Drawable.Callback
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static LayerDrawable()
{
InitJNI();
}
protected LayerDrawable(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _getId4070;
public virtual int getId(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable._getId4070, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable.staticClass, global::android.graphics.drawable.LayerDrawable._getId4070, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _inflate4071;
public override void inflate(android.content.res.Resources arg0, org.xmlpull.v1.XmlPullParser arg1, android.util.AttributeSet arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable._inflate4071, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable.staticClass, global::android.graphics.drawable.LayerDrawable._inflate4071, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _getDrawable4072;
public virtual global::android.graphics.drawable.Drawable getDrawable(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable._getDrawable4072, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.graphics.drawable.Drawable;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable.staticClass, global::android.graphics.drawable.LayerDrawable._getDrawable4072, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.graphics.drawable.Drawable;
}
internal static global::MonoJavaBridge.MethodId _draw4073;
public override void draw(android.graphics.Canvas arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable._draw4073, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable.staticClass, global::android.graphics.drawable.LayerDrawable._draw4073, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getChangingConfigurations4074;
public override int getChangingConfigurations()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable._getChangingConfigurations4074);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable.staticClass, global::android.graphics.drawable.LayerDrawable._getChangingConfigurations4074);
}
internal static global::MonoJavaBridge.MethodId _setDither4075;
public override void setDither(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable._setDither4075, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable.staticClass, global::android.graphics.drawable.LayerDrawable._setDither4075, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setAlpha4076;
public override void setAlpha(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable._setAlpha4076, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable.staticClass, global::android.graphics.drawable.LayerDrawable._setAlpha4076, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setColorFilter4077;
public override void setColorFilter(android.graphics.ColorFilter arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable._setColorFilter4077, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable.staticClass, global::android.graphics.drawable.LayerDrawable._setColorFilter4077, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isStateful4078;
public override bool isStateful()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable._isStateful4078);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable.staticClass, global::android.graphics.drawable.LayerDrawable._isStateful4078);
}
internal static global::MonoJavaBridge.MethodId _setVisible4079;
public override bool setVisible(bool arg0, bool arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable._setVisible4079, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable.staticClass, global::android.graphics.drawable.LayerDrawable._setVisible4079, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _getOpacity4080;
public override int getOpacity()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable._getOpacity4080);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable.staticClass, global::android.graphics.drawable.LayerDrawable._getOpacity4080);
}
internal static global::MonoJavaBridge.MethodId _onStateChange4081;
protected override bool onStateChange(int[] arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable._onStateChange4081, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable.staticClass, global::android.graphics.drawable.LayerDrawable._onStateChange4081, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onLevelChange4082;
protected override bool onLevelChange(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable._onLevelChange4082, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable.staticClass, global::android.graphics.drawable.LayerDrawable._onLevelChange4082, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onBoundsChange4083;
protected override void onBoundsChange(android.graphics.Rect arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable._onBoundsChange4083, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable.staticClass, global::android.graphics.drawable.LayerDrawable._onBoundsChange4083, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getIntrinsicWidth4084;
public override int getIntrinsicWidth()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable._getIntrinsicWidth4084);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable.staticClass, global::android.graphics.drawable.LayerDrawable._getIntrinsicWidth4084);
}
internal static global::MonoJavaBridge.MethodId _getIntrinsicHeight4085;
public override int getIntrinsicHeight()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable._getIntrinsicHeight4085);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable.staticClass, global::android.graphics.drawable.LayerDrawable._getIntrinsicHeight4085);
}
internal static global::MonoJavaBridge.MethodId _getPadding4086;
public override bool getPadding(android.graphics.Rect arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable._getPadding4086, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable.staticClass, global::android.graphics.drawable.LayerDrawable._getPadding4086, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _mutate4087;
public override global::android.graphics.drawable.Drawable mutate()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable._mutate4087)) as android.graphics.drawable.Drawable;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable.staticClass, global::android.graphics.drawable.LayerDrawable._mutate4087)) as android.graphics.drawable.Drawable;
}
internal static global::MonoJavaBridge.MethodId _getConstantState4088;
public override global::android.graphics.drawable.Drawable.ConstantState getConstantState()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable._getConstantState4088)) as android.graphics.drawable.Drawable.ConstantState;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable.staticClass, global::android.graphics.drawable.LayerDrawable._getConstantState4088)) as android.graphics.drawable.Drawable.ConstantState;
}
internal static global::MonoJavaBridge.MethodId _invalidateDrawable4089;
public virtual void invalidateDrawable(android.graphics.drawable.Drawable arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable._invalidateDrawable4089, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable.staticClass, global::android.graphics.drawable.LayerDrawable._invalidateDrawable4089, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _scheduleDrawable4090;
public virtual void scheduleDrawable(android.graphics.drawable.Drawable arg0, java.lang.Runnable arg1, long arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable._scheduleDrawable4090, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable.staticClass, global::android.graphics.drawable.LayerDrawable._scheduleDrawable4090, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _unscheduleDrawable4091;
public virtual void unscheduleDrawable(android.graphics.drawable.Drawable arg0, java.lang.Runnable arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable._unscheduleDrawable4091, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable.staticClass, global::android.graphics.drawable.LayerDrawable._unscheduleDrawable4091, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _setId4092;
public virtual void setId(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable._setId4092, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable.staticClass, global::android.graphics.drawable.LayerDrawable._setId4092, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _findDrawableByLayerId4093;
public virtual global::android.graphics.drawable.Drawable findDrawableByLayerId(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable._findDrawableByLayerId4093, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.graphics.drawable.Drawable;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable.staticClass, global::android.graphics.drawable.LayerDrawable._findDrawableByLayerId4093, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.graphics.drawable.Drawable;
}
internal static global::MonoJavaBridge.MethodId _getNumberOfLayers4094;
public virtual int getNumberOfLayers()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable._getNumberOfLayers4094);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable.staticClass, global::android.graphics.drawable.LayerDrawable._getNumberOfLayers4094);
}
internal static global::MonoJavaBridge.MethodId _setDrawableByLayerId4095;
public virtual bool setDrawableByLayerId(int arg0, android.graphics.drawable.Drawable arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable._setDrawableByLayerId4095, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable.staticClass, global::android.graphics.drawable.LayerDrawable._setDrawableByLayerId4095, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _setLayerInset4096;
public virtual void setLayerInset(int arg0, int arg1, int arg2, int arg3, int arg4)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable._setLayerInset4096, 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));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.LayerDrawable.staticClass, global::android.graphics.drawable.LayerDrawable._setLayerInset4096, 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));
}
internal static global::MonoJavaBridge.MethodId _LayerDrawable4097;
public LayerDrawable(android.graphics.drawable.Drawable[] arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.graphics.drawable.LayerDrawable.staticClass, global::android.graphics.drawable.LayerDrawable._LayerDrawable4097, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.graphics.drawable.LayerDrawable.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/graphics/drawable/LayerDrawable"));
global::android.graphics.drawable.LayerDrawable._getId4070 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.LayerDrawable.staticClass, "getId", "(I)I");
global::android.graphics.drawable.LayerDrawable._inflate4071 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.LayerDrawable.staticClass, "inflate", "(Landroid/content/res/Resources;Lorg/xmlpull/v1/XmlPullParser;Landroid/util/AttributeSet;)V");
global::android.graphics.drawable.LayerDrawable._getDrawable4072 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.LayerDrawable.staticClass, "getDrawable", "(I)Landroid/graphics/drawable/Drawable;");
global::android.graphics.drawable.LayerDrawable._draw4073 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.LayerDrawable.staticClass, "draw", "(Landroid/graphics/Canvas;)V");
global::android.graphics.drawable.LayerDrawable._getChangingConfigurations4074 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.LayerDrawable.staticClass, "getChangingConfigurations", "()I");
global::android.graphics.drawable.LayerDrawable._setDither4075 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.LayerDrawable.staticClass, "setDither", "(Z)V");
global::android.graphics.drawable.LayerDrawable._setAlpha4076 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.LayerDrawable.staticClass, "setAlpha", "(I)V");
global::android.graphics.drawable.LayerDrawable._setColorFilter4077 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.LayerDrawable.staticClass, "setColorFilter", "(Landroid/graphics/ColorFilter;)V");
global::android.graphics.drawable.LayerDrawable._isStateful4078 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.LayerDrawable.staticClass, "isStateful", "()Z");
global::android.graphics.drawable.LayerDrawable._setVisible4079 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.LayerDrawable.staticClass, "setVisible", "(ZZ)Z");
global::android.graphics.drawable.LayerDrawable._getOpacity4080 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.LayerDrawable.staticClass, "getOpacity", "()I");
global::android.graphics.drawable.LayerDrawable._onStateChange4081 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.LayerDrawable.staticClass, "onStateChange", "([I)Z");
global::android.graphics.drawable.LayerDrawable._onLevelChange4082 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.LayerDrawable.staticClass, "onLevelChange", "(I)Z");
global::android.graphics.drawable.LayerDrawable._onBoundsChange4083 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.LayerDrawable.staticClass, "onBoundsChange", "(Landroid/graphics/Rect;)V");
global::android.graphics.drawable.LayerDrawable._getIntrinsicWidth4084 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.LayerDrawable.staticClass, "getIntrinsicWidth", "()I");
global::android.graphics.drawable.LayerDrawable._getIntrinsicHeight4085 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.LayerDrawable.staticClass, "getIntrinsicHeight", "()I");
global::android.graphics.drawable.LayerDrawable._getPadding4086 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.LayerDrawable.staticClass, "getPadding", "(Landroid/graphics/Rect;)Z");
global::android.graphics.drawable.LayerDrawable._mutate4087 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.LayerDrawable.staticClass, "mutate", "()Landroid/graphics/drawable/Drawable;");
global::android.graphics.drawable.LayerDrawable._getConstantState4088 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.LayerDrawable.staticClass, "getConstantState", "()Landroid/graphics/drawable/Drawable$ConstantState;");
global::android.graphics.drawable.LayerDrawable._invalidateDrawable4089 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.LayerDrawable.staticClass, "invalidateDrawable", "(Landroid/graphics/drawable/Drawable;)V");
global::android.graphics.drawable.LayerDrawable._scheduleDrawable4090 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.LayerDrawable.staticClass, "scheduleDrawable", "(Landroid/graphics/drawable/Drawable;Ljava/lang/Runnable;J)V");
global::android.graphics.drawable.LayerDrawable._unscheduleDrawable4091 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.LayerDrawable.staticClass, "unscheduleDrawable", "(Landroid/graphics/drawable/Drawable;Ljava/lang/Runnable;)V");
global::android.graphics.drawable.LayerDrawable._setId4092 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.LayerDrawable.staticClass, "setId", "(II)V");
global::android.graphics.drawable.LayerDrawable._findDrawableByLayerId4093 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.LayerDrawable.staticClass, "findDrawableByLayerId", "(I)Landroid/graphics/drawable/Drawable;");
global::android.graphics.drawable.LayerDrawable._getNumberOfLayers4094 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.LayerDrawable.staticClass, "getNumberOfLayers", "()I");
global::android.graphics.drawable.LayerDrawable._setDrawableByLayerId4095 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.LayerDrawable.staticClass, "setDrawableByLayerId", "(ILandroid/graphics/drawable/Drawable;)Z");
global::android.graphics.drawable.LayerDrawable._setLayerInset4096 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.LayerDrawable.staticClass, "setLayerInset", "(IIIII)V");
global::android.graphics.drawable.LayerDrawable._LayerDrawable4097 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.LayerDrawable.staticClass, "<init>", "([Landroid/graphics/drawable/Drawable;)V");
}
}
}
| |
// ************************ CommandLineArgs : char ************************
//
// PreArg : '-' = BeginDirective, default = Arg;
// Arg : default = Arg;
// BeginDirective : '-' = BeginExtendedDirective, default = Directive;
// Directive : default = Directive;
// BeginExtendedDirective : default = ExtendedDirective;
// ExtendedDirective : default = ExtendedDirective;
//
//
// This file was automatically generated from a tool that converted the
// above state machine definition into this state machine class.
// Any changes to this code will be replaced the next time the code is generated.
using System;
using System.Collections.Generic;
namespace test
{
public class CommandLineArgs
{
public enum States
{
PreArg = 0, Arg = 1,
BeginDirective = 2, Directive = 3,
BeginExtendedDirective = 4, ExtendedDirective = 5,
}
private States? state = null;
public States? CurrentState { get { return state; } }
private char currentCommand;
public char CurrentCommand { get { return currentCommand; } }
private bool reset = false;
private Action<char> onPreArgState = null;
private Action<char> onPreArgEnter = null;
private Action<char> onPreArgExit = null;
private Action<char> onArgState = null;
private Action<char> onArgEnter = null;
private Action<char> onArgExit = null;
private Action<char> onBeginDirectiveState = null;
private Action<char> onBeginDirectiveEnter = null;
private Action<char> onBeginDirectiveExit = null;
private Action<char> onDirectiveState = null;
private Action<char> onDirectiveEnter = null;
private Action<char> onDirectiveExit = null;
private Action<char> onBeginExtendedDirectiveState = null;
private Action<char> onBeginExtendedDirectiveEnter = null;
private Action<char> onBeginExtendedDirectiveExit = null;
private Action<char> onExtendedDirectiveState = null;
private Action<char> onExtendedDirectiveEnter = null;
private Action<char> onExtendedDirectiveExit = null;
private Action<char> onAccept = null;
private Action<char> onDecline = null;
private Action<char> onEnd = null;
public bool? Input(Queue<char> data)
{
if (reset)
state = null;
bool? result = null;
if (data == null)
return null;
Reset:
reset = false;
switch (state)
{
case null:
if (data.Count > 0)
{
state = States.PreArg;
goto ResumePreArg;
}
else
goto End;
case States.PreArg:
goto ResumePreArg;
case States.Arg:
goto ResumeArg;
case States.BeginDirective:
goto ResumeBeginDirective;
case States.Directive:
goto ResumeDirective;
case States.BeginExtendedDirective:
goto ResumeBeginExtendedDirective;
case States.ExtendedDirective:
goto ResumeExtendedDirective;
}
EnterPreArg:
state = States.PreArg;
if (onPreArgEnter != null)
onPreArgEnter(currentCommand);
if (onPreArgState != null)
onPreArgState(currentCommand);
ResumePreArg:
if (data.Count > 0)
currentCommand = data.Dequeue();
else
goto End;
switch (currentCommand)
{
case '-':
if (onPreArgExit != null)
onPreArgExit(currentCommand);
goto EnterBeginDirective;
default:
if (onPreArgExit != null)
onPreArgExit(currentCommand);
goto EnterArg;
}
EnterArg:
state = States.Arg;
if (onArgEnter != null)
onArgEnter(currentCommand);
Arg:
if (onArgState != null)
onArgState(currentCommand);
ResumeArg:
if (data.Count > 0)
currentCommand = data.Dequeue();
else
goto End;
switch (currentCommand)
{
default:
goto Arg;
}
EnterBeginDirective:
state = States.BeginDirective;
if (onBeginDirectiveEnter != null)
onBeginDirectiveEnter(currentCommand);
if (onBeginDirectiveState != null)
onBeginDirectiveState(currentCommand);
ResumeBeginDirective:
if (data.Count > 0)
currentCommand = data.Dequeue();
else
goto End;
switch (currentCommand)
{
case '-':
if (onBeginDirectiveExit != null)
onBeginDirectiveExit(currentCommand);
goto EnterBeginExtendedDirective;
default:
if (onBeginDirectiveExit != null)
onBeginDirectiveExit(currentCommand);
goto EnterDirective;
}
EnterDirective:
state = States.Directive;
if (onDirectiveEnter != null)
onDirectiveEnter(currentCommand);
Directive:
if (onDirectiveState != null)
onDirectiveState(currentCommand);
ResumeDirective:
if (data.Count > 0)
currentCommand = data.Dequeue();
else
goto End;
switch (currentCommand)
{
default:
goto Directive;
}
EnterBeginExtendedDirective:
state = States.BeginExtendedDirective;
if (onBeginExtendedDirectiveEnter != null)
onBeginExtendedDirectiveEnter(currentCommand);
if (onBeginExtendedDirectiveState != null)
onBeginExtendedDirectiveState(currentCommand);
ResumeBeginExtendedDirective:
if (data.Count > 0)
currentCommand = data.Dequeue();
else
goto End;
switch (currentCommand)
{
default:
if (onBeginExtendedDirectiveExit != null)
onBeginExtendedDirectiveExit(currentCommand);
goto EnterExtendedDirective;
}
EnterExtendedDirective:
state = States.ExtendedDirective;
if (onExtendedDirectiveEnter != null)
onExtendedDirectiveEnter(currentCommand);
ExtendedDirective:
if (onExtendedDirectiveState != null)
onExtendedDirectiveState(currentCommand);
ResumeExtendedDirective:
if (data.Count > 0)
currentCommand = data.Dequeue();
else
goto End;
switch (currentCommand)
{
default:
goto ExtendedDirective;
}
End:
if (onEnd != null)
onEnd(currentCommand);
if (reset)
{
goto Reset;
}
return result;
}
public void AddOnPreArg(Action<char> addedFunc)
{
onPreArgState += addedFunc;
}
public void AddOnArg(Action<char> addedFunc)
{
onArgState += addedFunc;
}
public void AddOnBeginDirective(Action<char> addedFunc)
{
onBeginDirectiveState += addedFunc;
}
public void AddOnDirective(Action<char> addedFunc)
{
onDirectiveState += addedFunc;
}
public void AddOnBeginExtendedDirective(Action<char> addedFunc)
{
onBeginExtendedDirectiveState += addedFunc;
}
public void AddOnExtendedDirective(Action<char> addedFunc)
{
onExtendedDirectiveState += addedFunc;
}
public void AddOnPreArgEnter(Action<char> addedFunc)
{
onPreArgEnter += addedFunc;
}
public void AddOnArgEnter(Action<char> addedFunc)
{
onArgEnter += addedFunc;
}
public void AddOnBeginDirectiveEnter(Action<char> addedFunc)
{
onBeginDirectiveEnter += addedFunc;
}
public void AddOnDirectiveEnter(Action<char> addedFunc)
{
onDirectiveEnter += addedFunc;
}
public void AddOnBeginExtendedDirectiveEnter(Action<char> addedFunc)
{
onBeginExtendedDirectiveEnter += addedFunc;
}
public void AddOnExtendedDirectiveEnter(Action<char> addedFunc)
{
onExtendedDirectiveEnter += addedFunc;
}
public void AddOnPreArgExit(Action<char> addedFunc)
{
onPreArgExit += addedFunc;
}
public void AddOnArgExit(Action<char> addedFunc)
{
onArgExit += addedFunc;
}
public void AddOnBeginDirectiveExit(Action<char> addedFunc)
{
onBeginDirectiveExit += addedFunc;
}
public void AddOnDirectiveExit(Action<char> addedFunc)
{
onDirectiveExit += addedFunc;
}
public void AddOnBeginExtendedDirectiveExit(Action<char> addedFunc)
{
onBeginExtendedDirectiveExit += addedFunc;
}
public void AddOnExtendedDirectiveExit(Action<char> addedFunc)
{
onExtendedDirectiveExit += addedFunc;
}
public void AddOnAccept(Action<char> addedFunc)
{
onAccept += addedFunc;
}
public void AddOnDecline(Action<char> addedFunc)
{
onDecline += addedFunc;
}
public void AddOnEnd(Action<char> addedFunc)
{
onEnd += addedFunc;
}
internal void addOnAllStates( Action<char> addedFunc )
{
onPreArgState += addedFunc;
onArgState += addedFunc;
onBeginDirectiveState += addedFunc;
onDirectiveState += addedFunc;
onBeginExtendedDirectiveState += addedFunc;
onExtendedDirectiveState += addedFunc;
}
public void ResetStateOnEnd()
{
state = null;
reset = true;
}
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// An office equipment store.
/// </summary>
public class OfficeEquipmentStore_Core : TypeCore, IStore
{
public OfficeEquipmentStore_Core()
{
this._TypeId = 191;
this._Id = "OfficeEquipmentStore";
this._Schema_Org_Url = "http://schema.org/OfficeEquipmentStore";
string label = "";
GetLabel(out label, "OfficeEquipmentStore", typeof(OfficeEquipmentStore_Core));
this._Label = label;
this._Ancestors = new int[]{266,193,155,252};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{252};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// The larger organization that this local business is a branch of, if any.
/// </summary>
private BranchOf_Core branchOf;
public BranchOf_Core BranchOf
{
get
{
return branchOf;
}
set
{
branchOf = value;
SetPropertyInstance(branchOf);
}
}
/// <summary>
/// A contact point for a person or organization.
/// </summary>
private ContactPoints_Core contactPoints;
public ContactPoints_Core ContactPoints
{
get
{
return contactPoints;
}
set
{
contactPoints = value;
SetPropertyInstance(contactPoints);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>).
/// </summary>
private CurrenciesAccepted_Core currenciesAccepted;
public CurrenciesAccepted_Core CurrenciesAccepted
{
get
{
return currenciesAccepted;
}
set
{
currenciesAccepted = value;
SetPropertyInstance(currenciesAccepted);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Email address.
/// </summary>
private Email_Core email;
public Email_Core Email
{
get
{
return email;
}
set
{
email = value;
SetPropertyInstance(email);
}
}
/// <summary>
/// People working for this organization.
/// </summary>
private Employees_Core employees;
public Employees_Core Employees
{
get
{
return employees;
}
set
{
employees = value;
SetPropertyInstance(employees);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// A person who founded this organization.
/// </summary>
private Founders_Core founders;
public Founders_Core Founders
{
get
{
return founders;
}
set
{
founders = value;
SetPropertyInstance(founders);
}
}
/// <summary>
/// The date that this organization was founded.
/// </summary>
private FoundingDate_Core foundingDate;
public FoundingDate_Core FoundingDate
{
get
{
return foundingDate;
}
set
{
foundingDate = value;
SetPropertyInstance(foundingDate);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// The location of the event or organization.
/// </summary>
private Location_Core location;
public Location_Core Location
{
get
{
return location;
}
set
{
location = value;
SetPropertyInstance(location);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// A member of this organization.
/// </summary>
private Members_Core members;
public Members_Core Members
{
get
{
return members;
}
set
{
members = value;
SetPropertyInstance(members);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code><time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\>Tuesdays and Thursdays 4-8pm</time></code>. <br/>- If a business is open 7 days a week, then it can be specified as <code><time itemprop=\openingHours\ datetime=\Mo-Su\>Monday through Sunday, all day</time></code>.
/// </summary>
private OpeningHours_Core openingHours;
public OpeningHours_Core OpeningHours
{
get
{
return openingHours;
}
set
{
openingHours = value;
SetPropertyInstance(openingHours);
}
}
/// <summary>
/// Cash, credit card, etc.
/// </summary>
private PaymentAccepted_Core paymentAccepted;
public PaymentAccepted_Core PaymentAccepted
{
get
{
return paymentAccepted;
}
set
{
paymentAccepted = value;
SetPropertyInstance(paymentAccepted);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// The price range of the business, for example <code>$$$</code>.
/// </summary>
private PriceRange_Core priceRange;
public PriceRange_Core PriceRange
{
get
{
return priceRange;
}
set
{
priceRange = value;
SetPropertyInstance(priceRange);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Security;
using System.Text;
using System.Threading;
namespace System.Diagnostics
{
/// <devdoc>
/// <para>
/// Provides access to local and remote
/// processes. Enables you to start and stop system processes.
/// </para>
/// </devdoc>
public partial class Process : Component
{
private bool _haveProcessId;
private int _processId;
private bool _haveProcessHandle;
private SafeProcessHandle _processHandle;
private bool _isRemoteMachine;
private string _machineName;
private ProcessInfo _processInfo;
private ProcessThreadCollection _threads;
private ProcessModuleCollection _modules;
private bool _haveWorkingSetLimits;
private IntPtr _minWorkingSet;
private IntPtr _maxWorkingSet;
private bool _haveProcessorAffinity;
private IntPtr _processorAffinity;
private bool _havePriorityClass;
private ProcessPriorityClass _priorityClass;
private ProcessStartInfo _startInfo;
private bool _watchForExit;
private bool _watchingForExit;
private EventHandler _onExited;
private bool _exited;
private int _exitCode;
private DateTime? _startTime;
private DateTime _exitTime;
private bool _haveExitTime;
private bool _priorityBoostEnabled;
private bool _havePriorityBoostEnabled;
private bool _raisedOnExited;
private RegisteredWaitHandle _registeredWaitHandle;
private WaitHandle _waitHandle;
private StreamReader _standardOutput;
private StreamWriter _standardInput;
private StreamReader _standardError;
private bool _disposed;
private bool _haveMainWindow;
private IntPtr _mainWindowHandle;
private string _mainWindowTitle;
private bool _haveResponding;
private bool _responding;
private static object s_createProcessLock = new object();
private StreamReadMode _outputStreamReadMode;
private StreamReadMode _errorStreamReadMode;
// Support for asynchronously reading streams
public event DataReceivedEventHandler OutputDataReceived;
public event DataReceivedEventHandler ErrorDataReceived;
// Abstract the stream details
internal AsyncStreamReader _output;
internal AsyncStreamReader _error;
internal bool _pendingOutputRead;
internal bool _pendingErrorRead;
#if FEATURE_TRACESWITCH
internal static TraceSwitch _processTracing =
#if DEBUG
new TraceSwitch("processTracing", "Controls debug output from Process component");
#else
null;
#endif
#endif
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Diagnostics.Process'/> class.
/// </para>
/// </devdoc>
public Process()
{
// This class once inherited a finalizer. For backward compatibility it has one so that
// any derived class that depends on it will see the behaviour expected. Since it is
// not used by this class itself, suppress it immediately if this is not an instance
// of a derived class it doesn't suffer the GC burden of finalization.
if (GetType() == typeof(Process))
{
GC.SuppressFinalize(this);
}
_machineName = ".";
_outputStreamReadMode = StreamReadMode.Undefined;
_errorStreamReadMode = StreamReadMode.Undefined;
}
private Process(string machineName, bool isRemoteMachine, int processId, ProcessInfo processInfo)
{
GC.SuppressFinalize(this);
_processInfo = processInfo;
_machineName = machineName;
_isRemoteMachine = isRemoteMachine;
_processId = processId;
_haveProcessId = true;
_outputStreamReadMode = StreamReadMode.Undefined;
_errorStreamReadMode = StreamReadMode.Undefined;
}
public SafeProcessHandle SafeHandle
{
get
{
EnsureState(State.Associated);
return OpenProcessHandle();
}
}
public IntPtr Handle => SafeHandle.DangerousGetHandle();
/// <devdoc>
/// Returns whether this process component is associated with a real process.
/// </devdoc>
/// <internalonly/>
bool Associated
{
get { return _haveProcessId || _haveProcessHandle; }
}
/// <devdoc>
/// <para>
/// Gets the base priority of
/// the associated process.
/// </para>
/// </devdoc>
public int BasePriority
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.BasePriority;
}
}
/// <devdoc>
/// <para>
/// Gets
/// the
/// value that was specified by the associated process when it was terminated.
/// </para>
/// </devdoc>
public int ExitCode
{
get
{
EnsureState(State.Exited);
return _exitCode;
}
}
/// <devdoc>
/// <para>
/// Gets a
/// value indicating whether the associated process has been terminated.
/// </para>
/// </devdoc>
public bool HasExited
{
get
{
if (!_exited)
{
EnsureState(State.Associated);
UpdateHasExited();
if (_exited)
{
RaiseOnExited();
}
}
return _exited;
}
}
/// <summary>Gets the time the associated process was started.</summary>
public DateTime StartTime
{
get
{
if (!_startTime.HasValue)
{
_startTime = StartTimeCore;
}
return _startTime.Value;
}
}
/// <devdoc>
/// <para>
/// Gets the time that the associated process exited.
/// </para>
/// </devdoc>
public DateTime ExitTime
{
get
{
if (!_haveExitTime)
{
EnsureState(State.Exited);
_exitTime = ExitTimeCore;
_haveExitTime = true;
}
return _exitTime;
}
}
/// <devdoc>
/// <para>
/// Gets
/// the unique identifier for the associated process.
/// </para>
/// </devdoc>
public int Id
{
get
{
EnsureState(State.HaveId);
return _processId;
}
}
/// <devdoc>
/// <para>
/// Gets
/// the name of the computer on which the associated process is running.
/// </para>
/// </devdoc>
public string MachineName
{
get
{
EnsureState(State.Associated);
return _machineName;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the maximum allowable working set for the associated
/// process.
/// </para>
/// </devdoc>
public IntPtr MaxWorkingSet
{
get
{
EnsureWorkingSetLimits();
return _maxWorkingSet;
}
set
{
SetWorkingSetLimits(null, value);
}
}
/// <devdoc>
/// <para>
/// Gets or sets the minimum allowable working set for the associated
/// process.
/// </para>
/// </devdoc>
public IntPtr MinWorkingSet
{
get
{
EnsureWorkingSetLimits();
return _minWorkingSet;
}
set
{
SetWorkingSetLimits(value, null);
}
}
public ProcessModuleCollection Modules
{
get
{
if (_modules == null)
{
EnsureState(State.HaveId | State.IsLocal);
_modules = ProcessManager.GetModules(_processId);
}
return _modules;
}
}
public long NonpagedSystemMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PoolNonPagedBytes;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.NonpagedSystemMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public int NonpagedSystemMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.PoolNonPagedBytes);
}
}
public long PagedMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PageFileBytes;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PagedMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public int PagedMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.PageFileBytes);
}
}
public long PagedSystemMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PoolPagedBytes;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PagedSystemMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public int PagedSystemMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.PoolPagedBytes);
}
}
public long PeakPagedMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PageFileBytesPeak;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PeakPagedMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public int PeakPagedMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.PageFileBytesPeak);
}
}
public long PeakWorkingSet64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.WorkingSetPeak;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PeakWorkingSet64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public int PeakWorkingSet
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.WorkingSetPeak);
}
}
public long PeakVirtualMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.VirtualBytesPeak;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PeakVirtualMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public int PeakVirtualMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.VirtualBytesPeak);
}
}
/// <devdoc>
/// <para>
/// Gets or sets a value indicating whether the associated process priority
/// should be temporarily boosted by the operating system when the main window
/// has focus.
/// </para>
/// </devdoc>
public bool PriorityBoostEnabled
{
get
{
if (!_havePriorityBoostEnabled)
{
_priorityBoostEnabled = PriorityBoostEnabledCore;
_havePriorityBoostEnabled = true;
}
return _priorityBoostEnabled;
}
set
{
PriorityBoostEnabledCore = value;
_priorityBoostEnabled = value;
_havePriorityBoostEnabled = true;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the overall priority category for the
/// associated process.
/// </para>
/// </devdoc>
public ProcessPriorityClass PriorityClass
{
get
{
if (!_havePriorityClass)
{
_priorityClass = PriorityClassCore;
_havePriorityClass = true;
}
return _priorityClass;
}
set
{
if (!Enum.IsDefined(typeof(ProcessPriorityClass), value))
{
throw new ArgumentException(SR.Format(SR.InvalidEnumArgument, nameof(value), (int)value, typeof(ProcessPriorityClass)));
}
PriorityClassCore = value;
_priorityClass = value;
_havePriorityClass = true;
}
}
public long PrivateMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PrivateBytes;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PrivateMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public int PrivateMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.PrivateBytes);
}
}
/// <devdoc>
/// <para>
/// Gets
/// the friendly name of the process.
/// </para>
/// </devdoc>
public string ProcessName
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.ProcessName;
}
}
/// <devdoc>
/// <para>
/// Gets
/// or sets which processors the threads in this process can be scheduled to run on.
/// </para>
/// </devdoc>
public IntPtr ProcessorAffinity
{
get
{
if (!_haveProcessorAffinity)
{
_processorAffinity = ProcessorAffinityCore;
_haveProcessorAffinity = true;
}
return _processorAffinity;
}
set
{
ProcessorAffinityCore = value;
_processorAffinity = value;
_haveProcessorAffinity = true;
}
}
public int SessionId
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.SessionId;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the properties to pass into the <see cref='System.Diagnostics.Process.Start'/> method for the <see cref='System.Diagnostics.Process'/>
/// .
/// </para>
/// </devdoc>
public ProcessStartInfo StartInfo
{
get
{
if (_startInfo == null)
{
if (Associated)
{
throw new InvalidOperationException(SR.CantGetProcessStartInfo);
}
_startInfo = new ProcessStartInfo();
}
return _startInfo;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (Associated)
{
throw new InvalidOperationException(SR.CantSetProcessStartInfo);
}
_startInfo = value;
}
}
/// <devdoc>
/// <para>
/// Gets the set of threads that are running in the associated
/// process.
/// </para>
/// </devdoc>
public ProcessThreadCollection Threads
{
get
{
if (_threads == null)
{
EnsureState(State.HaveProcessInfo);
int count = _processInfo._threadInfoList.Count;
ProcessThread[] newThreadsArray = new ProcessThread[count];
for (int i = 0; i < count; i++)
{
newThreadsArray[i] = new ProcessThread(_isRemoteMachine, _processId, (ThreadInfo)_processInfo._threadInfoList[i]);
}
ProcessThreadCollection newThreads = new ProcessThreadCollection(newThreadsArray);
_threads = newThreads;
}
return _threads;
}
}
public int HandleCount
{
get
{
EnsureState(State.HaveProcessInfo);
EnsureHandleCountPopulated();
return _processInfo.HandleCount;
}
}
partial void EnsureHandleCountPopulated();
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.VirtualMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public long VirtualMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.VirtualBytes;
}
}
public int VirtualMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.VirtualBytes);
}
}
/// <devdoc>
/// <para>
/// Gets or sets whether the <see cref='System.Diagnostics.Process.Exited'/>
/// event is fired
/// when the process terminates.
/// </para>
/// </devdoc>
public bool EnableRaisingEvents
{
get
{
return _watchForExit;
}
set
{
if (value != _watchForExit)
{
if (Associated)
{
if (value)
{
OpenProcessHandle();
EnsureWatchingForExit();
}
else
{
StopWatchingForExit();
}
}
_watchForExit = value;
}
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public StreamWriter StandardInput
{
get
{
if (_standardInput == null)
{
throw new InvalidOperationException(SR.CantGetStandardIn);
}
return _standardInput;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public StreamReader StandardOutput
{
get
{
if (_standardOutput == null)
{
throw new InvalidOperationException(SR.CantGetStandardOut);
}
if (_outputStreamReadMode == StreamReadMode.Undefined)
{
_outputStreamReadMode = StreamReadMode.SyncMode;
}
else if (_outputStreamReadMode != StreamReadMode.SyncMode)
{
throw new InvalidOperationException(SR.CantMixSyncAsyncOperation);
}
return _standardOutput;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public StreamReader StandardError
{
get
{
if (_standardError == null)
{
throw new InvalidOperationException(SR.CantGetStandardError);
}
if (_errorStreamReadMode == StreamReadMode.Undefined)
{
_errorStreamReadMode = StreamReadMode.SyncMode;
}
else if (_errorStreamReadMode != StreamReadMode.SyncMode)
{
throw new InvalidOperationException(SR.CantMixSyncAsyncOperation);
}
return _standardError;
}
}
public long WorkingSet64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.WorkingSet;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.WorkingSet64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public int WorkingSet
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.WorkingSet);
}
}
public event EventHandler Exited
{
add
{
_onExited += value;
}
remove
{
_onExited -= value;
}
}
/// <devdoc>
/// Release the temporary handle we used to get process information.
/// If we used the process handle stored in the process object (we have all access to the handle,) don't release it.
/// </devdoc>
/// <internalonly/>
private void ReleaseProcessHandle(SafeProcessHandle handle)
{
if (handle == null)
{
return;
}
if (_haveProcessHandle && handle == _processHandle)
{
return;
}
#if FEATURE_TRACESWITCH
Debug.WriteLineIf(_processTracing.TraceVerbose, "Process - CloseHandle(process)");
#endif
handle.Dispose();
}
/// <devdoc>
/// This is called from the threadpool when a process exits.
/// </devdoc>
/// <internalonly/>
private void CompletionCallback(object context, bool wasSignaled)
{
StopWatchingForExit();
RaiseOnExited();
}
/// <internalonly/>
/// <devdoc>
/// <para>
/// Free any resources associated with this component.
/// </para>
/// </devdoc>
protected override void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
//Dispose managed and unmanaged resources
Close();
}
_disposed = true;
}
}
public bool Responding
{
get
{
if (!_haveResponding)
{
_responding = IsRespondingCore();
_haveResponding = true;
}
return _responding;
}
}
public string MainWindowTitle
{
get
{
if (_mainWindowTitle == null)
{
_mainWindowTitle = GetMainWindowTitle();
}
return _mainWindowTitle;
}
}
public bool CloseMainWindow()
{
return CloseMainWindowCore();
}
public bool WaitForInputIdle()
{
return WaitForInputIdle(int.MaxValue);
}
public bool WaitForInputIdle(int milliseconds)
{
return WaitForInputIdleCore(milliseconds);
}
public IntPtr MainWindowHandle
{
get
{
if (!_haveMainWindow)
{
EnsureState(State.IsLocal | State.HaveId);
_mainWindowHandle = ProcessManager.GetMainWindowHandle(_processId);
_haveMainWindow = true;
}
return _mainWindowHandle;
}
}
public ISynchronizeInvoke SynchronizingObject { get; set; }
/// <devdoc>
/// <para>
/// Frees any resources associated with this component.
/// </para>
/// </devdoc>
public void Close()
{
if (Associated)
{
if (_haveProcessHandle)
{
StopWatchingForExit();
#if FEATURE_TRACESWITCH
Debug.WriteLineIf(_processTracing.TraceVerbose, "Process - CloseHandle(process) in Close()");
#endif
_processHandle.Dispose();
_processHandle = null;
_haveProcessHandle = false;
}
_haveProcessId = false;
_isRemoteMachine = false;
_machineName = ".";
_raisedOnExited = false;
//Don't call close on the Readers and writers
//since they might be referenced by somebody else while the
//process is still alive but this method called.
_standardOutput = null;
_standardInput = null;
_standardError = null;
_output = null;
_error = null;
CloseCore();
Refresh();
}
}
/// <devdoc>
/// Helper method for checking preconditions when accessing properties.
/// </devdoc>
/// <internalonly/>
private void EnsureState(State state)
{
if ((state & State.Associated) != (State)0)
if (!Associated)
throw new InvalidOperationException(SR.NoAssociatedProcess);
if ((state & State.HaveId) != (State)0)
{
if (!_haveProcessId)
{
if (_haveProcessHandle)
{
SetProcessId(ProcessManager.GetProcessIdFromHandle(_processHandle));
}
else
{
EnsureState(State.Associated);
throw new InvalidOperationException(SR.ProcessIdRequired);
}
}
}
if ((state & State.IsLocal) != (State)0 && _isRemoteMachine)
{
throw new NotSupportedException(SR.NotSupportedRemote);
}
if ((state & State.HaveProcessInfo) != (State)0)
{
if (_processInfo == null)
{
if ((state & State.HaveId) == (State)0) EnsureState(State.HaveId);
_processInfo = ProcessManager.GetProcessInfo(_processId, _machineName);
if (_processInfo == null)
{
throw new InvalidOperationException(SR.NoProcessInfo);
}
}
}
if ((state & State.Exited) != (State)0)
{
if (!HasExited)
{
throw new InvalidOperationException(SR.WaitTillExit);
}
if (!_haveProcessHandle)
{
throw new InvalidOperationException(SR.NoProcessHandle);
}
}
}
/// <devdoc>
/// Make sure we are watching for a process exit.
/// </devdoc>
/// <internalonly/>
private void EnsureWatchingForExit()
{
if (!_watchingForExit)
{
lock (this)
{
if (!_watchingForExit)
{
Debug.Assert(_haveProcessHandle, "Process.EnsureWatchingForExit called with no process handle");
Debug.Assert(Associated, "Process.EnsureWatchingForExit called with no associated process");
_watchingForExit = true;
try
{
_waitHandle = new ProcessWaitHandle(_processHandle);
_registeredWaitHandle = ThreadPool.RegisterWaitForSingleObject(_waitHandle,
new WaitOrTimerCallback(CompletionCallback), null, -1, true);
}
catch
{
_watchingForExit = false;
throw;
}
}
}
}
}
/// <devdoc>
/// Make sure we have obtained the min and max working set limits.
/// </devdoc>
/// <internalonly/>
private void EnsureWorkingSetLimits()
{
if (!_haveWorkingSetLimits)
{
GetWorkingSetLimits(out _minWorkingSet, out _maxWorkingSet);
_haveWorkingSetLimits = true;
}
}
/// <devdoc>
/// Helper to set minimum or maximum working set limits.
/// </devdoc>
/// <internalonly/>
private void SetWorkingSetLimits(IntPtr? min, IntPtr? max)
{
SetWorkingSetLimitsCore(min, max, out _minWorkingSet, out _maxWorkingSet);
_haveWorkingSetLimits = true;
}
/// <devdoc>
/// <para>
/// Returns a new <see cref='System.Diagnostics.Process'/> component given a process identifier and
/// the name of a computer in the network.
/// </para>
/// </devdoc>
public static Process GetProcessById(int processId, string machineName)
{
if (!ProcessManager.IsProcessRunning(processId, machineName))
{
throw new ArgumentException(SR.Format(SR.MissingProccess, processId.ToString(CultureInfo.CurrentCulture)));
}
return new Process(machineName, ProcessManager.IsRemoteMachine(machineName), processId, null);
}
/// <devdoc>
/// <para>
/// Returns a new <see cref='System.Diagnostics.Process'/> component given the
/// identifier of a process on the local computer.
/// </para>
/// </devdoc>
public static Process GetProcessById(int processId)
{
return GetProcessById(processId, ".");
}
/// <devdoc>
/// <para>
/// Creates an array of <see cref='System.Diagnostics.Process'/> components that are
/// associated
/// with process resources on the
/// local computer. These process resources share the specified process name.
/// </para>
/// </devdoc>
public static Process[] GetProcessesByName(string processName)
{
return GetProcessesByName(processName, ".");
}
/// <devdoc>
/// <para>
/// Creates a new <see cref='System.Diagnostics.Process'/>
/// component for each process resource on the local computer.
/// </para>
/// </devdoc>
public static Process[] GetProcesses()
{
return GetProcesses(".");
}
/// <devdoc>
/// <para>
/// Creates a new <see cref='System.Diagnostics.Process'/>
/// component for each
/// process resource on the specified computer.
/// </para>
/// </devdoc>
public static Process[] GetProcesses(string machineName)
{
bool isRemoteMachine = ProcessManager.IsRemoteMachine(machineName);
ProcessInfo[] processInfos = ProcessManager.GetProcessInfos(machineName);
Process[] processes = new Process[processInfos.Length];
for (int i = 0; i < processInfos.Length; i++)
{
ProcessInfo processInfo = processInfos[i];
processes[i] = new Process(machineName, isRemoteMachine, processInfo.ProcessId, processInfo);
}
#if FEATURE_TRACESWITCH
Debug.WriteLineIf(_processTracing.TraceVerbose, "Process.GetProcesses(" + machineName + ")");
#if DEBUG
if (_processTracing.TraceVerbose) {
Debug.Indent();
for (int i = 0; i < processInfos.Length; i++) {
Debug.WriteLine(processes[i].Id + ": " + processes[i].ProcessName);
}
Debug.Unindent();
}
#endif
#endif
return processes;
}
/// <devdoc>
/// <para>
/// Returns a new <see cref='System.Diagnostics.Process'/>
/// component and associates it with the current active process.
/// </para>
/// </devdoc>
public static Process GetCurrentProcess()
{
return new Process(".", false, GetCurrentProcessId(), null);
}
/// <devdoc>
/// <para>
/// Raises the <see cref='System.Diagnostics.Process.Exited'/> event.
/// </para>
/// </devdoc>
protected void OnExited()
{
EventHandler exited = _onExited;
if (exited != null)
{
exited(this, EventArgs.Empty);
}
}
/// <devdoc>
/// Raise the Exited event, but make sure we don't do it more than once.
/// </devdoc>
/// <internalonly/>
private void RaiseOnExited()
{
if (!_raisedOnExited)
{
lock (this)
{
if (!_raisedOnExited)
{
_raisedOnExited = true;
OnExited();
}
}
}
}
/// <devdoc>
/// <para>
/// Discards any information about the associated process
/// that has been cached inside the process component. After <see cref='System.Diagnostics.Process.Refresh'/> is called, the
/// first request for information for each property causes the process component
/// to obtain a new value from the associated process.
/// </para>
/// </devdoc>
public void Refresh()
{
_processInfo = null;
_threads = null;
_modules = null;
_exited = false;
_haveWorkingSetLimits = false;
_haveProcessorAffinity = false;
_havePriorityClass = false;
_haveExitTime = false;
_havePriorityBoostEnabled = false;
RefreshCore();
}
/// <summary>
/// Opens a long-term handle to the process, with all access. If a handle exists,
/// then it is reused. If the process has exited, it throws an exception.
/// </summary>
private SafeProcessHandle OpenProcessHandle()
{
if (!_haveProcessHandle)
{
//Cannot open a new process handle if the object has been disposed, since finalization has been suppressed.
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
SetProcessHandle(GetProcessHandle());
}
return _processHandle;
}
/// <devdoc>
/// Helper to associate a process handle with this component.
/// </devdoc>
/// <internalonly/>
private void SetProcessHandle(SafeProcessHandle processHandle)
{
_processHandle = processHandle;
_haveProcessHandle = true;
if (_watchForExit)
{
EnsureWatchingForExit();
}
}
/// <devdoc>
/// Helper to associate a process id with this component.
/// </devdoc>
/// <internalonly/>
private void SetProcessId(int processId)
{
_processId = processId;
_haveProcessId = true;
ConfigureAfterProcessIdSet();
}
/// <summary>Additional optional configuration hook after a process ID is set.</summary>
partial void ConfigureAfterProcessIdSet();
/// <devdoc>
/// <para>
/// Starts a process specified by the <see cref='System.Diagnostics.Process.StartInfo'/> property of this <see cref='System.Diagnostics.Process'/>
/// component and associates it with the
/// <see cref='System.Diagnostics.Process'/> . If a process resource is reused
/// rather than started, the reused process is associated with this <see cref='System.Diagnostics.Process'/>
/// component.
/// </para>
/// </devdoc>
public bool Start()
{
Close();
ProcessStartInfo startInfo = StartInfo;
if (startInfo.FileName.Length == 0)
{
throw new InvalidOperationException(SR.FileNameMissing);
}
if (startInfo.StandardOutputEncoding != null && !startInfo.RedirectStandardOutput)
{
throw new InvalidOperationException(SR.StandardOutputEncodingNotAllowed);
}
if (startInfo.StandardErrorEncoding != null && !startInfo.RedirectStandardError)
{
throw new InvalidOperationException(SR.StandardErrorEncodingNotAllowed);
}
//Cannot start a new process and store its handle if the object has been disposed, since finalization has been suppressed.
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return StartCore(startInfo);
}
/// <devdoc>
/// <para>
/// Starts a process resource by specifying the name of a
/// document or application file. Associates the process resource with a new <see cref='System.Diagnostics.Process'/>
/// component.
/// </para>
/// </devdoc>
public static Process Start(string fileName)
{
return Start(new ProcessStartInfo(fileName));
}
/// <devdoc>
/// <para>
/// Starts a process resource by specifying the name of an
/// application and a set of command line arguments. Associates the process resource
/// with a new <see cref='System.Diagnostics.Process'/>
/// component.
/// </para>
/// </devdoc>
public static Process Start(string fileName, string arguments)
{
return Start(new ProcessStartInfo(fileName, arguments));
}
/// <devdoc>
/// <para>
/// Starts a process resource specified by the process start
/// information passed in, for example the file name of the process to start.
/// Associates the process resource with a new <see cref='System.Diagnostics.Process'/>
/// component.
/// </para>
/// </devdoc>
public static Process Start(ProcessStartInfo startInfo)
{
Process process = new Process();
if (startInfo == null)
throw new ArgumentNullException(nameof(startInfo));
process.StartInfo = startInfo;
return process.Start() ?
process :
null;
}
/// <devdoc>
/// Make sure we are not watching for process exit.
/// </devdoc>
/// <internalonly/>
private void StopWatchingForExit()
{
if (_watchingForExit)
{
RegisteredWaitHandle rwh = null;
WaitHandle wh = null;
lock (this)
{
if (_watchingForExit)
{
_watchingForExit = false;
wh = _waitHandle;
_waitHandle = null;
rwh = _registeredWaitHandle;
_registeredWaitHandle = null;
}
}
if (rwh != null)
{
rwh.Unregister(null);
}
if (wh != null)
{
wh.Dispose();
}
}
}
public override string ToString()
{
if (Associated)
{
string processName = ProcessName;
if (processName.Length != 0)
{
return String.Format(CultureInfo.CurrentCulture, "{0} ({1})", base.ToString(), processName);
}
}
return base.ToString();
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to wait
/// indefinitely for the associated process to exit.
/// </para>
/// </devdoc>
public void WaitForExit()
{
WaitForExit(Timeout.Infinite);
}
/// <summary>
/// Instructs the Process component to wait the specified number of milliseconds for
/// the associated process to exit.
/// </summary>
public bool WaitForExit(int milliseconds)
{
bool exited = WaitForExitCore(milliseconds);
if (exited && _watchForExit)
{
RaiseOnExited();
}
return exited;
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to start
/// reading the StandardOutput stream asynchronously. The user can register a callback
/// that will be called when a line of data terminated by \n,\r or \r\n is reached, or the end of stream is reached
/// then the remaining information is returned. The user can add an event handler to OutputDataReceived.
/// </para>
/// </devdoc>
public void BeginOutputReadLine()
{
if (_outputStreamReadMode == StreamReadMode.Undefined)
{
_outputStreamReadMode = StreamReadMode.AsyncMode;
}
else if (_outputStreamReadMode != StreamReadMode.AsyncMode)
{
throw new InvalidOperationException(SR.CantMixSyncAsyncOperation);
}
if (_pendingOutputRead)
throw new InvalidOperationException(SR.PendingAsyncOperation);
_pendingOutputRead = true;
// We can't detect if there's a pending synchronous read, stream also doesn't.
if (_output == null)
{
if (_standardOutput == null)
{
throw new InvalidOperationException(SR.CantGetStandardOut);
}
Stream s = _standardOutput.BaseStream;
_output = new AsyncStreamReader(s, OutputReadNotifyUser, _standardOutput.CurrentEncoding);
}
_output.BeginReadLine();
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to start
/// reading the StandardError stream asynchronously. The user can register a callback
/// that will be called when a line of data terminated by \n,\r or \r\n is reached, or the end of stream is reached
/// then the remaining information is returned. The user can add an event handler to ErrorDataReceived.
/// </para>
/// </devdoc>
public void BeginErrorReadLine()
{
if (_errorStreamReadMode == StreamReadMode.Undefined)
{
_errorStreamReadMode = StreamReadMode.AsyncMode;
}
else if (_errorStreamReadMode != StreamReadMode.AsyncMode)
{
throw new InvalidOperationException(SR.CantMixSyncAsyncOperation);
}
if (_pendingErrorRead)
{
throw new InvalidOperationException(SR.PendingAsyncOperation);
}
_pendingErrorRead = true;
// We can't detect if there's a pending synchronous read, stream also doesn't.
if (_error == null)
{
if (_standardError == null)
{
throw new InvalidOperationException(SR.CantGetStandardError);
}
Stream s = _standardError.BaseStream;
_error = new AsyncStreamReader(s, ErrorReadNotifyUser, _standardError.CurrentEncoding);
}
_error.BeginReadLine();
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to cancel the asynchronous operation
/// specified by BeginOutputReadLine().
/// </para>
/// </devdoc>
public void CancelOutputRead()
{
if (_output != null)
{
_output.CancelOperation();
}
else
{
throw new InvalidOperationException(SR.NoAsyncOperation);
}
_pendingOutputRead = false;
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to cancel the asynchronous operation
/// specified by BeginErrorReadLine().
/// </para>
/// </devdoc>
public void CancelErrorRead()
{
if (_error != null)
{
_error.CancelOperation();
}
else
{
throw new InvalidOperationException(SR.NoAsyncOperation);
}
_pendingErrorRead = false;
}
internal void OutputReadNotifyUser(String data)
{
// To avoid race between remove handler and raising the event
DataReceivedEventHandler outputDataReceived = OutputDataReceived;
if (outputDataReceived != null)
{
DataReceivedEventArgs e = new DataReceivedEventArgs(data);
outputDataReceived(this, e); // Call back to user informing data is available
}
}
internal void ErrorReadNotifyUser(String data)
{
// To avoid race between remove handler and raising the event
DataReceivedEventHandler errorDataReceived = ErrorDataReceived;
if (errorDataReceived != null)
{
DataReceivedEventArgs e = new DataReceivedEventArgs(data);
errorDataReceived(this, e); // Call back to user informing data is available.
}
}
/// <summary>
/// This enum defines the operation mode for redirected process stream.
/// We don't support switching between synchronous mode and asynchronous mode.
/// </summary>
private enum StreamReadMode
{
Undefined,
SyncMode,
AsyncMode
}
/// <summary>A desired internal state.</summary>
private enum State
{
HaveId = 0x1,
IsLocal = 0x2,
HaveProcessInfo = 0x8,
Exited = 0x10,
Associated = 0x20,
}
}
}
| |
/*
* CP28593.cs - Latin 3 (ISO) code page.
*
* Copyright (c) 2002 Southern Storm Software, Pty Ltd
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// Generated from "ibm-913.ucm".
namespace I18N.West
{
using System;
using I18N.Common;
public class CP28593 : ByteEncoding
{
public CP28593()
: base(28593, ToChars, "Latin 3 (ISO)",
"iso-8859-3", "iso-8859-3", "iso-8859-3",
true, true, true, true, 28593)
{}
private static readonly char[] ToChars = {
'\u0000', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005',
'\u0006', '\u0007', '\u0008', '\u0009', '\u000A', '\u000B',
'\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011',
'\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017',
'\u0018', '\u0019', '\u001A', '\u001B', '\u001C', '\u001D',
'\u001E', '\u001F', '\u0020', '\u0021', '\u0022', '\u0023',
'\u0024', '\u0025', '\u0026', '\u0027', '\u0028', '\u0029',
'\u002A', '\u002B', '\u002C', '\u002D', '\u002E', '\u002F',
'\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035',
'\u0036', '\u0037', '\u0038', '\u0039', '\u003A', '\u003B',
'\u003C', '\u003D', '\u003E', '\u003F', '\u0040', '\u0041',
'\u0042', '\u0043', '\u0044', '\u0045', '\u0046', '\u0047',
'\u0048', '\u0049', '\u004A', '\u004B', '\u004C', '\u004D',
'\u004E', '\u004F', '\u0050', '\u0051', '\u0052', '\u0053',
'\u0054', '\u0055', '\u0056', '\u0057', '\u0058', '\u0059',
'\u005A', '\u005B', '\u005C', '\u005D', '\u005E', '\u005F',
'\u0060', '\u0061', '\u0062', '\u0063', '\u0064', '\u0065',
'\u0066', '\u0067', '\u0068', '\u0069', '\u006A', '\u006B',
'\u006C', '\u006D', '\u006E', '\u006F', '\u0070', '\u0071',
'\u0072', '\u0073', '\u0074', '\u0075', '\u0076', '\u0077',
'\u0078', '\u0079', '\u007A', '\u007B', '\u007C', '\u007D',
'\u007E', '\u007F', '\u0080', '\u0081', '\u0082', '\u0083',
'\u0084', '\u0085', '\u0086', '\u0087', '\u0088', '\u0089',
'\u008A', '\u008B', '\u008C', '\u008D', '\u008E', '\u008F',
'\u0090', '\u0091', '\u0092', '\u0093', '\u0094', '\u0095',
'\u0096', '\u0097', '\u0098', '\u0099', '\u009A', '\u009B',
'\u009C', '\u009D', '\u009E', '\u009F', '\u00A0', '\u0126',
'\u02D8', '\u00A3', '\u00A4', '\u003F', '\u0124', '\u00A7',
'\u00A8', '\u0130', '\u015E', '\u011E', '\u0134', '\u00AD',
'\u003F', '\u017B', '\u00B0', '\u0127', '\u00B2', '\u00B3',
'\u00B4', '\u00B5', '\u0125', '\u00B7', '\u00B8', '\u0131',
'\u015F', '\u011F', '\u0135', '\u00BD', '\u003F', '\u017C',
'\u00C0', '\u00C1', '\u00C2', '\u003F', '\u00C4', '\u010A',
'\u0108', '\u00C7', '\u00C8', '\u00C9', '\u00CA', '\u00CB',
'\u00CC', '\u00CD', '\u00CE', '\u00CF', '\u003F', '\u00D1',
'\u00D2', '\u00D3', '\u00D4', '\u0120', '\u00D6', '\u00D7',
'\u011C', '\u00D9', '\u00DA', '\u00DB', '\u00DC', '\u016C',
'\u015C', '\u00DF', '\u00E0', '\u00E1', '\u00E2', '\u003F',
'\u00E4', '\u010B', '\u0109', '\u00E7', '\u00E8', '\u00E9',
'\u00EA', '\u00EB', '\u00EC', '\u00ED', '\u00EE', '\u00EF',
'\u003F', '\u00F1', '\u00F2', '\u00F3', '\u00F4', '\u0121',
'\u00F6', '\u00F7', '\u011D', '\u00F9', '\u00FA', '\u00FB',
'\u00FC', '\u016D', '\u015D', '\u02D9',
};
protected override void ToBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(chars[charIndex++]);
if(ch >= 161) switch(ch)
{
case 0x00A3:
case 0x00A4:
case 0x00A7:
case 0x00A8:
case 0x00AD:
case 0x00B0:
case 0x00B2:
case 0x00B3:
case 0x00B4:
case 0x00B5:
case 0x00B7:
case 0x00B8:
case 0x00BD:
case 0x00C0:
case 0x00C1:
case 0x00C2:
case 0x00C4:
case 0x00C7:
case 0x00C8:
case 0x00C9:
case 0x00CA:
case 0x00CB:
case 0x00CC:
case 0x00CD:
case 0x00CE:
case 0x00CF:
case 0x00D1:
case 0x00D2:
case 0x00D3:
case 0x00D4:
case 0x00D6:
case 0x00D7:
case 0x00D9:
case 0x00DA:
case 0x00DB:
case 0x00DC:
case 0x00DF:
case 0x00E0:
case 0x00E1:
case 0x00E2:
case 0x00E4:
case 0x00E7:
case 0x00E8:
case 0x00E9:
case 0x00EA:
case 0x00EB:
case 0x00EC:
case 0x00ED:
case 0x00EE:
case 0x00EF:
case 0x00F1:
case 0x00F2:
case 0x00F3:
case 0x00F4:
case 0x00F6:
case 0x00F7:
case 0x00F9:
case 0x00FA:
case 0x00FB:
case 0x00FC:
break;
case 0x0108: ch = 0xC6; break;
case 0x0109: ch = 0xE6; break;
case 0x010A: ch = 0xC5; break;
case 0x010B: ch = 0xE5; break;
case 0x011C: ch = 0xD8; break;
case 0x011D: ch = 0xF8; break;
case 0x011E: ch = 0xAB; break;
case 0x011F: ch = 0xBB; break;
case 0x0120: ch = 0xD5; break;
case 0x0121: ch = 0xF5; break;
case 0x0124: ch = 0xA6; break;
case 0x0125: ch = 0xB6; break;
case 0x0126: ch = 0xA1; break;
case 0x0127: ch = 0xB1; break;
case 0x0130: ch = 0xA9; break;
case 0x0131: ch = 0xB9; break;
case 0x0134: ch = 0xAC; break;
case 0x0135: ch = 0xBC; break;
case 0x015C: ch = 0xDE; break;
case 0x015D: ch = 0xFE; break;
case 0x015E: ch = 0xAA; break;
case 0x015F: ch = 0xBA; break;
case 0x016C: ch = 0xDD; break;
case 0x016D: ch = 0xFD; break;
case 0x017B: ch = 0xAF; break;
case 0x017C: ch = 0xBF; break;
case 0x02D8: ch = 0xA2; break;
case 0x02D9: ch = 0xFF; break;
default:
{
if(ch >= 0xFF01 && ch <= 0xFF5E)
ch -= 0xFEE0;
else
ch = 0x3F;
}
break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
protected override void ToBytes(String s, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(s[charIndex++]);
if(ch >= 161) switch(ch)
{
case 0x00A3:
case 0x00A4:
case 0x00A7:
case 0x00A8:
case 0x00AD:
case 0x00B0:
case 0x00B2:
case 0x00B3:
case 0x00B4:
case 0x00B5:
case 0x00B7:
case 0x00B8:
case 0x00BD:
case 0x00C0:
case 0x00C1:
case 0x00C2:
case 0x00C4:
case 0x00C7:
case 0x00C8:
case 0x00C9:
case 0x00CA:
case 0x00CB:
case 0x00CC:
case 0x00CD:
case 0x00CE:
case 0x00CF:
case 0x00D1:
case 0x00D2:
case 0x00D3:
case 0x00D4:
case 0x00D6:
case 0x00D7:
case 0x00D9:
case 0x00DA:
case 0x00DB:
case 0x00DC:
case 0x00DF:
case 0x00E0:
case 0x00E1:
case 0x00E2:
case 0x00E4:
case 0x00E7:
case 0x00E8:
case 0x00E9:
case 0x00EA:
case 0x00EB:
case 0x00EC:
case 0x00ED:
case 0x00EE:
case 0x00EF:
case 0x00F1:
case 0x00F2:
case 0x00F3:
case 0x00F4:
case 0x00F6:
case 0x00F7:
case 0x00F9:
case 0x00FA:
case 0x00FB:
case 0x00FC:
break;
case 0x0108: ch = 0xC6; break;
case 0x0109: ch = 0xE6; break;
case 0x010A: ch = 0xC5; break;
case 0x010B: ch = 0xE5; break;
case 0x011C: ch = 0xD8; break;
case 0x011D: ch = 0xF8; break;
case 0x011E: ch = 0xAB; break;
case 0x011F: ch = 0xBB; break;
case 0x0120: ch = 0xD5; break;
case 0x0121: ch = 0xF5; break;
case 0x0124: ch = 0xA6; break;
case 0x0125: ch = 0xB6; break;
case 0x0126: ch = 0xA1; break;
case 0x0127: ch = 0xB1; break;
case 0x0130: ch = 0xA9; break;
case 0x0131: ch = 0xB9; break;
case 0x0134: ch = 0xAC; break;
case 0x0135: ch = 0xBC; break;
case 0x015C: ch = 0xDE; break;
case 0x015D: ch = 0xFE; break;
case 0x015E: ch = 0xAA; break;
case 0x015F: ch = 0xBA; break;
case 0x016C: ch = 0xDD; break;
case 0x016D: ch = 0xFD; break;
case 0x017B: ch = 0xAF; break;
case 0x017C: ch = 0xBF; break;
case 0x02D8: ch = 0xA2; break;
case 0x02D9: ch = 0xFF; break;
default:
{
if(ch >= 0xFF01 && ch <= 0xFF5E)
ch -= 0xFEE0;
else
ch = 0x3F;
}
break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
}; // class CP28593
public class ENCiso_8859_3 : CP28593
{
public ENCiso_8859_3() : base() {}
}; // class ENCiso_8859_3
}; // namespace I18N.West
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.Data;
using System.Windows.Forms;
using System.Diagnostics;
using FPU = GuruComponents.Netrix.UserInterface.FontPicker;
namespace GuruComponents.Netrix.UserInterface.FontPicker
{
/// <summary>
/// This class realises the FontPicker UserControl
/// </summary>
/// <remarks>
/// The user control shows a font selection box and allows
/// the user to selected multiple fonts from different lists. Used for the style sheet editor and
/// in the PropertyGrid.
/// <para>
/// To protect the user interface the width of the control is limited to 168 pixel.
/// </para>
/// </remarks>
[ToolboxItem(true)]
[ToolboxBitmap(typeof(GuruComponents.Netrix.UserInterface.ResourceManager), "ToolBox.FontPicker.ico")]
[Designer(typeof(GuruComponents.Netrix.UserInterface.NetrixUIDesigner))]
public class FontPickerUserControl : System.Windows.Forms.UserControl
{
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Button btnAddEdit;
private System.Windows.Forms.Button btnRemove;
private System.Windows.Forms.Button btnUp;
private System.Windows.Forms.Button btnDown;
private FPU.FontListBox fontListBox;
private FPU.FontPickerBox ff;
private System.Windows.Forms.Label labelInnerTitle;
private ContentChangedEventHandler contentChangedHandler;
private System.Windows.Forms.Panel panelControl;
private ImageList imageListFF;
private IContainer components;
#region Component Designer generated code
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if( components != null )
components.Dispose();
}
base.Dispose( disposing );
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FontPickerUserControl));
this.btnAddEdit = new System.Windows.Forms.Button();
this.imageListFF = new System.Windows.Forms.ImageList(this.components);
this.panel1 = new System.Windows.Forms.Panel();
this.btnRemove = new System.Windows.Forms.Button();
this.btnUp = new System.Windows.Forms.Button();
this.btnDown = new System.Windows.Forms.Button();
this.labelInnerTitle = new System.Windows.Forms.Label();
this.panelControl = new System.Windows.Forms.Panel();
this.panel1.SuspendLayout();
this.panelControl.SuspendLayout();
this.SuspendLayout();
//
// btnAddEdit
//
this.btnAddEdit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnAddEdit.BackColor = System.Drawing.Color.White;
this.btnAddEdit.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.btnAddEdit.ImageIndex = 4;
this.btnAddEdit.ImageList = this.imageListFF;
this.btnAddEdit.Location = new System.Drawing.Point(160, 0);
this.btnAddEdit.Name = "btnAddEdit";
this.btnAddEdit.Size = new System.Drawing.Size(32, 23);
this.btnAddEdit.TabIndex = 1;
this.btnAddEdit.UseVisualStyleBackColor = false;
this.btnAddEdit.Click += new System.EventHandler(this.btnAddEdit_Click);
//
// imageListFF
//
this.imageListFF.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageListFF.ImageStream")));
this.imageListFF.TransparentColor = System.Drawing.Color.Transparent;
this.imageListFF.Images.SetKeyName(0, "AddFont.ico");
this.imageListFF.Images.SetKeyName(1, "RemoveFont.ico");
this.imageListFF.Images.SetKeyName(2, "FontUp.ico");
this.imageListFF.Images.SetKeyName(3, "FontDown.ico");
this.imageListFF.Images.SetKeyName(4, "AddFont.ico");
this.imageListFF.Images.SetKeyName(5, "RemoveFont.ico");
this.imageListFF.Images.SetKeyName(6, "FontUp.ico");
this.imageListFF.Images.SetKeyName(7, "FontDown.ico");
//
// panel1
//
this.panel1.BackColor = System.Drawing.SystemColors.Control;
this.panel1.Controls.Add(this.btnAddEdit);
this.panel1.Controls.Add(this.btnRemove);
this.panel1.Controls.Add(this.btnUp);
this.panel1.Controls.Add(this.btnDown);
this.panel1.Controls.Add(this.labelInnerTitle);
this.panel1.Dock = System.Windows.Forms.DockStyle.Top;
this.panel1.Location = new System.Drawing.Point(0, 0);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(288, 23);
this.panel1.TabIndex = 0;
//
// btnRemove
//
this.btnRemove.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnRemove.BackColor = System.Drawing.Color.White;
this.btnRemove.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.btnRemove.ImageIndex = 5;
this.btnRemove.ImageList = this.imageListFF;
this.btnRemove.Location = new System.Drawing.Point(192, 0);
this.btnRemove.Name = "btnRemove";
this.btnRemove.Size = new System.Drawing.Size(32, 23);
this.btnRemove.TabIndex = 2;
this.btnRemove.UseVisualStyleBackColor = false;
this.btnRemove.Click += new System.EventHandler(this.btnRemove_Click);
//
// btnUp
//
this.btnUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnUp.BackColor = System.Drawing.Color.White;
this.btnUp.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.btnUp.ImageIndex = 6;
this.btnUp.ImageList = this.imageListFF;
this.btnUp.Location = new System.Drawing.Point(224, 0);
this.btnUp.Name = "btnUp";
this.btnUp.Size = new System.Drawing.Size(32, 23);
this.btnUp.TabIndex = 3;
this.btnUp.UseVisualStyleBackColor = false;
this.btnUp.Click += new System.EventHandler(this.btnUp_Click);
//
// btnDown
//
this.btnDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnDown.BackColor = System.Drawing.Color.White;
this.btnDown.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.btnDown.ImageIndex = 7;
this.btnDown.ImageList = this.imageListFF;
this.btnDown.Location = new System.Drawing.Point(256, 0);
this.btnDown.Name = "btnDown";
this.btnDown.Size = new System.Drawing.Size(32, 23);
this.btnDown.TabIndex = 4;
this.btnDown.UseVisualStyleBackColor = false;
this.btnDown.Click += new System.EventHandler(this.btnDown_Click);
//
// labelInnerTitle
//
this.labelInnerTitle.Location = new System.Drawing.Point(0, 5);
this.labelInnerTitle.Name = "labelInnerTitle";
this.labelInnerTitle.Size = new System.Drawing.Size(192, 16);
this.labelInnerTitle.TabIndex = 1;
this.labelInnerTitle.Text = "Font";
//
// panelControl
//
this.panelControl.AllowDrop = true;
this.panelControl.Controls.Add(this.panel1);
this.panelControl.Dock = System.Windows.Forms.DockStyle.Fill;
this.panelControl.Location = new System.Drawing.Point(0, 0);
this.panelControl.Name = "panelControl";
this.panelControl.Size = new System.Drawing.Size(288, 144);
this.panelControl.TabIndex = 2;
//
// FontPickerUserControl
//
this.AllowDrop = true;
this.Controls.Add(this.panelControl);
this.Name = "FontPickerUserControl";
this.Size = new System.Drawing.Size(288, 144);
this.panel1.ResumeLayout(false);
this.panelControl.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The constructor is used to instantiate the control.
/// </summary>
/// <remarks>
/// This method sets the basix values and the localization. The list of selected fonts
/// is clear.
/// </remarks>
public FontPickerUserControl()
{
this.fontListBox = new GuruComponents.Netrix.UserInterface.FontPicker.FontListBox();
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
InitializeListbox();
SetUp();
}
internal FontPickerUserControl(bool @internal)
{
this.fontListBox = new GuruComponents.Netrix.UserInterface.FontPicker.FontListBox();
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
InitializeListbox();
SetUp();
}
private void InitializeListbox()
{
////
//// fontListBox
////
this.fontListBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.fontListBox.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.fontListBox.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
this.fontListBox.FamilyType = GuruComponents.Netrix.UserInterface.FontPicker.FontFamilyType.Web;
this.fontListBox.IntegralHeight = false;
this.fontListBox.ListType = GuruComponents.Netrix.UserInterface.FontPicker.ListBoxType.FontNameAndSample;
this.fontListBox.Location = new System.Drawing.Point(0, 24);
this.fontListBox.Name = "fontListBox";
this.fontListBox.SampleString = " - NET.RIX";
this.fontListBox.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended;
this.fontListBox.Size = new System.Drawing.Size(288, 120);
this.fontListBox.TabIndex = 1;
this.fontListBox.UserFonts = null;
//
this.panelControl.Controls.Add(this.fontListBox);
}
private void SetUp()
{
this.ff = new FPU.FontPickerBox();
this.ff.Name = "ff";
this.ff.Opacity = 1;
this.ff.ShowInTaskbar = false;
this.ff.Text = GuruComponents.Netrix.UserInterface.ResourceManager.GetString("FontPickerUserControl.ff.Text"); //"Font Selection Box";
this.ff.Visible = false;
this.ff.StartPosition = FormStartPosition.Manual;
this.ff.Location = this.PointToScreen(new System.Drawing.Point(0, 0));
btnAddEdit.GotFocus += new EventHandler( ButtonGotFocus );
btnRemove.GotFocus += new EventHandler( ButtonGotFocus );
btnUp.GotFocus += new EventHandler( ButtonGotFocus );
btnDown.GotFocus += new EventHandler( ButtonGotFocus );
fontListBox.Items.Clear();
this.fontListBox.DragDrop += new DragEventHandler(OnDragDrophandler);
this.fontListBox.DragEnter += new DragEventHandler(OnDragEnterHandler);
}
/// <summary>
/// The current Assembly version.
/// </summary>
/// <remarks>
/// This property returns the current assembly version to inform during design session about the assembly loaded.
/// </remarks>
[Browsable(true), Category("NetRix"), Description("Current Version. ReadOnly.")]
public string Version
{
get
{
return this.GetType().Assembly.GetName().Version.ToString();
}
}
private void OnDragEnterHandler(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Copy;
}
private void OnDragDrophandler(object sender, DragEventArgs e)
{
object o = e.Data.GetData(DataFormats.Text);
if (o != null)
{
this.fontListBox.NewItem(o.ToString());
}
else
{
System.Drawing.Text.PrivateFontCollection pfc = new System.Drawing.Text.PrivateFontCollection();
try
{
string[] FontName = (string[]) e.Data.GetData(DataFormats.FileDrop, true);
for (int f = 0; f < FontName.Length; f++)
{
pfc.AddFontFile(FontName[f]);
}
if (pfc.Families.Length > 0)
{
for (int i = 0; i < pfc.Families.Length; i++)
{
this.fontListBox.NewItem(((FontFamily)pfc.Families[i]).Name);
}
}
}
finally
{
pfc.Dispose();
}
}
}
/// <summary>
/// Reset the UI.
/// </summary>
/// <remarks>
/// The call will reset the localizable strings for the current culture.
/// </remarks>
public void ResetUI()
{
this.ff.Text = GuruComponents.Netrix.UserInterface.ResourceManager.GetString("FontPickerUserControl.ff.Text"); //"Font Selection Box";
this.ff.ResetUI();
}
/// <summary>
/// Caption of the window.
/// </summary>
/// <remarks>
/// This sets the text of the font box. It is not necessary to set this option because the
/// value is loaded from the satellite assemblies. Setting of this property is only required
/// if a different text is necessary.
/// </remarks>
[Browsable(true)]
[Description("Caption of the window.")]
[Category("NetRix")]
public string BoxCaption
{
set
{
this.ff.Text = value;
}
get
{
return this.ff.Text;
}
}
/// <summary>
/// The sample string used in the font list.
/// </summary>
/// <remarks>
/// This presets the sample string shown in the font list.
/// </remarks>
[Browsable(true)]
[Description("Sample string, shown after each font entry.")]
[Category("NetRix")]
public string SampleString
{
set
{
this.fontListBox.SampleString = value;
this.ff.SampleString = value;
}
get
{
return this.fontListBox.SampleString;
}
}
/// <summary>
/// Adds or removes the event handler for the event fired if any of the content is changed
/// </summary>
/// <remarks>
/// The event is fired if one of the fields has had a interaction with the user.
/// </remarks>
[Browsable(true)]
[Description("Event handler for the event fired if any of the content is changed.")]
[Category("NetRix")]
public event ContentChangedEventHandler ContentChanged
{
add
{
contentChangedHandler += value;
}
remove
{
contentChangedHandler -= value;
}
}
/// <summary>
/// Fired if the content of the list has changed.
/// </summary>
/// <param name="sender"></param>
private void OnContentChanged(object sender)
{
if (contentChangedHandler != null)
{
contentChangedHandler(sender, new EventArgs());
}
}
/// <summary>
/// Gets or sets the list of fonts using a comma separated string.
/// </summary>
/// <remarks>
/// This property transform the string collection used internally to populate a
/// comma separated list. This is for direct usage in the face or font-family attributes
/// which requires such a list.
/// </remarks>
[Browsable(true)]
[Description("Gets or sets the list of fonts using a comma separated string.")]
[Category("NetRix")]
public string PopulateStringList
{
get
{
string[] list = new string[fontListBox.Items.Count];
fontListBox.Items.CopyTo(list, 0);
return String.Join(",", list);
}
set
{
fontListBox.Items.Clear();
if (!value.Equals(String.Empty))
{
fontListBox.Items.AddRange(value.ToString().Split(','));
}
}
}
/// <summary>
/// Helps to protect the minimum measures of the control to more than 168 pixel.
/// </summary>
/// <remarks>
/// This is necessary to show the buttons and description text properly.
/// </remarks>
/// <param name="e"></param>
protected override void OnResize( EventArgs e )
{
if( this.Width < 168 )
{
this.Width = 168;
}
base.OnResize( e );
}
/// <summary>
/// Populates the inner list to transparent access.
/// </summary>
/// <remarks>
/// If the final application needs other types of font lists this property allows
/// the access to the base class list. This property is read only.
/// </remarks>
[Browsable(false)]
public System.Windows.Forms.ListBox.ObjectCollection Items
{
get
{
return this.fontListBox.Items;
}
}
/// <summary>
/// Gets or sets the border style around the control.
/// </summary>
[Browsable(true)]
[Description("Gets or sets the border style around the control.")]
[Category("NetRix")]
public BorderStyle Border
{
get
{
return this.panelControl.BorderStyle;
}
set
{
this.panelControl.BorderStyle = value;
}
}
/// <summary>
/// Allows the user to drop fonts onto the control.
/// </summary>
/// <remarks>
/// If dropping is allowed the listbox (not the entire control) will accept
/// fontnames (if strings are the data) or font objects from which the string is
/// extracted.
/// <para>
/// The control does not allow adding fonts more than once. If a font is added as string the whole string
/// is treated as one name. To allow users to add multiple fonts at the same time use the data type
/// <see cref="System.Windows.Forms.DataFormats.FileDrop">FileDrop</see>. The control expects that the path points
/// to a TrueType or OpenType font which exists on the local computer. The name will than be added to the
/// list. Font variants (Arial, Arial Bold, Arial Italics) are treated as one font and added only once,
/// as long as the fonts have the same base font.
/// </para>
/// <para>
/// Note: The control cannot be used as a drop source in the current version.
/// </para>
/// </remarks>
/// <example>
/// Assuming you have a button on your form and the AllowDrop property set to <c>true</c>. The button has
/// a property <c>Tag</c> set to "Arial". The following code will create a drag drop solution for adding
/// fonts to the list:
/// <code>
/// private void button_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
/// {
/// button1.DoDragDrop(((Button) sender).Tag.ToString(), DragDropEffects.Copy);
/// }
/// </code>
/// </example>
[Browsable(true)]
[Description("Allows the user to drop fonts onto the control.")]
[Category("NetRix")]
public new bool AllowDrop
{
get
{
return this.fontListBox.AllowDrop;
}
set
{
this.fontListBox.AllowDrop = value;
}
}
/// <summary>
/// Called if the button got the focus.
/// </summary>
/// <remarks>
/// Used to set the focus to the list instead to the button after the button was clicked.
/// </remarks>
/// <param name="e">The event arguments to put through to the handler.</param>
protected override void OnGotFocus( EventArgs e )
{
ButtonGotFocus( null, EventArgs.Empty );
}
private void ButtonGotFocus( object sender, EventArgs e )
{
fontListBox.Focus();
}
/// <summary>
/// Called if the Add (+) button has clicked. Shows the fontpicker list form.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnAddEdit_Click( object sender, EventArgs e )
{
this.ff.Location = this.PointToScreen(new System.Drawing.Point(0, 0));
if (ff.ShowDialog() == DialogResult.OK)
{
fontListBox.BeginUpdate();
foreach (string s in ff.SelectedFont)
{
fontListBox.NewItem(s);
fontListBox.SelectedIndex = -1;
}
fontListBox.EndUpdate();
}
this.OnContentChanged(sender);
}
/// <summary>
/// Gets or sets the Title of the Control, displayed left hand above the list.
/// </summary>
/// <remarks>
/// The title should only be set if the localized string is not appropriate.
/// </remarks>
[Browsable(true)]
[Description("Gets or sets the Title of the Control, displayed left hand above the list.")]
[Category("NetRix")]
public string Title
{
get
{
return labelInnerTitle.Text;
}
set
{
labelInnerTitle.Text = value;
}
}
/// <summary>
/// Called if the Remove (-) button was clicked.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnRemove_Click(object sender, System.EventArgs e)
{
fontListBox.RemoveSelected();
this.OnContentChanged(sender);
}
/// <summary>
/// Called if the Up button was clicked.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnUp_Click(object sender, System.EventArgs e)
{
fontListBox.MoveSelectedUp();
this.OnContentChanged(sender);
}
/// <summary>
/// Called if the down button was clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnDown_Click(object sender, System.EventArgs e)
{
fontListBox.MoveSelectedDown();
this.OnContentChanged(sender);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Orleans;
using Orleans.Concurrency;
using ProtoBuf;
namespace UnitTests.GrainInterfaces
{
[Serializable]
[GenerateSerializer]
public struct ValueTypeTestData
{
[Id(0)]
private readonly int intValue;
public ValueTypeTestData(int i)
{
intValue = i;
}
public int GetValue()
{
return intValue;
}
}
[Serializable]
[GenerateSerializer]
public enum TestEnum : byte
{
First,
Second,
Third
}
[Serializable]
[GenerateSerializer]
public enum CampaignEnemyTestType : sbyte
{
None = -1,
Brute = 0,
Enemy1,
Enemy2,
Enemy3
}
[GenerateSerializer]
public class ClassWithEnumTestData
{
[Id(0)]
public TestEnum EnumValue { get; set; }
[Id(1)]
public CampaignEnemyTestType Enemy { get; set; }
}
[ProtoContract]
[Serializable]
[GenerateSerializer]
public class LargeTestData
{
[ProtoMember(1)]
[Id(0)]
public string TestString { get; set; }
[ProtoMember(2)]
[Id(1)]
private readonly bool[] boolArray;
[ProtoMember(3)]
[Id(2)]
protected Dictionary<string, int> stringIntDict;
[ProtoMember(4)]
[Id(3)]
public TestEnum EnumValue { get; set; }
[ProtoMember(5)]
[Id(4)]
private readonly ClassWithEnumTestData[] classArray;
[ProtoMember(6)]
[Id(5)]
public string Description { get; set; }
public LargeTestData()
{
boolArray = new bool[20];
stringIntDict = new Dictionary<string, int>();
classArray = new ClassWithEnumTestData[50];
for (var i = 0; i < 50; i++)
{
classArray[i] = new ClassWithEnumTestData();
}
}
public void SetBit(int n, bool value = true)
{
boolArray[n] = value;
}
public bool GetBit(int n)
{
return boolArray[n];
}
public void SetEnemy(int n, CampaignEnemyTestType enemy)
{
classArray[n].Enemy = enemy;
}
public CampaignEnemyTestType GetEnemy(int n)
{
return classArray[n].Enemy;
}
public void SetNumber(string name, int value)
{
stringIntDict[name] = value;
}
public int GetNumber(string name)
{
return stringIntDict[name];
}
// This class is not actually used anywhere. It is here to test that the serializer generator properly handles
// nested generic classes. If it doesn't, then the generated serializer for this class will fail to compile.
[Serializable]
[GenerateSerializer]
public class NestedGeneric<T>
{
[Id(0)]
private T myT;
[Id(1)]
private string s;
public NestedGeneric(T t)
{
myT = t;
s = myT.ToString();
}
public override string ToString()
{
return s;
}
public void SetT(T t)
{
myT = t;
s = myT.ToString();
}
}
}
public interface IValueTypeTestGrain : IGrainWithGuidKey
{
Task<ValueTypeTestData> GetStateData();
Task SetStateData(ValueTypeTestData d);
}
public interface IRoundtripSerializationGrain : IGrainWithIntegerKey
{
Task<CampaignEnemyTestType> GetEnemyType();
Task<object> GetClosedGenericValue();
Task<RetVal> GetRetValForParamVal(ParamVal param);
}
[GenerateSerializer]
public record ParamVal([field: Id(0)] int Value);
[GenerateSerializer]
public record RetVal([field: Id(0)] int Value);
[Serializable]
[Immutable]
[GenerateSerializer]
public class ImmutableType
{
[Id(0)]
private readonly int a;
[Id(1)]
private readonly int b;
public int A { get { return a; } }
public int B { get { return b; } }
public ImmutableType(int aval, int bval)
{
a = aval;
b = bval;
}
}
[Serializable]
[GenerateSerializer]
public class EmbeddedImmutable
{
[Id(0)]
public string A { get; set; }
[Id(1)]
private readonly Immutable<List<int>> list;
public Immutable<List<int>> B { get { return list; } }
public EmbeddedImmutable(string a, params int[] listOfInts)
{
A = a;
var l = new List<int>();
l.AddRange(listOfInts);
list = new Immutable<List<int>>(l);
}
}
}
| |
#region license
// Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
//
// DO NOT EDIT THIS FILE!
//
// This file was generated automatically by astgen.boo.
//
namespace Boo.Lang.Compiler.Ast
{
using System.Collections;
using System.Runtime.Serialization;
[System.Serializable]
public partial class UnpackStatement : Statement
{
protected DeclarationCollection _declarations;
protected Expression _expression;
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public UnpackStatement CloneNode()
{
return (UnpackStatement)Clone();
}
/// <summary>
/// <see cref="Node.CleanClone"/>
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public UnpackStatement CleanClone()
{
return (UnpackStatement)base.CleanClone();
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public NodeType NodeType
{
get { return NodeType.UnpackStatement; }
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public void Accept(IAstVisitor visitor)
{
visitor.OnUnpackStatement(this);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Matches(Node node)
{
if (node == null) return false;
if (NodeType != node.NodeType) return false;
var other = ( UnpackStatement)node;
if (!Node.Matches(_modifier, other._modifier)) return NoMatch("UnpackStatement._modifier");
if (!Node.AllMatch(_declarations, other._declarations)) return NoMatch("UnpackStatement._declarations");
if (!Node.Matches(_expression, other._expression)) return NoMatch("UnpackStatement._expression");
return true;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Replace(Node existing, Node newNode)
{
if (base.Replace(existing, newNode))
{
return true;
}
if (_modifier == existing)
{
this.Modifier = (StatementModifier)newNode;
return true;
}
if (_declarations != null)
{
Declaration item = existing as Declaration;
if (null != item)
{
Declaration newItem = (Declaration)newNode;
if (_declarations.Replace(item, newItem))
{
return true;
}
}
}
if (_expression == existing)
{
this.Expression = (Expression)newNode;
return true;
}
return false;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public object Clone()
{
UnpackStatement clone = new UnpackStatement();
clone._lexicalInfo = _lexicalInfo;
clone._endSourceLocation = _endSourceLocation;
clone._documentation = _documentation;
clone._isSynthetic = _isSynthetic;
clone._entity = _entity;
if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone();
if (null != _modifier)
{
clone._modifier = _modifier.Clone() as StatementModifier;
clone._modifier.InitializeParent(clone);
}
if (null != _declarations)
{
clone._declarations = _declarations.Clone() as DeclarationCollection;
clone._declarations.InitializeParent(clone);
}
if (null != _expression)
{
clone._expression = _expression.Clone() as Expression;
clone._expression.InitializeParent(clone);
}
return clone;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override internal void ClearTypeSystemBindings()
{
_annotations = null;
_entity = null;
if (null != _modifier)
{
_modifier.ClearTypeSystemBindings();
}
if (null != _declarations)
{
_declarations.ClearTypeSystemBindings();
}
if (null != _expression)
{
_expression.ClearTypeSystemBindings();
}
}
[System.Xml.Serialization.XmlArray]
[System.Xml.Serialization.XmlArrayItem(typeof(Declaration))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public DeclarationCollection Declarations
{
get { return _declarations ?? (_declarations = new DeclarationCollection(this)); }
set
{
if (_declarations != value)
{
_declarations = value;
if (null != _declarations)
{
_declarations.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public Expression Expression
{
get { return _expression; }
set
{
if (_expression != value)
{
_expression = value;
if (null != _expression)
{
_expression.InitializeParent(this);
}
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
**
** Purpose: CultureInfo-specific collection of resources.
**
**
===========================================================*/
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Runtime.Versioning;
using System.Diagnostics;
namespace System.Resources
{
// A RuntimeResourceSet stores all the resources defined in one
// particular CultureInfo, with some loading optimizations.
//
// It is expected that nearly all the runtime's users will be satisfied with the
// default resource file format, and it will be more efficient than most simple
// implementations. Users who would consider creating their own ResourceSets and/or
// ResourceReaders and ResourceWriters are people who have to interop with a
// legacy resource file format, are creating their own resource file format
// (using XML, for instance), or require doing resource lookups at runtime over
// the network. This group will hopefully be small, but all the infrastructure
// should be in place to let these users write & plug in their own tools.
//
// The Default Resource File Format
//
// The fundamental problems addressed by the resource file format are:
//
// * Versioning - A ResourceReader could in theory support many different
// file format revisions.
// * Storing intrinsic datatypes (ie, ints, Strings, DateTimes, etc) in a compact
// format
// * Support for user-defined classes - Accomplished using Serialization
// * Resource lookups should not require loading an entire resource file - If you
// look up a resource, we only load the value for that resource, minimizing working set.
//
//
// There are four sections to the default file format. The first
// is the Resource Manager header, which consists of a magic number
// that identifies this as a Resource file, and a ResourceSet class name.
// The class name is written here to allow users to provide their own
// implementation of a ResourceSet (and a matching ResourceReader) to
// control policy. If objects greater than a certain size or matching a
// certain naming scheme shouldn't be stored in memory, users can tweak that
// with their own subclass of ResourceSet.
//
// The second section in the system default file format is the
// RuntimeResourceSet specific header. This contains a version number for
// the .resources file, the number of resources in this file, the number of
// different types contained in the file, followed by a list of fully
// qualified type names. After this, we include an array of hash values for
// each resource name, then an array of virtual offsets into the name section
// of the file. The hashes allow us to do a binary search on an array of
// integers to find a resource name very quickly without doing many string
// compares (except for once we find the real type, of course). If a hash
// matches, the index into the array of hash values is used as the index
// into the name position array to find the name of the resource. The type
// table allows us to read multiple different classes from the same file,
// including user-defined types, in a more efficient way than using
// Serialization, at least when your .resources file contains a reasonable
// proportion of base data types such as Strings or ints. We use
// Serialization for all the non-instrinsic types.
//
// The third section of the file is the name section. It contains a
// series of resource names, written out as byte-length prefixed little
// endian Unicode strings (UTF-16). After each name is a four byte virtual
// offset into the data section of the file, pointing to the relevant
// string or serialized blob for this resource name.
//
// The fourth section in the file is the data section, which consists
// of a type and a blob of bytes for each item in the file. The type is
// an integer index into the type table. The data is specific to that type,
// but may be a number written in binary format, a String, or a serialized
// Object.
//
// The system default file format (V1) is as follows:
//
// What Type of Data
// ==================================================== ===========
//
// Resource Manager header
// Magic Number (0xBEEFCACE) Int32
// Resource Manager header version Int32
// Num bytes to skip from here to get past this header Int32
// Class name of IResourceReader to parse this file String
// Class name of ResourceSet to parse this file String
//
// RuntimeResourceReader header
// ResourceReader version number Int32
// [Only in debug V2 builds - "***DEBUG***"] String
// Number of resources in the file Int32
// Number of types in the type table Int32
// Name of each type Set of Strings
// Padding bytes for 8-byte alignment (use PAD) Bytes (0-7)
// Hash values for each resource name Int32 array, sorted
// Virtual offset of each resource name Int32 array, coupled with hash values
// Absolute location of Data section Int32
//
// RuntimeResourceReader Name Section
// Name & virtual offset of each resource Set of (UTF-16 String, Int32) pairs
//
// RuntimeResourceReader Data Section
// Type and Value of each resource Set of (Int32, blob of bytes) pairs
//
// This implementation, when used with the default ResourceReader class,
// loads only the strings that you look up for. It can do string comparisons
// without having to create a new String instance due to some memory mapped
// file optimizations in the ResourceReader and FastResourceComparer
// classes. This keeps the memory we touch to a minimum when loading
// resources.
//
// If you use a different IResourceReader class to read a file, or if you
// do case-insensitive lookups (and the case-sensitive lookup fails) then
// we will load all the names of each resource and each resource value.
// This could probably use some optimization.
//
// In addition, this supports object serialization in a similar fashion.
// We build an array of class types contained in this file, and write it
// to RuntimeResourceReader header section of the file. Every resource
// will contain its type (as an index into the array of classes) with the data
// for that resource. We will use the Runtime's serialization support for this.
//
// All strings in the file format are written with BinaryReader and
// BinaryWriter, which writes out the length of the String in bytes as an
// Int32 then the contents as Unicode chars encoded in UTF-8. In the name
// table though, each resource name is written in UTF-16 so we can do a
// string compare byte by byte against the contents of the file, without
// allocating objects. Ideally we'd have a way of comparing UTF-8 bytes
// directly against a String object, but that may be a lot of work.
//
// The offsets of each resource string are relative to the beginning
// of the Data section of the file. This way, if a tool decided to add
// one resource to a file, it would only need to increment the number of
// resources, add the hash & location of last byte in the name section
// to the array of resource hashes and resource name positions (carefully
// keeping these arrays sorted), add the name to the end of the name &
// offset list, possibly add the type list of types types (and increase
// the number of items in the type table), and add the resource value at
// the end of the file. The other offsets wouldn't need to be updated to
// reflect the longer header section.
//
// Resource files are currently limited to 2 gigabytes due to these
// design parameters. A future version may raise the limit to 4 gigabytes
// by using unsigned integers, or may use negative numbers to load items
// out of an assembly manifest. Also, we may try sectioning the resource names
// into smaller chunks, each of size sqrt(n), would be substantially better for
// resource files containing thousands of resources.
//
#if CORERT
public // On CoreRT, this must be public because of need to whitelist past the ReflectionBlock.
#else
internal
#endif
sealed class RuntimeResourceSet : ResourceSet, IEnumerable
{
internal const int Version = 2; // File format version number
// Cache for resources. Key is the resource name, which can be cached
// for arbitrarily long times, since the object is usually a string
// literal that will live for the lifetime of the appdomain. The
// value is a ResourceLocator instance, which might cache the object.
private Dictionary<string, ResourceLocator> _resCache;
// For our special load-on-demand reader, cache the cast. The
// RuntimeResourceSet's implementation knows how to treat this reader specially.
private ResourceReader _defaultReader;
// This is a lookup table for case-insensitive lookups, and may be null.
// Consider always using a case-insensitive resource cache, as we don't
// want to fill this out if we can avoid it. The problem is resource
// fallback will somewhat regularly cause us to look up resources that
// don't exist.
private Dictionary<string, ResourceLocator> _caseInsensitiveTable;
// If we're not using our custom reader, then enumerate through all
// the resources once, adding them into the table.
private bool _haveReadFromReader;
internal RuntimeResourceSet(string fileName) : base(false)
{
_resCache = new Dictionary<string, ResourceLocator>(FastResourceComparer.Default);
Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
_defaultReader = new ResourceReader(stream, _resCache);
Reader = _defaultReader;
}
internal RuntimeResourceSet(Stream stream) : base(false)
{
_resCache = new Dictionary<string, ResourceLocator>(FastResourceComparer.Default);
_defaultReader = new ResourceReader(stream, _resCache);
Reader = _defaultReader;
}
protected override void Dispose(bool disposing)
{
if (Reader == null)
return;
if (disposing)
{
lock (Reader)
{
_resCache = null;
if (_defaultReader != null)
{
_defaultReader.Close();
_defaultReader = null;
}
_caseInsensitiveTable = null;
// Set Reader to null to avoid a race in GetObject.
base.Dispose(disposing);
}
}
else
{
// Just to make sure we always clear these fields in the future...
_resCache = null;
_caseInsensitiveTable = null;
_defaultReader = null;
base.Dispose(disposing);
}
}
public override IDictionaryEnumerator GetEnumerator()
{
return GetEnumeratorHelper();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumeratorHelper();
}
private IDictionaryEnumerator GetEnumeratorHelper()
{
IResourceReader copyOfReader = Reader;
if (copyOfReader == null || _resCache == null)
throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet);
return copyOfReader.GetEnumerator();
}
public override string GetString(string key)
{
object o = GetObject(key, false, true);
return (string)o;
}
public override string GetString(string key, bool ignoreCase)
{
object o = GetObject(key, ignoreCase, true);
return (string)o;
}
public override object GetObject(string key)
{
return GetObject(key, false, false);
}
public override object GetObject(string key, bool ignoreCase)
{
return GetObject(key, ignoreCase, false);
}
private object GetObject(string key, bool ignoreCase, bool isString)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
if (Reader == null || _resCache == null)
throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet);
object value = null;
ResourceLocator resLocation;
lock (Reader)
{
if (Reader == null)
throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet);
if (_defaultReader != null)
{
// Find the offset within the data section
int dataPos = -1;
if (_resCache.TryGetValue(key, out resLocation))
{
value = resLocation.Value;
dataPos = resLocation.DataPosition;
}
if (dataPos == -1 && value == null)
{
dataPos = _defaultReader.FindPosForResource(key);
}
if (dataPos != -1 && value == null)
{
Debug.Assert(dataPos >= 0, "data section offset cannot be negative!");
// Normally calling LoadString or LoadObject requires
// taking a lock. Note that in this case, we took a
// lock on the entire RuntimeResourceSet, which is
// sufficient since we never pass this ResourceReader
// to anyone else.
ResourceTypeCode typeCode;
if (isString)
{
value = _defaultReader.LoadString(dataPos);
typeCode = ResourceTypeCode.String;
}
else
{
value = _defaultReader.LoadObject(dataPos, out typeCode);
}
resLocation = new ResourceLocator(dataPos, (ResourceLocator.CanCache(typeCode)) ? value : null);
lock (_resCache)
{
_resCache[key] = resLocation;
}
}
if (value != null || !ignoreCase)
{
return value; // may be null
}
} // if (_defaultReader != null)
// At this point, we either don't have our default resource reader
// or we haven't found the particular resource we're looking for
// and may have to search for it in a case-insensitive way.
if (!_haveReadFromReader)
{
// If necessary, init our case insensitive hash table.
if (ignoreCase && _caseInsensitiveTable == null)
{
_caseInsensitiveTable = new Dictionary<string, ResourceLocator>(StringComparer.OrdinalIgnoreCase);
}
if (_defaultReader == null)
{
IDictionaryEnumerator en = Reader.GetEnumerator();
while (en.MoveNext())
{
DictionaryEntry entry = en.Entry;
string readKey = (string)entry.Key;
ResourceLocator resLoc = new ResourceLocator(-1, entry.Value);
_resCache.Add(readKey, resLoc);
if (ignoreCase)
_caseInsensitiveTable.Add(readKey, resLoc);
}
// Only close the reader if it is NOT our default one,
// since we need it around to resolve ResourceLocators.
if (!ignoreCase)
Reader.Close();
}
else
{
Debug.Assert(ignoreCase, "This should only happen for case-insensitive lookups");
ResourceReader.ResourceEnumerator en = _defaultReader.GetEnumeratorInternal();
while (en.MoveNext())
{
// Note: Always ask for the resource key before the data position.
string currentKey = (string)en.Key;
int dataPos = en.DataPosition;
ResourceLocator resLoc = new ResourceLocator(dataPos, null);
_caseInsensitiveTable.Add(currentKey, resLoc);
}
}
_haveReadFromReader = true;
}
object obj = null;
bool found = false;
bool keyInWrongCase = false;
if (_defaultReader != null)
{
if (_resCache.TryGetValue(key, out resLocation))
{
found = true;
obj = ResolveResourceLocator(resLocation, key, _resCache, keyInWrongCase);
}
}
if (!found && ignoreCase)
{
if (_caseInsensitiveTable.TryGetValue(key, out resLocation))
{
found = true;
keyInWrongCase = true;
obj = ResolveResourceLocator(resLocation, key, _resCache, keyInWrongCase);
}
}
return obj;
} // lock(Reader)
}
// The last parameter indicates whether the lookup required a
// case-insensitive lookup to succeed, indicating we shouldn't add
// the ResourceLocation to our case-sensitive cache.
private object ResolveResourceLocator(ResourceLocator resLocation, string key, Dictionary<string, ResourceLocator> copyOfCache, bool keyInWrongCase)
{
// We need to explicitly resolve loosely linked manifest
// resources, and we need to resolve ResourceLocators with null objects.
object value = resLocation.Value;
if (value == null)
{
ResourceTypeCode typeCode;
lock (Reader)
{
value = _defaultReader.LoadObject(resLocation.DataPosition, out typeCode);
}
if (!keyInWrongCase && ResourceLocator.CanCache(typeCode))
{
resLocation.Value = value;
copyOfCache[key] = resLocation;
}
}
return value;
}
}
}
| |
using UnityEngine;
using UnityEditor;
using ProBuilder2.Common;
using ProBuilder2.EditorCommon;
#if PB_DEBUG
using Parabox.Debug;
#endif
public class pb_Preferences
{
private static bool prefsLoaded = false;
static SelectMode pbDefaultSelectionMode;
static Color pbDefaultFaceColor;
static Color pbDefaultEdgeColor;
static Color pbDefaultSelectedVertexColor;
static bool defaultOpenInDockableWindow;
static Material pbDefaultMaterial;
static Vector2 settingsScroll = Vector2.zero;
static int defaultColliderType = 2;
static bool pbShowEditorNotifications;
static bool pbForceConvex = false;
static bool pbDragCheckLimit = false;
static bool pbForceVertexPivot = true;
static bool pbForceGridPivot = true;
static bool pbManifoldEdgeExtrusion;
static bool pbPerimeterEdgeBridgeOnly;
static bool pbPBOSelectionOnly;
static bool pbCloseShapeWindow = false;
static bool pbUVEditorFloating = true;
static bool pbShowSceneToolbar = true;
static bool pbStripProBuilderOnBuild = true;
static bool pbDisableAutoUV2Generation = false;
static bool pbShowSceneInfo = false;
static bool pbEnableBackfaceSelection = false;
static float pbUVGridSnapValue;
static float pbVertexHandleSize;
static pb_Shortcut[] defaultShortcuts;
[PreferenceItem (pb_Constant.PRODUCT_NAME)]
public static void PreferencesGUI ()
{
// Load the preferences
if (!prefsLoaded) {
LoadPrefs();
prefsLoaded = true;
OnWindowResize();
}
settingsScroll = EditorGUILayout.BeginScrollView(settingsScroll, GUILayout.MaxHeight(200));
EditorGUI.BeginChangeCheck();
/**
* GENERAL SETTINGS
*/
GUILayout.Label("General Settings", EditorStyles.boldLabel);
pbStripProBuilderOnBuild = EditorGUILayout.Toggle(new GUIContent("Strip PB Scripts on Build", "If true, when building an executable all ProBuilder scripts will be stripped from your built product."), pbStripProBuilderOnBuild);
pbDisableAutoUV2Generation = EditorGUILayout.Toggle(new GUIContent("Disable Auto UV2 Generation", "Disables automatic generation of UV2 channel. If Unity is sluggish when working with large ProBuilder objects, disabling UV2 generation will improve performance. Use `Actions/Generate UV2` or `Actions/Generate Scene UV2` to build lightmap UVs prior to baking."), pbDisableAutoUV2Generation);
pbShowSceneInfo = EditorGUILayout.Toggle(new GUIContent("Show Scene Info", "Displays the selected object vertex and triangle counts in the scene view."), pbShowSceneInfo);
pbEnableBackfaceSelection = EditorGUILayout.Toggle(new GUIContent("Enable Back-face Selection", "If enabled, you may select faces that have been culled by their back face."), pbEnableBackfaceSelection);
pbDefaultMaterial = (Material) EditorGUILayout.ObjectField("Default Material", pbDefaultMaterial, typeof(Material), false);
defaultOpenInDockableWindow = EditorGUILayout.Toggle("Open in Dockable Window", defaultOpenInDockableWindow);
GUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Default Collider");
defaultColliderType = (int)((ColliderType)EditorGUILayout.EnumPopup( (ColliderType)defaultColliderType ));
GUILayout.EndHorizontal();
if((ColliderType)defaultColliderType == ColliderType.MeshCollider)
pbForceConvex = EditorGUILayout.Toggle("Force Convex Mesh Collider", pbForceConvex);
pbShowEditorNotifications = EditorGUILayout.Toggle("Show Editor Notifications", pbShowEditorNotifications);
pbDragCheckLimit = EditorGUILayout.Toggle(new GUIContent("Limit Drag Check to Selection", "If true, when drag selecting faces, only currently selected pb-Objects will be tested for matching faces. If false, all pb_Objects in the scene will be checked. The latter may be slower in large scenes."), pbDragCheckLimit);
pbPBOSelectionOnly = EditorGUILayout.Toggle(new GUIContent("Only PBO are Selectable", "If true, you will not be able to select non probuilder objects in Geometry and Texture mode"), pbPBOSelectionOnly);
pbCloseShapeWindow = EditorGUILayout.Toggle(new GUIContent("Close shape window after building", "If true the shape window will close after hitting the build button"), pbCloseShapeWindow);
pbShowSceneToolbar = EditorGUILayout.Toggle(new GUIContent("Show Scene Toolbar", "Hide or show the SceneView mode toolbar."), pbShowSceneToolbar);
GUILayout.Space(4);
/**
* GEOMETRY EDITING SETTINGS
*/
GUILayout.Label("Geometry Editing Settings", EditorStyles.boldLabel);
pbDefaultFaceColor = EditorGUILayout.ColorField("Selected Face Color", pbDefaultFaceColor);
pbDefaultEdgeColor = EditorGUILayout.ColorField("Edge Wireframe Color", pbDefaultEdgeColor);
pbDefaultSelectedVertexColor = EditorGUILayout.ColorField("Selected Vertex Color", pbDefaultSelectedVertexColor);
pbVertexHandleSize = EditorGUILayout.Slider("Vertex Handle Size", pbVertexHandleSize, 0f, 1f);
pbForceVertexPivot = EditorGUILayout.Toggle(new GUIContent("Force Pivot to Vertex Point", "If true, new objects will automatically have their pivot point set to a vertex instead of the center."), pbForceVertexPivot);
pbForceGridPivot = EditorGUILayout.Toggle(new GUIContent("Force Pivot to Grid", "If true, newly instantiated pb_Objects will be snapped to the nearest point on grid. If ProGrids is present, the snap value will be used, otherwise decimals are simply rounded to whole numbers."), pbForceGridPivot);
pbManifoldEdgeExtrusion = EditorGUILayout.Toggle(new GUIContent("Manifold Edge Extrusion", "If false, only edges non-manifold edges may be extruded. If true, you may extrude any edge you like (for those who like to live dangerously)."), pbManifoldEdgeExtrusion);
pbPerimeterEdgeBridgeOnly = EditorGUILayout.Toggle(new GUIContent("Bridge Perimeter Edges Only", "If true, only edges on the perimeters of an object may be bridged. If false, you may bridge any between any two edges you like."), pbPerimeterEdgeBridgeOnly);
GUILayout.Space(4);
/**
* UV EDITOR SETTINGS
*/
GUILayout.Label("UV Editing Settings", EditorStyles.boldLabel);
pbUVGridSnapValue = EditorGUILayout.FloatField("UV Snap Increment", pbUVGridSnapValue);
pbUVGridSnapValue = Mathf.Clamp(pbUVGridSnapValue, .015625f, 2f);
pbUVEditorFloating = EditorGUILayout.Toggle(new GUIContent("Editor window floating", "If true UV Editor window will open as a floating window"), pbUVEditorFloating);
EditorGUILayout.EndScrollView();
GUILayout.Space(4);
GUILayout.Label("Shortcut Settings", EditorStyles.boldLabel);
if(GUI.Button(resetRect, "Use defaults"))
ResetToDefaults();
ShortcutSelectPanel();
ShortcutEditPanel();
// Save the preferences
if (EditorGUI.EndChangeCheck())
SetPrefs();
}
public static void OnWindowResize()
{
int pad = 10, buttonWidth = 100, buttonHeight = 20;
resetRect = new Rect(Screen.width-pad-buttonWidth, Screen.height-pad-buttonHeight, buttonWidth, buttonHeight);
}
public static void ResetToDefaults()
{
if(EditorUtility.DisplayDialog("Delete ProBuilder editor preferences?", "Are you sure you want to delete these?, this action cannot be undone.", "Yes", "No")) {
EditorPrefs.DeleteKey(pb_Constant.pbDefaultSelectionMode);
EditorPrefs.DeleteKey(pb_Constant.pbDefaultFaceColor);
EditorPrefs.DeleteKey(pb_Constant.pbDefaultEdgeColor);
EditorPrefs.DeleteKey(pb_Constant.pbDefaultOpenInDockableWindow);
EditorPrefs.DeleteKey(pb_Constant.pbDefaultShortcuts);
EditorPrefs.DeleteKey(pb_Constant.pbDefaultMaterial);
EditorPrefs.DeleteKey(pb_Constant.pbDefaultCollider);
EditorPrefs.DeleteKey(pb_Constant.pbForceConvex);
EditorPrefs.DeleteKey(pb_Constant.pbShowEditorNotifications);
EditorPrefs.DeleteKey(pb_Constant.pbDragCheckLimit);
EditorPrefs.DeleteKey(pb_Constant.pbForceVertexPivot);
EditorPrefs.DeleteKey(pb_Constant.pbForceGridPivot);
EditorPrefs.DeleteKey(pb_Constant.pbManifoldEdgeExtrusion);
EditorPrefs.DeleteKey(pb_Constant.pbPerimeterEdgeBridgeOnly);
EditorPrefs.DeleteKey(pb_Constant.pbDefaultSelectedVertexColor);
EditorPrefs.DeleteKey(pb_Constant.pbVertexHandleSize);
EditorPrefs.DeleteKey(pb_Constant.pbPBOSelectionOnly);
EditorPrefs.DeleteKey(pb_Constant.pbCloseShapeWindow);
EditorPrefs.DeleteKey(pb_Constant.pbUVEditorFloating);
EditorPrefs.DeleteKey(pb_Constant.pbShowSceneToolbar);
EditorPrefs.DeleteKey(pb_Constant.pbUVGridSnapValue);
EditorPrefs.DeleteKey(pb_Constant.pbStripProBuilderOnBuild);
EditorPrefs.DeleteKey(pb_Constant.pbDisableAutoUV2Generation);
EditorPrefs.DeleteKey(pb_Constant.pbShowSceneInfo);
EditorPrefs.DeleteKey(pb_Constant.pbEnableBackfaceSelection);
}
LoadPrefs();
}
static int shortcutIndex = 0;
static Rect selectBox = new Rect(130, 253, 183, 142);
static Rect resetRect = new Rect(0,0,0,0);
static Vector2 shortcutScroll = Vector2.zero;
static int CELL_HEIGHT = 20;
// static int tmp = 0;
static void ShortcutSelectPanel()
{
// tmp = EditorGUI.IntField(new Rect(400, 340, 80, 24), "", tmp);
GUILayout.Space(4);
GUI.contentColor = Color.white;
GUI.Box(selectBox, "");
GUIStyle labelStyle = GUIStyle.none;
if(EditorGUIUtility.isProSkin)
labelStyle.normal.textColor = new Color(1f, 1f, 1f, .8f);
labelStyle.alignment = TextAnchor.MiddleLeft;
labelStyle.contentOffset = new Vector2(4f, 0f);
shortcutScroll = EditorGUILayout.BeginScrollView(shortcutScroll, false, true, GUILayout.MaxWidth(183), GUILayout.MaxHeight(156));
for(int n = 1; n < defaultShortcuts.Length; n++)
{
if(n == shortcutIndex) {
GUI.backgroundColor = new Color(0.23f, .49f, .89f, 1f);
labelStyle.normal.background = EditorGUIUtility.whiteTexture;
Color oc = labelStyle.normal.textColor;
labelStyle.normal.textColor = Color.white;
GUILayout.Box(defaultShortcuts[n].action, labelStyle, GUILayout.MinHeight(CELL_HEIGHT), GUILayout.MaxHeight(CELL_HEIGHT));
labelStyle.normal.background = null;
labelStyle.normal.textColor = oc;
GUI.backgroundColor = Color.white;
}
else
{
if(GUILayout.Button(defaultShortcuts[n].action, labelStyle, GUILayout.MinHeight(CELL_HEIGHT), GUILayout.MaxHeight(CELL_HEIGHT)))
shortcutIndex = n;
}
}
EditorGUILayout.EndScrollView();
}
static Rect keyRect = new Rect(324, 240, 168, 18);
static Rect keyInputRect = new Rect(356, 240, 133, 18);
static Rect descriptionTitleRect = new Rect(324, 300, 168, 200);
static Rect descriptionRect = new Rect(324, 320, 168, 200);
static Rect modifiersRect = new Rect(324, 270, 168, 18);
static Rect modifiersInputRect = new Rect(383, 270, 107, 18);
static void ShortcutEditPanel()
{
// descriptionTitleRect = EditorGUI.RectField(new Rect(240,150,200,50), descriptionTitleRect);
string keyString = defaultShortcuts[shortcutIndex].key.ToString();
GUI.Label(keyRect, "Key");
keyString = EditorGUI.TextField(keyInputRect, keyString);
defaultShortcuts[shortcutIndex].key = pbUtil.ParseEnum(keyString, KeyCode.None);
GUI.Label(modifiersRect, "Modifiers");
defaultShortcuts[shortcutIndex].eventModifiers =
(EventModifiers)EditorGUI.EnumMaskField(modifiersInputRect, defaultShortcuts[shortcutIndex].eventModifiers);
GUI.Label(descriptionTitleRect, "Description", EditorStyles.boldLabel);
GUI.Label(descriptionRect, defaultShortcuts[shortcutIndex].description, EditorStyles.wordWrappedLabel);
}
static void LoadPrefs()
{
pbStripProBuilderOnBuild = pb_Preferences_Internal.GetBool(pb_Constant.pbStripProBuilderOnBuild);
pbDisableAutoUV2Generation = pb_Preferences_Internal.GetBool(pb_Constant.pbDisableAutoUV2Generation);
pbShowSceneInfo = pb_Preferences_Internal.GetBool(pb_Constant.pbShowSceneInfo);
pbEnableBackfaceSelection = pb_Preferences_Internal.GetBool(pb_Constant.pbEnableBackfaceSelection);
pbDefaultFaceColor = pb_Preferences_Internal.GetColor( pb_Constant.pbDefaultFaceColor );
pbDefaultEdgeColor = pb_Preferences_Internal.GetColor( pb_Constant.pbDefaultEdgeColor );
pbDefaultSelectedVertexColor = pb_Preferences_Internal.GetColor( pb_Constant.pbDefaultSelectedVertexColor );
if(!EditorPrefs.HasKey( pb_Constant.pbDefaultOpenInDockableWindow))
EditorPrefs.SetBool(pb_Constant.pbDefaultOpenInDockableWindow, true);
defaultOpenInDockableWindow = EditorPrefs.GetBool(pb_Constant.pbDefaultOpenInDockableWindow);
pbDefaultSelectionMode = pb_Preferences_Internal.GetEnum<SelectMode>(pb_Constant.pbDefaultSelectionMode);
defaultColliderType = (int)pb_Preferences_Internal.GetEnum<ColliderType>(pb_Constant.pbDefaultCollider);
pbUVGridSnapValue = pb_Preferences_Internal.GetFloat(pb_Constant.pbUVGridSnapValue);
pbDragCheckLimit = pb_Preferences_Internal.GetBool(pb_Constant.pbDragCheckLimit);
pbForceConvex = pb_Preferences_Internal.GetBool(pb_Constant.pbForceConvex);
pbForceGridPivot = pb_Preferences_Internal.GetBool(pb_Constant.pbForceGridPivot);
pbForceVertexPivot = pb_Preferences_Internal.GetBool(pb_Constant.pbForceVertexPivot);
pbManifoldEdgeExtrusion = pb_Preferences_Internal.GetBool(pb_Constant.pbManifoldEdgeExtrusion);
pbPerimeterEdgeBridgeOnly = pb_Preferences_Internal.GetBool(pb_Constant.pbPerimeterEdgeBridgeOnly);
pbPBOSelectionOnly = pb_Preferences_Internal.GetBool(pb_Constant.pbPBOSelectionOnly);
pbCloseShapeWindow = pb_Preferences_Internal.GetBool(pb_Constant.pbCloseShapeWindow);
pbVertexHandleSize = pb_Preferences_Internal.GetFloat(pb_Constant.pbVertexHandleSize);
pbUVEditorFloating = pb_Preferences_Internal.GetBool(pb_Constant.pbUVEditorFloating);
pbShowSceneToolbar = pb_Preferences_Internal.GetBool(pb_Constant.pbShowSceneToolbar);
pbDefaultMaterial = pb_Preferences_Internal.GetMaterial(pb_Constant.pbDefaultMaterial);
defaultShortcuts = EditorPrefs.HasKey(pb_Constant.pbDefaultShortcuts) ?
pb_Shortcut.ParseShortcuts(EditorPrefs.GetString(pb_Constant.pbDefaultShortcuts)) :
pb_Shortcut.DefaultShortcuts();
pbShowEditorNotifications = EditorPrefs.HasKey(pb_Constant.pbShowEditorNotifications) ?
EditorPrefs.GetBool(pb_Constant.pbShowEditorNotifications) : true;
}
public static void SetPrefs()
{
EditorPrefs.SetBool (pb_Constant.pbStripProBuilderOnBuild, pbStripProBuilderOnBuild);
EditorPrefs.SetBool (pb_Constant.pbDisableAutoUV2Generation, pbDisableAutoUV2Generation);
EditorPrefs.SetBool (pb_Constant.pbShowSceneInfo, pbShowSceneInfo);
EditorPrefs.SetBool (pb_Constant.pbEnableBackfaceSelection, pbEnableBackfaceSelection);
EditorPrefs.SetInt (pb_Constant.pbDefaultSelectionMode, (int)pbDefaultSelectionMode);
EditorPrefs.SetString (pb_Constant.pbDefaultFaceColor, pbDefaultFaceColor.ToString());
EditorPrefs.SetString (pb_Constant.pbDefaultEdgeColor, pbDefaultEdgeColor.ToString());
EditorPrefs.SetString (pb_Constant.pbDefaultSelectedVertexColor, pbDefaultSelectedVertexColor.ToString());
EditorPrefs.SetBool (pb_Constant.pbDefaultOpenInDockableWindow, defaultOpenInDockableWindow);
EditorPrefs.SetString (pb_Constant.pbDefaultShortcuts, pb_Shortcut.ShortcutsToString(defaultShortcuts));
string matPath = pbDefaultMaterial != null ? AssetDatabase.GetAssetPath(pbDefaultMaterial) : "";
EditorPrefs.SetString (pb_Constant.pbDefaultMaterial, matPath == "" ? pbDefaultMaterial.name : matPath);
EditorPrefs.SetInt (pb_Constant.pbDefaultCollider, defaultColliderType);
EditorPrefs.SetBool (pb_Constant.pbShowEditorNotifications, pbShowEditorNotifications);
EditorPrefs.SetBool (pb_Constant.pbForceConvex, pbForceConvex);
EditorPrefs.SetBool (pb_Constant.pbDragCheckLimit, pbDragCheckLimit);
EditorPrefs.SetBool (pb_Constant.pbForceVertexPivot, pbForceVertexPivot);
EditorPrefs.SetBool (pb_Constant.pbForceGridPivot, pbForceGridPivot);
EditorPrefs.SetBool (pb_Constant.pbManifoldEdgeExtrusion, pbManifoldEdgeExtrusion);
EditorPrefs.SetBool (pb_Constant.pbPerimeterEdgeBridgeOnly, pbPerimeterEdgeBridgeOnly);
EditorPrefs.SetBool (pb_Constant.pbPBOSelectionOnly, pbPBOSelectionOnly);
EditorPrefs.SetBool (pb_Constant.pbCloseShapeWindow, pbCloseShapeWindow);
EditorPrefs.SetBool (pb_Constant.pbUVEditorFloating, pbUVEditorFloating);
EditorPrefs.SetBool (pb_Constant.pbShowSceneToolbar, pbShowSceneToolbar);
// pb_Editor.instance.LoadPrefs();
EditorPrefs.SetFloat (pb_Constant.pbVertexHandleSize, pbVertexHandleSize);
EditorPrefs.SetFloat (pb_Constant.pbUVGridSnapValue, pbUVGridSnapValue);
pb_Editor_Graphics.LoadPrefs();
SceneView.RepaintAll();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.